text:
import React, { Component, PropTypes } from 'react';
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Movies.css';
import exampleMovie from './exampleMovie.json';

// Child components
import Details from './details/Details';
import List from './list/List';

class Movies extends Component {

  static propTypes = {
    movies: PropTypes.arrayOf(
      PropTypes.shape({
        TitleId: PropTypes.number,
        TitleName: PropTypes.string,
        ReleaseYear: PropTypes.number,
        Storylines: PropTypes.array,
      }),
    ),
  };

  state = {
    selectedMovie: exampleMovie,
  };

  handleSelect = (movie) => {
    if (this.state.selectedMovie.TitleId === movie.TitleId) return;
    this.setState({ selectedMovie: movie });
  };

  render() {
    return (

          <Grid>
            <Row className="show-grid">
              <Col md={6}>
                <Col md={12}>
                  <List
                    items={this.props.movies}
                    handleClick={this.handleSelect}
                    selectedMovie={this.state.selectedMovie}
                  />
                </Col>
              </Col>
              <Col md={6}>
                <Col md={12}>

                </Col>
              </Col>
            </Row>
          </Grid>

    );
  }

}

export default withStyles(s)(Movies);


text:
use v5.10.1;
use strict;
#no strict "refs";

given ($ARGV[0]){
 when ("LoadAvarage"){ loadAverage();}
 when ("MemoryUsage"){ memoryUsage("mem"); }
 when ("SwapUsage"){ memoryUsage("swap"); }
 when ("PacketsDropped"){ networkErrors("drops"); }
 when ("PacketsRetransmited"){ networkErrors("drops"); }
 when ("PacketsUdpNoPort"){ networkErrors("drops"); }
 when ("PacketsUdpErr"){ networkErrors("drops"); }
 when ("NtpStatus"){ ntpStatus(); }
 default {
   print << "EOF";
Not found the invokation parameter. The usage example is:

perl custom_monitoring.pl <MonitorParam>

where <MonitorParam> might be one of: LoadAvarage, MemoryUsage,
SwapUsage, PacketsDropped, PacketsRetransmited, PacketsUdpNoPort,
PacketsUdpErr, NtpStatus
EOF
 }
}

sub loadAverage(){
#The idea is to get output of the command "uptime", fetch of the couters
#of load average during 5,10,15 min intervals, and devide the one of them
#to result of executed command "nproc"
my $nproc = qx/nproc/;
my $uptime = qx/uptime/;
my @loadAvg = split(" ",$uptime =~ 's/^.*load average://ir');
printf "%d\n", $loadAvg[0]/$nproc;
}

sub memoryUsage(){
#Alforithm is to get and parse output of the cmd "free" to fetch 'total',
#'used' columns, and calculate the persentage of free space
  my @free = qx/free/;
  my (%memory,%swap) = ();
  my @headline = split(" ", $free[0]);
  my @mem = split(" ",@free[1]);
  my @sw = @free[2] !~ 'buffers/cache' ? split(" ",@free[2]) : split(" ",@free[3]);

  for (my $i = 0; $i < @headline; $i++){
    $memory{lc $headline[$i]} = $mem[$i+1];
    $swap{lc $headline[$i]} = $sw[$i+1];
  }
  given(lc @_[0]){
    when ("swap") {
      printf "%d\%\n", $swap{"used"}/$swap{"total"}*100;
      }
    when ("mem") {
      printf "%d\%\n", $memory{"used"}/$memory{"total"}*100;
      }
    }
}

sub parseSarOutput{
#Required the list of sar command output fo processing
#Returns the list of hashes of interface's statistics
  my @headers = grep { $_ =~ /IFACE/ } @_;
  @headers = split(" ",$headers[0]); #Should be only one element
  my @ifaces = ();

  for my $line (@_){

    if (length $line > 1 && $line !~ /Linux|IFACE|lo |Average/){
      my @candidate = split(" ",$line);
      my %item = ();
      for (my $i = 0; $i < @headers; $i++){
        $item{$headers[$i]} = $candidate[$i];
      }
      push @ifaces, {%item};
    }
  }
  return @ifaces;
}

sub examineErrors{
#Requred 2 arguments: list of hash and the list of headees
  my $data = shift(@_);
  my $headers = shift(@_);

  for (my $i=0; $i<@$data; $i++) {
    for my $header (@$headers){
      #say "$$data[$i]{'IFACE'} - $header:$$data[$i]{$header}" if $$data[$i]{$header} > 0;
      say "$$data[$i]{'IFACE'} - $header:$$data[$i]{$header}";
    }
  }
}

