text:
package p02_Multiple_Inheritance;

public class Main {
    public static void main(String[] args) {
        Puppy puppy = new Puppy();
        puppy.eat();
        puppy.bark();
        puppy.weep();
    }
}


text:
{% extends 'framework_templates/base.html' %}

{% block title %}Forgot your password?{% endblock %}

{% block main %}

Forgot your password?

{% if errors is defined and errors.general %}

{{ errors.general }}

{% endif %}

Enter your e-mail address and we'll send you a link to securely reset it.

<form action="/send-password-reset-email" method="POST">

Email Address

{% if values is defined and values.email_address %}
<input type="email"
    name="email_address"
    id="email_address"
    required
    value="{{ values.email_address }}"
    placeholder="joe@example.com" />

{% else %}
<input type="email" name="email_address" id="email_address" required
    placeholder="joe@example.com" />
{% endif %}

{% if errors is defined and errors.email_address %}
{{ errors.email_address }}

{% endif %}

<input type="submit" value="Send me an email!" />

</form>

{% endblock main %}

{% block scripts %}

{% endblock scripts %}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
XML EJEMPLO Borrar
<Site>
  <RelativeUrl>/</RelativeUrl>
  <Name>Enmarcha</Name>
  <Description>Sitio para las pruebas de Enmarcha</Description>
  <Template>BLANKINTERNET#0</Template>
  <Language>3082</Language>
  <SiteMasterPage>/_catalogs/masterpage/CustomPublishing.master</SiteMasterPage>
  <SystemMasterPage>/_catalogs/masterpage/CustomSystem.master</SystemMasterPage>
  <SiteLogo>
    <Url>/Style Library/Images/logo-enmarcha.png</Url>
  </SiteLogo>
  <SiteFeatures>
    <Feature Id="36544770-eeef-4b76-8196-37c79d85193d" />
  </SiteFeatures>
  <WebFeatures>
  </WebFeatures>
  <PropertyBags>
    <Value Key="ActiveDirectoryEntryPath" Val="LDAP://OU=Enmarcha,OU=Usuarios,DC=Enmarcha,DC=dev" />
  </PropertyBags>
  <WelcomePage>
    <Url>Paginas/Inicio.aspx</Url>
  </WelcomePage>
  <SiteSearchSettings>
    <SearchCenterUrl>/buscar</SearchCenterUrl>
    <SearchResultsPageUrl>/buscar/Paginas/Results.aspx</SearchResultsPageUrl>
  </SiteSearchSettings>
  <Variations EnableAutoSpawnPropertyName="true" AutoSpawnStopAfterDeletePropertyName="false" UpdateWebPartsPropertyName="true" CopyResourcesPropertyName="true" SendNotificationEmailPropertyName="false" SourceVarRootWebTemplatePropertyName="BLANKINTERNET#0">
    <Variation Title="es-es" Description="Spanish Language Pack" FlagControlDisplayName="Inicio" Language="es-ES" Locale="3082" HierarchyCreationMode="Publishing Sites and All Pages" IsSource="true"/>
  </Variations>
</Site>
-->
<Site>
  <RelativeUrl>/</RelativeUrl>
  <Name>Enmarcha</Name>
  <Description>Sitio para las pruebas de Enmarcha</Description>
  <Template>BLANKINTERNET#0</Template>
  <Language>3082</Language>
</Site>


text:
HackLime
========
> Sublime-Text Editor plugin to compile/run using HackerEarth's [API](http://api.hackerearth.com)

###Installtion:
* Copy it in 'HackLime' folder of your sublime package directory
* Edit `client_secret` in `config.py` with your secret key
* It is ready to work

###How to use:
> for both windows and linux

* *ctrl+shift+c* : compile the current open file
* *ctrl+shift+r* : run the current open file
* *ctrl+alt+h* : open help guide for HackLime

###How it works:
* HackLime is built on top of HackerEarth's API
* On a compile/run command it opens a output file, showing output details

###TODO
* I'm thinking of an Installtion script to help installing it.
* Status showing analysis of relative result of all responses.


text:
package edu.berkeley.nlp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Semaphore;

/**
 * Runs stuff in a shell
 *
 * @author denero
 */
public class Shell {

	private static class StreamGobbler extends Thread {
		InputStream is;
		String output;
		Semaphore semaphore;
		String prefix;
		boolean echo;

		StreamGobbler(InputStream is, String prefix, boolean echo) {
			this.is = is;
			semaphore = new Semaphore(1);
			semaphore.acquireUninterruptibly();
			this.echo = echo;
			this.prefix = prefix;
		}

		public void run() {
			StringBuilder outputBuilder = new StringBuilder();
			try {
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				while ((line = br.readLine()) != null) {
					outputBuilder.append(line + "\n");
					if(echo) System.out.println(prefix + line);
				}
			} catch (IOException ioe) {
				throw new RuntimeException(ioe);
			}
			output = outputBuilder.toString();
			semaphore.release();
		}

		public String getOutput() {
			semaphore.acquireUninterruptibly();
			semaphore.release();
			return output;
		}
	}

	public static String execute(String cmd) {
		return execute(cmd, false);
	}

