text:
from __future__ import absolute_import

try:
    from itertools import zip_longest as izip_longest, repeat  # pylint: disable=E0611
except ImportError:
    from itertools import izip_longest as izip_longest, repeat  # pylint: disable=E0611
import logging
import sys
import time
import warnings

from kafka.vendor import six
from kafka.vendor.six.moves import queue # pylint: disable=import-error

from kafka.consumer.base import (
    Consumer,
    FETCH_DEFAULT_BLOCK_TIMEOUT,
    AUTO_COMMIT_MSG_COUNT,
    AUTO_COMMIT_INTERVAL,
    FETCH_MIN_BYTES,
    FETCH_BUFFER_SIZE_BYTES,
    MAX_FETCH_BUFFER_SIZE_BYTES,
    FETCH_MAX_WAIT_TIME,
    ITER_TIMEOUT_SECONDS,
    NO_MESSAGES_WAIT_TIME_SECONDS
)
from kafka.errors import (
    KafkaError, ConsumerFetchSizeTooSmall,
    UnknownTopicOrPartitionError, NotLeaderForPartitionError,
    OffsetOutOfRangeError, FailedPayloadsError, check_error
)
from kafka.protocol.message import PartialMessage
from kafka.structs import FetchRequestPayload, OffsetRequestPayload

log = logging.getLogger(__name__)

class FetchContext(object):
    """
    Class for managing the state of a consumer during fetch
    """
    def __init__(self, consumer, block, timeout):
        warnings.warn('deprecated - this class will be removed in a future'
                      ' release', DeprecationWarning)
        self.consumer = consumer
        self.block = block

        if block:
            if not timeout:
                timeout = FETCH_DEFAULT_BLOCK_TIMEOUT
            self.timeout = timeout * 1000

    def __enter__(self):
        """Set fetch values based on blocking status"""
        self.orig_fetch_max_wait_time = self.consumer.fetch_max_wait_time
        self.orig_fetch_min_bytes = self.consumer.fetch_min_bytes
        if self.block:
            self.consumer.fetch_max_wait_time = self.timeout
            self.consumer.fetch_min_bytes = 1
        else:
            self.consumer.fetch_min_bytes = 0

    def __exit__(self, type, value, traceback):
        """Reset values"""
        self.consumer.fetch_max_wait_time = self.orig_fetch_max_wait_time
        self.consumer.fetch_min_bytes = self.orig_fetch_min_bytes

class SimpleConsumer(Consumer):
    """
    A simple consumer implementation that consumes all/specified partitions
    for a topic

    Arguments:
        client: a connected SimpleClient
        group: a name for this consumer, used for offset storage and must be unique
            If you are connecting to a server that does not support offset
            commit/fetch (any prior to 0.8.1.1), then you *must* set this to None
        topic: the topic to consume

    Keyword Arguments:
        partitions: An optional list of partitions to consume the data from

        auto_commit: default True. Whether or not to auto commit the offsets

        auto_commit_every_n: default 100. How many messages to consume
             before a commit

        auto_commit_every_t: default 5000. How much time (in milliseconds) to
             wait before commit
        fetch_size_bytes: number of bytes to request in a FetchRequest

        buffer_size: default 4K. Initial number of bytes to tell kafka we
             have available. This will double as needed.

        max_buffer_size: default 16K. Max number of bytes to tell kafka we have
             available. None means no limit.

        iter_timeout: default None. How much time (in seconds) to wait for a
             message in the iterator before exiting. None means no
             timeout, so it will wait forever.

        auto_offset_reset: default largest. Reset partition offsets upon
             OffsetOutOfRangeError. Valid values are largest and smallest.
             Otherwise, do not reset the offsets and raise OffsetOutOfRangeError.

        offset_storage: default zookeeper. Specifies that offset storage that
             will be used to fetch and commit the offsets. Valid values are
             'zookeeper', 'kafka', or 'dual'.

    Auto commit details:
    If both auto_commit_every_n and auto_commit_every_t are set, they will
    reset one another when one is triggered. These triggers simply call the
    commit method on this class. A manual call to commit will also reset
    these triggers
    """
    def __init__(self, client, group, topic, auto_commit=True, partitions=None,
                 auto_commit_every_n=AUTO_COMMIT_MSG_COUNT,
                 auto_commit_every_t=AUTO_COMMIT_INTERVAL,
                 fetch_size_bytes=FETCH_MIN_BYTES,
                 buffer_size=FETCH_BUFFER_SIZE_BYTES,
                 max_buffer_size=MAX_FETCH_BUFFER_SIZE_BYTES,
                 iter_timeout=None,
                 auto_offset_reset='largest',
                 offset_storage='zookeeper'):
        warnings.warn('deprecated - this class will be removed in a future'
                      ' release. Use KafkaConsumer instead.',
                      DeprecationWarning)
        super(SimpleConsumer, self).__init__(
            client, group, topic,
            partitions=partitions,
            auto_commit=auto_commit,
            auto_commit_every_n=auto_commit_every_n,
            auto_commit_every_t=auto_commit_every_t,
            offset_storage=offset_storage)

        if max_buffer_size is not None and buffer_size > max_buffer_size:
            raise ValueError('buffer_size (%d) is greater than '
                             'max_buffer_size (%d)' %
                             (buffer_size, max_buffer_size))
        self.buffer_size = buffer_size
        self.max_buffer_size = max_buffer_size
        self.fetch_max_wait_time = FETCH_MAX_WAIT_TIME
        self.fetch_min_bytes = fetch_size_bytes
        self.fetch_offsets = self.offsets.copy()
        self.iter_timeout = iter_timeout
        self.auto_offset_reset = auto_offset_reset
        self.queue = queue.Queue()

    def __repr__(self):
        return '<SimpleConsumer group=%s, topic=%s, partitions=%s>' % \
            (self.group, self.topic, str(self.offsets.keys()))

    def reset_partition_offset(self, partition):
        """Update offsets using auto_offset_reset policy (smallest|largest)

        Arguments:
            partition (int): the partition for which offsets should be updated

        Returns: Updated offset on success, None on failure
        """
        LATEST = -1
        EARLIEST = -2
        if self.auto_offset_reset == 'largest':
            reqs = [OffsetRequestPayload(self.topic, partition, LATEST, 1)]
        elif self.auto_offset_reset == 'smallest':
            reqs = [OffsetRequestPayload(self.topic, partition, EARLIEST, 1)]
        else:
            # Let's raise an reasonable exception type if user calls
            # outside of an exception context
            if sys.exc_info() == (None, None, None):
                raise OffsetOutOfRangeError('Cannot reset partition offsets without a '
                                            'valid auto_offset_reset setting '
                                            '(largest|smallest)')
            # Otherwise we should re-raise the upstream exception
            # b/c it typically includes additional data about
            # the request that triggered it, and we do not want to drop that
            raise # pylint: disable=E0704

        # send_offset_request
        log.info('Resetting topic-partition offset to %s for %s:%d',
                 self.auto_offset_reset, self.topic, partition)
        try:
            (resp, ) = self.client.send_offset_request(reqs)
        except KafkaError as e:
            log.error('%s sending offset request for %s:%d',
                      e.__class__.__name__, self.topic, partition)
        else:
            self.offsets[partition] = resp.offsets[0]
            self.fetch_offsets[partition] = resp.offsets[0]
            return resp.offsets[0]

    def seek(self, offset, whence=None, partition=None):
        """
        Alter the current offset in the consumer, similar to fseek

        Arguments:
            offset: how much to modify the offset
            whence: where to modify it from, default is None

                * None is an absolute offset
                * 0    is relative to the earliest available offset (head)
                * 1    is relative to the current offset
                * 2    is relative to the latest known offset (tail)

            partition: modify which partition, default is None.
                If partition is None, would modify all partitions.
        """

        if whence is None: # set an absolute offset
            if partition is None:
                for tmp_partition in self.offsets:
                    self.offsets[tmp_partition] = offset
            else:
                self.offsets[partition] = offset
        elif whence == 1:  # relative to current position
            if partition is None:
                for tmp_partition, _offset in self.offsets.items():
                    self.offsets[tmp_partition] = _offset + offset
            else:
                self.offsets[partition] += offset
        elif whence in (0, 2):  # relative to beginning or end
            reqs = []
            deltas = {}
            if partition is None:
                # divide the request offset by number of partitions,
                # distribute the remained evenly
                (delta, rem) = divmod(offset, len(self.offsets))
                for tmp_partition, r in izip_longest(self.offsets.keys(),
                                                     repeat(1, rem),
                                                     fillvalue=0):
                    deltas[tmp_partition] = delta + r

                for tmp_partition in self.offsets.keys():
                    if whence == 0:
                        reqs.append(OffsetRequestPayload(self.topic, tmp_partition, -2, 1))
                    elif whence == 2:
                        reqs.append(OffsetRequestPayload(self.topic, tmp_partition, -1, 1))
                    else:
                        pass
            else:
                deltas[partition] = offset
                if whence == 0:
                    reqs.append(OffsetRequestPayload(self.topic, partition, -2, 1))
                elif whence == 2:
                    reqs.append(OffsetRequestPayload(self.topic, partition, -1, 1))
                else:
                    pass

            resps = self.client.send_offset_request(reqs)
            for resp in resps:
                self.offsets[resp.partition] = \
                    resp.offsets[0] + deltas[resp.partition]
        else:
            raise ValueError('Unexpected value for `whence`, %d' % (whence,))

        # Reset queue and fetch offsets since they are invalid
        self.fetch_offsets = self.offsets.copy()
        self.count_since_commit += 1
        if self.auto_commit:
            self.commit()

        self.queue = queue.Queue()

    def get_messages(self, count=1, block=True, timeout=0.1):
        """
        Fetch the specified number of messages

        Keyword Arguments:
            count: Indicates the maximum number of messages to be fetched
            block: If True, the API will block till all messages are fetched.
                If block is a positive integer the API will block until that
                many messages are fetched.
            timeout: When blocking is requested the function will block for
                the specified time (in seconds) until count messages is
                fetched. If None, it will block forever.
        """
        messages = []
        if timeout is not None:
            timeout += time.time()

        new_offsets = {}
        log.debug('getting %d messages', count)
        while len(messages) < count:
            block_time = timeout - time.time()
            log.debug('calling _get_message block=%s timeout=%s', block, block_time)
            block_next_call = block is True or block > len(messages)
            result = self._get_message(block_next_call, block_time,
                                       get_partition_info=True,
                                       update_offset=False)
            log.debug('got %s from _get_messages', result)
            if not result:
                if block_next_call and (timeout is None or time.time() <= timeout):
                    continue
                break

            partition, message = result
            _msg = (partition, message) if self.partition_info else message
            messages.append(_msg)
            new_offsets[partition] = message.offset + 1

        # Update and commit offsets if necessary
        self.offsets.update(new_offsets)
        self.count_since_commit += len(messages)
        self._auto_commit()
        log.debug('got %d messages: %s', len(messages), messages)
        return messages

    def get_message(self, block=True, timeout=0.1, get_partition_info=None):
        return self._get_message(block, timeout, get_partition_info)

    def _get_message(self, block=True, timeout=0.1, get_partition_info=None,
                     update_offset=True):
        """
        If no messages can be fetched, returns None.
        If get_partition_info is None, it defaults to self.partition_info
        If get_partition_info is True, returns (partition, message)
        If get_partition_info is False, returns message
        """
        start_at = time.time()
        while self.queue.empty():
            # We're out of messages, go grab some more.
            log.debug('internal queue empty, fetching more messages')
            with FetchContext(self, block, timeout):
                self._fetch()

            if not block or time.time() > (start_at + timeout):
                break

        try:
            partition, message = self.queue.get_nowait()

            if update_offset:
                # Update partition offset
                self.offsets[partition] = message.offset + 1

                # Count, check and commit messages if necessary
                self.count_since_commit += 1
                self._auto_commit()

            if get_partition_info is None:
                get_partition_info = self.partition_info
            if get_partition_info:
                return partition, message
            else:
                return message
        except queue.Empty:
            log.debug('internal queue empty after fetch - returning None')
            return None

    def __iter__(self):
        if self.iter_timeout is None:
            timeout = ITER_TIMEOUT_SECONDS
        else:
            timeout = self.iter_timeout

        while True:
            message = self.get_message(True, timeout)
            if message:
                yield message
            elif self.iter_timeout is None:
                # We did not receive any message yet but we don't have a
                # timeout, so give up the CPU for a while before trying again
                time.sleep(NO_MESSAGES_WAIT_TIME_SECONDS)
            else:
                # Timed out waiting for a message
                break

    def _fetch(self):
        # Create fetch request payloads for all the partitions
        partitions = dict((p, self.buffer_size)
                      for p in self.fetch_offsets.keys())
        while partitions:
            requests = []
            for partition, buffer_size in six.iteritems(partitions):
                requests.append(FetchRequestPayload(self.topic, partition,
                                                    self.fetch_offsets[partition],
                                                    buffer_size))
            # Send request
            responses = self.client.send_fetch_request(
                requests,
                max_wait_time=int(self.fetch_max_wait_time),
                min_bytes=self.fetch_min_bytes,
                fail_on_error=False
            )

            retry_partitions = {}
            for resp in responses:

                try:
                    check_error(resp)
                except UnknownTopicOrPartitionError:
                    log.error('UnknownTopicOrPartitionError for %s:%d',
                              resp.topic, resp.partition)
                    self.client.reset_topic_metadata(resp.topic)
                    raise
                except NotLeaderForPartitionError:
                    log.error('NotLeaderForPartitionError for %s:%d',
                              resp.topic, resp.partition)
                    self.client.reset_topic_metadata(resp.topic)
                    continue
                except OffsetOutOfRangeError:
                    log.warning('OffsetOutOfRangeError for %s:%d. '
                                'Resetting partition offset...',
                                resp.topic, resp.partition)
                    self.reset_partition_offset(resp.partition)
                    # Retry this partition
                    retry_partitions[resp.partition] = partitions[resp.partition]
                    continue
                except FailedPayloadsError as e:
                    log.warning('FailedPayloadsError for %s:%d',
                                e.payload.topic, e.payload.partition)
                    # Retry this partition
                    retry_partitions[e.payload.partition] = partitions[e.payload.partition]
                    continue

                partition = resp.partition
                buffer_size = partitions[partition]

                # Check for partial message
                if resp.messages and isinstance(resp.messages[-1].message, PartialMessage):

                    # If buffer is at max and all we got was a partial message
                    # raise ConsumerFetchSizeTooSmall
                    if (self.max_buffer_size is not None and
                        buffer_size == self.max_buffer_size and
                        len(resp.messages) == 1):

                        log.error('Max fetch size %d too small', self.max_buffer_size)
                        raise ConsumerFetchSizeTooSmall()

                    if self.max_buffer_size is None:
                        buffer_size *= 2
                    else:
                        buffer_size = min(buffer_size * 2, self.max_buffer_size)
                    log.warning('Fetch size too small, increase to %d (2x) '
                                'and retry', buffer_size)
                    retry_partitions[partition] = buffer_size
                    resp.messages.pop()

                for message in resp.messages:
                    if message.offset < self.fetch_offsets[partition]:
                        log.debug('Skipping message %s because its offset is less than the consumer offset',
                                  message)
                        continue
                    # Put the message in our queue
                    self.queue.put((partition, message))
                    self.fetch_offsets[partition] = message.offset + 1
            partitions = retry_partitions


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">NotificationHubsE2ETestApp</string>
    <string name="menu_settings">Settings</string>
    <string name="menu_run_tests">Run Selected Tests</string>
    <string name="menu_check_all">Check all tests</string>
    <string name="menu_uncheck_all">Uncheck all tests</string>
    <string name="test_case_name">Test Case Name</string>
    <string name="menu_reset">Reset</string>
    <string name="menu_view_log">View Log</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