sub networkErrors(){
  my (@data, @headers) = ();
  given(shift){
    when("drops"){
      @data = qx/sar -n EDEV -s \$(date --date="now-20min" +%H:%M:%S)/;
      @headers = ('rxdrop/s','txdrop/s');
    }
  }
  my @parsed = parseSarOutput(@data);
  examineErrors(\@parsed, \@headers);
}
sub ntpStatus(){
  my @output = qx/ntpstat/;
  given($? >> 8){
    when (0) {
      say "Time synchronised";
    }
    when (1) {
      say "Time NOT synchronised";
    }
    when (2) {
      say "NTPD is NOT responded";
    }
    default {
      say "Unknown result";
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using EnvDTE;
using VSLangProj;

namespace Microsoft.VisualStudioTools.Project.Automation
{
    /// <summary>
    /// Represents a language-specific project item
    /// </summary>
    [ComVisible(true)]
    public class OAVSProjectItem : VSProjectItem
    {
        #region fields
        private FileNode fileNode;
        #endregion

        #region ctors
        internal OAVSProjectItem(FileNode fileNode)
        {
            this.FileNode = fileNode;
        }
        #endregion

        #region VSProjectItem Members

        public virtual EnvDTE.Project ContainingProject => this.fileNode.ProjectMgr.GetAutomationObject() as EnvDTE.Project;
        public virtual ProjectItem ProjectItem => this.fileNode.GetAutomationObject() as ProjectItem;
        public virtual DTE DTE => (DTE)this.fileNode.ProjectMgr.Site.GetService(typeof(DTE));
        public void RunCustomTool()
        {
        }

        #endregion

        #region public properties
        /// <summary>
        /// File Node property
        /// </summary>
        internal FileNode FileNode
        {
            get
            {
                return this.fileNode;
            }
            set
            {
                this.fileNode = value;
            }
        }
        #endregion

    }
}


text:
<keymap version="1" name="NetBeans 6.5" parent="$default">
  <action id="$Redo">
    <keyboard-shortcut first-keystroke="shift control Z"/>
    <keyboard-shortcut first-keystroke="shift alt BACK_SPACE"/>
    <keyboard-shortcut first-keystroke="control Y"/>
  </action>
  <action id="ActivateFavoritesToolWindow"/>
  <action id="ActivateFindToolWindow">
    <keyboard-shortcut first-keystroke="shift alt U"/>
    <keyboard-shortcut first-keystroke="shift control 0"/>
    <keyboard-shortcut first-keystroke="alt 2"/>
  </action>
  <action id="ActivateMessagesToolWindow">
    <keyboard-shortcut first-keystroke="control 4"/>
    <keyboard-shortcut first-keystroke="alt 0"/>
  </action>
  <action id="ActivatePaletteToolWindow">
    <keyboard-shortcut first-keystroke="shift control 8"/>
  </action>
  <action id="ActivateProjectToolWindow">
    <keyboard-shortcut first-keystroke="control 1"/>
    <keyboard-shortcut first-keystroke="control 2"/>
    <keyboard-shortcut first-keystroke="control 3"/>
    <keyboard-shortcut first-keystroke="alt 1"/>
  </action>
  <action id="ActivateStructureToolWindow">
    <keyboard-shortcut first-keystroke="control 7"/>
    <keyboard-shortcut first-keystroke="alt 7"/>
  </action>
  <action id="ActivateTODOToolWindow">
    <keyboard-shortcut first-keystroke="alt 6"/>
    <keyboard-shortcut first-keystroke="control 6"/>
  </action>
  <action id="AddToFavoritesPopup"/>
  <action id="Back">
    <keyboard-shortcut first-keystroke="alt LEFT"/>
    <mouse-shortcut keystroke="button4"/>
  </action>
  <action id="CheckinProject"/>
  <action id="ClassNameCompletion">
    <keyboard-shortcut first-keystroke="control alt SPACE"/>
    <keyboard-shortcut first-keystroke="control alt BACK_SLASH"/>
  </action>
  <action id="CloseActiveTab"/>
  <action id="CloseAllEditors">
    <keyboard-shortcut first-keystroke="shift control W"/>
    <keyboard-shortcut first-keystroke="shift control F4"/>
  </action>
  <action id="CloseContent">
    <keyboard-shortcut first-keystroke="control F4"/>
    <keyboard-shortcut first-keystroke="control W"/>
  </action>
  <action id="EditorChooseLookupItemDot">
    <keyboard-shortcut first-keystroke="control PERIOD"/>
  </action>
  <action id="CodeCompletion">
    <keyboard-shortcut first-keystroke="control SPACE"/>
    <keyboard-shortcut first-keystroke="control BACK_SLASH"/>
  </action>
  <action id="CollapseBlock"/>
  <action id="CollapseSelection"/>
  <action id="CommentByLineComment">
    <keyboard-shortcut first-keystroke="control SLASH"/>
    <keyboard-shortcut first-keystroke="shift control C"/>
  </action>
  <action id="CollapseRegionRecursively">
    <keyboard-shortcut first-keystroke="control DIVIDE"/>
  </action>
  <action id="Compile">
    <keyboard-shortcut first-keystroke="F9"/>
  </action>
  <action id="CompileDirty">
    <keyboard-shortcut first-keystroke="F11"/>
  </action>
  <action id="CompileProject">
    <keyboard-shortcut first-keystroke="shift F11"/>
  </action>
  <action id="CopyElement"/>
  <action id="CopyPaths"/>
  <action id="Debug">
    <keyboard-shortcut first-keystroke="control F5"/>
  </action>
  <action id="DebugClass">
    <keyboard-shortcut first-keystroke="shift control F5"/>
    <keyboard-shortcut first-keystroke="shift alt F5"/>
  </action>
  <action id="XDebugger.NewWatch">
    <keyboard-shortcut first-keystroke="shift control F7"/>
  </action>
  <action id="Debugger.ResumeThread">
    <keyboard-shortcut first-keystroke="F5"/>
  </action>
  <action id="EditorCompleteStatement">
    <keyboard-shortcut first-keystroke="shift control ENTER"/>
    <keyboard-shortcut first-keystroke="control SEMICOLON"/>
  </action>
  <action id="EditorDeleteLine">
    <keyboard-shortcut first-keystroke="control E"/>
  </action>
  <action id="EditorDuplicate">
    <keyboard-shortcut first-keystroke="control D"/>
    <keyboard-shortcut first-keystroke="shift control DOWN"/>
    <keyboard-shortcut first-keystroke="shift control UP"/>
  </action>
  <action id="EditorIndentSelection">
    <keyboard-shortcut first-keystroke="TAB"/>
  </action>
  <action id="EditorIndentLineOrSelection">
    <keyboard-shortcut first-keystroke="shift alt RIGHT"/>
  </action>
  <action id="EditorMoveToPageBottom">
    <keyboard-shortcut first-keystroke="shift alt END"/>
  </action>
  <action id="EditorMoveToPageTop">
    <keyboard-shortcut first-keystroke="shift alt HOME"/>
  </action>
  <action id="EditorScrollToCenter"/>
  <action id="EditorSelectWord">
    <keyboard-shortcut first-keystroke="shift alt PERIOD"/>
  </action>
  <action id="EditorToggleCase">
    <keyboard-shortcut first-keystroke="control U" second-keystroke="S"/>
  </action>
  <action id="EditorUnSelectWord">
    <keyboard-shortcut first-keystroke="shift alt COMMA"/>
  </action>
  <action id="EditorUnindentSelection">
    <keyboard-shortcut first-keystroke="shift alt LEFT"/>
    <keyboard-shortcut first-keystroke="shift TAB"/>
  </action>
  <action id="EvaluateExpression">
    <keyboard-shortcut first-keystroke="control F9"/>
  </action>
  <action id="ExpandAllToLevel1"/>
  <action id="ExpandAllToLevel2"/>
  <action id="ExpandAllToLevel3"/>
  <action id="ExpandAllToLevel4"/>
  <action id="ExpandAllToLevel5"/>
  <action id="ExpandRegionRecursively">
    <keyboard-shortcut first-keystroke="control MULTIPLY"/>
  </action>
  <action id="ExpandToLevel1"/>
  <action id="ExpandToLevel2"/>
  <action id="ExpandToLevel3"/>
  <action id="ExpandToLevel4"/>
  <action id="ExpandToLevel5"/>
  <action id="ExtractMethod">
    <keyboard-shortcut first-keystroke="shift alt M"/>
  </action>
  <action id="FileChooser.GotoHome"/>
  <action id="FileStructurePopup">
    <keyboard-shortcut first-keystroke="control F12"/>
    <keyboard-shortcut first-keystroke="shift control F12"/>
  </action>
  <action id="FindUsagesInFile"/>
  <action id="Forward">
    <keyboard-shortcut first-keystroke="alt RIGHT"/>
    <mouse-shortcut keystroke="button5"/>
  </action>
  <action id="GotoAction">
    <keyboard-shortcut first-keystroke="control I"/>
  </action>
  <action id="GotoBookmark0"/>
  <action id="GotoBookmark1"/>
  <action id="GotoBookmark2"/>
  <action id="GotoBookmark3"/>
  <action id="GotoBookmark4"/>
  <action id="GotoBookmark5"/>
  <action id="GotoBookmark6"/>
  <action id="GotoBookmark7"/>
  <action id="GotoBookmark8"/>
  <action id="GotoBookmark9"/>

  <action id="ToggleBookmark0"/>
  <action id="ToggleBookmark1"/>
  <action id="ToggleBookmark2"/>
  <action id="ToggleBookmark3"/>
  <action id="ToggleBookmark4"/>
  <action id="ToggleBookmark5"/>
  <action id="ToggleBookmark6"/>
  <action id="ToggleBookmark7"/>
  <action id="ToggleBookmark8"/>
  <action id="ToggleBookmark9"/>

  <action id="GotoClass">
    <keyboard-shortcut first-keystroke="control O"/>
  </action>
  <action id="GotoChangedFile">
    <keyboard-shortcut first-keystroke="control O"/>
  </action>
  <action id="GotoFile">
    <keyboard-shortcut first-keystroke="shift alt O"/>
  </action>
  <action id="GotoNextBookmark">
    <keyboard-shortcut first-keystroke="shift control PERIOD"/>
  </action>
  <action id="GotoNextError">
    <keyboard-shortcut first-keystroke="F2"/>
    <keyboard-shortcut first-keystroke="control PERIOD"/>
  </action>
  <action id="GotoPreviousBookmark">
    <keyboard-shortcut first-keystroke="shift control COMMA"/>
  </action>
  <action id="GotoPreviousError">
    <keyboard-shortcut first-keystroke="shift F2"/>
    <keyboard-shortcut first-keystroke="control COMMA"/>
  </action>
  <action id="GotoSuperMethod">
    <keyboard-shortcut first-keystroke="shift control P"/>
  </action>
  <action id="GotoSymbol">
    <keyboard-shortcut first-keystroke="shift control alt O"/>
  </action>
  <action id="Graph.Print">
    <keyboard-shortcut first-keystroke="shift control alt P"/>
  </action>
  <action id="GuiDesigner.ReloadCustomComponents">
    <keyboard-shortcut first-keystroke="shift control R"/>
  </action>
  <action id="HideAllWindows"/>
  <action id="HippieBackwardCompletion">
    <keyboard-shortcut first-keystroke="control K"/>
  </action>
  <action id="HippieCompletion">
    <keyboard-shortcut first-keystroke="shift control K"/>
  </action>
  <action id="ImplementMethods"/>
  <action id="IntroduceConstant">
    <keyboard-shortcut first-keystroke="shift alt C"/>
  </action>
  <action id="IntroduceField">
    <keyboard-shortcut first-keystroke="shift alt E"/>
  </action>
  <action id="IntroduceFunctionalParameter"/>
  <action id="IntroduceVariable">
    <keyboard-shortcut first-keystroke="shift alt V"/>
  </action>
  <action id="MethodDown">
    <keyboard-shortcut first-keystroke="control alt DOWN"/>
  </action>
  <action id="MethodHierarchy"/>
  <action id="MethodUp">
    <keyboard-shortcut first-keystroke="control alt UP"/>
  </action>
  <action id="Move">
    <keyboard-shortcut first-keystroke="control M"/>
  </action>
  <action id="MoveStatementDown">
    <keyboard-shortcut first-keystroke="shift alt PAGE_DOWN"/>
  </action>
  <action id="MoveStatementUp">
    <keyboard-shortcut first-keystroke="shift alt PAGE_UP"/>
  </action>
  <action id="NewElement">
    <keyboard-shortcut first-keystroke="alt INSERT"/>
    <keyboard-shortcut first-keystroke="control N"/>
  </action>
  <action id="NewProject">
    <keyboard-shortcut first-keystroke="shift control N"/>
  </action>
  <action id="NextEditorTab">
    <keyboard-shortcut first-keystroke="control alt PAGE_DOWN"/>
  </action>
  <action id="GotoNextElementUnderCaretUsage">
    <keyboard-shortcut first-keystroke="alt DOWN"/>
  </action>
  <action id="NextTab">
    <keyboard-shortcut first-keystroke="control PAGE_DOWN"/>
  </action>
  <action id="OpenFile">
    <keyboard-shortcut first-keystroke="shift control O"/>
  </action>
  <action id="OptimizeImports">
    <keyboard-shortcut first-keystroke="shift control I"/>
  </action>
  <action id="OverrideMethods"/>
  <action id="PreviousEditorTab">
    <keyboard-shortcut first-keystroke="control alt PAGE_UP"/>
  </action>
  <action id="GotoPrevElementUnderCaretUsage">
    <keyboard-shortcut first-keystroke="alt UP"/>
  </action>
  <action id="PreviousTab">
    <keyboard-shortcut first-keystroke="control PAGE_UP"/>
  </action>
  <action id="Print">
    <keyboard-shortcut first-keystroke="shift control alt P"/>
  </action>
  <action id="ExpressionTypeInfo"/>
  <action id="QuickImplementations"/>
  <action id="RecentChangedFiles"/>
  <action id="RecentChanges"/>
  <action id="RecentFiles">
    <keyboard-shortcut first-keystroke="shift F4"/>
  </action>
  <action id="ReformatCode">
    <keyboard-shortcut first-keystroke="shift alt F"/>
  </action>
  <action id="Refresh"/>
  <action id="RenameElement">
    <keyboard-shortcut first-keystroke="control R"/>
  </action>
  <action id="Replace">
    <keyboard-shortcut first-keystroke="control H"/>
  </action>
  <action id="ReplaceInPath">
    <keyboard-shortcut first-keystroke="shift control H"/>
  </action>
  <action id="Rerun"/>
  <action id="Resume">
    <keyboard-shortcut first-keystroke="F5"/>
  </action>
  <action id="Run">
    <keyboard-shortcut first-keystroke="F6"/>
  </action>
  <action id="RunClass">
    <keyboard-shortcut first-keystroke="shift alt F6"/>
    <keyboard-shortcut first-keystroke="shift F6"/>
  </action>
  <action id="RunToCursor">
    <keyboard-shortcut first-keystroke="F4"/>
  </action>
  <action id="SaveAll">
    <keyboard-shortcut first-keystroke="control S"/>
    <keyboard-shortcut first-keystroke="shift control S"/>
  </action>
  <action id="SelectIn">
    <keyboard-shortcut first-keystroke="shift control 1"/>
    <keyboard-shortcut first-keystroke="shift control 2"/>
    <keyboard-shortcut first-keystroke="shift control 3"/>
    <keyboard-shortcut first-keystroke="shift control 9"/>
  </action>
  <action id="ShowBookmarks">
    <keyboard-shortcut first-keystroke="shift control M"/>
  </action>
  <action id="ShowPopupMenu">
    <keyboard-shortcut first-keystroke="CONTEXT_MENU"/>
    <keyboard-shortcut first-keystroke="shift F10"/>
  </action>
  <action id="SmartTypeCompletion">
    <keyboard-shortcut first-keystroke="shift control SPACE"/>
    <keyboard-shortcut first-keystroke="shift control BACK_SLASH"/>
  </action>
  <action id="StepOut">
    <keyboard-shortcut first-keystroke="control F7"/>
  </action>
  <action id="Stop">
    <keyboard-shortcut first-keystroke="shift F5"/>
    <keyboard-shortcut first-keystroke="shift control DELETE"/>
  </action>
  <action id="StructuralSearchPlugin.StructuralReplaceAction"/>
  <action id="StructuralSearchPlugin.StructuralSearchAction"/>
  <action id="ToggleBookmark"/>
  <action id="ToggleDockMode">
    <keyboard-shortcut first-keystroke="control BACK_SPACE"/>
  </action>
  <action id="ToggleFloatingMode">
    <keyboard-shortcut first-keystroke="shift alt D"/>
  </action>
  <action id="TypeHierarchy">
    <keyboard-shortcut first-keystroke="shift alt F12"/>
  </action>
  <action id="Unwrap"/>
  <action id="ValidateJsp">
    <keyboard-shortcut first-keystroke="shift alt F9"/>
  </action>
  <action id="ValidateXml">
    <keyboard-shortcut first-keystroke="shift alt F9"/>
  </action>
  <action id="MoveLineDown">
    <keyboard-shortcut first-keystroke="shift alt DOWN"/>
  </action>
  <action id="MoveLineUp">
    <keyboard-shortcut first-keystroke="shift alt UP"/>
  </action>
  <action id="Vcs.ShowMessageHistory">
    <keyboard-shortcut first-keystroke="control M"/>
    <keyboard-shortcut first-keystroke="shift F4"/>
  </action>
  <action id="EditorMatchBrace"/>
  <action id="Git.Reword.Commit">
    <keyboard-shortcut first-keystroke="control R"/>
  </action>
  <action id="ShelvedChanges.Rename">
    <keyboard-shortcut first-keystroke="control R"/>
  </action>
</keymap>


text:
from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r"^$", views.HomePage.as_view(), name="home"),
    url(r"^test/$", views.TestPage.as_view(), name="test"),
    url(r"^thanks/$", views.ThanksPage.as_view(), name="thanks"),
    url(r"^admin/", admin.site.urls),
    url(r"^accounts/", include("accounts.urls", namespace="accounts")),
    url(r"^accounts/", include("django.contrib.auth.urls")),
    url(r"^journeys/", include("journeys.urls", namespace="journeys")),
    url(r"^notification/", include("notification.urls", namespace="notification")),
]


text:
require 'whois/record/parser/base'
require 'whois/record/parser/base_cocca'

module Whois
  class Record
    class Parser

      # Parser for the whois.nic.ec server.
      #
      # @see Whois::Record::Parser::Example
      #   The Example parser for the list of all available methods.
      #
      class WhoisNicEc < BaseCocca
        property_supported :status do
          if content_for_scanner =~ /Status:\s+(.+?)\n/
            super()
          else
            registrar ? :registered : :available
            # Whois.bug!(ParserError, "Unable to parse status.")
          end
        end
      end

    end
  end
end


text:
require 'rational'

module MTK
  module Lang

    # Defines duration constants using abbreviations for standard rhythm values ('w' for whole note, 'h' for half note, etc).
    #
    # These can be thought of like constants, but in order to support the lower case names,
    # it was necessary to define them as "pseudo constant" methods.
    # Like constants, these methods are available either through the module (MTK::Lang::Durations::q) or
    # via mixin (include MTK::Lang::Durations; q). They are listed under the "Instance Attribute Summary" of this page.
    #
    # These values assume the quarter note is one beat, so you may find they work best with 4/4 and other */4 time signatures
    # (although it's certainly possible to use them with less common time signatures like 5/8).
    #
    # @note Including this module defines a bunch of single-character variables, which may shadow existing variable names.
    #       Just be mindful of what is defined in this module when including it.
    #
    # @see Core::Duration
    # @see Events::Note
    module Durations
      extend MTK::Lang::PseudoConstants

      # @private
      # @!macro [attach] define_duration
      #   $3: $4 beat(s)
      #   @!attribute [r]
      #   @return [MTK::Core::Duration] duration of $4 beat(s)
      def self.define_duration name, value, description, beats
        define_constant name, value
      end

      # whole note
      # @macro [attach] durations.define_duration
      #   @attribute [r]
      #   @return [$2] duration for $1
      define_duration 'w', MTK::Core::Duration[4], 'whole note', 4

      define_duration 'h', MTK::Core::Duration[2], 'half note', 2

      define_duration 'q', MTK::Core::Duration[1], 'quarter note', 1

      define_duration 'e', MTK::Core::Duration[Rational(1,2)], 'eighth note', '1/2'

      define_duration 's', MTK::Core::Duration[Rational(1,4)], 'sixteenth note', '1/4'

      define_duration 'r', MTK::Core::Duration[Rational(1,8)], 'thirty-second note', '1/8'

      define_duration 'x', MTK::Core::Duration[Rational(1,16)], 'sixty-fourth note', '1/16'

      # All "psuedo constants" defined in this module
      DURATIONS = [w, h, q, e, s, r, x].freeze

      # The names of all "psuedo constants" defined in this module
      # @see MTK::Core::Duration::NAMES
      DURATION_NAMES = MTK::Core::Duration::NAMES

    end
  end
end


text:
package spark.api.java

import java.util.{List => JList}
import java.util.Comparator

import scala.Tuple2
import scala.collection.JavaConversions._

import org.apache.hadoop.mapred.JobConf
import org.apache.hadoop.mapred.OutputFormat
import org.apache.hadoop.mapreduce.{OutputFormat => NewOutputFormat}
import org.apache.hadoop.conf.Configuration

import spark.api.java.function.{Function2 => JFunction2}
import spark.api.java.function.{Function => JFunction}
import spark.partial.BoundedDouble
import spark.partial.PartialResult
import spark.OrderedRDDFunctions
import spark.storage.StorageLevel
import spark.HashPartitioner
import spark.Partitioner
import spark.RDD
import spark.SparkContext.rddToPairRDDFunctions

class JavaPairRDD[K, V](val rdd: RDD[(K, V)])(implicit val kManifest: ClassManifest[K],
  implicit val vManifest: ClassManifest[V]) extends JavaRDDLike[(K, V), JavaPairRDD[K, V]] {

  override def wrapRDD(rdd: RDD[(K, V)]): JavaPairRDD[K, V] = JavaPairRDD.fromRDD(rdd)

  override val classManifest: ClassManifest[(K, V)] =
    implicitly[ClassManifest[AnyRef]].asInstanceOf[ClassManifest[Tuple2[K, V]]]

  import JavaPairRDD._

  // Common RDD functions

  /** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
  def cache(): JavaPairRDD[K, V] = new JavaPairRDD[K, V](rdd.cache())

  /**
   * Set this RDD's storage level to persist its values across operations after the first time
   * it is computed. Can only be called once on each RDD.
   */
  def persist(newLevel: StorageLevel): JavaPairRDD[K, V] =
    new JavaPairRDD[K, V](rdd.persist(newLevel))

  // Transformations (return a new RDD)

  /**
   * Return a new RDD containing the distinct elements in this RDD.
   */
  def distinct(): JavaPairRDD[K, V] = new JavaPairRDD[K, V](rdd.distinct())

  /**
   * Return a new RDD containing the distinct elements in this RDD.
   */
  def distinct(numSplits: Int): JavaPairRDD[K, V] = new JavaPairRDD[K, V](rdd.distinct(numSplits))

  /**
   * Return a new RDD containing only the elements that satisfy a predicate.
   */
  def filter(f: Function[(K, V), java.lang.Boolean]): JavaPairRDD[K, V] =
    new JavaPairRDD[K, V](rdd.filter(x => f(x).booleanValue()))

  /**
   * Return a sampled subset of this RDD.
   */
  def sample(withReplacement: Boolean, fraction: Double, seed: Int): JavaPairRDD[K, V] =
    new JavaPairRDD[K, V](rdd.sample(withReplacement, fraction, seed))

  /**
   * Return the union of this RDD and another one. Any identical elements will appear multiple
   * times (use `.distinct()` to eliminate them).
   */
  def union(other: JavaPairRDD[K, V]): JavaPairRDD[K, V] =
    new JavaPairRDD[K, V](rdd.union(other.rdd))

  // first() has to be overridden here so that the generated method has the signature
  // 'public scala.Tuple2 first()'; if the trait's definition is used,
  // then the method has the signature 'public java.lang.Object first()',
  // causing NoSuchMethodErrors at runtime.
  override def first(): (K, V) = rdd.first()

  // Pair RDD functions

  /**
   * Generic function to combine the elements for each key using a custom set of aggregation
   * functions. Turns a JavaPairRDD[(K, V)] into a result of type JavaPairRDD[(K, C)], for a
   * "combined type" C * Note that V and C can be different -- for example, one might group an
   * RDD of type (Int, Int) into an RDD of type (Int, List[Int]). Users provide three
   * functions:
   *
   * - `createCombiner`, which turns a V into a C (e.g., creates a one-element list)
   * - `mergeValue`, to merge a V into a C (e.g., adds it to the end of a list)
   * - `mergeCombiners`, to combine two C's into a single one.
   *
   * In addition, users can control the partitioning of the output RDD, and whether to perform
   * map-side aggregation (if a mapper can produce multiple items with the same key).
   */
  def combineByKey[C](createCombiner: Function[V, C],
    mergeValue: JFunction2[C, V, C],
    mergeCombiners: JFunction2[C, C, C],
    partitioner: Partitioner): JavaPairRDD[K, C] = {
    implicit val cm: ClassManifest[C] =
      implicitly[ClassManifest[AnyRef]].asInstanceOf[ClassManifest[C]]
    fromRDD(rdd.combineByKey(
      createCombiner,
      mergeValue,
      mergeCombiners,
      partitioner
    ))
  }

  /**
   * Simplified version of combineByKey that hash-partitions the output RDD.
   */
  def combineByKey[C](createCombiner: JFunction[V, C],
    mergeValue: JFunction2[C, V, C],
    mergeCombiners: JFunction2[C, C, C],
    numSplits: Int): JavaPairRDD[K, C] =
    combineByKey(createCombiner, mergeValue, mergeCombiners, new HashPartitioner(numSplits))

  /**
   * Merge the values for each key using an associative reduce function. This will also perform
   * the merging locally on each mapper before sending results to a reducer, similarly to a
   * "combiner" in MapReduce.
   */
  def reduceByKey(partitioner: Partitioner, func: JFunction2[V, V, V]): JavaPairRDD[K, V] =
    fromRDD(rdd.reduceByKey(partitioner, func))

  /**
   * Merge the values for each key using an associative reduce function, but return the results
   * immediately to the master as a Map. This will also perform the merging locally on each mapper
   * before sending results to a reducer, similarly to a "combiner" in MapReduce.
   */
  def reduceByKeyLocally(func: JFunction2[V, V, V]): java.util.Map[K, V] =
    mapAsJavaMap(rdd.reduceByKeyLocally(func))

  /** Count the number of elements for each key, and return the result to the master as a Map. */
  def countByKey(): java.util.Map[K, Long] = mapAsJavaMap(rdd.countByKey())

  /**
   * (Experimental) Approximate version of countByKey that can return a partial result if it does
   * not finish within a timeout.
   */
  def countByKeyApprox(timeout: Long): PartialResult[java.util.Map[K, BoundedDouble]] =
    rdd.countByKeyApprox(timeout).map(mapAsJavaMap)

  /**
   * (Experimental) Approximate version of countByKey that can return a partial result if it does
   * not finish within a timeout.
   */
  def countByKeyApprox(timeout: Long, confidence: Double = 0.95)
  : PartialResult[java.util.Map[K, BoundedDouble]] =
    rdd.countByKeyApprox(timeout, confidence).map(mapAsJavaMap)

  /**
   * Merge the values for each key using an associative reduce function. This will also perform
   * the merging locally on each mapper before sending results to a reducer, similarly to a
   * "combiner" in MapReduce. Output will be hash-partitioned with numSplits splits.
   */
  def reduceByKey(func: JFunction2[V, V, V], numSplits: Int): JavaPairRDD[K, V] =
    fromRDD(rdd.reduceByKey(func, numSplits))

  /**
   * Group the values for each key in the RDD into a single sequence. Allows controlling the
   * partitioning of the resulting key-value pair RDD by passing a Partitioner.
   */
  def groupByKey(partitioner: Partitioner): JavaPairRDD[K, JList[V]] =
    fromRDD(groupByResultToJava(rdd.groupByKey(partitioner)))

  /**
   * Group the values for each key in the RDD into a single sequence. Hash-partitions the
   * resulting RDD with into `numSplits` partitions.
   */
  def groupByKey(numSplits: Int): JavaPairRDD[K, JList[V]] =
    fromRDD(groupByResultToJava(rdd.groupByKey(numSplits)))

  /**
   * Return a copy of the RDD partitioned using the specified partitioner. If `mapSideCombine`
   * is true, Spark will group values of the same key together on the map side before the
   * repartitioning, to only send each key over the network once. If a large number of
   * duplicated keys are expected, and the size of the keys are large, `mapSideCombine` should
   * be set to true.
   */
  def partitionBy(partitioner: Partitioner): JavaPairRDD[K, V] =
    fromRDD(rdd.partitionBy(partitioner))

  /**
   * Merge the values for each key using an associative reduce function. This will also perform
   * the merging locally on each mapper before sending results to a reducer, similarly to a
   * "combiner" in MapReduce.
   */
  def join[W](other: JavaPairRDD[K, W], partitioner: Partitioner): JavaPairRDD[K, (V, W)] =
    fromRDD(rdd.join(other, partitioner))

  /**
   * Perform a left outer join of `this` and `other`. For each element (k, v) in `this`, the
   * resulting RDD will either contain all pairs (k, (v, Some(w))) for w in `other`, or the
   * pair (k, (v, None)) if no elements in `other` have key k. Uses the given Partitioner to
   * partition the output RDD.
   */
  def leftOuterJoin[W](other: JavaPairRDD[K, W], partitioner: Partitioner)
  : JavaPairRDD[K, (V, Option[W])] =
    fromRDD(rdd.leftOuterJoin(other, partitioner))

  /**
   * Perform a right outer join of `this` and `other`. For each element (k, w) in `other`, the
   * resulting RDD will either contain all pairs (k, (Some(v), w)) for v in `this`, or the
   * pair (k, (None, w)) if no elements in `this` have key k. Uses the given Partitioner to
   * partition the output RDD.
   */
  def rightOuterJoin[W](other: JavaPairRDD[K, W], partitioner: Partitioner)
  : JavaPairRDD[K, (Option[V], W)] =
    fromRDD(rdd.rightOuterJoin(other, partitioner))

  /**
   * Simplified version of combineByKey that hash-partitions the resulting RDD using the default
   * parallelism level.
   */
  def combineByKey[C](createCombiner: JFunction[V, C],
    mergeValue: JFunction2[C, V, C],
    mergeCombiners: JFunction2[C, C, C]): JavaPairRDD[K, C] = {
    implicit val cm: ClassManifest[C] =
      implicitly[ClassManifest[AnyRef]].asInstanceOf[ClassManifest[C]]
    fromRDD(combineByKey(createCombiner, mergeValue, mergeCombiners))
  }

  /**
   * Merge the values for each key using an associative reduce function. This will also perform
   * the merging locally on each mapper before sending results to a reducer, similarly to a
   * "combiner" in MapReduce. Output will be hash-partitioned with the default parallelism level.
   */
  def reduceByKey(func: JFunction2[V, V, V]): JavaPairRDD[K, V] = {
    val partitioner = rdd.defaultPartitioner(rdd)
    fromRDD(reduceByKey(partitioner, func))
  }

  /**
   * Group the values for each key in the RDD into a single sequence. Hash-partitions the
   * resulting RDD with the default parallelism level.
   */
  def groupByKey(): JavaPairRDD[K, JList[V]] =
    fromRDD(groupByResultToJava(rdd.groupByKey()))

  /**
   * Return an RDD containing all pairs of elements with matching keys in `this` and `other`. Each
   * pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in `this` and
   * (k, v2) is in `other`. Performs a hash join across the cluster.
   */
  def join[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (V, W)] =
    fromRDD(rdd.join(other))

  /**
   * Return an RDD containing all pairs of elements with matching keys in `this` and `other`. Each
   * pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in `this` and
   * (k, v2) is in `other`. Performs a hash join across the cluster.
   */
  def join[W](other: JavaPairRDD[K, W], numSplits: Int): JavaPairRDD[K, (V, W)] =
    fromRDD(rdd.join(other, numSplits))

  /**
   * Perform a left outer join of `this` and `other`. For each element (k, v) in `this`, the
   * resulting RDD will either contain all pairs (k, (v, Some(w))) for w in `other`, or the
   * pair (k, (v, None)) if no elements in `other` have key k. Hash-partitions the output
   * using the default level of parallelism.
   */
  def leftOuterJoin[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (V, Option[W])] =
    fromRDD(rdd.leftOuterJoin(other))

  /**
   * Perform a left outer join of `this` and `other`. For each element (k, v) in `this`, the
   * resulting RDD will either contain all pairs (k, (v, Some(w))) for w in `other`, or the
   * pair (k, (v, None)) if no elements in `other` have key k. Hash-partitions the output
   * into `numSplits` partitions.
   */
  def leftOuterJoin[W](other: JavaPairRDD[K, W], numSplits: Int): JavaPairRDD[K, (V, Option[W])] =
    fromRDD(rdd.leftOuterJoin(other, numSplits))

  /**
   * Perform a right outer join of `this` and `other`. For each element (k, w) in `other`, the
   * resulting RDD will either contain all pairs (k, (Some(v), w)) for v in `this`, or the
   * pair (k, (None, w)) if no elements in `this` have key k. Hash-partitions the resulting
   * RDD using the default parallelism level.
   */
  def rightOuterJoin[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (Option[V], W)] =
    fromRDD(rdd.rightOuterJoin(other))

  /**
   * Perform a right outer join of `this` and `other`. For each element (k, w) in `other`, the
   * resulting RDD will either contain all pairs (k, (Some(v), w)) for v in `this`, or the
   * pair (k, (None, w)) if no elements in `this` have key k. Hash-partitions the resulting
   * RDD into the given number of partitions.
   */
  def rightOuterJoin[W](other: JavaPairRDD[K, W], numSplits: Int): JavaPairRDD[K, (Option[V], W)] =
    fromRDD(rdd.rightOuterJoin(other, numSplits))

  /**
   * Return the key-value pairs in this RDD to the master as a Map.
   */
  def collectAsMap(): java.util.Map[K, V] = mapAsJavaMap(rdd.collectAsMap())

  /**
   * Pass each value in the key-value pair RDD through a map function without changing the keys;
   * this also retains the original RDD's partitioning.
   */
  def mapValues[U](f: Function[V, U]): JavaPairRDD[K, U] = {
    implicit val cm: ClassManifest[U] =
      implicitly[ClassManifest[AnyRef]].asInstanceOf[ClassManifest[U]]
    fromRDD(rdd.mapValues(f))
  }

  /**
   * Pass each value in the key-value pair RDD through a flatMap function without changing the
   * keys; this also retains the original RDD's partitioning.
   */
  def flatMapValues[U](f: JFunction[V, java.lang.Iterable[U]]): JavaPairRDD[K, U] = {
    import scala.collection.JavaConverters._
    def fn = (x: V) => f.apply(x).asScala
    implicit val cm: ClassManifest[U] =
      implicitly[ClassManifest[AnyRef]].asInstanceOf[ClassManifest[U]]
    fromRDD(rdd.flatMapValues(fn))
  }

  /**
   * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the
   * list of values for that key in `this` as well as `other`.
   */
  def cogroup[W](other: JavaPairRDD[K, W], partitioner: Partitioner)
  : JavaPairRDD[K, (JList[V], JList[W])] =
    fromRDD(cogroupResultToJava(rdd.cogroup(other, partitioner)))

  /**
   * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a
   * tuple with the list of values for that key in `this`, `other1` and `other2`.
   */
  def cogroup[W1, W2](other1: JavaPairRDD[K, W1], other2: JavaPairRDD[K, W2], partitioner: Partitioner)
  : JavaPairRDD[K, (JList[V], JList[W1], JList[W2])] =
    fromRDD(cogroupResult2ToJava(rdd.cogroup(other1, other2, partitioner)))

  /**
   * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the
   * list of values for that key in `this` as well as `other`.
   */
  def cogroup[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (JList[V], JList[W])] =
    fromRDD(cogroupResultToJava(rdd.cogroup(other)))

  /**
   * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a
   * tuple with the list of values for that key in `this`, `other1` and `other2`.
   */
  def cogroup[W1, W2](other1: JavaPairRDD[K, W1], other2: JavaPairRDD[K, W2])
  : JavaPairRDD[K, (JList[V], JList[W1], JList[W2])] =
    fromRDD(cogroupResult2ToJava(rdd.cogroup(other1, other2)))

  /**
   * For each key k in `this` or `other`, return a resulting RDD that contains a tuple with the
   * list of values for that key in `this` as well as `other`.
   */
  def cogroup[W](other: JavaPairRDD[K, W], numSplits: Int): JavaPairRDD[K, (JList[V], JList[W])]
  = fromRDD(cogroupResultToJava(rdd.cogroup(other, numSplits)))

  /**
   * For each key k in `this` or `other1` or `other2`, return a resulting RDD that contains a
   * tuple with the list of values for that key in `this`, `other1` and `other2`.
   */
  def cogroup[W1, W2](other1: JavaPairRDD[K, W1], other2: JavaPairRDD[K, W2], numSplits: Int)
  : JavaPairRDD[K, (JList[V], JList[W1], JList[W2])] =
    fromRDD(cogroupResult2ToJava(rdd.cogroup(other1, other2, numSplits)))

  /** Alias for cogroup. */
  def groupWith[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (JList[V], JList[W])] =
    fromRDD(cogroupResultToJava(rdd.groupWith(other)))

  /** Alias for cogroup. */
  def groupWith[W1, W2](other1: JavaPairRDD[K, W1], other2: JavaPairRDD[K, W2])
  : JavaPairRDD[K, (JList[V], JList[W1], JList[W2])] =
    fromRDD(cogroupResult2ToJava(rdd.groupWith(other1, other2)))

  /**
   * Return the list of values in the RDD for key `key`. This operation is done efficiently if the
   * RDD has a known partitioner by only searching the partition that the key maps to.
   */
  def lookup(key: K): JList[V] = seqAsJavaList(rdd.lookup(key))

  /** Output the RDD to any Hadoop-supported file system. */
  def saveAsHadoopFile[F <: OutputFormat[_, _]](
    path: String,
    keyClass: Class[_],
    valueClass: Class[_],
    outputFormatClass: Class[F],
    conf: JobConf) {
    rdd.saveAsHadoopFile(path, keyClass, valueClass, outputFormatClass, conf)
  }

  /** Output the RDD to any Hadoop-supported file system. */
  def saveAsHadoopFile[F <: OutputFormat[_, _]](
    path: String,
    keyClass: Class[_],
    valueClass: Class[_],
    outputFormatClass: Class[F]) {
    rdd.saveAsHadoopFile(path, keyClass, valueClass, outputFormatClass)
  }

  /** Output the RDD to any Hadoop-supported file system. */
  def saveAsNewAPIHadoopFile[F <: NewOutputFormat[_, _]](
    path: String,
    keyClass: Class[_],
    valueClass: Class[_],
    outputFormatClass: Class[F],
    conf: Configuration) {
    rdd.saveAsNewAPIHadoopFile(path, keyClass, valueClass, outputFormatClass, conf)
  }

  /** Output the RDD to any Hadoop-supported file system. */
  def saveAsNewAPIHadoopFile[F <: NewOutputFormat[_, _]](
    path: String,
    keyClass: Class[_],
    valueClass: Class[_],
    outputFormatClass: Class[F]) {
    rdd.saveAsNewAPIHadoopFile(path, keyClass, valueClass, outputFormatClass)
  }

  /**
   * Output the RDD to any Hadoop-supported storage system, using a Hadoop JobConf object for
   * that storage system. The JobConf should set an OutputFormat and any output paths required
   * (e.g. a table name to write to) in the same way as it would be configured for a Hadoop
   * MapReduce job.
   */
  def saveAsHadoopDataset(conf: JobConf) {
    rdd.saveAsHadoopDataset(conf)
  }

  /**
   * Sort the RDD by key, so that each partition contains a sorted range of the elements in
   * ascending order. Calling `collect` or `save` on the resulting RDD will return or output an
   * ordered list of records (in the `save` case, they will be written to multiple `part-X` files
   * in the filesystem, in order of the keys).
   */
  def sortByKey(): JavaPairRDD[K, V] = sortByKey(true)

  /**
   * Sort the RDD by key, so that each partition contains a sorted range of the elements. Calling
   * `collect` or `save` on the resulting RDD will return or output an ordered list of records
   * (in the `save` case, they will be written to multiple `part-X` files in the filesystem, in
   * order of the keys).
   */
  def sortByKey(ascending: Boolean): JavaPairRDD[K, V] = {
    val comp = com.google.common.collect.Ordering.natural().asInstanceOf[Comparator[K]]
    sortByKey(comp, true)
  }

  /**
   * Sort the RDD by key, so that each partition contains a sorted range of the elements. Calling
   * `collect` or `save` on the resulting RDD will return or output an ordered list of records
   * (in the `save` case, they will be written to multiple `part-X` files in the filesystem, in
   * order of the keys).
   */
  def sortByKey(comp: Comparator[K]): JavaPairRDD[K, V] = sortByKey(comp, true)

  /**
   * Sort the RDD by key, so that each partition contains a sorted range of the elements. Calling
   * `collect` or `save` on the resulting RDD will return or output an ordered list of records
   * (in the `save` case, they will be written to multiple `part-X` files in the filesystem, in
   * order of the keys).
   */
  def sortByKey(comp: Comparator[K], ascending: Boolean): JavaPairRDD[K, V] = {
    class KeyOrdering(val a: K) extends Ordered[K] {
      override def compare(b: K) = comp.compare(a, b)
    }
    implicit def toOrdered(x: K): Ordered[K] = new KeyOrdering(x)
    fromRDD(new OrderedRDDFunctions(rdd).sortByKey(ascending))
  }
}

object JavaPairRDD {
  def groupByResultToJava[K, T](rdd: RDD[(K, Seq[T])])(implicit kcm: ClassManifest[K],
    vcm: ClassManifest[T]): RDD[(K, JList[T])] =
    rddToPairRDDFunctions(rdd).mapValues(seqAsJavaList _)

  def cogroupResultToJava[W, K, V](rdd: RDD[(K, (Seq[V], Seq[W]))])(implicit kcm: ClassManifest[K],
    vcm: ClassManifest[V]): RDD[(K, (JList[V], JList[W]))] = rddToPairRDDFunctions(rdd).mapValues((x: (Seq[V],
    Seq[W])) => (seqAsJavaList(x._1), seqAsJavaList(x._2)))

  def cogroupResult2ToJava[W1, W2, K, V](rdd: RDD[(K, (Seq[V], Seq[W1],
    Seq[W2]))])(implicit kcm: ClassManifest[K]) : RDD[(K, (JList[V], JList[W1],
    JList[W2]))] = rddToPairRDDFunctions(rdd).mapValues(
    (x: (Seq[V], Seq[W1], Seq[W2])) => (seqAsJavaList(x._1),
      seqAsJavaList(x._2),
      seqAsJavaList(x._3)))

  def fromRDD[K: ClassManifest, V: ClassManifest](rdd: RDD[(K, V)]): JavaPairRDD[K, V] =
    new JavaPairRDD[K, V](rdd)

  implicit def toRDD[K, V](rdd: JavaPairRDD[K, V]): RDD[(K, V)] = rdd.rdd
}


text:
struct nf_conn_labels {
	u8 words;
	unsigned long bits[];
};

static inline struct nf_conn_labels *nf_ct_labels_find(const struct nf_conn *ct)
{
#ifdef CONFIG_NF_CONNTRACK_LABELS
	return nf_ct_ext_find(ct, NF_CT_EXT_LABELS);
#else
	return NULL;
#endif
}

static inline struct nf_conn_labels *nf_ct_labels_ext_add(struct nf_conn *ct)
{
#ifdef CONFIG_NF_CONNTRACK_LABELS
	struct nf_conn_labels *cl_ext;
	struct net *net = nf_ct_net(ct);
	u8 words;

	words = ACCESS_ONCE(net->ct.label_words);
	if (words == 0)
		return NULL;

	cl_ext = nf_ct_ext_add_length(ct, NF_CT_EXT_LABELS,
				      words * sizeof(long), GFP_ATOMIC);
	if (cl_ext != NULL)
		cl_ext->words = words;

	return cl_ext;
#else
	return NULL;
#endif
}

int nf_connlabel_set(struct nf_conn *ct, u16 bit);

int nf_connlabels_replace(struct nf_conn *ct,
			  const u32 *data, const u32 *mask, unsigned int words);

#ifdef CONFIG_NF_CONNTRACK_LABELS
int nf_conntrack_labels_init(void);
void nf_conntrack_labels_fini(void);
int nf_connlabels_get(struct net *net, unsigned int bit);
void nf_connlabels_put(struct net *net);
#else
static inline int nf_conntrack_labels_init(void) { return 0; }
static inline void nf_conntrack_labels_fini(void) {}
static inline int nf_connlabels_get(struct net *net, unsigned int bit) { return 0; }
static inline void nf_connlabels_put(struct net *net) {}
#endif


text:
"""test cases of anyconfig.cli.main with multiple inputs.
"""
from . import collectors, test_base

class Collector(collectors.MultiDataCollector):
    kind = 'multi_inputs'

class TestCase(test_base.BaseTestCase):
    collector = Collector()

    def make_args(self, tdata):  # pylint: disable=no-self-use
        """Make arguments to run cli.main.
        """
        return ['anyconfig_cli'] + tdata.opts + [str(p) for p in tdata.inputs]

# vim:sw=4:ts=4:et:


text:
<!SLIDE>
# Common Integration Gateway
* Upgrade Independent of Other Instances
* Dedicated WebLogic Heap to Integrations
* Central Management of Node Definitions
* Shared Configuration File
* 8.53+ Queueing Changes in WebLogic


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

<title>F-Index</title>
<meta name="date" content="2014-04-20">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G I J N O P Q R S T U V W Z

F

first(Queryable.Matcher<T>) - Method in class za.co.neilson.collections.queryable.Queryable

ForeignKey - Annotation Type in za.co.neilson.sqlite.orm.annotations

 Designates an ObjectModel property as a foreign key reference to another
 ObjectModel.

foreignKeyParentColumn - Variable in class za.co.neilson.sqlite.orm.ObjectModelColumn

foreignKeyParentTable - Variable in class za.co.neilson.sqlite.orm.ObjectModelColumn

A C D E F G I J N O P Q R S T U V W Z

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
set -euo pipefail
# This script is run in the VM each time you run `vagrant-spk dev`.  This is
# the ideal place to invoke anything which is normally part of your app's build
# process - transforming the code in your repository into the collection of files
# which can actually run the service in production
#
# Some examples:
#
#   * For a C/C++ application, calling
#       ./configure && make && make install
#   * For a Python application, creating a virtualenv and installing
#     app-specific package dependencies:
#       virtualenv /opt/app/env
#       /opt/app/env/bin/pip install -r /opt/app/requirements.txt
#   * Building static assets from .less or .sass, or bundle and minify JS
#   * Collecting various build artifacts or assets into a deployment-ready
#     directory structure

# By default, this script does nothing.  You'll have to modify it as
# appropriate for your application.
cd /opt/app
npm install
gulp build


text:
<?php

namespace Firebrand\Hail\Models;

use Firebrand\Hail\Api\Client;
use Firebrand\Hail\Pages\HailPage;
use Firebrand\Hail\Pages\HailPageController;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Core\Convert;
use SilverStripe\Forms\LiteralField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\Connect\MySQLSchemaManager;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\Security\Permission;

/**
 * Hail Article DataObject
 *
 * @package silverstripe-hail
 * @author Maxime Rainville, Firebrand
 * @author Marc Espiard, Firebrand
 * @version 2.0
 *
 * @property string $Title
 * @property string $Author
 * @property string $Lead
 * @property string $Content
 * @property string $Location
 * @property string $Status Article status in Hail
 * @property string $Updated Date and time of last update in Hail
 * @property double $Rating
 * @property boolean $Flagged
 * @property string $Date Publication date and time in Hail
 * @property string $HailURL
 *
 * @method Image HeroImage()
 * @method Video HeroVideo()
 * @method ManyManyList PublicTags()
 * @method ManyManyList PrivateTags()
 * @method ManyManyList Attachments()
 * @method ManyManyList ImageGallery()
 * @method ManyManyList VideoGallery()
 */
class Article extends ApiObject
{
    /**
     * @inheritdoc
     */
    public static $object_endpoint = "articles";
    /**
     * @inheritdoc
     */
    public static $object_parameters = [
        'short_gallery_limit' => 3
    ];
    /**
     * @inheritdoc
     */
    protected static $api_map = [
        'Title' => 'title',
        'Author' => 'author',
        'Lead' => 'lead',
        'Location' => 'location',
        'Status' => 'status',
        'Created' => 'date',
        'Updated' => 'updated_date',
        'Rating' => 'average_rating',
        'Flagged' => 'flagged',
        'Date' => 'date',
        'HailURL' => 'hail_url',
    ];
    private static $table_name = "HailArticle";
    private static $db = [
        'Title' => 'Varchar',
        'Author' => 'Varchar',

        'Lead' => 'HTMLText',
        'Content' => 'HTMLText',
        'Date' => 'Datetime',
        'Location' => 'Varchar',
        'Status' => 'Varchar',

        'Updated' => 'Datetime',
        'Rating' => 'Double',
        'Flagged' => 'Boolean',
        'HailURL' => 'Varchar'
    ];
    private static $default_sort = "Date DESC";
    private static $has_one = [
        'HeroImage' => 'Firebrand\Hail\Models\Image',
        'HeroVideo' => 'Firebrand\Hail\Models\Video',
    ];
    private static $belongs_many_many = [
        'PublicTags' => 'Firebrand\Hail\Models\PublicTag',
        'PrivateTags' => 'Firebrand\Hail\Models\PrivateTag',
        'Attachments' => 'Firebrand\Hail\Models\Attachment'
    ];
    private static $many_many = [
        'ImageGallery' => 'Firebrand\Hail\Models\Image',
        'VideoGallery' => 'Firebrand\Hail\Models\Video',
    ];
    private static $summary_fields = [
        'Organisation.Title' => 'Hail Organisation',
        'HailID' => 'Hail ID',
        'Title' => 'Title',
        'Author' => 'Author',
        'Lead' => 'Lead',
        'Date' => 'Date'
    ];
    private static $indexes = [
        'SearchFields' => [
            'type' => 'fulltext',
            'columns' => ['Author', 'Title', 'Lead', 'Content'],
        ]
    ];
    private static $create_table_options = [
        MySQLSchemaManager::ID => 'ENGINE=MyISAM'
    ];

    /**
     * @inheritdoc
     */
    public function canDelete($member = false)
    {
        if(Permission::checkMember($member, 'ADMIN')){
            return true;
        }

        return parent::canDelete($member);
    }

    /**
     * @inheritdoc
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        // Show relations, SilverStripe can't do Read Only Gridfield by default yet
        $this->makeRecordViewer($fields, "Public Tags", $this->PublicTags());
        $this->makeRecordViewer($fields, "Private Tags", $this->PrivateTags());
        $this->makeRecordViewer($fields, "Image Gallery", $this->ImageGallery());
        $this->makeRecordViewer($fields, "Video Gallery", $this->VideoGallery());
        $this->makeRecordViewer($fields, "Attachments", $this->Attachments(), 'Firebrand\Hail\Forms\GridFieldAttachmentDownloadButton');

        // Display a thumbnail of the hero image
        if ($this->HeroImage()->ID != 0) {
            $heroField = new LiteralField(
                "HeroImage",
                $this->HeroImage()->getThumbnailField("Hero Image")
            );
            $fields->replaceField('HeroImageID', $heroField);
        } else {
            $fields->removeByName('HeroImageID');
        }

        // Display a thumbnail of the hero image
        if ($this->HeroVideo()->ID != 0) {
            $heroField = new LiteralField(
                "HeroVideo",
                $this->HeroVideo()->getThumbnailField("Hero Video")
            );
            $fields->replaceField('HeroVideoID', $heroField);
        } else {
            $fields->removeByName('HeroVideoID');
        }

        return $fields;
    }

    /**
     * @inheritdoc
     */
    protected function importing($data)
    {
        if (!empty($data['body'])) {
            $this->Content = $data['body'];
        }

        $this->processPublicTags($data['tags']);
        $this->processPrivateTags($data['private_tags']);
        $this->processHeroImage($data['hero_image']);
        $this->processHeroVideo($data['hero_video']);
        $this->processAttachments($data['attachments']);

        //IF we have an image gallery, fetch every images
        if (is_array($data['short_gallery']) && count($data['short_gallery']) > 0) {
            $this->fetchImages();
        }
        //IF we have an video gallery, fetch every videos
        if (is_array($data['short_video_gallery']) && count($data['short_video_gallery']) > 0) {
            $this->fetchVideos();
        }
    }

    /**
     * Fetch the image gallery of this article from the Hail API
     *
     * @return void
     * @throws
     */
    public function fetchImages()
    {
        try {
            $api_client = new Client();
            $list = $api_client->getImagesByArticles($this->HailID);
        } catch (\Exception $ex) {
            return;
        }

        $hailIdList = [];

        // Clean before importing
        $this->ImageGallery()->removeAll();

        foreach ($list as $hailData) {
            // Build up Hail ID list
            $hailIdList[] = $hailData['id'];

            // Check if we can find an existing item.
            $hailObj = Image::get()->filter(['HailID' => $hailData['id']])->First();

            if (!$hailObj) {
                $hailObj = new Image();
            }
            $hailObj->OrganisationID = $this->OrganisationID;
            $hailObj->HailOrgID = $this->HailOrgID;
            $hailObj->HailOrgName = $this->HailOrgName;

            $hailObj->importHailData($hailData);
            $this->ImageGallery()->add($hailObj);
        }
    }

    /**
     * Fetch the video gallery of this article from the Hail API
     *
     * @return void
     * @throws
     */
    public function fetchVideos()
    {
        try {
            $api_client = new Client();
            $list = $api_client->getVideosByArticles($this->HailID);
        } catch (\Exception $ex) {
            return;
        }

        $hailIdList = [];
        // CLean before importing
        $this->VideoGallery()->removeAll();

        foreach ($list as $hailData) {
            // Build up Hail ID list
            $hailIdList[] = $hailData['id'];

            // Check if we can find an existing item.
            $hailObj = Video::get()->filter(['HailID' => $hailData['id']])->First();
            if (!$hailObj) {
                $hailObj = new Video();
            }
            $hailObj->OrganisationID = $this->OrganisationID;
            $hailObj->HailOrgID = $this->HailOrgID;
            $hailObj->HailOrgName = $this->HailOrgName;

            $hailObj->importHailData($hailData);
            $this->VideoGallery()->add($hailObj);
        }
    }

    /**
     * Return the Article link for the current HailPageController
     *
     * @return string
     */
    public function Link()
    {
        $ctrl = Controller::curr();
        if ($ctrl instanceof HailPageController) {
            $link = $ctrl->Link();
        } else {
            //If outside HailPageController try to find the first Hail Page
            $page = HailPage::get()->first();
            if (!empty($page)) {
                $link = $page->Link();
            }
        }

        if (!isset($link)) {
            return "";
        }

        return $link . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title);
    }

    /**
     * Return the Article link for specified HailPage
     *
     * @param HailPage $page
     * @return string
     */
    public function getLinkForPage($page)
    {
        return $page->Link() . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title);
    }

    /**
     * Return the absolute Article link
     *
     * @return string
     */
    public function AbsoluteLink()
    {
        return Director::absoluteURL($this->Link());
    }

    /**
     * Helper to return the object type
     *
     * @return string
     */
    public function getType()
    {
        return "article";
    }

    /**
     * Helper to return the title from the breadcrumbs
     *
     * @return string
     */
    public function getMenuTitle()
    {
        return $this->Title;
    }

    /**
     * Return the placeholder HeroImage link
     *
     * @return string
     */
    public function getPlaceHolderHero()
    {
        return '/' . RESOURCES_DIR . '/' . HAIL_DIR . '/client/dist/images/placeholder-hero.jpg';
    }

    /**
     * List of this Article's public tag names separated by spaces.
     *
     * Suitable to be used as CSS classes.
     *
     * @return string
     */
    public function getTagList()
    {
        $string = '';
        foreach ($this->PublicTags() as $t) {
            $string .= Convert::raw2url($t->Name) . ' ';
        }
        return trim($string);
    }

    /**
     * List of this Article's images
     *
     * Includes the Hero Image
     *
     * @return ArrayList
     */
    public function getAllImages()
    {
        $images = new ArrayList();
        if ($this->hasHeroImage()) {
            $images->push($this->HeroImage());
        }
        if ($this->hasGalleryImages()) {
            $images->merge($this->ImageGallery());
        }
        $images->removeDuplicates('HailID');

        return $images;
    }

    /**
     * List of this Article's videos
     *
     * Includes the Hero Video
     *
     * @return ArrayList
     */
    public function getAllVideos()
    {
        $videos = new ArrayList();
        if ($this->hasHeroVideo()) {
            $videos->push($this->HeroVideo());
        }
        if ($this->hasGalleryVideos()) {
            $videos->merge($this->VideoGallery());
        }
        $videos->removeDuplicates('HailID');

        return $videos;
    }

    /**
     * Checks if Article has a HeroImage
     *
     * @return boolean
     */
    public function hasHeroImage()
    {
        return $this->HeroImage()->ID != 0;
    }

    /**
     * Checks if Article has a HeroVideo
     *
     * @return boolean
     */
    public function hasHeroVideo()
    {
        return $this->HeroVideo()->ID != 0;
    }

    /**
     * Checks if Article has an Image Gallery
     *
     * @return boolean
     */
    public function hasGalleryImages()
    {
        return $this->ImageGallery()->count() > 0;
    }

    /**
     * Checks if Article has a Video Gallery
     *
     * @return boolean
     */
    public function hasGalleryVideos()
    {
        return $this->VideoGallery()->count() > 0;
    }

    /**
     * Checks if Article has any Images attached (Hero and / or Gallery)
     *
     * @return boolean
     */
    public function hasImages()
    {
        return $this->hasHeroImage() || $this->hasGalleryImages();
    }

    /**
     * Checks if Article has any Videos attached (Hero and / or Gallery)
     *
     * @return boolean
     */
    public function hasVideos()
    {
        return $this->hasHeroVideo() || $this->hasGalleryVideos();
    }

    /**
     * Returns hero image to be added to article sitemap when googlesitemap module is installed
     *
     * @return Image|null
     */
    public function ImagesForSitemap()
    {
        if ($this->hasHeroImage()) {
            return $this->HeroImage();
        }

        return null;
    }
}