	public static String execute(String cmd, boolean echo) {
		try {
			Process proc = Runtime.getRuntime().exec(cmd);
			StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERR> ", echo);
			StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUT> ", echo);

			// kick them off
			errorGobbler.start();
			outputGobbler.start();

			proc.waitFor();
			return outputGobbler.getOutput();

		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}


text:
package com.conveyal.r5.analyst;

import com.conveyal.r5.OneOriginResult;
import com.conveyal.r5.analyst.cluster.RegionalTask;

/**
 * Computes an accessibility indicator at a single origin cell in a Web Mercator grid, using destination densities from
 * a Web Mercator density grid. Both grids must be at the same zoom level. This class computes accessibility given a
 * certain percentile of the travel times to each destination (described below and in Conway, Byrd and van Eggermond 2017).
 *
 * NOTE THIS NO LONGER DOES ANY BOOTSTRAPPING, the name is a remnant of additional computations it used to do.
 * THIS CLASS IS ONLY HERE so we can copy optimizations and comments out of it.
 * TODO This is in fact just a point estimate, and you will get different results when re-running the MC draws.
 * We have a bootstrapping method for estimating the error, but we've decided to hide that from the user, using it as
 * a calibration technique for setting a sufficient number of MC draws.
 *
 * The accessibility is calculated using a percentile of travel time to all destinations (there are plans to change
 * this to allow use of multiple percentiles).
 */
public class BootstrappingTravelTimeReducer {

    private final RegionalTask task;

    /** Accessibility result for this origin. */
    private double accessibility = 0;

    /** Destination opportunity density grid */
    public final Grid grid;

    /** Minimum number of times a destination must be reached to be considered reachable */
    private final int minCount;

    /**
     * As an optimization, since we only care whether a cell was reached and not exactly how long it took to reach,
     * we don't need to sort the travel times to a destination and read off specific percentiles of travel time.
     *
     * Sorting is O(n.log(n)) and this function is called up to millions of times in a tight loop.
     * We can decide whether a destination is reachable in a single sub-O(n) pass if we don't need to keep the times.
     * We pre-calculate how many of the travel times would need to fall under the threshold to attain a certain
     * percentile. We then count how many of the reported travel times fall under the threshold travel time and bail
     * out early as soon as that count is reached.
     *
     * A destination count is added into the accessibility result if the p-th percentile of travel time falls under
     * the threshold. If the 50th percentile travel time is below the threshold, that means that at least 50% of the
     * observations are below the threshold. If the 90th percentile travel time is below the threshold, that means that
     * at least 90% of the observations are below the threshold.
     *
     * TODO verify that this optimization actually affects runtime in the non-bootstrapping case.
     */
    public BootstrappingTravelTimeReducer (RegionalTask request, Grid grid) {
        this.task = request;
        this.grid = grid;
        // FIXME this assumes frequency entries are present.
        int nIterations = request.getTotalIterations(true);
        // TODO handle multiple percentiles, request already has an array to hold more than one of them
        if (request.percentiles.length != 1) {
            throw new IllegalArgumentException("Bootstrapped travel times only support a single percentile of travel time!");
        }
        // The disatance between the first value (0th percentile) and last value (100th percentile) is nIterations-1.
        // minCount should range from 1 (for 0th percentile / minimum) to N (for 100th percentile / maximum)
        minCount = (int) ((nIterations - 1) * (request.percentiles[0] / 100d)) + 1;
    }

    public void recordTravelTimesForTarget(int target, int[] travelTimesForTarget) {
        // We use the size of the grid to determine the number of destinations used in the linked point set in
        // TravelTimeComputer, therefore the target indices are relative to the grid, not the task.
        // TODO verify that the above is still accurate
        int gridx = target % grid.extents.width;
        int gridy = target / grid.extents.width;
        double opportunityCountAtTarget = grid.grid[gridx][gridy];

        // As an optimization, don't even bother to check whether cells that contain no opportunities are reachable.
        if (opportunityCountAtTarget < 1e-6) return;

        // If there is no variation in travel time to the destination, there is no need to compute percentiles.
        // This happens with non-transit modes like biking and walking.
        // FIXME identifier naming: we're using < so this is not a "max" trip duration (which would be <=)
        if (travelTimesForTarget.length == 1) {
            if (travelTimesForTarget[0] < task.maxTripDurationMinutes * 60) {
                accessibility += opportunityCountAtTarget;
            }
            return;
        }

        // See if more than the minimum number of travel times are below the threshold.
        // Bail out early once we've reached that minimum.
        int count = 0;
        for (int i = 0; i < travelTimesForTarget.length && count < minCount; i++) {
            if (travelTimesForTarget[i] < task.maxTripDurationMinutes * 60) count += 1;
        }
        // TODO Maybe sigmoidal rolloff here, to soften artifacts from large destinations that jump a few seconds in or out of the cutoff.
        if (count >= minCount) {
            accessibility += opportunityCountAtTarget;
        }
    }

    /**
     * Write the origin to SQS.
     * If no travel times to destinations have been streamed in by calling recordTravelTimesForTarget, the
     * bootstrapReplicationsOfAccessibility will all still be zero and the output will be zero, which allows
     * shortcutting around routing and propagation when the origin point is not connected to the street network.
     */
    public OneOriginResult finish () {
        // Only one accessibility figure, no bootstrapping.
        return null;
    }
}


text:
<?php

namespace Expresso\Task;

use Expresso\Expresso;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class Rollback extends TaskAbstract
{

    /**
     * @var string
     */
    protected $description = 'Deploy project';

    /**
     * @var string
     */
    protected $help = '--release select the release to rollback';

    public function configure()
    {
        Expresso::getExpresso()->getConsole()->getUserDefinition()->addOption(
            new InputOption('release', null, InputOption::VALUE_OPTIONAL, 'Select the release to rollback')
        );

        Expresso::getExpresso()->getConsole()->getUserDefinition()->addOption(
            new InputOption('rm-current', null, InputOption::VALUE_OPTIONAL, 'Remove the current release')
        );
    }

    public function execute()
    {
        $releasesList = $this->getReleasesList();
        $this->getWorker()->setWorkingDir($this->getWorker()->getBaseProjectDir());
        $results = $this->getWorker()->runOnServers('readlink current');
        foreach ($results as $result) {
            var_dump(($releasesList[$result->getServer()->getName()]));
            if (count($releasesList[$result->getServer()->getName()]) > 1) {
                $this->getWorker()->setWorkingDir($this->getWorker()->getBaseProjectDir());

                if ($this->getInput()->getOption('release')) {
                    $releaseName = $this->getInput()->getOption('release');
                } else {
                    $releaseName = $releasesList[$result->getServer()->getName()][1];
                }

                $this->getWorker()->runOnServers('rm -rf current',
                    array($result->getServer())
                );

                $this->getWorker()->runOnServers(
                    'ln -sfn ' . $this->getWorker()->getReleasesDir() . $releaseName . '/ current',
                    array($result->getServer())
                );

                $this->getWorker()->setWorkingDir($this->getWorker()->getReleasesDir());
                if ($this->getInput()->hasOption('rm-current')) {
                    $this->getWorker()->runOnServers('rm -rf ' . $result->toString(), array($result->getServer()));
                }
            } else {
                throw new \RuntimeException('Not enough release on server ' . $result->getServer()->getName());
            }
        }

        return;
    }

    /**
     * @return array
     */
    protected function getReleasesList()
    {
        $this->getWorker()->setWorkingDir($this->getWorker()->getReleasesDir());
        $results = $this->getWorker()->runOnServers('find . -maxdepth 1 -mindepth 1 -type d');

        $releases = array();
        foreach ($results as $result) {
            $releasesList = $result->toArray();
            foreach ($releasesList as $key => $item) {
                $item = basename($item);
                $releasesList[$key] = $item;

            }
            rsort($releasesList);
            $releases[$result->getServer()->getName()] = $releasesList;
        }
        return $releases;
    }
}


text:
<?php

namespace AbleCore\Install\Helpers\Fields;

use AbleCore\Install\Helpers\Field;
use AbleCore\Install\Helpers\FieldTypes;

class FieldCollectionField extends Field {

	public function setType($type = FieldTypes::FIELD_COLLECTION)
	{
		return parent::setType($type);
	}

	public function __construct($field_name, array $definition)
	{
		parent::__construct($field_name, $definition);
		$this->setSetting('path', '');
		$this->setSetting('hide_blank_items', true);
	}

}


text:
Reference
#########

Contents:

.. toctree::
    :maxdepth: 2

    workspace
    model
    providers
    browser
    formatter
    backends
    server
    auth
    common


text:
<?php

namespace js4php5\compiler\parser;

use js4php5\compiler\lexer\Lexer;
use js4php5\VarDumper;

//TODO: Fix known bug whre parser will get stuck on a script ending with a + (does not recognize bad syntax).
//Can be tested with a script containing only '+'.
abstract class Parser
{

    protected $pda;

    protected $action;

    protected $delta;

    public function __construct($pda)
    {
        $this->pda = $pda;
        $this->action = $pda['action'];
        $this->start = $pda['start'];
        $this->delta = $pda['delta'];
    }

    public function report()
    {
        # pr($this->action);
        pr($this->start);
        foreach ($this->delta as $label => $d) {
            echo "
State $label
";
            foreach ($d as $glyph => $step) {
                echo $glyph . " -> " . implode(':', $step) . "
";
            }
        }
    }

    /**
     * @param string              $symbol
     * @param Lexer               $lex
     * @param null|ParserStrategy $strategy
     *
     * @throws parse_error
     */
    public function parse($symbol, Lexer $lex, ParserStrategy $strategy = null)
    {
        $stack = array();
        $tos = $this->frame($symbol);
        $token = $lex->next();

        $c = 0;
        while (true) {
            $step = $this->getStep($tos->state, $token->getType());
//            if ($c++ == 16) {
//                VarDumper::dump($token, 'tos');
//                exit;
//            }

            // echo implode(':', $step)."
";
            switch ($step[0]) {
                case 'go':
                    $tos->shift($token->getText());
                    $tos->state = $step[1];
                    $token = $lex->next();
                    break;

                case 'do':
                    $semantic = $this->reduce($step[1], $tos->semantic());
                    if (empty($stack)) {
                        $strategy->assertDone($token, $lex);
                        return $semantic;
                    } else {
                        $tos = array_pop($stack);
                        $tos->shift($semantic);
                    }
                    break;

                case 'push':
                    $tos->state = $step[2];
                    $stack[] = $tos;
                    $tos = $this->frame($step[1]);
                    break;

                case 'fold':
                    $tos->fold($this->reduce($step[1], $tos->semantic()));
                    $tos->state = $step[2];
                    break;

                case 'error':
                    $stack[] = $tos;
                    $strategy->stuck($token, $lex, $stack);
                    break;

                default:
                    throw new parse_error("Impossible. Bad PDA has $step[0] instruction.");
            }
        }
        // return statement is in case 'do'
    }

    public function frame($symbol)
    {
        return new ParseStackFrame($symbol, $this->start[$symbol]);
    }

    public function getStep($label, $glyph)
    {
        $delta = $this->delta[$label];
        if (isset($delta[$glyph])) {
            return $delta[$glyph];
        }
        if (isset($delta['[default]'])) {
            return $delta['[default]'];
        }
        return array('error');
    }

    abstract public function reduce($action, $tokens);
}

/*
File: automata.so.php
License: GPL
Purpose: Contains various utilities for operating on finite automata.
*/

/*
First, we care about finality-extended e-NFAs. These are the basis for most
of the remainder of the systems.

Let it be noted early that pushdown automata will be constructed in terms
of (determinized) FAs which will interpret automata death as an indication
that the system needs to do something with the PDA stack.

We'll form the left-recursive closure of the available non-terminals following
the dieing state. If the next terminal is found in that set, then we also know
what to push and what state to enter. (Alternatively, we know the first step
in a recursive set of "pushes" which don't accept the terminal until the stack
looks the way it should.) Ambiguity here can be considered a bug in the
grammar specification. It makes the PDA non-deterministic. While it may be
possible to remove this non-determinism in some limited cases, I don't think
it's actually necessary.

We can, by this procedure, form a set of PDA rules for what to do with any
given terminal, assuming that the state transitions in the production DFA
call for a non-terminal. We thus have a special category of rule

There is another possibility: We are in a "final" state and we don't have
and edge or a push that accepts the next Token. In this case, we assume that
we have recognized a complete production rule.

We call its associated code block, which is expected to return a syntax tree
node. Then, we pop the stack. The symbol on the stack should tell which
DFA to jump into and what state it will be in after recognizing a member of
the production known to the called DFA.

We can convert this entire idea to the normal definition of a DPDA by:
1. Selecting disjoint state labels for every DFA.
2. Keeping all DFA transitions in the same table.

That done, a stack symbol is merely also a state label.

*/

/*
Now we can turn any production rule (head + set ) into a
DFA that recognizes the rule and can even invoke the correct action based
on a set of distinguishing marks. Any given final state in the DFA will
be marked with exactly the best matching action number.

A remaining problem is that of transduction. We would like to mark certain
glyphs with a symbol indicating that they cause the corresponding parse node
to go into the correct slot of a special parsing data structure which makes
for convenient reference within an action part of a rule. In other words,
we would really ideally like to turn NFTs into DFTs. It seems, at the moment,
that the transduction might still be non-deterministic. This not so much of
a problem as a big hassle.

However, if we always make the entire matched glyph list available in the form
of a list of parse nodes, then the action that corresponds to a given rule
branch is free to do fancy things.

All that remains is to build a PDA from a collection of DFAs.

These various DFAs will mostly have some transitions that are predicated on
non-terminal symbols in the CFG. We have to find all such transitions and deal
with them specially.
*/

/*
File: lex.so.php
License: GPL
Purpose: Provides a simple lexical analysis framework
Purpose: useful in so many ways. (Minilanguages are a
Purpose: fabulous way to save programming time.)
*/

$GLOBALS['wasted'] = 0;

/*
File: parser.so.php
License: GPL
Purpose: Contains the code necessary to operate the left-recursive parsers
Purpose: whose execution tables are generated by the parser generator.
*/


text:
import datetime

from django.contrib.auth.tokens import PasswordResetTokenGenerator

__all__ = ('TokenGenerator', 'token_generator')

## A simple token generator.
#
#  The "PasswordResetTokenGenerator" in Django is great, but it needs
#  a couple of methods to be overridden to make it a little easier to
#  use.
#
class TokenGenerator(PasswordResetTokenGenerator):

    def _num_days(self, dt):
        return (dt - datetime.datetime(2001,1,1)).seconds

    def _today(self):
        return datetime.datetime.now()

# Declare a global token generator.
token_generator = TokenGenerator()


text:
package com.apptentive.android.sdk.encryption.resolvers;

import android.os.Build;
import androidx.annotation.NonNull;

public class KeyResolverFactory {
	public static @NonNull KeyResolver createKeyResolver(int versionCode) {
		// Android API level 26 has a bug when symmetric key does not work. We use legacy approach instead.
		// see: https://stackoverflow.com/questions/36015194/android-keystoreexception-unknown-error
		if (versionCode == Build.VERSION_CODES.O) {
			return new KeyResolver26();
		}

		if (versionCode >= Build.VERSION_CODES.M) {
			return new KeyResolver23();
		}

		if (versionCode >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
			return new KeyResolver18();
		}

		return new KeyResolverNoOp();
	}
}


text:
"""Tests for `op_reg_gen` module."""

# pylint: disable=missing-function-docstring
# pylint: disable=invalid-name
# pylint: disable=g-direct-tensorflow-import

import sys

from tensorflow.compiler.mlir.python.mlir_wrapper import filecheck_wrapper as fw
from tensorflow.compiler.mlir.tfr.python import composite
from tensorflow.compiler.mlir.tfr.python.op_reg_gen import gen_register_op
from tensorflow.python.platform import test

Composite = composite.Composite

@composite.Composite(
    'TestNoOp', derived_attrs=['T: numbertype'], outputs=['o1: T'])
def _composite_no_op():
  pass

@Composite(
    'TestCompositeOp',
    inputs=['x: T', 'y: T'],
    attrs=['act: {"", "relu"}', 'trans: bool = true'],
    derived_attrs=['T: numbertype'],
    outputs=['o1: T', 'o2: T'])
def _composite_op(x, y, act, trans):
  return x + act, y + trans

class TFRGenTensorTest(test.TestCase):
  """MLIR Generation Tests for MLIR TFR Program."""

  def test_op_reg_gen(self):
    cxx_code = gen_register_op(sys.modules[__name__])
    cxx_code_exp = r"""
      CHECK: #include "tensorflow/core/framework/op.h"
      CHECK-EMPTY
      CHECK: namespace tensorflow {
      CHECK-EMPTY
      CHECK-LABEL: REGISTER_OP("TestNoOp")
      CHECK-NEXT:      .Attr("T: numbertype")
      CHECK-NEXT:      .Output("o1: T");
      CHECK-EMPTY
      CHECK-LABEL: REGISTER_OP("TestCompositeOp")
      CHECK-NEXT:      .Input("x: T")
      CHECK-NEXT:      .Input("y: T")
      CHECK-NEXT:      .Attr("act: {'', 'relu'}")
      CHECK-NEXT:      .Attr("trans: bool = true")
      CHECK-NEXT:      .Attr("T: numbertype")
      CHECK-NEXT:      .Output("o1: T")
      CHECK-NEXT:      .Output("o2: T");
      CHECK-EMPTY
      CHECK:  }  // namespace tensorflow
    """
    self.assertTrue(fw.check(str(cxx_code), cxx_code_exp), str(cxx_code))

if __name__ == '__main__':
  test.main()


text:
namespace More.VisualStudio.ViewModels
{
    using More.Collections.Generic;
    using More.ComponentModel;
    using More.Windows.Input;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.ComponentModel.DataAnnotations;
    using System.Diagnostics.Contracts;
    using System.Reflection;

    /// <summary>
    /// Represents a view model for selecting a type.
    /// </summary>
    public class TypeBrowserViewModel : ValidatableObject, ILocalAssemblySource
    {
        readonly HashSet<string> restrictedBaseTypeNames = new HashSet<string>( StringComparer.Ordinal );
        readonly InteractionRequest<WindowCloseInteraction> close = new InteractionRequest<WindowCloseInteraction>( "CloseWindow" );
        readonly ObservableKeyedCollection<string, IInteractionRequest> interactionRequests = new ObservableKeyedCollection<string, IInteractionRequest>( r => r.Id );
        readonly ObservableKeyedCollection<string, INamedCommand> dialogCommands = new ObservableKeyedCollection<string, INamedCommand>( c => c.Id );
        readonly ObservableCollection<AssemblyName> localAssemblyReferences = new ObservableCollection<AssemblyName>();
        bool filterByConvention = false;
        string nameConvention;
        string title = SR.DefaultTypeSelectionTitle;
        Type selectedType;
        ISpecification<Type> typeFilter;
        Assembly localAssembly;

        /// <summary>
        /// Initializes a new instance of the <see cref="TypeBrowserViewModel"/> class.
        /// </summary>
        public TypeBrowserViewModel()
        {
            interactionRequests.Add( close );
            dialogCommands.Add( new NamedCommand<object>( SR.OKCaption, p => close.Request( new WindowCloseInteraction() ), p => SelectedType != null ) );
            dialogCommands.Add( new NamedCommand<object>( SR.CancelCaption, p => close.Request( new WindowCloseInteraction( true ) ) ) );
        }

        static ISpecification<Type> CreateFilter( string nameConvention, ICollection<string> restrictedBaseTypeNames )
        {
            Contract.Ensures( Contract.Result<ISpecification<Type>>() != null );

            var names = restrictedBaseTypeNames;
            var unrestrictedType = new Specification<Type>( t => !t.IsRestricted( names ) );
            var core = new Specification<Type>( t => t.IsClass ).Or( t => t.IsInterface ).And( unrestrictedType );

            if ( string.IsNullOrEmpty( nameConvention ) )
            {
                return core;
            }

            var comparison = StringComparison.OrdinalIgnoreCase;
            var name = new Specification<Type>( t => t.Name.Contains( nameConvention, comparison ) )
                                           .Or( t => t.Namespace.Contains( nameConvention, comparison ) )
                                          .And( core );

            return name;
        }

        /// <summary>
        /// Gets or sets an associated title.
        /// </summary>
        /// <value>The associated title.</value>
        public string Title
        {
            get
            {
                Contract.Ensures( title != null );
                return title ?? ( title = string.Empty );
            }
            set => SetProperty( ref title, value );
        }

        /// <summary>
        /// Gets the collection of view model interaction requests.
        /// </summary>
        /// <value>A <see cref="ObservableKeyedCollection{TKey,TValue}">keyed collection</see> of
        /// <see cref="IInteractionRequest">interaction requests</see>.</value>
        public ObservableKeyedCollection<string, IInteractionRequest> InteractionRequests
        {
            get
            {
                Contract.Ensures( interactionRequests != null );
                return interactionRequests;
            }
        }

        /// <summary>
        /// Gets the collection of view model dialog commands.
        /// </summary>
        /// <value>A <see cref="ObservableKeyedCollection{TKey,TValue}">keyed collection</see> of
        /// <see cref="INamedCommand">commands</see>.</value>
        /// <remarks>These commands control the behavior of a view, such as cancelling it.</remarks>
        public ObservableKeyedCollection<string, INamedCommand> DialogCommands
        {
            get
            {
                Contract.Ensures( dialogCommands != null );
                return dialogCommands;
            }
        }

        /// <summary>
        /// Gets or sets the local assembly used to filter types by.
        /// </summary>
        /// <value>The local <see cref="Assembly">assembly</see>.</value>
        public Assembly LocalAssembly
        {
            get => localAssembly;
            set
            {
                if ( SetProperty( ref localAssembly, value ) )
                {
                    OnPropertyChanged( nameof( LocalAssemblyName ) );
                }
            }
        }

        /// <summary>
        /// Gets the local assembly name used to filter types by.
        /// </summary>
        /// <value>The local <see cref="AssemblyName">assembly name</see>.</value>
        public AssemblyName LocalAssemblyName => LocalAssembly?.GetName();

        /// <summary>
        /// Gets a collection of references used by the local assembly.
        /// </summary>
        /// <value>A <see cref="ObservableCollection{T}">collection</see> of <see cref="AssemblyName">assembly references</see>
        /// used by the <see cref="LocalAssembly">local assembly</see>.</value>
        public ObservableCollection<AssemblyName> LocalAssemblyReferences
        {
            get
            {
                Contract.Ensures( localAssemblyReferences != null );
                return localAssemblyReferences;
            }
        }

        IReadOnlyList<AssemblyName> ILocalAssemblySource.LocalAssemblyReferences => LocalAssemblyReferences;

        /// <summary>
        /// Gets or sets a value indicating whether types are filtered by convention.
        /// </summary>
        /// <value>True if types are filtered by convention; otherwise, false. The default value is false.</value>
        public bool FilterByConvention
        {
            get => filterByConvention;
            set
            {
                if ( !SetProperty( ref filterByConvention, value ) )
                {
                    return;
                }

                var convention = value ? NameConvention : null;
                TypeFilter = CreateFilter( convention, RestrictedBaseTypeNames );
            }
        }

        /// <summary>
        /// Gets or sets the name used to filter types by convention.
        /// </summary>
        /// <value>The name of types to be filtered by convention.</value>
        /// <remarks>If the <see cref="FilterByConvention"/> is <c>false</c>, then the value of this property is ignored.</remarks>
        public string NameConvention
        {
            get => nameConvention;
            set
            {
                if ( !SetProperty( ref nameConvention, value ) )
                {
                    return;
                }

                if ( FilterByConvention )
                {
                    TypeFilter = CreateFilter( value, RestrictedBaseTypeNames );
                }
            }
        }

        /// <summary>
        /// Gets or sets the selected type.
        /// </summary>
        /// <value>The selected type.</value>
        [Required]
        public Type SelectedType
        {
            get => selectedType;
            set
            {
                if ( SetProperty( ref selectedType, value ) )
                {
                    DialogCommands.RaiseCanExecuteChanged();
                }
            }
        }

        /// <summary>
        /// Gets or sets the type filter specification.
        /// </summary>
        /// <value>A <see cref="ISpecification{T}">specification</see> representing the type filter.</value>
        /// <remarks>The default <see cref="ISpecification{T}">specification</see> is based on the values
        /// of the <see cref="FilterByConvention"/> and <see cref="NameConvention"/> properties.</remarks>
        public ISpecification<Type> TypeFilter
        {
            get
            {
                Contract.Ensures( typeFilter != null );
                return typeFilter ?? ( typeFilter = CreateFilter( NameConvention, RestrictedBaseTypeNames ) );
            }
            set
            {
                Arg.NotNull( value, nameof( value ) );

                if ( !SetProperty( ref typeFilter, value ) )
                {
                    return;
                }

                // if the filter is updated, re-evaluate the specification if a type has been selected
                if ( value != null && SelectedType != null && !value.IsSatisfiedBy( SelectedType ) )
                {
                    SelectedType = null;
                }
            }
        }

        /// <summary>
        /// Gets a collection of restricted base type names.
        /// </summary>
        /// <value>A <see cref="ICollection{T}">collection</see> of base type names.</value>
        /// <remarks>The specified type names can be the type <see cref="Type.FullName">full name</see>
        /// or <see cref="Type.Name">simple name</see>.</remarks>
        public ICollection<string> RestrictedBaseTypeNames
        {
            get
            {
                Contract.Ensures( restrictedBaseTypeNames != null );
                return restrictedBaseTypeNames;
            }
        }
    }
}


text:
package com.frank.search.solr.repository.query;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.query.ParametersParameterAccessor;

import java.util.Iterator;

/**
 * Implementation of {@link SolrParameterAccessor}
 *
 * @author Christoph Strobl
 */
public class SolrParametersParameterAccessor implements SolrParameterAccessor {

	private final SolrParameters parameters;
	private final ParametersParameterAccessor parametersParameterAccessorDelegate;

	public SolrParametersParameterAccessor(SolrQueryMethod solrQueryMethod, Object[] values) {
		this.parameters = solrQueryMethod.getParameters();
		this.parametersParameterAccessorDelegate = new ParametersParameterAccessor(this.parameters, values.clone());
	}

	@Override
	public float getBoost(int index) {
		return parameters.getBindableParameter(index).getBoost();
	}

	@Override
	public Pageable getPageable() {
		return parametersParameterAccessorDelegate.getPageable();
	}

	@Override
	public Sort getSort() {
		return parametersParameterAccessorDelegate.getSort();
	}

	@Override
	public Object getBindableValue(int index) {
		return parametersParameterAccessorDelegate.getBindableValue(index);
	}

	@Override
	public boolean hasBindableNullValue() {
		return parametersParameterAccessorDelegate.hasBindableNullValue();
	}

	@Override
	public Iterator<Object> iterator() {
		return new BindableSolrParameterIterator(parametersParameterAccessorDelegate.iterator());
	}

	public class BindableSolrParameterIterator implements Iterator<Object> {

		private final Iterator<Object> delegate;
		private int currentIndex = 0;

		public BindableSolrParameterIterator(Iterator<Object> delegate) {
			this.delegate = delegate;
		}

		@Override
		public boolean hasNext() {
			return delegate.hasNext();
		}

		@Override
		public BindableSolrParameter next() {
			BindableSolrParameter solrParameter = new BindableSolrParameter(currentIndex, delegate.next());
			solrParameter.setBoost(parameters.getBindableParameter(currentIndex).getBoost());
			currentIndex++;
			return solrParameter;
		}

		@Override
		public void remove() {
			delegate.remove();
		}

	}

}


text:
'use strict';

routing.$inject = ['$urlRouterProvider', '$locationProvider', '$stateProvider'];

export default function routing($urlRouterProvider, $locationProvider, $stateProvider) {

  $locationProvider.html5Mode(true);

  $urlRouterProvider.otherwise('/');
}


text:
import os
import shutil
import tempfile
import unittest

import mock

from chainer import dataset
from chainer import testing

class TestGetSetDatasetRoot(unittest.TestCase):

    def test_set_dataset_root(self):
        orig_root = dataset.get_dataset_root()
        new_root = '/tmp/dataset_root'
        try:
            dataset.set_dataset_root(new_root)
            self.assertEqual(dataset.get_dataset_root(), new_root)
        finally:
            dataset.set_dataset_root(orig_root)

class TestGetDatasetDirectory(unittest.TestCase):

    def test_get_dataset_directory(self):
        root = dataset.get_dataset_root()
        path = dataset.get_dataset_directory('test', False)
        self.assertEqual(path, os.path.join(root, 'test'))

class TestCacheOrLoadFile(unittest.TestCase):

    def setUp(self):
        self.default_dataset_root = dataset.get_dataset_root()
        self.temp_dir = tempfile.mkdtemp()
        dataset.set_dataset_root(self.temp_dir)

    def tearDown(self):
        dataset.set_dataset_root(self.default_dataset_root)
        shutil.rmtree(self.temp_dir)

    def test_cache_exists(self):
        creator = mock.Mock()
        loader = mock.Mock()

        file_desc, file_name = tempfile.mkstemp()

        try:
            dataset.cache_or_load_file(file_name, creator, loader)
        finally:
            os.close(file_desc)
            os.remove(file_name)

        self.assertFalse(creator.called)
        loader.assert_called_once_with(file_name)

    def test_new_file(self):
        def create(path):
            with open(path, 'w') as f:
                f.write('test')

        creator = mock.Mock()
        creator.side_effect = create
        loader = mock.Mock()

        dir_path = tempfile.mkdtemp()
        # This file always does not exists as the directory is new.
        path = os.path.join(dir_path, 'cahche')

        try:
            dataset.cache_or_load_file(path, creator, loader)

            self.assertEqual(creator.call_count, 1)
            self.assertFalse(loader.called)

            self.assertTrue(os.path.exists(path))
            with open(path) as f:
                self.assertEqual(f.read(), 'test')

        finally:
            shutil.rmtree(dir_path)

class TestCacheOrLoadFileFileExists(unittest.TestCase):

    def setUp(self):
        self.default_dataset_root = dataset.get_dataset_root()
        self.temp_file_desc, self.temp_file_name = tempfile.mkstemp()
        dataset.set_dataset_root(self.temp_file_name)
        self.dir_path = tempfile.mkdtemp()

    def tearDown(self):
        dataset.set_dataset_root(self.default_dataset_root)
        os.close(self.temp_file_desc)
        os.remove(self.temp_file_name)
        shutil.rmtree(self.dir_path)

    def test_file_exists(self):
        creator = mock.Mock()
        loader = mock.Mock()

        # This file always does not exists as the directory is new.
        path = os.path.join(self.dir_path, 'cahche')

        with self.assertRaises(RuntimeError):
            dataset.cache_or_load_file(path, creator, loader)

class TestCachedDownload(unittest.TestCase):

    def setUp(self):
        self.default_dataset_root = dataset.get_dataset_root()
        self.temp_dir = tempfile.mkdtemp()
        dataset.set_dataset_root(self.temp_dir)

    def tearDown(self):
        dataset.set_dataset_root(self.default_dataset_root)
        shutil.rmtree(self.temp_dir)

    def test_fail_to_make_dir(self):
        with mock.patch('os.makedirs') as f:
            f.side_effect = OSError()
            with self.assertRaises(OSError):
                dataset.cached_download('https://example.com')

    def test_file_exists(self):
        # Make an empty file which has the same name as the cache directory
        with open(os.path.join(self.temp_dir, '_dl_cache'), 'w'):
            pass
        with self.assertRaises(OSError):
            dataset.cached_download('https://example.com')

    def test_cached_download(self):
        with mock.patch('six.moves.urllib.request.urlretrieve') as f:
            def download(url, path):
                with open(path, 'w') as f:
                    f.write('test')
            f.side_effect = download

            cache_path = dataset.cached_download('https://example.com')

        self.assertEqual(f.call_count, 1)
        args, kwargs = f.call_args
        self.assertEqual(kwargs, {})
        self.assertEqual(len(args), 2)
        # The second argument is a temporary path, and it is removed
        self.assertEqual(args[0], 'https://example.com')

        self.assertTrue(os.path.exists(cache_path))
        with open(cache_path) as f:
            stored_data = f.read()
        self.assertEqual(stored_data, 'test')

testing.run_module(__name__, __file__)


text:
from pymongo import MongoClient
from helpers import db_url, db_database, group_xls, to_int
from subjects import subject_name

mongo = MongoClient(db_url)
db = mongo[db_database]

print("Updating A-level results (2015)...")

A2 = group_xls("../data/2015/ks5_subjects.xlsx", "1.A level",
               group_by="URN",
               extract=["Subject", "Number entered", "Grade A*", "Grade A", "Grade B", "Grade C", "Grade D", "Grade E", "No results"],
               header_row=2)

for school in A2:
    urn = str(school["URN"])
    subjects = {}

    for row in school["rows"]:
        total = int(row["Number entered"])
        subject = subject_name(row["Subject"])

        if total > 5:
            subjects[subject] = {
                "A*": to_int(row["Grade A*"]),
                "A": to_int(row["Grade A"]),
                "B": to_int(row["Grade B"]),
                "C": to_int(row["Grade C"]),
                "D": to_int(row["Grade D"]),
                "E": to_int(row["Grade E"]),
                "NR": to_int(row["No results"]),
                "total": total
            }
        else:
            subjects[subject] = {
                "total": total
            }

    db.schools.update(
        { "_id": urn },
        { "$set": { "performance.2015.results.a-level": subjects } }
    )

mongo.close()

print("\nDone.")


text:
namespace Microsoft.Azure.Management.Security
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// AssessmentsOperations operations.
    /// </summary>
    public partial interface IAssessmentsOperations
    {
        /// <summary>
        /// Get security assessments on all your scanned resources inside a
        /// scope
        /// </summary>
        /// <param name='scope'>
        /// Scope of the query, can be subscription
        /// (/subscriptions/0b06d9ea-afe6-4779-bd59-30e5c2d9d13f) or management
        /// group (/providers/Microsoft.Management/managementGroups/mgName).
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<SecurityAssessmentResponse>>> ListWithHttpMessagesAsync(string scope, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get a security assessment on your scanned resource
        /// </summary>
        /// <param name='resourceId'>
        /// The identifier of the resource.
        /// </param>
        /// <param name='assessmentName'>
        /// The Assessment Key - Unique key for the assessment type
        /// </param>
        /// <param name='expand'>
        /// OData expand. Optional. Possible values include: 'links',
        /// 'metadata'
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<SecurityAssessmentResponse>> GetWithHttpMessagesAsync(string resourceId, string assessmentName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Create a security assessment on your resource. An assessment
        /// metadata that describes this assessment must be predefined with the
        /// same name before inserting the assessment result
        /// </summary>
        /// <param name='resourceId'>
        /// The identifier of the resource.
        /// </param>
        /// <param name='assessmentName'>
        /// The Assessment Key - Unique key for the assessment type
        /// </param>
        /// <param name='assessment'>
        /// Calculated assessment on a pre-defined assessment metadata
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<SecurityAssessmentResponse>> CreateOrUpdateWithHttpMessagesAsync(string resourceId, string assessmentName, SecurityAssessment assessment, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Delete a security assessment on your resource. An assessment
        /// metadata that describes this assessment must be predefined with the
        /// same name before inserting the assessment result
        /// </summary>
        /// <param name='resourceId'>
        /// The identifier of the resource.
        /// </param>
        /// <param name='assessmentName'>
        /// The Assessment Key - Unique key for the assessment type
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceId, string assessmentName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Get security assessments on all your scanned resources inside a
        /// scope
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<SecurityAssessmentResponse>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Symbols</title>
	<link rel="stylesheet" href="../css/style.css">
	<script type="text/javascript" src="../../lib/paper.js"></script>
	<script type="text/paperscript" canvas="canvas">
		var ellipse = new Path.Ellipse({
			from: [0, 0],
			to: [200, 100],
			fillColor: 'red'
		});
		var symbol = new Symbol(ellipse);
		var p1 = symbol.place([100, 100]);
		p1.rotate(45);
		var p2 = symbol.place([300, 200]);
		p2.rotate(-30);
		document.getElementById('svg').appendChild(project.exportSVG());
	</script>
</head>
<body>
	<canvas id="canvas" width="500" height="500"></canvas>
	<svg id="svg" width="500" height="500"></svg>
</body>
</html>


text:
/**
 * Helper function that will load data from the Princeton Election Consortium's endpoints
 * and update the extension's HTML pages with the data
 *
 * @returns Void
 */
function updatePECBackground() {
	updatePEC('background');
}

/**
 * Helper function that will load data from the Princeton Election Consortium's endpoints
 * and update the extension's HTML pages with the data
 *
 *
 * @returns Void
 */
function updatePECPopup() {
	updatePEC('popup');
}

/**
 * Helper function that will load data from the Princeton Election Consortium's endpoints
 * and update the extension's HTML pages with the data
 *
 * @param   String target one of 'popup' or 'background'
 *
 * @returns Void
 */
function updatePEC(target) {
	// the 'current_ev.html' is a microformat page consisting of a UL with a number of child LI elements.
	// the content of these change with the election season and we may update our formatting below to adjust
	$("#raw").load("http://election.princeton.edu/code/output/banner.html", function() {
		var newestPost = '';
		var newestPostByline = '';

		var lidata = [];

		for (i=0; i < 6; i++) {
			val = $("#raw li").eq(i).text();
			if (val !== '' && val !== 'RSS') {
				lidata.push(val);
			}
		}
		if (target == 'popup') {

			for (i=0; i< 6; i++) {
				if (typeof(lidata[i] != 'undefined')) {
					$("#li" + i).html(lidata[i]);
				}
			}

			// load the RSS feed so we can link to the newest post
			$.get("http://election.princeton.edu/feed", function(data) {
				var $xml = $(data);
				$xml.find("item:first").each(function() {
					var $this = $(this),
						item = {
							title: $this.find("title").text(),
							link: $this.find("link").text(),
							description: $this.find("description").text(),
							pubDate: $this.find("pubDate").text(),
							author: $this.find("creator").text()
						};

					newestPost = '' + item.title + '';
					newestPostByline = 'by ' + item.author + ' at ' + item.pubDate;
				  $("#newest-post-link").html(newestPost);
				  $("#newest-post-byline").html(newestPostByline);
				});
			});

			// graph image
			var graph_image_url = 'http://election.princeton.edu/wp-content/uploads/autographics/EV_histogram_today-200px.png';
			$("#graph-image").attr("src", graph_image_url);

			// map image
			var map_image_url = "http://election.princeton.edu/wp-content/uploads/autographics/EV_map.png-white";
			$("#map-image").attr("src", map_image_url);

			// hide spinner
			$("#spinner").hide();

			// reveal the loaded content container
			$("#loaded-content").show();
		}

		var title = lidata.join("\n");
		var badge = '';
		chrome.browserAction.setBadgeText({ text: badge });
		chrome.browserAction.setTitle( { title: title } );

	});

}


text:
<?php

namespace Zimbra\Soap\Tests;

use Zimbra\Soap\Request;
use Zimbra\Soap\Request\Attr;
use Zimbra\Soap\Request\Batch;

/**
 * Testcase class for soap request.
 */
class RequestTest extends ZimbraSoapTestCase
{
    public function testRequest()
    {
        $stub = $this->getMockForAbstractClass('\Zimbra\Soap\Request');
        $this->assertStringEndsWith('Request', $stub->requestName());
        $this->assertStringEndsWith('Response', $stub->responseName());

        $xml = '<?xml version="1.0"?>'."\n"
            .'<'.$stub->requestName().' />';
        $this->assertXmlStringEqualsXmlString($xml, $stub->toXml()->asXml());
    }

    public function testAttrRequest()
    {
        $stub = $this->getMockForAbstractClass('\Zimbra\Soap\Request\Attr');

        $attr1 = new \Zimbra\Struct\KeyValuePair('key1', 'value1');
        $attr2 = new \Zimbra\Struct\KeyValuePair('key2', 'value2');
        $attr3 = new \Zimbra\Struct\KeyValuePair('key3', 'value3');
        $stub->addAttr($attr1)->getAttrs()->addAll([$attr2, $attr3]);
        $this->assertEquals([$attr1, $attr2, $attr3], $stub->getAttrs()->all());

        $xml = '<?xml version="1.0"?>'."\n"
            .'<'.$stub->requestName().'>'
                .'value1'
                .'value2'
                .'value3'
            .'</'.$stub->requestName().'>';
        $this->assertXmlStringEqualsXmlString($xml, $stub->toXml()->asXml());
    }

    public function testBatchRequest()
    {
        $req1 = $this->getMockForAbstractClass('\Zimbra\Soap\Request');
        $req1->setXmlNamespace('urn:zimbraMail');

        $req2 = $this->getMockForAbstractClass('\Zimbra\Soap\Request');
        $req2->setXmlNamespace('urn:zimbraAdmin');

        $batch = new Batch([$req1, $req2]);
        $this->assertEquals([$req1, $req2], $batch->getRequests()->all());

         $xml = '<?xml version="1.0"?>'."\n"
                .'<BatchRequest>'
                    .'<'.$req1->requestName().' xmlns="urn:zimbraMail" requestId="0" />'
                    .'<'.$req2->requestName().' xmlns="urn:zimbraAdmin" requestId="1" />'
                .'</BatchRequest>';
        $this->assertXmlStringEqualsXmlString($xml, $batch->toXml()->asXml());
    }
}


text:
package org.camunda.bpm.engine.impl.cmd;

import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;

import java.io.Serializable;

import org.camunda.bpm.engine.impl.cfg.CommandChecker;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;

/**
 * @author Frederik Heremans
 */
public class GetJobExceptionStacktraceCmd implements Command<String>, Serializable{

  private static final long serialVersionUID = 1L;
  private String jobId;

  public GetJobExceptionStacktraceCmd(String jobId) {
    this.jobId = jobId;
  }

  public String execute(CommandContext commandContext) {
    ensureNotNull("jobId", jobId);

    JobEntity job = commandContext
      .getJobManager()
      .findJobById(jobId);

    ensureNotNull("No job found with id " + jobId, "job", job);

    for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
      checker.checkReadJob(job);
    }

    return job.getExceptionStacktrace();
  }

}


text:
/*!
 * wavesurfer.js microphone plugin 6.0.2 (2022-02-20)
 * https://wavesurfer-js.org
 * @license BSD-3-Clause
 */
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define("WaveSurfer", [], factory);
	else if(typeof exports === 'object')
		exports["WaveSurfer"] = factory();
	else
		root["WaveSurfer"] = root["WaveSurfer"] || {}, root["WaveSurfer"]["microphone"] = factory();
})(self, function() {
return /******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./src/plugin/microphone/index.js":
/*!****************************************!*\
  !*** ./src/plugin/microphone/index.js ***!
  \****************************************/
/***/ ((module, exports) => {

Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports["default"] = void 0;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

/**
 * @typedef {Object} MicrophonePluginParams
 * @property {MediaStreamConstraints} constraints The constraints parameter is a
 * MediaStreamConstaints object with two members: video and audio, describing
 * the media types requested. Either or both must be specified.
 * @property {number} bufferSize=4096 The buffer size in units of sample-frames.
 * If specified, the bufferSize must be one of the following values: `256`,
 * `512`, `1024`, `2048`, `4096`, `8192`, `16384`
 * @property {number} numberOfInputChannels=1 Integer specifying the number of
 * channels for this node's input. Values of up to 32 are supported.
 * @property {number} numberOfOutputChannels=1 Integer specifying the number of
 * channels for this node's output.
 * @property {?boolean} deferInit Set to true to manually call
 * `initPlugin('microphone')`
 */

/**
 * Visualize microphone input in a wavesurfer instance.
 *
 * @implements {PluginClass}
 * @extends {Observer}
 * @example
 * // es6
 * import MicrophonePlugin from 'wavesurfer.microphone.js';
 *
 * // commonjs
 * var MicrophonePlugin = require('wavesurfer.microphone.js');
 *
 * // if you are using <script> tags
 * var MicrophonePlugin = window.WaveSurfer.microphone;
 *
 * // ... initialising wavesurfer with the plugin
 * var wavesurfer = WaveSurfer.create({
 *   // wavesurfer options ...
 *   plugins: [
 *     MicrophonePlugin.create({
 *       // plugin options ...
 *     })
 *   ]
 * });
 */
var MicrophonePlugin = /*#__PURE__*/function () {
  function MicrophonePlugin(params, ws) {
    var _this = this;

    _classCallCheck(this, MicrophonePlugin);

    this.params = params;
    this.wavesurfer = ws;
    this.active = false;
    this.paused = false;
    this.browser = this.detectBrowser();

    this.reloadBufferFunction = function (e) {
      return _this.reloadBuffer(e);
    }; // cross-browser getUserMedia

    var promisifiedOldGUM = function promisifiedOldGUM(constraints, successCallback, errorCallback) {
      // get a hold of getUserMedia, if present
      var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia; // Some browsers just don't implement it - return a rejected
      // promise with an error to keep a consistent interface

      if (!getUserMedia) {
        return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
      } // otherwise, wrap the call to the old navigator.getUserMedia with
      // a Promise

      return new Promise(function (successCallback, errorCallback) {
        getUserMedia.call(navigator, constraints, successCallback, errorCallback);
      });
    }; // Older browsers might not implement mediaDevices at all, so we set an
    // empty object first

    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {};
    } // Some browsers partially implement mediaDevices. We can't just assign
    // an object with getUserMedia as it would overwrite existing
    // properties. Here, we will just add the getUserMedia property if it's
    // missing.

    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = promisifiedOldGUM;
    }

    this.constraints = this.params.constraints || {
      video: false,
      audio: true
    };
    this.bufferSize = this.params.bufferSize || 4096;
    this.numberOfInputChannels = this.params.numberOfInputChannels || 1;
    this.numberOfOutputChannels = this.params.numberOfOutputChannels || 1;

    this._onBackendCreated = function () {
      // wavesurfer's AudioContext where we'll route the mic signal to
      _this.micContext = _this.wavesurfer.backend.getAudioContext();
    };
  }

  _createClass(MicrophonePlugin, [{
    key: "init",
    value: function init() {
      this.wavesurfer.on('backend-created', this._onBackendCreated);

      if (this.wavesurfer.backend) {
        this._onBackendCreated();
      }
    }
    /**
     * Destroy the microphone plugin.
     */

  }, {
    key: "destroy",
    value: function destroy() {
      // make sure the buffer is not redrawn during
      // cleanup and demolition of this plugin.
      this.paused = true;
      this.wavesurfer.un('backend-created', this._onBackendCreated);
      this.stop();
    }
    /**
     * Allow user to select audio input device, e.g. microphone, and
     * start the visualization.
     */

  }, {
    key: "start",
    value: function start() {
      var _this2 = this;

      navigator.mediaDevices.getUserMedia(this.constraints).then(function (data) {
        return _this2.gotStream(data);
      }).catch(function (data) {
        return _this2.deviceError(data);
      });
    }
    /**
     * Pause/resume visualization.
     */

  }, {
    key: "togglePlay",
    value: function togglePlay() {
      if (!this.active) {
        // start it first
        this.start();
      } else {
        // toggle paused
        this.paused = !this.paused;

        if (this.paused) {
          this.pause();
        } else {
          this.play();
        }
      }
    }
    /**
     * Play visualization.
     */

  }, {
    key: "play",
    value: function play() {
      this.paused = false;
      this.connect();
    }
    /**
     * Pause visualization.
     */

  }, {
    key: "pause",
    value: function pause() {
      this.paused = true; // disconnect sources so they can be used elsewhere
      // (eg. during audio playback)

      this.disconnect();
    }
    /**
     * Stop the device stream and remove any remaining waveform drawing from
     * the wavesurfer canvas.
     */

  }, {
    key: "stop",
    value: function stop() {
      if (this.active) {
        // stop visualization and device
        this.stopDevice(); // empty last frame

        this.wavesurfer.empty();
      }
    }
    /**
     * Stop the device and the visualization.
     */

  }, {
    key: "stopDevice",
    value: function stopDevice() {
      this.active = false; // stop visualization

      this.disconnect(); // stop stream from device

      if (this.stream && this.stream.getTracks) {
        this.stream.getTracks().forEach(function (stream) {
          return stream.stop();
        });
      }
    }
    /**
     * Connect the media sources that feed the visualization.
     */

  }, {
    key: "connect",
    value: function connect() {
      if (this.stream !== undefined) {
        // Create a local buffer for data to be copied to the Wavesurfer buffer for Edge
        if (this.browser.browser === 'edge') {
          this.localAudioBuffer = this.micContext.createBuffer(this.numberOfInputChannels, this.bufferSize, this.micContext.sampleRate);
        } // Create an AudioNode from the stream.

        this.mediaStreamSource = this.micContext.createMediaStreamSource(this.stream);
        this.levelChecker = this.micContext.createScriptProcessor(this.bufferSize, this.numberOfInputChannels, this.numberOfOutputChannels);
        this.mediaStreamSource.connect(this.levelChecker);
        this.levelChecker.connect(this.micContext.destination);
        this.levelChecker.onaudioprocess = this.reloadBufferFunction;
      }
    }
    /**
     * Disconnect the media sources that feed the visualization.
     */

  }, {
    key: "disconnect",
    value: function disconnect() {
      if (this.mediaStreamSource !== undefined) {
        this.mediaStreamSource.disconnect();
      }

      if (this.levelChecker !== undefined) {
        this.levelChecker.disconnect();
        this.levelChecker.onaudioprocess = undefined;
      }

      if (this.localAudioBuffer !== undefined) {
        this.localAudioBuffer = undefined;
      }
    }
    /**
     * Redraw the waveform.
     *
     * @param {object} event Audioprocess event
     */

  }, {
    key: "reloadBuffer",
    value: function reloadBuffer(event) {
      if (!this.paused) {
        this.wavesurfer.empty();

        if (this.browser.browser === 'edge') {
          // copy audio data to a local audio buffer,
          // from https://github.com/audiojs/audio-buffer-utils
          var channel, l;

          for (channel = 0, l = Math.min(this.localAudioBuffer.numberOfChannels, event.inputBuffer.numberOfChannels); channel < l; channel++) {
            this.localAudioBuffer.getChannelData(channel).set(event.inputBuffer.getChannelData(channel));
          }

          this.wavesurfer.loadDecodedBuffer(this.localAudioBuffer);
        } else {
          this.wavesurfer.loadDecodedBuffer(event.inputBuffer);
        }
      }
    }
    /**
     * Audio input device is ready.
     *
     * @param {MediaStream} stream The microphone's media stream.
     */

  }, {
    key: "gotStream",
    value: function gotStream(stream) {
      this.stream = stream;
      this.active = true; // start visualization

      this.play(); // notify listeners

      this.fireEvent('deviceReady', stream);
    }
    /**
     * Device error callback.
     *
     * @param {string} code Error message
     */

  }, {
    key: "deviceError",
    value: function deviceError(code) {
      // notify listeners
      this.fireEvent('deviceError', code);
    }
    /**
     * Extract browser version out of the provided user agent string.
     * @param {!string} uastring userAgent string.
     * @param {!string} expr Regular expression used as match criteria.
     * @param {!number} pos position in the version string to be returned.
     * @return {!number} browser version.
     */

  }, {
    key: "extractVersion",
    value: function extractVersion(uastring, expr, pos) {
      var match = uastring.match(expr);
      return match && match.length >= pos && parseInt(match[pos], 10);
    }
    /**
     * Browser detector.
     * @return {object} result containing browser, version and minVersion
     *     properties.
     */

  }, {
    key: "detectBrowser",
    value: function detectBrowser() {
      // Returned result object.
      var result = {};
      result.browser = null;
      result.version = null;
      result.minVersion = null; // Non supported browser.

      if (typeof window === 'undefined' || !window.navigator) {
        result.browser = 'Not a supported browser.';
        return result;
      }

      if (navigator.mozGetUserMedia) {
        // Firefox
        result.browser = 'firefox';
        result.version = this.extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1);
        result.minVersion = 31;
        return result;
      } else if (navigator.webkitGetUserMedia) {
        // Chrome/Chromium/Webview/Opera
        result.browser = 'chrome';
        result.version = this.extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
        result.minVersion = 38;
        return result;
      } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
        // Edge
        result.browser = 'edge';
        result.version = this.extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2);
        result.minVersion = 10547;
        return result;
      } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
        // Safari
        result.browser = 'safari';
        result.minVersion = 11;
        result.version = this.extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
        return result;
      } // Non supported browser default.

      result.browser = 'Not a supported browser.';
      return result;
    }
  }], [{
    key: "create",
    value:
    /**
     * Microphone plugin definition factory
     *
     * This function must be used to create a plugin definition which can be
     * used by wavesurfer to correctly instantiate the plugin.
     *
     * @param  {MicrophonePluginParams} params parameters use to initialise the plugin
     * @return {PluginDefinition} an object representing the plugin
     */
    function create(params) {
      return {
        name: 'microphone',
        deferInit: params && params.deferInit ? params.deferInit : false,
        params: params,
        instance: MicrophonePlugin
      };
    }
  }]);

  return MicrophonePlugin;
}();

exports["default"] = MicrophonePlugin;
module.exports = exports.default;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/************************************************************************/
/******/
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__("./src/plugin/microphone/index.js");
/******/
/******/ 	return __webpack_exports__;
/******/ })()
;
});
//# sourceMappingURL=wavesurfer.microphone.js.map


