text:
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
@import '../../Content/font-awesome.min.css';
@import '../../Content/bootstrap-dialog.css';
@import '../../Content/bootstrap-switch/bootstrap3/bootstrap-switch.min.css';
@import '../../Content/toastr.min.css';
@import '../../Content/bootstrap-datepicker.min.css';
@import '../../Content/bootstrap-datepicker3.min.css';
@import '../../Content/bootstrap-datetimepicker.min.css';
@import '../../Content/DataTables/css/jquery.dataTables.min.css';
@import '../../Content/DataTables/css/dataTables.bootstrap.min.css';
@import '../../Content/select2.min.css';
@import '../../Content/select2-bootstrap.css';
@import '../../Content/themes.css';

@import url('//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');

@import '../../Content/residency.css';
@import '../../Content/residency-custom-bootstrap.css';


text:
package Math::Int64;

use strict;
use warnings;

BEGIN {
    our $VERSION = '0.29';

    require XSLoader;
    XSLoader::load('Math::Int64', $VERSION);
}

use constant MAX_INT64  => string_to_int64 ( '0x7fff_ffff_ffff_ffff');
use constant MIN_INT64  => string_to_int64 ('-0x8000_0000_0000_0000');
use constant MAX_UINT64 => string_to_uint64( '0xffff_ffff_ffff_ffff');

require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(int64
                    int64_to_number
                    net_to_int64 int64_to_net
                    native_to_int64 int64_to_native
                    string_to_int64 hex_to_int64
                    BER_to_int64 int64_to_BER
                    int64_to_string int64_to_hex
                    int64_rand
                    int64_srand
                    uint64
                    uint64_to_number
                    net_to_uint64 uint64_to_net
                    native_to_uint64 uint64_to_native
                    string_to_uint64 hex_to_uint64
                    BER_to_uint64 uint64_to_BER
                    uint64_to_string uint64_to_hex
                    uint64_rand
                    BER_length
                    MAX_INT64 MIN_INT64 MAX_UINT64
                  );

my %available_pragmas = map { $_ => 1 } qw(native_if_available
                                           die_on_overflow);

sub import {
    my $pkg = shift;
    my (%pragmas, @subs, %native);
    for (@_) {
        if ($_ =~ /^:(.*)/ and $available_pragmas{$1}) {
            $pragmas{$1} = 1
        }
        else {
            push @subs, $_;
        }
    }

    if ($pragmas{die_on_overflow}) {
        require Math::Int64::die_on_overflow;
        Math::Int64::die_on_overflow->import;
    }

    if ($pragmas{native_if_available}) {
        require Math::Int64::native_if_available;
        Math::Int64::native_if_available->import;
    }

    Math::Int64->export_to_level(1, $pkg, @subs);
}

use overload ( '+' => \&_add,
               '+=' => \&_add,
               '-' => \&_sub,
               '-=' => \&_sub,
               '*' => \&_mul,
               '*=' => \&_mul,
               '**' => \&_pow,
               '**=' => \&_pow,
               '/' => \&_div,
               '/=' => \&_div,
               '%' => \&_rest,
               '%=' => \&_rest,
               'neg' => \&_neg,
               '++' => \&_inc,
               '--' => \&_dec,
               '!' => \&_not,
               '~' => \&_bnot,
               '&' => \&_and,
               '|' => \&_or,
               '^' => \&_xor,
               '<<' => \&_left,
               '>>' => \&_right,
               '<=>' => \&_spaceship,
               '>' => \&_gtn,
               '<' => \&_ltn,
               '>=' => \&_gen,
               '<=' => \&_len,
               '==' => \&_eqn,
               '!=' => \&_nen,
               'bool' => \&_bool,
               '0+' => \&_number,
               '""' => \&_string,
               '=' => \&_clone,
               fallback => 1 );

package Math::UInt64;
use overload ( '+' => \&_add,
               '+=' => \&_add,
               '-' => \&_sub,
               '-=' => \&_sub,
               '*' => \&_mul,
               '*=' => \&_mul,
               '**' => \&_pow,
               '**=' => \&_pow,
               '/' => \&_div,
               '/=' => \&_div,
               '%' => \&_rest,
               '%=' => \&_rest,
               'neg' => \&_neg,
               '++' => \&_inc,
               '--' => \&_dec,
               '!' => \&_not,
               '~' => \&_bnot,
               '&' => \&_and,
               '|' => \&_or,
               '^' => \&_xor,
               '<<' => \&_left,
               '>>' => \&_right,
               '<=>' => \&_spaceship,
               '>' => \&_gtn,
               '<' => \&_ltn,
               '>=' => \&_gen,
               '<=' => \&_len,
               '==' => \&_eqn,
               '!=' => \&_nen,
               'bool' => \&_bool,
               '0+' => \&_number,
               '""' => \&_string,
               '=' => \&_clone,
               fallback => 1 );

1;

__END__

=head1 NAME

Math::Int64 - Manipulate 64 bits integers in Perl

=head1 SYNOPSIS

  use Math::Int64 qw(int64 uint64);

  my $i = int64(1);
  my $j = $i << 40;
  print($i + $j * 1000000);

  my $k = uint64("12345678901234567890");

=head1 DESCRIPTION

This module adds support for 64 bit integers, signed and unsigned, to
Perl.

=head2 Exportable functions

=over 4

=item int64()

=item int64($value)

Creates a new int64 value and initializes it to C<$value>, where
$value can be a Perl number or a string containing a number.

For instance:

  $i = int64(34);
  $j = int64("-123454321234543212345");

  $k = int64(1234567698478483938988988); # wrong!!!
                                         #  the unquoted number would
                                         #  be converted first to a
                                         #  real number causing it to
                                         #  loose some precision.

Once the int64 number is created it can be manipulated as any other
Perl value supporting all the standard operations (addition, negation,
multiplication, postincrement, etc.).

=item net_to_int64($str)

Converts an 8 bytes string containing an int64 in network order to the
internal representation used by this module.

=item int64_to_net($int64)

Returns an 8 bytes string with the representation of the int64 value
in network order.

=item native_to_int64($str)

=item int64_to_native($int64)

similar to net_to_int64 and int64_to_net, but using the native CPU
order.

=item int64_to_number($int64)

returns the optimum representation of the int64 value using Perl
internal types (IV, UV or NV). Precision may be lost.

For instance:

  for my $l (10, 20, 30, 40, 50, 60) {
    my $i = int64(1) << $l;
    my $n = int64_to_number($i);
    print "int64:$i => perl:$n\n";
  }

=item string_to_int64($str, $base)

Converts the string to a int64 value. The conversion is done according
to the given base, which must be a number between 2 and 36 inclusive
or the special value 0. C<$base> defaults to 0.

The string may begin with an arbitrary amount of white space followed
by a single optional C<+> or C<-> sign. If base is zero or 16, the
string may then include a "0x" prefix, and the number will be read in
base 16; otherwise, a zero base is taken as 10 (decimal) unless the
next character is '0', in which case it is taken as 8 (octal).

Underscore characters (C<_>) between the digits are ignored.

No overflow checks are performed by this function unless the
C<die_on_overflow> pragma is used (see L</Die on overflow> below).

See also L<strtoll(3)>.

=item hex_to_int64($i64)

Shortcut for string_to_int64($str, 16)

=item int64_to_string($i64, $base)

Converts the int64 value to its string representation in the given
base (defaults to 10).

=item int64_to_hex($i64)

Shortcut for C<int64_to_string($i64, 16)>.

=item int64_to_BER($i64)

Converts the int64 value to its BER representation (see
L<perlfunc/pack> for a description of the BER format).

In the case of signed numbers, they are transformed into unsigned
numbers before encoding them in the BER format with the following
rule:

  $neg = ($i64 < 0 ? 1 : 0);
  $u64 = (($neg ? ~$i64 : $i64) << 1) | $neg;

That way, positive and negative integers are interleaved as 0, -1, 1,
2, -2, .... The format is similar to that used by Google protocol
buffers to encode signed varints but with the most significant groups
first (protocol buffers uses the least significant groups first
variant).

If you don't want that preprocessing for signed numbers, just use the
C<uint64_to_BER> function instead.

=item BER_to_int64($str)

Decodes the int64 number in BER format from the given string.

There must not be any extra bytes on the string after the encoded number.

=item BER_length($str)

Given a string with a BER encoded number at the beginning, this
function returns the number of bytes it uses.

The rigth way to shift a BER encoded number from the beginning of some
string is as follows:

   $i64 = BER_to_int64(substr($str, 0, BER_length($str), ''));

=item int64_rand

Generates a 64 bit random number using ISAAC-64 algorithm.

=item int64_srand($seed)

=item int64_srand()

Sets the seed for the random number generator.

C<$seed>, if given, should be a 2KB long string.

=item uint64

=item uint64_to_number

=item net_to_uint64

=item uint64_to_net

=item native_to_uint64

=item uint64_to_native

=item string_to_uint64

=item hex_to_uint64

=item uint64_to_string

=item uint64_to_hex

These functions are similar to their int64 counterparts, but
manipulate 64 bit unsigned integers.

=item uint64_to_BER($u64)

Encodes the given unsigned integer in BER format (see L<perlfunc/pack>).

=item BER_to_uint64($str)

Decodes from the given string an unsigned number in BER format.

=back

=head2 Die on overflow

The lexical pragma C<Math::Int64::die_on_overflow> configures the
module to throw an error when some operation results in integer
overflow.

For instance:

  use Math::Int64 qw(uint64);
  use Math::Int64::die_on_overflow;

  my $zero = uint64(0);
  say ($zero - 1);                 # dies as -1 falls outside
                                   # the uint64_t range

  no Math::Int64::die_on_overflow; # deactivates lexical pragma
  say ($zero - 1);                 # no error is detected here!

The pragma can also be activated as follows:

  use Math::Int64 ':die_on_overflow';