text:
<?
$config['error_prefix'] = '
<button type="button" class="close" data-dismiss="alert" aria-label="Закрыть">×</button>';
$config['error_suffix'] = '
';
?>


text:
package apps

import (
	"fmt"
	"strings"

	"github.com/dokku/dokku/plugins/common"
)

// ReportSingleApp is an internal function that displays the app report for one or more apps
func ReportSingleApp(appName string, format string, infoFlag string) error {
	if err := common.VerifyAppName(appName); err != nil {
		return err
	}

	flags := map[string]common.ReportFunc{
		"--app-created-at":             reportCreatedAt,
		"--app-deploy-source":          reportDeploySource,
		"--app-deploy-source-metadata": reportDeploySourceMetadata,
		"--app-dir":                    reportDir,
		"--app-locked":                 reportLocked,
	}

	flagKeys := []string{}
	for flagKey := range flags {
		flagKeys = append(flagKeys, flagKey)
	}

	trimPrefix := false
	uppercaseFirstCharacter := true
	infoFlags := common.CollectReport(appName, infoFlag, flags)
	return common.ReportSingleApp("app", appName, infoFlag, infoFlags, flagKeys, format, trimPrefix, uppercaseFirstCharacter)
}

func reportCreatedAt(appName string) string {
	createdAt, err := common.PropertyListGet("apps", appName, "created-at")
	if err != nil {
		return ""
	}
	return fmt.Sprint(strings.Join(createdAt, ","))
}

