text:
import sys
import argparse

def git_clone(args):
    print('in git_clone')
    print(args)

def git_init(args):
    print('in git_init')
    print(args)

def git_commit(args):
    print('in git_commit')
    print(args)

def subcommands(args):
    """
    # 1.1 add long option with arg
    parser.add('--arg', type=int, help='long option with arg')
    # 1.2 add long option without arg (True,False)
    parser.add('--bool', action='store_true', help='long option without arg (true-false)')
    # 1.3 add long option without arg (Count)
    parser.add('--count', action='count', help='long option without arg (count)')

    # 2.1 add short option with arg
    parser.add('-a', type=int, help='short option with arg')
    # 2.2 add short option without arg (True,False)
    parser.add('-b', action='store_true', help='short option without arg (true-false)')
    # 2.3 add short option without arg (Count)
    parser.add('-c', action='count', help='short option without arg (count)')

    # 3.1 add long short option with arg
    parser.add('-q', '--quiet', type=int, help='long short option with arg')
    # 3.2 add long short option without arg (True,False)
    parser.add('-v', '--verbosity', action='store_true', help='long short option without arg (true-false)')
    # 3.3 add long short option without arg (Count)
    parser.add('-t', '--times', action='count', help='long short option without arg (count)')

    # 4.1 add mutually exclusive option without arg
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", action="store_true")
    group.add_argument("-q", "--quiet", action="store_true")
    # add_argument_group
    """
    main_parser_usage = """git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]"""
    main_parser_epilog = """git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept."""

    clone_parser_usage = """usage: git clone [<options>] [--] <repo> [<dir>]"""
    clone_parser_epilog = ""

    init_parser_usage = """usage: git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"""
    init_parser_epilog = ""

    commit_parser_usage = "usage: git commit [<options>] [--] <pathspec>..."
    commit_parser_epilog = ""
    # CREATE TOP-LEVEL PARSER
    #Keyword Arguments:
    #- prog - The name of the program (default: sys.argv[0])
    #- usage - The string describing the program usage (default: generated from arguments added to parser)
    #- description - Text to display before the argument help (default: none)
    #- epilog - Text to display after the argument help (default: none)
    #- parents - A list of ArgumentParser objects whose arguments should also be included
    #- formatter_class - A class for customizing the help output
    #- prefix_chars - The set of characters that prefix optional arguments (default: '-')
    #- fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
    #    additional arguments
    #- argument_default - The global default value for arguments (default: None)
    #- conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
    #- add_help - Add a -h/--help option to the parser (default: True)
    #- allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)
    parser = argparse.ArgumentParser(prog='git', usage=main_parser_usage, description=None,
        epilog=main_parser_epilog)

    # CREATE SUB-COMMANDS
    #ArgumentParser.add_subparsers([title ][, description ][, prog ][, parser_class ][, action ]
    #    [, option_string ][, dest ][, help ][, metavar ])
    #Keyword Arguments:
    #- title - title for the sub-parser group in help output; by default "subcommands" if description is provided, otherwise uses title for positional arguments
    #- description - description for the sub-parser group in help output, by default None
    #- prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument
    #- parser_class - class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser)
    #- action - the basic type of action to be taken when this argument is encountered at the command line
    #- dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored
    #- help - help for sub-parser group in help output, by default None
    #- metavar - string presenting available sub-commands in help; by default it is None and presents sub-commands in form {cmd1, cmd2, ..}
    subparsers = parser.add_subparsers(dest='subcmd', title='These are common Git commands used in various situations',
            description=None, metavar='')

    # create the parser for the 'clone' command
    parser_clone = subparsers.add_parser('clone', prog='git clone', help='Clone a repository into a new directory',
            usage=clone_parser_usage, epilog=clone_parser_epilog)
    parser_clone.set_defaults(func=git_clone)
    parser_clone.add_argument('bar', type=int, help='bar help')

    # create the parser for the 'init' command
    parser_init = subparsers.add_parser('init', prog='git init', help='Create an empty Git repository or reinitialize an existing one',
            usage=init_parser_usage, epilog=init_parser_epilog)
    parser_init.set_defaults(func=git_init)
    parser_init.add_argument('--template', metavar='<template-directory>', help='directory from which templates will be used')
    parser_init.add_argument('--bare', action='store_true', help='create a bare repository')
    parser_init.add_argument('--shared', metavar='[=<permissions>]', help='specify that the git repository is to be shared amongst several users')
    parser_init.add_argument('-q', '--quiet', action='store_true', help='be quiet')
    parser_init.add_argument('--separate-git-dir', metavar='<gitdir>', help='separate git dir from working tree')
    #ArgumentParser.set_defaults(**kwargs)

    # create the parser for the 'commit' command
    #parser_commit = subparsers.add_parser('commit', aliases=['ci'], prog='git commit', help='Record changes to the repository',
    parser_commit = subparsers.add_parser('commit', prog='git commit', help='Record changes to the repository',
            usage=commit_parser_usage, epilog=commit_parser_epilog)
    parser_init.set_defaults(func=git_commit)
    parser_commit.add_argument('-q', '--quiet', action='store_true', help='suppress summary after successful commit')
    parser_commit.add_argument('-v', '--verbose', action='store_true', help='show diff in commit message template')
    #ArgumentParser.add_argument_group(title=None, description=None)
    group_commit_msg = parser_commit.add_argument_group(title='Commit message options', description=None)
    group_commit_msg.add_argument('-F', '--file', metavar='<file>', help='read message from file')
    group_commit_msg.add_argument('--author', metavar='<author>', help='override author for commit')
    group_commit_msg.add_argument('--date', metavar='<date>', help='override date for commit')
    group_commit_msg.add_argument('-m', '--message', metavar='<message>', help='commit message')
    group_commit_msg.add_argument('-c', '--reedit-message', metavar='<commit>', help='reuse and edit message from specified commit')
    group_commit_msg.add_argument('-C', '--reuse-message', metavar='<commit>', help='reuse message from specified commit')
    group_commit_msg.add_argument('--fixup', metavar='<commit>', help='use autosquash formatted message to fixup specified commit')
    group_commit_msg.add_argument('--squash', metavar='<commit>', help='use autosquash formatted message to squash specified commit')
    group_commit_msg.add_argument('--reset-author', metavar='<commit>', help='the commit is authored by me now (used with -C/-c/--amend)')
    group_commit_msg.add_argument('-s', '--signoff', action='store_true', help='add Signed-off-by:')
    group_commit_msg.add_argument('-t', '--template', metavar='<file>', help='use specified template file')
    group_commit_msg.add_argument('-e', '--edit', action='store_true', help='force edit of commit')
    group_commit_msg.add_argument('--cleanup', metavar='<default>', help='how to strip spaces and #comments from message')
    group_commit_msg.add_argument('--status', action='store_true', help='include status in commit message template')
    group_commit_msg.add_argument('-S', '--gpg-sign', metavar='[=<key-id>]', help='GPG sign commit')

    group_commit_ctx = parser_commit.add_argument_group(title='Commit contents options', description=None)
    group_commit_ctx.add_argument('-a', '--all', action='store_true', help='commit all changed files')
    group_commit_ctx.add_argument('-i', '--include', action='store_true', help='add specified files to index for commit')
    group_commit_ctx.add_argument('--interactive', action='store_true', help='interactively add files')
    group_commit_ctx.add_argument('-p', '--patch', action='store_true', help='interactively add changes')
    group_commit_ctx.add_argument('-o', '--only', action='store_true', help='commit only specified files')
    group_commit_ctx.add_argument('-n', '--no-verify', action='store_true', help='bypass pre-commit and commit-msg hooks')
    group_commit_ctx.add_argument('--dry-run', action='store_true', help='show what would be committed')
    group_commit_ctx.add_argument('--short', action='store_true', help='show status concisely')
    group_commit_ctx.add_argument('--branch', action='store_true', help='show branch information')
    group_commit_ctx.add_argument('--ahead-behind', action='store_true', help='compute full ahead/behind values')
    group_commit_ctx.add_argument('--porcelain', action='store_true', help='machine-readable output')
    group_commit_ctx.add_argument('--long', action='store_true', help='show status in long format (default)')
    group_commit_ctx.add_argument('-z', '--null', action='store_true', help='terminate entries with NUL')
    group_commit_ctx.add_argument('--amend', action='store_true', help='amend previous commit')
    group_commit_ctx.add_argument('--no-post-rewrite', action='store_true', help='bypass post-rewrite hook')
    group_commit_ctx.add_argument('-u', '--untracked-files', metavar='[=<mode>]', choices=['all', 'normal', 'no'], help='show untracked files, optional modes: all, normal, no. (Default: all)')

    # ADD ARGUMENT
    #ArgumentParser.add_argument(name or  ags...[, action ][, nargs ][, const ][, default ][, type ]
    #    [, choices ][, required ][, help ][, metavar ][, dest ])
    #- name or ags - Either a name or a list of option strings, e.g. foo or -f, --foo.
    #- action - The basic type of action to be taken when this argument is encountered at the command line.
    #    store, store_const, store_true, store_false, append, append_const, count, help, version,
    #    subclass of Action with methods __call__ | __init__ override.
    #- nargs - The number of command-line arguments that should be consumed.
    #- const - A constant value required by some action and nargs selections.
    #- default - The value produced if the argument is absent from the command line.
    #- type - The type to which the command-line argument should be converted, built-in types and functions.
    #- choices - A container of the allowable values for the argument.
    #- required - Whether or not the command-line option may be omitted (optionals only).
    #- help - A brief description of what the argument does, %(prog)s, %(type)s, %(default)s.
    #- metavar - A name for the argument in usage messages.
    #- dest - The name of the attribute to be added to the object returned by parse_args().

    parser.add_argument('--version', dest='version', action='store_true', help='print version number', required=False)
    parser.add_argument('-C', dest='path', default='path', type=str, help='C help', required=False)
    parser.add_argument('-c', dest='conf', default='conf', type=str)#, help='C help', required=False)
    flags = parser.parse_args(args)
    flags.func(flags)

if __name__ == "__main__":
    subcommands(sys.argv[1:])