Once this pragma is used, several Math::Int64 operations may become
slower. Deactivating the pragma will not make them fast again.

On Perl 5.8.x, as lexical pragmas support is not available, the pragma
C<die_on_overflow> pragma is global and can not be deactivated.

=head2 Fallback to native 64bit support if available

If the lexical pragma C<Math::Int64::native_if_available> is used in
your program and the version of perl in use has native support for
64bit intgers, the functions imported from the module that create
64bit integers (i.e. C<uint64>, C<int64>, C<string_to_int64>,
C<native_to_int64>, etc.) will return regular perl scalars.

For instance:

  use Math::Int64 qw(int64);

  $a = int64(34); # always returns an object of the class Math::Int64

  use Math::Int64::native_if_available;
  $a = int64(34); # returns a regular scalar on perls compiled with
                  # 64bit support

This feature is not enabled by default because the semantics for perl
scalars and for 64 bit integers as implemented in this module are not
identical.

Perl is prone to coerze integers into floats while this module keeps
then always as 64bit integers. Specifically, the division operation
and overflows are the most problematic cases.

Besides that, in most situations it is safe to use the native fallback.

As happens with the C<die_on_overflow> pragma, on Perl 5.8.x it is
global.

The pragma can also be activated as follows:

  use Math::Int64 ':native_if_available';

=head2 Transparent conversion of objects to int64/uint64

When in some operation involving int64/uint64 numbers, a blessed
object is passed as an operand, the module would try to coerce the
object into an int64/uint64 number calling the methods
C<as_int64>/C<as_uint64> respectively.

If the corresponding method is not implemented, the object will be
stringified and then parsed as a base 10 number.

=head2 Storable integration

Objects of classes Math::Int64 and Math::UInt64 implement the
STORABLE_freeze and STORABLE_thaw methods for a transparent
integration with L<Storable>.

=head2 C API

This module provides a native C API that can be used to create and
read Math::Int64 int64 and uint64 SVs from your own XS modules.

In order to use it you need to follow these steps:

=over 4

=item *

Import the files C<perl_math_int64.c>, C<perl_math_int64.h> and
optionally C<typemaps> from Math::Int64 C<c_api_client> directory into
your project directory.

=item *

Include the file C<perl_math_int64.h> in the C or XS source files
where you want to convert 64bit integers to/from Perl SVs.

Note that this header file requires the types int64_t and uint64_t to
be defined beforehand.

=item *

Add the file C<perl_math_int64.c> to your compilation targets (see the
sample Makefile.PL below).

=item *

Add a call to the macro C<PERL_MATH_INT64_LOAD_OR_CROAK> into the
C<BOOT> section of your XS file.

=back

For instance:

 --- Foo64.xs ---------

  #include "EXTERN.h"
  #include "perl.h"
  #include "XSUB.h"
  #include "ppport.h"

  /* #define MATH_INT64_NATIVE_IF_AVAILABLE */
  #include "math_int64.h"

  MODULE = Foo64		PACKAGE = Foo64
  BOOT:
      PERL_MATH_INT64_LOAD_OR_CROAK;

  int64_t
  some_int64()
  CODE:
      RETVAL = -42;
  OUTPUT:
      RETVAL

  --- Makefile.PL -----

  use ExtUtils::MakeMaker;
  WriteMakefile( NAME         => 'Foo64',
                 VERSION_FROM => 'lib/Foo64.pm',
                 OBJECT       => '$(O_FILES)' );

If the macro C<MATH_INT64_NATIVE_IF_AVAILABLE> is defined before
including C<perl_math_int64.h> and the perl interpreter is compiled
with native 64bit integer support, IVs will be used to represent 64bit
integers instead of the object representation provided by Math::Int64.

These are the C macros available from Math::Int64 C API:

=over 4

=item SV *newSVi64(int64_t i64)

Returns an SV representing the given int64_t value.

=item SV *newSVu64(uint64_t 64)

Returns an SV representing the given uint64_t value.

=item int64_t SvI64(SV *sv)

Extracts the int64_t value from the given SV.

=item uint64_t SvU64(SV *sv)

Extracts the uint64_t value from the given SV.

=item int SvI64OK(SV *sv)

Returns true is the given SV contains a valid int64_t value.

=item int SvU64OK(SV *sv)

Returns true is the given SV contains a valid uint64_t value.

=item uint64_t randU64(void)

Returns a random 64 bits unsigned integer.

=back

If you require any other function available through the C API don't
hesitate to ask for it!

=head1 BUGS AND SUPPORT

The Storable integration feature is experimental.

The C API feature is experimental.

This module requires int64 support from the C compiler.

In order to report bugs you can send me and email to the address that
appears below or use the CPAN RT bugtracking system available at
L<http://rt.cpan.org>.

The source for the development version of the module is hosted at
GitHub: L<https://github.com/salva/p5-Math-Int64>.

=head2 My wishlist

If you like this module and you're feeling generous, take a look at my
Amazon Wish List: L<http://amzn.com/w/1WU1P6IR5QZ42>

=head1 SEE ALSO

The C API usage sample module L<Math::Int64::C_API::Sample>.

Other modules providing support for larger integers or numbers are
L<Math::BigInt>, L<Math::BigRat> and L<Math::Big>,
L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and
L<Math::BigInt::GMP>.

=head1 COPYRIGHT AND LICENSE

Copyright E<copy> 2007, 2009, 2011-2013 by Salvador FandiE<ntilde>o
(sfandino@yahoo.com)

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.

=cut

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>chefdash | {% block title %}Home{% endblock %}</title>
		<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename = 'style.css') }}" />

		<meta name="viewport" content="width=device-width, user-scalable=no" />
		{% block extrahead %}{% endblock %}

				{% block header %}
				{% endblock %}

				{% block body %}{% endblock %}


text:
from __future__ import annotations

import asyncio
import atexit
import copy
import logging
import math
import weakref
from contextlib import suppress
from inspect import isawaitable
from typing import TYPE_CHECKING, Any, ClassVar

from tornado import gen
from tornado.ioloop import IOLoop

import dask
from dask.utils import parse_bytes, parse_timedelta
from dask.widgets import get_template

from distributed.core import Status, rpc
from distributed.deploy.adaptive import Adaptive
from distributed.deploy.cluster import Cluster
from distributed.scheduler import Scheduler
from distributed.security import Security
from distributed.utils import NoOpAwaitable, TimeoutError, import_term, silence_logging

if TYPE_CHECKING:
    # Circular imports
    from distributed import Nanny, Worker

logger = logging.getLogger(__name__)

class ProcessInterface:
    """
    An interface for Scheduler and Worker processes for use in SpecCluster

    This interface is responsible to submit a worker or scheduler process to a
    resource manager like Kubernetes, Yarn, or SLURM/PBS/SGE/...
    It should implement the methods below, like ``start`` and ``close``
    """

    @property
    def status(self):
        return self._status

    @status.setter
    def status(self, new_status):
        if not isinstance(new_status, Status):
            raise TypeError(f"Expected Status; got {new_status!r}")
        self._status = new_status

    def __init__(self, scheduler=None, name=None):
        self.address = getattr(self, "address", None)
        self.external_address = None
        self.lock = asyncio.Lock()
        self.status = Status.created
        self._event_finished = asyncio.Event()

    def __await__(self):
        async def _():
            async with self.lock:
                if self.status == Status.created:
                    await self.start()
                    assert self.status == Status.running
            return self

        return _().__await__()

    async def start(self):
        """Submit the process to the resource manager

        For workers this doesn't have to wait until the process actually starts,
        but can return once the resource manager has the request, and will work
        to make the job exist in the future

        For the scheduler we will expect the scheduler's ``.address`` attribute
        to be available after this completes.
        """
        self.status = Status.running

    async def close(self):
        """Close the process

        This will be called by the Cluster object when we scale down a node,
        but only after we ask the Scheduler to close the worker gracefully.
        This method should kill the process a bit more forcefully and does not
        need to worry about shutting down gracefully
        """
        self.status = Status.closed
        self._event_finished.set()

    async def finished(self):
        """Wait until the server has finished"""
        await self._event_finished.wait()

    def __repr__(self):
        return f"<{dask.utils.typename(type(self))}: status={self.status.name}>"

    def _repr_html_(self):
        return get_template("process_interface.html.j2").render(process_interface=self)

    async def __aenter__(self):
        await self
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        await self.close()

