text:
'use strict';

import {parse, StyleNode} from './css-parse'
import {nativeShadow, nativeCssVariables} from './style-settings'
import StyleTransformer from './style-transformer'
import * as StyleUtil from './style-util'
import StyleProperties from './style-properties'
import placeholderMap from './style-placeholder'
import StyleInfo from './style-info'
import StyleCache from './style-cache'
import {flush as watcherFlush} from './document-watcher'
import templateMap from './template-map'
import * as ApplyShimUtils from './apply-shim-utils'
import documentWait from './document-wait'
import {updateNativeProperties} from './common-utils'
import {CustomStyleInterfaceInterface} from './custom-style-interface' //eslint-disable-line no-unused-vars

/**
 * @const {StyleCache}
 */
const styleCache = new StyleCache();

export default class ScopingShim {
  constructor() {
    this._scopeCounter = {};
    this._documentOwner = document.documentElement;
    let ast = new StyleNode();
    ast['rules'] = [];
    this._documentOwnerStyleInfo = StyleInfo.set(this._documentOwner, new StyleInfo(ast));
    this._elementsHaveApplied = false;
    this._applyShim = null;
    /** @type {?CustomStyleInterfaceInterface} */
    this._customStyleInterface = null;
    documentWait(() => {
      this._ensure();
    });
  }
  flush() {
    watcherFlush();
  }
  _generateScopeSelector(name) {
    let id = this._scopeCounter[name] = (this._scopeCounter[name] || 0) + 1;
    return `${name}-${id}`;
  }
  getStyleAst(style) {
    return StyleUtil.rulesForStyle(style);
  }
  styleAstToString(ast) {
    return StyleUtil.toCssText(ast);
  }
  _gatherStyles(template) {
    let styles = template.content.querySelectorAll('style');
    let cssText = [];
    for (let i = 0; i < styles.length; i++) {
      let s = styles[i];
      cssText.push(s.textContent);
      s.parentNode.removeChild(s);
    }
    return cssText.join('').trim();
  }
  _getCssBuild(template) {
    let style = template.content.querySelector('style');
    if (!style) {
      return '';
    }
    return style.getAttribute('css-build') || '';
  }
  /**
   * Prepare the styling and template for the given element type
   *
   * @param {HTMLTemplateElement} template
   * @param {string} elementName
   * @param {string=} typeExtension
   */
  prepareTemplate(template, elementName, typeExtension) {
    if (template._prepared) {
      return;
    }
    template._prepared = true;
    template.name = elementName;
    template.extends = typeExtension;
    templateMap[elementName] = template;
    let cssBuild = this._getCssBuild(template);
    let cssText = this._gatherStyles(template);
    let info = {
      is: elementName,
      extends: typeExtension,
      __cssBuild: cssBuild,
    };
    if (!nativeShadow) {
      StyleTransformer.dom(template.content, elementName);
    }
    // check if the styling has mixin definitions or uses
    this._ensure();
    let hasMixins = this._applyShim['detectMixin'](cssText);
    let ast = parse(cssText);
    // only run the applyshim transforms if there is a mixin involved
    if (hasMixins && nativeCssVariables) {
      this._applyShim['transformRules'](ast, elementName);
    }
    template['_styleAst'] = ast;
    template._cssBuild = cssBuild;

    let ownPropertyNames = [];
    if (!nativeCssVariables) {
      ownPropertyNames = StyleProperties.decorateStyles(template['_styleAst'], info);
    }
    if (!ownPropertyNames.length || nativeCssVariables) {
      let root = nativeShadow ? template.content : null;
      let placeholder = placeholderMap[elementName];
      let style = this._generateStaticStyle(info, template['_styleAst'], root, placeholder);
      template._style = style;
    }
    template._ownPropertyNames = ownPropertyNames;
  }
  _generateStaticStyle(info, rules, shadowroot, placeholder) {
    let cssText = StyleTransformer.elementStyles(info, rules);
    if (cssText.length) {
      return StyleUtil.applyCss(cssText, info.is, shadowroot, placeholder);
    }
  }
  _prepareHost(host) {
    let {is, typeExtension} = StyleUtil.getIsExtends(host);
    let placeholder = placeholderMap[is];
    let template = templateMap[is];
    let ast;
    let ownStylePropertyNames;
    let cssBuild;
    if (template) {
      ast = template['_styleAst'];
      ownStylePropertyNames = template._ownPropertyNames;
      cssBuild = template._cssBuild;
    }
    return StyleInfo.set(host,
      new StyleInfo(
        ast,
        placeholder,
        ownStylePropertyNames,
        is,
        typeExtension,
        cssBuild
      )
    );
  }
  _ensureApplyShim() {
    if (this._applyShim) {
      return;
    } else if (window.ShadyCSS.ApplyShim) {
      this._applyShim = window.ShadyCSS.ApplyShim;
      this._applyShim['invalidCallback'] = ApplyShimUtils.invalidate;
    } else {
      this._applyShim = {
        /* eslint-disable no-unused-vars */
        ['detectMixin'](str){return false},
        ['transformRule'](ast){},
        ['transformRules'](ast, name){},
        /* eslint-enable no-unused-vars */
      }
    }
  }
  _ensureCustomStyleInterface() {
    if (this._customStyleInterface) {
      return;
    } else if (window.ShadyCSS.CustomStyleInterface) {
      this._customStyleInterface = /** @type {!CustomStyleInterfaceInterface} */(window.ShadyCSS.CustomStyleInterface);
      /** @type {function(!HTMLStyleElement)} */
      this._customStyleInterface['transformCallback'] = (style) => {this.transformCustomStyleForDocument(style)};
      this._customStyleInterface['validateCallback'] = () => {
        requestAnimationFrame(() => {
          if (this._customStyleInterface['enqueued'] || this._elementsHaveApplied) {
            this.flushCustomStyles();
          }
        })
      };
    } else {
      this._customStyleInterface = /** @type {!CustomStyleInterfaceInterface} */({
        ['processStyles']() {},
        ['enqueued']: false,
        ['getStyleForCustomStyle'](s) { return null } // eslint-disable-line no-unused-vars
      })
    }
  }
  _ensure() {
    this._ensureApplyShim();
    this._ensureCustomStyleInterface();
  }
  /**
   * Flush and apply custom styles to document
   */
  flushCustomStyles() {
    this._ensure();
    let customStyles = this._customStyleInterface['processStyles']();
    // early return if custom-styles don't need validation
    if (!this._customStyleInterface['enqueued']) {
      return;
    }
    if (!nativeCssVariables) {
      this._updateProperties(this._documentOwner, this._documentOwnerStyleInfo);
      this._applyCustomStyles(customStyles);
    } else {
      this._revalidateCustomStyleApplyShim(customStyles);
    }
    this._customStyleInterface['enqueued'] = false;
    // if custom elements have upgraded and there are no native css variables, we must recalculate the whole tree
    if (this._elementsHaveApplied && !nativeCssVariables) {
      this.styleDocument();
    }
  }
  /**
   * Apply styles for the given element
   *
   * @param {!HTMLElement} host
   * @param {Object=} overrideProps
   */
  styleElement(host, overrideProps) {
    let {is} = StyleUtil.getIsExtends(host);
    let styleInfo = StyleInfo.get(host);
    if (!styleInfo) {
      styleInfo = this._prepareHost(host);
    }
    // Only trip the `elementsHaveApplied` flag if a node other that the root document has `applyStyle` called
    if (!this._isRootOwner(host)) {
      this._elementsHaveApplied = true;
    }
    if (overrideProps) {
      styleInfo.overrideStyleProperties =
        styleInfo.overrideStyleProperties || {};
      Object.assign(styleInfo.overrideStyleProperties, overrideProps);
    }
    if (!nativeCssVariables) {
     this._updateProperties(host, styleInfo);
      if (styleInfo.ownStylePropertyNames && styleInfo.ownStylePropertyNames.length) {
        this._applyStyleProperties(host, styleInfo);
      }
    } else {
      if (styleInfo.overrideStyleProperties) {
        updateNativeProperties(host, styleInfo.overrideStyleProperties);
      }
      let template = templateMap[is];
      // bail early if there is no shadowroot for this element
      if (!template && !this._isRootOwner(host)) {
        return;
      }
      if (template && template._style && !ApplyShimUtils.templateIsValid(template)) {
        // update template
        if (!ApplyShimUtils.templateIsValidating(template)) {
          this._ensure();
          this._applyShim['transformRules'](template['_styleAst'], is);
          template._style.textContent = StyleTransformer.elementStyles(host, styleInfo.styleRules);
          ApplyShimUtils.startValidatingTemplate(template);
        }
        // update instance if native shadowdom
        if (nativeShadow) {
          let root = host.shadowRoot;
          if (root) {
            let style = root.querySelector('style');
            style.textContent = StyleTransformer.elementStyles(host, styleInfo.styleRules);
          }
        }
        styleInfo.styleRules = template['_styleAst'];
      }
    }
  }
  _styleOwnerForNode(node) {
    let root = node.getRootNode();
    let host = root.host;
    if (host) {
      if (StyleInfo.get(host)) {
        return host;
      } else {
        return this._styleOwnerForNode(host);
      }
    }
    return this._documentOwner;
  }
  _isRootOwner(node) {
    return (node === this._documentOwner);
  }
  _applyStyleProperties(host, styleInfo) {
    let is = StyleUtil.getIsExtends(host).is;
    let cacheEntry = styleCache.fetch(is, styleInfo.styleProperties, styleInfo.ownStylePropertyNames);
    let cachedScopeSelector = cacheEntry && cacheEntry.scopeSelector;
    let cachedStyle = cacheEntry ? cacheEntry.styleElement : null;
    let oldScopeSelector = styleInfo.scopeSelector;
    // only generate new scope if cached style is not found
    styleInfo.scopeSelector = cachedScopeSelector || this._generateScopeSelector(is);
    let style = StyleProperties.applyElementStyle(host, styleInfo.styleProperties, styleInfo.scopeSelector, cachedStyle);
    if (!nativeShadow) {
      StyleProperties.applyElementScopeSelector(host, styleInfo.scopeSelector, oldScopeSelector);
    }
    if (!cacheEntry) {
      styleCache.store(is, styleInfo.styleProperties, style, styleInfo.scopeSelector);
    }
    return style;
  }
  _updateProperties(host, styleInfo) {
    let owner = this._styleOwnerForNode(host);
    let ownerStyleInfo = StyleInfo.get(owner);
    let ownerProperties = ownerStyleInfo.styleProperties;
    let props = Object.create(ownerProperties || null);
    let hostAndRootProps = StyleProperties.hostAndRootPropertiesForScope(host, styleInfo.styleRules);
    let propertyData = StyleProperties.propertyDataFromStyles(ownerStyleInfo.styleRules, host);
    let propertiesMatchingHost = propertyData.properties
    Object.assign(
      props,
      hostAndRootProps.hostProps,
      propertiesMatchingHost,
      hostAndRootProps.rootProps
    );
    this._mixinOverrideStyles(props, styleInfo.overrideStyleProperties);
    StyleProperties.reify(props);
    styleInfo.styleProperties = props;
  }
  _mixinOverrideStyles(props, overrides) {
    for (let p in overrides) {
      let v = overrides[p];
      // skip override props if they are not truthy or 0
      // in order to fall back to inherited values
      if (v || v === 0) {
        props[p] = v;
      }
    }
  }
  /**
   * Update styles of the whole document
   *
   * @param {Object=} properties
   */
  styleDocument(properties) {
    this.styleSubtree(this._documentOwner, properties);
  }
  /**
   * Update styles of a subtree
   *
   * @param {!HTMLElement} host
   * @param {Object=} properties
   */
  styleSubtree(host, properties) {
    let root = host.shadowRoot;
    if (root || this._isRootOwner(host)) {
      this.styleElement(host, properties);
    }
    // process the shadowdom children of `host`
    let shadowChildren = root && (root.children || root.childNodes);
    if (shadowChildren) {
      for (let i = 0; i < shadowChildren.length; i++) {
        let c = /** @type {!HTMLElement} */(shadowChildren[i]);
        this.styleSubtree(c);
      }
    } else {
      // process the lightdom children of `host`
      let children = host.children || host.childNodes;
      if (children) {
        for (let i = 0; i < children.length; i++) {
          let c = /** @type {!HTMLElement} */(children[i]);
          this.styleSubtree(c);
        }
      }
    }
  }
  /* Custom Style operations */
  _revalidateCustomStyleApplyShim(customStyles) {
    for (let i = 0; i < customStyles.length; i++) {
      let c = customStyles[i];
      let s = this._customStyleInterface['getStyleForCustomStyle'](c);
      if (s) {
        this._revalidateApplyShim(s);
      }
    }
  }
  _applyCustomStyles(customStyles) {
    for (let i = 0; i < customStyles.length; i++) {
      let c = customStyles[i];
      let s = this._customStyleInterface['getStyleForCustomStyle'](c);
      if (s) {
        StyleProperties.applyCustomStyle(s, this._documentOwnerStyleInfo.styleProperties);
      }
    }
  }
  transformCustomStyleForDocument(style) {
    let ast = StyleUtil.rulesForStyle(style);
    StyleUtil.forEachRule(ast, (rule) => {
      if (nativeShadow) {
        StyleTransformer.normalizeRootSelector(rule);
      } else {
        StyleTransformer.documentRule(rule);
      }
      if (nativeCssVariables) {
        this._ensure();
        this._applyShim['transformRule'](rule);
      }
    });
    if (nativeCssVariables) {
      style.textContent = StyleUtil.toCssText(ast);
    } else {
      this._documentOwnerStyleInfo.styleRules.rules.push(ast);
    }
  }
  _revalidateApplyShim(style) {
    if (nativeCssVariables) {
      let ast = StyleUtil.rulesForStyle(style);
      this._ensure();
      this._applyShim['transformRules'](ast);
      style.textContent = StyleUtil.toCssText(ast);
    }
  }
  getComputedStyleValue(element, property) {
    let value;
    if (!nativeCssVariables) {
      // element is either a style host, or an ancestor of a style host
      let styleInfo = StyleInfo.get(element) || StyleInfo.get(this._styleOwnerForNode(element));
      value = styleInfo.styleProperties[property];
    }
    // fall back to the property value from the computed styling
    value = value || window.getComputedStyle(element).getPropertyValue(property);
    // trim whitespace that can come after the `:` in css
    // example: padding: 2px -> " 2px"
    return value.trim();
  }
  // given an element and a classString, replaces
  // the element's class with the provided classString and adds
  // any necessary ShadyCSS static and property based scoping selectors
  setElementClass(element, classString) {
    let root = element.getRootNode();
    let classes = classString ? classString.split(/\s/) : [];
    let scopeName = root.host && root.host.localName;
    // If no scope, try to discover scope name from existing class.
    // This can occur if, for example, a template stamped element that
    // has been scoped is manipulated when not in a root.
    if (!scopeName) {
      var classAttr = element.getAttribute('class');
      if (classAttr) {
        let k$ = classAttr.split(/\s/);
        for (let i=0; i < k$.length; i++) {
          if (k$[i] === StyleTransformer.SCOPE_NAME) {
            scopeName = k$[i+1];
            break;
          }
        }
      }
    }
    if (scopeName) {
      classes.push(StyleTransformer.SCOPE_NAME, scopeName);
    }
    if (!nativeCssVariables) {
      let styleInfo = StyleInfo.get(element);
      if (styleInfo && styleInfo.scopeSelector) {
        classes.push(StyleProperties.XSCOPE_NAME, styleInfo.scopeSelector);
      }
    }
    StyleUtil.setElementClassRaw(element, classes.join(' '));
  }
  _styleInfoForNode(node) {
    return StyleInfo.get(node);
  }
}