text:
angular.module('app').factory('fbRef', function(rootRef){
    return {
        getItemsRef: function() {
            return rootRef.child('items');

        },
        getUserInfoRef: function(){
            return rootRef.child('userInfo');
        },
        getJobsRef: function(){
            return rootRef.child('jobs');
        }
    }
})


text:
/**
 * phantomas CommonJS module
 */
"use strict";

const Browser = require("./browser"),
  EventEmitter = require("./AwaitEventEmitter"),
  debug = require("debug")("phantomas:core"),
  loader = require("./loader"),
  puppeteer = require("puppeteer"),
  path = require("path"),
  Results = require("../core/results"),
  VERSION = require("./../package").version;

/**
 * Main CommonJS module entry point
 *
 * @param {string} url
 * @param {Object} opts
 * @returns {browser}
 */
function phantomas(url, opts) {
  var events = new EventEmitter(),
    browser,
    options;

  debug("OS: %s %s", process.platform, process.arch);
  debug("Node.js: %s", process.version);
  debug("phantomas: %s", VERSION);
  debug(
    "Puppeteer: preferred revision r%s",
    puppeteer.default._preferredRevision
  );
  debug("URL: <%s>", url);

  // options handling
  options = Object.assign({}, opts || {}); // avoid #563
  options.url = options.url || url || false;

  debug("Options: %s", JSON.stringify(options));

  events.setMaxListeners(250); // MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

  var results = new Results();
  results.setUrl(url);
  results.setGenerator("phantomas v" + VERSION);

  // set up and run Puppeteer
  browser = new Browser();
  browser.bind(events);

  var promise = new Promise(async (resolve, reject) => {
    try {
      if (typeof options.url !== "string") {
        return reject(Error("URL must be a string"));
      }

      const page = await browser.init(options),
        debugScope = require("debug")("phantomas:scope:log");

      // prepare a small instance object that will be passed to modules and extensions on init
      const scope = {
        getParam: (param, _default) => {
          return options[param] || _default;
        },
        getVersion: () => VERSION,

        emit: events.emit.bind(events),
        on: events.on.bind(events),
        once: events.once.bind(events),

        log: debugScope.bind(debug),

        addOffender: results.addOffender.bind(results),
        incrMetric: results.incrMetric.bind(results),
        setMetric: results.setMetric,
        addToAvgMetric: results.addToAvgMetric,

        getMetric: results.getMetric,

        // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluatepagefunction-args
        evaluate: page.evaluate.bind(page),

        // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1
        querySelectorAll: async function querySelectorAll(
          selector
        ) /* istanbul ignore next */ {
          debug('querySelectorAll("%s")', selector);
          return page.$$(selector);
        },

        // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args
        injectJs: async (script) => {
          const debug = require("debug")("phantomas:injectJs");

          // Make sure we're on an HTML document, not an XML document for example
          const prefix = "if (document.constructor.name === 'HTMLDocument') {",
            suffix = "}";

          const preloadFile =
            prefix + require("fs").readFileSync(script, "utf8") + suffix;

          await page.evaluateOnNewDocument(preloadFile);

          debug(script + " JavaScript file has been injected into page scope");
        },
      };

      // pass phantomas options to page scope
      // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args
      /* istanbul ignore next */
      await page.evaluateOnNewDocument((options) => {
        window.__phantomas_options = options;
      }, options);

      // expose the function that will pass events from page scope code into Node.js layer
      // @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction
      await page.exposeFunction("__phantomas_emit", scope.emit);

      // Inject helper code into the browser's scope
      events.on("init", () => {
        scope.injectJs(__dirname + "/../core/scope.js");
      });

      // bind to sendMsg calls from page scope code
      events.on("scopeMessage", (type, args) => {
        const debug = require("debug")("phantomas:core:scopeEvents");
        // debug(type + ' [' + args + ']');

        switch (type) {
          case "addOffender":
          case "incrMetric":
          case "log":
          case "setMetric":
            scope[type].apply(scope, args);
            break;

          /* istanbul ignore next */
          default:
            debug("Unrecognized event type: " + type);
        }
      });

      // bind to a first response
      // and reject a promise if the first response is 4xx / 5xx HTTP error
      var firstResponseReceived = false;

      events.once("recv", async (entry) => {
        if (!firstResponseReceived && entry.status >= 400) {
          debug(
            "<%s> response code is HTTP %d %s",
            entry.url,
            entry.status,
            entry.statusText
          );

          // close the browser before leaving here, otherwise subsequent instances will have problems
          await browser.close();
          reject(
            new Error(
              "HTTP response code from <" + entry.url + "> is " + entry.status
            )
          );
        }

        firstResponseReceived = true;
      });

      // load modules and extensions
      debug("Loading core modules...");
      loader.loadCoreModules(scope);

      debug("Loading extensions...");
      loader.loadExtensions(scope);

      debug("Loading modules...");
      loader.loadModules(scope);

      await events.emit("init", page, browser.getPuppeteerBrowser()); // @desc Browser's scope and modules are set up, the page is about to be loaded

      // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagegotourl-options
      const waitUntil = options["wait-for-network-idle"]
          ? "networkidle0"
          : undefined,
        timeout = options.timeout;

      await browser.visit(url, waitUntil, timeout);

      // resolve our run
      // https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#browserclose
      await events.emit("beforeClose", page); // @desc Called before the Chromium (and all of its pages) is closed
      await browser.close();

      // your last chance to add metrics
      await events.emit("report"); // @desc Called just before the phantomas results are returned to the caller

      resolve(results);
    } catch (ex) {
      debug("Exception caught: " + ex);
      debug(ex);

      // close the browser before leaving here, otherwise subsequent instances will have problems
      await browser.close();
      reject(ex);
    }
  });

  promise.on = events.on.bind(events);
  promise.once = events.once.bind(events);

  return promise;
}