cask 'flash-npapi' do
  version '27.0.0.187'
  sha256 'f9fb07154525746ce23fc5dcf8f247c87ee9ca357fcae1ae9f063a8c448b2141'

  # macromedia.com was verified as official when first introduced to the cask
  url "https://fpdownload.adobe.com/get/flashplayer/pdc/#{version}/install_flash_player_osx.dmg"
  appcast 'http://fpdownload2.macromedia.com/get/flashplayer/update/current/xml/version_en_mac_pl.xml',
          checkpoint: '26279ca81dea1717dec4c2d638ee46a14c9caa731f6bd2bc9ac35380bdef0ec9'
  name 'Adobe Flash Player NPAPI (plugin for Safari and Firefox)'
  homepage 'https://get.adobe.com/flashplayer/'

  auto_updates true

  pkg 'Install Adobe Flash Player.app/Contents/Resources/Adobe Flash Player.pkg'

  uninstall pkgutil: 'com.adobe.pkg.FlashPlayer',
            delete:  '/Library/Internet Plug-Ins/Flash Player.plugin'

  zap trash: [
               '~/Library/Caches/Adobe/Flash Player',
               '~/Library/Logs/FlashPlayerInstallManager.log',
               '/Library/Internet Plug-Ins/flashplayer.xpt',
             ]
end


text:
var Promise = require('bluebird');

function stopWatcherFilter(){
  return Promise.all([
    stopWatcher(this.source),
    stopWatcher(this.theme)
  ]);
}

function stopWatcher(box){
  if (box.isWatching()) return box.unwatch();
}

module.exports = stopWatcherFilter;


text:
import simuvex
from simuvex.s_type import SimTypeTop, SimTypeLength, SimTypeInt

import logging
l = logging.getLogger("simuvex.procedures.libc.memcmp")

class memcmp(simuvex.SimProcedure):
    #pylint:disable=arguments-differ

    def run(self, s1_addr, s2_addr, n):
        # TODO: look into smarter types here
        self.argument_types = {0: self.ty_ptr(SimTypeTop()),
                               1: self.ty_ptr(SimTypeTop()),
                               2: SimTypeLength(self.state.arch)}
        self.return_type = SimTypeInt(32, True)

        max_memcmp_size = self.state.libc.max_buffer_size

        definite_size = self.state.se.min_int(n)
        conditional_s1_start = s1_addr + definite_size
        conditional_s2_start = s2_addr + definite_size
        if self.state.se.symbolic(n):
            conditional_size = int(max(max_memcmp_size - definite_size, 0))
        else:
            conditional_size = 0

        l.debug("Definite size %s and conditional size: %s", definite_size, conditional_size)

        if definite_size > 0:
            s1_part = self.state.memory.load(s1_addr, definite_size, endness='Iend_BE')
            s2_part = self.state.memory.load(s2_addr, definite_size, endness='Iend_BE')
            cases = [ [s1_part == s2_part, self.state.se.BVV(0, self.state.arch.bits)], [self.state.se.ULT(s1_part, s2_part), self.state.se.BVV(-1, self.state.arch.bits)], [self.state.se.UGT(s1_part, s2_part), self.state.se.BVV(1, self.state.arch.bits) ] ]
            definite_answer = self.state.se.ite_cases(cases, 2)
            constraint = self.state.se.Or(*[c for c,_ in cases])
            self.state.add_constraints(constraint)

            l.debug("Created definite answer: %s", definite_answer)
            l.debug("Created constraint: %s", constraint)
            l.debug("... crom cases: %s", cases)
        else:
            definite_answer = self.state.se.BVV(0, self.state.arch.bits)

        if not self.state.se.symbolic(definite_answer) and self.state.se.any_int(definite_answer) != 0:
            return definite_answer

        if conditional_size > 0:
            s1_all = self.state.memory.load(conditional_s1_start, conditional_size, endness='Iend_BE')
            s2_all = self.state.memory.load(conditional_s2_start, conditional_size, endness='Iend_BE')
            conditional_rets = { 0: definite_answer }

            for byte, bit in zip(range(conditional_size), range(conditional_size*8, 0, -8)):
                s1_part = s1_all[conditional_size*8-1 : bit-8]
                s2_part = s2_all[conditional_size*8-1 : bit-8]
                cases = [ [s1_part == s2_part, self.state.se.BVV(0, self.state.arch.bits)], [self.state.se.ULT(s1_part, s2_part), self.state.se.BVV(-1, self.state.arch.bits)], [self.state.se.UGT(s1_part, s2_part), self.state.se.BVV(1, self.state.arch.bits) ] ]
                conditional_rets[byte+1] = self.state.se.ite_cases(cases, 0)
                self.state.add_constraints(self.state.se.Or(*[c for c,_ in cases]))

            ret_expr = self.state.se.ite_dict(n - definite_size, conditional_rets, 2)
            self.state.add_constraints(self.state.se.Or(*[n-definite_size == c for c in conditional_rets.keys()]))
            return ret_expr
        else:
            return definite_answer


text:
#include <algorithm>
#include "commons.h"
#include "BufferStream.h"
#include "FileSystem.h"
#include "IFile.h"
#include "KVFile.h"
#include "test_commons.h"