/* exports */
ScopingShim.prototype['flush'] = ScopingShim.prototype.flush;
ScopingShim.prototype['prepareTemplate'] = ScopingShim.prototype.prepareTemplate;
ScopingShim.prototype['styleElement'] = ScopingShim.prototype.styleElement;
ScopingShim.prototype['styleDocument'] = ScopingShim.prototype.styleDocument;
ScopingShim.prototype['styleSubtree'] = ScopingShim.prototype.styleSubtree;
ScopingShim.prototype['getComputedStyleValue'] = ScopingShim.prototype.getComputedStyleValue;
ScopingShim.prototype['setElementClass'] = ScopingShim.prototype.setElementClass;
ScopingShim.prototype['_styleInfoForNode'] = ScopingShim.prototype._styleInfoForNode;
ScopingShim.prototype['transformCustomStyleForDocument'] = ScopingShim.prototype.transformCustomStyleForDocument;
ScopingShim.prototype['getStyleAst'] = ScopingShim.prototype.getStyleAst;
ScopingShim.prototype['styleAstToString'] = ScopingShim.prototype.styleAstToString;
ScopingShim.prototype['flushCustomStyles'] = ScopingShim.prototype.flushCustomStyles;
Object.defineProperties(ScopingShim.prototype, {
  'nativeShadow': {
    get() {
      return nativeShadow;
    }
  },
  'nativeCss': {
    get() {
      return nativeCssVariables;
    }
  }
});


text:
from isomorphism.ColorRefinementChecker import ColorRefinementChecker
from graph.graphIO import loadgraph
from isomorphism.IndividualizationRefinementChecker import IndividualizationRefinementChecker

# L = loadgraphs('data\colorref_smallexample_4_7.grl')
# checker = ColorRefinementChecker()
# print(checker.isIsomorphic(L[0][0], L[0][1]))
# print(checker.isIsomorphic(L[0][0], L[0][2]))
# print(checker.isIsomorphic(L[0][0], L[0][3]))

L = loadgraph('data\\basicAut1.gr')
checker = IndividualizationRefinementChecker()
print(checker.countIsomorphisms(L[0], L[0]))
#print(checker.countIsomorphisms(L[0][1], L[0][2]))
#L = loadgraphs('data\\trees90.grl')
#print(checker.countIsomorphisms(L[0][0], L[0][3]))
#print(checker.countIsomorphisms(L[0][1], L[0][2]))

redpajama_set_name: RedPajamaGithub


text:
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var astUtils = require("../ast-utils");

//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------