class SpecCluster(Cluster):
    """Cluster that requires a full specification of workers

    The SpecCluster class expects a full specification of the Scheduler and
    Workers to use.  It removes any handling of user inputs (like threads vs
    processes, number of cores, and so on) and any handling of cluster resource
    managers (like pods, jobs, and so on).  Instead, it expects this
    information to be passed in scheduler and worker specifications.  This
    class does handle all of the logic around asynchronously cleanly setting up
    and tearing things down at the right times.  Hopefully it can form a base
    for other more user-centric classes.

    Parameters
    ----------
    workers: dict
        A dictionary mapping names to worker classes and their specifications
        See example below
    scheduler: dict, optional
        A similar mapping for a scheduler
    worker: dict
        A specification of a single worker.
        This is used for any new workers that are created.
    asynchronous: bool
        If this is intended to be used directly within an event loop with
        async/await
    silence_logs: bool
        Whether or not we should silence logging when setting up the cluster.
    name: str, optional
        A name to use when printing out the cluster, defaults to type name

    Examples
    --------
    To create a SpecCluster you specify how to set up a Scheduler and Workers

    >>> from dask.distributed import Scheduler, Worker, Nanny
    >>> scheduler = {'cls': Scheduler, 'options': {"dashboard_address": ':8787'}}
    >>> workers = {
    ...     'my-worker': {"cls": Worker, "options": {"nthreads": 1}},
    ...     'my-nanny': {"cls": Nanny, "options": {"nthreads": 2}},
    ... }
    >>> cluster = SpecCluster(scheduler=scheduler, workers=workers)

    The worker spec is stored as the ``.worker_spec`` attribute

    >>> cluster.worker_spec
    {
       'my-worker': {"cls": Worker, "options": {"nthreads": 1}},
       'my-nanny': {"cls": Nanny, "options": {"nthreads": 2}},
    }

    While the instantiation of this spec is stored in the ``.workers``
    attribute

    >>> cluster.workers
    {
        'my-worker': <Worker ...>
        'my-nanny': <Nanny ...>
    }

    Should the spec change, we can await the cluster or call the
    ``._correct_state`` method to align the actual state to the specified
    state.

    We can also ``.scale(...)`` the cluster, which adds new workers of a given
    form.

    >>> worker = {'cls': Worker, 'options': {}}
    >>> cluster = SpecCluster(scheduler=scheduler, worker=worker)
    >>> cluster.worker_spec
    {}

    >>> cluster.scale(3)
    >>> cluster.worker_spec
    {
        0: {'cls': Worker, 'options': {}},
        1: {'cls': Worker, 'options': {}},
        2: {'cls': Worker, 'options': {}},
    }

    Note that above we are using the standard ``Worker`` and ``Nanny`` classes,
    however in practice other classes could be used that handle resource
    management like ``KubernetesPod`` or ``SLURMJob``.  The spec does not need
    to conform to the expectations of the standard Dask Worker class.  It just
    needs to be called with the provided options, support ``__await__`` and
    ``close`` methods and the ``worker_address`` property..

    Also note that uniformity of the specification is not required.  Other API
    could be added externally (in subclasses) that adds workers of different
    specifications into the same dictionary.

    If a single entry in the spec will generate multiple dask workers then
    please provide a `"group"` element to the spec, that includes the suffixes
    that will be added to each name (this should be handled by your worker
    class).

    >>> cluster.worker_spec
    {
        0: {"cls": MultiWorker, "options": {"processes": 3}, "group": ["-0", "-1", -2"]}
        1: {"cls": MultiWorker, "options": {"processes": 2}, "group": ["-0", "-1"]}
    }

    These suffixes should correspond to the names used by the workers when
    they deploy.

    >>> [ws.name for ws in cluster.scheduler.workers.values()]
    ["0-0", "0-1", "0-2", "1-0", "1-1"]
    """

    _instances: ClassVar[weakref.WeakSet[SpecCluster]] = weakref.WeakSet()

    def __init__(
        self,
        workers=None,
        scheduler=None,
        worker=None,
        asynchronous=False,
        loop=None,
        security=None,
        silence_logs=False,
        name=None,
        shutdown_on_close=True,
        scheduler_sync_interval=1,
    ):
        if loop is None and asynchronous:
            loop = IOLoop.current()

        self._created = weakref.WeakSet()

        self.scheduler_spec = copy.copy(scheduler)
        self.worker_spec = copy.copy(workers) or {}
        self.new_spec = copy.copy(worker)
        self.scheduler = None
        self.workers = {}
        self._i = 0
        self.security = security or Security()
        self._futures = set()

        if silence_logs:
            self._old_logging_level = silence_logging(level=silence_logs)
            self._old_bokeh_logging_level = silence_logging(
                level=silence_logs, root="bokeh"
            )

        self._instances.add(self)
        self._correct_state_waiting = None
        self._name = name or type(self).__name__
        self.shutdown_on_close = shutdown_on_close

        super().__init__(
            asynchronous=asynchronous,
            loop=loop,
            name=name,
            scheduler_sync_interval=scheduler_sync_interval,
        )

        try:
            called_from_running_loop = (
                getattr(loop, "asyncio_loop", None) is asyncio.get_running_loop()
            )
        except RuntimeError:
            called_from_running_loop = asynchronous

        if not called_from_running_loop:
            self._loop_runner.start()
            self.sync(self._start)
            try:
                self.sync(self._correct_state)
            except Exception:
                self.sync(self.close)
                raise

    async def _start(self):
        while self.status == Status.starting:
            await asyncio.sleep(0.01)
        if self.status == Status.running:
            return
        if self.status == Status.closed:
            raise ValueError("Cluster is closed")

        self._lock = asyncio.Lock()
        self.status = Status.starting

        if self.scheduler_spec is None:
            try:
                import distributed.dashboard  # noqa: F401
            except ImportError:
                pass
            else:
                options = {"dashboard": True}
            self.scheduler_spec = {"cls": Scheduler, "options": options}

        try:
            # Check if scheduler has already been created by a subclass
            if self.scheduler is None:
                cls = self.scheduler_spec["cls"]
                if isinstance(cls, str):
                    cls = import_term(cls)
                self.scheduler = cls(**self.scheduler_spec.get("options", {}))
                self.scheduler = await self.scheduler
            self.scheduler_comm = rpc(
                getattr(self.scheduler, "external_address", None)
                or self.scheduler.address,
                connection_args=self.security.get_connection_args("client"),
            )
            await super()._start()
        except Exception as e:  # pragma: no cover
            self.status = Status.failed
            await self._close()
            raise RuntimeError(f"Cluster failed to start: {e}") from e

    def _correct_state(self):
        if self._correct_state_waiting:
            # If people call this frequently, we only want to run it once
            return self._correct_state_waiting
        else:
            task = asyncio.ensure_future(self._correct_state_internal())
            self._correct_state_waiting = task
            return task

    async def _correct_state_internal(self):
        async with self._lock:
            self._correct_state_waiting = None

            to_close = set(self.workers) - set(self.worker_spec)
            if to_close:
                if self.scheduler.status == Status.running:
                    await self.scheduler_comm.retire_workers(workers=list(to_close))
                tasks = [
                    asyncio.create_task(self.workers[w].close())
                    for w in to_close
                    if w in self.workers
                ]
                await asyncio.gather(*tasks)
            for name in to_close:
                if name in self.workers:
                    del self.workers[name]

            to_open = set(self.worker_spec) - set(self.workers)
            workers = []
            for name in to_open:
                d = self.worker_spec[name]
                cls, opts = d["cls"], d.get("options", {})
                if "name" not in opts:
                    opts = opts.copy()
                    opts["name"] = name
                if isinstance(cls, str):
                    cls = import_term(cls)
                worker = cls(
                    getattr(self.scheduler, "contact_address", None)
                    or self.scheduler.address,
                    **opts,
                )
                self._created.add(worker)
                workers.append(worker)
            if workers:
                await asyncio.wait(workers)
                for w in workers:
                    w._cluster = weakref.ref(self)
                    await w  # for tornado gen.coroutine support
            self.workers.update(dict(zip(to_open, workers)))

    def _update_worker_status(self, op, msg):
        if op == "remove":
            name = self.scheduler_info["workers"][msg]["name"]

            def f():
                if (
                    name in self.workers
                    and msg not in self.scheduler_info["workers"]
                    and not any(
                        d["name"] == name
                        for d in self.scheduler_info["workers"].values()
                    )
                ):
                    self._futures.add(asyncio.ensure_future(self.workers[name].close()))
                    del self.workers[name]

            delay = parse_timedelta(
                dask.config.get("distributed.deploy.lost-worker-timeout")
            )

            asyncio.get_running_loop().call_later(delay, f)
        super()._update_worker_status(op, msg)

    def __await__(self):
        async def _():
            if self.status == Status.created:
                await self._start()
            await self.scheduler
            await self._correct_state()
            if self.workers:
                await asyncio.wait(list(self.workers.values()))  # maybe there are more
            return self

        return _().__await__()

    async def _close(self):
        while self.status == Status.closing:
            await asyncio.sleep(0.1)
        if self.status == Status.closed:
            return
        if self.status == Status.running or self.status == Status.failed:
            self.status = Status.closing

            # Need to call stop here before we close all servers to avoid having
            # dangling tasks in the ioloop
            with suppress(AttributeError):
                self._adaptive.stop()

            f = self.scale(0)
            if isawaitable(f):
                await f
            await self._correct_state()
            await asyncio.gather(*self._futures)

            if self.scheduler_comm:
                async with self._lock:
                    with suppress(OSError):
                        await self.scheduler_comm.terminate()
                    await self.scheduler_comm.close_rpc()
            else:
                logger.warning("Cluster closed without starting up")

            if self.scheduler:
                await self.scheduler.close()
            for w in self._created:
                assert w.status in {
                    Status.closing,
                    Status.closed,
                    Status.failed,
                }, w.status

        if hasattr(self, "_old_logging_level"):
            silence_logging(self._old_logging_level)
        if hasattr(self, "_old_bokeh_logging_level"):
            silence_logging(self._old_bokeh_logging_level, root="bokeh")

        await super()._close()

    async def __aenter__(self):
        await self
        await self._correct_state()
        assert self.status == Status.running
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        super().__exit__(exc_type, exc_value, traceback)
        self._loop_runner.stop()

    def _threads_per_worker(self) -> int:
        """Return the number of threads per worker for new workers"""
        if not self.new_spec:  # pragma: no cover
            raise ValueError("To scale by cores= you must specify cores per worker")

        for name in ["nthreads", "ncores", "threads", "cores"]:
            with suppress(KeyError):
                return self.new_spec["options"][name]
        raise RuntimeError("unreachable")

    def _memory_per_worker(self) -> int:
        """Return the memory limit per worker for new workers"""
        if not self.new_spec:  # pragma: no cover
            raise ValueError(
                "to scale by memory= your worker definition must include a "
                "memory_limit definition"
            )

        for name in ["memory_limit", "memory"]:
            with suppress(KeyError):
                return parse_bytes(self.new_spec["options"][name])

        raise ValueError(
            "to use scale(memory=...) your worker definition must include a "
            "memory_limit definition"
        )

    def scale(self, n=0, memory=None, cores=None):
        if memory is not None:
            n = max(n, int(math.ceil(parse_bytes(memory) / self._memory_per_worker())))

        if cores is not None:
            n = max(n, int(math.ceil(cores / self._threads_per_worker())))

        if len(self.worker_spec) > n:
            not_yet_launched = set(self.worker_spec) - {
                v["name"] for v in self.scheduler_info["workers"].values()
            }
            while len(self.worker_spec) > n and not_yet_launched:
                del self.worker_spec[not_yet_launched.pop()]

        while len(self.worker_spec) > n:
            self.worker_spec.popitem()

        if self.status not in (Status.closing, Status.closed):
            while len(self.worker_spec) < n:
                self.worker_spec.update(self.new_worker_spec())

        self.loop.add_callback(self._correct_state)

        if self.asynchronous:
            return NoOpAwaitable()

    def _new_worker_name(self, worker_number):
        """Returns new worker name.

        This can be overridden in SpecCluster derived classes to customise the
        worker names.
        """
        return worker_number

    def new_worker_spec(self):
        """Return name and spec for the next worker

        Returns
        -------
        d: dict mapping names to worker specs

        See Also
        --------
        scale
        """
        new_worker_name = self._new_worker_name(self._i)
        while new_worker_name in self.worker_spec:
            self._i += 1
            new_worker_name = self._new_worker_name(self._i)

        return {new_worker_name: self.new_spec}

    @property
    def _supports_scaling(self):
        return bool(self.new_spec)

    async def scale_down(self, workers):
        # We may have groups, if so, map worker addresses to job names
        if not all(w in self.worker_spec for w in workers):
            mapping = {}
            for name, spec in self.worker_spec.items():
                if "group" in spec:
                    for suffix in spec["group"]:
                        mapping[str(name) + suffix] = name
                else:
                    mapping[name] = name

            workers = {mapping.get(w, w) for w in workers}

        for w in workers:
            if w in self.worker_spec:
                del self.worker_spec[w]
        await self

    scale_up = scale  # backwards compatibility

    @property
    def plan(self):
        out = set()
        for name, spec in self.worker_spec.items():
            if "group" in spec:
                out.update({str(name) + suffix for suffix in spec["group"]})
            else:
                out.add(name)
        return out

    @property
    def requested(self):
        out = set()
        for name in self.workers:
            try:
                spec = self.worker_spec[name]
            except KeyError:
                continue
            if "group" in spec:
                out.update({str(name) + suffix for suffix in spec["group"]})
            else:
                out.add(name)
        return out

    def adapt(
        self,
        Adaptive: type[Adaptive] = Adaptive,
        minimum: float = 0,
        maximum: float = math.inf,
        minimum_cores: int | None = None,
        maximum_cores: int | None = None,
        minimum_memory: str | None = None,
        maximum_memory: str | None = None,
        **kwargs: Any,
    ) -> Adaptive:
        """Turn on adaptivity

        This scales Dask clusters automatically based on scheduler activity.

        Parameters
        ----------
        minimum : int
            Minimum number of workers
        maximum : int
            Maximum number of workers
        minimum_cores : int
            Minimum number of cores/threads to keep around in the cluster
        maximum_cores : int
            Maximum number of cores/threads to keep around in the cluster
        minimum_memory : str
            Minimum amount of memory to keep around in the cluster
            Expressed as a string like "100 GiB"
        maximum_memory : str
            Maximum amount of memory to keep around in the cluster
            Expressed as a string like "100 GiB"

        Examples
        --------
        >>> cluster.adapt(minimum=0, maximum_memory="100 GiB", interval='500ms')

        See Also
        --------
        dask.distributed.Adaptive : for more keyword arguments
        """
        if minimum_cores is not None:
            minimum = max(
                minimum or 0, math.ceil(minimum_cores / self._threads_per_worker())
            )
        if minimum_memory is not None:
            minimum = max(
                minimum or 0,
                math.ceil(parse_bytes(minimum_memory) / self._memory_per_worker()),
            )
        if maximum_cores is not None:
            maximum = min(
                maximum, math.floor(maximum_cores / self._threads_per_worker())
            )
        if maximum_memory is not None:
            maximum = min(
                maximum,
                math.floor(parse_bytes(maximum_memory) / self._memory_per_worker()),
            )

        return super().adapt(
            Adaptive=Adaptive, minimum=minimum, maximum=maximum, **kwargs
        )

    @classmethod
    def from_name(cls, name: str) -> ProcessInterface:
        """Create an instance of this class to represent an existing cluster by name."""
        raise NotImplementedError()

