text:
package com.twitter.scalding

import cascading.pipe._
import cascading.pipe.assembly._
import cascading.operation._
import cascading.tuple.Fields
import cascading.tuple.TupleEntry

import scala.{ Range => ScalaRange }

/**
 * This controls the sequence of reductions that happen inside a
 * particular grouping operation.  Not all elements can be combined,
 * for instance, a scanLeft/foldLeft generally requires a sorting
 * but such sorts are (at least for now) incompatible with doing a combine
 * which includes some map-side reductions.
 */
class GroupBuilder(val groupFields: Fields) extends FoldOperations[GroupBuilder] with StreamOperations[GroupBuilder] {
  // We need the implicit conversions from symbols to Fields
  import Dsl._

  /**
   * Holds the "reducers/combiners", the things that we can do paritially map-side.
   */
  private var reds: Option[List[AggregateBy]] = Some(Nil)

  /**
   * This is the description of this Grouping in terms of a sequence of Every operations
   */
  protected var evs: List[Pipe => Every] = Nil
  protected var isReversed: Boolean = false

  protected var sortF: Option[Fields] = None
  def sorting = sortF
  /*
  * maxMF is the maximum index of a "middle field" allocated for mapReduceMap operations
  */
  private var maxMF: Int = 0

  private def getNextMiddlefield: String = {
    val out = "__middlefield__" + maxMF.toString
    maxMF += 1
    return out
  }

  private def tryAggregateBy(ab: AggregateBy, ev: Pipe => Every): Boolean = {
    // Concat if there if not none
    reds = reds.map(rl => ab :: rl)
    evs = ev :: evs
    return !reds.isEmpty
  }

  /**
   * Holds the number of reducers to use in the reduce stage of the groupBy/aggregateBy.
   * By default uses whatever value is set in the jobConf.
   */
  private var numReducers: Option[Int] = None

  /**
   * Holds an optional user-specified description to be used in .dot and MR step names.
   */
  private var descriptions: Seq[String] = Nil

  /**
   * Limit of number of keys held in SpillableTupleMap on an AggregateBy
   */
  private var spillThreshold: Option[Int] = None

  /**
   * Holds all the input fields that will be used in groupBy
   */
  private var projectFields: Option[Fields] = Some(groupFields)

  /**
   * Override the number of reducers used in the groupBy.
   */
  def reducers(r: Int) = {
    if (r > 0) {
      numReducers = Some(r)
    }
    this
  }

  /**
   * Override the description to be used in .dot and MR step names.
   */
  def setDescriptions(newDescriptions: Seq[String]) = {
    descriptions = newDescriptions
    this
  }

  /**
   * Override the spill threshold on AggregateBy
   */
  def spillThreshold(t: Int): GroupBuilder = {
    spillThreshold = Some(t)
    this
  }

  /**
   * This cancels map side aggregation
   * and forces everything to the reducers
   */
  def forceToReducers = {
    reds = None
    this
  }

  protected def overrideReducers(p: Pipe): Pipe = {
    numReducers.map { r => RichPipe.setReducers(p, r) }.getOrElse(p)
  }

  protected def overrideDescription(p: Pipe): Pipe = {
    RichPipe.setPipeDescriptions(p, descriptions)
  }

  /**
   * == Warning ==
   * This may significantly reduce performance of your job.
   * It kills the ability to do map-side aggregation.
   */
  def buffer(args: Fields)(b: Buffer[_]): GroupBuilder = {
    every(pipe => new Every(pipe, args, b))
  }

  /**
   * Prefer aggregateBy operations!
   */
  def every(ev: Pipe => Every): GroupBuilder = {
    projectFields = None // Assume we are keeping all outputs
    reds = None
    evs = ev :: evs
    this
  }

  /**
   * Prefer reduce or mapReduceMap. foldLeft will force all work to be
   * done on the reducers.  If your function is not associative and
   * commutative, foldLeft may be required.
   *
   * == Best Practice ==
   * Make sure init is an immutable object.
   *
   * == Note ==
   * Init needs to be serializable with Kryo (because we copy it for each
   * grouping to avoid possible errors using a mutable init object).
   */
  def foldLeft[X, T](fieldDef: (Fields, Fields))(init: X)(fn: (X, T) => X)(implicit setter: TupleSetter[X], conv: TupleConverter[T]): GroupBuilder = {
    val (inFields, outFields) = fieldDef
    conv.assertArityMatches(inFields)
    setter.assertArityMatches(outFields)
    val ag = new FoldAggregator[T, X](fn, init, outFields, conv, setter)
    val beforePF = projectFields
    every(pipe => new Every(pipe, inFields, ag))
    // Update projectFields, which makes sense in a fold, but invalidated on every
    projectFields = beforePF.map { Fields.merge(_, inFields) }
    this
  }

  /**
   * Type `T` is the type of the input field `(input to map, T => X)`
   *
   * Type `X` is the intermediate type, which your reduce function operates on
   * `(reduce is (X,X) => X)`
   *
   * Type `U` is the final result type, `(final map is: X => U)`
   *
   * The previous output goes into the reduce function on the left, like foldLeft,
   * so if your operation is faster for the accumulator to be on one side, be aware.
   */
  def mapReduceMap[T, X, U](fieldDef: (Fields, Fields))(mapfn: T => X)(redfn: (X, X) => X)(mapfn2: X => U)(implicit startConv: TupleConverter[T],
    middleSetter: TupleSetter[X],
    middleConv: TupleConverter[X],
    endSetter: TupleSetter[U]): GroupBuilder = {
    val (maybeSortedFromFields, maybeSortedToFields) = fieldDef
    //Check for arity safety:
    // To fields CANNOT have a sorting, or cascading gets unhappy:
    // TODO this may be fixed in cascading later
    val toFields = new Fields(asList(maybeSortedToFields): _*)
    val fromFields = new Fields(asList(maybeSortedFromFields): _*)
    startConv.assertArityMatches(fromFields)
    endSetter.assertArityMatches(toFields)
    // Update projectFields
    projectFields = projectFields.map { Fields.merge(_, fromFields) }
    val ag = new MRMAggregator[T, X, U](mapfn, redfn, mapfn2, toFields, startConv, endSetter)
    val ev = (pipe => new Every(pipe, fromFields, ag)): Pipe => Every
    assert(middleSetter.arity > 0,
      "The middle arity must have definite size, try wrapping in scala.Tuple1 if you need a hack")
    // Create the required number of middlefields based on the arity of middleSetter
    val middleFields = strFields(ScalaRange(0, middleSetter.arity).map { i => getNextMiddlefield })
    val mrmBy = new MRMBy[T, X, U](fromFields, middleFields, toFields,
      mapfn, redfn, mapfn2, startConv, middleSetter, middleConv, endSetter)
    tryAggregateBy(mrmBy, ev)
    this
  }

  /**
   * Corresponds to a Cascading Buffer
   * which allows you to stream through the data, keeping some, dropping, scanning, etc...
   * The iterator you are passed is lazy, and mapping will not trigger the
   * entire evaluation.  If you convert to a list (i.e. to reverse), you need to be aware
   * that memory constraints may become an issue.
   *
   * == Warning ==
   * Any fields not referenced by the input fields will be aligned to the first output,
   * and the final hadoop stream will have a length of the maximum of the output of this, and
   * the input stream.  So, if you change the length of your inputs, the other fields won't
   * be aligned.  YOU NEED TO INCLUDE ALL THE FIELDS YOU WANT TO KEEP ALIGNED IN THIS MAPPING!
   * POB: This appears to be a Cascading design decision.
   *
   * == Warning ==
   * mapfn needs to be stateless.  Multiple calls needs to be safe (no mutable
   * state captured)
   */
  def mapStream[T, X](fieldDef: (Fields, Fields))(mapfn: (Iterator[T]) => TraversableOnce[X])(implicit conv: TupleConverter[T], setter: TupleSetter[X]) = {
    val (inFields, outFields) = fieldDef
    //Check arity
    conv.assertArityMatches(inFields)
    setter.assertArityMatches(outFields)
    val b = new BufferOp[Unit, T, X]((),
      (u: Unit, it: Iterator[T]) => mapfn(it), outFields, conv, setter)
    every(pipe => new Every(pipe, inFields, b, defaultMode(inFields, outFields)))
  }

  def reverse: GroupBuilder = {
    assert(reds.isEmpty, "Cannot sort when reducing")
    assert(!isReversed, "Reverse called a second time! Only one allowed")
    isReversed = true
    this
  }

  /**
   * Analog of standard scanLeft (@see scala.collection.Iterable.scanLeft )
   * This invalidates map-side aggregation, forces all data to be transferred
   * to reducers.  Use only if you REALLY have to.
   *
   * == Best Practice ==
   * Make sure init is an immutable object.
   *
   * == Note ==
   * init needs to be serializable with Kryo (because we copy it for each
   * grouping to avoid possible errors using a mutable init object).
   *  We override the default implementation here to use Kryo to serialize
   *  the initial value, for immutable serializable inits, this is not needed
   */
  override def scanLeft[X, T](fieldDef: (Fields, Fields))(init: X)(fn: (X, T) => X)(implicit setter: TupleSetter[X], conv: TupleConverter[T]): GroupBuilder = {
    val (inFields, outFields) = fieldDef
    //Check arity
    conv.assertArityMatches(inFields)
    setter.assertArityMatches(outFields)
    val b = new BufferOp[X, T, X](init,
      // On scala 2.8, there is no scanLeft
      // On scala 2.9, their implementation creates an off-by-one bug with the unused fields
      (i: X, it: Iterator[T]) => new ScanLeftIterator(it, i, fn),
      outFields, conv, setter)
    every(pipe => new Every(pipe, inFields, b, defaultMode(inFields, outFields)))
  }

  def groupMode: GroupMode =
    (reds, evs, sortF) match {
      case (None, Nil, Some(_)) => IdentityMode // no reducers or everys, just a sort
      case (Some(Nil), Nil, _) => IdentityMode // no sort, just identity. used to shuffle data
      case (None, _, _) => GroupByMode
      case (Some(redList), _, None) => AggregateByMode // use map-side aggregation
      case _ => sys.error("Invalid GroupBuilder state: %s, %s, %s".format(reds, evs, sortF))
    }

  protected def groupedPipeOf(name: String, in: Pipe): GroupBy = {
    val gb: GroupBy = sortF match {
      case None => new GroupBy(name, in, groupFields)
      case Some(sf) => new GroupBy(name, in, groupFields, sf, isReversed)
    }
    overrideReducers(gb)
    overrideDescription(gb)
    gb
  }

  def schedule(name: String, pipe: Pipe): Pipe = {
    val maybeProjectedPipe = projectFields.map { pipe.project(_) }.getOrElse(pipe)
    groupMode match {
      case GroupByMode =>
        //In this case we cannot aggregate, so group:
        val start: Pipe = groupedPipeOf(name, maybeProjectedPipe)
        // Time to schedule the Every operations
        evs.foldRight(start) { (op: (Pipe => Every), p) => op(p) }

      case IdentityMode =>
        //This is the case where the group function is identity: { g => g }
        groupedPipeOf(name, pipe)

      case AggregateByMode =>
        //There is some non-empty AggregateBy to do:
        val redlist = reds.get
        val ag = new AggregateBy(name,
          maybeProjectedPipe,
          groupFields,
          spillThreshold.getOrElse(0), // cascading considers 0 to be the default
          redlist.reverse.toArray: _*)

        overrideReducers(ag.getGroupBy())
        overrideDescription(ag.getGroupBy())
        ag
    }
  }