IndexRange * writeIFile(int partition,
                             vector<pair<string, string> > & kvs,
                             const string & path,
                             KeyValueType type,
                             const string & codec) {
  FileOutputStream * fout = (FileOutputStream*)FileSystem::getLocal().create(path);
  IFileWriter * iw = new IFileWriter(fout, CHECKSUM_CRC32, type, type, codec);
  for (int i=0;i<partition;i++) {
    iw->startPartition();
    for (size_t i = 0;i<kvs.size();i++) {
      pair<string, string> & p = kvs[i];
      iw->write(p.first.c_str(), p.first.length(),
                p.second.c_str(), p.second.length());
    }
    iw->endPartition();
  }
  IndexRange * info = iw->getIndex(0);
  delete iw;
  delete fout;
  return info;
}

void readIFile(vector<pair<string, string> > & kvs, const string & path,
                KeyValueType type, IndexRange * info, const string & codec) {
  FileInputStream * fin = (FileInputStream*) FileSystem::getLocal().open(path);
  IFileReader * ir = new IFileReader(fin, CHECKSUM_CRC32, type, type, info, codec);
  size_t count = 0;
  while (ir->nextPartition() == 0) {
    const char * key, *value;
    uint32_t keyLen, valueLen;
    while (NULL != (key = ir->nextKey(keyLen))) {
      value = ir->value(valueLen);
      string keyS(key, keyLen);
      string valueS(value, valueLen);
      kvs.push_back(std::make_pair(keyS, valueS));
    }
  }
  delete ir;
  delete fin;
}

void TestIFileReadWrite(KeyValueType kvtype, int partition, int size,
                        vector<pair<string, string> > & kvs, const string & codec="") {
  string outputpath = "ifilewriter";
  IndexRange * info = writeIFile(partition, kvs, outputpath, kvtype, codec);
  LOG("write finished");
  vector<pair<string, string> > readkvs;
  readIFile(readkvs, outputpath, kvtype, info, codec);
  LOG("read finished");
  ASSERT_EQ(kvs.size()*partition, readkvs.size());
  for (int i=0;i<partition;i++) {
    vector<pair<string, string> > cur_part(readkvs.begin()+i*kvs.size(),
                                           readkvs.begin()+(i+1)*kvs.size());
    ASSERT_EQ(kvs.size(), cur_part.size());
//    for (size_t j=0;j<kvs.size();j++) {
//      SCOPED_TRACE(j);
//      ASSERT_EQ(kvs[j], cur_part[j]);
//    }
    ASSERT_EQ(kvs, cur_part);
  }
  FileSystem::getLocal().remove(outputpath);
}

TEST(IFile, WriteRead) {
  int partition = TestConfig.getInt("ifile.partition", 7);
  int size = TestConfig.getInt("partition.size", 20000);
  vector<pair<string, string> > kvs;
  Generate(kvs, size, "bytes");
  TestIFileReadWrite(TextType, partition, size, kvs);
  TestIFileReadWrite(BytesType, partition, size, kvs);
  TestIFileReadWrite(UnknownType, partition, size, kvs);
  TestIFileReadWrite(TextType, partition, size, kvs, "org.apache.hadoop.io.compress.SnappyCodec");
}

void TestIFileWriteRead2(vector<pair<string, string> > & kvs, char * buff,
                         size_t buffsize, const string & codec,
                         ChecksumType checksumType, KeyValueType type) {
  int partition = TestConfig.getInt("ifile.partition", 50);
  Timer timer;
  OutputBuffer outputBuffer = OutputBuffer(buff, buffsize);
  IFileWriter * iw = new IFileWriter(&outputBuffer, checksumType, type, type, codec);
  timer.reset();
  for (int i=0;i<partition;i++) {
    iw->startPartition();
    for (size_t j=0;j<kvs.size();j++) {
      iw->write(kvs[j].first.c_str(), kvs[j].first.length(),
                kvs[j].second.c_str(), kvs[j].second.length());
    }
    iw->endPartition();
  }
  IndexRange * info = iw->getIndex(0);
  LOG("%s", timer.getSpeedM2("Write data", info->getEndPosition(),
          info->getRealEndPosition()).c_str());
  delete iw;

  InputBuffer inputBuffer = InputBuffer(buff, outputBuffer.tell());
  IFileReader * ir = new IFileReader(&inputBuffer, checksumType, type, type, info, codec);
  timer.reset();
  while (0 == ir->nextPartition()) {
    const char * key, * value;
    uint32_t keyLen, valueLen;
    while (NULL != (key=ir->nextKey(keyLen))) {
      value = ir->value(valueLen);
    }
  }
  LOG("%s", timer.getSpeedM2(" Read data", info->getEndPosition(),
          info->getRealEndPosition()).c_str());
  delete ir;
  delete info;
}

void TestKVFileWriteRead2(vector<pair<string, string> > & kvs, char * buff,
                         size_t buffsize, const string & codec,
                         ChecksumType checksumType, KeyValueType type) {
  int partition = TestConfig.getInt("ifile.partition", 50);
  Timer timer;
  OutputBuffer outputBuffer = OutputBuffer(buff, buffsize);
  KVFileWriter * iw = new KVFileWriter(&outputBuffer, checksumType, codec);
  timer.reset();
  for (int i=0;i<partition;i++) {
    iw->startPartition();
    for (size_t j=0;j<kvs.size();j++) {
      iw->write(kvs[j].first.c_str(), kvs[j].first.length(),
                kvs[j].second.c_str(), kvs[j].second.length());
    }
    iw->endPartition();
  }
  IndexRange * info = iw->getIndex(0);
  LOG("%s", timer.getSpeedM2("Write data", info->getEndPosition(),
          info->getRealEndPosition()).c_str());
  delete iw;

  InputBuffer inputBuffer = InputBuffer(buff, outputBuffer.tell());
  KVFileReader * ir = new KVFileReader(&inputBuffer, checksumType, info, codec);
  timer.reset();
  while (0 == ir->nextPartition()) {
    const char * key, * value;
    uint32_t keyLen, valueLen;
    while (NULL != (key=ir->nextKey(keyLen))) {
      value = ir->value(valueLen);
    }
  }
  LOG("%s", timer.getSpeedM2(" Read data", info->getEndPosition(),
          info->getRealEndPosition()).c_str());
  delete ir;
  delete info;
}

TEST(Perf, IFile) {
  int size = TestConfig.getInt("partition.size", 20000);
  string codec = TestConfig.get("ifile.codec", "");
  string type = TestConfig.get("ifile.type", "bytes");

  vector<pair<string, string> > kvs;
  Generate(kvs, size, type);
  std::sort(kvs.begin(), kvs.end());

  size_t buffsize = 200*1024*1024;
  char * buff = new char[buffsize];
  memset(buff, 0, buffsize);

  LOG("Test TextType CRC32");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32, TextType);
  LOG("Test BytesType CRC32");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32, BytesType);
  LOG("Test UnknownType CRC32");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32, UnknownType);
  LOG("Test KVFile CRC32");
  TestKVFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32, UnknownType);

  LOG("Test TextType CRC32C");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32C, TextType);
  LOG("Test BytesType CRC32C");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32C, BytesType);
  LOG("Test UnknownType CRC32C");
  TestIFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32C, UnknownType);
  LOG("Test KVFile CRC32C");
  TestKVFileWriteRead2(kvs, buff, buffsize, codec, CHECKSUM_CRC32C, UnknownType);

  delete [] buff;
}


text:
from restbasetest import *
from common.rest.storage_helper import VolumeHelper, VolumeSnapshotHelper

class TestVolumeSnapshotRequests(RESTBaseTest):

    @classmethod
    def setup_class(cls):
        super(TestVolumeSnapshotRequests, cls).setup_class()

        cls.vhelper = VolumeHelper(cls.utils)
        cls.shelper = VolumeSnapshotHelper(cls.utils)

        # remove snapshots and volumes to relieve storage
        cls.utils.cleanup_objects(cls.shelper.delete_snapshot, 'snapshots')
        cls.utils.cleanup_objects(cls.vhelper.delete_volume, 'volumes', name_key='displayName')

    def teardown(self):
        self.utils.cleanup_objects(self.shelper.delete_snapshot, 'snapshots')
        self.utils.cleanup_objects(self.vhelper.delete_volume, 'volumes', name_key='displayName')

    def test_list_of_snapshots(self):
        snapshots = self.utils.get_list('snapshots')
        ok_(type(snapshots) == list, "Unable to get list of snapshots.")

    def test_create_show_delete_snapshot(self):
        # operations with volumes take a lot of storage and time, so were implemented as one sequence.

        # create volume
        vol = self.vhelper.create_volume()
        # create volume snapshot
        created_snap = self.shelper.create_snapshot(parameters={'id': vol['id']})
        # verify snapshot for correct volume was created
        ok_(created_snap['volumeId'] == vol['id'], "Unable to create volume snapshot.")

        # show snapshot
        shown_snap = self.shelper.show_snapshot(created_snap['id'])
        ok_(created_snap == shown_snap,
            "'Show snapshot' failed. Expected: %s, Actual: %s." % (created_snap, shown_snap))

        # delete snapshot
        res = self.shelper.delete_snapshot(created_snap['id'])
        ok_(res is True, "Unable to delete volume snapshot.")

# just for local debugging
if __name__ == "__main__":
    t = TestVolumeSnapshotRequests()
    t.setup_class()
    t.test_list_of_snapshots()
    t.test_create_show_delete_snapshot()
    t.teardown()


text:
from google.cloud import aiplatform_v1beta1

def sample_get_custom_job():
    # Create a client
    client = aiplatform_v1beta1.JobServiceClient()

    # Initialize request argument(s)
    request = aiplatform_v1beta1.GetCustomJobRequest(
        name="name_value",
    )

    # Make the request
    response = client.get_custom_job(request=request)

    # Handle the response
    print(response)

# [END aiplatform_v1beta1_generated_JobService_GetCustomJob_sync]


text:
require 'rails_helper'

RSpec.describe "people/index", type: :view do
  before(:each) do
    assign(:people, [
      Person.create!(
        :first_name => "First Name",
        :last_name => "Last Name"
      ),
      Person.create!(
        :first_name => "First Name",
        :last_name => "Last Name"
      )
    ])
  end

  it "renders a list of people" do
    render
    assert_select "tr>td", :text => "Last Name, First Name".to_s, :count => 2
  end
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v12/common/asset_types.proto

package com.google.ads.googleads.v12.common;

public interface DiscoveryCarouselCardAssetOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v12.common.DiscoveryCarouselCardAsset)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Asset resource name of the associated 1.91:1 marketing image. This and/or
   * square marketing image asset is required.
   *

   *
   * string marketing_image_asset = 1;
   * @return The marketingImageAsset.
   */
  java.lang.String getMarketingImageAsset();
  /**
   *

   * Asset resource name of the associated 1.91:1 marketing image. This and/or
   * square marketing image asset is required.
   *

   *
   * string marketing_image_asset = 1;
   * @return The bytes for marketingImageAsset.
   */
  com.google.protobuf.ByteString
      getMarketingImageAssetBytes();

  /**
   *

   * Asset resource name of the associated square marketing image. This
   * and/or a marketing image asset is required.
   *

   *
   * string square_marketing_image_asset = 2;
   * @return The squareMarketingImageAsset.
   */
  java.lang.String getSquareMarketingImageAsset();
  /**
   *

   * Asset resource name of the associated square marketing image. This
   * and/or a marketing image asset is required.
   *

   *
   * string square_marketing_image_asset = 2;
   * @return The bytes for squareMarketingImageAsset.
   */
  com.google.protobuf.ByteString
      getSquareMarketingImageAssetBytes();

  /**
   *

   * Asset resource name of the associated 4:5 portrait marketing image.
   *

   *
   * string portrait_marketing_image_asset = 3;
   * @return The portraitMarketingImageAsset.
   */
  java.lang.String getPortraitMarketingImageAsset();
  /**
   *

   * Asset resource name of the associated 4:5 portrait marketing image.
   *

   *
   * string portrait_marketing_image_asset = 3;
   * @return The bytes for portraitMarketingImageAsset.
   */
  com.google.protobuf.ByteString
      getPortraitMarketingImageAssetBytes();

  /**
   *

   * Required. Headline of the carousel card.
   *

   *
   * string headline = 4 [(.google.api.field_behavior) = REQUIRED];
   * @return The headline.
   */
  java.lang.String getHeadline();
  /**
   *

   * Required. Headline of the carousel card.
   *

   *
   * string headline = 4 [(.google.api.field_behavior) = REQUIRED];
   * @return The bytes for headline.
   */
  com.google.protobuf.ByteString
      getHeadlineBytes();

  /**
   *

   * Call to action text.
   *

   *
   * string call_to_action_text = 5;
   * @return The callToActionText.
   */
  java.lang.String getCallToActionText();
  /**
   *

   * Call to action text.
   *

   *
   * string call_to_action_text = 5;
   * @return The bytes for callToActionText.
   */
  com.google.protobuf.ByteString
      getCallToActionTextBytes();
}


text:
/** @jsx hJSX */
import {Rx} from '@cycle/core';
import {hJSX} from '@cycle/dom';

export default function labeledSlider(responses) {
  const initialValue$ = responses.props.get('initial').first();
  const newValue$ = responses.DOM.get('.slider', 'input')
    .map((ev) => parseInt(ev.target.value), 10);

  const value$ = initialValue$.concat(newValue$);
  const props$ = responses.props.get('*');

  const vtree$ = Rx.Observable
    .combineLatest(props$, value$, (props, value) =>

          {props.children.concat(value + props.unit)}

        <input className="slider" type="range"
          min={props.min}
          max={props.max}
          value={value} />

    );

  return {
    DOM: vtree$,
    events: {
      newValue: newValue$,
    },
  };
}


text:
import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
  /**
   * The selector is what angular internally uses
   * for `document.querySelectorAll(selector)` in our index.html
   * where, in this case, selector is the string 'home'.
   */
  selector: 'home',
  /**
   * We need to tell Angular's Dependency Injection which providers are in our app.
   */
  providers: [

  ],
  /**
   * Our list of styles in our component. We may add more to compose many styles together.
   */
  styleUrls: [ './home.component.css' ],
  /**
   * Every Angular template is first compiled by the browser before Angular runs it's compiler.
   */
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {

  public constructor (
    private _element: ElementRef,
  ) {

  }

  public ngOnInit() {

  }

}


text:
#ifndef __CCActionInstant_h__
#define __CCActionInstant_h__

#include <string>
#include <functional>

#include "CCAction.h"

NS_CC_BEGIN

/**
 *	@addtogroup actions
 *	@{
 */

/**
 *	@brief Instant actions are immediate actions. They don't have a duration like
 *	the IntervalAction actions.
 */
class CC_DLL ActionInstant : public FiniteTimeAction //<NSCopying>
{
	public :

		//
		// Overrides
		//
		virtual ActionInstant*		clone ( KDvoid ) const override = 0;
		virtual ActionInstant*		reverse ( KDvoid ) const override = 0;
		virtual KDbool				isDone ( KDvoid ) const override;
		virtual KDvoid				step ( KDfloat dt ) override;
		virtual KDvoid				update ( KDfloat fTime ) override;
};

/**
 *	@brief Show the node
 */
class CC_DLL Show : public ActionInstant
{
	public :

		/** Allocates and initializes the action */
		static Show*				create ( KDvoid );

		Show ( KDvoid ) { }

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual ActionInstant*		reverse ( KDvoid ) const override;
		virtual Show*				clone ( KDvoid ) const override;
};

/**
 *	@brief Hide the node
 */
class CC_DLL Hide : public ActionInstant
{
	public :

		/** Allocates and initializes the action */
		static Hide*				create ( KDvoid );

		Hide ( KDvoid ) { }

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual ActionInstant*		reverse ( KDvoid ) const override;
		virtual Hide*				clone ( KDvoid ) const override;
};

/**
 *	@brief Toggles the visibility of a node
 */
class CC_DLL ToggleVisibility : public ActionInstant
{
	public :

		/** Allocates and initializes the action */
		static ToggleVisibility*	create ( KDvoid );

		ToggleVisibility ( KDvoid ) { }

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual ToggleVisibility*	reverse ( KDvoid ) const override;
		virtual ToggleVisibility*	clone ( KDvoid ) const override;
};

/**
 *	@brief Remove the node
 */
class CC_DLL RemoveSelf : public ActionInstant
{
	public :

		/** create the action */
		static RemoveSelf*			create ( KDbool bIsNeedCleanUp = true );

		RemoveSelf ( KDvoid )
		{
			m_bIsNeedCleanUp = true;
		}

		/** init the action */
		KDbool						init ( KDbool bIsNeedCleanUp );

		//
		// Override
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual RemoveSelf*			clone ( KDvoid ) const override;
		virtual RemoveSelf*			reverse ( KDvoid ) const override;

	protected :

		KDbool						m_bIsNeedCleanUp;
};

/**
 *	@brief Flips the sprite horizontally
 *	@since v0.99.0
 */
class CC_DLL FlipX : public ActionInstant
{
	public :

		/** create the action */
		static FlipX*				create ( KDbool x );

		FlipX ( KDvoid )
		{
			m_bFlipX = false;
		}

		/** init the action */
		KDbool						initWithFlipX ( KDbool x );

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual FlipX*				reverse ( KDvoid ) const override;
		virtual FlipX*				clone ( KDvoid ) const override;

	protected :

		KDbool						m_bFlipX;
};

/**
 *	@brief Flips the sprite vertically
 *	@since v0.99.0
 */
class CC_DLL FlipY : public ActionInstant
{
	public :

		/** create the action */
		static FlipY*				create ( KDbool y );

		FlipY ( KDvoid )
		{
			m_bFlipY = false;
		}

		/** init the action */
		KDbool						initWithFlipY ( KDbool y );

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual FlipY*				reverse ( KDvoid ) const override;
		virtual FlipY*				clone ( KDvoid ) const override;

	protected :

		KDbool						m_bFlipY;
};

/**
 *	@brief Places the node in a certain position
 */
class CC_DLL Place : public ActionInstant //<NSCopying>
{
	public :

		Place ( KDvoid ) { }

		/** creates a Place action with a position */
		static Place*				create ( const Point& tPos );

		/** Initializes a Place action with a position */
		KDbool						initWithPosition ( const Point& tPos );

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual Place*				reverse ( KDvoid ) const override;
		virtual Place*				clone ( KDvoid ) const override;

	protected :

		Point						m_tPosition;
};

/**
 *	@brief Calls a 'callback'
 */
class CC_DLL CallFunc : public ActionInstant //<NSCopying>
{
	public :

		/**
		 *	creates the action with the callback of type std::function<void()>.
		 *	This is the preferred way to create the callback.
		 *	When this funtion bound in js or lua ,the input param will be changed
		 *	In js: var create(var func, var this, var [data]) or var create(var func)
		 *	In lua:local create(local funcID)
		 */
		static CallFunc*			create ( const std::function<KDvoid()>& pFunc );

	public :

		/**
		 *	@js ctor
		 */
		CallFunc ( KDvoid )
		{
			m_pFunction = nullptr;
		}

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual ~CallFunc ( KDvoid );

		/**
		 *	initializes the action with the std::function<void()>
		 *	@js NK
		 *	@lua NK
		 */
		KDbool						initWithFunction ( const std::function<KDvoid()>& pFunc );

		/** executes the callback */
		virtual KDvoid				execute ( KDvoid );

		//
		// Overrides
		//
		virtual KDvoid				update ( KDfloat fTime ) override;
		virtual CallFunc*			reverse ( KDvoid ) const override;
		virtual CallFunc*			clone ( KDvoid ) const override;

		inline Object*				getTargetCallback ( KDvoid )
		{
			return m_pSelectorTarget;
		}

		inline KDvoid				setTargetCallback ( Object* pSelector )
		{
			if ( pSelector != m_pSelectorTarget )
			{
				CC_SAFE_RETAIN ( pSelector );
				CC_SAFE_RELEASE ( m_pSelectorTarget );
				m_pSelectorTarget = pSelector;
			}
		}

	protected :

		/** Target that will be called */
		Object*						m_pSelectorTarget;

		union
		{
			SEL_CallFunc			m_pCallFunc;
			SEL_CallFuncN			m_pCallFuncN;
		};

		/** function that will be called */
		std::function<KDvoid()>		m_pFunction;
};

/**
 *	@brief Calls a 'callback' with the node as the first argument
 *	N means Node
 */
class CC_DLL CallFuncN : public CallFunc
{
	public :

		/**
		 *	creates the action with the callback of type std::function<void()>.
		 *	This is the preferred way to create the callback.
		 */
		static CallFuncN*			create ( const std::function<KDvoid(Node*)>& pFunc );

	public :

		CallFuncN ( KDvoid )
		{
			m_pFunctionN = nullptr;
		}

		/**
		 *	initializes the action with the std::function<void(Node*)>
		 */
		KDbool						initWithFunction ( const std::function<KDvoid(Node*)>& pFunc );