async def run_spec(spec: dict[str, Any], *args: Any) -> dict[str, Worker | Nanny]:
    workers = {}
    for k, d in spec.items():
        cls = d["cls"]
        if isinstance(cls, str):
            cls = import_term(cls)
        workers[k] = cls(*args, **d.get("opts", {}))

    if workers:
        await asyncio.gather(*workers.values())
        for w in workers.values():
            await w  # for tornado gen.coroutine support
    return workers

@atexit.register
def close_clusters():
    for cluster in list(SpecCluster._instances):
        if getattr(cluster, "shutdown_on_close", False):
            with suppress(gen.TimeoutError, TimeoutError):
                if getattr(cluster, "status", Status.closed) != Status.closed:
                    cluster.close(timeout=10)


text:
<?php
/**
 * Created by PhpStorm.
 * User: sumit
 * Date: 11/6/13
 * Time: 1:37 PM
 */

namespace elevate\test\HVObjects\Thing\DataXML\Type;

use elevate\HVObjects\Thing\DataXML\Type\DeviceType;
use elevate\test\HVObjects\BaseObjectTest;
use elevate\HVObjects\Generic\Date\Date;
use elevate\HVObjects\Generic\Date\Time;
use elevate\HVObjects\Generic\Date\DateTime;
use elevate\HVObjects\Generic\CodedValue;
use elevate\HVObjects\Generic\CodableValue;
use elevate\HVObjects\Generic\Name;
use elevate\HVObjects\Generic\Address;
use elevate\HVObjects\Generic\Phone;
use elevate\HVObjects\Generic\Email;
use elevate\HVObjects\Generic\Contact;
use elevate\HVObjects\Generic\Person;
use elevate\HVObjects\Generic\AppointmentExtension;
use elevate\HVObjects\Generic\Recurrent;

/*

class AppointmentExtensionTest extends BaseObjectTest
{
    public static function setUpBeforeClass()
    {
        self::$sampleXMLPath = __DIR__ . '/../SampleXML/Generic/AppointmentExtension.xml';
        self::$objectNamespace = 'elevate\HVObjects\Generic\AppointmentExtension';

        $dateTime = '2013-12-15T00:06:21+00:00';
        $recurrentThing = new Recurrent( $dateTime, 'mon' );
        $apptExtension = new AppointmentExtension('Mentis Unit Test', $recurrentThing);

        self::$testObject = $apptExtension;
        parent::setUpBeforeClass();

    }

} */


text:
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
    // [START dialogflow_v3_generated_Deployments_ListDeployments_async]
    using Google.Api.Gax;
    using Google.Cloud.Dialogflow.Cx.V3;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedDeploymentsClientSnippets
    {
        /// <summary>Snippet for ListDeploymentsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ListDeploymentsRequestObjectAsync()
        {
            // Create client
            DeploymentsClient deploymentsClient = await DeploymentsClient.CreateAsync();
            // Initialize request argument(s)
            ListDeploymentsRequest request = new ListDeploymentsRequest
            {
                ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"),
            };
            // Make the request
            PagedAsyncEnumerable<ListDeploymentsResponse, Deployment> response = deploymentsClient.ListDeploymentsAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Deployment item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListDeploymentsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Deployment item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<Deployment> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (Deployment item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END dialogflow_v3_generated_Deployments_ListDeployments_async]
}


text:
<?php

use DreamFactory\Platform\Resources\User\Session;
use DreamFactory\Platform\Yii\Components\PlatformUserIdentity;

/**
 * LoginForm class.
 * LoginForm is the data structure for keeping user login form data.
 * It is used by the 'login' action of 'WebController'.
 */
class LoginForm extends CFormModel
{
	//*************************************************************************
	//	Constants
	//*************************************************************************

	/**
	 * @var string The faux-attribute to hold any authentication errors
	 */
	const ERROR_ATTRIBUTE = 'Authentication';
	/**
	 * @var string The standard authentication error message
	 */
	const ERROR_MESSAGE = 'Invalid user name and password combination.';

	//*************************************************************************
	//	Members
	//*************************************************************************

	/**
	 * @var string
	 */
	public $username;
	/**
	 * @var string
	 */
	public $password;
	/**
	 * @var boolean
	 */
	public $rememberMe = false;

	//*************************************************************************
	//	Methods
	//*************************************************************************

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			array( 'username, password', 'required' ),
			array( 'rememberMe', 'boolean' ),
			array( 'password', 'authenticate' ),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'username'   => 'Email Address',
			'password'   => 'Password',
			'rememberMe' => 'Keep me logged in',
		);
	}

	/**
	 * Authenticates the password.
	 * This is the 'authenticate' validator as declared in rules().
	 */
	public function authenticate( $attribute, $params )
	{
		if ( !$this->hasErrors() )
		{
			try
			{
				$_duration = $this->rememberMe ? 3600 * 24 * 30 : 0;
				/** @var PlatformUserIdentity $_identity */
				if ( Session::userLogin( $this->username, $this->password, $_duration, false ) )
				{
					return true;
				}

				$this->addError( static::ERROR_ATTRIBUTE, static::ERROR_MESSAGE );
			}
			catch ( \Exception $_ex )
			{
				$this->addError( static::ERROR_ATTRIBUTE, $_ex->getMessage() );
			}

		}

		return false;
	}
}


text:
package org.jbpm.designer.expressioneditor.marshalling;

public interface ExpressionEditorMessageTokens {