phantomas.metadata = require(__dirname + "/metadata/metadata.json");
phantomas.path = path.normalize(__dirname + "/..");
phantomas.version = VERSION;

module.exports = phantomas;


text:
Formulas
========

Formulas modules implement common and shared functions for solvers such as
 * QUBO -> Hamiltonian conversion
 * Energy calculation frmm bits or spins including batched versions.

There are 3 versions of formulas modules in sqaod.py, sqaod.cpu and sqaod.cuda.

The sqoad.py.formulas module has reference implementations.  Other formuas modules in sqaod.cpu and sqaod.cuda are accleretaed by CPU or CUDA respectively.

sqaod.py.formulas
^^^^^^^^^^^^^^^^^

:note: A parameter, dtype, has None as the default value, which is simply ignored in sqaod.py.formulas.
       Dtype paramter here is to keep function sigunatures being the same as those in other modules.

.. automodule:: sqaod.py.formulas
   :members:

sqaod.cpu.formulas, sqaod.cuda.formulas
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Functions in sqaod.cpu.formulas sqaod.cuda.formulas have the same sinatures and functionlities, thus, documentations are ommited here.

One exception is the dtype parameter.   The dtype paramter does not have its default value, and should be explicitly specified.  Allowed values are numpy.float32 and numpy.float64.  Floating-point parameters (such as vector, matrix, scalars) given to these functions will be converted to the type specified by dtype before calculation.