		//
		// Overrides
		//
		virtual CallFuncN*			clone ( KDvoid ) const override;
		virtual KDvoid				execute ( KDvoid ) override;

	protected :

		/** function that will be called with the "sender" as the 1st argument */
		std::function<KDvoid(Node*)>	m_pFunctionN;
};

// end of actions group
/// @}

NS_CC_END

#endif	// __CCActionInstant_h__


text:
<?php

namespace Telegram\Bot\Objects\Updates;

use Telegram\Bot\Objects\AbstractResponseObject;
use Telegram\Bot\Objects\Location;
use Telegram\Bot\Objects\User;

/**
 * Class ChosenInlineResult.
 *
 * @link https://core.telegram.org/bots/api#choseninlineresult
 *
 * @property string   $result_id          The unique identifier for the result that was chosen.
 * @property User     $from               The user that chose the result.
 * @property Location $location           (Optional). Sender location, only for bots that require user location.
 * @property string   $inline_message_id  (Optional). Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message.
 * @property string   $query              The query that was used to obtain the result.
 */
class ChosenInlineResult extends AbstractResponseObject
{
    public function relations(): array
    {
        return [
            'from'     => User::class,
            'location' => Location::class,
        ];
    }

    public function objectType(): ?string
    {
        return $this->findType(['location', 'inline_message_id']);
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package samples

import scala.util.parsing.combinator._

object SimpleWordParser extends RegexParsers {

  def word: Parser[String] = """[a-z]+""".r ^^ {
    _.toString
  }
}


text:
import sys
import os
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup
from distutils.command.install_data import install_data
try:
    from pypi2rpm.command.bdist_rpm2 import bdist_rpm2
except:
    from distutils.command.bdist_rpm import bdist_rpm as bdist_rpm2

class osx_install_data(install_data):
    # On MacOS, the platform-specific lib dir is /System/Library/Framework/Python/.../
    # which is wrong. Python 2.5 supplied with MacOS 10.5 has an Apple-specific fix
    # for this in distutils.command.install_data#306. It fixes install_lib but not
    # install_data, which is why we roll our own install_data class.

    def finalize_options(self):
        # By the time finalize_options is called, install.install_lib is set to the
        # fixed directory, so we set the installdir to install_lib. The
        # install_data class uses ('install_data', 'install_dir') instead.
        self.set_undefined_options('install', ('install_lib', 'install_dir'))
        install_data.finalize_options(self)

if sys.platform == "darwin":
    cmdclasses = {'install_data': osx_install_data}
else:
    cmdclasses = {'install_data': install_data}
cmdclasses["bdist_rpm2"] = bdist_rpm2

def fullsplit(path, result=None):
    """
    Split a pathname into components (the opposite of os.path.join) in a
    platform-neutral way.
    """
    if result is None:
        result = []
    head, tail = os.path.split(path)
    if head == '':
        return [tail] + result
    if head == path:
        return result
    return fullsplit(head, [tail] + result)

def is_not_module(filename):
    return os.path.splitext(f)[1] not in ['.py', '.pyc', '.pyo']

packages = []
data_files = []
for git_dir in ['crucible']:
    for dirpath, dirnames, filenames in os.walk(git_dir):
        # Ignore dirnames that start with '.'
        for i, dirname in enumerate(dirnames):
            if dirname.startswith('.') and not dirname.startswith(".git"): del dirnames[i]
        if '__init__.py' in filenames:
            packages.append('.'.join(fullsplit(dirpath)))
            data = [f for f in filenames if is_not_module(f)]
            if data:
                data_files.append([dirpath, [os.path.join(dirpath, f) for f in data]])
        elif filenames:
            data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames]])

args = {
    'name': 'git-crucible',
    'version': __import__("crucible").__version__,
    'url' : "http://github.com/rckclmbr/git-crucible",
    'description': "Git extension that creates reviews in Crucible straight from the command line.",
    'long_description': """Git extension that creates reviews in Crucible straight from the command line.""",
    'author': 'Josh Braegger',
    'author_email': 'rckclmbr@gmail.com',
    'maintainer': 'Josh Braegger',
    'maintainer_email': 'rckclmbr@gmail.com',
    'license': 'BSD',
    'packages': packages,
    'data_files': data_files,
    'scripts': ["bin/git-crucible"],
    'cmdclass': cmdclasses,
    'tests_require': ["nose", "mock"],
    'test_suite': "nose.collector",
    'install_requires': "argparse",
    'classifiers': [
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Environment :: Console',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ]
}

setup(**args)


text:
FOUNDATION_EXPORT double TableAdapterVersionNumber;

//! Project version string for TableAdapter.
FOUNDATION_EXPORT const unsigned char TableAdapterVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <TableAdapter/PublicHeader.h>


text:
#ifndef __ALLOCATOR_HPP__
#define __ALLOCATOR_HPP__

#include "common/hashmap.hpp"
#include "common/resources.hpp"

#include "master/master.hpp"

namespace mesos {
namespace internal {
namespace master {

// Basic model of an allocator: resources are allocated to a framework
// in the form of offers. A framework can refuse some resources in
// offers and run tasks in others. Resources can be recovered from a
// framework when tasks finish/fail (or are lost due to a slave
// failure) or when an offer is rescinded.

class Allocator {
public:
  virtual ~Allocator() {}

  virtual void initialize(Master* _master) {}

  virtual void frameworkAdded(Framework* framework) {}

  virtual void frameworkRemoved(Framework* framework) {}

  virtual void slaveAdded(Slave* slave) {}

  virtual void slaveRemoved(Slave* slave) {}

  virtual void resourcesRequested(
      const FrameworkID& frameworkId,
      const std::vector<ResourceRequest>& requests) {}

  // Whenever resources offered to a framework go unused (e.g.,
  // refused) the master invokes this callback.
  virtual void resourcesUnused(
      const FrameworkID& frameworkId,
      const SlaveID& slaveId,
      const Resources& resources) {}

  // Whenever resources are "recovered" in the cluster (e.g., a task
  // finishes, an offer is removed because a framework has failed or
  // is failing over) the master invokes this callback.
  virtual void resourcesRecovered(
      const FrameworkID& frameworkId,
      const SlaveID& slaveId,
      const Resources& resources) {}

  // Whenever a framework that has filtered resources want's to revive
  // offers for those resources the master invokes this callback.
  virtual void offersRevived(Framework* framework) {}

  virtual void timerTick() {}

  virtual void gotUsage(const UsageMessage& usage) {}
};

} // namespace master {
} // namespace internal {
} // namespace mesos {

#endif // __ALLOCATOR_HPP__


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Lidgren.Network")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Lidgren.Network")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]
[assembly: Guid("78f2a988-46e1-4fc4-b7b4-dd2cbe46da6a")]

[assembly: AssemblyVersion("0.28.0")]
[assembly: AssemblyFileVersion("0.28.0")]
[assembly: AssemblyInformationalVersion("0.28.0-compiled")]

[assembly: System.CLSCompliant(true)]
[assembly: InternalsVisibleTo("LmpCommonTest")]


text: CKEDITOR.plugins.setLang("preview","eu",{preview:"Aurrebista"});


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>README.rdoc</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="../css/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="../css/main.css" type="text/css" media="screen" />

            README.rdoc

README.rdoc

Last modified: 2011-05-26 23:43:53 +0000

Welcome to Rails

Rails is a web-application framework that includes everything needed to
create database-backed web applications according to the Model-View-Control
pattern.

This pattern splits the view (also called the presentation) into
“dumb” templates that are primarily responsible for inserting
pre-built data in between HTML tags. The model contains the
“smart” domain objects (such as Account, Product, Person, Post)
that holds all the business logic and knows how to persist themselves to a
database. The controller handles the incoming requests (such as Save New
Account, Update Product, Show Post) by manipulating the model and directing
data to the view.

In Rails, the model is handled by what’s called an object-relational
mapping layer entitled Active Record. This layer allows you to present the
data from database rows as objects and embellish these data objects with
business logic methods. You can read more about Active Record in its README.

The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two
layers are bundled in a single package due to their heavy interdependence.
This is unlike the relationship between the Active Record and Action Pack
that is much more separate. Each of these packages can be used
independently outside of Rails. You can read more about Action Pack in its
README.

Getting Started

Install Rails at the command prompt if you haven’t yet:

 gem install rails

At the command prompt, create a new Rails application:

 rails new myapp

where “myapp” is the application name.

Change directory to <tt>myapp</tt> and start the web server:

 cd myapp; rails server

Run with <tt>--help</tt> for options.

Go to localhost:3000/ and you’ll
see:

 "Welcome aboard: You're riding Ruby on Rails!"

Follow the guidelines to start developing your application. You can find
the following resources handy:

The README file created within your application.

The Getting
Started with Rails.

The Ruby on Rails Tutorial.

The Ruby on
Rails guides.

The API documentation.

Contributing

We encourage you to contribute to Ruby on Rails! Please check out the Contributing
to Rails guide for guidelines about how to proceed. Join us!

License

Ruby on Rails is released under the MIT license.


text:
package androidx.camera.view;

import android.graphics.Bitmap;
import android.util.Size;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.camera.core.SurfaceRequest;

import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.Executor;

/**
 * Wraps the underlying handling of the {@link android.view.Surface} used for preview, which is
 * done using either a {@link android.view.TextureView} (see {@link TextureViewImplementation})
 * or a {@link android.view.SurfaceView} (see {@link SurfaceViewImplementation}).
 */
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
abstract class PreviewViewImplementation {

    @Nullable
    Size mResolution;

    @NonNull
    FrameLayout mParent;

    @NonNull
    private final PreviewTransformation mPreviewTransform;

    private boolean mWasSurfaceProvided = false;

    abstract void initializePreview();

    @Nullable
    abstract View getPreview();

    PreviewViewImplementation(@NonNull FrameLayout parent,
            @NonNull PreviewTransformation previewTransform) {
        mParent = parent;
        mPreviewTransform = previewTransform;
    }

    /**
     * Starts to execute the {@link SurfaceRequest} by providing a Surface.
     *
     *
A listener can be set optionally to be notified when the provided Surface is not in use
     * any more or the SurfaceRequest is cancelled before providing a Surface. This can be used
     * as a signal that SurfaceRequest (and the Preview) is no longer using PreviewView and we
     * can do some cleanup. The listener will be invoked on main thread.
     */
    abstract void onSurfaceRequested(@NonNull SurfaceRequest surfaceRequest,
            @Nullable OnSurfaceNotInUseListener onSurfaceNotInUseListener);