    static final String OPERATOR_TOKEN = "operator";
    static final String CONDITION_TOKEN = "condition";
    static final String CONDITIONS_TOKEN = "conditions";
    static final String PARAMETERS_TOKEN = "parameters";
    static final String SCRIPT_TOKEN = "script";
    static final String ERROR_CODE_TOKEN = "errorCode";
    static final String ERROR_MESSAGE_TOKEN = "errorMessage";
}


text:
from __future__ import unicode_literals

import frappe
import unittest

class TestGSuiteTemplates(unittest.TestCase):
	pass


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace BGE.Scenarios
{
	public class Opening_Scenario : Scenario
	{
		List<GameObject> prefabList = new List<GameObject>();

		public override string Description()
		{
			return "Opening Scene";
		}

		public override void Start()
		{
			Params.Load("default.txt");
			float range = Params.GetFloat("world_range");

			leader = CreateBoid(new Vector3(0, 0, 0), leaderPrefab);
			leader.GetComponent<SteeringBehaviours>().SeekEnabled = true;
			leader.GetComponent<SteeringBehaviours>().ObstacleAvoidanceEnabled = true;
			leader.GetComponent<SteeringBehaviours>().PlaneAvoidanceEnabled = true;
			leader.GetComponent<SteeringBehaviours>().seekTargetPos = new Vector3(-1000, 0, 1000);
			leader.AddComponent<MeshCollider> ();
			leader.AddComponent<MeshRenderer> ();
			leader.AddComponent<Rigidbody> ();
			leader.rigidbody.useGravity = false;
			leader.tag = "leader";
			leader.rigidbody.velocity = new Vector3 (-10 ,0,10);

			GameObject camFollower;
			camFollower = CreateCamFollower(leader, new Vector3(0.85415f ,40f, 180.08089f));
			// Create the boids
			GameObject fleet = null;

			for (int i = 0; i < Params.GetInt("num_tauri"); i++)
			{
				int j = 2;
				if(i % 2 == 0)
				{
					j = -j;
				}
				else
				{
					j = Math.Abs(j);
				}

				Vector3 offset = new Vector3(60 * j,0,60 * j);
				Vector3 pos = leader.transform.position + offset;
				fleet = CreateBoid(pos, tauriPrefab);
				fleet.GetComponent<SteeringBehaviours>().leader = leader;
				fleet.GetComponent<SteeringBehaviours>().offset = new Vector3(j * 30,j * 2, 0);
				fleet.GetComponent<SteeringBehaviours>().ObstacleAvoidanceEnabled = true;
				fleet.GetComponent<SteeringBehaviours>().seekTargetPos = new Vector3(-1000, 0, 1000);
				fleet.GetComponent<SteeringBehaviours>().OffsetPursuitEnabled = true;
				fleet.GetComponent<SteeringBehaviours>().SeparationEnabled = true;
				fleet.GetComponent<SteeringBehaviours>().PlaneAvoidanceEnabled = true;
				fleet.AddComponent<Rigidbody> ();
				fleet.rigidbody.useGravity = false;
				fleet.rigidbody.velocity = new Vector3 (-10 ,0,10);
			}

			prefabList.Add (wraithPrefab);
			prefabList.Add (gliderPrefab);
			prefabList.Add (asauranPrefab);

			int prefabIndex;
			// Now make a fleet
			int fleetSize = 8;
			float xOff = 90;
			float zOff = -90;
			for (int i = 2; i < fleetSize; i++)
			{
				for (int j = 0; j < i; j++)
				{
					prefabIndex = UnityEngine.Random.Range(0,3);

					float z = (i - 1) * zOff;
					Vector3 offset = new Vector3((xOff * (-i / 2.0f)) + (j * xOff), UnityEngine.Random.Range(-50,50), z);
					fleet = CreateBoid(new Vector3(-800,90,1000) + offset, prefabList[prefabIndex]);
					fleet.AddComponent<Rigidbody> ();
					fleet.rigidbody.useGravity = false;
				}
			}
			GroundEnabled(true);
		}

		public override void Update()
		{
		}
	}
}


text:
{% extends 'backend/layout.twig.php' %}
{% block title %}ChassisPHP Login{% endblock %}
{% block content %}

    {% if message.content is defined %}

        {{ message.content }}

    {% endif %}

Reset Password

    <form action="/backend/forgot" method="post">

          Email
          <input name="email" placeholder="email" class="input-control"{% if formVars.email is defined %} value="{{ formVars.email }}"{% endif %} />

          <button type="submit">Continue</button>
          Cancel

        {% if message.content == 'Could not reset your password, please contact support' %}
        Contact Support
        {% endif %}
    </form>

{% endblock %}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace Dnn.PersonaBar.ConfigConsole.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using Dnn.PersonaBar.ConfigConsole.Components;
    using DotNetNuke.Abstractions;
    using DotNetNuke.Abstractions.Application;
    using DotNetNuke.Common;
    using Microsoft.Extensions.DependencyInjection;
    using Moq;
    using NUnit.Framework;

    /// <summary>
    /// <see cref="ConfigConsoleController"/> unit tests.
    /// </summary>
    [TestFixture]
    public class ConfigConsoleControllerTests
    {
        private const string GoodConfigXml = "<configuration></configuration>";
        private const string BadConfigXml = "<configuration1></configuration1>";
        private const string BadXml = "<configuration></configuration1>";

        /// <summary>
        /// Method that is called immediately before each test is run.
        /// </summary>
        [SetUp]
        public static void Setup()
        {
            var applicationStatusInfoMock = new Mock<IApplicationStatusInfo>();

            applicationStatusInfoMock
                .Setup(info => info.ApplicationMapPath)
                .Returns(Environment.CurrentDirectory);

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddTransient(container => applicationStatusInfoMock.Object);
            serviceCollection.AddTransient(container => Mock.Of<INavigationManager>());

            Globals.DependencyProvider = serviceCollection.BuildServiceProvider();
        }

        /// <summary>
        /// Unit test for <see cref="ConfigConsoleController.ValidateConfigFile(string, string)"/>.
        /// </summary>
        /// <param name="fileName">File name to test.</param>
        /// <param name="fileContent">File content to test.</param>
        /// <param name="expectedErrorCount">Expected number of validation errors.</param>
        /// <param name="shouldThrow">Whether the method should throw an exception or not.</param>
        [Test]
        [TestCase(ConfigConsoleController.WebConfig, GoodConfigXml, 0, false)]
        [TestCase(ConfigConsoleController.WebConfig, BadConfigXml, 1, false)]
        [TestCase(ConfigConsoleController.WebConfig, BadXml, 0, true)]
        [TestCase("Random.config", GoodConfigXml, 0, false)]
        [TestCase("Random.config", BadConfigXml, 0, false)]
        [TestCase("Random.config", BadXml, 0, false)]
        [TestCase("Random.file", "Random content", 0, false)]

        public void ValidateConfigFile(string fileName, string fileContent, int expectedErrorCount, bool shouldThrow)
        {
            // arrange
            var sut = new ConfigConsoleController();

            Exception exception = null;
            IEnumerable<string> errors = new string[0];

            // act
            try
            {
                errors = sut.ValidateConfigFile(fileName, fileContent);
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            // assert
            Assert.AreEqual(shouldThrow, exception != null);
            Assert.AreEqual(expectedErrorCount, errors.Count());
        }
    }
}


text:
"""Defines gsutil-supported credential types."""

from __future__ import absolute_import

class CredTypes(object):
  HMAC = "HMAC"
  OAUTH2_SERVICE_ACCOUNT = "OAuth 2.0 Service Account"
  OAUTH2_USER_ACCOUNT = "Oauth 2.0 User Account"
  GCE = "GCE"
  DEVSHELL = "Google Developer Shell"


text:
require 'spec_helper'

RSpec.describe DiscordDistanceCalculator::MessageHandler do
  let(:message) { "!distance 32084 04101 km" }
  let(:any_old_message) { "lorem ipsum" }
  let(:locations) { ["32084", "04101"] }
  let(:distance) { 1130 }
  let(:handler) { DiscordDistanceCalculator::MessageHandler.new(message) }
  let(:second_handler) { DiscordDistanceCalculator::MessageHandler.new(any_old_message) }

  context "when message is received with distance command" do
    it "finds distance command in message" do
      expect(handler.has_command?).to eq(true)
    end

    it "finds locations in message" do
      expect(handler.get_locations).to eq(locations)
    end

    it "uses DistanceCalculator object to calculate distance between objects" do
      expect(handler.distance_calculator).to be_within(5).of(distance)
    end

    it "finds kilometers parameter in message" do
      expect(handler.has_km?).to eq(true)
    end
  end

  context "when any old message is received" do
    it "examines message for distance command" do
      expect(second_handler.has_command?).to eq(false)
    end
  end
end


text:
/*	$NetBSD: hunt_private.h,v 1.9 2014/03/30 05:30:28 dholland Exp $	*/

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

#include <stdbool.h>
#include <stdio.h> /* for BUFSIZ */

#ifdef INTERNET
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <net/if.h>
#else
#include <sys/un.h>
#endif

/*
 * external variables
 */

extern bool Last_player;

extern char Buf[BUFSIZ];
extern int huntsocket;

#ifdef INTERNET
extern char *Send_message;
#endif

#ifdef MONITOR
extern bool Am_monitor;
#endif

extern char map_key[256];
extern bool no_beep;

#ifdef INTERNET
/* XXX this had to be made public to split off server.c; fix it up */
extern SOCKET Daemon;
#endif

/*
 * function types
 */

/* in connect.c */
void do_connect(const char *, size_t, char, int32_t);

/* in hunt.c */
__dead void bad_con(void);
__dead void bad_ver(void);
__dead __printflike(2, 3) void leave(int, const char *, ...);
__dead __printflike(2, 3) void leavex(int, const char *, ...);
void intr(int);

/* in otto.c */
void otto(int, int, char);