  /**
   * This invalidates aggregateBy!
   */
  def sortBy(f: Fields): GroupBuilder = {
    reds = None
    val sort = sortF match {
      case None => f
      case Some(sf) => {
        sf.append(f)
        sf
      }
    }
    sortF = Some(sort)
    // Update projectFields
    projectFields = projectFields.map { Fields.merge(_, sort) }
    this
  }

  /**
   * This is convenience method to allow plugging in blocks
   * of group operations similar to `RichPipe.thenDo`
   */
  def thenDo(fn: (GroupBuilder) => GroupBuilder) = fn(this)

  /**
   * An identity function that keeps all the tuples. A hack to implement
   * groupAll and groupRandomly.
   */
  def pass: GroupBuilder = takeWhile(0) { (t: TupleEntry) => true }

  /**
   * beginning of block with access to expensive nonserializable state. The state object should
   * contain a function release() for resource management purpose.
   */
  def using[C <: { def release(): Unit }](bf: => C) = new {

    /**
     * mapStream with state.
     */
    def mapStream[T, X](fieldDef: (Fields, Fields))(mapfn: (C, Iterator[T]) => TraversableOnce[X])(implicit conv: TupleConverter[T], setter: TupleSetter[X]) = {
      val (inFields, outFields) = fieldDef
      //Check arity
      conv.assertArityMatches(inFields)
      setter.assertArityMatches(outFields)

      val b = new SideEffectBufferOp[Unit, T, C, X](
        (), bf,
        (u: Unit, c: C, it: Iterator[T]) => mapfn(c, it),
        new Function1[C, Unit] with java.io.Serializable { def apply(c: C): Unit = { c.release() } },
        outFields, conv, setter)
      every(pipe => new Every(pipe, inFields, b, defaultMode(inFields, outFields)))
    }
  }

}

/**
 * Scala 2.8 Iterators don't support scanLeft so we have to reimplement
 * The Scala 2.9 implementation creates an off-by-one bug with the unused fields in the Fields API
 */
class ScanLeftIterator[T, U](it: Iterator[T], init: U, fn: (U, T) => U) extends Iterator[U] with java.io.Serializable {
  protected var prev: Option[U] = None
  def hasNext: Boolean = { prev.isEmpty || it.hasNext }
  // Don't use pattern matching in a performance-critical section
  @SuppressWarnings(Array("org.brianmckenna.wartremover.warts.OptionPartial"))
  def next = {
    prev = prev.map { fn(_, it.next) }
      .orElse(Some(init))
    prev.get
  }
}

sealed private[scalding] abstract class GroupMode
private[scalding] case object AggregateByMode extends GroupMode
private[scalding] case object GroupByMode extends GroupMode
private[scalding] case object IdentityMode extends GroupMode


text:
/**
 * angular-switchery v1.0.0
 * Natan Santolo <natan.santolo@gmail.com>
 * License: MIT
 */
(function(window, angular, undefined) {

    'use strict';

    if (!angular) {
        throw('angular-switchery: AngularJS not found.');
    }

    window.requestAnimFrame = (function() {
        return window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(callback, element) {
                window.setTimeout(callback, 1000 / 60);
            };
    })();

    angular
        .module('angular.switchery', [])
        .directive('ngSwitchery', ['$timeout', '$parse',
            function switcheryDirective($timeout, $parse) {
                return {
                    'require': 'ngModel',
                    'restrict': 'AE',
                    'scope': {
                        'checked': '=ngModel'
                    },
                    'link': function switcheryLink($scope, $element, $attrs, ngModel) {
                        if (!ngModel) {
                            return false;
                        }
                        // switch instance
                        var _switch;
                        // switcher options
                        var options = ($attrs && $attrs.ngSwitchery) ? $parse($attrs.ngSwitchery)($scope) : {};
                        // switcher render function
                        function renderSwitch() {
                            window.requestAnimFrame(drawSwitch);
                        }
                        // switcher draw function
                        function drawSwitch() {
                            // if needed create new instance
                            if (!_switch) {
                                _switch = new window.Switchery($element[0], options);
                                // console.log('switcher created with options', options);
                            }
                            // save model state
                            _switch.element.checked = $scope.checked;
                            // reset handler
                            _switch.element.onchange = null;
                            // set switcher position
                            _switch.setPosition(false);
                            // when switcher change
                            _switch.element.onchange = function() {
                                $scope.$apply(function() {
                                    // update the model
                                    ngModel.$setViewValue(_switch.element.checked);
                                });
                            };
                        }
                        // when the model changes, render switcher
                        $scope.$watch('checked', function(state, oldState) {
                            if (state !== oldState) {
                                renderSwitch();
                            }
                        });
                        // render switch
                        renderSwitch();
                    }
                };
            }
        ]);

})(window, window.angular);

redpajama_set_name: RedPajamaGithub


text:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import api from '../middleware/api';
import rootReducer from '../reducers';

export default function configureStore(initialState) {
  return createStore(
    rootReducer,
    initialState,
    applyMiddleware(thunk, api)
  );
}


text:
from vt_manager_kvm.communication.sfa.util.xrn import hrn_to_urn
from vt_manager_kvm.communication.sfa.rspecs.rspec import RSpec
from vt_manager_kvm.communication.sfa.rspecs.version_manager import VersionManager

class SfaRSpecConverter:

    @staticmethod
    def to_pg_rspec(rspec, content_type = None):
        if not isinstance(rspec, RSpec):
            sfa_rspec = RSpec(rspec)
        else:
            sfa_rspec = rspec

        if not content_type or content_type not in \
          ['ad', 'request', 'manifest']:
            content_type = sfa_rspec.version.content_type

        version_manager = VersionManager()
        pg_version = version_manager._get_version('protogeni', '2', 'request')
        pg_rspec = RSpec(version=pg_version)

        # get networks
        networks = sfa_rspec.version.get_networks()

        for network in networks:
            # get nodes
            sfa_node_elements = sfa_rspec.version.get_node_elements(network=network)
            for sfa_node_element in sfa_node_elements:
                # create node element
                node_attrs = {}
                node_attrs['exclusive'] = 'false'
                if 'component_manager_id' in sfa_node_element.attrib:
                    node_attrs['component_manager_id'] = sfa_node_element.attrib['component_manager_id']
                else:
                    node_attrs['component_manager_id'] = hrn_to_urn(network, 'authority+cm')

                if 'component_id' in sfa_node_element.attrib:
                    node_attrs['compoenent_id'] = sfa_node_element.attrib['component_id']

                if sfa_node_element.find('hostname') != None:
                    hostname = sfa_node_element.find('hostname').text
                    node_attrs['component_name'] = hostname
                    node_attrs['client_id'] = hostname
                node_element = pg_rspec.xml.add_element('node', node_attrs)

                if content_type == 'request':
                    sliver_element = sfa_node_element.find('sliver')
                    sliver_type_elements = sfa_node_element.xpath('./sliver_type', namespaces=sfa_rspec.namespaces)
                    available_sliver_types = [element.attrib['name'] for element in sliver_type_elements]
                    valid_sliver_types = ['emulab-openvz', 'raw-pc']

                    # determine sliver type
                    requested_sliver_type = 'emulab-openvz'
                    for available_sliver_type in available_sliver_types:
                        if available_sliver_type in valid_sliver_types:
                            requested_sliver_type = available_sliver_type

                    if sliver_element != None:
                        pg_rspec.xml.add_element('sliver_type', {'name': requested_sliver_type}, parent=node_element)
                else:
                    # create node_type element
                    for hw_type in ['plab-pc', 'pc']:
                        hdware_type_element = pg_rspec.xml.add_element('hardware_type', {'name': hw_type}, parent=node_element)
                    # create available element
                    pg_rspec.xml.add_element('available', {'now': 'true'}, parent=node_element)
                    # create locaiton element
                    # We don't actually associate nodes with a country.
                    # Set country to "unknown" until we figure out how to make
                    # sure this value is always accurate.
                    location = sfa_node_element.find('location')
                    if location != None:
                        location_attrs = {}
                        location_attrs['country'] =  location.get('country', 'unknown')
                        location_attrs['latitude'] = location.get('latitude', 'None')
                        location_attrs['longitude'] = location.get('longitude', 'None')
                        pg_rspec.xml.add_element('location', location_attrs, parent=node_element)

        return pg_rspec.toxml()

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        print SfaRSpecConverter.to_pg_rspec(sys.argv[1])


text:
task GenerateMarkdown {
    $module = Import-Module -FullyQualifiedName $ManifestPath -Force -PassThru

    try
    {
        if ($module.ExportedFunctions.Count -eq 0)
        {
            'No functions have been exported for this module. Skipping Markdown generation...'
            return
        }

        if (Get-ChildItem -Path $DocsPath -Filter '*.md' -Recurse)
        {
            $items = Get-ChildItem -Path $DocsPath -Directory -Recurse
            foreach ($item in $items)
            {
                "Updating Markdown help in [$($item.BaseName)]..."
                $null = Update-MarkdownHelp -Path $item.FullName -AlphabeticParamsOrder
            }
        }

        $params = @{
            AlphabeticParamsOrder  = $true
            ErrorAction           = 'SilentlyContinue'
            Locale                = 'en-US'
            Module                = $ModuleName
            OutputFolder          = "$DocsPath\en-US"
            WithModulePage        = $true
        }

        # ErrorAction is set to SilentlyContinue so this
        # command will not overwrite an existing Markdown file.
        "Creating new Markdown help for [$ModuleName]..."
        $null = New-MarkdownHelp @params
    }
    finally
    {
        Remove-Module -Name $ModuleName -Force
    }
}


text:
var EventEmitter = require('events').EventEmitter;

var HistoryManager = function() {
  EventEmitter.call(this);

  this._tracks = [];
};

HistoryManager.prototype = Object.create(EventEmitter.prototype);
HistoryManager.constructor = HistoryManager;

Object.defineProperty(HistoryManager.prototype, 'tracks', {
  enumerable: true,
  configurable: false,
  get: function() {
    return this._tracks;
  }
});

HistoryManager.prototype.add = function(track) {
  if (!this._hasTrack(track)) {
    this._tracks.push(track);
    this.emit('history-updated', this._tracks);
  }
};

HistoryManager.prototype.remove = function(track) {
  if (this._hasTrack(track)) {
    var index = this._getTrackIndex(track);
    this._tracks.splice(index, 1);
    this.emit('history-updated', this._tracks);
  }
};

HistoryManager.prototype.clean = function() {
  this._tracks = [];
  this.emit('history-updated', this._tracks);
};

HistoryManager.prototype._hasTrack = function(track) {
  var index = this._getTrackIndex(track);
  return index !== -1;
};

HistoryManager.prototype._getTrackIndex = function(track) {
  return this._tracks.indexOf(track);
};

module.exports = new HistoryManager();


text:
<html>

<head>
  <base href="/">

  <title>Angular 2 QuickStart</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="styles.css">
  <link rel="stylesheet" href="node_modules/primeui/themes/delta/theme.css">
  <link rel="stylesheet" type="text/css" href="app/resources/icons/css/font-awesome.min.css" />
  <link rel="stylesheet" href="node_modules/primeui/primeui-ng-all.min.css">

  <!-- 1. Load libraries -->
  <!-- IE required polyfills, in this exact order -->
  <script src="lib/es6-shim.min.js"></script>
  <script src="lib/system-polyfills.js"></script>
  <script src="lib/shims_for_IE.js"></script>

  <script src="lib/angular2-polyfills.js"></script>
  <script src="lib/system.src.js"></script>

  <script src="lib/primeui-ng-all.min.js"></script>

  <!-- 2. Configure SystemJS -->
  <script>
    System.config({
        packages: {
          app: {
//            format: 'register',
            defaultExtension: 'js'
          },
          primeng: {
            defaultExtension: 'js'
          },
          angular2: {
            defaultExtension: false
          }
        },
        map: {
            'primeng': 'lib/primeng',
            //'angular2': 'lib/angular2'
        }
      });
      System.import('app/main')
            .then(null, console.error.bind(console));
  </script>

    <script src="lib/Rx.js"></script>
    <script src="lib/angular2.dev.js"></script>
    <script src="lib/router.dev.js"></script>
    <script src="lib/http.dev.js"></script>