func reportDeploySource(appName string) string {
	return common.PropertyGet("apps", appName, "deploy-source")
}

func reportDeploySourceMetadata(appName string) string {
	return common.PropertyGet("apps", appName, "deploy-source-metadata")
}

func reportDir(appName string) string {
	return common.AppRoot(appName)
}

func reportLocked(appName string) string {
	locked := "false"
	if appIsLocked(appName) {
		locked = "true"
	}

	return locked
}


text:
layout: post
title: "muzyczne co nieco: żeglarsko ze skrzypcami"
date: 2014-12-20 21:00:00
category: muzyczne-co-nieco
tags: [muzyka, szanty, piosenka żeglarska]

description: "Piosenki żeglarskie i szanty bywają bardzo różne. Bywa ostro, bywa bardzo delikatnie, bywa romantycznie, bywa jakoś-tam. Dzisiaj trafiłem na coś, na co raczej rzadko trafia się przy piosence związanej z głębszą wodą."
excerpt: ""

---

{% include JB/setup %}

Piosenki żeglarskie i szanty bywają bardzo różne. Bywa ostro, bywa bardzo delikatnie, bywa romantycznie, bywa jakoś-tam. Dzisiaj trafiłem na coś, na co raczej rzadko trafia się przy piosence związanej z głębszą wodą. Przed Państwem Fiddler's Green w wykonaniu wokalowo-gitarowo-skrzypcowym. Tym nowym, ciekawym elementem są właśnie skrzypce, oto i one:

<iframe width="560" height="315" src="//www.youtube.com/embed/UcPSzygqhd0" frameborder="0" allowfullscreen="allowfullscreen"></iframe>


text:
<?php

namespace MediaBinBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Tools\Pagination\Paginator;
use MediaBinBundle\Model\BinInterface;

class BinRepository extends EntityRepository
{
    public function getExpiredBin($limit = 10)
    {
        $expireDate = new \DateTime();
        // Keep bin during 7 days after expiration
        $expireDate->add(new \DateInterval('P7D'));

        return $this->createQueryBuilder('b')
            ->where('b.expireAt < :expire')
            ->setParameter('expire', $expireDate)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }

    public function getLatestsPublicBin($offset = 0, $limit = 10)
    {
        $queryBuilder = $this->createQueryBuilder('b')
            ->where('b.expireAt > :expire')
            ->andWhere('b.visibility = :visibility')
            ->setParameter('expire', new \DateTime())
            ->setParameter('visibility', BinInterface::VISIBILITY_PUBLIC)
            ->orderBy('b.id', 'DESC')
            ->setFirstResult($offset)
            ->setMaxResults($limit);

        return new Paginator($queryBuilder, false);
    }

    public function getUserBin($user, $offset = 0, $limit = 10)
    {
        $queryBuilder = $this->createQueryBuilder('b')
            ->where('b.user = :user')
            ->setParameter('user', $user)
            ->orderBy('b.id', 'DESC')
            ->setFirstResult($offset)
            ->setMaxResults($limit);

        return new Paginator($queryBuilder, false);
    }
}