/* in playit.c */
void playit(void);
int quit(int);
void clear_the_screen(void);
void do_message(void);

/* in server.c */
#ifdef INTERNET
void serverlist_setup(const char *, uint16_t);
void serverlist_query(unsigned short msg);
unsigned serverlist_num(void);
const struct sockaddr_storage *serverlist_gethost(unsigned, socklen_t *);
unsigned short serverlist_getresponse(unsigned);
#endif


text:
typedef std::pair<int, int> piece;
#define state int

class NFA
{
public:
	NFA();
	~NFA();
	void build(std::string postfix);

	struct Link {
		state to;
		char c;
		Link(int _to, char _c) : to(_to), c(_c)
		{}
	};

	std::vector <state> move(std::vector <state> &fromStates, char c);
	std::vector <state> moveWithoutEpsilons(std::vector <state> &fromStates);
	state getStartState() {
		return startState;
	}
	state getFinalState() {
		return finalState;
	}

protected:
	std::vector <state> justMove(std::vector <state> &fromStates, char c);
	std::stack<int> renumbering;
	piece buildOr(piece a, piece b);
	piece buildConcat(piece a, piece b);
	piece buildSymbol(char c);
	piece buildKleeneÑlosure(piece a);
	state buildInit();
	piece buildEpsilon();

private:
	std::vector<std::vector <Link> > states;
	state startState;
	state finalState;

};


text:
var hsCrud = angular.module('hsCrud', ['restangular'])
    .run(['Restangular', function (restangular) {
        restangular.setRequestSuffix('.json');

        restangular.setRestangularFields({
            id: "EntityId"
        });

        restangular.setRequestInterceptor(function (elem, operation) {
            //console.log('operation ' + operation);
            if (operation === "delete" || operation === "remove") {
                return undefined;
            }
            return elem;
        });
    }])
    .provider('basicCrud', ['RestangularProvider', function (restangularProvider) {

        var self = this;
        this.restObjects = [];
        this.$get = ['Restangular', function (restangular) {
            return {
                loadOne: function (ofType, entityId) {
                    var onePromise = restangular.one(ofType, entityId);
                    var restObj = { 'typeName': ofType, 'onePromise': onePromise, 'result': onePromise.get() };

                    return restObj;
                },
                loadList: function (ofType, queryParams) {
                    var allPromise = restangular.all(ofType);
                    var restObj = { 'typeName': ofType, 'allPromise': allPromise, 'resultList': allPromise.getList(queryParams) };

                    return restObj;
                },
                create: function (ofType, object) {
                    return restangular.all(ofType).post(object);
                },
                putList: function (listPromise, updatedObj) {
                    console.log('putting', updatedObj);
                    return listPromise.put(updatedObj);
                },
                /*
                    Return a promise for item deletion which will be resolved after the response is gotten from the server.
                */
                deleteItem: function (restItem) {
                    return restItem.customDELETE('');
                },
                setBaseUrl: function (baseUrl) {
                    console.log('setBaseUrl ' + baseUrl);
                    restangularProvider.setBaseUrl(baseUrl);
                },
                //Takes handler in form of function (response, operation, what, url)
                setResponseExtractor: function (handlerCallback) {
                    restangularProvider.setResponseExtractor(handlerCallback);
                }
            };
        }];
    }]);


text:
package konoha.syntax;

import java.lang.reflect.Type;
import java.util.regex.Pattern;

import konoha.script.ScriptContext;
import konoha.script.SyntaxTree;

public class RegExp extends SyntaxExtension {

	public static void hack(ScriptContext context) {
		context.addSyntaxExtension(new RegExp(context));
	}

	public RegExp(ScriptContext context) {
		super(context);
	}

	@Override
	public String getName() {
		return "RegExp";
	}

	@Override
	public Type acceptType(SyntaxTree node) {
		String regExp = node.toText();
		regExp = regExp.substring(1, regExp.length() - 1);
		Pattern p = Pattern.compile(regExp);
		return node.setConst(Pattern.class, p);
	}

	@Override
	public Object acceptEval(SyntaxTree node) {
		return node.getValue();
	}

}


text:
XListViewSharp
==============

A C#/Xamarin.Android port of XListView from Java.

Abandoned, I ended up using an infinite list instead.

Original https://github.com/Maxwin-z/XListView-Android


text:
package com.reason.lang.core.psi.impl;

import com.intellij.navigation.ItemPresentation;
import com.intellij.psi.NavigatablePsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.psi.impl.source.tree.CompositePsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.IncorrectOperationException;
import com.reason.lang.core.ORUtil;
import com.reason.lang.core.psi.PsiSignature;
import com.reason.lang.core.psi.PsiStructuredElement;
import icons.ORIcons;
import javax.swing.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class PsiClassMethod extends CompositePsiElement
    implements NavigatablePsiElement, PsiNameIdentifierOwner, PsiStructuredElement {

  protected PsiClassMethod(IElementType type) {
    super(type);
  }

  @Nullable
  @Override
  public PsiElement getNameIdentifier() {
    return ORUtil.findImmediateFirstChildOfClass(this, PsiLowerIdentifier.class);
  }

  @Override
  public String getName() {
    PsiElement nameIdentifier = getNameIdentifier();
    return nameIdentifier == null ? "" : nameIdentifier.getText();
  }

  @Nullable
  @Override
  public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
    return null;
  }

  @Nullable
  public PsiSignature getSignature() {
    return ORUtil.findImmediateFirstChildOfClass(this, PsiSignature.class);
  }

  public ItemPresentation getPresentation() {
    return new ItemPresentation() {
      @Nullable
      @Override
      public String getPresentableText() {
        return getName();
      }

      @Nullable
      @Override
      public String getLocationString() {
        PsiSignature signature = getSignature();
        return signature == null ? null : signature.getText();
      }

      @NotNull
      @Override
      public Icon getIcon(boolean unused) {
        return ORIcons.METHOD;
      }
    };
  }

  @Nullable
  @Override
  public String toString() {
    return "Class.Method " + getName();
  }
}


text:
namespace captions {

// static
void LiveCaptionUnavailabilityNotifier::Create(
    content::RenderFrameHost* frame_host,
    mojo::PendingReceiver<media::mojom::MediaFoundationRendererNotifier>
        receiver) {
  CHECK(frame_host);
  // The object is bound to the lifetime of |frame_host| and the mojo
  // connection. See DocumentService for details.
  new LiveCaptionUnavailabilityNotifier(*frame_host, std::move(receiver));
}

LiveCaptionUnavailabilityNotifier::LiveCaptionUnavailabilityNotifier(
    content::RenderFrameHost& frame_host,
    mojo::PendingReceiver<media::mojom::MediaFoundationRendererNotifier>
        receiver)
    : DocumentService<media::mojom::MediaFoundationRendererNotifier>(
          frame_host,
          std::move(receiver)) {
  content::WebContents* web_contents = GetWebContents();
  if (!web_contents)
    return;
  context_ = CaptionBubbleContextBrowser::Create(web_contents);

  Profile* profile =
      Profile::FromBrowserContext(render_frame_host().GetBrowserContext());
  profile_prefs_ = profile->GetPrefs();

  pref_change_registrar_ = std::make_unique<PrefChangeRegistrar>();
  pref_change_registrar_->Init(profile_prefs_);

  // Unretained is safe because |this| owns the pref_change_registrar_.
  pref_change_registrar_->Add(
      prefs::kLiveCaptionEnabled,
      base::BindRepeating(&LiveCaptionUnavailabilityNotifier::
                              OnSpeechRecognitionAvailabilityChanged,
                          base::Unretained(this)));
}

LiveCaptionUnavailabilityNotifier::~LiveCaptionUnavailabilityNotifier() =
    default;

void LiveCaptionUnavailabilityNotifier::MediaFoundationRendererCreated(
    mojo::PendingReceiver<media::mojom::MediaFoundationRendererObserver>
        observer) {
  observers_.Add(this, std::move(observer));
  if (ShouldDisplayMediaFoundationRendererError()) {
    DisplayMediaFoundationRendererError();
  }
}

content::WebContents* LiveCaptionUnavailabilityNotifier::GetWebContents() {
  return content::WebContents::FromRenderFrameHost(&render_frame_host());
}

LiveCaptionController*
LiveCaptionUnavailabilityNotifier::GetLiveCaptionController() {
  Profile* profile =
      Profile::FromBrowserContext(render_frame_host().GetBrowserContext());
  if (!profile)
    return nullptr;

  return LiveCaptionControllerFactory::GetForProfile(profile);
}

bool LiveCaptionUnavailabilityNotifier::
    ShouldDisplayMediaFoundationRendererError() {
  if (!profile_prefs_->GetBoolean(prefs::kLiveCaptionEnabled))
    return false;

  if (observers_.empty())
    return false;

  return !ErrorSilencedForOrigin();
}

bool LiveCaptionUnavailabilityNotifier::ErrorSilencedForOrigin() {
  const base::Value::List& silenced_sites_list = profile_prefs_->GetList(
      prefs::kLiveCaptionMediaFoundationRendererErrorSilenced);

  const auto it = std::find_if(
      silenced_sites_list.begin(), silenced_sites_list.end(),
      [&](const base::Value& value) {
        return value.GetString() ==
               render_frame_host().GetLastCommittedOrigin().Serialize();
      });

  return it != silenced_sites_list.end();
}

void LiveCaptionUnavailabilityNotifier::DisplayMediaFoundationRendererError() {
  LiveCaptionController* live_caption_controller = GetLiveCaptionController();
  if (!live_caption_controller)
    return;

  // This will trigger the caption bubble to display a message informing the
  // user that Live Caption is unavailable and link them to the settings page
  // where they can disable the media foundation renderer to enable Live
  // Caption. The error message may be overwritten if recognition events are
  // received from another audio stream.
  live_caption_controller->OnError(
      context_.get(),
      CaptionBubbleErrorType::kMediaFoundationRendererUnsupported,
      base::BindRepeating(&LiveCaptionUnavailabilityNotifier::
                              OnMediaFoundationRendererErrorClicked,
                          weak_factory_.GetWeakPtr()),
      base::BindRepeating(
          &LiveCaptionUnavailabilityNotifier::
              OnMediaFoundationRendererErrorDoNotShowAgainCheckboxClicked,
          weak_factory_.GetWeakPtr()));
}

void LiveCaptionUnavailabilityNotifier::
    OnMediaFoundationRendererErrorDoNotShowAgainCheckboxClicked(
        CaptionBubbleErrorType error_type,
        bool checked) {
  PrefService* prefs =
      Profile::FromBrowserContext(render_frame_host().GetBrowserContext())
          ->GetPrefs();
  ListPrefUpdate update(
      prefs, prefs::kLiveCaptionMediaFoundationRendererErrorSilenced);
  base::Value::List& update_list = update->GetList();
  if (checked) {
    update_list.Append(
        render_frame_host().GetLastCommittedOrigin().Serialize());
  } else {
    update_list.EraseIf([&](const base::Value& value) {
      return value.GetString() ==
             render_frame_host().GetLastCommittedOrigin().Serialize();
    });
  }
}

void LiveCaptionUnavailabilityNotifier::
    OnMediaFoundationRendererErrorClicked() {
  Profile* profile =
      Profile::FromBrowserContext(render_frame_host().GetBrowserContext());
  chrome::ShowSiteSettings(
      profile, render_frame_host().GetLastCommittedOrigin().GetURL());
}

void LiveCaptionUnavailabilityNotifier::
    OnSpeechRecognitionAvailabilityChanged() {
  if (ShouldDisplayMediaFoundationRendererError()) {
    DisplayMediaFoundationRendererError();
  }
}

}  // namespace captions


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.quarkus.resteasy.reactive</groupId>
        <artifactId>resteasy-reactive-client-parent</artifactId>
        <version>999-SNAPSHOT</version>
    </parent>

    <artifactId>resteasy-reactive-client-processor</artifactId>
    <name>RESTEasy Reactive - Client - Processor</name>

    <dependencies>
        <dependency>
            <groupId>io.smallrye</groupId>
            <artifactId>jandex</artifactId>
        </dependency>
        <dependency>
            <groupId>io.quarkus.gizmo</groupId>
            <artifactId>gizmo</artifactId>
        </dependency>
        <dependency>
            <groupId>io.quarkus.resteasy.reactive</groupId>
            <artifactId>resteasy-reactive-client</artifactId>
        </dependency>
        <dependency>
            <groupId>io.quarkus.resteasy.reactive</groupId>
            <artifactId>resteasy-reactive-common-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.spec.javax.ws.rs</groupId>
            <artifactId>jboss-jaxrs-api_2.1_spec</artifactId>
        </dependency>
        <dependency>
            <groupId>jakarta.enterprise</groupId>
            <artifactId>jakarta.enterprise.cdi-api</artifactId>
        </dependency>
        <dependency>
            <groupId>jakarta.annotation</groupId>
            <artifactId>jakarta.annotation-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.logging</groupId>
            <artifactId>jboss-logging</artifactId>
        </dependency>

        <!-- Test -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <id>jakarta-rewrite</id>
            <activation>
                <property>
                    <name>jakarta-rewrite</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.openrewrite.maven</groupId>
                        <artifactId>rewrite-maven-plugin</artifactId>
                        <configuration>
                            <activeRecipes>
                                <recipe>io.quarkus.jakarta-jaxrs-switch</recipe>
                            </activeRecipes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