var NO_FUNC = "nofunc";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    /**
     * Finds and validates all variables in a given scope.
     * @param {Scope} scope The scope object.
     * @returns {void}
     * @private
     */
    function findVariablesInScope(scope) {
        var typeOption = context.options[0];

        /**
         * Report the node
         * @param {object} reference reference object
         * @param {ASTNode} declaration node to evaluate
         * @returns {void}
         * @private
         */
        function checkLocationAndReport(reference, declaration) {
            if (typeOption !== NO_FUNC || declaration.defs[0].type !== "FunctionName") {
                if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) {
                    context.report(reference.identifier, "\"{{a}}\" was used before it was defined", {a: reference.identifier.name});
                }
            }
        }

        scope.references.forEach(function(reference) {
            // if the reference is resolved check for declaration location
            // if not, it could be function invocation, try to find manually
            if (reference.resolved && reference.resolved.identifiers.length > 0) {
                checkLocationAndReport(reference, reference.resolved);
            } else {
                var declaration = astUtils.getVariableByName(scope, reference.identifier.name);
                // if there're no identifiers, this is a global environment variable
                if (declaration && declaration.identifiers.length !== 0) {
                    checkLocationAndReport(reference, declaration);
                }
            }
        });
    }

    /**
     * Validates variables inside of a node's scope.
     * @param {ASTNode} node The node to check.
     * @returns {void}
     * @private
     */
    function findVariables() {
        var scope = context.getScope();
        findVariablesInScope(scope);
    }

    var ruleDefinition = {
        "Program": function() {
            var scope = context.getScope();
            findVariablesInScope(scope);

            // both Node.js and Modules have an extra scope
            if (context.ecmaFeatures.globalReturn || context.ecmaFeatures.modules) {
                findVariablesInScope(scope.childScopes[0]);
            }
        }
    };

    if (context.ecmaFeatures.blockBindings) {
        ruleDefinition.BlockStatement = ruleDefinition.SwitchStatement = findVariables;

        ruleDefinition.ArrowFunctionExpression = function(node) {
            if (node.body.type !== "BlockStatement") {
                findVariables(node);
            }
        };
    } else {
        ruleDefinition.FunctionExpression = ruleDefinition.FunctionDeclaration = ruleDefinition.ArrowFunctionExpression = findVariables;
    }

    return ruleDefinition;
};

module.exports.schema = [
    {
        "enum": ["nofunc"]
    }
];


text:
<?= $this->title ?>

<?= message::get(); ?>

    <?= html::anchor('files/nationals', 'National File Folders') ?> »
    <?php $parent = $this->folder->parent; ?>
    <?php if ($parent->loaded): ?>
      <?= html::anchor('files/nationals/folder/'. $parent->id, $parent->name) ?> »
    <?php endif ?>
    <?= $this->folder->name ?>

      <?php if ($this->folder->children->count()): ?>
        <?php foreach ($this->folder->children as $subfolder): ?>
          <?php if ($subfolder->national): ?>

<?= html::anchor('files/nationals/folder/'. $subfolder->id, $subfolder->name); ?>

<?= $subfolder->description ?>

          <?php endif ?>
        <?php endforeach ?>
      <?php endif ?>

      <?php if ($this->folder->files->count()): ?>
        <?php foreach ($this->folder->files as $file): ?>
          <div class="file file-type-<?= $file->type() ?> hoverable">

<?= html::anchor($file->url(), $file->name); ?>

<?= $file->description; ?>

        <?php endforeach ?>
      <?php endif; ?>
      <?php if ( ! ($this->folder->children->count() || $this->folder->files->count())): ?>

There are no files in this folder.

      <?php endif ?>


text:
'use strict';

var path    = require('path')
  , test    = require('tap').test
  , request = require('request')
  , helper  = require(path.join(__dirname, '..', '..', 'lib', 'agent_helper.js'))
  , API     = require(path.join(__dirname, '..', '..', '..', 'api.js'))
  ;

test("ignoring an Express 3 route", function (t) {
  t.plan(7);

  var agent   = helper.instrumentMockedAgent()
    , api     = new API(agent)
    , express = require('express')
    , app     = express()
    , server  = require('http').createServer(app)
    ;

  this.tearDown(function cb_tearDown() {
    server.close(function cb_close() {
      helper.unloadAgent(agent);
    });
  });

  agent.on('transactionFinished', function (transaction) {
    t.equal(transaction.name, 'WebTransaction/Expressjs/GET//polling/:id',
            "transaction has expected name even on error");
    t.ok(transaction.ignore, "transaction is ignored");

    t.notOk(agent.traces.trace, "should have no transaction trace");

    var metrics = agent.metrics.unscoped;
    t.equal(Object.keys(metrics).length, 0, "no metrics added to agent collection");

    var errors = agent.errors.errors;
    t.equal(errors.length, 0, "no errors noticed");
  });

  app.get('/polling/:id', function (req, res) {
    api.setIgnoreTransaction(true);

    res.send(400, {status : 'pollpollpoll'});
    res.end();
  });

  server.listen(8080, function () {
    request.get('http://localhost:8080/polling/31337',
                {json : true},
                function (error, res, body) {

      t.equal(res.statusCode, 400, "got expected error");
      t.deepEqual(body, {status : 'pollpollpoll'}, "got expected response");
    });
  });
});


text:
class CreateParentResources < ActiveRecord::Migration
  def change
    create_table :parent_resources do |t|
      t.string :name
      t.string :description

      t.timestamps
    end
  end
end


text:
home="$(cd "$(dirname $0)"; pwd)"

# enable class cache feature
export agent_opts="$agent_opts -Dskywalking.agent.is_cache_enhanced_class=true -Dskywalking.agent.class_cache_mode=MEMORY"

java -jar ${agent_opts} ${home}/../libs/retransform-class-scenario.jar &


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using Reactive.Bindings;

namespace ShapeWpf
{
    public class AppModel
    {
        const string PolygonPointsString = "100,200 100,100 0,0 100,100 0,100 100,0 0,100 0,200";
        const string BaseRandomPointsString = "100,200 100,100 100,100 0,100 0,100 0,200";

        public PointCollection PolygonPoints { get; } = PointCollection.Parse(PolygonPointsString);

        public ReactiveProperty<TipPoints> RandomTips { get; } = new ReactiveProperty<TipPoints>(new TipPoints { X1 = 0, X2 = 100 });
        public ReadOnlyReactiveProperty<PointCollection> RandomPoints { get; }

        public AppModel()
        {
            Observable.Interval(TimeSpan.FromSeconds(1 / 60.0))
                .Select(_ => NextTips(RandomTips.Value))
                .ObserveOn(SynchronizationContext.Current)
                .Subscribe(t => RandomTips.Value = t);
            RandomPoints = RandomTips.Select(CreateRandomPoints).ToReadOnlyReactiveProperty();
        }

        static PointCollection CreateRandomPoints(TipPoints tips)
        {
            var points = PointCollection.Parse(BaseRandomPointsString);
            points.Insert(2, new Point(tips.X1, 0));
            points.Insert(5, new Point(tips.X2, 0));
            return points;
        }

        static readonly Random Random = new Random();

        static TipPoints NextTips(TipPoints tips)
        {
            var d1 = Random.Next(-3, 4);
            var d2 = Random.Next(-3, 4);
            return new TipPoints { X1 = tips.X1 + d1, X2 = tips.X2 + d2 };
        }
    }

    public struct TipPoints
    {
        public int X1 { get; set; }
        public int X2 { get; set; }
    }
}


text:
from dipy.workflows.workflow import Workflow

class CombinedWorkflow(Workflow):
    def __init__(self, output_strategy='append', mix_names=False,
                 force=False, skip=False):
        """ Workflow that combines multiple workflows.
        The workflow combined together are referred as sub flows in this class.
        """

        self._optionals = {}
        super(CombinedWorkflow, self).__init__(output_strategy, mix_names,
                                               force, skip)

    def get_sub_runs(self):
        """ Returns a list of tuples
        (sub flow name, sub flow run method, sub flow short name)
        to be used in the sub flow parameters extraction.
        """
        sub_runs = []
        for flow in self._get_sub_flows():
            sub_runs.append((flow.__name__, flow.run, flow.get_short_name()))

        return sub_runs

    def _get_sub_flows(self):
        """ Returns a list of sub flows used in the combined_workflow. Needs to
        be implemented in every new combined_workflow.
        """
        raise AttributeError('Error: _get_sub_flows() has to be defined for {}'.
                             format(self.__class__))

    def set_sub_flows_optionals(self, opts):
        """ Sets the self._optionals variable with all sub flow arguments
        that were passed in the commandline.
        """
        self._optionals = {}
        for key, sub_dict in opts.items():
            self._optionals[key] = \
                dict((k, v) for k, v in sub_dict.items() if v is not None)

    def get_optionals(self, flow, **kwargs):
        """ Returns the sub flow's optional arguments merged with those passed
        as params in kwargs.
        """
        opts = self._optionals[flow.__name__]
        opts.update(kwargs)

        return opts

    def run_sub_flow(self, flow, *args, **kwargs):
        """ Runs the sub flow with the optional parameters passed via the
        command line. This is a convenience method to make sub flow running
        more intuitive on the concrete CombinedWorkflow side.
        """
        return flow.run(*args, **self.get_optionals(type(flow), **kwargs))


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1\PacketIntervals;

use UnexpectedValueException;

/**
 * From how long ago in the past these intervals were observed.
 *
 * Protobuf type google.cloud.compute.v1.PacketIntervals.Duration
 */
class Duration
{
    /**
     * A value indicating that the enum field is not set.
     *
     * Generated from protobuf enum UNDEFINED_DURATION = 0;
     */
    const UNDEFINED_DURATION = 0;
    /**
     * Generated from protobuf enum DURATION_UNSPECIFIED = 529071340;
     */
    const DURATION_UNSPECIFIED = 529071340;
    /**
     * Generated from protobuf enum HOUR = 2223588;
     */
    const HOUR = 2223588;
    /**
     * From BfdSession object creation time.
     *
     * Generated from protobuf enum MAX = 76100;
     */
    const MAX = 76100;
    /**
     * Generated from protobuf enum MINUTE = 126786068;
     */
    const MINUTE = 126786068;

    private static $valueToName = [
        self::UNDEFINED_DURATION => 'UNDEFINED_DURATION',
        self::DURATION_UNSPECIFIED => 'DURATION_UNSPECIFIED',
        self::HOUR => 'HOUR',
        self::MAX => 'MAX',
        self::MINUTE => 'MINUTE',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}


text:
/*
 *

 */
package com.compomics.pride_asa_pipeline.core.service.impl;

import com.compomics.pride_asa_pipeline.core.model.MascotGenericFile;
import com.compomics.pride_asa_pipeline.core.service.DbExperimentService;
import com.compomics.pride_asa_pipeline.core.service.DbSpectrumService;
import com.compomics.pride_asa_pipeline.model.Identification;
import com.compomics.pride_asa_pipeline.model.Identifications;
import com.compomics.pride_asa_pipeline.model.Peak;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.log4j.Logger;

/**
 * @author Niels Hulstaert
 */
public class DbExperimentServiceImpl extends ExperimentServiceImpl implements DbExperimentService {