    /**
     * Invoked when the preview needs to be adjusted, either because the layout bounds of the
     * preview's container {@link PreviewView} have changed, or the {@link PreviewView.ScaleType}
     * has changed.
     *

     * Corrects and adjusts the preview using the latest {@link PreviewView.ScaleType} and
     * display properties such as the display orientation and size.
     */
    void redrawPreview() {
        View preview = getPreview();
        // Only calls setScaleX/Y and setTranslationX/Y after the surface has been provided.
        // Otherwise, it might cause some preview stretched issue when using PERFORMANCE mode
        // together with Compose UI. For more details, please see b/183864890.
        if (preview == null || !mWasSurfaceProvided) {
            return;
        }
        mPreviewTransform.transformView(new Size(mParent.getWidth(),
                mParent.getHeight()), mParent.getLayoutDirection(), preview);
    }

    /** Invoked after a {@link android.view.Surface} has been provided to the camera for preview. */
    void onSurfaceProvided() {
        mWasSurfaceProvided = true;
        redrawPreview();
    }

    /** Invoked when onAttachedToWindow happens in the PreviewView. */
    abstract void onAttachedToWindow();

    /** Invoked when onDetachedFromWindow happens in the PreviewView */
    abstract void onDetachedFromWindow();

    /**
     * Returns a {@link ListenableFuture} which will complete when the next frame is shown.
     *
     *
For implementation that does not support frame update event, the returned future will
     * complete immediately.
     */
    @NonNull
    abstract ListenableFuture<Void> waitForNextFrame();

    @Nullable
    Bitmap getBitmap() {
        final Bitmap bitmap = getPreviewBitmap();
        if (bitmap == null) {
            return null;
        }
        return mPreviewTransform.createTransformedBitmap(bitmap,
                new Size(mParent.getWidth(), mParent.getHeight()),
                mParent.getLayoutDirection());
    }

    @Nullable
    abstract Bitmap getPreviewBitmap();

    void setFrameUpdateListener(
            @NonNull Executor executor, @NonNull PreviewView.OnFrameUpdateListener listener) {}

    /**
     * Listener to be notified when the provided Surface is no longer in use or the request is
     * cancelled before a Surface is provided.
     */
    interface OnSurfaceNotInUseListener {
        void onSurfaceNotInUse();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Man. Brit. Discomyc. (London) 136 (1887)

#### Original name
Hymenoscyphus scutula f. scutula

### Remarks
null


text:
/* 	led_test.c
 * 	###############################################################################
 *
 * 	A simple software application to test the functionality of the led_controller
 * 	IP core. The value of a counter is output to the LEDs.
 *
 * 	###############################################################################
 * 	v1.0 -- 25/10/2013
 * 	############################################################################### */

/* Generated driver function for led_controller IP core */
#include "led_controller.h"
#include "xparameters.h"
#include "xil_printf.h"
#include "xil_io.h"

// Define maximum LED value (2^8)-1 = 255
#define LED_LIMIT 255
// Define delay length
#define DELAY 10000000

/* 	Define the base memory address of the led_controller IP core */
#define LED_BASE XPAR_LED_CONTROLLER_0_S00_AXI_BASEADDR

/* main function */
int main(void){
	/* unsigned 32-bit variables for storing current LED value */
	u32 led_val = 0;
	int i=0;

	xil_printf("led_controller IP test begin.\r\n");
	xil_printf("--------------------------------------------\r\n\n");

	/* Loop forever */
	while(1){
			while(led_val<=LED_LIMIT){
				/* Print value to terminal */
				xil_printf("LED value: %d\r\n", led_val);
				/* Write value to led_controller IP core using generated driver function */
				LED_CONTROLLER_mWriteReg(LED_BASE, 0, led_val);
				/* increment LED value */
				led_val++;
				/* run a simple delay to allow changes on LEDs to be visible */
				for(i=0;i<DELAY;i++);
			}
			/* Reset LED value to zero */
			led_val = 0;
		}
	return 1;
}


text:
using System;

class MethodExample
{
    static void PrintLogo()
    {
        string x = Console.ReadLine();
        Console.WriteLine(x);
        Console.WriteLine("www.telerik.com");
    }

    static void Main()
    {
        PrintLogo();
    }
}


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Maker;

use Sonata\AdminBundle\Command\Validators;
use Sonata\AdminBundle\Manipulator\ServicesManipulator;
use Sonata\AdminBundle\Model\ModelManagerInterface;
use Symfony\Bundle\MakerBundle\ConsoleStyle;
use Symfony\Bundle\MakerBundle\DependencyBuilder;
use Symfony\Bundle\MakerBundle\Generator;
use Symfony\Bundle\MakerBundle\InputConfiguration;
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
use Symfony\Bundle\MakerBundle\Str;
use Symfony\Bundle\MakerBundle\Util\ClassNameDetails;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\DependencyInjection\Container;

/**
 * @author Gaurav Singh Faujdar <faujdar@gmail.com>
 */
final class AdminMaker extends AbstractMaker
{
    private string $projectDirectory;

    /**
     * @var array<string, ModelManagerInterface<object>>
     */
    private array $availableModelManagers;

    private string $skeletonDirectory;

    /**
     * @phpstan-var class-string
     *
     * @psalm-suppress PropertyNotSetInConstructor
     * @phpstan-ignore-next-line
     *
     * @see AdminMaker::configure
     */
    private string $modelClass;

    /**
     * @psalm-suppress PropertyNotSetInConstructor
     * @phpstan-ignore-next-line
     *
     * @see AdminMaker::configure
     */
    private string $modelClassBasename;

    /**
     * @psalm-suppress PropertyNotSetInConstructor
     * @phpstan-ignore-next-line
     *
     * @see AdminMaker::configure
     */
    private string $adminClassBasename;

    private ?string $controllerClassBasename = null;

    /**
     * @psalm-suppress PropertyNotSetInConstructor
     * @phpstan-ignore-next-line
     *
     * @see AdminMaker::configure
     */
    private string $managerType;

    /**
     * @var ModelManagerInterface<object>
     *
     * @psalm-suppress PropertyNotSetInConstructor
     * @phpstan-ignore-next-line
     *
     * @see AdminMaker::configure
     */
    private ModelManagerInterface $modelManager;

    private string $defaultController;

    /**
     * @param array<string, ModelManagerInterface<object>> $modelManagers
     */
    public function __construct(string $projectDirectory, array $modelManagers, string $defaultController)
    {
        $this->projectDirectory = $projectDirectory;
        $this->availableModelManagers = $modelManagers;
        $this->skeletonDirectory = sprintf('%s/../Resources/skeleton', __DIR__);
        $this->defaultController = $defaultController;
    }

    public static function getCommandName(): string
    {
        return 'make:sonata:admin';
    }

    public static function getCommandDescription(): string
    {
        return 'Generates an admin class based on the given model class';
    }

    public function configureCommand(Command $command, InputConfiguration $inputConfig): void
    {
        $command
            ->addArgument('model', InputArgument::REQUIRED, 'The fully qualified model class')
            ->addOption('admin', 'a', InputOption::VALUE_OPTIONAL, 'The admin class basename')
            ->addOption('controller', 'c', InputOption::VALUE_OPTIONAL, 'The controller class basename')
            ->addOption('manager', 'm', InputOption::VALUE_OPTIONAL, 'The model manager type')
            ->addOption('services', 's', InputOption::VALUE_OPTIONAL, 'The services YAML file')
            ->addOption('id', 'i', InputOption::VALUE_OPTIONAL, 'The admin service ID');

        $inputConfig->setArgumentAsNonInteractive('model');
    }

    public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
    {
        $io->section('Welcome to the Sonata Admin');
        $this->modelClass = $io->ask(
            'The fully qualified model class',
            $input->getArgument('model'),
            [Validators::class, 'validateClass']
        );
        $this->modelClassBasename = \array_slice(explode('\\', $this->modelClass), -1)[0];

        $this->adminClassBasename = $io->ask(
            'The admin class basename',
            $input->getOption('admin') ?? sprintf('%sAdmin', $this->modelClassBasename),
            [Validators::class, 'validateAdminClassBasename']
        );
        if (\count($this->availableModelManagers) > 1) {
            $managerTypes = array_keys($this->availableModelManagers);
            $this->managerType = $io->choice('The manager type', $managerTypes, $managerTypes[0]);

            $input->setOption('manager', $this->managerType);
        }
        if ($io->confirm('Do you want to generate a controller?', false)) {
            $this->controllerClassBasename = $io->ask(
                'The controller class basename',
                $input->getOption('controller') ?? sprintf('%sAdminController', $this->modelClassBasename),
                [Validators::class, 'validateControllerClassBasename']
            );
            $input->setOption('controller', $this->controllerClassBasename);
        }
        if ($io->confirm('Do you want to update the services YAML configuration file?', true)) {
            $path = sprintf('%s/config/', $this->projectDirectory);
            $servicesFile = $io->ask(
                'The services YAML configuration file',
                $input->getOption('services') ?? (is_file($path.'admin.yaml') ? 'admin.yaml' : 'services.yaml'),
                [Validators::class, 'validateServicesFile']
            );
            $id = $io->ask(
                'The admin service ID',
                $this->getAdminServiceId($this->adminClassBasename),
                [Validators::class, 'validateServiceId']
            );
            $input->setOption('services', $servicesFile);
            $input->setOption('id', $id);
        }
        $input->setArgument('model', $this->modelClass);
        $input->setOption('admin', $this->adminClassBasename);
    }

    /**
     * Configure any library dependencies that your maker requires.
     */
    public function configureDependencies(DependencyBuilder $dependencies): void
    {
    }

    /**
     * Called after normal code generation: allows you to do anything.
     */
    public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
    {
        $this->configure($input);

        $adminClassNameDetails = $generator->createClassNameDetails(
            $this->adminClassBasename,
            'Admin\\',
            'Admin'
        );

        /** @phpstan-var class-string $adminClassFullName */
        $adminClassFullName = $adminClassNameDetails->getFullName();
        $this->generateAdmin($io, $generator, $adminClassNameDetails);

        $controllerClassFullName = '';
        if (null !== $this->controllerClassBasename) {
            $controllerClassNameDetails = $generator->createClassNameDetails(
                $this->controllerClassBasename,
                'Controller\\',
                'Controller'
            );

            $this->generateController($io, $generator, $controllerClassNameDetails);

            $controllerClassFullName = $controllerClassNameDetails->getFullName();
        }

        $this->generateService($input, $io, $adminClassFullName, $controllerClassFullName);
    }