package com.sohu.cache.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.sohu.cache.entity.AppUser;

/**
 * 用户管理dao
 * @author leifu
 * @Time 2014年6月5日
 */
public interface AppUserDao {

	public AppUser get(@Param("id") Long id);

	public int save(AppUser user);

	public int update(AppUser user);

	public int delete(@Param("id") Long id);

	public int updatePwd(@Param("id") Long id, @Param("password") String password);

	public AppUser getByName(@Param("name") String name);

	AppUser getByEmail(@Param("email") String email);

    public List<AppUser> getUserList(@Param("chName") String chName);

	List<AppUser> getAdminList();

    public List<AppUser> getAllUser();
}


text:
use std::{borrow::Cow, collections::BTreeMap};

use maplit::btreemap;
use ruma_common::{serde::StringEnum, RoomVersionId};
use serde::{Deserialize, Serialize};
use serde_json::{from_value as from_json_value, to_value as to_json_value, Value as JsonValue};

use self::iter::{CapabilitiesIter, CapabilityRef};
use crate::PrivOwnedStr;

pub mod iter;
pub mod v3;

/// Contains information about all the capabilities that the server supports.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Capabilities {
    /// Capability to indicate if the user can change their password.
    #[serde(
        rename = "m.change_password",
        default,
        skip_serializing_if = "ChangePasswordCapability::is_default"
    )]
    pub change_password: ChangePasswordCapability,

    /// The room versions the server supports.
    #[serde(
        rename = "m.room_versions",
        default,
        skip_serializing_if = "RoomVersionsCapability::is_default"
    )]
    pub room_versions: RoomVersionsCapability,

    /// Capability to indicate if the user can change their display name.
    #[serde(
        rename = "m.set_displayname",
        default,
        skip_serializing_if = "SetDisplayNameCapability::is_default"
    )]
    pub set_displayname: SetDisplayNameCapability,

    /// Capability to indicate if the user can change their avatar.
    #[serde(
        rename = "m.set_avatar_url",
        default,
        skip_serializing_if = "SetAvatarUrlCapability::is_default"
    )]
    pub set_avatar_url: SetAvatarUrlCapability,

    /// Capability to indicate if the user can change the third-party identifiers associated with
    /// their account.
    #[serde(
        rename = "m.3pid_changes",
        default,
        skip_serializing_if = "ThirdPartyIdChangesCapability::is_default"
    )]
    pub thirdparty_id_changes: ThirdPartyIdChangesCapability,

    /// Any other custom capabilities that the server supports outside of the specification,
    /// labeled using the Java package naming convention and stored as arbitrary JSON values.
    #[serde(flatten)]
    custom_capabilities: BTreeMap<String, JsonValue>,
}

impl Capabilities {
    /// Creates empty `Capabilities`.
    pub fn new() -> Self {
        Default::default()
    }

    /// Returns the value of the given capability.
    ///
    /// Prefer to use the public fields of `Capabilities` where possible; this method is meant to be
    /// used for unsupported capabilities only.
    pub fn get(&self, capability: &str) -> Option<Cow<'_, JsonValue>> {
        fn serialize<T: Serialize>(cap: &T) -> JsonValue {
            to_json_value(cap).expect("capability serialization to succeed")
        }

        match capability {
            "m.change_password" => Some(Cow::Owned(serialize(&self.change_password))),
            "m.room_versions" => Some(Cow::Owned(serialize(&self.room_versions))),
            "m.set_displayname" => Some(Cow::Owned(serialize(&self.set_displayname))),
            "m.set_avatar_url" => Some(Cow::Owned(serialize(&self.set_avatar_url))),
            "m.3pid_changes" => Some(Cow::Owned(serialize(&self.thirdparty_id_changes))),
            _ => self.custom_capabilities.get(capability).map(Cow::Borrowed),
        }
    }

    /// Sets a capability to the given value.
    ///
    /// Prefer to use the public fields of `Capabilities` where possible; this method is meant to be
    /// used for unsupported capabilities only and does not allow setting arbitrary data for
    /// supported ones.
    pub fn set(&mut self, capability: &str, value: JsonValue) -> serde_json::Result<()> {
        match capability {
            "m.change_password" => self.change_password = from_json_value(value)?,
            "m.room_versions" => self.room_versions = from_json_value(value)?,
            "m.set_displayname" => self.set_displayname = from_json_value(value)?,
            "m.set_avatar_url" => self.set_avatar_url = from_json_value(value)?,
            "m.3pid_changes" => self.thirdparty_id_changes = from_json_value(value)?,
            _ => {
                self.custom_capabilities.insert(capability.to_owned(), value);
            }
        }

        Ok(())
    }

    /// Returns an iterator over the capabilities.
    pub fn iter(&self) -> CapabilitiesIter<'_> {
        CapabilitiesIter::new(self)
    }
}

impl<'a> IntoIterator for &'a Capabilities {
    type Item = CapabilityRef<'a>;
    type IntoIter = CapabilitiesIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Information about the m.change_password capability
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ChangePasswordCapability {
    /// `true` if the user can change their password, `false` otherwise.
    pub enabled: bool,
}

impl ChangePasswordCapability {
    /// Creates a new `ChangePasswordCapability` with the given enabled flag.
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }

    /// Returns whether all fields have their default value.
    pub fn is_default(&self) -> bool {
        self.enabled
    }
}

impl Default for ChangePasswordCapability {
    fn default() -> Self {
        Self { enabled: true }
    }
}

/// Information about the m.room_versions capability
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct RoomVersionsCapability {
    /// The default room version the server is using for new rooms.
    pub default: RoomVersionId,

    /// A detailed description of the room versions the server supports.
    pub available: BTreeMap<RoomVersionId, RoomVersionStability>,
}

impl RoomVersionsCapability {
    /// Creates a new `RoomVersionsCapability` with the given default room version ID and room
    /// version descriptions.
    pub fn new(
        default: RoomVersionId,
        available: BTreeMap<RoomVersionId, RoomVersionStability>,
    ) -> Self {
        Self { default, available }
    }

    /// Returns whether all fields have their default value.
    pub fn is_default(&self) -> bool {
        self.default == RoomVersionId::V1
            && self.available.len() == 1
            && self
                .available
                .get(&RoomVersionId::V1)
                .map(|stability| *stability == RoomVersionStability::Stable)
                .unwrap_or(false)
    }
}