text:
package com.example.helloworld.core;

import java.security.Principal;
import java.util.Random;
import java.util.Set;

public class User implements Principal {
    private static final Random rng = new Random();

    private final String name;

    private final Set<String> roles;

    public User(String name) {
        this.name = name;
        this.roles = null;
    }

    public User(String name, Set<String> roles) {
        this.name = name;
        this.roles = roles;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return rng.nextInt(100);
    }

    public Set<String> getRoles() {
        return roles;
    }
}


text:
package org.cactoos.text;

import org.cactoos.Text;
import org.hamcrest.core.IsEqual;
import org.hamcrest.core.IsNot;
import org.junit.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.IsText;

/**
 * Test case for {@link FormattedText}.
 *
 * @since 0.27
 * @checkstyle JavadocMethodCheck (100 lines)
 */
public final class ComparableTextTest {

    @Test
    public void comparesWithASubtext() {
        new Assertion<>(
            "Can't compare sub texts",
            new ComparableText(
                new TextOf(
                    "here to there"
                )
            ).compareTo(
                new ComparableText(
                    new Sub("from here to there", 5)
                )
            ),
            new IsEqual<>(0)
        ).affirm();
    }

    @Test
    public void comparesToUncheckedText() {
        final String txt = "foobar";
        new Assertion<>(
            "These UncheckedText are not equal",
            new ComparableText(
                new UncheckedText(
                    new TextOf(txt)
                )
            ).compareTo(
                new ComparableText(new TextOf(txt))
            ),
            new IsEqual<>(0)
        ).affirm();
    }