    private function getAdminServiceId(string $adminClassBasename): string
    {
        return Container::underscore(sprintf(
            'admin.%s',
            str_replace('\\', '.', 'Admin' === substr($adminClassBasename, -5) ?
                substr($adminClassBasename, 0, -5) : $adminClassBasename)
        ));
    }

    /**
     * @phpstan-param class-string $adminClassFullName
     */
    private function generateService(
        InputInterface $input,
        ConsoleStyle $io,
        string $adminClassFullName,
        string $controllerClassFullName
    ): void {
        $servicesFile = $input->getOption('services');
        if (null !== $servicesFile) {
            $file = sprintf('%s/config/%s', $this->projectDirectory, $servicesFile);
            $servicesManipulator = new ServicesManipulator($file);
            $controllerName = null !== $this->controllerClassBasename ? $controllerClassFullName : '~';

            $id = $input->getOption('id') ?? $this->getAdminServiceId($this->adminClassBasename);

            $servicesManipulator->addResource(
                $id,
                $this->modelClass,
                $adminClassFullName,
                $controllerName,
                substr($this->managerType, \strlen('sonata.admin.manager.'))
            );

            $io->writeln(sprintf(
                '%sThe service "<info>%s</info>" has been appended to the file <info>"%s</info>".',
                \PHP_EOL,
                $id,
                realpath($file)
            ));
        }
    }

    private function generateController(
        ConsoleStyle $io,
        Generator $generator,
        ClassNameDetails $controllerClassNameDetails
    ): void {
        $controllerClassFullName = $controllerClassNameDetails->getFullName();
        $generator->generateClass(
            $controllerClassFullName,
            sprintf('%s/AdminController.tpl.php', $this->skeletonDirectory),
            [
                'default_controller' => $this->defaultController,
                'default_controller_short_name' => Str::getShortClassName($this->defaultController),
            ]
        );
        $generator->writeChanges();
        $io->writeln(sprintf(
            '%sThe controller class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
            \PHP_EOL,
            $controllerClassNameDetails->getShortName(),
            $controllerClassFullName
        ));
    }

    private function generateAdmin(
        ConsoleStyle $io,
        Generator $generator,
        ClassNameDetails $adminClassNameDetails
    ): void {
        $adminClassFullName = $adminClassNameDetails->getFullName();

        $fields = $this->modelManager->getExportFields($this->modelClass);
        $fieldString = '';
        foreach ($fields as $field) {
            $fieldString = $fieldString.sprintf('%12s', '')."->add('".$field."')".\PHP_EOL;
        }

        $fieldString .= sprintf('%12s', '');

        $generator->generateClass(
            $adminClassFullName,
            sprintf('%s/Admin.tpl.php', $this->skeletonDirectory),
            ['fields' => $fieldString]
        );

        $generator->writeChanges();

        $io->writeln(sprintf(
            '%sThe admin class "<info>%s</info>" has been generated under the file "<info>%s</info>".',
            \PHP_EOL,
            $adminClassNameDetails->getShortName(),
            $adminClassFullName
        ));
    }

    private function configure(InputInterface $input): void
    {
        $this->modelClass = Validators::validateClass($input->getArgument('model'));
        $this->modelClassBasename = (new \ReflectionClass($this->modelClass))->getShortName();
        $this->adminClassBasename = Validators::validateAdminClassBasename(
            $input->getOption('admin') ?? sprintf('%sAdmin', $this->modelClassBasename)
        );

        $this->controllerClassBasename = $input->getOption('controller');
        if (null !== $this->controllerClassBasename) {
            $this->controllerClassBasename = Validators::validateControllerClassBasename($this->controllerClassBasename);
        }

        if (0 === \count($this->availableModelManagers)) {
            throw new \InvalidArgumentException('There are no model managers registered.');
        }

        $this->managerType = $input->getOption('manager') ?? array_keys($this->availableModelManagers)[0];
        $this->modelManager = $this->availableModelManagers[$this->managerType] ?? current($this->availableModelManagers);
    }
}


text:
package br.eti.hmagalhaes.bomclima.model.dao;

import java.util.List;

import br.eti.hmagalhaes.bomclima.model.dao.exception.NonUniqueResultException;
import br.eti.hmagalhaes.bomclima.model.dto.UsuarioSearchParams;
import br.eti.hmagalhaes.bomclima.model.entity.Usuario;

public interface UsuarioDAO extends GenericDAO<Usuario, Integer> {

	/**
	 * @throws NonUniqueResultException Quando mais de um registro for
	 *             encontrado com o mesmo login.
	 */
	Usuario findByLogin(String login) throws NonUniqueResultException;

	List<Usuario> find(UsuarioSearchParams params);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using PlayMe.Common.Model;
using PlayMe.Data;
using PlayMe.Server.Interfaces;
using PlayMe.Server.Player;
using PlayMe.Server.SoundBoard;
using PlayMe.UnitTest.Plumbing;

namespace PlayMe.UnitTest.PlayMe.Server
{
    [TestFixture]
    public class SoundBoard_Tests : TestBase<SoundBoardService>
    {
        [Test]
        public void if_not_enabled_PlayVetoSound_plays_nothing()
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();
            var playerMock = GetMock<IStreamedPlayer>();
            settingsMock.Setup(m => m.IsEnabled).Returns(false);

            //act
            ClassUnderTest.PlayVetoSound();

            //assert
            playerMock.Verify(m => m.PlayFromFile(It.IsAny<string>()), Times.Never());
        }

        [Test]
        public void if_first_skip_of_the_day_PlayVetoSound_plays_first_blood()
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();

            settingsMock.Setup(m => m.IsEnabled).Returns(true);
            settingsMock.Setup(m => m.SecondsBetweenSkipThreshold).Returns(10);

            var pathBuilderMock = GetMock<IPathBuilder>();
            pathBuilderMock.Setup(m => m.BuildFilePath("firstblood.wav")).Returns("\\\\apath\\sounds\\firstbloo.wav");

            var nowMock = GetMock<INowHelper>();
            nowMock.Setup(m => m.Now).Returns(new DateTime(2013, 1, 2));

            var dataServiceMock = GetMock<IDataService<SoundBoardInfo>>();
            dataServiceMock.Setup(m => m.GetAll())
                           .Returns(new List<SoundBoardInfo>(){new SoundBoardInfo {lastSkippedSongTime = new DateTime(2013, 1, 1).ToUniversalTime()}}.AsQueryable());

            var playerMock = GetMock<IStreamedPlayer>();

            //act
            ClassUnderTest.PlayVetoSound();

            //assert
            playerMock.Verify(m => m.PlayFromFile("\\\\apath\\sounds\\firstbloo.wav"), Times.Once());
        }

        [Test]
        public void if_not_first_skip_of_the_day_PlayVetoSound_doesnt_play_first_blood()
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();

            settingsMock.Setup(m => m.IsEnabled).Returns(true);

            var pathBuilderMock = GetMock<IPathBuilder>();
            pathBuilderMock.Setup(m => m.BuildFilePath("firstblood.wav")).Returns("\\\\apath\\sounds\\firstbloo.wav");

            var nowMock = GetMock<INowHelper>();
            nowMock.Setup(m => m.Now).Returns(new DateTime(2013, 1, 1));

            var dataServiceMock = GetMock<IDataService<SoundBoardInfo>>();
            dataServiceMock.Setup(m => m.GetAll())
                           .Returns(new List<SoundBoardInfo>() { new SoundBoardInfo { lastSkippedSongTime = new DateTime(2013, 1, 1).ToUniversalTime() } }.AsQueryable());

            var playerMock = GetMock<IStreamedPlayer>();

            //act
            ClassUnderTest.PlayVetoSound();

            //assert
            playerMock.Verify(m => m.PlayFromFile("\\\\apath\\sounds\\firstbloo.wav"), Times.Never());
        }

        [TestCase(1, "doublekill.wav")]
        [TestCase(4, "ultrakill.wav")]
        public void if_skipped_PlayVetoSound_increments_skip_count_and_plays_correct_sound(int lastSkipCount, string fileName)
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();

            settingsMock.Setup(m => m.IsEnabled).Returns(true);
            settingsMock.Setup(m => m.SecondsBetweenSkipThreshold).Returns(10);
            var pathBuilderMock = GetMock<IPathBuilder>();
            pathBuilderMock.Setup(m => m.BuildFilePath(fileName)).Returns("\\\\apath\\sounds\\" + fileName);

            var nowMock = GetMock<INowHelper>();
            nowMock.Setup(m => m.Now).Returns(new DateTime(2013, 1, 2, 10, 0, 5));

            var dataServiceMock = GetMock<IDataService<SoundBoardInfo>>();
            dataServiceMock.Setup(m => m.GetAll())
                           .Returns(new List<SoundBoardInfo>() { new SoundBoardInfo { lastSkippedSongTime = new DateTime(2013, 1, 2 , 10, 0, 0).ToUniversalTime(), skippedSongsCount = lastSkipCount} }.AsQueryable());

            var playerMock = GetMock<IStreamedPlayer>();

            //act
            ClassUnderTest.PlayVetoSound();

            //assert
            dataServiceMock.Verify(m => m.InsertOrUpdate(It.Is<SoundBoardInfo>(c => c.skippedSongsCount == lastSkipCount + 1)), Times.Once());
            playerMock.Verify(m => m.PlayFromFile("\\\\apath\\sounds\\" + fileName), Times.Once());
            playerMock.Verify(m => m.PlayFromFile("\\\\apath\\sounds\\firstbloo.wav"), Times.Never());
        }

        [Test]
        public void if_skipped_maximum_times_PlayVetoSound_plays_no_sound()
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();

            settingsMock.Setup(m => m.IsEnabled).Returns(true);
            settingsMock.Setup(m => m.SecondsBetweenSkipThreshold).Returns(10);

            var pathBuilderMock = GetMock<IPathBuilder>();
            pathBuilderMock.Setup(m => m.BuildFilePath(It.IsAny<string>())).Returns("\\\\apath\\sounds\\filename.wav");

            var nowMock = GetMock<INowHelper>();
            nowMock.Setup(m => m.Now).Returns(new DateTime(2013, 1, 2, 10, 0, 5));

            var dataServiceMock = GetMock<IDataService<SoundBoardInfo>>();
            dataServiceMock.Setup(m => m.GetAll())
                           .Returns(new List<SoundBoardInfo>() { new SoundBoardInfo { lastSkippedSongTime = new DateTime(2013, 1, 2, 10, 0, 0).ToUniversalTime(), skippedSongsCount = 11 } }.AsQueryable());