    private static final Logger LOGGER = Logger.getLogger(DbExperimentServiceImpl.class);
    private DbSpectrumService spectrumService;
    private boolean iFirstMfgFile;

    public DbSpectrumService getSpectrumService() {
        return spectrumService;
    }

    public void setSpectrumService(DbSpectrumService spectrumService) {
        this.spectrumService = spectrumService;
    }

    @Override
    public Identifications loadExperimentIdentifications(String experimentAccession) {
        Identifications identifications = new Identifications();
        List<Identification> identificationList = experimentRepository.loadExperimentIdentifications(experimentAccession);
        for (Identification identification : identificationList) {
            identifications.addIdentification(identification);
        }
        return identifications;
    }

    @Override
    public void updateChargeStates(String experimentAccession, Set<Integer> chargeStates) {
        //go over the identifications and check their charges
        List<Identification> loadExperimentIdentifications = experimentRepository.loadExperimentIdentifications(experimentAccession);
        for (Identification ident : loadExperimentIdentifications) {
            chargeStates.add(ident.getPeptide().getCharge());
        }
    }

    @Override
    public long getNumberOfSpectra(String experimentAccession) {
        return experimentRepository.getNumberOfSpectra(experimentAccession);
    }

    @Override
    public Set<String> getProteinAccessions(String experimentAccession) {
        Set<String> proteinAccessions = new HashSet<String>();
        List<String> proteinAccessionList = experimentRepository.getProteinAccessions(experimentAccession);
        for (String proteinAccession : proteinAccessionList) {
            proteinAccessions.add(proteinAccession);
        }
        return proteinAccessions;
    }

    @Override
    public long getNumberOfPeptides(String experimentAccession) {
        return experimentRepository.getNumberOfPeptides(experimentAccession);
    }