text:
package org.lxp.study.util;

public interface Calculator {
    public int add(int a, int b);
}


text:
package outbound

//go:generate errorgen

import (
	"context"
	"strings"
	"sync"

	"v2ray.com/core"
	"v2ray.com/core/app/proxyman"
	"v2ray.com/core/common"
	"v2ray.com/core/common/errors"
	"v2ray.com/core/features/outbound"
)

// Manager is to manage all outbound handlers.
type Manager struct {
	access           sync.RWMutex
	defaultHandler   outbound.Handler
	taggedHandler    map[string]outbound.Handler
	untaggedHandlers []outbound.Handler
	running          bool
}

// New creates a new Manager.
func New(ctx context.Context, config *proxyman.OutboundConfig) (*Manager, error) {
	m := &Manager{
		taggedHandler: make(map[string]outbound.Handler),
	}
	return m, nil
}

// Type implements common.HasType.
func (m *Manager) Type() interface{} {
	return outbound.ManagerType()
}

// Start implements core.Feature
func (m *Manager) Start() error {
	m.access.Lock()
	defer m.access.Unlock()

	m.running = true

	for _, h := range m.taggedHandler {
		if err := h.Start(); err != nil {
			return err
		}
	}

	for _, h := range m.untaggedHandlers {
		if err := h.Start(); err != nil {
			return err
		}
	}

	return nil
}

// Close implements core.Feature
func (m *Manager) Close() error {
	m.access.Lock()
	defer m.access.Unlock()

	m.running = false

	var errs []error
	for _, h := range m.taggedHandler {
		errs = append(errs, h.Close())
	}

	for _, h := range m.untaggedHandlers {
		errs = append(errs, h.Close())
	}

	return errors.Combine(errs...)
}

// GetDefaultHandler implements outbound.Manager.
func (m *Manager) GetDefaultHandler() outbound.Handler {
	m.access.RLock()
	defer m.access.RUnlock()

	if m.defaultHandler == nil {
		return nil
	}
	return m.defaultHandler
}

// GetHandler implements outbound.Manager.
func (m *Manager) GetHandler(tag string) outbound.Handler {
	m.access.RLock()
	defer m.access.RUnlock()
	if handler, found := m.taggedHandler[tag]; found {
		return handler
	}
	return nil
}

// AddHandler implements outbound.Manager.
func (m *Manager) AddHandler(ctx context.Context, handler outbound.Handler) error {
	m.access.Lock()
	defer m.access.Unlock()

	if m.defaultHandler == nil {
		m.defaultHandler = handler
	}

	tag := handler.Tag()
	if len(tag) > 0 {
		m.taggedHandler[tag] = handler
	} else {
		m.untaggedHandlers = append(m.untaggedHandlers, handler)
	}

	if m.running {
		return handler.Start()
	}

	return nil
}

// RemoveHandler implements outbound.Manager.
func (m *Manager) RemoveHandler(ctx context.Context, tag string) error {
	if tag == "" {
		return common.ErrNoClue
	}
	m.access.Lock()
	defer m.access.Unlock()

	delete(m.taggedHandler, tag)
	if m.defaultHandler.Tag() == tag {
		m.defaultHandler = nil
	}

	return nil
}

// Select implements outbound.HandlerSelector.
func (m *Manager) Select(selectors []string) []string {
	m.access.RLock()
	defer m.access.RUnlock()

	tags := make([]string, 0, len(selectors))

	for tag := range m.taggedHandler {
		match := false
		for _, selector := range selectors {
			if strings.HasPrefix(tag, selector) {
				match = true
				break
			}
		}
		if match {
			tags = append(tags, tag)
		}
	}

	return tags
}

func init() {
	common.Must(common.RegisterConfig((*proxyman.OutboundConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
		return New(ctx, config.(*proxyman.OutboundConfig))
	}))
	common.Must(common.RegisterConfig((*core.OutboundHandlerConfig)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
		return NewHandler(ctx, config.(*core.OutboundHandlerConfig))
	}))
}


text:
/* ========================================================================== */
/* === umf_cholmod ========================================================== */
/* ========================================================================== */

/* umfpack_cholmod: user-defined ordering function to interface UMFPACK
 * to CHOLMOD.
 *
 * This routine is an example of a user-provided ordering function for UMFPACK.
 *
 * This function can be passed to umfpack_*_fsymbolic as the
 * user_ordering function pointer.
 */

#include "umf_internal.h"
#include "umf_cholmod.h"

#ifndef NCHOLMOD
#include "cholmod.h"
#endif

#if defined (DINT) || defined (ZINT)
#define CHOLMOD_start       cholmod_start
#define CHOLMOD_transpose   cholmod_transpose
#define CHOLMOD_analyze     cholmod_analyze
#define CHOLMOD_free_sparse cholmod_free_sparse
#define CHOLMOD_free_factor cholmod_free_factor
#define CHOLMOD_finish      cholmod_finish
#define CHOLMOD_print_common      cholmod_print_common
#else
#define CHOLMOD_start       cholmod_l_start
#define CHOLMOD_transpose   cholmod_l_transpose
#define CHOLMOD_analyze     cholmod_l_analyze
#define CHOLMOD_free_sparse cholmod_l_free_sparse
#define CHOLMOD_free_factor cholmod_l_free_factor
#define CHOLMOD_finish      cholmod_l_finish
#define CHOLMOD_print_common      cholmod_l_print_common
#endif