text:
'' Copyright (c) 2013, Kcchouette and b-dauphin on Github
'' All rights reserved.
''
'' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
''
''     Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
''     Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
''     Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
''
'' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FrmBilanIndividuel
    Inherits System.Windows.Forms.Form

    'Form remplace la méthode Dispose pour nettoyer la liste des composants.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Requise par le Concepteur Windows Form
    Private components As System.ComponentModel.IContainer

    'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form
    'Elle peut être modifiée à l'aide du Concepteur Windows Form.
    'Ne la modifiez pas à l'aide de l'éditeur de code.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.CbxNomPre = New System.Windows.Forms.ComboBox()
        Me.TxtNum = New System.Windows.Forms.TextBox()
        Me.btnAff = New System.Windows.Forms.Button()
        Me.rbtNom = New System.Windows.Forms.RadioButton()
        Me.rbtNum = New System.Windows.Forms.RadioButton()
        Me.PnlChoix = New System.Windows.Forms.Panel()
        Me.BtnRet = New System.Windows.Forms.Button()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.LstCacheNum = New System.Windows.Forms.ListBox()
        Me.PnlChoix.SuspendLayout()
        Me.SuspendLayout()
        '
        'CbxNomPre
        '
        Me.CbxNomPre.Enabled = False
        Me.CbxNomPre.Font = New System.Drawing.Font("Courier New", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.CbxNomPre.FormattingEnabled = True
        Me.CbxNomPre.Location = New System.Drawing.Point(101, 29)
        Me.CbxNomPre.Name = "CbxNomPre"
        Me.CbxNomPre.Size = New System.Drawing.Size(241, 22)
        Me.CbxNomPre.Sorted = True
        Me.CbxNomPre.TabIndex = 0
        '
        'TxtNum
        '
        Me.TxtNum.Location = New System.Drawing.Point(101, 3)
        Me.TxtNum.Name = "TxtNum"
        Me.TxtNum.Size = New System.Drawing.Size(41, 20)
        Me.TxtNum.TabIndex = 1
        '
        'btnAff
        '
        Me.btnAff.Location = New System.Drawing.Point(278, 109)
        Me.btnAff.Name = "btnAff"
        Me.btnAff.Size = New System.Drawing.Size(75, 23)
        Me.btnAff.TabIndex = 4
        Me.btnAff.Text = "Afficher"
        Me.btnAff.UseVisualStyleBackColor = True
        '
        'rbtNom
        '
        Me.rbtNom.AutoSize = True
        Me.rbtNom.Location = New System.Drawing.Point(3, 35)
        Me.rbtNom.Name = "rbtNom"
        Me.rbtNom.Size = New System.Drawing.Size(92, 17)
        Me.rbtNom.TabIndex = 5
        Me.rbtNom.Text = "Nom-Prénom :"
        Me.rbtNom.UseVisualStyleBackColor = True
        '
        'rbtNum
        '
        Me.rbtNum.AutoSize = True
        Me.rbtNum.Checked = True
        Me.rbtNum.Location = New System.Drawing.Point(3, 3)
        Me.rbtNum.Name = "rbtNum"
        Me.rbtNum.Size = New System.Drawing.Size(68, 17)
        Me.rbtNum.TabIndex = 6
        Me.rbtNum.TabStop = True
        Me.rbtNum.Text = "Numéro :"
        Me.rbtNum.UseVisualStyleBackColor = True
        '
        'PnlChoix
        '
        Me.PnlChoix.Controls.Add(Me.TxtNum)
        Me.PnlChoix.Controls.Add(Me.rbtNum)
        Me.PnlChoix.Controls.Add(Me.rbtNom)
        Me.PnlChoix.Controls.Add(Me.CbxNomPre)
        Me.PnlChoix.Location = New System.Drawing.Point(11, 27)
        Me.PnlChoix.Name = "PnlChoix"
        Me.PnlChoix.Size = New System.Drawing.Size(352, 67)
        Me.PnlChoix.TabIndex = 7
        '
        'BtnRet
        '
        Me.BtnRet.Location = New System.Drawing.Point(12, 109)
        Me.BtnRet.Name = "BtnRet"
        Me.BtnRet.Size = New System.Drawing.Size(75, 23)
        Me.BtnRet.TabIndex = 8
        Me.BtnRet.Text = "Retour"
        Me.BtnRet.UseVisualStyleBackColor = True
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Location = New System.Drawing.Point(18, 9)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(127, 13)
        Me.Label1.TabIndex = 9
        Me.Label1.Text = "Sélectionnez un candidat"
        '
        'LstCacheNum
        '
        Me.LstCacheNum.FormattingEnabled = True
        Me.LstCacheNum.Location = New System.Drawing.Point(292, 4)
        Me.LstCacheNum.Name = "LstCacheNum"
        Me.LstCacheNum.Size = New System.Drawing.Size(61, 17)
        Me.LstCacheNum.TabIndex = 11
        Me.LstCacheNum.Visible = False
        '
        'FrmBilanIndividuel
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(365, 144)
        Me.ControlBox = False
        Me.Controls.Add(Me.LstCacheNum)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.BtnRet)
        Me.Controls.Add(Me.PnlChoix)
        Me.Controls.Add(Me.btnAff)
        Me.Name = "FrmBilanIndividuel"
        Me.Text = "Bilan Individuel"
        Me.PnlChoix.ResumeLayout(False)
        Me.PnlChoix.PerformLayout()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents CbxNomPre As System.Windows.Forms.ComboBox
    Friend WithEvents TxtNum As System.Windows.Forms.TextBox
    Friend WithEvents btnAff As System.Windows.Forms.Button
    Friend WithEvents rbtNom As System.Windows.Forms.RadioButton
    Friend WithEvents rbtNum As System.Windows.Forms.RadioButton
    Friend WithEvents PnlChoix As System.Windows.Forms.Panel
    Friend WithEvents BtnRet As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents LstCacheNum As System.Windows.Forms.ListBox
End Class

redpajama_set_name: RedPajamaGithub


text:
namespace MvcTurbine.Web.Controllers {
    using System.Collections.Generic;
    using System.Web.Mvc;

    /// <summary>
    /// Custom implementation of <see cref="ActionDescriptor"/> to wire up inferred action execution.
    /// </summary>
    public class InferredActionDescriptor : ActionDescriptor {
        private readonly string actionName;
        private readonly ControllerDescriptor controllerDescriptor;

        /// <summary>
        /// See <see cref="ActionDescriptor"/>
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="controllerDescriptor"></param>
        public InferredActionDescriptor(string actionName, ControllerDescriptor controllerDescriptor, InferredAction inferredAction) {
            InferredAction = inferredAction;
            this.actionName = actionName;
            this.controllerDescriptor = controllerDescriptor;
        }

        /// <summary>
        /// See <see cref="ActionDescriptor.ActionName"/>.
        /// </summary>
        public override string ActionName {
            get { return actionName; }
        }

        /// <summary>
        /// See <see cref="ActionDescriptor.ControllerDescriptor"/>.
        /// </summary>
        public override ControllerDescriptor ControllerDescriptor {
            get { return controllerDescriptor; }
        }

        /// <summary>
        /// See <see cref="InferredAction"/>.
        /// </summary>
        public InferredAction InferredAction { get; private set; }

        /// <summary>
        /// Always returns a <see cref="ViewResult"/> with the specified <see cref="ActionName"/> as the name of the view.
        /// For more information, see <see cref="ActionDescriptor.Execute"/>.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public override object Execute(ControllerContext controllerContext, IDictionary<string, object> parameters) {
            if (InferredAction != null && InferredAction.ModelProvider != null) {
                controllerContext.Controller.ViewData.Model = InferredAction.ModelProvider();
            }

            return new InferredViewResult {
                ViewName = ActionName,
                ViewData = controllerContext.Controller.ViewData
            };
        }

        /// <summary>
        /// Gets an one item array of <see cref="InferredParameterDescriptor"/> containing the current instance.
        /// </summary>
        /// <returns></returns>
        public override ParameterDescriptor[] GetParameters() {
            return new ParameterDescriptor[] { new InferredParameterDescriptor(this, ActionName) };
        }
    }
}


text:
require 'spec_helper'

class TestMiddleware < Acfs::Middleware::Base
end

describe Acfs::Service::Middleware do
  let(:srv_class) { Class.new(Acfs::Service) }
  let(:options) { {} }
  let(:middleware) { TestMiddleware }

  describe '.use' do
    let(:options) { {abc: 'cde'} }

    it 'adds middleware to list' do
      srv_class.use middleware

      expect(srv_class.middleware).to include(middleware)
    end

    it 'adds middleware to stack' do
      srv_class.use middleware

      expect(srv_class.middleware.build(1)).to be_a(middleware)
    end

    it 'instantiates middleware object' do
      expect(middleware).to receive(:new).with(anything, options)

      srv_class.use middleware, options
      srv_class.middleware.build
    end
  end
end


text:
/**
 * Created by avas on 31.07.2015.
 */

angular.module('web')
    .factory('Interceptor', ['$q', 'Exception', function ($q, Exception) {

        return {
            responseError: function (rejection) {
                if (rejection.status === 500 && rejection.data.localizedMessage) {
                    Exception.handle(rejection);
                } else if (rejection.status === 401) {
                    var localLoginPage = "#/login?err=session";
                    var isSso = rejection.data &&
                        rejection.data.loginMode &&
                        rejection.data.loginMode === "SSO";

                    if (!isSso) window.location = localLoginPage;
                }
                return $q.reject(rejection);
            }
        }
    }]);