            var playerMock = GetMock<IStreamedPlayer>();

            //act
            ClassUnderTest.PlayVetoSound();

            //assert
            playerMock.Verify(m => m.PlayFromFile(It.IsAny<string>()), Times.Never());
        }

        [Test]
        public void if_skipped_outside_seconds_between_skip_threshold_PlayVetoSound_resets_skipCount_and_plays_no_sound()
        {
            //arrange
            var settingsMock = GetMock<ISoundBoardSettings>();

            settingsMock.Setup(m => m.IsEnabled).Returns(true);
            settingsMock.Setup(m => m.SecondsBetweenSkipThreshold).Returns(10);

            var pathBuilderMock = GetMock<IPathBuilder>();
            pathBuilderMock.Setup(m => m.BuildFilePath(It.IsAny<string>())).Returns("\\\\apath\\sounds\\filename.wav");

            var nowMock = GetMock<INowHelper>();
            nowMock.Setup(m => m.Now).Returns(new DateTime(2013, 1, 2, 10, 0, 15)); //5 seconds outside of threshold

            var soundInfo = new SoundBoardInfo
                                {
                                    lastSkippedSongTime = new DateTime(2013, 1, 2, 10, 0, 0).ToUniversalTime(),
                                    skippedSongsCount = 3
                                };
            var dataServiceMock = GetMock<IDataService<SoundBoardInfo>>();
            dataServiceMock.Setup(m => m.GetAll())
                           .Returns(new List<SoundBoardInfo>() { soundInfo }.AsQueryable());

            var playerMock = GetMock<IStreamedPlayer>();

            //act
            ClassUnderTest.PlayVetoSound();
            soundInfo.skippedSongsCount = 1;
            //assert
            dataServiceMock.Verify(m => m.InsertOrUpdate(It.Is<SoundBoardInfo>(c=>c.skippedSongsCount == 1)), Times.Once());
            playerMock.Verify(m => m.PlayFromFile(It.IsAny<string>()), Times.Never());
        }
    }
}


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

namespace ASC.Data.Backup.Tasks.Modules
{
    internal static class ModuleProvider
    {
        public static readonly List<IModuleSpecifics> AllModules = new List<IModuleSpecifics>
            {
                new TenantsModuleSpecifics(),
                new AuditModuleSpecifics(),
                new CommunityModuleSpecifics(),
                new CalendarModuleSpecifics(),
                new ProjectsModuleSpecifics(),
                new CrmModuleSpecifics(),
                new FilesModuleSpecifics(),
                new MailModuleSpecifics(),
                new CrmModuleSpecifics2(),
                new FilesModuleSpecifics2(),
                new CrmInvoiceModuleSpecifics(),
                new WebStudioModuleSpecifics(),
                new CoreModuleSpecifics()
            }
            .ToList();

        public static IModuleSpecifics GetByStorageModule(string storageModuleName, string storageDomainName = null)
        {
            switch (storageModuleName)
            {
                case "files":
                    return AllModules.FirstOrDefault(m => m.ModuleName == ModuleName.Files);

                case "projects":
                    return AllModules.FirstOrDefault(m => m.ModuleName == ModuleName.Projects);

                case "crm":
                    return AllModules.FirstOrDefault(m => m.ModuleName == (storageDomainName == "mail_messages" ? ModuleName.Crm2 : ModuleName.Crm));

                case "forum":
                    return AllModules.FirstOrDefault(m => m.ModuleName == ModuleName.Community);

                case "mailaggregator":
                    return AllModules.FirstOrDefault(m => m.ModuleName == ModuleName.Mail);

                default:
                    return null;
            }
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Exodus 4D
 * Date: 02.03.2019
 * Time: 16:44
 */

namespace Exodus4D\Pathfinder\Controller\Api\Rest;

use Exodus4D\Pathfinder\Model\Pathfinder;
use Exodus4D\Pathfinder\Lib\Config;

class SignatureHistory extends AbstractRestController {

    /**
     * get historic signature data
     * @param \Base $f3
     * @param $params
     * @throws \Exception
     */
    public function get(\Base $f3, $params){
        $historyData = [];

        if($systemId = (int)$params['id']){
            $activeCharacter = $this->getCharacter();

            /**
             * @var $system Pathfinder\SystemModel
             */
            $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel');
            $system->getById($systemId);

            if($system->hasAccess($activeCharacter)){
                $historyDataAll = $system->getSignaturesHistory();
                foreach($historyDataAll as $historyEntry){
                    $label = [
                        $historyEntry['character']->name,
                        $historyEntry['action'],
                        count($historyEntry['signatures']),
                        Config::formatTimeInterval((int)(microtime(true) - $historyEntry['stamp']))
                    ];

                    $historyData[] = [
                        'value' => md5((string)$historyEntry['stamp']),
                        'text' => implode('%%', $label)
                    ];
                }
            }
        }

        $this->out($historyData);
    }

    /**
     * put (load) historic signature data
     * @param \Base $f3
     * @throws \Exception
     */
    public function put(\Base $f3){
        $requestData = $this->getRequestData($f3);
        $signaturesData = [];

        if(
            ($systemId = (int)$requestData['systemId']) &&
            ($stamp = (string)$requestData['stamp'])
        ){
            $activeCharacter = $this->getCharacter();

            /**
             * @var $system Pathfinder\SystemModel
             */
            $system = Pathfinder\AbstractPathfinderModel::getNew('SystemModel');
            $system->getById($systemId, 0);
            if($system->hasAccess($activeCharacter)){
                if($historyEntry = $system->getSignatureHistoryEntry($stamp)){
                    $updateSignaturesHistory = false;

                    // history entry found for $stamp -> format signatures data
                    // -> same format as if they would come from client for save
                    foreach($historyEntry['signatures'] as $signatureData){
                        $data = [
                            'id'            => (int)$signatureData->id,
                            'groupId'       => (int)$signatureData->groupId,
                            'typeId'        => (int)$signatureData->typeId,
                            'connectionId'  => (int)$signatureData->connectionId,
                            'name'          => (string)$signatureData->name,
                            'description'   => (string)$signatureData->description,
                        ];

                        $signature = $system->getSignatureById($data['id']);

                        if(is_null($signature)){
                            $signature = $system->getNewSignature();
                        }

                        $signature->setData($data);
                        $signature->save($activeCharacter);
                        $signaturesData[] = $signature->getData();
                        $updateSignaturesHistory = true;

                        $signature->reset();
                    }

                    // delete "old" signatures ------------------------------------------------------------------------
                    $updatedSignatureIds = array_column($signaturesData, 'id');
                    $signatures = $system->getSignatures();
                    foreach($signatures as $signature){
                        if(!in_array($signature->_id, $updatedSignatureIds)){
                            if($signature->delete()){
                                $updateSignaturesHistory = true;
                            }
                        }
                    }

                    if($updateSignaturesHistory){
                        // signature count changed -> clear fieldsCache[]
                        $system->reset(false);
                        $system->updateSignaturesHistory($activeCharacter, 'undo');
                    }
                }
            }
        }

        $this->out($signaturesData);
    }
}


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

package org.chromium.ui.base;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;

import org.chromium.base.ContextUtils;
import org.chromium.base.LocaleUtils;
import org.chromium.base.Log;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;

import java.io.IOException;
import java.util.Arrays;

/**
 * This class provides the resource bundle related methods for the native
 * library.
 *
 * IMPORTANT: Clients that use {@link ResourceBundle} and/or
 * {@link org.chromium.ui.resources.ResourceExtractor} MUST call either
 * {@link ResourceBundle#setAvailablePakLocales(String[], String[])} or
 * {@link ResourceBundle#setNoAvailableLocalePaks()} before calling the getters in this class.
 */
@JNINamespace("ui")
public final class ResourceBundle {
    private static final String TAG = "ResourceBundle";
    private static String[] sCompressedLocales;
    private static String[] sUncompressedLocales;

    private ResourceBundle() {}

    /**
     * Called when there are no locale pak files available.
     */
    @CalledByNative
    public static void setNoAvailableLocalePaks() {
        assert sCompressedLocales == null && sUncompressedLocales == null;
        sCompressedLocales = new String[] {};
        sUncompressedLocales = new String[] {};
    }

    /**
     * Sets the available compressed and uncompressed locale pak files.
     * @param compressed Locales that have compressed pak files.
     * @param uncompressed Locales that have uncompressed pak files.
     */
    public static void setAvailablePakLocales(String[] compressed, String[] uncompressed) {
        assert sCompressedLocales == null && sUncompressedLocales == null;
        sCompressedLocales = compressed;
        sUncompressedLocales = uncompressed;
    }

    /**
     * Return the array of locales that have compressed pak files. Do not modify the array.
     * @return The locales that have compressed pak files.
     */
    public static String[] getAvailableCompressedPakLocales() {
        assert sCompressedLocales != null;
        return sCompressedLocales;
    }

    /**
     * Return the location of a locale-specific uncompress .pak file asset.
     *
     * @param locale Chromium locale name.
     * @param inBundle If true, return the path of the uncompressed .pak file
     *                 containing Chromium UI strings within app bundles. If
     *                 false, return the path of the uncompressed WebView UI
     *                 strings instead. Note that APK .pak files are stored
     *                 compressed and handled differently.
     * @return Asset path to uncompressed .pak file, or null if the locale is
     *         not supported by this version of Chromium, or the file is
     *         missing.
     */
    @CalledByNative
    private static String getLocalePakResourcePath(String locale, boolean inBundle) {
        if (sUncompressedLocales == null) {
            // Locales may be null in unit tests.
            return null;
        }
        if (Arrays.binarySearch(sUncompressedLocales, locale) < 0) {
            // This locale is not supported by Chromium.
            return null;
        }
        String pathPrefix = "assets/stored-locales/";
        if (inBundle) {
            if (locale.equals("en-US")) {
                pathPrefix = "assets/fallback-locales/";
            } else {
                String lang = LocalizationUtils.getSplitLanguageForAndroid(
                        LocaleUtils.toLanguage(locale));
                pathPrefix = "assets/locales#lang_" + lang + "/";
            }
        }
        String assetPath = pathPrefix + locale + ".pak";
        AssetManager manager = ContextUtils.getApplicationContext().getAssets();
        // The file may not exist if the language split for this locale has not been installed
        // yet, so make sure it exists before returning the asset path.
        try (AssetFileDescriptor afd = manager.openNonAssetFd(assetPath)) {
            return assetPath;
        } catch (IOException e) {
            Log.e(TAG, "Error while loading asset %s: %s", assetPath, e);
        }
        return null;
    }
}