int UMF_cholmod
(
    /* inputs */
    Int nrow,               /* A is nrow-by-ncol */
    Int ncol,               /* A is nrow-by-ncol */
    Int symmetric,          /* if true and nrow=ncol do A+A', else do A'A */
    Int Ap [ ],             /* column pointers, size ncol+1 */
    Int Ai [ ],             /* row indices, size nz = Ap [ncol] */
    /* output */
    Int Perm [ ],           /* fill-reducing permutation, size ncol */
    /* user-defined */
    void *user_params,      /* Int array of size 3 */
    double user_info [3]    /* [0]: max col count for L=chol(P(A+A')P')
                               [1]: nnz (L)
                               [2]: flop count for chol, if A real */
)
{
#ifndef NCHOLMOD
    double dmax, flops, c, lnz ;
    cholmod_sparse Amatrix, *A, *AT, *S ;
    cholmod_factor *L ;
    cholmod_common cm ;
    Int *P, *ColCount ;
    Int k, ordering_option, print_level, *params ;

    params = (Int *) user_params ;
    ordering_option = params [0] ;
    print_level = params [1] - 1 ;
    params [2] = -1 ;

    if (Ap == NULL || Ai == NULL || Perm == NULL || nrow < 0 || ncol < 0)
    {
        /* invalid inputs */
        return (FALSE) ;
    }
    if (nrow != ncol)
    {
        /* force symmetric to be false */
        symmetric = FALSE ;
    }

    /* start CHOLMOD */
    CHOLMOD_start (&cm) ;
    cm.supernodal = CHOLMOD_SIMPLICIAL ;
    cm.print = print_level ;

    /* adjust cm based on ordering_option */
    switch (ordering_option)
    {

        default:
        case UMFPACK_ORDERING_AMD:
            /* AMD on A+A' if symmetric, COLAMD on A otherwise */
            cm.nmethods = 1 ;
            cm.method [0].ordering = symmetric ? CHOLMOD_AMD : CHOLMOD_COLAMD ;
            cm.postorder = TRUE ;
            break ;

        case UMFPACK_ORDERING_METIS:
            /* metis on A+A' if symmetric, A'A otherwise */
            cm.nmethods = 1 ;
            cm.method [0].ordering = CHOLMOD_METIS ;
            cm.postorder = TRUE ;
            break ;

        case UMFPACK_ORDERING_NONE:
        case UMFPACK_ORDERING_GIVEN:
        case UMFPACK_ORDERING_USER:
            /* no ordering.  No input permutation here, and no user
               function, so all these are the same as "none". */
            cm.nmethods = 1 ;
            cm.method [0].ordering = CHOLMOD_NATURAL ;
            cm.postorder = FALSE ;
            break ;

        case UMFPACK_ORDERING_BEST:
            /* try AMD, METIS and NESDIS on A+A', or COLAMD(A), METIS(A'A),
               and NESDIS (A'A) */
            cm.nmethods = 3 ;
            cm.method [0].ordering = symmetric ? CHOLMOD_AMD : CHOLMOD_COLAMD ;
            cm.method [1].ordering = CHOLMOD_METIS ;
            cm.method [2].ordering = CHOLMOD_NESDIS ;
            cm.postorder = TRUE ;
            break ;

        case UMFPACK_ORDERING_CHOLMOD:
            /* no change to CHOLMOD defaults:
            Do not use given permutation, since it's not provided.
            Try AMD.  If fill-in and flop count are low, use AMD.
            Otherwise, try METIS and take the best of AMD and METIS.
            cm.method [0].ordering = CHOLMOD_GIVEN
            cm.method [1].ordering = CHOLMOD_AMD
            cm.method [2].ordering = CHOLMOD_METIS
            cm.nmethods = 2 if METIS installed, 3 otherwise ('given' is skipped)
            */
            break ;
    }

    /* construct a CHOLMOD version of the input matrix A */
    A = &Amatrix ;
    A->nrow = nrow ;                /* A is nrow-by-ncol */
    A->ncol = ncol ;
    A->nzmax = Ap [ncol] ;          /* with nzmax entries */
    A->packed = TRUE ;              /* there is no A->nz array */
    if (symmetric)
    {
        A->stype = 1 ;                  /* A is symmetric */
    }
    else
    {
        A->stype = 0 ;                  /* A is unsymmetric */
    }
    A->itype = CHOLMOD_INT ;
    A->xtype = CHOLMOD_PATTERN ;
    A->dtype = CHOLMOD_DOUBLE ;
    A->nz = NULL ;
    A->p = Ap ;                     /* column pointers */
    A->i = Ai ;                     /* row indices */
    A->x = NULL ;                   /* no numerical values */
    A->z = NULL ;
    A->sorted = FALSE ;             /* columns of A might not be sorted */

    if (symmetric)
    {
        /* CHOLMOD with order the symmetric matrix A */
        AT = NULL ;
        S = A ;
    }
    else
    {
        /* S = A'.  CHOLMOD will order S*S', which is A'*A */
        AT = CHOLMOD_transpose (A, 0, &cm) ;
        S = AT ;
    }

    /* order and analyze S or S*S' */
    L = CHOLMOD_analyze (S, &cm) ;
    CHOLMOD_free_sparse (&AT, &cm) ;
    if (L == NULL)
    {
        return (FALSE) ;
    }

    /* determine the ordering used */
    switch (L->ordering)
    {

        case CHOLMOD_AMD:
        case CHOLMOD_COLAMD:
            params [2] = UMFPACK_ORDERING_AMD ;
            break ;

        case CHOLMOD_METIS:
        case CHOLMOD_NESDIS:
            params [2] = UMFPACK_ORDERING_METIS ;
            break ;

        case CHOLMOD_GIVEN:
        case CHOLMOD_NATURAL:
        default:
            params [2] = UMFPACK_ORDERING_NONE ;
            break ;
    }

    /* copy the permutation from L to the output and compute statistics */
    P = L->Perm ;
    ColCount = L->ColCount ;
    dmax = 1 ;
    lnz = 0 ;
    flops = 0 ;
    for (k = 0 ; k < ncol ; k++)
    {
        Perm [k] = P [k] ;
        c = ColCount [k] ;
        if (c > dmax) dmax = c ;
        lnz += c ;
        flops += c*c ;
    }
    user_info [0] = dmax ;
    user_info [1] = lnz ;
    user_info [2] = flops ;

    CHOLMOD_free_factor (&L, &cm) ;
    if (print_level > 0)
    {
        CHOLMOD_print_common ("for UMFPACK", &cm) ;
    }
    CHOLMOD_finish (&cm) ;
    return (TRUE) ;
#else
    /* CHOLMOD and its supporting packages (CAMD, CCOLAMD, COLAMD, METIS)
      not installed */
    return (FALSE) ;
#endif
}


text:
module.exports = (resolve, rootDir) => {
  const config = {
    automock: false,
    moduleNameMapper: {
      '^[./a-zA-Z0-9$_-]+\\.(jpg|png|gif|eot|otf|svg|ttf|woff|woff2|mp4|webm)$': resolve('config/jest/FileStub.js'),
      '^[./a-zA-Z0-9$_-]+\\.css$': resolve('config/jest/CSSStub.js')
    },
    persistModuleRegistryBetweenSpecs: true,
    //scriptPreprocessor: resolve('config/jest/transform.js'),
    scriptPreprocessor: resolve('config/jest/preprocessor.js'),
    setupFiles: [
      resolve('config/polyfills.js')
    ],
    moduleFileExtensions: ["ts", "tsx", "js"],
    setupTestFrameworkScriptFile: resolve('config/jest/environment.js'),
    testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/build/'],
    // JDN->removed the testFileExtensions to use testRegEx for test resolution.
    // Allowed patterns:
    // **/__tests__/*.(j|t)s(x?)
    // **/*.test.(j|t)s(x?)
    // **/*.spec.(j|t)s(x?)
    testRegex: '(__tests__/.*|\\.(test|spec))\\.(j|t)s(x?)$',
    testEnvironment: 'node',
    verbose: true
  };
  if (rootDir) {
    config.rootDir = rootDir;
  }
  return config;
};


text:
'use strict';

describe('Directive: pageSelect', function () {

  // load the directive's module
  beforeEach(module('testApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<page-select></page-select>');
    element = $compile(element)(scope);
    expect(element.text()).toBe('this is the pageSelect directive');
  }));
});


text:
#import <MIME/MFMessageStore.h>

@class NSData;

@interface MFDataMessageStore : MFMessageStore
{
    NSData *_data;
    Class _messageClass;
}

- (id)mailboxUid;
- (id)_cachedBodyDataForMessage:(id)arg1 valueIfNotPresent:(id)arg2;
- (id)_cachedHeadersForMessage:(id)arg1 valueIfNotPresent:(id)arg2;
- (id)_cachedBodyForMessage:(id)arg1 valueIfNotPresent:(id)arg2;
- (id)bodyDataForMessage:(id)arg1 isComplete:(_Bool *)arg2 isPartial:(_Bool *)arg3 downloadIfNecessary:(_Bool)arg4;
- (id)headerDataForMessage:(id)arg1 downloadIfNecessary:(_Bool)arg2;
- (id)account;
- (id)message;
- (void)setMessageClass:(Class)arg1;
- (void)writeUpdatedMessageDataToDisk;
- (id)storePath;
- (void)dealloc;
- (id)initWithData:(id)arg1;

@end


text:
module OauthTwitter
  module API
    module Statuses

      ##
      # Url path of status API
      PATH = {
        :mentions_timeline => '/1.1/statuses/mentions_timeline.json',
        :user_timeline     => '/1.1/statuses/user_timeline.json',
        :home_timeline     => '/1.1/statuses/home_timeline.json',
        :retweets_of_me    => '/1.1/statuses/retweets_of_me.json'
      }

      ##
      # Load current user's Tweet with @user_name mentioned, include user
      # mention themselves.
      #
      # @param params [Hash] always supply a user_id or screen_name. If both
      #   are supplied, user_id will be used
      # @param options [Hash]
      #
      # @return [Array]
      def mentions_timeline(params={}, options={})
        query = params.clone
        return send_status_request(:mentions_timeline, query, options)
      end

      ##
      #
      def user_timeline(params={}, options={})
        query = params.clone
        return send_status_request(:user_timeline, query, options)
      end

      ##
      # Load current use's (determined by oauth_token and oauth_token_secret
      # variables) home time.
      #
      # @param params [Hash] parameters that consistent with Twitter's API.
      # @param options [Hash] options to perform more operations.
      #
      #   :pages => [Int] indicate many pages will return, for example,
      #   if count = 5, pages = 3, then it will return 5 * 3 = 15 tweets
      #   from the user's timeline. Cursor stops if response no more reponse.
      #
      #   :detailed => [Bool] if false, will return just the data
      #
      # @return [Array] hash structured the same as Twitter's JSON response.
      def home_timeline(params={}, options={})
        query = params.clone
        return send_status_request(:home_timeline, query, options)
      end

      ##
      #
      def retweets_of_me(params={}, options={})
        query = params.clone
        return send_status_request(:retweets_of_me, query, options)
      end

      private
      ##
      # Private helper for each of the status API
      def send_status_request(api_symbol, query, options)
        full_response = []
        response = nil
        options[:pages] ||= 1
        options[:pages].times do |page_num|
          response = send_request(:GET, PATH[api_symbol], query, true, options)
          break unless response[:valid]
          break if response[:data].empty?
          full_response += response[:data]
          query[:max_id] = response[:data].last['id'] - 1
        end
        return assemble_multi_page_response(full_response, response, options)
      end

    end
  end
end


text:
@interface NSString (IntConverter)
+ (id)stringFromUInt32:(unsigned int)arg1;
+ (id)stringFromUInt64:(unsigned long long)arg1;
- (unsigned int)uInt32Value;
- (unsigned long long)uInt64Value;
@end


text:
package com.busqueumlugar.enumerador;

import java.io.Serializable;

import com.busqueumlugar.util.MessageUtils;

public enum TipoImovelEnum implements Serializable, ICodigoDescricao {

    A(MessageUtils.getMessage("lbl.tipo.imovel.apto")),
	C(MessageUtils.getMessage("lbl.tipo.imovel.casa.padrao")),
	Q(MessageUtils.getMessage("lbl.tipo.imovel.quarto")),
	B(MessageUtils.getMessage("lbl.tipo.imovel.cobertura")),
	M(MessageUtils.getMessage("lbl.tipo.imovel.comercial")),
	P(MessageUtils.getMessage("lbl.tipo.imovel.pousada")),
	MN(MessageUtils.getMessage("lbl.tipo.imovel.mansao")),
	T(MessageUtils.getMessage("lbl.tipo.imovel.terreno")),
	F(MessageUtils.getMessage("lbl.tipo.imovel.fazenda")),
	H(MessageUtils.getMessage("lbl.tipo.imovel.haras")),
	S(MessageUtils.getMessage("lbl.tipo.imovel.sitio")),
	L(MessageUtils.getMessage("lbl.tipo.imovel.loft")),
	K(MessageUtils.getMessage("lbl.tipo.imovel.kitinete")),
	N(MessageUtils.getMessage("lbl.tipo.imovel.flat")),
	V(MessageUtils.getMessage("lbl.tipo.imovel.casa.vila")),
	O(MessageUtils.getMessage("lbl.tipo.imovel.loteamento")),
	E(MessageUtils.getMessage("lbl.tipo.imovel.hotel")),
	D(MessageUtils.getMessage("lbl.tipo.imovel.casa.condominio")),
	G(MessageUtils.getMessage("lbl.tipo.imovel.galpao")),
	I(MessageUtils.getMessage("lbl.tipo.imovel.predio")),
	R(MessageUtils.getMessage("lbl.tipo.imovel.chacara")),
	U(MessageUtils.getMessage("lbl.tipo.imovel.studio"));

    private String descricao;

    private TipoImovelEnum( final String descricao) {

        this.descricao = descricao;
    }

    @Override
    public String getRotulo() {

        return this.descricao;
    }

    @Override
    public String getIdentificador() {

        return this.name();
    }

    public static String getLabel(String key) {

        return TipoImovelEnum.valueOf(key).getRotulo();
    }

}


text:
@extends('layouts.master')

@section('head')
{{ HTML::script('/js/fintrack.input.js') }}
<title>Finance Tracker - Edit Income</title>
@stop

@section('content')
{{ Form::open(['route'=>['income.update', $view, $income->income_id], 'class' => 'form-horizontal']) }}

        Date

            <input type="text" class="date-pick input-small" name="create_date" value="{{{ $income->create_date }}}"/>

        Amount

            <input type="text" name="amount" class="focus" value="{{{ number_format($income->amount, 2, '.', '') }}}" size="12"/>

        Description

            <textarea name="descr" cols="30" rows="5">{{{ $income->descr }}}</textarea>

        User

            {{ Form::select('user_id', $users, $income->user_id) }}

            {{ Form::submit('Update', ['class' => 'btn btn-small btn-primary']) }}
            {{ Form::reset('Reset', ['class' => 'btn btn-small']) }}
            {{ Form::button('Back to list', ['class' => 'btn btn-small']) }}

            @if($errors->has())
            @foreach($errors->all() as $error)