</head>

<!-- 3. Display the application -->

<body>
  <my-app>Loading...</my-app>
</body>

</html>


text:
package cache

import (
	"go.ligato.io/cn-infra/v2/logging"

	controller "github.com/contiv/vpp/plugins/controller/api"
	nsmodel "github.com/contiv/vpp/plugins/ksr/model/namespace"
	podmodel "github.com/contiv/vpp/plugins/ksr/model/pod"
	policymodel "github.com/contiv/vpp/plugins/ksr/model/policy"
	"github.com/contiv/vpp/plugins/policy/cache/namespaceidx"
	"github.com/contiv/vpp/plugins/policy/cache/podidx"
	"github.com/contiv/vpp/plugins/policy/cache/policyidx"
	"github.com/contiv/vpp/plugins/policy/utils"
)

// PolicyCache s used for a in-memory storage of K8s State data with fast
// lookups using idxmap-s.
// The cache processes K8s State data updates and RESYNC events through Update()
// and Resync() APIs, respectively.
// The cache allows to get notified about changes via convenient callbacks.
// A watcher needs to implement the interface PolicyCacheWatcher and subscribe
// for watching using Watch() API.
// The cache provides various fast lookup methods (e.g. by the label selector).
type PolicyCache struct {
	Deps

	configuredPolicies   *policyidx.ConfigIndex
	configuredPods       *podidx.ConfigIndex
	configuredNamespaces *namespaceidx.ConfigIndex
	watchers             []PolicyCacheWatcher
}

// Deps lists dependencies of PolicyCache.
type Deps struct {
	Log logging.Logger
}

// Init initializes policy cache.
func (pc *PolicyCache) Init() error {
	pc.reset()

	pc.watchers = []PolicyCacheWatcher{}
	return nil
}

// reset resets the cache to empty content.
func (pc *PolicyCache) reset() {
	pc.configuredPolicies = policyidx.NewConfigIndex(pc.Log, "policies")
	pc.configuredPods = podidx.NewConfigIndex(pc.Log, "pods")
	pc.configuredNamespaces = namespaceidx.NewConfigIndex(pc.Log, "namespaces")
}

// Update processes a K8s state data change event.
// The change is applied into the cache and all subscribed watchers are
// notified.
// The function will forward any error returned by a watcher.
func (pc *PolicyCache) Update(kubeStateChange *controller.KubeStateChange) error {
	return pc.changePropagateEvent(kubeStateChange)
}

// Resync processes a K8s state data resync event.
// The cache content is full replaced with the received data and all
// subscribed watchers are notified.
// The function will forward any error returned by a watcher.
func (pc *PolicyCache) Resync(kubeStateData controller.KubeStateData) error {
	dataResyncEvent := pc.resyncParseEvent(kubeStateData)

	for _, watcher := range pc.watchers {
		watcher.Resync(dataResyncEvent)
	}

	return nil
}

// Watch subscribes a new watcher.
func (pc *PolicyCache) Watch(watcher PolicyCacheWatcher) error {
	pc.watchers = append(pc.watchers, watcher)
	return nil
}

// LookupPod returns data of a given Pod.
func (pc *PolicyCache) LookupPod(pod podmodel.ID) (found bool, data *podmodel.Pod) {
	return pc.configuredPods.LookupPod(pod.String())
}

// LookupPodsByLabelSelectorInsideNs evaluates pod label selectors in a namespace and returns IDs of matching pods.
func (pc *PolicyCache) LookupPodsByLabelSelectorInsideNs(policyNamespace string,
	podLabelSelector *policymodel.Policy_LabelSelector) (pods []podmodel.ID) {

	// An empty podSelector matches all pods in this namespace.
	if len(podLabelSelector.MatchExpression) == 0 && len(podLabelSelector.MatchLabel) == 0 {
		pods := pc.configuredPods.LookupPodsByNamespace(policyNamespace)
		pc.Log.WithField("LookupPodsByNSLabelSelector", policyNamespace).
			Infof("Empty PodSelector returning pods: %+v", pods)
		return utils.UnstringPodID(pods)
	}

	// List of match labels and match expressions.
	matchLabels := podLabelSelector.MatchLabel
	matchExpressions := podLabelSelector.MatchExpression

	// Get matching pods for policy's pod label selectors
	mlPods := pc.getMatchLabelPodsInsideNs(policyNamespace, matchLabels)
	mePods := pc.getMatchExpressionPodsInsideNs(policyNamespace, matchExpressions)

	// If both pod labels and expressions exist,
	// we need to find the intersection of the returning pods
	// Requirements are AND'ed
	if len(matchLabels) > 0 && len(matchExpressions) > 0 {
		return utils.UnstringPodID(utils.Intersect(mlPods, mePods))
	}
	if len(matchLabels) > 0 {
		return utils.UnstringPodID(mlPods)
	}
	return utils.UnstringPodID(mePods)
}

// LookupPodsByNsLabelSelector evaluates namespace label selector and returns IDs of pods in the matched namespaces.
func (pc *PolicyCache) LookupPodsByNsLabelSelector(
	namespaceLabelSelector *policymodel.Policy_LabelSelector) (pods []podmodel.ID) {
	// An empty namespace selector matches all namespaces.
	if len(namespaceLabelSelector.MatchExpression) == 0 && len(namespaceLabelSelector.MatchLabel) == 0 {
		allPods := pc.configuredPods.ListAll()
		kubeSystemPods := pc.configuredPods.LookupPodsByNamespace("kube-system")
		// Excluding "kube-system" pods
		pods := utils.Difference(allPods, kubeSystemPods)

		pc.Log.WithField("LookupPodsByNSLabelSelector", namespaceLabelSelector).
			Infof("Empty namespace selector returning pods: %+v", pods)
		return utils.UnstringPodID(pods)
	}

	// List of match labels and match expressions.
	matchNsLabels := namespaceLabelSelector.MatchLabel
	matchNsExpressions := namespaceLabelSelector.MatchExpression

	// Get matching pods for policy's namespace label selectors
	mlPods := pc.getPodsByNsLabelSelector(matchNsLabels)
	mePods := pc.getPodsByNsMatchExpression(matchNsExpressions)

	// If both namespace labels and expressions exist,
	// we need to find the intersection of the returning pods
	// Requirements are AND'ed
	if len(matchNsLabels) > 0 && len(matchNsExpressions) > 0 {
		return utils.UnstringPodID(utils.Intersect(mlPods, mePods))
	}
	if len(matchNsLabels) > 0 {
		return utils.UnstringPodID(mlPods)
	}
	return utils.UnstringPodID(mePods)

}

// LookupPodsByNamespace returns IDs of all pods inside a given namespace.
func (pc *PolicyCache) LookupPodsByNamespace(namespace string) (pods []podmodel.ID) {
	podsByNamespace := pc.configuredPods.LookupPodsByNamespace(namespace)
	pods = utils.UnstringPodID(podsByNamespace)

	return pods
}

// ListAllPods returns the IDs of all known pods.
func (pc *PolicyCache) ListAllPods() (pods []podmodel.ID) {
	allPods := pc.configuredPods.ListAll()
	pods = utils.UnstringPodID(allPods)

	return pods
}

// LookupPolicy returns the data of a given Policy.
func (pc *PolicyCache) LookupPolicy(policy policymodel.ID) (found bool, data *policymodel.Policy) {
	found, data = pc.configuredPolicies.LookupPolicy(policy.String())
	if !found {
		return found, nil
	}
	return found, data
}

// LookupPoliciesByPod returns the IDs of all policies assigned to a given pod.
func (pc *PolicyCache) LookupPoliciesByPod(pod podmodel.ID) (policyIDs []policymodel.ID) {
	policyIDs = []policymodel.ID{}
	policyData := []*policymodel.Policy{}

	// Get and store the data from all the policies in cache.
	policies := pc.ListAllPolicies()
	for _, policy := range policies {
		found, data := pc.LookupPolicy(policy)
		if !found {
			continue
		}
		policyData = append(policyData, data)
	}

	// For every policy data if podID matches any of policy's attached pods
	// save and return the policyID
	for _, pData := range policyData {
		podIDs := pc.LookupPodsByLabelSelectorInsideNs(pData.Namespace, pData.Pods)
		for _, podID := range podIDs {
			if podID == pod {
				policyID := policymodel.GetID(pData)
				policyIDs = append(policyIDs, policyID)
			}
		}
	}

	return policyIDs
}

// ListAllPolicies returns IDs of all policies.
func (pc *PolicyCache) ListAllPolicies() (policyIDs []policymodel.ID) {
	allPolicies := pc.configuredPolicies.ListAll()
	policyIDs = utils.UnstringPolicyID(allPolicies)

	return policyIDs
}

// LookupNamespace returns data of a given namespace.
func (pc *PolicyCache) LookupNamespace(namespace nsmodel.ID) (found bool, data *nsmodel.Namespace) {
	found, data = pc.configuredNamespaces.LookupNamespace(namespace.String())

	if !found {
		return found, nil
	}

	return found, data
}