text:
module NamesManager
  module HardCodedAuthors
    # Sometimes the information to give credit for some commits is just not
    # present in the repository, or is present in a way the application does
    # not understand. This method has a hard-coded list of contributor names
    # for those commits.
    #
    # See the comment in each case for their justification.
    #
    # Please add commits here very exceptionally, only when there's no way
    # we can extract the candidates from the commit. False positives are
    # handled by NamesManager::FalsePositives, and regular aliases are managed
    # by NamesManager::CanonicalNames.
    def hard_coded_authors(commit)
      case commit.sha1
      when '1382f4de1f9b0e443e7884bd4da53c20f0754568'
        # This was a commit backported from 2.3 that missed Dana in the way.
        ['David Burger', 'Dana Jones']
      when '882dd4e6054470ee56c46ab1432861952c81b633'
        # The following patch comes from this ticket https://rails.lighthouseapp.com/projects/8994/tickets/2856
        # but Yehuda told me credit for that commit was screwed up.
        ['David Calavera']
      when 'f9a02b12d15bdbd3c2ed18b16b31b712a77027bc'
        # The attribution is done with parens in a way we do not extract.
        ['Juan Lupión']
      when '4b4aa8f6e08ba2aa2ddce56f1d5b631a78eeef6c'
        # parens again
        ['Jesper Hvirring Henriksen']
      when '945d999aadc9df41487e675fa0a863396cb54e31'
        # Author is "pivotal", but Adam Milligan told me Chris is the author (via github).
        ['Chris Heisterkamp']
      when 'eb457ceee13779ade67e1bdebd2919d476148277'
        # Author is "pivotal", but Adam Milligan told me Joseph is the author (via github).
        ['Joseph Palermo']
      when '6f2c4991efbbc5f567a6df36ca78de4f3ca24ee2', '9dbde4f5cbd0617ee6cce3e41d41335f9c9ce3fd'
        # Author is "pivotal", but Adam Milligan told me he himself is the author (via github).
        ['Adam Milligan']
      when 'ddf2b4add33d5e54c5f5e7adacadbb50d3fa7b52'
        # These were Xavier's edits that for some reason were committed by Mikel.
        ['Xavier Noria']
      when '3b1c69d2dd2b24a29e4443d7dc481589320a3f3e'
        # This was a patch from a bugmash that was applied by Xavier directly.
        # See https://rails.lighthouseapp.com/projects/8994/tickets/4284.
        ['Kieran Pilkington']
      when 'a4041c5392457448cfdfef2e1b24007cfa46948b'
        # Vishnu forked using a different email address, and credit goes in the git commit
        # to Vishnu K. Sharma because of that, but the commit is his.
        ['Vishnu Atrai']
      when 'ec44763f03b49e8c6e3bff71772ba32863a01306'
        # Mohammad El-Abid asked for this fix on Twitter (see https://twitter.com/The_Empty/status/73864303123496960).
        ['Mohammad Typaldos']
      when '99dd117d6292b66a60567fd950c7ca2bda7e01f3'
        # Same here.
        ['Mohammad Typaldos']
      when '3582bce6fdb30730b34b91a17b8bb33066eed7b8'
        # The attribution was wrong, and amended later in 33736bc18a9733d95953f6eaec924db10badc908.
        ['Juanjo Bazán', 'Tarmo Tänav', 'BigTitus']
      when '7e8e91c439c1a877f867cd7ba634f7297ccef04b'
        # Credit was given in a non-conventional manner.
        ['Godfrey Chan', 'Philippe Creux']
      when '798881ecd4510b9e1e5e10529fc2d81b9deb961e', '134c1156dd5713da41c62ff798fe3979723e64cc'
        # Idem.
        ['Godfrey Chan', 'Sergio Campamá']
      when 'b23ffd0dac895aa3fd3afd8d9be36794941731b2'
        # See https://github.com/rails/rails/pull/13692#issuecomment-33617156.
        ['Łukasz Sarnacki', 'Matt Aimonetti']
      when '1240338a02e5decab2a94b651fff78889d725e31'
        # Blake and Arthur paired on this YAML compatibility backport.
        ['Blake Mesdag', 'Arthur Neves']
      when 'd318badc269358c53d9dfb4000e8c4c21a94b578'
        # Adrien worked on the fix, Grey on a regression spec, but only Grey's PR
        # was merged. See https://github.com/fxn/rails-contributors/pull/59.
        ['Grey Baker', 'Adrien Siami']
      when '41adf8710e695f01a8100a87c496231d29e57cf2'
        # This commit uses non-conventional notation for multiple credits.
        ['Mislav Marohnić', 'Geoff Buesing']
      when '6ddde027c4e51262e58f67438672d66a2b278f43'
        # Idem.
        ['Arthur Zapparoli', 'Michael Koziarski']
      when '063c393bf0a2eb762770c97f925b7c2867361ad4'
        ['ivanvr']
      when '872e22c60391dc45b7551cc0698d5530bb310611'
        # This patch comes from https://github.com/rails/web-console/pull/91,
        # originally authored by Daniel, but ported to upstream Rails by Genadi.
        ['Daniel Rikowski', 'Genadi Samokovarov']
      else
        nil
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace DM6To5Migrator
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainWindow());
        }
    }
}


text:
require 'rails_helper'

describe "Authentication", js: true do
  let!(:user) { FactoryGirl.create :user }
  context "login" do
    it "redirects to the root path and shows the admin navbar with valid credentials" do
      visit go_path
      fill_in "Username", with: user.username
      fill_in "Password", with: user.password
      click_on "Log In"
      expect(page).to have_content("#{user.username.titleize}")
    end
  end
end


text:
"""The Goal Zero Yeti integration."""
from __future__ import annotations

import logging

from goalzero import Yeti, exceptions

from homeassistant.components.binary_sensor import DOMAIN as DOMAIN_BINARY_SENSOR
from homeassistant.components.sensor import DOMAIN as DOMAIN_SENSOR
from homeassistant.components.switch import DOMAIN as DOMAIN_SWITCH
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, ATTR_MODEL, CONF_HOST, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import (
    CoordinatorEntity,
    DataUpdateCoordinator,
    UpdateFailed,
)