{{ $error }}

            @endforeach
            @endif
            @if(Session::has('success'))

{{Session::get('success')}}

            @endif

{{ Form::close() }}
@stop


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

<TITLE>
net.authorize.xml Class Hierarchy (Authorize.Net Java SDK)
</TITLE>

<META NAME="date" CONTENT="2011-08-25">

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

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Hierarchy For Package net.authorize.xml

Package Hierarchies:
All Packages

Class Hierarchy

java.lang.Object

net.authorize.xml.Message
net.authorize.Result<T> (implements java.io.Serializable)

net.authorize.xml.Result<T>

      Overview
      Package
      Class
      Use
    Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net.test.util;

import android.util.Base64;

import org.chromium.base.test.util.UrlUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;

/**
 * Certificate related utility methods.
 */
public class CertTestUtil {
    /**
     * The location of the directory that contains certificates for testing.
     */
    public static final String CERTS_DIRECTORY =
            UrlUtils.getIsolatedTestFilePath("net/data/ssl/certificates/");

    private static final String BEGIN_MARKER = "-----BEGIN CERTIFICATE-----";
    private static final String END_MARKER = "-----END CERTIFICATE-----";

    private CertTestUtil() {}

    /**
     * Converts a PEM formatted cert in a given file to the binary DER format.
     *
     * @param pemPathname the location of the certificate to convert.
     * @return array of bytes that represent the certificate in DER format.
     * @throws IOException if the file cannot be read.
     */
    public static byte[] pemToDer(String pemPathname) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(pemPathname));
        StringBuilder builder = new StringBuilder();

        // Skip past leading junk lines, if any.
        String line = reader.readLine();
        while (line != null && !line.contains(BEGIN_MARKER)) line = reader.readLine();

        // Then skip the BEGIN_MARKER itself, if present.
        while (line != null && line.contains(BEGIN_MARKER)) line = reader.readLine();

        // Now gather the data lines into the builder.
        while (line != null && !line.contains(END_MARKER)) {
            builder.append(line.trim());
            line = reader.readLine();
        }

        reader.close();
        return Base64.decode(builder.toString(), Base64.DEFAULT);
    }

    /**
     * Returns SHA256 hash of the public key of a given certificate.
     *
     * @param cert the cert that should be used to retrieve the public key from.
     * @return SHA256 hash of the public key.
     */
    public static byte[] getPublicKeySha256(Certificate cert) {
        try {
            byte[] publicKey = cert.getPublicKey().getEncoded();
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            return digest.digest(publicKey);
        } catch (NoSuchAlgorithmException ex) {
            // This exception should never happen since SHA-256 is known algorithm
            throw new RuntimeException(ex);
        }
    }
}


text:
<bill session="115" type="h" number="2494" updated="2017-07-20T17:26:14Z">
  <state datetime="2017-05-17">REFERRED</state>
  <status>
    <introduced datetime="2017-05-17"/>
  </status>
  <introduced datetime="2017-05-17"/>
  <titles>
    <title type="short" as="introduced">Drain the Swamp and the President's Assets Act</title>
    <title type="short" as="introduced">Drain the Swamp and the President’s Assets Act</title>
    <title type="official" as="introduced">To amend the Ethics in Government Act of 1978 to require the President to place any financial conflicts of interest into a blind trust, and for other purposes.</title>
    <title type="display">Drain the Swamp and the President's Assets Act</title>
  </titles>
  <sponsor bioguide_id="E000297"/>
  <cosponsors>
    <cosponsor bioguide_id="C001068" joined="2017-05-17"/>
    <cosponsor bioguide_id="M000312" joined="2017-05-17"/>
  </cosponsors>
  <actions>
    <action datetime="2017-05-17">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-05-17" state="REFERRED">
      <text>Referred to the House Committee on Oversight and Government Reform.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSGO" name="House Oversight and Government Reform" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Government operations and politics"/>
    <term name="Corporate finance and management"/>
    <term name="Financial services and investments"/>
    <term name="Government ethics and transparency, public corruption"/>
    <term name="Presidents and presidential powers, Vice Presidents"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
import _ from 'underscore';
import { ReactiveVar } from 'meteor/reactive-var';
import { ReactiveDict } from 'meteor/reactive-dict';
import { Template } from 'meteor/templating';

import { t } from '../../utils/client';
import { EmojiPicker } from './lib/EmojiPicker';
import { emoji } from '../lib/rocketchat';

const emojiListByCategory = new ReactiveDict('emojiList');

const getEmojiElement = (emoji, image) => image && `<li class="emoji-${ emoji } emoji-picker-item" data-emoji="${ emoji }" title="${ emoji }">${ image }</li>`;

const createEmojiList = (category, actualTone) => {
	const html = Object.values(emoji.packages).map((emojiPackage) => {
		if (!emojiPackage.emojisByCategory[category]) {
			return;
		}

		return emojiPackage.emojisByCategory[category].map((current) => {
			const tone = actualTone > 0 && emojiPackage.toneList.hasOwnProperty(current) ? `_tone${ actualTone }` : '';
			return getEmojiElement(current, emojiPackage.renderPicker(`:${ current }${ tone }:`));
		}).join('');
	}).join('') || `<li>${ t('No_emojis_found') }</li>`;

	return html;
};

export function updateRecentEmoji(category) {
	emojiListByCategory.set(category, createEmojiList(category));
}

const createPickerEmojis = (instance) => {
	const categories = instance.categoriesList;
	const actualTone = instance.tone;

	categories.forEach((category) => emojiListByCategory.set(category.key, createEmojiList(category.key, actualTone)));
};

function getEmojisBySearchTerm(searchTerm) {
	let html = '
';
	const t = Template.instance();
	const actualTone = t.tone;

	EmojiPicker.currentCategory.set('');

	const searchRegExp = new RegExp(RegExp.escape(searchTerm.replace(/:/g, '')), 'i');

	for (let current in emoji.list) {
		if (!emoji.list.hasOwnProperty(current)) {
			continue;
		}

		if (searchRegExp.test(current)) {
			const emojiObject = emoji.list[current];
			const { emojiPackage } = emojiObject;
			let tone = '';
			current = current.replace(/:/g, '');

			if (actualTone > 0 && emoji.packages[emojiPackage].toneList.hasOwnProperty(emoji)) {
				tone = `_tone${ actualTone }`;
			}

			let emojiFound = false;

			for (const key in emoji.packages[emojiPackage].emojisByCategory) {
				if (emoji.packages[emojiPackage].emojisByCategory.hasOwnProperty(key)) {
					const contents = emoji.packages[emojiPackage].emojisByCategory[key];
					if (contents.indexOf(current) !== -1) {
						emojiFound = true;
						break;
					}
				}
			}

			if (emojiFound) {
				const image = emoji.packages[emojiPackage].renderPicker(`:${ current }${ tone }:`);
				html += getEmojiElement(current, image);
			}
		}
	}
	html += '
';

	return html;
}

Template.emojiPicker.helpers({
	emojiCategories() {
		return Template.instance().categoriesList;
	},
	emojiByCategory(category) {
		let emojisByCategory = [];
		for (const emojiPackage in emoji.packages) {
			if (emoji.packages.hasOwnProperty(emojiPackage)) {
				if (emoji.packages[emojiPackage].emojisByCategory.hasOwnProperty(category)) {
					emojisByCategory = emojisByCategory.concat(emoji.packages[emojiPackage].emojisByCategory[category]);
				}
			}
		}
		return emojisByCategory;
	},
	searching() {
		return Template.instance().currentSearchTerm.get().length > 0;
	},
	searchResults() {
		return getEmojisBySearchTerm(Template.instance().currentSearchTerm.get());
	},
	emojiList(category) {
		return emojiListByCategory.get(category);
	},
	currentTone() {
		return `tone-${ Template.instance().tone }`;
	},
	/**
	 * Returns true if a given emoji category is active
	 *
	 * @param {string} category hash
	 * @return {boolean} true if active, false otherwise
	 */
	activeCategory(category) {
		return EmojiPicker.currentCategory.get() === category ? 'active' : '';
	},
	/**
	 * Returns currently active emoji category hash
	 *
	 * @return {string} category hash
	 */
	currentCategory() {
		return EmojiPicker.currentCategory.get();
	},
});

Template.emojiPicker.events({
	'click .emoji-picker'(event) {
		event.stopPropagation();
		event.preventDefault();
	},
	'click .category-link'(event) {
		event.stopPropagation();
		event.preventDefault();

		EmojiPicker.showCategory(event.currentTarget.hash.substr(1));

		return false;
	},
	'scroll .emojis': _.throttle((event, instance) => {
		if (EmojiPicker.scrollingToCategory) {
			return;
		}

		const container = instance.$(event.currentTarget);
		const scrollTop = container.scrollTop() + 8;

		const last = EmojiPicker.getCategoryPositions()
			.filter((pos) => pos.top <= scrollTop)
			.pop();

		if (!last) {
			return;
		}

		const { el } = last;

		const category = el.id.replace('emoji-list-category-', '');

		EmojiPicker.currentCategory.set(category);
	}, 300),
	'click .change-tone > a'(event, instance) {
		event.stopPropagation();
		event.preventDefault();

		instance.$('.tone-selector').toggleClass('show');
	},
	'click .tone-selector .tone'(event, instance) {
		event.stopPropagation();
		event.preventDefault();

		const tone = parseInt(event.currentTarget.dataset.tone);
		let newTone;

		if (tone > 0) {
			newTone = `_tone${ tone }`;
		} else {
			newTone = '';
		}

		for (const emojiPackage in emoji.packages) {
			if (emoji.packages.hasOwnProperty(emojiPackage)) {
				if (emoji.packages[emojiPackage].hasOwnProperty('toneList')) {
					for (const _emoji in emoji.packages[emojiPackage].toneList) {
						if (emoji.packages[emojiPackage].toneList.hasOwnProperty(_emoji)) {
							$(`.emoji-${ _emoji }`).html(emoji.packages[emojiPackage].render(`:${ _emoji }${ newTone }:`));
						}
					}
				}
			}
		}

		EmojiPicker.setTone(tone);

		instance.setCurrentTone(tone);

		$('.tone-selector').toggleClass('show');
	},
	'click .emoji-list .emoji-picker-item'(event, instance) {
		event.stopPropagation();

		const _emoji = event.currentTarget.dataset.emoji;
		const actualTone = instance.tone;
		let tone = '';

		for (const emojiPackage in emoji.packages) {
			if (emoji.packages.hasOwnProperty(emojiPackage)) {
				if (actualTone > 0 && emoji.packages[emojiPackage].toneList.hasOwnProperty(_emoji)) {
					tone = `_tone${ actualTone }`;
				}
			}
		}

		const input = $('.emoji-picker .js-emojipicker-search');
		if (input) {
			input.val('');
		}
		instance.currentSearchTerm.set('');

		EmojiPicker.pickEmoji(_emoji + tone);
	},
	'keyup .js-emojipicker-search, change .js-emojipicker-search'(event, instance) {
		const value = event.target.value.trim();
		const cst = instance.currentSearchTerm;
		if (value === cst.get()) {
			return;
		}
		cst.set(value);
	},
});

Template.emojiPicker.onCreated(function() {
	this.tone = EmojiPicker.getTone();
	const recent = EmojiPicker.getRecent();

	this.currentSearchTerm = new ReactiveVar('');

	this.categoriesList = [];
	for (const emojiPackage in emoji.packages) {
		if (emoji.packages.hasOwnProperty(emojiPackage)) {
			if (emoji.packages[emojiPackage].emojiCategories) {
				if (typeof emoji.packages[emojiPackage].categoryIndex !== 'undefined') {
					this.categoriesList.splice(emoji.packages[emojiPackage].categoryIndex, 0, ...emoji.packages[emojiPackage].emojiCategories);
				} else {
					this.categoriesList = this.categoriesList.concat(emoji.packages[emojiPackage].emojiCategories);
				}
			}
		}
	}

	recent.forEach((_emoji) => {
		emoji.packages.base.emojisByCategory.recent.push(_emoji);
	});

	this.setCurrentTone = (newTone) => {
		$('.current-tone').removeClass(`tone-${ this.tone }`);
		$('.current-tone').addClass(`tone-${ newTone }`);
		this.tone = newTone;
	};

	createPickerEmojis(this);
});