    @Test
    public void equalsToItself() {
        final Text text = new TextOf("text");
        new Assertion<>(
            "Does not equal to itself",
            text,
            new IsText(text)
        ).affirm();
    }

    @Test
    public void equalsAndHashCodeOfComparableOfTheSameText() {
        final Text text = new TextOf("my text");
        final Text actual = new ComparableText(text);
        final Text expected = new ComparableText(text);
        new Assertion<>(
            "Does not equal to a comparable text made from the same Text",
            actual,
            new IsEqual<>(expected)
        ).affirm();
        new Assertion<>(
            "Hash codes of the equal objects are not equal",
            actual.hashCode(),
            new IsEqual<>(
                expected.hashCode()
            )
        ).affirm();
    }

    @Test
    public void equalsOfDifferentText() {
        final Text text = new ComparableText(
            new TextOf("my value")
        );
        new Assertion<>(
            "Is equal to the completely different object",
            text,
            new IsNot<>(
                new IsEqual<>(
                    "The string is ignored"
                )
            )
        ).affirm();
        new Assertion<>(
            "Is equal to the completely different text",
            text,
            new IsNot<>(
                new IsText(
                    "The text is ignored"
                )
            )
        ).affirm();
        new Assertion<>(
            "Is equal to the different ComparableText",
            text,
            new IsNot<>(
                new IsEqual<>(
                    new ComparableText(
                        new TextOf("A different text")
                    )
                )
            )
        ).affirm();
        new Assertion<>(
            "The string is equal to the different ComparableText",
            text,
            new IsNot<>(
                new IsText(
                    new ComparableText(
                        new TextOf("A different value")
                    )
                )
            )
        ).affirm();
    }
}