from .const import (
    ATTRIBUTION,
    DATA_KEY_API,
    DATA_KEY_COORDINATOR,
    DOMAIN,
    MIN_TIME_BETWEEN_UPDATES,
)

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [DOMAIN_BINARY_SENSOR, DOMAIN_SENSOR, DOMAIN_SWITCH]

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Goal Zero Yeti from a config entry."""
    name = entry.data[CONF_NAME]
    host = entry.data[CONF_HOST]

    api = Yeti(host, async_get_clientsession(hass))
    try:
        await api.init_connect()
    except exceptions.ConnectError as ex:
        raise ConfigEntryNotReady(f"Failed to connect to device: {ex}") from ex

    async def async_update_data() -> None:
        """Fetch data from API endpoint."""
        try:
            await api.get_state()
        except exceptions.ConnectError as err:
            raise UpdateFailed("Failed to communicate with device") from err

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        name=name,
        update_method=async_update_data,
        update_interval=MIN_TIME_BETWEEN_UPDATES,
    )
    await coordinator.async_config_entry_first_refresh()
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        DATA_KEY_API: api,
        DATA_KEY_COORDINATOR: coordinator,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok

class YetiEntity(CoordinatorEntity):
    """Representation of a Goal Zero Yeti entity."""

    _attr_extra_state_attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}

    def __init__(
        self,
        api: Yeti,
        coordinator: DataUpdateCoordinator,
        name: str,
        server_unique_id: str,
    ) -> None:
        """Initialize a Goal Zero Yeti entity."""
        super().__init__(coordinator)
        self.api = api
        self._name = name
        self._server_unique_id = server_unique_id

    @property
    def device_info(self) -> DeviceInfo:
        """Return the device information of the entity."""
        return DeviceInfo(
            identifiers={(DOMAIN, self._server_unique_id)},
            manufacturer="Goal Zero",
            model=self.api.sysdata[ATTR_MODEL],
            name=self._name,
            sw_version=self.api.data["firmwareVersion"],
        )


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016-present Open Networking Laboratory
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>onos-bmv2-protocol</artifactId>
        <groupId>org.onosproject</groupId>
        <version>1.7.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>onos-bmv2-protocol-ctl</artifactId>

    <packaging>bundle</packaging>

    <dependencies>
        <dependency>
            <groupId>org.apache.thrift</groupId>
            <artifactId>libthrift</artifactId>
            <version>0.9.3</version>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-bmv2-protocol-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-bmv2-protocol-thrift-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.felix</groupId>
            <artifactId>org.apache.felix.scr.annotations</artifactId>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-core-serializers</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.onosproject</groupId>
                <artifactId>onos-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
<!-- Navigation -->

<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    // var $body   = document.body;
    // var $toggle = document.querySelector('.navbar-toggle');
    // var $navbar = document.querySelector('#huxblog_navbar');
    // var $collapse = document.querySelector('.navbar-collapse');

    // $toggle.addEventListener('click', handleMagic)
    // function handleMagic(e){
    //     if ($navbar.className.indexOf('in') > 0) {
    //     // CLOSE
    //         $navbar.className = " ";
    //         // wait until animation end.
    //         setTimeout(function(){
    //             // prevent frequently toggle
    //             if($navbar.className.indexOf('in') < 0) {
    //                 $collapse.style.height = "0px"
    //             }
    //         },400)
    //     }else{
    //     // OPEN
    //         $collapse.style.height = "auto"
    //         $navbar.className += " in";
    //     }
    // }
</script>


text:
import { imageDemoTest } from '../../../tests/shared/imageTest';

describe('AutoComplete image', () => {
  imageDemoTest('auto-complete');
});


text:
import logging
import numpy as np
import os
import subprocess
import tempfile

from . import scene
from . import rman

ZERO = scene.npvector((0, 0, 0))

_film = rman.Identifier(
    'Film', positional=['string'],
    named={
        'xresolution': 'integer',
        'yresolution': 'integer',
        'cropwindow': 'float[4]',
        'filename': 'string'
    })

_look_at = rman.Identifier('LookAt', positional=['point', 'point', 'vector'])

_camera = rman.Identifier(
    'Camera', positional=['string'],
    named={
        'shutteropen': 'float',
        'shutterclose': 'float',
        'lensradius': 'float',
        'focaldistance': 'float',
        'fov': 'float',
        'autofocus': 'bool'
    })

_sampler = rman.Identifier(
    'Sampler', positional=['string'],
    named={
        'pixelsamples': 'integer',
    })

_area_light_source = rman.Identifier(
    'AreaLightSource', positional=['string'],
    named={'L': 'rgb'})

_translate = rman.Identifier('Translate', positional=['vector'])

_rotate = rman.Identifier('Rotate', positional=['float', 'vector'])

_shape = rman.Identifier(
    'Shape', positional=['string'],
    named={
        'radius': 'float',
        'indices': 'integer[]',
        'P': 'point[]'
    })

class PbrtRenderer(object):
  def __init__(self, executable=None, output_file=None, scene_file=None,
               width=384, height=256, samples_per_pixel=None, slaves=None,
               exrpptm=None, exrnormalize=None, exrtopng=None):
    self.executable = executable
    self.output_file = output_file
    self.scene_file = scene_file
    self.width = width
    self.height = height
    self.samples_per_pixel = samples_per_pixel
    self.scene_file_ext = 'pbrt'
    self.exrpptm = exrpptm
    self.exrnormalize = exrnormalize
    self.exrtopng = exrtopng

  @property
  def output_file(self):
    return self._output_file

  @output_file.setter
  def output_file(self, value):
    logging.info('output_file = %s', value)
    if value is None:
      self._output_file = None
      self._exr_file = None
      return
    self._output_file = value
    base, ext = os.path.splitext(value)
    logging.info('base = %s, ext = %s', base, ext)
    assert ext == '.png'
    self._exr_file = base + '.exr'

  def render(self, scene, generate_only=False):
    scene_file = self.scene_file or tempfile.mkstemp()[1]
    logging.info('Created scene file %s', scene_file)
    self._write_scene_file(scene, scene_file)

    if not generate_only:
      self._run_renderer(scene_file)

    if not self.scene_file:
      logging.info('Deleting %s', scene_file)
      os.remove(scene_file)

  def _write_object(self, writer, obj):
    writer.begin_block('Attribute')

    if obj.light is not None:
      color = obj.light.color * obj.light.power
      writer.write(_area_light_source('diffuse', L=obj.light.color))

    if isinstance(obj, scene.Sphere):
      if not np.array_equal(obj.center, ZERO):
        writer.write(_translate(obj.center))
      writer.write(_shape("sphere", radius=obj.radius))
    else:
      assert False, "Unsupported object type"

    writer.end_block('Attribute')

  def _write_scene_file(self, scene, scene_file):
    with rman.FileWriter(scene_file) as writer:
      writer.write(_look_at(scene.camera.loc, scene.camera.to, scene.camera.up))
      writer.write(_film(
          'image',
          xresolution=self.width, yresolution=self.height,
          filename=self._exr_file))
      writer.write(_camera('perspective', fov=scene.camera.fov))
      if self.samples_per_pixel:
        writer.write(_sampler('lowdiscrepancy', pixelsamples=self.samples_per_pixel))

      writer.begin_block('World')
      for obj in scene.objects:
        self._write_object(writer, obj)
      writer.end_block('World')

  def _run_renderer(self, scene_file):
    if self.executable is None:
      logging.error(
          'Trying to call pbrt, but path to the executable is not specified.')
    assert self.executable is not None
    args = [self.executable, scene_file]
    logging.info('Running %s', ' '.join(args))
    subprocess.call(args)

    args = [self.exrpptm, '-c', '1.0', self._exr_file, self._exr_file + '.pp']
    logging.info('Running %s', ' '.join(args))
    subprocess.call(args)
    args = [self.exrnormalize, self._exr_file + '.pp', self._exr_file + '.n']
    logging.info('Running %s', ' '.join(args))
    subprocess.call(args)
    args = [self.exrtopng, self._exr_file + '.n', self.output_file]
    logging.info('Running %s', ' '.join(args))
    subprocess.call(args)

  def batch_render(self, scene_files):
    logging.info('Rendering %d files', len(scene_files))
    for f in scene_files:
      self._run_renderer(f)


text:
<?php

namespace LIN3S\WPFoundation\Configuration\Assets;

/**
 * Interface of assets class. This interface forces to register
 * all the scripts and stylesheet under assets method.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 */
interface AssetsInterface
{
    const ASSETS_JS = 'assets/js';
    const BUILD_JS = 'build/js';
    const CSS = 'build/css';
    const VENDOR = 'assets/vendor';
    const NPM = '../node_modules';

    /**
     * Registers all the scripts and stylesheet files that they
     * are going to be execute when the WP_DEBUG is "true". Development mode.
     *
     * It's a callback of WordPress internal "wp_enqueue_scripts" method.
     */
//    public function developmentAssets();

    /**
     * Registers all the scripts and stylesheet files that they
     * are going to be execute when the WP_DEBUG is "false". Production mode.
     *
     * It's a callback of WordPress internal "wp_enqueue_scripts" method.
     */
//    public function productionAssets();

    /**
     * Registers all the scripts and stylesheet files used in wp-admin.
     * It's a callback of WordPress internal "admin_enqueue_scripts" method.
     */
    public function adminAssets();
}


text:
import webapp2

from framework.plugin_loader import get_plugins

class Handler(object):
    AUTH_ADMIN = 'admin'
    AUTH_AUTHENTICATED = 'authenticated'
    AUTH_UNAUTHENTICATED = 'unauthenticated'

    def __init__(self, url=None, handler=None):
        self.url = url
        self.handler = handler

class Module(object):
    def __init__(self, name=None, scopes=None, sort_order=0):
        self.name = name
        self.scopes = scopes
        self.sort_order = sort_order

def get_handlers_for_auth(auth):
    for plugin in get_plugins():
        for handler in plugin.get_handlers(auth):
            yield webapp2.Route(handler.url, handler.handler)

def get_client_handlers(handlers):
    home_handler = None
    for handler in handlers:
        if handler.template == '/':
            home_handler = handler.handler
            break
    if home_handler:
        for plugin in get_plugins():
            for route in plugin.get_client_routes():
                yield webapp2.Route(route, home_handler)


text:
app.registerConfig("Config/BaseIncludeConfig", {

    incPropNumber: [ "number", 200 ],

    incPropString: [ "string", "my string" ]

});


text:
/*
 * This is not the original file distributed by the Apache Software Foundation
 * It has been modified by the Hipparchus project
 */

package org.hipparchus.ode;

import org.hipparchus.CalculusFieldElement;
import org.hipparchus.ode.sampling.FieldODEStateInterpolator;
import org.hipparchus.ode.sampling.FieldODEStepHandler;
import org.hipparchus.util.MathUtils;

/**
 * This class is used to handle steps for the test problems
 * integrated during the junit tests for the ODE integrators.
 * @param <T> the type of the field elements
 */
public class TestFieldProblemHandler<T extends CalculusFieldElement<T>>
    implements FieldODEStepHandler<T> {

    /** Associated problem. */
    private TestFieldProblemAbstract<T> problem;

    /** Maximal errors encountered during the integration. */
    private T maxValueError;
    private T maxTimeError;

    /** Error at the end of the integration. */
    private T lastError;

    /** Time at the end of integration. */
    private T lastTime;

    /** ODE solver used. */
    private FieldODEIntegrator<T> integrator;

    /** Expected start for step. */
    private T expectedStepStart;

    /**
     * Simple constructor.
     * @param problem problem for which steps should be handled
     * @param integrator ODE solver used
     */
    public TestFieldProblemHandler(TestFieldProblemAbstract<T> problem, FieldODEIntegrator<T> integrator) {
        this.problem      = problem;
        this.integrator   = integrator;
        maxValueError     = problem.getField().getZero();
        maxTimeError      = problem.getField().getZero();
        lastError         = problem.getField().getZero();
        expectedStepStart = null;
    }

    public void init(FieldODEStateAndDerivative<T> state0, T t) {
        maxValueError     = problem.getField().getZero();
        maxTimeError      = problem.getField().getZero();
        lastError         = problem.getField().getZero();
        expectedStepStart = null;
    }

    public void handleStep(FieldODEStateInterpolator<T> interpolator) {

        T start = interpolator.getPreviousState().getTime();
        if (start.subtract(problem.getInitialState().getTime()).divide(integrator.getCurrentSignedStepsize()).norm() > 0.001) {
            // multistep integrators do not handle the first steps themselves
            // so we have to make sure the integrator we look at has really started its work
            if (expectedStepStart != null) {
                // the step should either start at the end of the integrator step
                // or at an event if the step is split into several substeps
                T stepError = MathUtils.max(maxTimeError, start.subtract(expectedStepStart).abs());
                for (T eventTime : problem.getTheoreticalEventsTimes()) {
                    stepError = MathUtils.min(stepError, start.subtract(eventTime).abs());
                }
                maxTimeError = MathUtils.max(maxTimeError, stepError);
            }
            expectedStepStart = interpolator.getCurrentState().getTime();
        }

        T pT = interpolator.getPreviousState().getTime();
        T cT = interpolator.getCurrentState().getTime();
        T[] errorScale = problem.getErrorScale();

        // walk through the step
        for (int k = 0; k <= 20; ++k) {

            T time = pT.add(cT.subtract(pT).multiply(k).divide(20));
            T[] interpolatedY = interpolator.getInterpolatedState(time).getPrimaryState();
            T[] theoreticalY  = problem.computeTheoreticalState(time);

            // update the errors
            for (int i = 0; i < interpolatedY.length; ++i) {
                T error = errorScale[i].multiply(interpolatedY[i].subtract(theoreticalY[i]).norm());
                maxValueError = MathUtils.max(error, maxValueError);
            }
        }
    }

    public void finish(FieldODEStateAndDerivative<T> finalState) {
        T[] theoreticalY  = problem.computeTheoreticalState(finalState.getTime());
        for (int i = 0; i < finalState.getCompleteState().length; ++i) {
            T error = finalState.getCompleteState()[i].subtract(theoreticalY[i]).abs();
            lastError = MathUtils.max(error, lastError);
        }
        lastTime = finalState.getTime();
    }

    /**
     * Get the maximal value error encountered during integration.
     * @return maximal value error
     */
    public T getMaximalValueError() {
        return maxValueError;
    }

    /**
     * Get the maximal time error encountered during integration.
     * @return maximal time error
     */
    public T getMaximalTimeError() {
        return maxTimeError;
    }

    /**
     * Get the error at the end of the integration.
     * @return error at the end of the integration
     */
    public T getLastError() {
        return lastError;
    }

    /**
     * Get the time at the end of the integration.
     * @return time at the end of the integration.
     */
    public T getLastTime() {
        return lastTime;
    }

}


text:
'use strict';

const editBlockId = '#edit';
const infoBlockId = '#info';

const trackArtLinkId = '#album-art-link';
const trackArtImgId = '#album-art-img';

const editBtnId = '#edit-link';
const loveBtnId = '#love-link';
const skipBtnId = '#skip-link';
const unskipBtnId = '#unskip-link';
const submitBtnId = '#submit-link';
const swapBtnId = '#swap-link';
const revertBtnId = '#revert-link';

const inputGenericId = '#edit input';

const fieldTitleMap = {
	album: 'infoViewAlbumPage',
	track: 'infoViewTrackPage',
	artist: 'infoViewArtistPage',
	albumArtist: 'infoViewArtistPage',
};

const defaultTrackArtUrl = '/icons/cover_art_default.png';

class InfoPopupView {
	constructor() {
		this.infoPopup = this.makeInfoPopup();

		this.clickListeners = {
			[loveBtnId]: this.infoPopup.onLoveBtnClick,

			[editBtnId]: this.infoPopup.onEditBtnClick,
			[revertBtnId]: this.infoPopup.onRevertBtnClick,
			[skipBtnId]: this.infoPopup.onSkipBtnClick,
			[submitBtnId]: this.infoPopup.onSubmitBtnClick,
			[swapBtnId]: this.infoPopup.onSwapBtnClick,
		};

		this.setupControlListeners();
	}

	/**
	 * Functions must be implemented.
	 */

	makeInfoPopup() {
		throw new Error('No implementation!');
	}

	i18n(/* messageId, ...placeholders */) {
		throw new Error('No implementation!');
	}

	/** Basic functions */

	getInfoPopup() {
		return this.infoPopup;
	}

	/** Controls */

	focusOnInput() {
		$(inputGenericId).first().focus();
	}

	isDebugInfoVisible() {
		return $('#debug').prop('hidden') === false;
	}

	setConnectorLabel(label) {
		$('#label').text(label);
	}

	setEditBlockVisible() {
		$(infoBlockId).prop('hidden', true);
		$(editBlockId).prop('hidden', false);
	}

	setInfoBlockVisible() {
		$(infoBlockId).prop('hidden', false);
		$(editBlockId).prop('hidden', true);
	}

	setTrackArt(url) {
		$(trackArtImgId).attr('src', url || defaultTrackArtUrl);
		$(trackArtLinkId).attr('href', url || defaultTrackArtUrl);
	}

	setUserLovedIcon(isLoved) {
		if (isLoved) {
			$(loveBtnId).addClass('loved');
			$(loveBtnId).removeClass('unloved');
		} else {
			$(loveBtnId).addClass('unloved');
			$(loveBtnId).removeClass('loved');
		}
		$(loveBtnId).attr('title', this.i18n(isLoved ? 'infoUnlove' : 'infoLove'));
	}

	setUserPlayCount(playCount) {
		if (playCount === 0) {
			$('#userPlayCount').prop('hidden', true);
		} else {
			$('#userPlayCount').prop('hidden', false);
			$('#userPlayCount').attr('title', this.i18n('infoYourScrobbles', playCount));
			$('#userPlayCountLabel').text(playCount);
		}
	}

	showDebugInfo(data) {
		$('#debug').prop('hidden', false);
		$('#debug pre').text(data);
	}

	/** Buttons */

	setEditButtonState(flag) {
		this.setButtonState(
			editBtnId, flag, 'infoEditTitle', 'infoEditUnableTitle'
		);
	}

	setRevertButtonState(flag) {
		this.setButtonState(
			revertBtnId, flag, 'infoRevertTitle', 'infoRevertUnableTitle'
		);
	}

	setRevertButtonVisible(flag) {
		$(revertBtnId).prop('hidden', !flag);
	}

	setSkipButtonState(flag) {
		this.setButtonState(
			skipBtnId, flag, 'infoSkipTitle', 'infoSkipUnableTitle'
		);
	}

	setSkipButtonVisible(flag) {
		$(skipBtnId).prop('hidden', !flag);
	}

	setSubmitButtonState(flag) {
		this.setButtonState(
			submitBtnId, flag, 'infoSubmitTitle', 'infoSubmitUnableTitle'
		);
	}

	setSwapButtonState(flag) {
		this.setButtonState(
			swapBtnId, flag, 'infoSwapTitle', 'infoSwapUnableTitle'
		);
	}

	setUnskipButtonState(flag) {
		this.setButtonState(
			unskipBtnId, flag, 'infoSkippedTitle', 'infoSkippedTitle'
		);
	}

	setUnskipButtonVisible(flag) {
		$(unskipBtnId).prop('hidden', !flag);
	}

	/** Fields */

	getEditedTrackFields() {
		const trackInfo = {};

		for (const field of ['artist', 'track', 'album', 'albumArtist']) {
			const selector = InfoPopupView.getInputSelector(field);
			trackInfo[field] = $(selector).val().trim() || null;
		}

		return trackInfo;
	}

	setFieldValue(field, value) {
		const selector = InfoPopupView.getFieldSelector(field);

		$(selector).text(value);
		$(selector).prop('hidden', !value);
	}

	setFieldInput(field, value) {
		const selector = InfoPopupView.getInputSelector(field);

		$(selector).val(value);
	}

	setFieldUrl(field, url, title) {
		const selector = InfoPopupView.getFieldSelector(field);
		const fieldTitleId = fieldTitleMap[field];

		$(selector).attr('href', url);
		$(selector).attr('title', this.i18n(fieldTitleId, title));
	}

	removeFieldUrl(field) {
		const selector = InfoPopupView.getFieldSelector(field);

		$(selector).removeAttr('href');
		$(selector).removeAttr('title');
	}

	/** Internal functions */

	setupControlListeners() {
		for (const controlId in this.clickListeners) {
			const onClick = this.clickListeners[controlId].bind(this.infoPopup);

			$(controlId).off('click');
			$(controlId).on('click', () => {
				onClick();
			});
		}

		$(inputGenericId).off('keyup');
		$(inputGenericId).on('keyup', (e) => {
			const isSubmitAction = e.which === 13;

			if (isSubmitAction) {
				this.infoPopup.onEnterPressed();
			} else {
				this.infoPopup.onInputsChanged();
			}
		});

		$('body').click((e) => {
			if (e.altKey) {
				this.infoPopup.onAltClick();
			}
		});
	}

	setControlEnabled(selector, state) {
		$(selector).prop('disabled', !state);
	}

	setButtonTitle(selector, titleId) {
		$(selector).attr('title', this.i18n(titleId));
	}

	setButtonState(selector, state, enabledTitleId, disabledTitleId) {
		this.setControlEnabled(selector, state);
		if (state) {
			this.setButtonTitle(selector, enabledTitleId);
		} else {
			this.setButtonTitle(selector, disabledTitleId);
		}
	}

	/** Helpers */

	static getFieldSelector(field) {
		return `#${field}`;
	}

	static getInputSelector(field) {
		return `#${field}-input`;
	}
}

define(() => InfoPopupView);


text:
package org.wso2.andes.server.cluster.coordination.hazelcast;

import com.hazelcast.core.ITopic;
import com.hazelcast.core.MessageListener;
import org.apache.commons.lang.StringUtils;
import org.wso2.andes.configuration.AndesConfigurationManager;
import org.wso2.andes.configuration.enums.AndesConfiguration;
import org.wso2.andes.kernel.AndesContext;
import org.wso2.andes.kernel.AndesContextInformationManager;
import org.wso2.andes.kernel.AndesException;
import org.wso2.andes.kernel.disruptor.inbound.InboundEventManager;
import org.wso2.andes.kernel.subscription.AndesSubscriptionManager;
import org.wso2.andes.server.cluster.coordination.BindingNotificationHandler;
import org.wso2.andes.server.cluster.coordination.ClusterNotification;
import org.wso2.andes.server.cluster.coordination.ClusterNotificationListenerManager;
import org.wso2.andes.server.cluster.coordination.CoordinationConstants;
import org.wso2.andes.server.cluster.coordination.DBSyncNotificationHandler;
import org.wso2.andes.server.cluster.coordination.ExchangeNotificationHandler;
import org.wso2.andes.server.cluster.coordination.QueueNotificationHandler;
import org.wso2.andes.server.cluster.coordination.SubscriptionNotificationHandler;

public class HazelcastClusterNotificationListenerImpl implements ClusterNotificationListenerManager {

    /**
     * Distributed topic to sent among cluster nodes to run andes recover task.
     */
    private ITopic<ClusterNotification> dbSyncNotifierChannel;

    /**
     * Distributed topic to send cluster notifications among cluster nodes.
     */
    private ITopic<ClusterNotification> clusterNotifierChannel;

    /**
     * IDs of subscribers registered for Hazelcast topics
     */
    private String dbSyncNotificationListenerId;
    private String clusterEventListenerId;

    /**
     * Hazelcast agent for forwarding HZ related requests
     */
    private HazelcastAgent hazelcastAgent;

    /**
     * Defines the maximum number of messages that will be read at a single try from a Hazelcast reliable topic.
     * This value is set to a very low number since these reliable topics only handle cluster notifications on
     * subscription changes, exchange changes, etc.
     * and the frequency of messages being published is very low.
     */
    private final int HAZELCAST_RELIABLE_TOPIC_READ_BACH_SIZE = 5;

    /**
     * Defines the maximum number of messages that can be stored in the ring buffer associated with a
     * Hazelcast Reliable Topic. The buffer could be initialized with a somewhat low number since these reliable topics
     * only handle cluster notifications on subscription changes, exchange changes, etc. which are a very not so
     * frequent. But, there could be extreme and rare situations where subscriptions, bindings, etc. change at a very
     * high rate and to be able to tolerate that, the capacity is kept at 1000.
     */
    private final int HAZELCAST_RING_BUFFER_CAPACITY = 1000;

    /**
     * Disables statistics on the messages published to Hazelcast Reliable Topics.
     * We don't need statistics on the messages that are published, therefore, we have disabled statistics.
     */
    private final boolean ENABLE_STATISTICS = false;

    /**
     * Create a Hazelcast based cluster notification implementation
     *
     * @param hazelcastAgent Hazelcast agent of broker
     */
    public HazelcastClusterNotificationListenerImpl(HazelcastAgent hazelcastAgent) {
        this.hazelcastAgent = hazelcastAgent;
        addTopics();
    }

    @Override
    public void initializeListener(InboundEventManager inboundEventManager,
                                   AndesSubscriptionManager subscriptionManager,
                                   AndesContextInformationManager contextInformationManager) throws AndesException {

        addTopicListeners(inboundEventManager, subscriptionManager, contextInformationManager);
    }

    /**
     * Recreate Hazelcast topics and add listeners.
     */
    public void reInitializeListener() throws AndesException {
        addTopics();
        InboundEventManager eventManager = AndesContext.getInstance().getInboundEventManager();
        AndesSubscriptionManager subscriptionManager = AndesContext.getInstance().getAndesSubscriptionManager();
        AndesContextInformationManager contextInformationManager = AndesContext.getInstance()
                .getAndesContextInformationManager();
        addTopicListeners(eventManager, subscriptionManager, contextInformationManager);
    }

    @Override
    public void stopListener() throws AndesException {
        //Do nothing, this will be handled by shutting down the hazelcast instance.
    }

    private void addTopics() {
        // Defines the time it takes for a message published to a Hazelcast reliable topic to be expired.
        // The messages that are published to these topics should ideally be read at the same time. One instance
        // where this would not happen is when a node gets disconnected. Since all the messages that are published
        // to these topics are stored in the database, this situation is handled by synchronizing the information in
        // the databases when the node recovers. Therefore, we do not need undelivered messages to delivered
        // after a while. Therefore, we need messages to be held in the buffer onle for a very little time.
        int hazelcastRingBufferTTL = AndesConfigurationManager.readValue(AndesConfiguration
                .COORDINATION_CLUSTER_NOTIFICATION_TIMEOUT);

        // Creating the channel for communicating database sync notification to run andes recovery task.
        this.dbSyncNotifierChannel = hazelcastAgent.createReliableTopic(
                CoordinationConstants.HAZELCAST_DB_SYNC_NOTIFICATION_TOPIC_NAME,
                ENABLE_STATISTICS, HAZELCAST_RELIABLE_TOPIC_READ_BACH_SIZE, HAZELCAST_RING_BUFFER_CAPACITY,
                hazelcastRingBufferTTL);

        // Creating the channel for publishing and subscribing cluster notifications.
        this.clusterNotifierChannel = hazelcastAgent.createReliableTopic(
                CoordinationConstants.HAZELCAST_CLUSTER_EVENT_NOTIFIER_TOPIC_NAME,
                ENABLE_STATISTICS, HAZELCAST_RELIABLE_TOPIC_READ_BACH_SIZE, HAZELCAST_RING_BUFFER_CAPACITY,
                hazelcastRingBufferTTL);

    }

    private void addTopicListeners(InboundEventManager inboundEventManager,
                                   AndesSubscriptionManager subscriptionManager,
                                   AndesContextInformationManager contextInformationManager) throws AndesException {

        // Register cluster notification listener and add handlers assigned for different types of artifacts.
        HZBasedClusterNotificationListener hzBasedClusterNotificationListener = new
                HZBasedClusterNotificationListener();
        hzBasedClusterNotificationListener.addSubscriptionNotificationHandler(new SubscriptionNotificationHandler
                (subscriptionManager, inboundEventManager));
        hzBasedClusterNotificationListener.addBindingNotificationHandler(new BindingNotificationHandler
                (contextInformationManager, inboundEventManager));
        hzBasedClusterNotificationListener.addExchangeNotificationHandler(new ExchangeNotificationHandler
                (contextInformationManager, inboundEventManager));
        hzBasedClusterNotificationListener.addQueueNotificationHandler(new QueueNotificationHandler
                (contextInformationManager, inboundEventManager));

        clusterEventListenerId = checkAndRegisterListerToTopic(clusterNotifierChannel,
                hzBasedClusterNotificationListener, clusterEventListenerId);

        // Register DB sync notification listener.
        HZBasedDatabaseSyncNotificationListener HZBasedDatabaseSyncNotificationListener = new
                HZBasedDatabaseSyncNotificationListener();
        HZBasedDatabaseSyncNotificationListener.addHandler(new DBSyncNotificationHandler());

        dbSyncNotificationListenerId = checkAndRegisterListerToTopic(dbSyncNotifierChannel,
                HZBasedDatabaseSyncNotificationListener, dbSyncNotificationListenerId);
    }

    /**
     * Check if there is a listener registered by given id. If registered,
     * remove and register the new listener
     *
     * @param topic      Hazelcast topic
     * @param listener   Listener to register
     * @param listenerId ID of the listener to check if there is an existing
     * @return ID of the registered subscriber
     */
    private String checkAndRegisterListerToTopic(ITopic<ClusterNotification> topic,
                                                 MessageListener<ClusterNotification> listener,
                                                 String listenerId) {
        if (StringUtils.isNotEmpty(listenerId)) {
            topic.removeMessageListener(listenerId);
        }
        return topic.addMessageListener(listener);

    }

    /**
     * Get channel for publishing and subscribing cluster notifications.
     *
     * @return {@link ITopic} for cluster notifications
     */
    public ITopic<ClusterNotification> getClusterNotificationChannel() {
        return clusterNotifierChannel;
    }

    /**
     * Get channel for publishing and subscribing db sync events.
     *
     * @return {@link ITopic} for db sync events
     */
    public ITopic<ClusterNotification> getDBSyncNotificationChannel() {
        return dbSyncNotifierChannel;
    }
}


text:
#ifndef STREETYP_H
#define STREETYP_H

#include "types.h"
#include "arraydef.h"

//}

/*
  A \texttt{Reference} consists of an \texttt{address} pointing a leaf,
  or to a branching node. The boolean \texttt{toleaf} is \texttt{True} if
  and only if \texttt{address} points to a leaf.
*/

typedef struct
{
  BOOL toleaf;
  Uint *address;
} Reference;            // \Typedef{Reference}

/*
  The following types are used for references to leaves and
  branching nodes, respectively. We will always identify a leaf and
  and branching node with their references.
*/

typedef Uint * Bref;    // \Typedef{Bref}
typedef Uint * Lref;    // \Typedef{Lref}

/*
  For each branching node we store five values, as described in Section
  \ref{Representation}. These values comprise the following structure.
*/

typedef struct
{
  Uint headposition,        // the head position of the branching node
       depth;               // the depth of the branching node
  Bref suffixlink;          // the suffix link is always to a branching node
  Reference firstchild,     // the reference to the first child
            branchbrother;  // the reference to the right brother;
                            // if this doesn't exist then it's \texttt{NULL}
} Branchinfo;               // \Typedef{Branchinfo}

/*
  For each leaf, we store a reference to its right brother, which is
  \texttt{NULL}, if the right brother does not exist. This is
  expressed in the type synonym \texttt{Leafinfo}.
*/

typedef Reference Leafinfo;  // \Typedef{Leafinfo}

/*
  A suffix tree is implemented by the type \texttt{Suffixtree}.
  This structure contains several components which are mostly only used
  during the suffix tree construction. For applications, assume the
  following definition. Note that the input sequence is represented
  as an array of elements of type \texttt{SYMBOL}. The latter
  is a synonym for \texttt{Uchar} by default.

@typedef struct
@{
@  SYMBOL *text;     // points to the input string
@  Uint textlen;     // the length of the input string
@  Uint *branchtab;  // stores the infos for the branching nodes
@  Uint *leaftab;    // stores the brother-references of the leaves
@} Suffixtree;       // \Typedef{Suffixtree}

*/

//\Ignore{

struct Suffixtreetype
{
  Uint textlen,               // the length of the input string
       *leaftab,              // stores the brother-references of the leafs
       *branchtab,            // table TBranch
       *rootchildren;         // references to successors of root
  SYMBOL *text,               // points to the input string
         *sentinel;           // points to the position of the \(\$\)-symbol

  Uint nextfreeleafnum,       // the number of the next leaf
       headnodedepth,         // the depth of the headnode
       insertnode,            // the node the split edge leads to
       insertprev,            // the edge preceeding the split edge
       smallnotcompleted,     // the number of small nodes in the current chain
       nextfreebranchnum,     // the number of the next free branch node
       onsuccpath,            // refers to node on success path of headnode
       currentdepth,          // depth of the new branch node
       branchnodeoffset,      // number of leafs in tree
       alphasize,             // the number of different characters in t
       maxbranchdepth,        // maximal depth of branching node
       largenode,             // number of large nodes
       smallnode,             // number of small nodes
       *setlink,              // address of a nil-reference
       *nextfreeleafptr,      // points to next free entry in leaftab
       *chainstart,           // address of the node, current chains starts at
       *nextfreebranch,       // reference to next free base addr. in branchtab
       *headnode,             // left component of head location
       currentbranchtabsize,  // current number of cells in branchtab
       *firstnotallocated,    // refers to the last address, such that at
                              // least \texttt{LARGEINTS} integers are
                              // available. So a large node can be stored in
                              // the available amount of space.
       *nonmaximal,           // bit table: if node with headposition \(i\) is
                              // not maximal, then \(nonmaximal[i]\) is set.
       *leafcounts;           // holds counts of the number of leafs in subtree
                              // indexed by headposition
  BOOL setatnewleaf;          // nil-reference is stored in new leaf
  SYMBOL *headstart,          // these references represent the right component
         *headend,            // of the head location \((\overline{u},v)\).
                              // \emph{headstart} refers to the first character
                              // of \(v\), and \emph{headend} to the last
                              // character. In case, \(v=\varepsilon\),
                              // \(\emph{headend}=\emph{NULL}\).
         *tailptr;            // points to the tail

#ifdef DEBUG
  char * (*showsymbolstree)(SYMBOL,Uchar *);
  Uchar *alphabet;
  Uint splitleafedge,
       splitinternaledge,
       artificial,
       insertleafcalls,
       largelinks,
       largelinkwork,
       largelinklinkwork,
       multiplications,
       nodecount,
       *maxset;
  void *generalcounter;
#endif
#if (SYMBOLBYTES == 2) || (SYMBOLBYTES == 4)
  Sint lastcharindex;
#endif

};

typedef struct Suffixtreetype Suffixtree;

DECLAREARRAYSTRUCT(Bref);

//}

/*
  A location is implemented by the type \texttt{Location}.
*/

typedef struct
{
  Stringtype locstring; // string represented by location
  Bref previousnode;    // reference to previous node (which is branching)
  SYMBOL *firstptr;     // pointer to first character of edge label
  Uint edgelen,         // length of edge
       remain;          // number of remaining characters on edge
  Reference nextnode;   // reference to node the edge points to
} Location;             // \Typedef{Location}

/*
  If a location is a node \(\overline{u}\), we set \texttt{remain} to 0, and
  store a reference to \(\overline{u}\) in \texttt{nextnode}. Moreover, we
  store a position where \(u\) starts and its length in \texttt{locstring}.
  If the location is of the form \((\overline{u},v,w,\overline{uvw})\),
  then the components of the location satisfies the following values:
  \begin{enumerate}
  \item
  \texttt{previousnode} is a reference to \(\overline{u}\)
  \item
  \texttt{firstptr} points to the first symbol of the edge label \(vw\).
  \item
  \(\texttt{edgelen}=\Size{vw}\)
  \item
  \(\texttt{remain}=\Size{w}\)
  \item
  \texttt{nextnode} is a reference to \(\overline{uvw}\).
  \end{enumerate}
  Since \(w\) is not empty, a location is a node location if and only if
  \texttt{remain} is 0.
*/

//\Ignore{

/*
  A simple location stores just a part of information stored in a suffix tree.
*/

typedef struct
{
  Uint remain,
       textpos;  // these last two items are redundant and can be computed
  Reference nextnode;
} Simpleloc;     // \Typedef{Simpleloc}

DECLAREARRAYSTRUCT(Simpleloc);

/*
  A path in the suffix tree is stored as an array of \texttt{Pathinfo}-records.
*/

typedef struct
{
  Uint depth, headposition;
  Bref ref;
} Pathinfo;      // \Typedef{Pathinfo}

DECLAREARRAYSTRUCT(Pathinfo);

typedef struct
{
  BOOL secondtime;
  ArrayBref stack;
} DFSstate;      // \Typedef{DFSstate}

#endif

//}


text:
<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

{{ site.tagline }}

    Home

    {% comment %}
      The code below dynamically generates a sidebar nav of pages with
      `layout: page` in the front-matter. See readme for usage.
    {% endcomment %}

    {% assign pages_list = site.pages %}
    {% for node in pages_list %}
      {% if node.title != null %}
        {% if node.layout == "page" %}
          {{ node.title }}
        {% endif %}
      {% endif %}
    {% endfor %}

    Twitter
    Google+
    Grupo de Discusión
    Canal IRC
    GitHub
    Temario de Discusión

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.


text:
<resources>
  <string name="app_name">BaseKit</string>
</resources>


text:
@implementation FourthModel

@end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

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

var _Layer2 = require('../../Layer');

var _Layer3 = _interopRequireDefault(_Layer2);

var _Tensor = require('../../Tensor');

var _Tensor2 = _interopRequireDefault(_Tensor);

var _WebGL = require('../../WebGL2');

var _isEqual = require('lodash/isEqual');

var _isEqual2 = _interopRequireDefault(_isEqual);

var _range = require('lodash/range');

var _range2 = _interopRequireDefault(_range);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

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

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

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

/**
 * _Merge layer class
 */
var _Merge = function (_Layer) {
  _inherits(_Merge, _Layer);

  /**
   * Creates a _Merge layer
   * @param {Object} [attrs] - layer attributes
   */
  function _Merge() {
    var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

    _classCallCheck(this, _Merge);

    var _this = _possibleConstructorReturn(this, (_Merge.__proto__ || Object.getPrototypeOf(_Merge)).call(this, attrs));

    _this.layerClass = '_Merge';

    // GPU setup
    if (_this.gpu) {
      _this.copyTextureProgram = _WebGL.webgl2.compileProgram(require('../../copyTexture.webgl2.glsl'));
    }
    return _this;
  }

  /**
   * Layer computational logic
   *
   * @param {Tensor[]} inputs
   * @returns
   */

  _createClass(_Merge, [{
    key: 'call',
    value: function call(inputs) {
      if (this.gpu) {
        inputs.forEach(function (input) {
          if (!input.glTexture) {
            input.createGLTexture();
          }
        });
        this._call_gpu(inputs);
      } else {
        var valid = this._validateInputs(inputs);
        if (!valid) {
          throw new Error(`${this.name} [${this.layerClass} layer] Invalid inputs to call method.`);
        }
        this._call_cpu(inputs);
      }
      return this.output;
    }

    /**
     * Internal method for validating inputs
     * @param {Tensor[]} inputs
     * @returns {Boolean} valid
     */

  }, {
    key: '_validateInputs',
    value: function _validateInputs(inputs) {
      var shapes = inputs.map(function (x) {
        return x.tensor.shape.slice();
      });
      if (['sum', 'mul', 'ave', 'max'].indexOf(this.mode) > -1) {
        if (!shapes.every(function (shape) {
          return (0, _isEqual2.default)(shape, shapes[0]);
        })) {
          throw new Error(`${this.name} [${this.layerClass} layer] All input shapes must be the same for mode ${this.mode}.`);
        }
      }
      if (this.mode === 'dot') {
        if (inputs.length !== 2) {
          throw new Error(`${this.name} [${this.layerClass} layer] Exactly 2 inputs required for mode ${this.mode}.`);
        }
        if (this.dotAxes[0] < 0) {
          this.dotAxes[0] = shapes[0].length + this.dotAxes[0];
        }
        if (this.dotAxes[1] < 0) {
          this.dotAxes[1] = shapes[1].length + this.dotAxes[1];
        }
        if (shapes[0][this.dotAxes[0]] !== shapes[1][this.dotAxes[1]]) {
          throw new Error(`${this.name} [${this.layerClass} layer] Dimensions incompatibility using dot mode.`);
        }
      } else if (this.mode === 'concat') {
        var nonConcatShapes = shapes.slice();
        var _concatAxis = this.concatAxis < 0 ? nonConcatShapes[0].length + this.concatAxis : this.concatAxis;
        if (this.concatAxis === 0) _concatAxis = 0;
        (0, _range2.default)(nonConcatShapes.length).forEach(function (i) {
          nonConcatShapes[i].splice(_concatAxis, 1);
        });
        if (!nonConcatShapes.every(function (shape) {
          return (0, _isEqual2.default)(shape, nonConcatShapes[0]);
        })) {
          throw new Error(`${this.name} [${this.layerClass} layer] In concat mode, all shapes must be the same except along the concat axis.`);
        }
      }
      return true;
    }

    /**
     * CPU call
     * @param {Tensor[]} inputs
     */

  }, {
    key: '_call_cpu',
    value: function _call_cpu(inputs) {}
    // implemented in child classes

    /**
     * GPU call
     * mode: sum, mul, ave, max
     * method for mode concat/dot implemented in child class
     * @param {Tensor[]} inputs
     */

  }, {
    key: '_call_gpu',
    value: function _call_gpu(inputs) {
      // create output textures if doesn't already exist
      if (!this.output) {
        this.output = new _Tensor2.default([], inputs[0].glTextureShape);
        this.output.createGLTexture();
        if (inputs[0].glTextureIsTiled) {
          this.output.glTextureIsTiled = inputs[0].glTextureIsTiled;
          this.output.untiledShape = inputs[0].untiledShape;
        }
      }

      var numInputs = inputs.length;

      _WebGL.webgl2.selectProgram(this.mergeProgram);
      _WebGL.webgl2.bindOutputTexture(this.output.glTexture, this.output.glTextureShape);
      var uniforms = [].concat(_toConsumableArray(this.output.glTextureShape));
      var uniformTypes = ['int', 'int'];
      var uniformNames = ['rows', 'cols'];
      if (this.mode === 'ave') {
        uniforms.push(numInputs);
        uniformTypes.push('int');
        uniformNames.push('numInputs');
      }
      _WebGL.webgl2.bindUniforms(this.mergeProgram, uniforms, uniformTypes, uniformNames);

      var textures = [inputs[0].glTexture, inputs[1].glTexture];
      var textureTypes = ['2d', '2d'];
      var textureNames = ['input1', 'input2'];
      _WebGL.webgl2.bindInputTextures(this.mergeProgram, textures, textureTypes, textureNames);
      _WebGL.webgl2.runProgram();

      if (numInputs > 2) {
        if (!this.runningOutput) {
          this.runningOutput = new _Tensor2.default([], inputs[0].glTextureShape);
          this.runningOutput.createGLTexture();
        }

        for (var i = 2; i < numInputs; i++) {
          // copy output texture to intermediate output
          _WebGL.webgl2.selectProgram(this.copyTextureProgram);
          _WebGL.webgl2.bindOutputTexture(this.runningOutput.glTexture, this.runningOutput.glTextureShape);
          _WebGL.webgl2.bindInputTextures(this.copyTextureProgram, [this.output.glTexture], ['2d'], ['source']);
          _WebGL.webgl2.runProgram();

          _WebGL.webgl2.bindUniforms(this.mergeProgram, [i], ['int'], ['i']);
          var _textures = [this.runningOutput.glTexture, inputs[i].glTexture];
          _WebGL.webgl2.bindInputTextures(this.mergeProgram, _textures, textureTypes, textureNames);
          _WebGL.webgl2.runProgram();
        }
      }

      // GPU -> CPU data transfer
      if (this.outbound.length === 0) {
        this.output.transferFromGLTexture();
      }
    }
  }]);

  return _Merge;
}(_Layer3.default);

exports.default = _Merge;


text:
#ifndef _pcrexx_match_hpp__
#define _pcrexx_match_hpp__

// Copyright (c) 2012, Andre Caron (andre.l.caron@gmail.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/*!
 * @file match.hpp
 * @see http://www.pcre.org/pcre.txt
 */

#include <pcre.h>
#include "exception.hpp"
#include "options.hpp"
#include "pattern.hpp"
#include "traits.hpp"
#include <map>
#include <vector>

namespace pcrexx {

    /*!
     * @brief Regular expression search/match result.
     * @tparam C Character type.  @c traits<C> must be defined.  By default,
     *  it is only @c traits<char> and @c traits<wchar_t> are provided.
     * @tparam S String type.  Must have a default constructor, copy
     *  constructor, copy-assignment operator and a constructor that accepts
     *  a C-style null-terminated string with @c C as character type.  It must
     *  also have a @c c_str() member function that returns a C-style
     *  null-terminated string.
     *
     * Seaach/match results are useful for extrating captured groups from a
     * matched subject string.
     *
     * @note Match objects are immutable and thread-safe.
     */
    template<class C, class S=typename traits<C>::string>
    class basic_match
    {
        /* nested types. */
    public:
        typedef C char_type;
        typedef traits<char_type> traits_type;

        typedef S string_type;

        typedef basic_pattern<char_type> pattern_type;

        /* data. */
    private:
        string_type myText;
        int myGroups;
        std::vector<int> myResults;

        /* construction. */
    public:
        basic_match ()
            : myText()
            , myGroups(0)
            , myResults()
        {}

        /*!
         * @brief Match @a text using @a pattern.
         */
        basic_match ( const pattern_type& pattern, const string_type& text,
                      runtime_options options=runtime_options() )
            : myText(text),
              myGroups(pattern.capturing_groups()),
              myResults((1+myGroups)*3, 0)
        {
            const int status = traits_type::execute
                (pattern.handle(), 0, text.data(), text.size(),
                 0, options, &myResults[0], myResults.size());
            if (status < 0)
            {
                if (status != PCRE_ERROR_NOMATCH) {
                    throw (exception(status, "name_table()"));
                }
                myGroups = 0, myResults.clear();
            }
        }

        /* methods. */
    public:
        /*!
         * @brief Subject text.
         */
        const string_type& text () const
        {
            return (myText);
        }

        /*!
         * @brief Get the offset of the entire match.
         */
        int group_base () const
        {
            return (myResults[0]);
        }

        /*!
         * @brief Get the offset of a specific group within the match.
         */
        int group_base ( int i ) const
        {
            return (myResults[2*i]);
        }

        /*!
         * @brief Get the size of the entire match.
         */
        int group_size () const
        {
            return (myResults[1]-myResults[0]);
        }

        /*!
         * @brief Get the size a specific group within the match.
         */
        int group_size ( int i ) const
        {
            return (myResults[2*i+1]-myResults[2*i]);
        }

        /*!
         * @brief Get the contents of the entire match.
         */
        string_type group () const
        {
            return (myText.substr(group_base(), group_size()));
        }

        /*!
         * @brief Get the contents of a specific group within the match.
         */
        string_type group ( int i ) const
        {
            return (myText.substr(group_base(i), group_size(i)));
        }

        /*!
         * @brief Get the contents of all captured groups, in order.
         */
        std::vector<string_type> groups () const;

        /*!
         * @brief Get the contents of all captured groups, by name.
         *
         * @todo Keep an internal copy of the pattern to implement
         *  this without requiring the client to supply the pattern again.
         */
        std::map<string_type,string_type>
            named_groups ( const pattern_type& pattern ) const
        {
            std::vector<string_type> names = pattern.group_names();
            std::map<string_type,string_type> groups;
            for (std::size_t i=0; (i < names.size()); ++i)
            {
                const string_type& name = names[i];
                const string_type  data = group(pattern.group_index(name));
                groups.insert(std::make_pair(name, data));
            }
            return (groups);
        }

        /* operators. */
    public:
        operator bool () const
        {
            return (myResults.size() > 0);
        }
    };

    /*!
     * @brief Search/match result for UTF-8 strings stored in @c std::string.
     */
    typedef basic_match<char> match;

    /*!
     * @brief Search/match result for UTF-16 strings stored in @c std::wstring.
     */
    typedef basic_match<wchar_t> wmatch;

    // pattern(text,options) -> match.
    template<class C, class S>
    basic_match<C,S> basic_pattern<C,S>::operator()
        (const S& text, runtime_options options) const
    {
        return (basic_match<C,S>(*this, text, options));
    }

}

#endif /* _pcrexx_match_hpp__ */


text:
package unitTesting;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.After;
import org.junit.Test;

import Bean.Review;

public class ReviewController_getReview_Test extends ReviewController_Test {
	@Test
	public void test() {
		Review myReview = myHandler.getReview("test1");

		List<String> expectedActors = Arrays.asList("Tremblay Guy");

		assertNotNull(myReview);
		assertEquals(new Timestamp(1446526800000L), myReview.getCreationDate());
		assertEquals(new Timestamp(1446526800000L), myReview.getEditionDate());
		assertEquals("test1", myReview.getTitle());
		assertEquals(new Timestamp(1446526800000L), myReview.getRelease());
		assertEquals("Arthuer", myReview.getProducer());
		assertEquals("Aucun", myReview.getSummary());
		assertEquals("Action", myReview.getKind());
		assertEquals("Francais", myReview.getNationnality());
		assertEquals(expectedActors, myReview.getActors());
	}
}


text:
A library for parsing a string to a javascript object.

Main difference between the JSON.parse function and this function is that js-object-parser will be able to parse
```"{A:b, C:d, E:{any-object:{a:1, b:2}}}"```, where JSON.parse fails as it requires every property to be wrapped in quotationmarks, i.e:
```"{"A":"b", "C":"d", "E":{"any-object":{"a":1, "b":2}}}" ```

### Example / Usage
Add it to your project by

```html
	npm install js-object-parser
```
In your program

```javascript
import objectParser from 'js-object-parser';

console.log(objectParser.parse('{A:"b", C:[1,2,"3"]}'));
//Outputs: {A: "b", C: [1,2,"3"]}

```
It can handle nested objects:

```javascript

console.log(objectParser.parse('{A:{BCDEF:{G:"h"}, I:"j"}}'));
//Outputs: { A: { BCDEF: { G: "h" }, I: "j" } }

```

### Test

For testing, run
```
# Clone repository
git clone https://github.com/simonlovesyou/js-object-parser.git
# Navigate into project folder
cd js-object-parser
# Install dependencies
npm install
# Run tests
npm test
```

### Creator
[simonlovesyou](https://github.com/simonlovesyou)

## License (MIT)

Copyright (c) 2015 Simon Johansson

JohanssonLSimon@gmail.com

[Website](http://www.simonsager.se)
[Twitter](https://twitter.com/simonjohansosn)


text:
package edu.umass.cs.jfoley.coop.front;

import ciir.jfoley.chai.io.Directory;
import ciir.jfoley.chai.io.IO;
import ciir.jfoley.chai.string.StrUtil;
import edu.umass.cs.jfoley.coop.bills.IntCoopIndex;
import edu.umass.cs.jfoley.coop.conll.server.ServerErr;
import edu.umass.cs.jfoley.coop.conll.server.ServerFn;
import org.lemurproject.galago.tupleflow.web.WebHandler;
import org.lemurproject.galago.tupleflow.web.WebServer;
import org.lemurproject.galago.tupleflow.web.WebServerException;
import org.lemurproject.galago.utility.Parameters;
import org.lemurproject.galago.utility.StreamUtil;
import org.lemurproject.galago.utility.tools.Arguments;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jfoley
 */
public class CoopDemoFrontEnd implements WebHandler {
  public final CoopIndex coopIndex;
  public final Directory htmlDir;
  private Map<String, ServerFn> apiMethods;

  public CoopDemoFrontEnd(Directory coopDir, Directory htmlDir) throws IOException {
    this.coopIndex = new IntCoopIndex(coopDir);
    this.htmlDir = htmlDir;

    apiMethods = new ConcurrentHashMap<>();
    apiMethods.put("debug", (p) -> p);
    IndexFns.setup(coopIndex, apiMethods);
  }

  public static void main(String[] args) throws IOException, WebServerException {
    Parameters argp = Arguments.parse(args);

    //String defaultIndex = "/mnt/scratch3/jfoley/robust.ints";
    String defaultIndex = "/mnt/scratch/jfoley/nyt-clinton.ints";

    Directory input = Directory.Read(argp.get("input", defaultIndex));
    Directory htmlDir = Directory.Read(argp.get("html", "coop/front_html"));

    CoopDemoFrontEnd server = new CoopDemoFrontEnd(input, htmlDir);
    WebServer ws = WebServer.start(argp.get("port", 2347), server);

    System.out.println("Started server: "+ws.getURL()+" port="+ws.getPort());

    ws.join();
  }

  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String method = request.getMethod();
    boolean GET = method.equals("GET");
    boolean POST = method.equals("POST");

    String path = request.getPathInfo();

    // safen-up.
    if(path.contains("..")) doError(response, ServerErr.BadRequest, "Bad Request; contains '..'");

    if(path.startsWith("/api/")) {
      handleAPI(request, response, method, path);
      return;
    }

    if(path.equals("/")) {
      path = "/index.html";
    }

    String contentType = null;
    if(path.endsWith(".html")) {
      contentType = "text/html";
    } else if(path.endsWith(".js")) {
      contentType = "application/javascript";
    } else if(path.endsWith(".css")) {
      contentType = "text/css";
    }

    if(contentType != null) {
      InputStream is = IO.openInputStream(htmlDir.childPath(path));
      if(is == null) {
        doError(response, ServerErr.NotFound, "Couldn't find resource for: "+path);
        //response.sendError(ServerErr.NotFound, path);
        return;
      }

      response.setContentType(contentType);
      try (InputStream read = is; OutputStream out = response.getOutputStream()) {
        StreamUtil.copyStream(read, out);
        response.setStatus(200);
        return;
      }
    }

    doError(response, ServerErr.NotFound, "No response for: "+path);
  }

  private void handleAPI(HttpServletRequest request, HttpServletResponse response, String method, String path) throws IOException {
    Parameters req;
    switch (method) {
      case "GET":
        req = WebServer.parseGetParameters(request);
        break;
      case "POST":
        req = parseBody(request);
        break;
      default:
        response.sendError(ServerErr.BadRequest, "Unsupported method.");
        return;
    }

    assert(path.startsWith("/api/"));

    String endpoint = StrUtil.takeAfter(path, "/api/");
    ServerFn apiFn = apiMethods.get(endpoint);
    if(apiFn == null) {
      response.sendError(ServerErr.NotFound, "No such API call: "+endpoint);
      return;
    }

    try {
      response.setStatus(200);
      response.setContentType("application/json");
      // allow other domains to use this from JS
      response.addHeader("Access-Control-Allow-Origin", "*");

      PrintWriter out = response.getWriter();
      long start = System.currentTimeMillis();
      Parameters json = apiFn.handleRequest(req);
      long end = System.currentTimeMillis();
      json.put("time", end-start);
      out.println(json.toString());
      out.close();

      response.setStatus(200);

    } catch (IllegalArgumentException iae) {
      iae.printStackTrace(System.err);
      doError(response, ServerErr.BadRequest, iae.getMessage());
    } catch (ServerErr err) {
      doError(response, err.code, err.msg);
    } catch (AssertionError e) {
      e.printStackTrace(System.err);
      try (PrintWriter out = response.getWriter()) {
        e.printStackTrace(out);
      }
      doError(response, 501, "Assertion Failed: "+e.getMessage());
    } catch (Exception e) {
      e.printStackTrace(System.err);
      try (PrintWriter out = response.getWriter()) {
        e.printStackTrace(out);
      }
      doError(response, 501, e.getMessage());
    }
  }

  public static void doError(HttpServletResponse response, int code, String message) throws IOException {
    response.setStatus(code);
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.println(Parameters.parseArray("message", message).toString());
    out.close();
  }

  public static Parameters parseBody(HttpServletRequest req) throws ServerErr {
    String contentType = req.getContentType();
    String ct = StrUtil.takeBefore(contentType, ";");
    switch(ct) {
      default:
        throw new ServerErr(ServerErr.BadRequest, "Content-Type='"+contentType+"' not allowed, try 'application/json' instead.");
      case "text/json":
      case "application/json":
        try {
          return Parameters.parseReader(req.getReader());
        } catch (IOException e) {
          throw new ServerErr(400, e.getMessage());
        }
    }
  }
}