// ListAllNamespaces returns IDs of all known namespaces.
func (pc *PolicyCache) ListAllNamespaces() (namespaces []nsmodel.ID) {
	allNamespaces := pc.configuredNamespaces.ListAll()
	namespaces = utils.UnstringNamespaceID(allNamespaces)

	return namespaces
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">

        <link rel="stylesheet" href="/fe/node_modules/bootstrap/dist/css/bootstrap.css">
        <link rel="stylesheet" href="//cdn.bootcss.com/ionic/1.3.2/css/ionic.css">
        <link rel="stylesheet" href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
        <link rel="stylesheet/less" rel="stylesheet" href="/fe/less/main.less">
        <link rel='icon' href='favicon.ico' type='image/x-icon'/>


text:
JRuby::Rack::RailsBooter.run_boot_hooks!

require 'jruby/rack/rack_ext'

require 'action_controller'

module ActionController
  class Base
    def servlet_request
      request.env['java.servlet_request']
    end

    def forward_to(url)
      request.forward_to(url)
    end
  end
end


text:
package org.gdg.subscriber;

import org.gdg.livenotifiers.EmailNotifier;
import org.gdg.livenotifiers.LiveFeedChannel;
import org.gdg.publisher.IPublisher;
import org.gdg.publisher.Message;

public class LiveFileChangeNotifier implements ISubscriber {

	IPublisher publisher;

	public LiveFileChangeNotifier(IPublisher publisher)
	{
		this.publisher = publisher;
		publisher.attach(this);
	}

	@Override
	public void update(Message message) {

		LiveFeedChannel.sendUpdateToUser(message);
		EmailNotifier.sendUpdate(message, "satendrasarvagya@gmail.com");

	}

}


text:
package io.aos.antlr4;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.atn.PredictionMode;

import javax.print.PrintException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/** Run a lexer/parser combo, optionally printing tree string or generating
 *  postscript file. Optionally taking input file.
 *
 *  $ java org.antlr.v4.runtime.misc.TestRig GrammarName startRuleName
 *        [-tree]
 *        [-tokens] [-gui] [-ps file.ps]
 *        [-trace]
 *        [-diagnostics]
 *        [-SLL]
 *        [input-filename(s)]
 */
public class RigMain {
    public static final String LEXER_START_RULE_NAME = "tokens";

    protected String grammarName;
    protected String startRuleName;
    protected final List<String> inputFiles = new ArrayList<String>();
    protected boolean printTree = false;
    protected boolean gui = false;
    protected String psFile = null;
    protected boolean showTokens = false;
    protected boolean trace = false;
    protected boolean diagnostics = false;
    protected String encoding = null;
    protected boolean SLL = false;

    public RigMain(String[] args) throws Exception {

        args = new String[]{"simple1.Simple1", "prog", "-tree", "-gui", "-tokens"};
        // type 100+2*34, then ^D

        if ( args.length < 2 ) {
            System.err.println("java org.antlr.v4.runtime.misc.TestRig GrammarName startRuleName\n" +
                               "  [-tokens] [-tree] [-gui] [-ps file.ps] [-encoding encodingname]\n" +
                               "  [-trace] [-diagnostics] [-SLL]\n"+
                               "  [input-filename(s)]");
            System.err.println("Use startRuleName='tokens' if GrammarName is a lexer grammar.");
            System.err.println("Omitting input-filename makes rig read from stdin.");
            return;
        }
        int i=0;
        grammarName = args[i];
        i++;
        startRuleName = args[i];
        i++;
        while ( i<args.length ) {
            String arg = args[i];
            i++;
            if ( arg.charAt(0)!='-' ) { // input file name
                inputFiles.add(arg);
                continue;
            }
            if ( arg.equals("-tree") ) {
                printTree = true;
            }
            if ( arg.equals("-gui") ) {
                gui = true;
            }
            if ( arg.equals("-tokens") ) {
                showTokens = true;
            }
            else if ( arg.equals("-trace") ) {
                trace = true;
            }
            else if ( arg.equals("-SLL") ) {
                SLL = true;
            }
            else if ( arg.equals("-diagnostics") ) {
                diagnostics = true;
            }
            else if ( arg.equals("-encoding") ) {
                if ( i>=args.length ) {
                    System.err.println("missing encoding on -encoding");
                    return;
                }
                encoding = args[i];
                i++;
            }
            else if ( arg.equals("-ps") ) {
                if ( i>=args.length ) {
                    System.err.println("missing filename on -ps");
                    return;
                }
                psFile = args[i];
                i++;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        RigMain testRig = new RigMain(args);
        if(args.length >= 2) {
            testRig.process();
        }
    }

    public void process() throws Exception {
//      System.out.println("exec "+grammarName+"."+startRuleName);
        String lexerName = grammarName+"Lexer";
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Class<? extends Lexer> lexerClass = null;
        try {
            lexerClass = cl.loadClass(lexerName).asSubclass(Lexer.class);
        }
        catch (java.lang.ClassNotFoundException cnfe) {
            // might be pure lexer grammar; no Lexer suffix then
            lexerName = grammarName;
            try {
                lexerClass = cl.loadClass(lexerName).asSubclass(Lexer.class);
            }
            catch (ClassNotFoundException cnfe2) {
                System.err.println("Can't load "+lexerName+" as lexer or parser");
                return;
            }
        }

        Constructor<? extends Lexer> lexerCtor = lexerClass.getConstructor(CharStream.class);
        Lexer lexer = lexerCtor.newInstance((CharStream)null);

        Class<? extends Parser> parserClass = null;
        Parser parser = null;
        if ( !startRuleName.equals(LEXER_START_RULE_NAME) ) {
            String parserName = grammarName+"Parser";
            parserClass = cl.loadClass(parserName).asSubclass(Parser.class);
            if ( parserClass==null ) {
                System.err.println("Can't load "+parserName);
            }
            Constructor<? extends Parser> parserCtor = parserClass.getConstructor(TokenStream.class);
            parser = parserCtor.newInstance((TokenStream)null);
        }

        if ( inputFiles.size()==0 ) {
            InputStream is = System.in;
            Reader r;
            if ( encoding!=null ) {
                r = new InputStreamReader(is, encoding);
            }
            else {
                r = new InputStreamReader(is);
            }

            process(lexer, parserClass, parser, is, r);
            return;
        }
        for (String inputFile : inputFiles) {
            InputStream is = System.in;
            if ( inputFile!=null ) {
                is = new FileInputStream(inputFile);
            }
            Reader r;
            if ( encoding!=null ) {
                r = new InputStreamReader(is, encoding);
            }
            else {
                r = new InputStreamReader(is);
            }

            if ( inputFiles.size()>1 ) {
                System.err.println(inputFile);
            }
            process(lexer, parserClass, parser, is, r);
        }
    }

    protected void process(Lexer lexer, Class<? extends Parser> parserClass, Parser parser, InputStream is, Reader r) throws IOException, IllegalAccessException, InvocationTargetException, PrintException {
        try {
            ANTLRInputStream input = new ANTLRInputStream(r);
            lexer.setInputStream(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);

            tokens.fill();

            if ( showTokens ) {
                for (Object tok : tokens.getTokens()) {
                    System.out.println(tok);
                }
            }

            if ( startRuleName.equals(LEXER_START_RULE_NAME) ) return;

            if ( diagnostics ) {
                parser.addErrorListener(new DiagnosticErrorListener());
                parser.getInterpreter().setPredictionMode(PredictionMode.LL_EXACT_AMBIG_DETECTION);
            }

            if ( printTree || gui || psFile!=null ) {
                parser.setBuildParseTree(true);
            }

            if ( SLL ) { // overrides diagnostics
                parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
            }

            parser.setTokenStream(tokens);
            parser.setTrace(trace);

            try {
                Method startRule = parserClass.getMethod(startRuleName);
                ParserRuleContext tree = (ParserRuleContext) startRule.invoke(parser, (Object[])null);

                if ( printTree ) {
                    System.out.println(tree.toStringTree(parser));
                }
                if ( gui ) {
                    tree.inspect(parser);
                }
                if ( psFile!=null ) {
                    tree.save(parser, psFile); // Generate postscript
                }
            }
            catch (NoSuchMethodException nsme) {
                System.err.println("No method for rule "+startRuleName+" or it has arguments");
            }
        }
        finally {
            if ( r!=null ) r.close();
            if ( is!=null ) is.close();
        }
    }
}


text:
package org.apache.flink.graph.types.valuearray;

import org.apache.flink.api.common.typeutils.ComparatorTestBase;
import org.apache.flink.api.common.typeutils.TypeComparator;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.types.DoubleValue;

/** Tests for {@link DoubleValueArrayComparator}. */
public class DoubleValueArrayComparatorTest extends ComparatorTestBase<DoubleValueArray> {

    @Override
    protected TypeComparator<DoubleValueArray> createComparator(boolean ascending) {
        return new DoubleValueArrayComparator(ascending);
    }

    @Override
    protected TypeSerializer<DoubleValueArray> createSerializer() {
        return new DoubleValueArraySerializer();
    }

    @Override
    protected DoubleValueArray[] getSortedTestData() {
        DoubleValueArray lva0 = new DoubleValueArray();

        DoubleValueArray lva1 = new DoubleValueArray();
        lva1.add(new DoubleValue(5));

        DoubleValueArray lva2 = new DoubleValueArray();
        lva2.add(new DoubleValue(5));
        lva2.add(new DoubleValue(10));

        return new DoubleValueArray[] {lva0, lva1};
    }
}


text:
import maxlength from '../../../src/js/components/validation/maxlength'

describe('validation:maxlength', () => {
  it('should return true if the field has maxlength lower than the required', () => {
    let field = {
      value: 'foo',
      getAttribute: () => 4
    }

    expect(maxlength(field)).to.be.true
  })

  it('should return true if the field has maxlength equal than the required', () => {
    let field = {
      value: 'foo',
      getAttribute: () => 3
    }

    expect(maxlength(field)).to.be.true
  })

  it('should return false if the field has maxlength greater than the required', () => {
    let field = {
      value: 'foo',
      getAttribute: () => 2
    }

    expect(maxlength(field)).to.be.false
  })
})


text:
package com.taobao.tddl.group.exception;

import java.sql.SQLException;

/**
 * 当一组的数据库都试过,都不可用了,并且没有更多的数据源了,抛出该错误
 *
 * @author linxuan
 */
public class NoMoreDataSourceException extends SQLException {

    private static final long serialVersionUID = 1L;

    public NoMoreDataSourceException(String reason){
        super(reason
              + "\nPlease grep 'createSQLException' or 'createCommunicationsException' or 'time out' to find real causes."
              + " And you can reference " + "'http://baike.corp.taobao.com/index.php/TDDL_FAQ'");
    }

}


text:
package filters

import (
	"github.com/karlseguin/gspec"
	"testing"
)

func TestReturnsTheLastItem(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	spec.Expect(filter([]string{"leto", "atreides"}, nil).(string)).ToEqual("atreides")
}

func TestReturnsTheLastItemIfOnlyOneItem(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	spec.Expect(filter([]string{"leto"}, nil).(string)).ToEqual("leto")
}

func TestReturnsTheLastItemOfAnArray(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	arr := [4]int{1, 2, 3, 48}
	spec.Expect(filter(arr, nil).(int)).ToEqual(48)
}

func TestLastPassthroughOnEmptyArray(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	arr := [0]int{}
	spec.Expect(filter(arr, nil).([0]int)).ToEqual(arr)
}

func TestLastPassthroughOnEmptySlice(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	arr := []int{}
	spec.Expect(len(filter(arr, nil).([]int))).ToEqual(0)
}

func TestLastPassthroughOnInvalidType(t *testing.T) {
	spec := gspec.New(t)
	filter := LastFactory(nil)
	spec.Expect(filter("hahah", nil).(string)).ToEqual("hahah")
}


text:
from agescx.enums.eCondition import *

class Condition:

    """Initialize Condition

    Attributes:
        conditionType (int): type of condition
        check (int): is checked ? (always)
        resource (int): resource type
        amount (int): amount of resource
        unitObject (int): unit object
        unitId (int): id of unit
        unitName (int): name of unit
        sourcePlayer (int): affected player
        tech (int): is tech discovered ?
        timer (int): how much time
        unknown1 (int): unknown1
        x1 (int): selected area start X position
        y1 (int): selected area start Y position
        x2 (int): selected area end X position
        y2 (int): selected area end Y position
        aiSinal (int): check signal from ai
    """

    def __init__(self, type=0, check=0x10,
                 amount=0, resource=0, unitObject=0,
                 unitId=0, unitName=0, sourcePlayer=0,
                 tech=0, timer=0, unknown1=0,
                 x1=0, y1=0, x2=0, y2=0,
                 unitGroup=0, unitType=0, aiSignal=0
                 ):
        self.type = type  # condition type
        self.check = check
        self.amount = amount
        self.resource = resource
        self.unitObject = unitObject
        self.unitId = unitId
        self.unitName = unitName
        self.sourcePlayer = sourcePlayer
        self.tech = tech
        self.timer = timer
        self.unknown1 = unknown1
        self.x1, self.y1 = x1, y1
        self.x2, self.y2 = x2, y2
        self.unitGroup = unitGroup
        self.unitType = unitType
        self.aiSignal = aiSignal

    def __repr__(self):
        name = "CONDITION:\n"
        info1 = "\tTYPE:{} - {}".format(self.type, eCondition[self.type])
        return name + info1

    def toJSON(self):
        """return JSON"""
        data = dict()
        data["type"] = self.type
        data["check"] = self.check
        data["amount"] = self.amount
        data["resource"] = self.resource
        data["unitObject"] = self.unitObject
        data["unitId"] = self.unitId
        data["unitName"] = self.unitName
        data["sourcePlayer"] = self.sourcePlayer
        data["tech"] = self.tech
        data["timer"] = self.timer
        data["x1"] = self.x1
        data["y1"] = self.y1
        data["x2"] = self.x2
        data["y2"] = self.y2
        data["unitGroup"] = self.unitGroup
        data["unitType"] = self.unitType
        data["aiSignal"] = self.aiSignal
        return data


text:
package com.kimjio.dgsw.hs.activity.timetable;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

import com.kimjio.dgsw.hs.R;

/**
 * Created by whdghks913 on 2015-12-10.
 */
public class TimeTableAdapter extends RecyclerView.Adapter<TimeTableAdapter.TimeTableViewHolder> {
//    private int mBackground;
    private ArrayList<TimeTableInfo> mValues = new ArrayList<>();

    public TimeTableAdapter(Context mContext) {
//        TypedValue mTypedValue = new TypedValue();
//        mContext.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
//        mBackground = mTypedValue.resourceId;
    }

    public void addItem(int time, String name, String room) {
        TimeTableInfo addInfo = new TimeTableInfo();

        addInfo.time = time;
        addInfo.name = name;
        addInfo.room = room;

        mValues.add(addInfo);
    }

    @Override
    public TimeTableAdapter.TimeTableViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_timetable_item, parent, false);
//        mView.setBackgroundResource(mBackground);

        return new TimeTableViewHolder(mView);
    }

    @Override
    public void onBindViewHolder(final TimeTableViewHolder holder, int position) {
        TimeTableInfo mInfo = getItemData(position);

        holder.mTimeText.setText(String.valueOf(mInfo.time));
        holder.mTimeName.setText(mInfo.name);
        holder.mRoom.setText(mInfo.room);
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public TimeTableInfo getItemData(int position) {
        return mValues.get(position);
    }

    public class TimeTableViewHolder extends RecyclerView.ViewHolder {
        //        public final View mView;
        public final TextView mTimeText, mTimeName, mRoom;

        public TimeTableViewHolder(View mView) {
            super(mView);
//            this.mView = mView;

            mTimeText = (TextView) mView.findViewById(R.id.mTimeText);
            mTimeName = (TextView) mView.findViewById(R.id.mTimeName);
            mRoom = (TextView) mView.findViewById(R.id.mRoom);
        }
    }

    public class TimeTableInfo {
        public int time;
        public String name;
        public String room;
    }
}


text:
package dagger.functional;

import static com.google.common.truth.Truth.assertThat;

import dagger.functional.ComponentWithReusableBindings.ChildOne;
import dagger.functional.ComponentWithReusableBindings.ChildTwo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class ReusableTest {
  @Test
  public void testReusable() {
    ComponentWithReusableBindings parent = DaggerComponentWithReusableBindings.create();
    ChildOne childOne = parent.childOne();
    ChildTwo childTwo = parent.childTwo();

    Object reusableInParent = parent.reusableInParent();
    assertThat(parent.reusableInParent()).isSameAs(reusableInParent);
    assertThat(childOne.reusableInParent()).isSameAs(reusableInParent);
    assertThat(childTwo.reusableInParent()).isSameAs(reusableInParent);

    Object reusableFromChildOne = childOne.reusableInChild();
    assertThat(childOne.reusableInChild()).isSameAs(reusableFromChildOne);

    Object reusableFromChildTwo = childTwo.reusableInChild();
    assertThat(childTwo.reusableInChild()).isSameAs(reusableFromChildTwo);

    assertThat(reusableFromChildTwo).isNotSameAs(reusableFromChildOne);
  }
}


text:
<!DOCTYPE html>

    <title>Conditions of sales | ICPIAF</title>
    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="ICPIAF – INSTITUT DE CERCETARE SI PRODUCTIE PENTRU INDUSTRIA ALIMENTARA SI FRIG">
    <meta name="author" content="Daniel Codrea">

    <link rel="shortcut icon" href="assets/img/favicon.ico" type="image/x-icon">

    <link rel="stylesheet" href="assets/css/bootstrap.min.css">

    <link href="assets/css/bootstrap-theme.min.css" rel="stylesheet">

    <link rel="stylesheet" href="assets/css/font-awesome.min.css" type="text/css" media="screen">

    <link rel="stylesheet" href="assets/css/simple-line-icons.css" type="text/css" media="screen">

    <link rel="stylesheet" href="assets/css/flaticon.css" type="text/css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/settings.css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/theme.css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/responsive.css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/animate.css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/slicknav.css" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/river.css" title="river" media="screen">

    <link rel="stylesheet" type="text/css" href="assets/css/tipuesearch.css" media="screen">

               office@icpiaf.ro

              +40 (264) 435232; +40 (746) 033377

              Fax: +40 (264) 435245

              Fabricii de Chibrituri 13-21, Cluj-Napoca

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

              Home

              Products

                  Milk processing equipment and equipment for "small farmers"

Milk processing plants

Milk processing equipment

Stainless steel tanks and containers

                  Heat exchangers in co-operation with thermowave germany

Plate heat exchanges

Module welded heat exchangers

Heating stations

Domestic hot water preparation units

                  Filters and other equipment for waste water treatment

Self cleaning automated filters

Self cleaning filters with pistons

Automatic continuous self cleaning filters

Self-cleaning filters

                  Industrial cooling plants and equipment

Technological refrigeration plants

Refrigeration plants for storage rooms

Punched and drawn products

              Dealer

GRUNDFOS pumps and pumping systems

SAUTER automation equipment

LENZE gears and drivers

SWEP brazed heat exchangers

Services

Certificates

Conditions of sale

Inquiry

Contact

          Home

          Products

              Milk processing equipment and equipment for "small farmers"

Milk processing plants

Milk processing equipment

Stainless steel tanks and containers

              Heat exchangers in co-operation with thermowave germany

Plate heat exchanges

Module welded heat exchangers

Heating stations

Domestic hot water preparation units

              Filters and other equipment for waste water treatment

Self cleaning automated filters

Self cleaning filters with pistons

Automatic continuous self cleaning filters

Self-cleaning filters

              Industrial cooling plants and equipment

Technological refrigeration plants

Refrigeration plants for storage rooms

Punched and drawn products

          Dealer

GRUNDFOS pumps and pumping systems

SAUTER automation equipment

LENZE gears and drivers

SWEP brazed heat exchangers

Services

Certificates

Conditions of sale

Inquiry

Contact

CONDITII DE VANZARE

Cap.I Domeniul de aplicare

1. Aceste conditii se aplică confirmărilor de comenzi şi contractelor de vanzari emise de către SC ICPIAF SA pentru orice client din România.

2. Orice modificare a prezentelor condiţii se poate face numai în scris, cu acordul furnizorului.

Cap.II Preţul şi valoarea contractului

1. Preţurile şi valoarea sunt cele cuprinse în contractul de vânzare, sunt exprimate în EUR în condiţii Exworks, SC ICPIAF SA, Cluj Napoca, fără ambalaj şi se consideră acceptate de client la semnarea contractelor.

2. La cererea clientului, produsele vor putea fi ambalate, iar preţul ambalajului şi ambalarii va fi convenit prin act adiţional la contract.

3. Preţurile vor putea suferi modificări datorită modificării unor legi, ordonanţe, reglementări etc., modificările respective se vor conveni de ambele părţi prin acte adiţionale la contract.

Cap.III Modalităţi şi condiţii de plată

1.Plata valorii contractului de vanzare se face in lei la cursul BRD din ziua facturarii prin modalitatile de plata convenite la contractare.

2. Modalităţile şi condiţiile de plată concrete vor fi stabilite prin contractul de vanzare.

Cap.IV Termenele de livrare

1. Termenele de livrare stabilite în contractul de vînzare sunt exprimate în unităţi de timp de la data plăţii integrale a avansului şi perfectarea contractului.

2. Termenele de livrare rămân ferme numai dacă clientul îşi respectă obligaţiile asumate, în caz contrar termenele de livrare se decalează de drept de către furnizor în mod corespunzător.

3. Termenele de livrare pot fi realizate şi anticipat faţă de termenul contractual dacă clientul nu formulează obiecţiuni în acest sens la semnarea contractului, acesta obligându-se să preia şi să platească produsele anticipat.

4. In cazuri deosebite, când subfurnizorii ICPIAF întârzie livrările subfurniturilor, furnizorul este îndreptăţit să solicite decalarea termenului de livrare. In cazuri bine justificate, părţile vor semna un act adiţional la contract cu noul termen de livrare convenit.

Cap.V Calitatea şi recepţia produselor

1. Calitatea produselor se constată cu ocazia recepţiei sau autorecepţiei la furnizor în conformitate cu prevederile documentaţiei sau standardelor de firmă şi se atestă prin certificatul de calitate şi garanţie care însoţeşte produsul la livrare. Furnizorul poate face modificări ale produsului pentru îmbunătaţirea parametrilor tehnici si de fiabilitate a produselor.

2. Recepţia produselor se va efectua pe ştandurile furnizorului în conformitate cu prescripţiile standardelor de firmă, prin autorecepţie.

3. Recepţia poate fi efectuată şi în prezenţa delegatului împuternicit al clientului, dacă acesta îşi exprima în mod expres această intenţie la contractare.

4. In cazul în care clientul doreşte să participe la recepţie la furnizor, furnizorul va înştiinţa clientul cu 24 ore înainte de data recepţiei. Dacă delegatul împuternicit nu se prezintă pentru recepţie în termenul de 24 de ore, furnizorul va trece la efectuarea autorecepţiei, considerând că clientul a renunţat să participe la recepţie la furnizor. Neparticiparea la recepţie la furnizor nu exclude dreptul de reclamaţie cantitativă şi calitativă a produsului conform prevederilor legale şi nici răspunderea furnizorului în limitele contractuale şi prevederile legale, dar nu dă dreptul la nerespectarea plăţilor conform contract

5. În cazul respingerii la recepţie a utilajelor se va conveni pe cale amiabilă modul de rezolvare a acestei situaţii.

6. Dreptul de dispoziţie asupra produselor trece la client din momentul recepţiei sau autoreceptiei. Totodată trec asupra clientului şi riscurile la aceste date.

7. Produsele livrate rămân în deplina proprietate a furnizorului şi este interzisă înstrăinarea lor de către client până la plata integrală a valorii produselor , inclusiv plata diferenţelor de curs valutar şi a eventualelor penaliţăţi care pot apărea din neachitarea facturilor la termen.

CAP.VI Garanţii

1.Perioada de garanţie este stabilită prin contract. Perioada de garanţie pentru părţile componente fabricate de alţi furnizori nu poate depăşi perioada de garanţie acordată de aceştia. Garanţia acoperă asigurarea pieselor înlocuitoare de către furnizor, iar manopera înlocuirii acestora revine clientului. Reperele defecte vor fi identificate de către client şi vor fi expediate la furnizor pentru expertiză şi constatare. Consumabilele de genul: siguranţe fuzibile, garnituri, contactoare, furtune etc. nu beneficiază de termenul de garanţie, înlocuirea acestora revenind clientului.

2. In cazul în care s-a convenit prin contractul de vînzare că punerea în funcţiune se face de furnizor, punerea în funcţiune a echipamentelor va fi consemnată prin proces verbal de punere în funcţiune de reprezentanţii ambelor părţi. Pentru a beneficia de garanţia la utilajele frigorifice, punerea în funcţiune a acestora se va face sub asistenţa tehnică a furnizorului. În cazurile în care s-a convenit ca punerea în funcţiune să se facă sub asistenţa tehnică a furnizorului, este interzisă exploatarea utilajului până la data punerii în funcţiune, sub sancţiunea scoaterii din garanţie.

3.SC ICPIAF SA, Cluj - Napoca acordă garanţie la o utilizare normală, conform prescripţiilor din cartea tehnică care însoţeşte produsul la livrare.

4. Furnizorul are obligaţia să înlocuiască piesele defecte sau să repună în stare de folosinţă (funcţionare) produsul în cauză, prin remediere sau înlocuire după caz, în termenul ce se va stabili de către părţi cu ocazia constatării defecţiunii, dacă în perioada de garanţie s-au constatat defecte din culpa sa. Uzurile normale nu se consideră defecte.

5.Cheltuielile cu manopera, transportul şi cazarea specialiştilor furnizorului vor fi suportate de client.

6. La solicitarea ICPIAF, piesele defecte care au fost înlocuite vor fi returnate furnizorului pentru constatare.

7. Pentru vicii ascunse producătorul răspunde conform legii.

8. Clientul are obligaţia să manipuleze, să depoziteze, să conserve, să monteze, să folosească şi să întreţină produsul conform prescripţiilor date de producător prin documentaţia de însoţire a produsului şi cu ocazia asistenţei tehnice, după caz.Furnizorul nu răspunde de defecţiunile apărute ca urmare a nerespectării de către client a prescripţiilor date.

9. Reclamarea de către client a defectelor produsului în perioada de garanţie va fi făcută în termen de cel mult 5 zile de la data constatării.

10. Clientul este obligat să ia toate măsurile pentru a limita pagubele ce ar surveni din cauza defectelor produsului.

11. Clientul se obligă să utilizeze piese de schimb achiziţionate numai de la furnizor sau indicate de acesta.

12.Garanţia încetează în cazul în care nu se respectă cele de mai sus, precum şi în cazul în care se constată datorii financiare ale clientului faţă de furnizor.

Cap.VII Clauze speciale

1. Renunţarea unilaterală din partea beneficiarului în timpul derulării contractului se poate face numai cu 20 de zile înainte de termenul de livrare si obligă clientul la plata cheltuielilor efectuate de furnizor până în momentul renunţării şi a unor daune în valoare de 10% din valoarea produselor.

2. Pentru nerespectarea plăţilor, conform prevederilor din contract, clientul datorează penalizări de 0,2 % din valoarea datorată pentru fiecare zi calendaristică de întârziere.

3. Prezentul contract exclude acordarea de daune-interese sau orice altfel de despăgubiri cauzate de nefunctionarea utilajului.

4. Alte servicii oferite:

          - service post garanţie - contra cost pe bază de comandă.

            - instruire personal de deservire - gratuit.

            - carte tehnică şi instrucţiuni de folosire în limba română - gratuit.

5. La înţelegere între părţi, produsele pot fi transportate de furnizor contra cost.

Cap.VIII. Forţa majoră

1. Forţa majoră apără de răspundere partea care o invocă dacă este adusă la cunoştinta celeilalte părţi în termen de 5 zile de la aparitia acesteia.

2. Forţa majoră cuprinde evenimentele ce se pot produce după intrarea în vigoare a contractului, în afara voinţei şi controlului părţilor şi care împiedică total sau parţial, îndeplinirea obligaţiilor contractuale.

3. Prin notificarea situaţiei de forţă majoră către cealaltă parte, partea afectată de forţa majoră va fi exonerată de răspunderea de a executa obligaţiile sale din prezentul contract, dar numai în măsura şi numai în perioada în care executarea obligaţiilor sale este împiedicată de cazul de forţa majoră.

4. Notificarea va include cauzele şi consecinţele posibile. Partea care reclamă forţa majoră va notifica celeilalte părţi terminarea acestei perioade.

5. Partea care invocă forţa majoră va transmite celeilalte părţi dovada existenţei faptelor constituind forţa majoră. Această dovadă constă într-un certificat al unui organ guvernamental, instituţie calificată sau Camera de Comerţ. Toate notificările făcute conform acestui aliniat, vor fi date în 15 zile de la data de începere şi terminare a cazului de forţă majoră, prin scrisoare recomandată.

6. În cazul în care forţa majoră continuă pe o perioadă mai mare de 6 luni, oricare din părţi poate cere rezilierea contractului prin darea unei notificări scrise.

7. Nerespectarea condiţiilor mai sus menţionate de către unul din partenerii contractuali are ca urmare suportarea riscurilor şi consecinţelor cazului de fortă majoră de către partenerul contractual care nu şi-a respectat obligaţiile mai sus menţionate.

8. Cazurile de forţă majoră anunţate aşa cum s-a menţionat mai sus, prelungesc automat termenele obligaţiilor contractuale ale părţilor, cu durata lor.

9. Întîrzierile şi nerespectarea obligaţiilor contractuale cauzate de forţa majoră nu sunt supuse penalizărilor sau altor compensaţii sau participarea la daune.

Cap. IX Răspunderea contractuală.

1.Neînţelegerile precontractuale se rezolvă prin conciliere, dacă părţile nu se înţeleg, contractul emis se consideră neperfectat şi este lovit de nulitate.

2. Orice modificare sau anulare a contractului de vînzare se poate face numai cu acordul părţilor.

3. Eventualele litigii între părţi vor fi soluţionate pe cale amiabilă şi în caz de neînţelegere se va apela la Comisia de Arbitraj de pe lîngă CCIA Cluj pentru soluţionare în conformitate cu regulile şi prevederile arbitrare ale acestora.

4. Prezentele condiţii generale de vînzare si livrare se completează cu prevederile legale în vigoare şi constituie anexă la contract.

Societate comerciala cu capital privat romanesc, cu activitati de baza atat in conceptia si proiectarea cat si in executia unei game foarte largi de echipamente si utilaje tehnologice

            Sediu ICPIAF

               Str. Fabricii de Chibrituri 13-21, Cluj-Napoca

               +40 (264) 435232; +40 (746) 033377

               office@icpiaf.ro

               FAX:+40 (264) 435245

          Copyright © 2010 -  ICPIAF - Designed by
          inadcodDesign - Powered by See Web Solutions


text:
package gedi.gui.genovis.tracks;

import gedi.gui.genovis.GenoVisViewer;
import gedi.gui.genovis.SwingGenoVisViewer;
import gedi.util.MathUtils;
import gedi.util.mutable.MutableDouble;

public class ScaleLimitLinker  {

	private MutableDouble fixedMin = new MutableDouble(Double.NaN);
	private MutableDouble fixedMax = new MutableDouble(Double.NaN);

	private MutableDouble min = new MutableDouble(Double.NaN);
	private MutableDouble max = new MutableDouble(Double.NaN);

	private boolean hasRegisteredListener = false;

	public void updateMinMax(NumericTrack<?> t, double min, double max) {
		if (!hasRegisteredListener) {
			t.getViewer().addPrepaintListener(v->{
				this.min.N = Double.NaN;
				this.max.N = Double.NaN;
			});
			hasRegisteredListener = true;
		}

		double tmin = MathUtils.saveMin(min,this.min.N);
		double tmax = MathUtils.saveMax(max,this.max.N);
//		boolean refresh = (Double.isNaN(fixedMin) && tmin!=this.min) || (Double.isNaN(fixedMax) && tmax!=this.max);
		this.min.N = tmin;
		this.max.N = tmax;
//		if (refresh)
//			t.getViewer().repaint();
	}

	public MutableDouble computeCurrentMin(Void data) {
		return Double.isNaN(fixedMin.N)?this.min:fixedMin;
	}

	public MutableDouble computeCurrentMax(Void data) {
		return Double.isNaN(fixedMax.N)?this.max:fixedMax;
	}

}


text:
include("d2q9/d2q9Set.jl")
include("equilibrium_func.jl")
include("macro_var.jl")


text:
<?php
/**
 * @license http://opensource.org/licenses/MIT MIT
 */

namespace Rundiz\SimpleCache\Drivers;

use Psr\SimpleCache\CacheInterface;

use Rundiz\SimpleCache\Exceptions\InvalidArgumentException;

/**
 * APC driver class.
 *
 * @since 3.0
 */
class Apcu implements CacheInterface
{

    use MultipleTrait;

    /**
     * {@inheritDoc}
     */
    public function clear(): bool
    {
        return apcu_clear_cache();
    }// clear

    /**
     * {@inheritDoc}
     */
    public function delete($key): bool
    {
        if (!is_string($key)) {
            throw new InvalidArgumentException('$key must be a string');
        }

        if (!apcu_exists($key)) {
            return true;
        }

        return apcu_delete($key);
    }// delete

    /**
     * {@inheritDoc}
     */
    public function get($key, $default = null)
    {
        if (!is_string($key)) {
            throw new InvalidArgumentException('$key must be a string');
        }

        $value = apcu_fetch($key, $success);
        if (!$success) {
            return $default;
        }
        return $value;
    }// get

    /**
     * {@inheritDoc}
     */
    public function has($key): bool
    {
        if (!is_string($key)) {
            throw new InvalidArgumentException('$key must be a string');
        }

        return apcu_exists($key);
    }// has

    /**
     * {@inheritDoc}
     */
    public function set($key, $value, $ttl = null): bool
    {
        if (!is_string($key)) {
            throw new InvalidArgumentException('$key must be a string');
        }

        if ($ttl === null || (!is_int($ttl) && !$ttl instanceof \DateInterval)) {
            $ttl = 60;
        }

        if ($ttl instanceof \DateInterval) {
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
        } elseif (!is_int($ttl)) {
            throw new InvalidArgumentException('The $ttl must be integer or \\DateInterval object.');
        }

        return apcu_store($key, $value, (int) $ttl);
    }// set

// delete

}


text:
package foundation

import "C"

/*
* Provides interface to the hashing (messege digest) algorithms.
 */
type Hash interface {
	context

	/*
	 * Length of the digest (hashing output) in bytes.
	 */
	GetDigestLen() uint

	/*
	 * Block length of the digest function in bytes.
	 */
	GetBlockLen() uint

	/*
	 * Calculate hash over given data.
	 */
	Hash(data []byte) []byte

	/*
	 * Start a new hashing.
	 */
	Start()

	/*
	 * Add given data to the hash.
	 */
	Update(data []byte)

	/*
	 * Accompilsh hashing and return it's result (a message digest).
	 */
	Finish() []byte

	/*
	 * Release underlying C context.
	 */
	Delete()
}


text:
<idea-plugin version="2" url="http://setial.github.com/intellij-javadocs">
    <id>com.github.setial</id>
    <name>JavaDoc</name>
    <version>3.1.0</version>
    <vendor email="s.timofiychuk@gmail.com" url="http://setial.github.com/intellij-javadocs">
        Sergey Timofiychuk
    </vendor>

    <description><![CDATA[
      Plugin that generates java docs on java class elements, like field, method, etc.
      ]]></description>

    <change-notes><![CDATA[

Changes in intellij-javadoc-3.1.0

Add freemarker lib to plugin

Changes in intellij-javadoc-2.1.0

Fix issue related to File Locked Exception

Fix issue on update 'throws' tags

Fix issue on generate @see and @link tags

Fix issue on load custom template configuration

Improve field templates to generate correct javadoc for constants in interfaces

Improve field templates to generate correct javadoc for constants in enums

Add fieldName variable to templates

Add notification messages during indexing process

Change template engine to freemarker

Changes in intellij-javadoc-2.0.0

Update support build versions (supported intellij idea build versions 132.102+)

Fix issue related to File Locked Exception

Changes in intellij-javadoc-1.0.11

Add actions to Remove javadocs on selected element or on the java file

Add actions to Create/Remove javadocs on a project/package/selected files

Changes in intellij-javadoc-1.0.10

Fix critical issue on generate javadocs in interfaces

Changes in intellij-javadoc-1.0.9

                Change key mappings, since previous are reserved by intellij idea 13.

                Details about new mapping please find on wiki page

Fix bug to show menu only in generate menu of java sources

Changes in intellij-javadoc-1.0.8

Persist javadocs settings on a global level

Changes in intellij-javadoc-1.0.7

Fixed issue with line breaks on javadocs for enum values.

Fixed exception on try to generate javadoc on last line of class.

Add generic types support

Changes in intellij-javadoc-1.0.6

Fixed issue with generating javadocs formatted as single line.

Add feature of generating javadocs for the elements in selected area.

Changes in intellij-javadoc-1.0.5

Introduce new setting that allows to check whether you want to generate splitted class name or not

Bug fixing

Changes in intellij-javadoc-1.0.4

Fixed logging issue on different environment

Changes in intellij-javadoc-1.0.3

Improve regular expressions to better methods recognition

Improve the way how old javadoc and new one are merged in update mode

Changes in intellij-javadoc-1.0.2

Recompile plugin with java 1.6 support

Changes in intellij-javadoc-1.0.1

Initial implementation of "JavaDoc" plugin

      ]]>
    </change-notes>

    <idea-version since-build="142.4783"/>

    <depends>com.intellij.modules.java</depends>

    <application-components>
        <component>
            <interface-class>com.github.setial.intellijjavadocs.operation.JavaDocWriter</interface-class>
            <implementation-class>com.github.setial.intellijjavadocs.operation.impl.JavaDocWriterImpl</implementation-class>
        </component>
        <component>
            <interface-class>com.github.setial.intellijjavadocs.configuration.JavaDocConfiguration</interface-class>
            <implementation-class>com.github.setial.intellijjavadocs.configuration.impl.JavaDocConfigurationImpl</implementation-class>
        </component>
        <component>
            <interface-class>com.github.setial.intellijjavadocs.template.DocTemplateManager</interface-class>
            <implementation-class>com.github.setial.intellijjavadocs.template.impl.DocTemplateManagerImpl</implementation-class>
        </component>
    </application-components>

    <project-components>
        <component>
            <interface-class>com.github.setial.intellijjavadocs.template.DocTemplateProcessor</interface-class>
            <implementation-class>com.github.setial.intellijjavadocs.template.impl.DocTemplateProcessorImpl</implementation-class>
        </component>
    </project-components>

    <actions>
        <group id="com.github.setial.action.file_content" text="_JavaDocs" description="Generate JavaDocs" popup="true">
            <separator/>
            <action id="com.github.setial.intellijjavadocs.action.JavaDocGenerateActionOnEditor"
                    class="com.github.setial.intellijjavadocs.action.JavaDocGenerateAction"
                    text="Create JavaDocs for the selected element"
                    description="Generate javadocs for the selected element.">
                <keyboard-shortcut keymap="$default" first-keystroke="shift alt J"/>
            </action>
            <action id="com.github.setial.intellijjavadocs.action.JavaDocsGenerateActionOnEditor"
                    class="com.github.setial.intellijjavadocs.action.JavaDocsGenerateAction"
                    text="Create JavaDocs for all elements"
                    description="Generate javadocs for all elements in the current java file.">
                <keyboard-shortcut keymap="$default" first-keystroke="shift ctrl alt J"/>
            </action>

            <action id="com.github.setial.intellijjavadocs.action.JavaDocRemoveActionOnEditor"
                    class="com.github.setial.intellijjavadocs.action.JavaDocRemoveAction"
                    text="Remove JavaDocs for the selected element"
                    description="Remove javadocs for the selected element.">
                <keyboard-shortcut keymap="$default" first-keystroke="shift alt Z"/>
            </action>
            <action id="com.github.setial.intellijjavadocs.action.JavaDocsRemoveActionOnEditor"
                    class="com.github.setial.intellijjavadocs.action.JavaDocsRemoveAction"
                    text="Remove JavaDocs for all elements"
                    description="Remove javadocs for all elements in the current java file.">
                <keyboard-shortcut keymap="$default" first-keystroke="shift ctrl alt Z"/>
            </action>
            <separator/>
            <add-to-group group-id="GenerateGroup" anchor="last"/>
        </group>
        <group id="com.github.setial.action.file_tree" text="_JavaDocs" description="Generate JavaDocs" popup="true">
            <action id="com.github.setial.intellijjavadocs.action.JavaDocsGenerateActionOnProject"
                    class="com.github.setial.intellijjavadocs.action.JavaDocsGenerateAction"
                    text="Create JavaDocs for all elements"
                    description="Generate javadocs for all elements in the current java file.">
            </action>
            <action id="com.github.setial.intellijjavadocs.action.JavaDocsRemoveActionOnProject"
                    class="com.github.setial.intellijjavadocs.action.JavaDocsRemoveAction"
                    text="Remove JavaDocs for all elements"
                    description="Remove javadocs for all elements in the current java file.">
            </action>
            <add-to-group group-id="CodeFormatGroup" anchor="last" />
            <add-to-group group-id="ProjectViewPopupMenuModifyGroup" anchor="last" />
        </group>
    </actions>

    <extensions defaultExtensionNs="com.intellij">
        <applicationConfigurable instance="com.github.setial.intellijjavadocs.configuration.impl.JavaDocConfigurationImpl"></applicationConfigurable>
    </extensions>
</idea-plugin>


text:
var crossbeamsGridStore = {

  gridStore: {},

  addGrid: function(gridId, gridOptions) {
    this.gridStore[gridId] = gridOptions;
  },

  getGrid: function(gridId) {
    return this.gridStore[gridId];
  },

  removeGrid: function(gridId) {
    this.gridStore[gridId].api.destroy();
    delete this.gridStore[gridId];
  },

  listGridIds: function() {
    var grid_id, lst = [];
    for(grid_id in this.gridStore) {
      lst.push(grid_id);
    }
    return lst.join(', ');
  }

};

var crossbeamsGridEvents = {

  csvExport: function(grid_id, file_name) {
    var visibleCols, colKeys = [], gridOptions;

    // Get visible columns that do not explicitly have "suppressCsvExport" set.
    gridOptions = crossbeamsGridStore.getGrid(grid_id);
    visibleCols = gridOptions.columnApi.getAllDisplayedColumns();

    for (_i = 0, _len = visibleCols.length; _i < _len; _i++) {
      if(visibleCols[_i].colDef.suppressCsvExport && visibleCols[_i].colDef.suppressCsvExport === true) {
      }
      else {
        colKeys.push(visibleCols[_i].colId);
      }
    }

    var params = {
      fileName: file_name,
      columnKeys: colKeys // Visible, non-suppressed columns.
      // skipHeader: true,
      // skipFooters: true,
      // skipGroups: true,
      // allColumns: true,
      // suppressQuotes: true,
      // onlySelected: true,
      // columnSeparator: ';'
    };

    // Ensure long numbers are exported as strings.
    params.processCellCallback = function(params) {
      var testStr;
      // If HTML entities are a problem...
      // params.value.replace(/&/g, "&").replace(/\\"/g, "\"").replace(/"/g, "\"").replace(/>/g, ">").replace(///g, "/").replace(/</g, "<");

      if (params.value) {
        testStr = ''+params.value;
        if (testStr.length > 12 && !isNaN(testStr) && !testStr.includes('.')) {
          return "'"+testStr;
        }
        else {
          return params.value;
        }
      }
      else {
        return params.value;
      }
    };

    gridOptions.api.exportDataAsCsv(params);
  },

  toggleToolPanel: function(grid_id) {
    var gridOptions, isShowing;
    gridOptions = crossbeamsGridStore.getGrid(grid_id);
    isShowing = gridOptions.api.isToolPanelShowing();
    gridOptions.api.showToolPanel( !isShowing );
  },

  printAGrid: function(grid_id, grid_url) {
     var disp_setting =  "toolbar=yes,location=no,directories=yes,menubar=yes,";
         //disp_setting += "scrollbars=yes,width=650, height=600, left=100, top=25";
    window.open("/print_grid?grid_url="+encodeURIComponent(grid_url), "printGrid", disp_setting);
  },

  quickSearch: function(event) {
    var gridOptions;
    // clear on Esc
    if (event.which == 27) {
      event.target.value = "";
    }
    gridOptions = crossbeamsGridStore.getGrid(event.target.dataset.gridId);
    gridOptions.api.setQuickFilter(event.target.value);
  },

  // setFilterChangeEvent: function(grid_id) {
  //   var gridOptions;
  //
  //   gridOptions = crossbeamsGridStore.getGrid(grid_id);
  //   gridOptions.api.afterFilterChanged();
  //   //.api.rowModel.rootNode.childrenAfterFilter.length
  //
  // }
  showFilterChange: function(grid_id) {
    var gridOptions, filterLength;
    gridOptions = crossbeamsGridStore.getGrid(grid_id);
    if(gridOptions.api.rowModel.rootNode.childrenAfterFilter) {
      filterLength = gridOptions.api.rowModel.rootNode.childrenAfterFilter.length;
    }
    else {
      filterLength = 0;
    }
    console.log('onAfterFilterChanged', filterLength, grid_id);
  },

  promptClick: function(target) {
    var target = event.target;
    var prompt = target.dataset.prompt,
        url    = target.dataset.url,
        method = target.dataset.method;

    if (confirm(prompt)) {
      document.body.innerHTML += '<form id="dynForm" action="' + url +
        '" method="post"><input name="_method" type="hidden" value="'+method+'" /></form>';
      document.getElementById("dynForm").submit();
    }
    //TODO: make call via AJAX & reload grid? Or http to server to figure it out?.....
    //ALSO: disable link automatically while call is being processed...
    event.stopPropagation();
    event.preventDefault();
  }

};

var crossbeamsGridFormatters = {
  testRender: function(params) {
    return '' + params.value.toUpperCase() + '';
  },

  // Return a number with thousand separator and at least 2 digits after the decimal.
  numberWithCommas2: function (params) {
    var x = params.value;
    if (typeof x === 'string') { x = parseFloat(x); }
    if (isNaN(x)) { return ''; }
    x = Math.round((x + 0.00001) * 100) / 100 // Round to 2 digits if longer.
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if(parts[1] === undefined || parts[1].length === 0) {parts[1] = '00'; }
    if(parts[1].length === 1) {parts[1] += '0'; }
    return parts.join(".");
  },

  // Return a number with thousand separator and at least 4 digits after the decimal.
  numberWithCommas4: function (params) {
    var x = params.value;
    if (typeof x === 'string') { x = parseFloat(x); }
    if (isNaN(x)) { return ''; }
    x = Math.round((x + 0.0000001) * 10000) / 10000 // Round to 4 digits if longer.
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if(parts[1] === undefined || parts[1].length === 0) {parts[1] = '0000'; }
    while(parts[1].length < 4) {parts[1] += '0'; }
    return parts.join(".");
  },

  booleanFormatter: function(params) {
    if(params.value === ''){ return ''; }
    if(params.value == 't' || params.value == 'true' || params.value == 'y' || params.value == 1) {
      return " ";
    }
    else {
      return " ";
    }
  },

  hrefInlineFormatter: function(params) {
    //var rainPerTenMm = params.value / 10;
    return "edit";
  },

  hrefSimpleFormatter: function(params) {
    var val = params.value;
    return ""+val.split('|')[1]+"";
  },

  // Creates a link that when clicked prompts for a yes/no answer.
  // Column value is in the format "url|link_text|prompt|method".
  // Only url and link_text are required.
  hrefPromptFormatter: function(params) {
    var url, link_text, prompt, method;
    [url, link_text, prompt, method] = params.value.split('|');
    prompt = prompt || 'Are you sure?';
    method = (method || 'post').toLowerCase();
    return ""+link_text+"";
  }

};

// function to act as a class
function NumericCellEditor() {
}

// gets called once before the renderer is used
NumericCellEditor.prototype.init = function (params) {
    // create the cell
    this.eInput = document.createElement('input');
    this.eInput.value = crossbeamsUtils.isCharNumeric(params.charPress) ? params.charPress : params.value;

    var that = this;
    this.eInput.addEventListener('keypress', function (event) {
        if (!crossbeamsUtils.isKeyPressedNumeric(event)) {
            that.eInput.focus();
            if (event.preventDefault) event.preventDefault();
        }
    });

    // only start edit if key pressed is a number, not a letter
    var charPressIsNotANumber = params.charPress && ('1234567890'.indexOf(params.charPress) < 0);
    this.cancelBeforeStart = charPressIsNotANumber;
};

// gets called once when grid ready to insert the element
NumericCellEditor.prototype.getGui = function () {
    return this.eInput;
};

// focus and select can be done after the gui is attached
NumericCellEditor.prototype.afterGuiAttached = function () {
    this.eInput.focus();
};

// returns the new value after editing
NumericCellEditor.prototype.isCancelBeforeStart = function () {
    return this.cancelBeforeStart;
};

// example - will reject the number if it contains the value 007
// - not very practical, but demonstrates the method.
NumericCellEditor.prototype.isCancelAfterEnd = function () {
    // var value = this.getValue();
    // return value.indexOf('007') >= 0;
};

// returns the new value after editing
NumericCellEditor.prototype.getValue = function () {
    if(this.eInput.value === '') {
      return '';
    }
  else {
    return parseInt(this.eInput.value);
  }
};

// any cleanup we need to be done here
NumericCellEditor.prototype.destroy = function () {
    // but this example is simple, no cleanup, we could  even leave this method out as it's optional
};

// if true, then this editor will appear in a popup
NumericCellEditor.prototype.isPopup = function () {
    // and we could leave this method out also, false is the default
    return false;
};

(function() {
  var loadGrid;
  var onBtExport;

  translateColDefs = function(columnDefs) {
    //console.log(columnDefs);
    var newColDefs = [], col, newCol, fn;
    for (_i = 0, _len = columnDefs.length; _i < _len; _i++) {
      col = columnDefs[_i];
      newCol = {};
      for(attr in col) {
        if(attr==='cellRenderer') {
          //fn = window[col[attr]];
          //newCol[attr] = fn;
          //newCol[attr] = eval(col[attr]);
          if(col[attr] ==='crossbeamsGridFormatters.testRender') {
            newCol[attr] = crossbeamsGridFormatters.testRender;
          }
          if(col[attr] ==='crossbeamsGridFormatters.numberWithCommas2') {
            newCol[attr] = crossbeamsGridFormatters.numberWithCommas2;
          }
          if(col[attr] ==='crossbeamsGridFormatters.numberWithCommas4') {
            newCol[attr] = crossbeamsGridFormatters.numberWithCommas4;
          }
          if(col[attr] ==='crossbeamsGridFormatters.booleanFormatter') {
            newCol[attr] = crossbeamsGridFormatters.booleanFormatter;
          }
          if(col[attr] ==='crossbeamsGridFormatters.hrefInlineFormatter') {
            newCol[attr] = crossbeamsGridFormatters.hrefInlineFormatter;
          }
          if(col[attr] ==='crossbeamsGridFormatters.hrefSimpleFormatter') {
            newCol[attr] = crossbeamsGridFormatters.hrefSimpleFormatter;
          }
          if(col[attr] ==='crossbeamsGridFormatters.hrefPromptFormatter') {
            newCol[attr] = crossbeamsGridFormatters.hrefPromptFormatter;
          }

        }
        else {
          if(attr==='cellEditor') {
            console.log('edit');
            if(col[attr] ==='NumericCellEditor') {
            console.log('edit - NUM');
              newCol[attr] = NumericCellEditor;
            }
          }
          else {
            newCol[attr] = col[attr];
          }
        }
      }
      newColDefs.push(newCol);
    }
    return newColDefs;
  };

  loadGrid = function(grid, gridOptions) {
    var httpRequest, url;
    url = grid.getAttribute('data-gridurl');
    httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url);
    httpRequest.send();
    return httpRequest.onreadystatechange = function() {
      var httpResult, newColDefs;
      if (httpRequest.readyState === 4 && httpRequest.status === 200) {
        httpResult = JSON.parse(httpRequest.responseText);
        newColDefs = translateColDefs(httpResult.columnDefs);
        gridOptions.api.setColumnDefs(newColDefs);
        gridOptions.api.setRowData(httpResult.rowDefs);
      }
    };
  };

  //document.addEventListener(eventName, eventHandler);
  document.addEventListener("DOMContentLoaded", function() {
    var grid, gridOptions, grids, _i, _len, _results, grid_id;
    grids = document.querySelectorAll('[data-grid]');
    //_results = [];
    for (_i = 0, _len = grids.length; _i < _len; _i++) {
      grid = grids[_i];
      grid_id = grid.getAttribute('id');
      for_print = grid.dataset.gridPrint;
      // lookup of grid ids? populate here and clear when grid unloaded...
      gridOptions = {
        columnDefs: null,
        rowDefs: null,
        enableColResize: true,
        enableSorting: true,
        enableFilter: true,
        suppressScrollLag: true,
        enableRangeSelection: true,
        enableStatusBar: true,
        suppressAggFuncInHeader: true,
        // onAfterFilterChanged: function() {console.log('onAfterFilterChanged', this.api.rowModel.rootNode.childrenAfterFilter.length, grid_id);}
        // onAfterFilterChanged: crossbeamsGridEvents.showFilterChange(grid_id)
        //suppressCopyRowsToClipboard: true
        //quickFilterText: 'fred'
      };
      if(for_print) {
        gridOptions.forPrint        = true;
        gridOptions.enableStatusBar = false;
      }

      new agGrid.Grid(grid, gridOptions);
      crossbeamsGridStore.addGrid(grid_id, gridOptions);
      gridOptions.onAfterFilterChanged = crossbeamsGridEvents.showFilterChange(grid_id);
      //_results.push(loadGrid(grid, gridOptions));
      loadGrid(grid, gridOptions);
    }
    //return _results;
  });

}).call(this);


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Kind Schema
 */
var KindSchema = new Schema({
	voornaam: {
		type: String,
		default: '',
		required: 'Vul de voornaam in',
		trim: true
	},
	familienaam: {
		type: String,
		default: '',
		required: 'Vul de familienaam in',
		trim: true
	},
	rijksregisternummer: {
		type: String,
		default: '',
		required: 'Vul het rijksregisternummer in',
		trim: true
	},
	geboortedatum: {
		type: Date,
		default: Date.now,
		required: 'Vul de geboortedatum in',
	},
	adres: {
		straat: {
			type: String,
			default: '',
			required: 'Vul de straat in',
			trim: true
		},
		nummer: {
			type: String,
			default: '',
			required: 'Vul het huisnummer in',
			trim: true
		},
		bus: {
			type: String,
			default: '',
			trim: true
		},
		gemeente: {
			type: String,
			default: '',
			required: 'Vul de gemeente in',
			trim: true
		},
		postcode: {
			type: String,
			default: '',
			required: 'Vul de postcode in',
			trim: true
		}
	},
	ouders: [{ type: String}],
	vakanties: [{ type: String }]
});

mongoose.model('Kind', KindSchema);


text:
<?php

namespace Google\Service\Vault;

class CloseMatterResponse extends \Google\Model
{
  protected $matterType = Matter::class;
  protected $matterDataType = '';

  /**
   * @param Matter
   */
  public function setMatter(Matter $matter)
  {
    $this->matter = $matter;
  }
  /**
   * @return Matter
   */
  public function getMatter()
  {
    return $this->matter;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(CloseMatterResponse::class, 'Google_Service_Vault_CloseMatterResponse');


text:
package ro.pub.cs.vmchecker.client;

import java.util.Date;

import com.google.gwt.user.client.Cookies;

/**
 * @author claudiugh
 *
 * This class handles persistent storage using cookie interface
 * for several useful tokens
 */
public class CookieManager {
	public static final String COURSE_COOKIE = "VMCHK-COURSE";
	public static final String USERNAME_COOKIE = "VMCHK-USER";

	/**
	 * the username is stored as cookie because it is obtained only
	 * when login is successfully performed
	 * @param username
	 */
	public static void saveUsername(String username) {
		Date now = new Date();
		Cookies.setCookie(USERNAME_COOKIE, username, new Date(now.getYear() + 1, now.getMonth(), now.getDay()));
	}

	public static String getUsername() {
		return Cookies.getCookie(USERNAME_COOKIE);
	}

	/**
	 * the courseId is stored in order to restore the last
	 * course view after an active sessions ends
	 * @param courseId
	 */
	public static void saveLastCourse(String courseId) {
		Date now = new Date();
		Cookies.setCookie(COURSE_COOKIE, courseId, new Date(now.getYear() + 1, now.getMonth(), now.getDay()));
	}

	public static String getLastCourse() {
		return Cookies.getCookie(COURSE_COOKIE);
	}

}


text:
Cucumber web steps [![Build Status](http://travis-ci.org/kucaahbe/cucumber-websteps.png)](http://travis-ci.org/kucaahbe/cucumber-websteps)
==========================================================================================================================================

Attention!!!

Before you start, please read [this](http://aslakhellesoy.com/post/11055981222/the-training-wheels-came-off).

This gem just collected common browsing step, just to prevent you from repeating self by writing every time this steps in every your project.

Write your own steps, use this steps if you really need to write in scenario "When I click ..."

Description
-----------

[Capybara](http://github.com/jnicklas/capybara) powered common cucumber web steps for any web application (blackjack and hookers included).

Because!

* Here collected [all "web steps"](http://github.com/cucumber/cucumber-rails/blob/master/lib/generators/cucumber/install/templates/step_definitions/web_steps.rb.erb) you need and even more([-=INCLUDED STEPS DOCUMENTATION LINK=-](http://relishapp.com/kucaahbe/cucumber-websteps))
* Support your favorite testing framework (test/unit, minitest, rspec-1, rspec-2) Note: not yet tested with rspec-1, coming soon
* work with both :rack\_test and :selenium drivers
* all in one place, DRY.
* [launchy](http://rubygems.org/gems/launchy) included :)
* blackjack and hookers  ;)

[Install](http://relishapp.com/kucaahbe/cucumber-websteps)
----------------------------------------------------------

and enjoy!

![Steps:)](http://github.com/kucaahbe/cucumber-websteps/raw/master/steps.jpg)


text:
export default [
  {
    title: 'Brand Manual',
    description: 'Visual Brand Identity Manual.',
    link:
      'https://myfranciscan.franciscan.edu/ICS/clientconfig/customcontent/marcom/MarComTab/LogoManual2.pdf',
    hoverable: true
  },
  {
    title: 'Logos',
    description: 'Official Franciscan University Logos.',
    link: '/logos',
    hoverable: true
  },
  {
    title: 'Letterhead',
    description:
      'Franciscan University approved letterhead and letter writing guidelines.',
    link: '/letterhead',
    hoverable: true
  },
  {
    title: 'Suggest a Story',
    description: 'Help us share your news.',
    link: '/share-a-story',
    hoverable: true
  },
  {
    title: 'Service Request Form',
    description:
      'Let us know what you need, and we will get started on it as soon as we can.',
    link: '/service-request-form',
    hoverable: true
  },
  {
    title: 'Powerpoint',
    description: 'Official Franciscan University Powerpoint template.',
    link:
      'https://myfranciscan.franciscan.edu/ICS/clientconfig/customcontent/marcom/MarComTab/PowerPointPres.pptx',
    hoverable: true
  },
  {
    title: 'Posters',
    description: 'Resources for creating posters.',
    link: '/posters',
    hoverable: true
  },
  {
    title: 'Glossary',
    description: 'Common MarCom terms and definitions.',
    link: '/glossary',
    hoverable: true
  },
  {
    title: 'Tutorial',
    description: 'Video guide of the Resource Center.',
    link: '/tutorial',
    hoverable: true
  }
]