text:
//
// BIM IFC library: this library works with Autodesk(R) Revit(R) to export IFC files containing model geometry.
// Copyright (C) 2012  Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.IFC;
using Revit.IFC.Common.Extensions;
using Revit.IFC.Export.Exporter;
using Revit.IFC.Export.Toolkit;

namespace Revit.IFC.Export.Utility
{
    /// <summary>
    /// Used to keep a cache of the created IfcClassifications.
    /// </summary>
    public class ClassificationCache
    {
        private IDictionary<string, IFCAnyHandle> m_ClassificationHandles = null;

        /// <summary>
        /// The map of classification names to the IfcClassification handles.
        /// </summary>
        public IDictionary<string, IFCAnyHandle> ClassificationHandles
        {
            get
            {
                if (m_ClassificationHandles == null)
                    m_ClassificationHandles = new Dictionary<string, IFCAnyHandle>();
                return m_ClassificationHandles;
            }
        }

        private IDictionary<string, IFCClassification> m_ClassificationsByName = null;

        /// <summary>
        /// The list of defined classifications, sorted by name.
        /// </summary>
        public IDictionary<string, IFCClassification> ClassificationsByName
        {
            get
            {
                if (m_ClassificationsByName == null)
                    m_ClassificationsByName = new Dictionary<string, IFCClassification>();
                return m_ClassificationsByName;
            }
        }