impl Default for RoomVersionsCapability {
    fn default() -> Self {
        Self {
            default: RoomVersionId::V1,
            available: btreemap! { RoomVersionId::V1 => RoomVersionStability::Stable },
        }
    }
}

/// The stability of a room version.
#[doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/doc/string_enum.md"))]
#[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
#[ruma_enum(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RoomVersionStability {
    /// Support for the given version is stable.
    Stable,

    /// Support for the given version is unstable.
    Unstable,

    #[doc(hidden)]
    _Custom(PrivOwnedStr),
}

/// Information about the `m.set_displayname` capability
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct SetDisplayNameCapability {
    /// `true` if the user can change their display name, `false` otherwise.
    pub enabled: bool,
}

impl SetDisplayNameCapability {
    /// Creates a new `SetDisplayNameCapability` with the given enabled flag.
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }

    /// Returns whether all fields have their default value.
    pub fn is_default(&self) -> bool {
        self.enabled
    }
}

impl Default for SetDisplayNameCapability {
    fn default() -> Self {
        Self { enabled: true }
    }
}

/// Information about the `m.set_avatar_url` capability
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct SetAvatarUrlCapability {
    /// `true` if the user can change their avatar, `false` otherwise.
    pub enabled: bool,
}

impl SetAvatarUrlCapability {
    /// Creates a new `SetAvatarUrlCapability` with the given enabled flag.
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }

    /// Returns whether all fields have their default value.
    pub fn is_default(&self) -> bool {
        self.enabled
    }
}

impl Default for SetAvatarUrlCapability {
    fn default() -> Self {
        Self { enabled: true }
    }
}

/// Information about the `m.3pid_changes` capability
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ThirdPartyIdChangesCapability {
    /// `true` if the user can change the third-party identifiers associated with their account,
    /// `false` otherwise.
    pub enabled: bool,
}

impl ThirdPartyIdChangesCapability {
    /// Creates a new `ThirdPartyIdChangesCapability` with the given enabled flag.
    pub fn new(enabled: bool) -> Self {
        Self { enabled }
    }

    /// Returns whether all fields have their default value.
    pub fn is_default(&self) -> bool {
        self.enabled
    }
}

impl Default for ThirdPartyIdChangesCapability {
    fn default() -> Self {
        Self { enabled: true }
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use assert_matches::assert_matches;
    use serde_json::json;

    use super::Capabilities;

    #[test]
    fn capabilities_iter() -> serde_json::Result<()> {
        let mut caps = Capabilities::new();
        let custom_cap = json!({
            "key": "value",
        });
        caps.set("m.some_random_capability", custom_cap)?;
        let mut caps_iter = caps.iter();

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.change_password");
        assert_eq!(iter_res.value(), Cow::Borrowed(&json!({ "enabled": true })));

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.room_versions");
        assert_eq!(
            iter_res.value(),
            Cow::Borrowed(&json!({ "available": { "1": "stable" },"default" :"1" }))
        );

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.set_displayname");
        assert_eq!(iter_res.value(), Cow::Borrowed(&json!({ "enabled": true })));

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.set_avatar_url");
        assert_eq!(iter_res.value(), Cow::Borrowed(&json!({ "enabled": true })));

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.3pid_changes");
        assert_eq!(iter_res.value(), Cow::Borrowed(&json!({ "enabled": true })));

        let iter_res = caps_iter.next().unwrap();
        assert_eq!(iter_res.name(), "m.some_random_capability");
        assert_eq!(iter_res.value(), Cow::Borrowed(&json!({ "key": "value" })));

        assert_matches!(caps_iter.next(), None);
        Ok(())
    }
}


text:
"""
Custom user model for deployments.
"""

import urllib
import hashlib

from django.db import models
from django.utils.translation import ugettext_lazy as _

from authtools.models import AbstractEmailUser

class DeployUser(AbstractEmailUser):
    """
    Custom user class for deployments. Email as username using django-custom-user.
    """

    AMELIA = 'amelia.min.css'
    CERULEAN = 'cerulean.min.css'
    COSMO = 'cosmo.min.css'
    CYBORG = 'cyborg.min.css'
    DARKLY = 'darkly.min.css'
    FLATLY = 'flatly.min.css'
    JOURNAL = 'journal.min.css'
    LUMEN = 'lumen.min.css'
    READABLE = 'readable.min.css'
    SIMPLEX = 'simplex.min.css'
    SLATE = 'slate.min.css'
    SPACELAB = 'spacelab.min.css'
    SUPERHERO = 'superhero.min.css'
    UNITED = 'united.min.css'
    YETI = 'yeti.min.css'

    TEMPLATES = (
        (AMELIA, 'Amelia'),
        (CERULEAN, 'Cerulean'),
        (COSMO, 'Cosmo'),
        (CYBORG, 'Cyborg'),
        (DARKLY, 'Darkly'),
        (FLATLY, 'Flatly'),
        (JOURNAL, 'Journal'),
        (LUMEN, 'Lumen'),
        (READABLE, 'Readable'),
        (SIMPLEX, 'Simplex'),
        (SLATE, 'Slate'),
        (SPACELAB, 'Spacelab'),
        (SUPERHERO, 'Superhero'),
        (UNITED, 'United'),
        (YETI, 'Yeti'),
    )

    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    template = models.CharField(max_length=255, blank=True, choices=TEMPLATES, default=YETI)

    def __unicode__(self):
        return u'{} {}'.format(self.first_name, self.last_name)

    @property
    def role(self):
        """
        Assumes the user is only assigned to one role and return it
        """
        return self.group_strigify()

    def _get_groups(self):
        if not hasattr(self, '_cached_groups'):
            self._cached_groups = list(self.groups.values_list("name", flat=True))
        return self._cached_groups

    def user_is_admin(self):
        if not self.pk:
            return False
        return "Admin" in self._get_groups()

    def user_is_deployer(self):
        if not self.pk:
            return False
        return "Deployer" in self._get_groups()

    def user_is_historian(self):
        if not self.pk:
            return False
        return "Historian" in self._get_groups()

    def group_strigify(self):
        """
        Converts this user's group(s) to a string and returns it.
        """
        return "/".join(self._get_groups())

    def gravatar(self, size=20):
        """
        Construct a gravatar image address for the user
        """
        default = "mm"

        gravatar_url = "http://www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?"
        gravatar_url += urllib.urlencode({'d': default, 's': str(size)})

        return gravatar_url


text:
package org.apache.shardingsphere.sharding.merge.dql.pagination;

import org.apache.shardingsphere.underlying.merge.result.MergedResult;
import org.apache.shardingsphere.underlying.merge.result.impl.decorator.DecoratorMergedResult;
import org.apache.shardingsphere.sql.parser.binder.segment.select.pagination.PaginationContext;

import java.sql.SQLException;

/**
 * Decorator merged result for row number pagination.
 */
public final class RowNumberDecoratorMergedResult extends DecoratorMergedResult {

    private final PaginationContext pagination;

    private final boolean skipAll;

    private long rowNumber;

    public RowNumberDecoratorMergedResult(final MergedResult mergedResult, final PaginationContext pagination) throws SQLException {
        super(mergedResult);
        this.pagination = pagination;
        skipAll = skipOffset();
    }

    private boolean skipOffset() throws SQLException {
        long end = pagination.getActualOffset();
        for (int i = 0; i < end; i++) {
            if (!getMergedResult().next()) {
                return true;
            }
        }
        rowNumber = end + 1;
        return false;
    }

    @Override
    public boolean next() throws SQLException {
        if (skipAll) {
            return false;
        }
        if (!pagination.getActualRowCount().isPresent()) {
            return getMergedResult().next();
        }
        return rowNumber++ < pagination.getActualRowCount().get() && getMergedResult().next();
    }
}


text:
Ext.namespace("GeoExt.ux");
GeoExt.ux.WFSTFeatureEditingManager &&
Ext.apply(GeoExt.ux.WFSTFeatureEditingManager.prototype, {
    drawMenuButtonText: "Ajouter",
    drawMenuButtonTooltipText: "Outil d'ajout: Choisir une couche dans la liste et dessiner un nouvel élément en cliquant sur la carte.",
    editMenuButtonText: "Éditer",
    editMenuButtonTooltipText: "Outil d'édition: Choisir une couche dans la liste et cliquer sur un élément dans la carte à éditer.",
    featureGridContainerTitleText: "Features",
    featureEditorGridContainerTitleText: "Élément en cours d'édition",
    returnToSelectionText: "Retourner à la sélection",
    commitSuccessText: "Modifications sauvegardées avec succès",
    commitFailText: "Une erreur est survenue.  Les modifications n'ont pas été sauvegardées"
});

GeoExt.ux.WFSTFeatureEditingStatusBar &&
Ext.apply(GeoExt.ux.WFSTFeatureEditingStatusBar.prototype, {
    text: 'Prêt',
    defaultText: 'Prêt',
    busyText: 'Sauvegarde en cours.  Veuillez patienter...'
});

GeoExt.ux.FeatureEditorGrid &&
Ext.apply(GeoExt.ux.FeatureEditorGrid.prototype, {
    deleteMsgTitle: "Supprimer l'élément?",
    deleteMsg: "Etes-vous certain de vouloir supprimer cet élément?",
    deleteButtonText: "Supprimer",
    deleteButtonTooltip: "Supprimer cet élément",
    cancelMsgTitle: "Annuler les modifications?",
    cancelMsg: "L'élément contient des changements non sauvegardés.  Annuler les modifications?",
    cancelButtonText: "Annuler",
    cancelButtonTooltip: "Arrête l'édition, annule les changements",
    saveButtonText: "Sauvegarder",
    saveButtonTooltip: "Sauvegarder les changements",
    nameHeader: "Attribut",
    valueHeader: "Valeur"
});