    @Override
    public void getSpectraAsMgfFile(String experimentAccession, File mgfFile, boolean rebuildCache) {
        LOGGER.debug(String.format("writing spectra from experiment %s to %s", experimentAccession, mgfFile.getAbsolutePath()));

        if (rebuildCache) {
            LOGGER.debug(String.format("rebuilding spectrum cache for experiment %s", experimentAccession));
            buildSpectrumCacheForExperiment(experimentAccession);
        }

        BufferedOutputStream outputStream = null;
        try {
            //create new mgf file from scratch
            MascotGenericFile mascotGenericFile = new MascotGenericFile();
            mascotGenericFile.setFilename(experimentAccession);

            outputStream = new BufferedOutputStream(new FileOutputStream(mgfFile));
            writeCachedSpectra(outputStream, experimentAccession);
        } catch (FileNotFoundException e) {
            LOGGER.error(e.getMessage(), e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * Builds up the spectrum cache for an entire experiment.
     *
     * @param experimentAccession
     */
    private void buildSpectrumCacheForExperiment(String experimentAccession) {

        //clear the existing cache
        LOGGER.debug(String.format("clearing spectrum cache before starting to cache all spectra for experiment %s", experimentAccession));
        spectrumService.clearCache();

        //get spectra metadata
        List<Map<String, Object>> spectraMetadata = experimentRepository.getSpectraMetadata(experimentAccession);

        HashMap<String, Map> spectrumIdMap = new HashMap<String, Map>();
        for (Map<String, Object> spectrumMetadata : spectraMetadata) {
            spectrumIdMap.put((String) spectrumMetadata.get("spectrum_id"), spectrumMetadata);
        }

        Iterator<String> lSpectrumIdIterator = spectrumIdMap.keySet().iterator();
        ArrayList<String> lSpectrumidCacheList = Lists.newArrayList();

        while (lSpectrumIdIterator.hasNext()) {
            String spectrumId = lSpectrumIdIterator.next();
            lSpectrumidCacheList.add(spectrumId);
        }

        if (lSpectrumidCacheList.size() > 0) {
            spectrumService.cacheSpectra(lSpectrumidCacheList);
            LOGGER.debug(String.format("added %s entries to the spectrum Cache", lSpectrumidCacheList.size()));
        }

    }

    private void writeCachedSpectra(BufferedOutputStream aOutputStream, String experimentAccession) throws IOException {
        MascotGenericFile mascotGenericFile = null;
        PeakToMapFunction peakToMap = new PeakToMapFunction();

        //get spectra metadata
        List<Map<String, Object>> spectraMetadata = experimentRepository.getSpectraMetadata(experimentAccession);

        HashMap<String, Map> spectrumIdMap = new HashMap<String, Map>();
        for (Map<String, Object> spectrumMetadata : spectraMetadata) {
            spectrumIdMap.put((String) spectrumMetadata.get("spectrum_id"), spectrumMetadata);
        }

        for (String cachedSpectrumId : spectrumIdMap.keySet()) {
            Map spectrumMetadata = spectrumIdMap.get(cachedSpectrumId);

            //write identification data to stream
            mascotGenericFile = new MascotGenericFile();

            mascotGenericFile.setTitle(cachedSpectrumId.toString());

            Object lPrecursor_mz = spectrumMetadata.get("precursor_mz");
            if (lPrecursor_mz != null) {
                mascotGenericFile.setPrecursorMZ(Double.parseDouble(lPrecursor_mz.toString()));
            }

            Object lPrecursor_charge_state = spectrumMetadata.get("precursor_charge_state");
            if (lPrecursor_charge_state != null) {
                mascotGenericFile.setCharge(Integer.parseInt(lPrecursor_charge_state.toString()));
            }

            mascotGenericFile.setPeaks(peakToMap.apply(spectrumService.getSpectrumPeaksBySpectrumId(cachedSpectrumId)));

            //first mascot generic file has to start at the first line
            //else insert empty line
            if (iFirstMfgFile) {
                mascotGenericFile.setComments("");
                iFirstMfgFile = Boolean.FALSE;
            } else {
                mascotGenericFile.setComments("\n\n");
            }
            mascotGenericFile.writeToStream(aOutputStream);
        }
        LOGGER.debug(String.format("finished writing %d spectra to %s", spectraMetadata.size(), mascotGenericFile.getFilename()));

    }

    /**
     * Helper function class to Convert the pride-asap List<Peak> instances in
     * the HashMaps for the MascotGenericFile instance.
     */
    private class PeakToMapFunction implements Function<List<Peak>, HashMap> {

        @Override
        public HashMap apply(@Nullable List<Peak> aPeaks) {
            HashMap lResult = Maps.newHashMap();
            for (Peak lPeak : aPeaks) {
                lResult.put(lPeak.getMzRatio(), lPeak.getIntensity());
            }
            return lResult;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:rep="internal"
    jcr:primaryType="rep:ACL">
    <allo
        jcr:primaryType="rep:GrantACE"
        rep:principalName="everyone"
        rep:privileges="{Name}[jcr:all]"/>
    <deny
        jcr:primaryType="rep:GrantACE"
        rep:principalName="testuser"
        rep:privileges="{Name}[jcr:all]"/>
</jcr:root>


text:
"""data_helper tests package

Example:
    Run all tests from parent directory::

        python -m tests

    Run module test::

        python -m tests <module>
        python tests/<module.py>

"""

from SuiteHandler import SuiteHandler
import check, hash, parse, regex, transform

def run(sh, *args):
    sh.run_suite(*args)

sh = SuiteHandler({
    "check": check.suite,
    "hash": hash.suite,
    "parse": parse.suite,
    "regex": regex.suite,
    "transform": transform.suite
})

if __name__ == "__main__":
    run(sh)
    print sh.result
    for f in sh.result.failures:
        for t in f:
            print t
        print ''
    for e in sh.result.errors:
        for t in e:
            print t
        print ''


text:
<mavenModuleSet>
	<action></action>
	<action></action>
	<description>Fluxx, aggrégez vos flux RSS!</description>
	<displayName>fluxx</displayName>
	<name>fluxx</name>
	<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/</url>
	<buildable>true</buildable>
	<build>
		<number>102</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/102/</url>
	</build>
	<build>
		<number>101</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/101/</url>
	</build>
	<color>blue_anime</color>
	<firstBuild>
		<number>101</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/101/</url>
	</firstBuild>
	<healthReport>
		<description>Résultats des tests: 0 tests en échec sur un total de 72
			tests.</description>
		<iconUrl>health-80plus.gif</iconUrl>
		<score>100</score>
	</healthReport>
	<healthReport>
		<description>Stabilité du build: Aucun build récent n'a échoué.
		</description>
		<iconUrl>health-80plus.gif</iconUrl>
		<score>100</score>
	</healthReport>
	<inQueue>false</inQueue>
	<keepDependencies>false</keepDependencies>
	<lastBuild>
		<number>102</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/102/</url>
	</lastBuild>
	<lastCompletedBuild>
		<number>101</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/101/</url>
	</lastCompletedBuild>
	<lastStableBuild>
		<number>101</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/101/</url>
	</lastStableBuild>
	<lastSuccessfulBuild>
		<number>101</number>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/101/</url>
	</lastSuccessfulBuild>
	<nextBuildNumber>103</nextBuildNumber>
	<concurrentBuild>false</concurrentBuild>
	<scm></scm>
	<module>
		<name>fr.fluxx:fluxx</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx/</url>
		<color>blue</color>
		<displayName>fluxx</displayName>
	</module>
	<module>
		<name>fr.fluxx:fluxx-admin</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx-admin/
		</url>
		<color>disabled</color>
		<displayName>fluxx-admin</displayName>
	</module>
	<module>
		<name>fr.fluxx:fluxx-core</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx-core/
		</url>
		<color>disabled</color>
		<displayName>fluxx-core</displayName>
	</module>
	<module>
		<name>fr.fluxx:fluxx-ear</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx-ear/
		</url>
		<color>disabled</color>
		<displayName>fluxx-ear</displayName>
	</module>
	<module>
		<name>fr.fluxx:fluxx-integration-test</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx-integration-test/
		</url>
		<color>disabled</color>
		<displayName>fluxx-integration-test</displayName>
	</module>
	<module>
		<name>fr.fluxx:fluxx-web</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.fluxx$fluxx-web/
		</url>
		<color>disabled</color>
		<displayName>fluxx-web</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps:fluxx</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps$fluxx/
		</url>
		<color>disabled</color>
		<displayName>Fluxx</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps:fluxx-admin</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps$fluxx-admin/
		</url>
		<color>disabled</color>
		<displayName>fluxx-admin</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps:fluxx-core</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps$fluxx-core/
		</url>
		<color>disabled</color>
		<displayName>fluxx-core</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps:fluxx-integration-test</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps$fluxx-integration-test/
		</url>
		<color>disabled</color>
		<displayName>fluxx-integration-test</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps:fluxx-web</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps$fluxx-web/
		</url>
		<color>disabled</color>
		<displayName>fluxx-web</displayName>
	</module>
	<module>
		<name>fr.kaddath.apps.fluxx:fluxx</name>
		<url>http://fluxx.fr.cr:8080/hudson/job/fluxx/fr.kaddath.apps.fluxx$fluxx/
		</url>
		<color>disabled</color>
		<displayName>fluxx</displayName>
	</module>
</mavenModuleSet>


text:
requirejs.config({
	"baseUrl": "js/lib",
	"paths": {
		"app": "../app",
		"jquery": "//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery",
		"knockout": "//cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-debug"
	}
});

// Load the main module to start the app
requirejs(["app/main"]);


text:
package com.at.springboot.mybatis.vo;

import lombok.Data;

@Data
public class Book {

    private Long id;

    private String createdTime;

    private String updatedTime;

    private String title;

    private Long authorId;

    private String isbn;

    private Integer pageCount;

}


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Command;

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Bundle\FrameworkBundle\Command\RouterDebugCommand;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class RouterDebugCommandTest extends TestCase
{
    public function testDebugAllRoutes()
    {
        $tester = $this->createCommandTester();
        $ret = $tester->execute(array('name' => null), array('decorated' => false));

        $this->assertEquals(0, $ret, 'Returns 0 in case of success');
        $this->assertContains('Name   Method   Scheme   Host   Path', $tester->getDisplay());
    }

    public function testDebugSingleRoute()
    {
        $tester = $this->createCommandTester();
        $ret = $tester->execute(array('name' => 'foo'), array('decorated' => false));

        $this->assertEquals(0, $ret, 'Returns 0 in case of success');
        $this->assertContains('Route Name   | foo', $tester->getDisplay());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testDebugInvalidRoute()
    {
        $this->createCommandTester()->execute(array('name' => 'test'));
    }

    /**
     * @return CommandTester
     */
    private function createCommandTester()
    {
        $application = new Application($this->getKernel());

        $command = new RouterDebugCommand();
        $application->add($command);

        return new CommandTester($application->find('debug:router'));
    }

    private function getKernel()
    {
        $routeCollection = new RouteCollection();
        $routeCollection->add('foo', new Route('foo'));
        $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock();
        $router
            ->expects($this->any())
            ->method('getRouteCollection')
            ->will($this->returnValue($routeCollection))
        ;

        $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock();
        $container
            ->expects($this->once())
            ->method('has')
            ->with('router')
            ->will($this->returnValue(true))
        ;
        $container
            ->expects($this->any())
            ->method('get')
            ->with('router')
            ->willReturn($router)
        ;

        $kernel = $this->getMockBuilder(KernelInterface::class)->getMock();
        $kernel
            ->expects($this->any())
            ->method('getContainer')
            ->willReturn($container)
        ;
        $kernel
            ->expects($this->once())
            ->method('getBundles')
            ->willReturn(array())
        ;

        return $kernel;
    }
}


text:
@implementation NSString (Extension)
-(CGSize )sizeWithFont:(UIFont *)font{
   NSDictionary *att = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    return [self sizeWithAttributes:att];
}

-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
   NSDictionary *att = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:att context:nil].size;

}

@end


text:
/**
 * @module shimmer/example/provider
 * @fileOverview a quick example of how Shimmer could be exposed to a larger project
 * @author rozzzly
 */

import Shimmer from '../src/Shimmer';
import BaseShim from './BaseShim';

const shimmer = new Shimmer();
BaseShim(shimmer);
export default shimmer;

/**
 * checks if we are running on the server, or in a browser
 *
 * @method isServer
 * @memberOf module:shimmer/example/provider
 * @return {Boolean} if current context is running on server
 */
export function isServer() {
    return shimmer.shim('isServer')();
}

/**
 * Replacement for `typeof sym === 'symbol'`
 * `typeof` cannot be overwritten, for compatibility's sake when a native Symbol is not available,
 * finesse will use this util instead.
 * @see https://github.com/ljharb/object.assign/issues/17
 * @method isSymbol
 * @memberOf module:shimmer/example/provider
 * @param {Symbol} sym - variable that could be a Symbol
 * @return {Boolean} if given variable is a Symbol
 */
export function isSymbol(sym) {
    return Object.prototype.toString.call(sym) === '[object Symbol]';
}

export const instance = { isSymbol, isServer };


text:
using System;
using Aliyun.Api.LogService.Domain.Project;

namespace Aliyun.Api.LogService.Domain.MachineGroup
{
    public class ListMachineGroupRequest : ProjectScopedRequest
    {
        public const Int32 DefaultOffset = 0;
        public const Int32 DefaultSize = 500;

        /// <summary>
        /// 用于过滤的机器组名称(支持部分匹配)。
        /// </summary>
        public String GroupName { get; set; }

        /// <summary>
        /// 返回记录的起始位置,默认为 0。
        /// </summary>
        public Int32 Offset { get; set; } = DefaultOffset;

        /// <summary>
        /// 每页返回最大条目,默认 500(最大值)。
        /// </summary>
        public Int32 Size { get; set; } = DefaultSize;
    }
}


text:
	#4.1 IF found return index number
	#4.2 ElSE return -1
# 5. Binary search sorts array, and obtains middle element.
	#5.1 IF element is equal to passed student name return index
	#5.2 Else if element is less than middle element search through array from start to middle element index.
	#5.2 Else if element is large than middle element search through array from middle element index to sorted array length.
	#5.2 ElSE return -1

# Initial Solution

# class Student
# 	attr_accessor :scores, :first_name, :average

# 	def initialize(name,scores)
# 		@first_name = name
# 		@scores = scores
# 		@average = average
# 		@letter_grade = letter_grade
# 	end

# 	def average

# 		score_sum = 0

# 		@scores.each do |x|

# 			score_sum+= x

# 		end

# 		score_average = score_sum/@scores.size

# 		return score_average

# 	end

# 	def letter_grade

# 		if @average >= 90

# 			letter_grade = "A"

# 		elsif @average >=  80

# 			letter_grade = "B"

# 		elsif @average >=  70

# 			letter_grade = "C"

# 		elsif @average >= 60

# 			letter_grade = "D"

# 		else

# 			letter_grade = "F"

# 		end

# 		return letter_grade

# 	end

# end

# def linear_search(array,student_name)

# 	index = 0
# 	found = false

# 	array.each do |x|

# 		if x.first_name == student_name

# 			return index
# 			found = true
# 		elsif
# 			index+=1
# 		end

# 	end

# 	if found == false

# 		return -1
# 	end

# end

# def binary_search(array,student_name)

# 	index = 0

# 	found = false

# 	sorted = array.sort_by do |item|

#     item.first_name

# 	end

# 	puts "Looking for #{student_name}"

# 	puts "SORTED"

# 	sorted.each do |x|

# 		puts x.first_name
# 	end

# 	if sorted.length % 2 == 0

# 		middle = sorted[((array.length/2).round)-1].first_name

# 		middle_index = ((array.length/2).round)-1

# 	else

# 		middle = sorted[((array.length/2).round)].first_name

# 		middle_index = (array.length/2)

# 	end

# 	puts "MIDDLE STUDENT IS #{middle} AT INDEX #{middle_index}"

# 	if student_name == middle

# 		puts "equal"

# 		return middle_index

# 	elsif student_name < middle

# 		puts "lower"

# 		sorted[0, middle_index].each do |x|

# 			if x.first_name == student_name

# 				return index
# 				found = true
# 			elsif
# 				index+=1

# 			end

# 		end

# 	elsif student_name > middle

# 		puts "higher"

# 		index = middle_index

# 		sorted[middle_index,sorted.length].each do |x|

# 			if x.first_name == student_name
# 				return index
# 				found = true
# 			elsif
# 				index+=1
# 			end

# 		end

# 	else

# 		index+=1

# 	end

# 	if found == false

# 		return -1
# 	end

# end

# student_1 = Student.new("Alex",[100,100,100,0,100])
# student_2 = Student.new("Luis",[100,100,100,0,100])
# student_3 = Student.new("John",[100,100,100,0,100])
# student_4 = Student.new("Andrew",[100,100,100,0,100])
# student_5 = Student.new("Peter",[100,100,100,0,100])

# students =[student_1,student_2,student_3,student_4,student_5]

# Refactored Solution

class Student
	attr_accessor :scores, :first_name, :average

	def initialize(name,scores)
		@first_name = name
		@scores = scores
		@average = average
		@letter_grade = letter_grade
	end

	def average

		score_sum = 0

		@scores.each {|x| score_sum+= x}

		score_average = score_sum/@scores.size

		return score_average

	end

	def letter_grade

		if @average >= 90

			letter_grade = "A"

		elsif @average >=  80

			letter_grade = "B"

		elsif @average >=  70

			letter_grade = "C"

		elsif @average >= 60

			letter_grade = "D"

		else

			letter_grade = "F"

		end

		return letter_grade

	end

end

def linear_search(array,student_name)

	index = 0
	found = false

	array.each do |x|

		if x.first_name == student_name
			return index
			found = true
		elsif
			index+=1
		end

	end

	if found == false

		return -1
	end

end

def binary_search(array,student_name)

	index = 0

	found = false

	sorted = array.sort_by {|item| item.first_name}

	if sorted.length % 2 == 0

		middle = sorted[((array.length/2).round)-1].first_name

		middle_index = ((array.length/2).round)-1

	else

		middle = sorted[((array.length/2).round)].first_name

		middle_index = (array.length/2)

	end

	if student_name == middle

		return middle_index

	elsif student_name < middle

		sorted[0, middle_index].each do |x|

			if x.first_name == student_name
				return index
				found = true
			elsif
				index+=1

			end

		end

	elsif student_name > middle

		index = middle_index

		sorted[middle_index,sorted.length].each do |x|

			if x.first_name == student_name
				return index
				found = true
			elsif
				index+=1
			end

		end

	else

		index+=1

	end

	if found == false

		return -1
	end

end

student_1 = Student.new("Alex",[100,100,100,0,100])
student_2 = Student.new("Luis",[100,100,100,0,100])
student_3 = Student.new("John",[100,100,100,0,100])
student_4 = Student.new("Andrew",[100,100,100,0,100])
student_5 = Student.new("Peter",[100,100,100,0,100])

students =[student_1,student_2,student_3,student_4,student_5]

# DRIVER TESTS GO BELOW THIS LINE
# Initial Tests:

p students[0].first_name == "Alex"
p students[0].scores.length == 5
p students[0].scores[0] == students[0].scores[4]
p students[0].scores[3] == 0

# # # # Additional Tests 1:

p students[0].average == 80
p students[0].letter_grade == 'B'

# Additional Tests 2:

p linear_search(students, "Alex") == 0
p linear_search(students, "NOT A STUDENT") == -1

# Additional Tests 3:

p binary_search(students, "Alex") == 0
p binary_search(students, "NOT A STUDENT") == -1

# Reflection

=begin

What concepts did you review or learn in this challenge?

Reviewed iteration, each method as well as slice. If statements and array methods.

What is still confusing to you about Ruby?

Not much is confusing, sometime I have trouble understanding more complicated methods. Also, I am still confused
what the difference bewteen "" and '' is.

What are you going to study to get more prepared for Phase 1?

Harder methods as well as maing recursive methods.

=end


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1663</FormatID>
      <FormatName>Maya Binary File Format</FormatName>
      <FormatVersion>32 Bit</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Model</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>Maya is an application used to generate 3D assets for use in film, television, game development and architecture, currently developed and maintained by Autodesk.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>216</ProvenanceSourceID>
      <ProvenanceName>The Canadian Centre for Architecture / The Canadian Centre for Architecture</ProvenanceName>
      <ProvenanceSourceDate>09 Jan 2016</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>09 Jan 2016</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/861</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Developers>
        <DeveloperID>18</DeveloperID>
        <DeveloperName>
        </DeveloperName>
        <OrganisationName>Autodesk Corporation</OrganisationName>
        <DeveloperCompoundName>Autodesk Corporation</DeveloperCompoundName>
      </Developers>
      <Support>
        <SupportID>18</SupportID>
        <SupportName>
        </SupportName>
        <OrganisationName>Autodesk Corporation</OrganisationName>
        <SupportCompoundName>Autodesk Corporation</SupportCompoundName>
      </Support>
      <ExternalSignature>
        <ExternalSignatureID>1782</ExternalSignatureID>
        <Signature>mb</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>1221</SignatureID>
        <SignatureName>Maya Binary 32 Bit</SignatureName>
        <SignatureNote>BOF: FOR4{4}(Maya|MAYA)FOR4</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1493</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>464F5234{4}(4D617961|4D415941)464F5234</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text: .. automodule:: vivarium.framework.population.population_view


text:
<?php
/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Component\CustomUrl\Tests\Unit\Document\Subscriber;

use Sulu\Bundle\ContentBundle\Document\BasePageDocument;
use Sulu\Component\CustomUrl\Document\CustomUrlDocument;
use Sulu\Component\CustomUrl\Document\Subscriber\InvalidateSubscriber;
use Sulu\Component\CustomUrl\Manager\CustomUrlManagerInterface;
use Sulu\Component\DocumentManager\Event\PersistEvent;

class InvalidateSubscriberTest extends \PHPUnit_Framework_TestCase
{
    public function testHandlePersist()
    {
        $manager = $this->prophesize(CustomUrlManagerInterface::class);
        $subscriber = new InvalidateSubscriber($manager->reveal());

        $customUrl = $this->prophesize(CustomUrlDocument::class);

        $document = $this->prophesize(BasePageDocument::class);
        $event = $this->prophesize(PersistEvent::class);
        $event->getDocument()->willReturn($document->reveal());

        $manager->findByPage($document->reveal())->willReturn([$customUrl->reveal()]);
        $manager->invalidate($customUrl->reveal())->shouldBeCalled();

        $subscriber->handlePersist($event->reveal());
    }

    public function testHandlePersistOtherDocuments()
    {
        $manager = $this->prophesize(CustomUrlManagerInterface::class);
        $subscriber = new InvalidateSubscriber($manager->reveal());

        $customUrl = $this->prophesize(CustomUrlDocument::class);

        $document = new \stdClass();
        $event = $this->prophesize(PersistEvent::class);
        $event->getDocument()->willReturn($document);

        $manager->findByPage($document)->shouldNotBeCalled();
        $manager->invalidate($customUrl->reveal())->shouldNotBeCalled();

        $subscriber->handlePersist($event->reveal());
    }
}


text:
module Spree
  module Stock
    class Estimator
      attr_reader :order, :currency

      def initialize(order)
        @order = order
        @currency = order.currency
      end

      def shipping_rates(package, shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END)
        rates = calculate_shipping_rates(package, shipping_method_filter)
        choose_default_shipping_rate(rates)
        sort_shipping_rates(rates)
      end

      private
      def choose_default_shipping_rate(shipping_rates)
        unless shipping_rates.empty?
          shipping_rates.min_by(&:cost).selected = true
        end
      end

      def sort_shipping_rates(shipping_rates)
        shipping_rates.sort_by!(&:cost)
      end

      def calculate_shipping_rates(package, ui_filter)
        shipping_methods(package, ui_filter).map do |shipping_method|
          cost = shipping_method.calculator.compute(package)
          tax_category = shipping_method.tax_category
          if tax_category
            tax_rate = tax_category.tax_rates.detect do |rate|
              # If the rate's zone matches the order's zone, a positive adjustment will be applied.
              # If the rate is from the default tax zone, then a negative adjustment will be applied.
              # See the tests in shipping_rate_spec.rb for an example of this.d
              rate.zone == order.tax_zone || rate.zone.default_tax?
            end
          end

          if cost
            rate = shipping_method.shipping_rates.new(cost: cost)
            rate.tax_rate = tax_rate if tax_rate
          end

          rate
        end.compact
      end

      def shipping_methods(package, display_filter)
        package.shipping_methods.select do |ship_method|
          calculator = ship_method.calculator
          begin
            ship_method.available_to_display(display_filter) &&
            ship_method.include?(order.ship_address) &&
            calculator.available?(package) &&
            (calculator.preferences[:currency].blank? ||
             calculator.preferences[:currency] == currency)
          rescue Exception => exception
            log_calculator_exception(ship_method, exception)
          end
        end
      end

      def log_calculator_exception(ship_method, exception)
        Rails.logger.info("Something went wrong calculating rates with the #{ship_method.name} (ID=#{ship_method.id}) shipping method.")
        Rails.logger.info("*" * 50)
        Rails.logger.info(exception.backtrace.join("\n"))
      end
    end
  end
end


text:
package org.apache.spark.mllib.clustering

import org.json4s._
import org.json4s.DefaultFormats
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

import org.apache.spark.SparkContext
import org.apache.spark.annotation.Since
import org.apache.spark.api.java.JavaRDD
import org.apache.spark.internal.Logging
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.util.{Loader, Saveable}
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Row, SparkSession}

/**
 * Clustering model produced by [[BisectingKMeans]].
 * The prediction is done level-by-level from the root node to a leaf node, and at each node among
 * its children the closest to the input point is selected.
 *
 * @param root the root node of the clustering tree
 */
@Since("1.6.0")
class BisectingKMeansModel private[clustering] (
    private[clustering] val root: ClusteringTreeNode,
    @Since("2.4.0") val distanceMeasure: String,
    @Since("3.0.0") val trainingCost: Double
  ) extends Serializable with Saveable with Logging {

  @Since("1.6.0")
  def this(root: ClusteringTreeNode) = this(root, DistanceMeasure.EUCLIDEAN, 0.0)

  private val distanceMeasureInstance: DistanceMeasure =
    DistanceMeasure.decodeFromString(distanceMeasure)

  /**
   * Leaf cluster centers.
   */
  @Since("1.6.0")
  def clusterCenters: Array[Vector] = root.leafNodes.map(_.center)

  /**
   * Number of leaf clusters.
   */
  lazy val k: Int = clusterCenters.length

  /**
   * Predicts the index of the cluster that the input point belongs to.
   */
  @Since("1.6.0")
  def predict(point: Vector): Int = {
    root.predict(point, distanceMeasureInstance)
  }

  /**
   * Predicts the indices of the clusters that the input points belong to.
   */
  @Since("1.6.0")
  def predict(points: RDD[Vector]): RDD[Int] = {
    points.map { p => root.predict(p, distanceMeasureInstance) }
  }

  /**
   * Java-friendly version of `predict()`.
   */
  @Since("1.6.0")
  def predict(points: JavaRDD[Vector]): JavaRDD[java.lang.Integer] =
    predict(points.rdd).toJavaRDD().asInstanceOf[JavaRDD[java.lang.Integer]]

  /**
   * Computes the squared distance between the input point and the cluster center it belongs to.
   */
  @Since("1.6.0")
  def computeCost(point: Vector): Double = {
    root.computeCost(point, distanceMeasureInstance)
  }

  /**
   * Computes the sum of squared distances between the input points and their corresponding cluster
   * centers.
   */
  @Since("1.6.0")
  def computeCost(data: RDD[Vector]): Double = {
    data.map(root.computeCost(_, distanceMeasureInstance)).sum()
  }

  /**
   * Java-friendly version of `computeCost()`.
   */
  @Since("1.6.0")
  def computeCost(data: JavaRDD[Vector]): Double = this.computeCost(data.rdd)

  @Since("2.0.0")
  override def save(sc: SparkContext, path: String): Unit = {
    BisectingKMeansModel.SaveLoadV3_0.save(sc, this, path)
  }

  override protected def formatVersion: String = "3.0"
}

@Since("2.0.0")
object BisectingKMeansModel extends Loader[BisectingKMeansModel] {

  @Since("2.0.0")
  override def load(sc: SparkContext, path: String): BisectingKMeansModel = {
    val (loadedClassName, formatVersion, __) = Loader.loadMetadata(sc, path)
    (loadedClassName, formatVersion) match {
      case (SaveLoadV1_0.thisClassName, SaveLoadV1_0.thisFormatVersion) =>
        val model = SaveLoadV1_0.load(sc, path)
        model
      case (SaveLoadV2_0.thisClassName, SaveLoadV2_0.thisFormatVersion) =>
        val model = SaveLoadV2_0.load(sc, path)
        model
      case (SaveLoadV3_0.thisClassName, SaveLoadV3_0.thisFormatVersion) =>
        val model = SaveLoadV3_0.load(sc, path)
        model
      case _ => throw new Exception(
        s"BisectingKMeansModel.load did not recognize model with (className, format version):" +
          s"($loadedClassName, $formatVersion).  Supported:\n" +
          s"  (${SaveLoadV1_0.thisClassName}, ${SaveLoadV1_0.thisClassName}\n" +
          s"  (${SaveLoadV2_0.thisClassName}, ${SaveLoadV2_0.thisClassName})\n" +
          s"  (${SaveLoadV3_0.thisClassName}, ${SaveLoadV3_0.thisClassName})")
    }
  }

  private case class Data(index: Int, size: Long, center: Vector, norm: Double, cost: Double,
     height: Double, children: Seq[Int])

  private object Data {
    def apply(r: Row): Data = Data(r.getInt(0), r.getLong(1), r.getAs[Vector](2), r.getDouble(3),
      r.getDouble(4), r.getDouble(5), r.getSeq[Int](6))
  }

  private def getNodes(node: ClusteringTreeNode): Array[ClusteringTreeNode] = {
    if (node.children.isEmpty) {
      Array(node)
    } else {
      node.children.flatMap(getNodes) ++ Array(node)
    }
  }

  private def buildTree(rootId: Int, nodes: Map[Int, Data]): ClusteringTreeNode = {
    val root = nodes(rootId)
    if (root.children.isEmpty) {
      new ClusteringTreeNode(root.index, root.size, new VectorWithNorm(root.center, root.norm),
        root.cost, root.height, new Array[ClusteringTreeNode](0))
    } else {
      val children = root.children.map(c => buildTree(c, nodes))
      new ClusteringTreeNode(root.index, root.size, new VectorWithNorm(root.center, root.norm),
        root.cost, root.height, children.toArray)
    }
  }

  private[clustering] object SaveLoadV1_0 {
    private[clustering] val thisFormatVersion = "1.0"

    private[clustering]
    val thisClassName = "org.apache.spark.mllib.clustering.BisectingKMeansModel"

    def save(sc: SparkContext, model: BisectingKMeansModel, path: String): Unit = {
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val metadata = compact(render(
        ("class" -> thisClassName) ~ ("version" -> thisFormatVersion)
          ~ ("rootId" -> model.root.index)))
      sc.parallelize(Seq(metadata), 1).saveAsTextFile(Loader.metadataPath(path))

      val data = getNodes(model.root).map(node => Data(node.index, node.size,
        node.centerWithNorm.vector, node.centerWithNorm.norm, node.cost, node.height,
        node.children.map(_.index)))
      spark.createDataFrame(data).write.parquet(Loader.dataPath(path))
    }

    def load(sc: SparkContext, path: String): BisectingKMeansModel = {
      implicit val formats: DefaultFormats = DefaultFormats
      val (className, formatVersion, metadata) = Loader.loadMetadata(sc, path)
      assert(className == thisClassName)
      assert(formatVersion == thisFormatVersion)
      val rootId = (metadata \ "rootId").extract[Int]
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val rows = spark.read.parquet(Loader.dataPath(path))
      Loader.checkSchema[Data](rows.schema)
      val data = rows.select("index", "size", "center", "norm", "cost", "height", "children")
      val nodes = data.rdd.map(Data.apply).collect().map(d => (d.index, d)).toMap
      val rootNode = buildTree(rootId, nodes)
      val totalCost = rootNode.leafNodes.map(_.cost).sum
      new BisectingKMeansModel(rootNode, DistanceMeasure.EUCLIDEAN, totalCost)
    }
  }

  private[clustering] object SaveLoadV2_0 {
    private[clustering] val thisFormatVersion = "2.0"

    private[clustering]
    val thisClassName = "org.apache.spark.mllib.clustering.BisectingKMeansModel"

    def save(sc: SparkContext, model: BisectingKMeansModel, path: String): Unit = {
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val metadata = compact(render(
        ("class" -> thisClassName) ~ ("version" -> thisFormatVersion)
          ~ ("rootId" -> model.root.index) ~ ("distanceMeasure" -> model.distanceMeasure)))
      sc.parallelize(Seq(metadata), 1).saveAsTextFile(Loader.metadataPath(path))

      val data = getNodes(model.root).map(node => Data(node.index, node.size,
        node.centerWithNorm.vector, node.centerWithNorm.norm, node.cost, node.height,
        node.children.map(_.index)))
      spark.createDataFrame(data).write.parquet(Loader.dataPath(path))
    }

    def load(sc: SparkContext, path: String): BisectingKMeansModel = {
      implicit val formats: DefaultFormats = DefaultFormats
      val (className, formatVersion, metadata) = Loader.loadMetadata(sc, path)
      assert(className == thisClassName)
      assert(formatVersion == thisFormatVersion)
      val rootId = (metadata \ "rootId").extract[Int]
      val distanceMeasure = (metadata \ "distanceMeasure").extract[String]
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val rows = spark.read.parquet(Loader.dataPath(path))
      Loader.checkSchema[Data](rows.schema)
      val data = rows.select("index", "size", "center", "norm", "cost", "height", "children")
      val nodes = data.rdd.map(Data.apply).collect().map(d => (d.index, d)).toMap
      val rootNode = buildTree(rootId, nodes)
      val totalCost = rootNode.leafNodes.map(_.cost).sum
      new BisectingKMeansModel(rootNode, distanceMeasure, totalCost)
    }
  }

  private[clustering] object SaveLoadV3_0 {
    private[clustering] val thisFormatVersion = "3.0"

    private[clustering]
    val thisClassName = "org.apache.spark.mllib.clustering.BisectingKMeansModel"

    def save(sc: SparkContext, model: BisectingKMeansModel, path: String): Unit = {
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val metadata = compact(render(
        ("class" -> thisClassName) ~ ("version" -> thisFormatVersion)
          ~ ("rootId" -> model.root.index) ~ ("distanceMeasure" -> model.distanceMeasure)
          ~ ("trainingCost" -> model.trainingCost)))
      sc.parallelize(Seq(metadata), 1).saveAsTextFile(Loader.metadataPath(path))

      val data = getNodes(model.root).map(node => Data(node.index, node.size,
        node.centerWithNorm.vector, node.centerWithNorm.norm, node.cost, node.height,
        node.children.map(_.index)))
      spark.createDataFrame(data).write.parquet(Loader.dataPath(path))
    }

    def load(sc: SparkContext, path: String): BisectingKMeansModel = {
      implicit val formats: DefaultFormats = DefaultFormats
      val (className, formatVersion, metadata) = Loader.loadMetadata(sc, path)
      assert(className == thisClassName)
      assert(formatVersion == thisFormatVersion)
      val rootId = (metadata \ "rootId").extract[Int]
      val distanceMeasure = (metadata \ "distanceMeasure").extract[String]
      val trainingCost = (metadata \ "trainingCost").extract[Double]
      val spark = SparkSession.builder().sparkContext(sc).getOrCreate()
      val rows = spark.read.parquet(Loader.dataPath(path))
      Loader.checkSchema[Data](rows.schema)
      val data = rows.select("index", "size", "center", "norm", "cost", "height", "children")
      val nodes = data.rdd.map(Data.apply).collect().map(d => (d.index, d)).toMap
      val rootNode = buildTree(rootId, nodes)
      new BisectingKMeansModel(rootNode, distanceMeasure, trainingCost)
    }
  }
}


text:
      {{'msg.storage.ui.criterion.criteria' | translate}}

              <input type="checkbox" [checked]="isCheckedCriterion(criterion)">

              {{criterion.criterionName | translate}}


text:
import { Routes, RouterModule } from '@angular/router';

import { Catalogs } from './catalogs.component';

import { Companies } from './companies';
import { CompanyEditorForm } from './companies/editor/editor.component';

import { PartsComponent } from './parts';
import { PartEditorForm } from './parts/editor/editor.component';

const routes: Routes = [{
    path: '',
    component: Catalogs,
    children: [
        {path: 'companies', component: Companies},
        {path: 'companies/editor/:id', component: CompanyEditorForm},
        {path: 'parts', component: PartsComponent},
        {path: 'parts/editor/:id', component: PartEditorForm},
    ]
}];

export const routing = RouterModule.forChild(routes);


text:
class AddExtractedTextMapping < ActiveRecord::Migration[4.2]
  def change
    index_alias = CheckElasticSearchModel.get_index_alias
    client = $repository.client
    options = {
      index: index_alias,
      body: {
        properties: {
          extracted_text: { type: 'text', analyzer: 'check' }
        }
      }
    }
    client.indices.put_mapping options
  end
end


text:
package com.hazelcast.map.impl.mapstore;

import com.hazelcast.map.impl.mapstore.writebehind.WriteBehindManager;
import com.hazelcast.map.impl.mapstore.writethrough.WriteThroughManager;

/**
 * Static factory class for various map store managers.
 */
public final class MapStoreManagers {

    private MapStoreManagers() {
    }

    public static MapStoreManager createWriteThroughManager(MapStoreContext mapStoreContext) {
        return new WriteThroughManager(mapStoreContext);
    }

    public static MapStoreManager createWriteBehindManager(MapStoreContext mapStoreContext) {
        return new WriteBehindManager(mapStoreContext);
    }

    public static MapStoreManager emptyMapStoreManager() {
        return EmptyHolder.EMPTY;
    }

    private static class EmptyHolder {
        static final MapStoreManager EMPTY = createEmptyManager();
    }

    private static MapStoreManager createEmptyManager() {
        return new MapStoreManager() {
            @Override
            public void start() {
            }

            @Override
            public void stop() {
            }

            @Override
            public MapDataStore getMapDataStore(String mapName, int partitionId) {
                return MapDataStores.EMPTY_MAP_DATA_STORE;
            }
        };
    }
}


text:
"""Task for a walker to move to a target."""

from dm_control import composer
from dm_control.composer import variation
from dm_control.composer.observation import observable
from dm_control.composer.variation import distributions
import numpy as np

DEFAULT_DISTANCE_TOLERANCE_TO_TARGET = 1.0

class GoToTarget(composer.Task):
  """A task that requires a walker to move towards a target."""

  def __init__(self,
               walker,
               arena,
               moving_target=False,
               target_relative=False,
               target_relative_dist=1.5,
               steps_before_moving_target=10,
               distance_tolerance=DEFAULT_DISTANCE_TOLERANCE_TO_TARGET,
               target_spawn_position=None,
               walker_spawn_position=None,
               walker_spawn_rotation=None,
               physics_timestep=0.005,
               control_timestep=0.025):
    """Initializes this task.

    Args:
      walker: an instance of `locomotion.walkers.base.Walker`.
      arena: an instance of `locomotion.arenas.floors.Floor`.
      moving_target: bool, Whether the target should move after receiving the
        walker reaches it.
      target_relative: bool, Whether the target be set relative to its current
        position.
      target_relative_dist: float, new target distance range if
        using target_relative.
      steps_before_moving_target: int, the number of steps before the target
        moves, if moving_target==True.
      distance_tolerance: Accepted to distance to the target position before
        providing reward.
      target_spawn_position: a sequence of 2 numbers, or a `composer.Variation`
        instance that generates such sequences, specifying the position at
        which the target is spawned at the beginning of an episode.
        If None, the entire arena is used to generate random target positions.
      walker_spawn_position: a sequence of 2 numbers, or a `composer.Variation`
        instance that generates such sequences, specifying the position at
        which the walker is spawned at the beginning of an episode.
        If None, the entire arena is used to generate random spawn positions.
      walker_spawn_rotation: a number, or a `composer.Variation` instance that
        generates a number, specifying the yaw angle offset (in radians) that is
        applied to the walker at the beginning of an episode.
      physics_timestep: a number specifying the timestep (in seconds) of the
        physics simulation.
      control_timestep: a number specifying the timestep (in seconds) at which
        the agent applies its control inputs (in seconds).
    """

    self._arena = arena
    self._walker = walker
    self._walker.create_root_joints(self._arena.attach(self._walker))

    arena_position = distributions.Uniform(
        low=-np.array(arena.size) / 2, high=np.array(arena.size) / 2)
    if target_spawn_position is not None:
      self._target_spawn_position = target_spawn_position
    else:
      self._target_spawn_position = arena_position

    if walker_spawn_position is not None:
      self._walker_spawn_position = walker_spawn_position
    else:
      self._walker_spawn_position = arena_position

    self._walker_spawn_rotation = walker_spawn_rotation

    self._distance_tolerance = distance_tolerance
    self._moving_target = moving_target
    self._target_relative = target_relative
    self._target_relative_dist = target_relative_dist
    self._steps_before_moving_target = steps_before_moving_target
    self._reward_step_counter = 0

    self._target = self.root_entity.mjcf_model.worldbody.add(
        'site',
        name='target',
        type='sphere',
        pos=(0., 0., 0.),
        size=(0.1,),
        rgba=(0.9, 0.6, 0.6, 1.0))

    enabled_observables = []
    enabled_observables += self._walker.observables.proprioception
    enabled_observables += self._walker.observables.kinematic_sensors
    enabled_observables += self._walker.observables.dynamic_sensors
    enabled_observables.append(self._walker.observables.sensors_touch)
    for obs in enabled_observables:
      obs.enabled = True

    walker.observables.add_egocentric_vector(
        'target',
        observable.MJCFFeature('pos', self._target),
        origin_callable=lambda physics: physics.bind(walker.root_body).xpos)

    self.set_timesteps(
        physics_timestep=physics_timestep, control_timestep=control_timestep)

  @property
  def root_entity(self):
    return self._arena

  def target_position(self, physics):
    return np.array(physics.bind(self._target).pos)

  def initialize_episode_mjcf(self, random_state):
    self._arena.regenerate(random_state=random_state)

    target_x, target_y = variation.evaluate(
        self._target_spawn_position, random_state=random_state)
    self._target.pos = [target_x, target_y, 0.]

  def initialize_episode(self, physics, random_state):
    self._walker.reinitialize_pose(physics, random_state)
    if self._walker_spawn_rotation:
      rotation = variation.evaluate(
          self._walker_spawn_rotation, random_state=random_state)
      quat = [np.cos(rotation / 2), 0, 0, np.sin(rotation / 2)]
    else:
      quat = None
    walker_x, walker_y = variation.evaluate(
        self._walker_spawn_position, random_state=random_state)
    self._walker.shift_pose(
        physics,
        position=[walker_x, walker_y, 0.],
        quaternion=quat,
        rotate_velocity=True)

    self._failure_termination = False
    walker_foot_geoms = set(self._walker.ground_contact_geoms)
    walker_nonfoot_geoms = [
        geom for geom in self._walker.mjcf_model.find_all('geom')
        if geom not in walker_foot_geoms]
    self._walker_nonfoot_geomids = set(
        physics.bind(walker_nonfoot_geoms).element_id)
    self._ground_geomids = set(
        physics.bind(self._arena.ground_geoms).element_id)
    self._ground_geomids.add(physics.bind(self._target).element_id)

  def _is_disallowed_contact(self, contact):
    set1, set2 = self._walker_nonfoot_geomids, self._ground_geomids
    return ((contact.geom1 in set1 and contact.geom2 in set2) or
            (contact.geom1 in set2 and contact.geom2 in set1))

  def should_terminate_episode(self, physics):
    return self._failure_termination

  def get_discount(self, physics):
    if self._failure_termination:
      return 0.
    else:
      return 1.

  def get_reward(self, physics):
    reward = 0.
    distance = np.linalg.norm(
        physics.bind(self._target).pos[:2] -
        physics.bind(self._walker.root_body).xpos[:2])
    if distance < self._distance_tolerance:
      reward = 1.
      if self._moving_target:
        self._reward_step_counter += 1
    return reward

  def before_step(self, physics, action, random_state):
    self._walker.apply_action(physics, action, random_state)

  def after_step(self, physics, random_state):
    self._failure_termination = False
    for contact in physics.data.contact:
      if self._is_disallowed_contact(contact):
        self._failure_termination = True
        break
    if (self._moving_target and
        self._reward_step_counter >= self._steps_before_moving_target):

      # Reset the target position.
      if self._target_relative:
        walker_pos = physics.bind(self._walker.root_body).xpos[:2]
        target_x, target_y = random_state.uniform(
            -np.array([self._target_relative_dist, self._target_relative_dist]),
            np.array([self._target_relative_dist, self._target_relative_dist]))
        target_x += walker_pos[0]
        target_y += walker_pos[1]
      else:
        target_x, target_y = variation.evaluate(
            self._target_spawn_position, random_state=random_state)
      physics.bind(self._target).pos = [target_x, target_y, 0.]

      # Reset the number of steps at the target for the moving target.
      self._reward_step_counter = 0


text: DROP INDEX users_name_key