        private IList<string> m_CustomClassificationCodeNames = null;

        /// <summary>
        /// The names of the shared parameters used to defined custom classifications.
        /// </summary>
        public IList<string> CustomClassificationCodeNames
        {
            get
            {
                if (m_CustomClassificationCodeNames == null)
                    m_CustomClassificationCodeNames = new List<string>();
                return m_CustomClassificationCodeNames;
            }
        }

        private IDictionary<string, string> m_FieldNameToClassificationNames = null;

        /// <summary>
        /// The map of shared parameter field name to the corresponding classification name.
        /// </summary>
        public IDictionary<string, string> FieldNameToClassificationNames
        {
            get
            {
                if (m_FieldNameToClassificationNames == null)
                    m_FieldNameToClassificationNames = new Dictionary<string, string>();
                return m_FieldNameToClassificationNames;
            }
        }

        /// <summary>
        /// Create a new ClassificationCache.
        /// </summary>
        /// <param name="doc">The document.</param>
        public ClassificationCache(Document doc)
        {
            // The UI currently supports only one, but future UIs may support a list.
            IList<IFCClassification> classifications;
            if (IFCClassificationMgr.GetSavedClassifications(doc, null, out classifications))
            {
                foreach (IFCClassification classification in classifications)
                {
                    bool classificationHasName = !string.IsNullOrWhiteSpace(classification.ClassificationName);
                    if (classificationHasName)
                        ClassificationsByName[classification.ClassificationName] = classification;
                    if (!string.IsNullOrWhiteSpace(classification.ClassificationFieldName))
    {
                        string[] splitResult = classification.ClassificationFieldName.Split(new Char[] { ',', ';', '\t', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        for (int i=0; i<splitResult.Length; i++)
                        {
                            // found [<Classification Field Names>]
                            string classificationFieldName = splitResult[i].Trim();
                            CustomClassificationCodeNames.Add(classificationFieldName);
                            if (classificationHasName)
                                FieldNameToClassificationNames[classificationFieldName] = classification.ClassificationName;
                        }
                    }
                }
            }
        }
    }
}


text:
body.subordinate .navbar {
  margin-bottom: 0;
}
body.subordinate #userList {
  float: left;
  margin-top: 0px;
  border-right: 1px solid #E5E5E5;
  padding: 10px 16px 10px 0;
  height: 91%;
  width: 310px;
}
body.subordinate #userList div.title {
  padding-left: 15px;
}
body.subordinate #userList #userTree {
  margin: 0 10px 0 0;
  padding: 0;
  width: 300px;
}
body.subordinate #reports {
  float: left;
  padding-left: 30px;
  width: 65%;
}
body.subordinate #reports li.report {
  border-bottom: 1px solid #E5E5E5;
}
#reportList {
  color: #555;
}
#reportList li.report {
  border-bottom: 1px solid #E5E5E5;
  padding: 10px;
  margin-bottom: 15px;
  float: left;
  width: 100%;
}
#reportList li.report .date span {
  font-size: 18px;
  font-weight: bold;
  color: #1a700b;
  padding-left: 5px;
}
#reportList li.report .content {
  margin: 0;
  padding: 0;
}
#reportList li.report .reply,
#reportList li.report .delete {
  float: right;
  padding: 0 20px 0 0;
}
div.pageination {
  opacity: 0;
}
div.pageination div.pagetip {
  text-align: center;
  padding-top: 15px;
}
div.pageination div.aligncenter {
  text-align: center;
}


text:
from datetime import datetime

from django.test import TestCase
from django.utils import timezone

from .models import Video

VIDEO_ID = 'BJ80RsAQKqE'

class VideoTest(TestCase):
    def setUp(self):
        self.time = timezone.now()

    def test_fetch_video(self):
        v = Video.remote.fetch(VIDEO_ID)[0]

        self.assertEqual(v.video_id, VIDEO_ID)
        self.assertGreater(len(v.title), 0)
        self.assertGreater(len(v.description), 0)
        self.assertGreater(v.fetched_at, self.time)
        self.assertIsInstance(v.published_at, datetime)
        self.assertTrue(v.channel_id)

    def test_search_videos(self):

        videos = Video.remote.search('Django Unchaned Trailer')
        video = videos[0]

        self.assertEqual(len(videos), 50)
        self.assertIsInstance(video, Video)
        with self.assertRaises(Video.DoesNotExist):
            Video.objects.get(pk=video.pk)

        video.save()
        self.assertEqual(video, Video.objects.get(pk=video.pk))

class YoutubeApiTest(VideoTest):
    pass


text:
export class BindingToRemoteData {
  datasource = new kendo.data.DataSource({
    transport: {
      read: function(options) {
        return System.import('samples/chart/donut-charts/json/screen-resolution.json!json')
        .then(data => options.success(data));
      }
    },
    sort: {
      field: 'order',
      dir: 'asc'
    },
    group: {
      field: 'year'
    }
  });

  legend = {
    position: 'top'
  };

  title = {
    text: '1024x768 screen resolution trends'
  };

  seriesDefaults = {
    type: 'donut',
    startAngle: 270
  };

  series = [{
    field: 'share',
    categoryField: 'resolution',
    visibleInLegendField: 'visibleInLegend',
    padding: 10
  }];

  tooltip = {
    visible: true,
    template: '#= dataItem.resolution #: #= value #% (#= dataItem.year #)'
  }
}


text:
<?php
/**
 * Register form template
 *
 * @author Andrii Biriev
 */
defined('BEXEC')or die('No direct access!');
use Application\BRouter;
use Brilliant\CMS\BLang;
$bRouter = BRouter::getInstance();
$urlRegisterCompany = $bRouter->generateURL('users',array('view'=>'register_company','lang'=>BLang::$langcode));
?>

Registration at Financello

Register User

<a href="<?php echo $urlRegisterCompany; ?>">Register Company

		<form class="form-register" method="POST" autocomplete="off">

You are registering as a single user. After signup, you could accept invites from other companies or create own.

			<?php foreach($this->errors as $error): ?>

<?php echo $error; ?>

			<?php endforeach; ?>

				Name
				<input type="text" name="name" id="inputName" class="form-control" placeholder="Your name" required="" autofocus="" value="<?php echo $this->name; ?>" autocomplete="off">

				Email address
				<input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required="" value="<?php echo $this->email; ?>" autocomplete="off">

				Password
				<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required="" value="<?php echo $this->password; ?>" autocomplete="off">

			<input type="hidden" name="do" value="register">
			<button class="btn btn-lg btn-primary btn-block" type="submit">Create new user</button>
		</form>


text:
<?php

namespace im\users\models;

use im\users\traits\ModuleTrait;
use Yii;
use yii\authclient\ClientInterface;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "tbl_user_auth".
 *
 * @property integer $id Id
 * @property integer $user_id User id
 * @property string $provider Name of service
 * @property string $provider_id Account id
 * @property string $provider_attributes Account properties returned by social network (json encoded)
 * @property integer $created_at Created time
 * @property integer $updated_at Updated time
 *
 * @property User $user
 */
class Auth extends ActiveRecord
{
    use ModuleTrait;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%auth}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'timestampBehavior' => [
                'class' => TimestampBehavior::className()
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('auth', 'ID'),
            'user_id' => Yii::t('auth', 'User ID'),
            'provider' => Yii::t('auth', 'Provider'),
            'provider_id' => Yii::t('auth', 'Provider ID'),
            'provider_attributes' => Yii::t('auth', 'Provider attributes'),
            'create_time' => Yii::t('auth', 'Created at'),
            'update_time' => Yii::t('auth', 'Updated at')
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne($this->module->userModel, ['id' => 'user_id']);
    }

    /**
     * Finds auth by client.
     *
     * @param ClientInterface $client
     * @return static|null
     */
    public static function findByClient(ClientInterface $client)
    {
        return static::find()->where([
            'provider' => $client->getId(),
            'provider_id' => $client->getUserAttributes()['id']
        ])->one();
    }

    /**
     * Creates auth instance by from client.
     *
     * @param ClientInterface $client
     * @return static
     */
    public static function getInstance(ClientInterface $client)
    {
        return  Yii::createObject([
            'class' => static::className(),
            'provider' => $client->getId(),
            'provider_id' => $client->getUserAttributes()['id'],
            'provider_attributes' => json_encode($client->getUserAttributes())
        ]);
    }
}