text:
package androidx.recyclerview.selection;

import static androidx.core.util.Preconditions.checkArgument;

import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * Provides a means of controlling when and where band selection can be initiated.
 *
 *

 * Two default implementations are provided: {@link EmptyArea}, and {@link NonDraggableArea}.
 *
 * @see SelectionTracker.Builder#withBandPredicate(BandPredicate)
 */
public abstract class BandPredicate {

    /**
     * @return true if band selection can be initiated in response to the {@link MotionEvent}.
     */
    public abstract boolean canInitiate(@NonNull MotionEvent e);

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    static boolean hasSupportedLayoutManager(@NonNull RecyclerView recyclerView) {
        RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
        return lm instanceof GridLayoutManager
                || lm instanceof LinearLayoutManager;
    }

    /**
     * A BandPredicate that allows initiation of band selection only in areas of RecyclerView
     * that map to {@link RecyclerView#NO_POSITION}. In most cases, this will be the empty areas
     * between views.
     *
     *

     * Use this implementation to permit band selection only in empty areas
     * surrounding view items. But be advised that if there is no empy area around
     * view items, band selection cannot be initiated.
     */
    public static final class EmptyArea extends BandPredicate {

        private final RecyclerView mRecyclerView;

        /**
         * @param recyclerView the owner RecyclerView
         */
        public EmptyArea(@NonNull RecyclerView recyclerView) {
            checkArgument(recyclerView != null);

            mRecyclerView = recyclerView;
        }

        @Override
        public boolean canInitiate(@NonNull MotionEvent e) {
            if (!hasSupportedLayoutManager(mRecyclerView)
                    || mRecyclerView.hasPendingAdapterUpdates()) {
                return false;
            }

            View itemView = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
            int position = itemView != null
                    ? mRecyclerView.getChildAdapterPosition(itemView)
                    : RecyclerView.NO_POSITION;

            return position == RecyclerView.NO_POSITION;
        }
    }

    /**
     * A BandPredicate that allows initiation of band selection in any area that is not
     * draggable as determined by consulting
     * {@link ItemDetailsLookup.ItemDetails#inDragRegion(MotionEvent)}. By default empty
     * areas (those with a position that maps to {@link RecyclerView#NO_POSITION}
     * are considered non-draggable.
     *
     *

     * Use this implementation in order to permit band selection in
     * otherwise empty areas of a View. This is useful especially in
     * list layouts where there is no empty space surrounding the list items,
     * and individual list items may contain extra white space (like
     * in a list of varying length words).
     *
     * @see ItemDetailsLookup.ItemDetails#inDragRegion(MotionEvent)
     */
    public static final class NonDraggableArea extends BandPredicate {

        private final RecyclerView mRecyclerView;
        private final ItemDetailsLookup<?> mDetailsLookup;

        /**
         * Creates a new instance.
         *
         * @param recyclerView  the owner RecyclerView
         * @param detailsLookup provides access to item details.
         */
        public NonDraggableArea(
                @NonNull RecyclerView recyclerView, @NonNull ItemDetailsLookup<?> detailsLookup) {

            checkArgument(recyclerView != null);
            checkArgument(detailsLookup != null);

            mRecyclerView = recyclerView;
            mDetailsLookup = detailsLookup;
        }

        @Override
        public boolean canInitiate(@NonNull MotionEvent e) {
            if (!hasSupportedLayoutManager(mRecyclerView)
                    || mRecyclerView.hasPendingAdapterUpdates()) {
                return false;
            }

            @Nullable ItemDetailsLookup.ItemDetails<?> details =
                    mDetailsLookup.getItemDetails(e);
            return (details == null) || !details.inDragRegion(e);
        }
    }
}


text:
module Echoman
  class Request < Rack::Request
  end
end

redpajama_set_name: RedPajamaGithub


text:
/* global describe it beforeEach before */
var test = require('tape')
var Transformime = require('../src/transformime').Transformime
var createTransform = require('../src/transformime').createTransform

/**
* Dummy Transformer for spying on
*/
function DummyTransformer (mimetype, data, doc) {
  let pre = doc.createElement('pre')
  DummyTransformer.lastData = data
  DummyTransformer.lastDoc = doc
  pre.textContent = data
  return pre
}

var tf
var dummyTransformer1, dummyTransformer2, dummyTransformer3, dummyTransformer4, dummyTransformer5

function beforeEach () {
  tf = new Transformime()
  dummyTransformer1 = tf.push(DummyTransformer, 'transformime/dummy1')
  dummyTransformer2 = tf.push(DummyTransformer, 'transformime/dummy2')
  dummyTransformer3 = tf.push(DummyTransformer, 'transformime/dummy3')
  dummyTransformer4 = tf.push(DummyTransformer, 'transformime/a')
  dummyTransformer5 = tf.push(DummyTransformer, 'transformime/a')
}

test('should have default transformers', function (t) {
  tf = new Transformime()
  t.true(Array.isArray(tf.transformers))
  t.end()
})

test('should have called our DummyRender', function (t) {
  beforeEach()
  var elPromise = tf.transform({'transformime/dummy1': 'dummy-data'}, document)

  elPromise.then((results) => {
    t.equal(DummyTransformer.lastData, 'dummy-data')
    t.equal(DummyTransformer.lastDoc, document)

    // el should be an HTMLElement
    t.true(results.el instanceof document.defaultView.HTMLElement)
    t.end()
  })
})
test('should fail when the mimetype is not known', function (t) {
  let elPromise = tf.transform({'transformime/unknown': 'my-data'}, document)

  elPromise.catch((err) => {
    t.equal(err.message, 'Transformer(s) for transformime/unknown not found.')
    t.end()
  })
})
test('when called with all mimetypes in the mimebundle, only return lastmost', function (t) {
  let mimeBundle = {
    'transformime/dummy1': 'dummy data 1',
    'transformime/dummy2': 'dummy data 2',
    'transformime/dummy3': 'dummy data 3'
  }

  var elPromise = tf.transform(mimeBundle, document)
  elPromise.then((results) => {
    t.equal(DummyTransformer.lastData, 'dummy data 3')
    t.equal(results.mimetype, 'transformime/dummy3')
    t.equal(results.el.textContent, 'dummy data 3')
    t.end()
  })
})
test('when called with a lesser mimebundle, choose most rich', function (t) {
  let mimeBundle = {
    'transformime/dummy1': 'dummy data 1',
    'transformime/dummy2': 'dummy data 2'
  }

  let elPromise = tf.transform(mimeBundle, document)
  elPromise.then(() => {
    t.equal(DummyTransformer.lastData, 'dummy data 2')
    t.end()
  })
})
test("when called with mimetypes it doesn't know, it uses supported mimetypes", function (t) {
  let mimeBundle = {
    'video/quicktime': 'cat vid',
    'transformime/dummy1': 'dummy data 1',
    'application/x-shockwave-flash': 'flashy',
    'application/msword': 'DOC',
    'application/zip': 'zippy'
  }

  let elPromise = tf.transform(mimeBundle, document)
  elPromise.then(() => {
    t.equal(DummyTransformer.lastData, 'dummy data 1')
    t.end()
  })
})
test('get should get the right transformer for a given mimetype', function (t) {
  let transformer = tf.get('transformime/dummy1')
  t.equal(dummyTransformer1, transformer)
  t.end()
})
test('get should return undefined with an unknown mimetype', function (t) {
  t.equal(tf.get('cats/calico'), undefined, "found a transformer when I shouldn't have")
  t.end()
})
test('get respects priority order', function (t) {
  beforeEach()
  let transformer = tf.get('transformime/a')
  t.equal(dummyTransformer5, transformer)
  t.end()
})

test('createTransform returns a transform function for our dummyTransformer', function (t) {
  function dummyTransformer(mimetype, data, document) {
    dummyTransformer.doc = document
    let div = document.createElement('div')
    div.innerHTML = data
    return div
  }
  dummyTransformer.mimetype = 'transformime/dummy'

  var transform = createTransform([dummyTransformer])

  transform({'transformime/dummy': 'dummy-data'}).then((result) => {
    t.equal(dummyTransformer.doc, document)
    t.equal(result.mimetype, 'transformime/dummy')
    t.equal(result.el.innerHTML, 'dummy-data')
    t.end()
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<Theme xmlns="http://wixtoolset.org/schemas/thmutil/2010">
  <Window Width="500" Height="388" HexStyle="100a0000" FontId="0">#(loc.Caption)</Window>
  Segoe UI
  Segoe UI
  Segoe UI
  Segoe UI
  Segoe UI
  Segoe UI
  Segoe UI
  <Image X="0" Y="0" Width="164" Height="312" ImageFile="logo.png" Visible="yes"/>
  <Text X="130" Y="-45" Width="500" Height="2" FontId="5" Visible="yes"></Text>
  <Page Name="Install">
    <Text X="175" Y="30" Width="-11" Height="100" FontId="2" DisablePrefix="yes">#(loc.WillInstall)</Text>
    <Hypertext Name="EulaHyperlink" X="175" Y="-60" Width="-11" Height="17" TabStop="no" FontId="3" HideWhenDisabled="yes">#(loc.InstallLicenseLinkText)</Hypertext>
    <Text X="175" Y="-81" Width="-11" Height="17" FontId="3" DisablePrefix="yes">#(loc.InstallVersion)</Text>
    <Button Name="InstallButton" X="-91" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.InstallInstallButton)</Button>
    <Button Name="WelcomeCancelButton" X="-11" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.InstallCloseButton)</Button>
  </Page>
  <Page Name="Progress">
    <Text X="175" Y="30" Width="-11" Height="30" FontId="2" DisablePrefix="yes">#(loc.ProgressHeader)</Text>
    <Text X="175" Y="71" Width="70" Height="17" FontId="3" DisablePrefix="yes">#(loc.ProgressLabel)</Text>
    <Text Name="OverallProgressPackageText" X="175" Y="71" Width="-11" Height="17" FontId="3" DisablePrefix="yes">#(loc.OverallProgressPackageText)</Text>
    <Progressbar Name="OverallCalculatedProgressbar" X="175" Y="93" Width="250" Height="15" />
    <Button Name="ProgressCancelButton" X="-11" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.ProgressCancelButton)</Button>
  </Page>
  <Page Name="Modify">
    <Text X="175" Y="30" Width="-11" Height="100" FontId="2" DisablePrefix="yes">#(loc.ModifyHeader)</Text>
    <Button Name="RepairButton" X="-171" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0" HideWhenDisabled="yes">#(loc.ModifyRepairButton)</Button>
    <Button Name="UninstallButton" X="-91" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.ModifyUninstallButton)</Button>
    <Button Name="ModifyCancelButton" X="-11" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.ModifyCloseButton)</Button>
  </Page>
  <Page Name="Success">
    <Text X="175" Y="30" Width="-11" Height="100" FontId="2" DisablePrefix="yes">#(loc.SuccessHeader)</Text>
    <Button Name="LaunchButton" X="-91" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0" HideWhenDisabled="yes">#(loc.SuccessLaunchButton)</Button>
    <Text Name="SuccessRestartText" X="175" Y="-51" Width="-11" Height="34" FontId="3" HideWhenDisabled="yes" DisablePrefix="yes">#(loc.SuccessRestartText)</Text>
    <Button Name="SuccessRestartButton" X="-91" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0" HideWhenDisabled="yes">#(loc.SuccessRestartButton)</Button>
    <Button Name="SuccessCancelButton" X="-11" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.SuccessCloseButton)</Button>
  </Page>
  <Page Name="Failure">
    <Text X="175" Y="30" Width="-11" Height="30" FontId="2" DisablePrefix="yes">#(loc.FailureHeader)</Text>
    <Hypertext Name="FailureLogFileLink" X="175" Y="71" Width="-11" Height="51" FontId="3" TabStop="yes" HideWhenDisabled="yes">#(loc.FailureHyperlinkLogText)</Hypertext>
    <Hypertext Name="FailureMessageText" X="175" Y="131" Width="-11" Height="51" FontId="3" TabStop="yes" HideWhenDisabled="yes" />
    <Text Name="FailureRestartText" X="175" Y="160" Width="-11" Height="34" FontId="3" HideWhenDisabled="yes" DisablePrefix="yes">#(loc.FailureRestartText)</Text>
    <Button Name="FailureRestartButton" X="-91" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0" HideWhenDisabled="yes">#(loc.FailureRestartButton)</Button>
    <Button Name="FailureCloseButton" X="-11" Y="-11" Width="75" Height="23" TabStop="yes" FontId="0">#(loc.FailureCloseButton)</Button>
  </Page>
</Theme>


text:
<?php

namespace spec\Sylius\Component\Payment\Model;

use PhpSpec\ObjectBehavior;

/**
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class CreditCardSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Payment\Model\CreditCard');
    }

    function it_implements_Sylius_credit_card_interface()
    {
        $this->shouldImplement('Sylius\Component\Payment\Model\CreditCardInterface');
    }

    function it_implements_Sylius_payment_source_interface()
    {
        $this->shouldImplement('Sylius\Component\Payment\Model\PaymentSourceInterface');
    }

    function it_has_no_id_by_default()
    {
        $this->getId()->shouldReturn(null);
    }

    function it_has_no_cardholder_name_by_default()
    {
        $this->getCardholderName()->shouldReturn(null);
    }

    function its_carholder_name_is_mutable()
    {
        $this->setCardholderName('John Doe');
        $this->getCardholderName()->shouldReturn('John Doe');
    }

    function it_has_no_number_by_default()
    {
        $this->getNumber()->shouldReturn(null);
    }

    function its_number_is_mutable()
    {
        $this->setNumber('5321');
        $this->getNumber()->shouldReturn('5321');
    }

    function it_returns_last_4_digits_in_masked_number()
    {
        $this->setNumber('1244 1242 5434 1234');
        $this->getMaskedNumber()->shouldReturn('XXXX XXXX XXXX 1234');
    }

    function it_returns_masked_number_when_converted_to_string()
    {
        $this->setNumber('1244 1242 5434 1234');
        $this->__toString()->shouldReturn('XXXX XXXX XXXX 1234');
    }

    function it_has_no_security_code_by_default()
    {
        $this->getSecurityCode()->shouldReturn(null);
    }

    function its_security_code_is_mutable()
    {
        $this->setSecurityCode('373');
        $this->getSecurityCode()->shouldReturn('373');
    }

    function it_has_no_expiry_month_by_default()
    {
        $this->getExpiryMonth()->shouldReturn(null);
    }

    function its_expiry_month_is_mutable()
    {
        $this->setExpiryMonth(11);
        $this->getExpiryMonth()->shouldReturn(11);
    }

    function it_has_no_expiry_year_by_default()
    {
        $this->getExpiryYear()->shouldReturn(null);
    }

    function its_expiry_year_is_mutable()
    {
        $this->setExpiryYear(15);
        $this->getExpiryYear()->shouldReturn(15);
    }

    function it_has_no_token_by_default()
    {
        $this->getToken()->shouldReturn(null);
    }

    function its_token_is_mutable()
    {
        $this->setToken('2sa42aaSOx');
        $this->getToken()->shouldReturn('2sa42aaSOx');
    }

    function it_initializes_creation_date_by_default()
    {
        $this->getCreatedAt()->shouldHaveType('DateTime');
    }

    function it_has_no_last_update_date_by_default()
    {
        $this->getUpdatedAt()->shouldReturn(null);
    }
}


text:
from __future__ import absolute_import

import os
from testmill import console, error, util, ravello
from testmill.state import env

def password_login():
    """Try to log in with a username and password."""
    try:
        env.api.login(env.username, env.password)
    except ravello.RavelloError as e:
        error.raise_error('Could not login to Ravello ({!s})\n'
                          'Check your username and password.', e)

def token_login():
    """Try to log in with a token."""
    cfgdir = util.get_config_dir()
    tokfile = os.path.join(cfgdir, 'api-token')
    try:
        with file(tokfile) as ftok:
            token = ftok.read()
    except IOError:
        error.raise_error('Not logged in')
    token = token.strip()
    try:
        env.api.login(token=token)
    except ravello.RavelloError as e:
        error.raise_error('Token has expired.\n'
                          "Use 'ravtest login' to refresh.")

def store_token():
    """Store the login token."""
    cfgdir = util.get_config_dir()
    tokname = os.path.join(cfgdir, 'api-token')
    with file(tokname, 'w') as ftok:
        ftok.write(env.api._cookie)
        ftok.write('\n')
    if hasattr(os, 'chmod'):
        os.chmod(tokname, 0o600)

def remove_token():
    """Remove the login token."""
    cfgdir = util.get_config_dir()
    tokname = os.path.join(cfgdir, 'api-token')
    try:
        st = os.stat(tokname)
    except OSError:
        return
    os.unlink(tokname)

def default_login():
    """Login function. Used by most sub-commands to ensure there is a valid
    connection to the Ravello API."""
    if env.username and env.password:
        password_login()
    else:
        token_login()


text:
#ifndef N3D_ANIMATIONRIG_H
#define N3D_ANIMATIONRIG_H

#include "AnimationClip.h"

namespace nest
{
	typedef struct
	{
		std::string name;

		Matrix4 *target;

		Vector4 *oldP, *newP;

		Quaternion *oldR, *newR;

		Vector4 *oldS, *newS;

	} RigData;

	class AnimationRig
	{
	public:

		std::string name;

		std::vector<RigData> rigs;

		/**
		 *	Apply animation data to rig vector.
		 *
You'd setupRigData() first, then applyAnimation().

		 */
		void applyAnimation(std::vector<PoseData> &poses);

		/**
		 *	Blend old,new transforms and store them to target matrix for rendering.
		 *
You'd applyAnimation() first, then play it.

		 */
		void displayAnimation(float dt);
	};
}

#endif


text:
@implementation VLayoutManager

- (id)init
{
    self =[super init];
    if (self){
        self.layoutInfos = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)addlayoutInfo:(VLayoutInfo*)layoutInfo
{
    [self.layoutInfos addObject:layoutInfo];
}

- (void)addlayoutInfo:(VLayoutInfo *)layoutInfo insert:(NSUInteger)index
{
    [self.layoutInfos insertObject:layoutInfo atIndex:index];
}

- (void)addlayoutInfos:(NSArray *)layoutInfo
{
    [self.layoutInfos addObjectsFromArray:layoutInfo];
}

- (void)removelayoutInfo:(VLayoutInfo*)layoutInfo
{
    [self.layoutInfos removeObject:layoutInfo];
}

- (void)removelayoutInfoAtIndex:(NSInteger)index
{
    [self.layoutInfos removeObjectAtIndex:index];
}

- (void)removeAlllayoutInfo
{
    [self.layoutInfos removeAllObjects];
}

- (NSInteger)layoutInfoCount{
    return self.layoutInfos.count;
}

- (VLayoutInfo *)layoutInfo:(NSInteger)index
{
    if (index<[self layoutInfoCount]) {
        return self.layoutInfos[index];
    }
    return nil;
}

@end


text:
ENV['RACK_ENV'] = 'test'

$: << File.expand_path("../../.", __FILE__)

require 'service_broker'
require 'rspec'
require 'rack/test'

module AsyncHelper
  def eventually(options = {})
    timeout = options[:timeout] || 2
    interval = options[:interval] || 0.1
    time_limit = Time.now + timeout
    loop do
      begin
        yield
      rescue => error
      end
      return if error.nil?
      raise error if Time.now >= time_limit
      sleep interval
    end
  end
end

RSpec.configure do |conf|
  conf.include Rack::Test::Methods
  #conf.include AsyncHelper

  def app
    ServiceBroker
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ADBaseLibrary
{
    public enum ResponseStatus
    {
        Ok,
        MissingRequirement,
        MissingPlugin,
        InvalidArgument,
        InvalidLogin,
        MissingAuthenticationParameters,
        NotSupported,
        LoginRequired,
        WebError,
        TransferError,
        SystemError,
        Canceled
    }
}


text:
package org.apereo.cas.support.events.dao;

import java.util.ArrayList;
import java.util.Collection;

/**
 * This is {@link NoOpCasEventRepository}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class NoOpCasEventRepository extends AbstractCasEventRepository {

    @Override
    public void save(final CasEvent event) {
    }

    @Override
    public Collection<CasEvent> load() {
        return new ArrayList<>(0);
    }
}


text:
import zookeeper
from zc.zk.testing import Node, badpath
import zc.zk.testing

TESTING_FLAG = 32
def create(self, handle, path, data, acl, flags=0):
	with self.lock:
		self._check_handle(handle)
		base, name = path.rsplit('/', 1)
		if flags & zookeeper.SEQUENCE:
			if not hasattr(self, 'sequences'):
				self.sequences = {}
			cnt = self.sequences.setdefault(path, -1) + 1
			self.sequences[path] = cnt
			name = "%s%010d" % (name, cnt)
			path = "%s%010d" % (path, cnt)
		if base.endswith('/'):
			raise zookeeper.BadArgumentsException('bad arguments')
		node = self._traverse(base)
		for p in node.acl:
			if not (p['perms'] & zookeeper.PERM_CREATE):
				raise zookeeper.NoAuthException('not authenticated')
		if name in node.children:
			raise zookeeper.NodeExistsException()
		node.children[name] = newnode = Node(data)
		newnode.acl = acl
		newnode.flags = flags
		node.children_changed(handle, zookeeper.CONNECTED_STATE, base)
		if flags & zookeeper.EPHEMERAL:
			self.sessions[handle].add(path)
		return path

def exists(self, handle, path, watch=None):
	# exists watch doesn't work yet
	if badpath(path):
		raise zookeeper.BadArgumentsException('bad argument')
	with self.lock:
		if watch:
			node = self._traverse(path)
			node.watchers += ((handle, watch), )
		self._check_handle(handle)
		try:
			self._traverse(path)
			return True
		except zookeeper.NoNodeException:
			return False

def deleted(self, handle, state, path):
	watchers = self.watchers
	self.watchers = ()
	for h, w in watchers:
		w(h, zookeeper.DELETED_EVENT | TESTING_FLAG, state, path)
	watchers = self.child_watchers
	self.child_watchers = ()
	for h, w in watchers:
		w(h, zookeeper.DELETED_EVENT | TESTING_FLAG, state, path)


text:
#include "config.h"
#if ENABLE(FTPDIR)
#include "FTPDirectoryDocument.h"

#include "ExceptionCodePlaceholder.h"
#include "HTMLDocumentParser.h"
#include "HTMLNames.h"
#include "HTMLTableElement.h"
#include "LocalizedStrings.h"
#include "Logging.h"
#include "FTPDirectoryParser.h"
#include "SegmentedString.h"
#include "Settings.h"
#include "SharedBuffer.h"
#include "Text.h"
#include <wtf/CurrentTime.h>
#include <wtf/GregorianDateTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>

using namespace std;

namespace WebCore {

using namespace HTMLNames;

class FTPDirectoryDocumentParser : public HTMLDocumentParser {
public:
    static PassRefPtr<FTPDirectoryDocumentParser> create(HTMLDocument* document)
    {
        return adoptRef(new FTPDirectoryDocumentParser(document));
    }

    virtual void append(PassRefPtr<StringImpl>);
    virtual void finish();

    virtual bool isWaitingForScripts() const { return false; }

    inline void checkBuffer(int len = 10)
    {
        if ((m_dest - m_buffer) > m_size - len) {
            // Enlarge buffer
            int newSize = max(m_size * 2, m_size + len);
            int oldOffset = m_dest - m_buffer;
            m_buffer = static_cast<UChar*>(fastRealloc(m_buffer, newSize * sizeof(UChar)));
            m_dest = m_buffer + oldOffset;
            m_size = newSize;
        }
    }

private:
    FTPDirectoryDocumentParser(HTMLDocument*);

    // The parser will attempt to load the document template specified via the preference
    // Failing that, it will fall back and create the basic document which will have a minimal
    // table for presenting the FTP directory in a useful manner
    bool loadDocumentTemplate();
    void createBasicDocument();

    void parseAndAppendOneLine(const String&);
    void appendEntry(const String& name, const String& size, const String& date, bool isDirectory);
    PassRefPtr<Element> createTDForFilename(const String&);

    RefPtr<HTMLTableElement> m_tableElement;

    bool m_skipLF;

    int m_size;
    UChar* m_buffer;
    UChar* m_dest;
    String m_carryOver;

    ListState m_listState;
};

FTPDirectoryDocumentParser::FTPDirectoryDocumentParser(HTMLDocument* document)
    : HTMLDocumentParser(document, false)
    , m_skipLF(false)
    , m_size(254)
    , m_buffer(static_cast<UChar*>(fastMalloc(sizeof(UChar) * m_size)))
    , m_dest(m_buffer)
{
}

void FTPDirectoryDocumentParser::appendEntry(const String& filename, const String& size, const String& date, bool isDirectory)
{
    RefPtr<Element> rowElement = m_tableElement->insertRow(-1, IGNORE_EXCEPTION);
    rowElement->setAttribute("class", "ftpDirectoryEntryRow", IGNORE_EXCEPTION);

    RefPtr<Element> element = document()->createElement(tdTag, false);
    element->appendChild(Text::create(document(), String(&noBreakSpace, 1)), IGNORE_EXCEPTION);
    if (isDirectory)
        element->setAttribute("class", "ftpDirectoryIcon ftpDirectoryTypeDirectory", IGNORE_EXCEPTION);
    else
        element->setAttribute("class", "ftpDirectoryIcon ftpDirectoryTypeFile", IGNORE_EXCEPTION);
    rowElement->appendChild(element, IGNORE_EXCEPTION);

    element = createTDForFilename(filename);
    element->setAttribute("class", "ftpDirectoryFileName", IGNORE_EXCEPTION);
    rowElement->appendChild(element, IGNORE_EXCEPTION);

    element = document()->createElement(tdTag, false);
    element->appendChild(Text::create(document(), date), IGNORE_EXCEPTION);
    element->setAttribute("class", "ftpDirectoryFileDate", IGNORE_EXCEPTION);
    rowElement->appendChild(element, IGNORE_EXCEPTION);

    element = document()->createElement(tdTag, false);
    element->appendChild(Text::create(document(), size), IGNORE_EXCEPTION);
    element->setAttribute("class", "ftpDirectoryFileSize", IGNORE_EXCEPTION);
    rowElement->appendChild(element, IGNORE_EXCEPTION);
}

PassRefPtr<Element> FTPDirectoryDocumentParser::createTDForFilename(const String& filename)
{
    String fullURL = document()->baseURL().string();
    if (fullURL[fullURL.length() - 1] == '/')
        fullURL.append(filename);
    else
        fullURL.append("/" + filename);

    RefPtr<Element> anchorElement = document()->createElement(aTag, false);
    anchorElement->setAttribute("href", fullURL, IGNORE_EXCEPTION);
    anchorElement->appendChild(Text::create(document(), filename), IGNORE_EXCEPTION);

    RefPtr<Element> tdElement = document()->createElement(tdTag, false);
    tdElement->appendChild(anchorElement, IGNORE_EXCEPTION);

    return tdElement.release();
}

static String processFilesizeString(const String& size, bool isDirectory)
{
    if (isDirectory)
        return "--";

    bool valid;
    int64_t bytes = size.toUInt64(&valid);
    if (!valid)
        return unknownFileSizeText();

    if (bytes < 1000000)
        return String::format("%.2f KB", static_cast<float>(bytes)/1000);

    if (bytes < 1000000000)
        return String::format("%.2f MB", static_cast<float>(bytes)/1000000);

    return String::format("%.2f GB", static_cast<float>(bytes)/1000000000);
}

static bool wasLastDayOfMonth(int year, int month, int day)
{
    static int lastDays[] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    if (month < 0 || month > 11)
        return false;

    if (month == 2) {
        if (year % 4 == 0 && (year % 100 || year % 400 == 0)) {
            if (day == 29)
                return true;
            return false;
        }

        if (day == 28)
            return true;
        return false;
    }

    return lastDays[month] == day;
}

static String processFileDateString(const FTPTime& fileTime)
{
    // FIXME: Need to localize this string?

    String timeOfDay;

    if (!(fileTime.tm_hour == 0 && fileTime.tm_min == 0 && fileTime.tm_sec == 0)) {
        int hour = fileTime.tm_hour;
        ASSERT(hour >= 0 && hour < 24);

        if (hour < 12) {
            if (hour == 0)
                hour = 12;
            timeOfDay = String::format(", %i:%02i AM", hour, fileTime.tm_min);
        } else {
            hour = hour - 12;
            if (hour == 0)
                hour = 12;
            timeOfDay = String::format(", %i:%02i PM", hour, fileTime.tm_min);
        }
    }

    // If it was today or yesterday, lets just do that - but we have to compare to the current time
    GregorianDateTime now;
    now.setToCurrentLocalTime();

    if (fileTime.tm_year == now.year()) {
        if (fileTime.tm_mon == now.month()) {
            if (fileTime.tm_mday == now.monthDay())
                return "Today" + timeOfDay;
            if (fileTime.tm_mday == now.monthDay() - 1)
                return "Yesterday" + timeOfDay;
        }

        if (now.monthDay() == 1 && (now.month() == fileTime.tm_mon + 1 || (now.month() == 0 && fileTime.tm_mon == 11)) &&
            wasLastDayOfMonth(fileTime.tm_year, fileTime.tm_mon, fileTime.tm_mday))
                return "Yesterday" + timeOfDay;
    }

    if (fileTime.tm_year == now.year() - 1 && fileTime.tm_mon == 12 && fileTime.tm_mday == 31 && now.month() == 1 && now.monthDay() == 1)
        return "Yesterday" + timeOfDay;

    static const char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" };

    int month = fileTime.tm_mon;
    if (month < 0 || month > 11)
        month = 12;

    String dateString;

    if (fileTime.tm_year > -1)
        dateString = String(months[month]) + " " + String::number(fileTime.tm_mday) + ", " + String::number(fileTime.tm_year);
    else
        dateString = String(months[month]) + " " + String::number(fileTime.tm_mday) + ", " + String::number(now.year());

    return dateString + timeOfDay;
}

void FTPDirectoryDocumentParser::parseAndAppendOneLine(const String& inputLine)
{
    ListResult result;
    CString latin1Input = inputLine.latin1();

    FTPEntryType typeResult = parseOneFTPLine(latin1Input.data(), m_listState, result);

    // FTPMiscEntry is a comment or usage statistic which we don't care about, and junk is invalid data - bail in these 2 cases
    if (typeResult == FTPMiscEntry || typeResult == FTPJunkEntry)
        return;

    String filename(result.filename, result.filenameLength);
    if (result.type == FTPDirectoryEntry) {
        filename.append("/");

        // We have no interest in linking to "current directory"
        if (filename == "./")
            return;
    }

    LOG(FTP, "Appending entry - %s, %s", filename.ascii().data(), result.fileSize.ascii().data());

    appendEntry(filename, processFilesizeString(result.fileSize, result.type == FTPDirectoryEntry), processFileDateString(result.modifiedTime), result.type == FTPDirectoryEntry);
}

static inline PassRefPtr<SharedBuffer> createTemplateDocumentData(Settings* settings)
{
    RefPtr<SharedBuffer> buffer = 0;
    if (settings)
        buffer = SharedBuffer::createWithContentsOfFile(settings->ftpDirectoryTemplatePath());
    if (buffer)
        LOG(FTP, "Loaded FTPDirectoryTemplate of length %i\n", buffer->size());
    return buffer.release();
}

bool FTPDirectoryDocumentParser::loadDocumentTemplate()
{
    DEFINE_STATIC_LOCAL(RefPtr<SharedBuffer>, templateDocumentData, (createTemplateDocumentData(document()->settings())));
    // FIXME: Instead of storing the data, we'd rather actually parse the template data into the template Document once,
    // store that document, then "copy" it whenever we get an FTP directory listing.  There are complexities with this
    // approach that make it worth putting this off.

    if (!templateDocumentData) {
        LOG_ERROR("Could not load templateData");
        return false;
    }

    HTMLDocumentParser::insert(String(templateDocumentData->data(), templateDocumentData->size()));

    RefPtr<Element> tableElement = document()->getElementById("ftpDirectoryTable");
    if (!tableElement)
        LOG_ERROR("Unable to find element by id \"ftpDirectoryTable\" in the template document.");
    else if (!isHTMLTableElement(tableElement.get()))
        LOG_ERROR("Element of id \"ftpDirectoryTable\" is not a table element");
    else
        m_tableElement = toHTMLTableElement(tableElement.get());

    // Bail if we found the table element
    if (m_tableElement)
        return true;

    // Otherwise create one manually
    tableElement = document()->createElement(tableTag, false);
    m_tableElement = toHTMLTableElement(tableElement.get());
    m_tableElement->setAttribute("id", "ftpDirectoryTable", IGNORE_EXCEPTION);

    // If we didn't find the table element, lets try to append our own to the body
    // If that fails for some reason, cram it on the end of the document as a last
    // ditch effort
    if (Element* body = document()->body())
        body->appendChild(m_tableElement, IGNORE_EXCEPTION);
    else
        document()->appendChild(m_tableElement, IGNORE_EXCEPTION);

    return true;
}

void FTPDirectoryDocumentParser::createBasicDocument()
{
    LOG(FTP, "Creating a basic FTP document structure as no template was loaded");

    // FIXME: Make this "basic document" more acceptable

    RefPtr<Element> bodyElement = document()->createElement(bodyTag, false);

    document()->appendChild(bodyElement, IGNORE_EXCEPTION);

    RefPtr<Element> tableElement = document()->createElement(tableTag, false);
    m_tableElement = toHTMLTableElement(tableElement.get());
    m_tableElement->setAttribute("id", "ftpDirectoryTable", IGNORE_EXCEPTION);

    bodyElement->appendChild(m_tableElement, IGNORE_EXCEPTION);
}

void FTPDirectoryDocumentParser::append(PassRefPtr<StringImpl> inputSource)
{
    String source(inputSource);

    // Make sure we have the table element to append to by loading the template set in the pref, or
    // creating a very basic document with the appropriate table
    if (!m_tableElement) {
        if (!loadDocumentTemplate())
            createBasicDocument();
        ASSERT(m_tableElement);
    }

    bool foundNewLine = false;

    m_dest = m_buffer;
    SegmentedString str = source;
    while (!str.isEmpty()) {
        UChar c = str.currentChar();

        if (c == '\r') {
            *m_dest++ = '\n';
            foundNewLine = true;
            // possibly skip an LF in the case of an CRLF sequence
            m_skipLF = true;
        } else if (c == '\n') {
            if (!m_skipLF)
                *m_dest++ = c;
            else
                m_skipLF = false;
        } else {
            *m_dest++ = c;
            m_skipLF = false;
        }

        str.advance();

        // Maybe enlarge the buffer
        checkBuffer();
    }

    if (!foundNewLine) {
        m_dest = m_buffer;
        return;
    }

    UChar* start = m_buffer;
    UChar* cursor = start;

    while (cursor < m_dest) {
        if (*cursor == '\n') {
            m_carryOver.append(String(start, cursor - start));
            LOG(FTP, "%s", m_carryOver.ascii().data());
            parseAndAppendOneLine(m_carryOver);
            m_carryOver = String();

            start = ++cursor;
        } else
            cursor++;
    }

    // Copy the partial line we have left to the carryover buffer
    if (cursor - start > 1)
        m_carryOver.append(String(start, cursor - start - 1));
}

void FTPDirectoryDocumentParser::finish()
{
    // Possible the last line in the listing had no newline, so try to parse it now
    if (!m_carryOver.isEmpty()) {
        parseAndAppendOneLine(m_carryOver);
        m_carryOver = String();
    }

    m_tableElement = 0;
    fastFree(m_buffer);

    HTMLDocumentParser::finish();
}

FTPDirectoryDocument::FTPDirectoryDocument(Frame* frame, const KURL& url)
    : HTMLDocument(frame, url)
{
#if !LOG_DISABLED
    LogFTP.state = WTFLogChannelOn;
#endif
}

PassRefPtr<DocumentParser> FTPDirectoryDocument::createParser()
{
    return FTPDirectoryDocumentParser::create(this);
}

}

#endif // ENABLE(FTPDIR)


text:
#ifndef BOOST_OUTCOME_IOSTREAM_SUPPORT_HPP
#define BOOST_OUTCOME_IOSTREAM_SUPPORT_HPP

#include "outcome.hpp"

#include <iostream>
#include <sstream>

BOOST_OUTCOME_V2_NAMESPACE_BEGIN

namespace detail
{
  template <class T> typename std::add_lvalue_reference<T>::type lvalueref() noexcept;

  template <class T> inline std::ostream &operator<<(std::ostream &s, const value_storage_trivial<T> &v)
  {
    s << static_cast<uint16_t>(v._status.status_value) << " " << v._status.spare_storage_value << " ";
    if(v._status.have_value())
    {
      s << v._value;  // NOLINT
    }
    return s;
  }
  inline std::ostream &operator<<(std::ostream &s, const value_storage_trivial<void> &v)
  {
    s << static_cast<uint16_t>(v._status.status_value) << " " << v._status.spare_storage_value << " ";
    return s;
  }
  template <class T> inline std::ostream &operator<<(std::ostream &s, const value_storage_nontrivial<T> &v)
  {
    s << static_cast<uint16_t>(v._status.status_value) << " " << v._status.spare_storage_value << " ";
    if(v._status.have_value())
    {
      s << v._value;  // NOLINT
    }
    return s;
  }
  template <class T> inline std::istream &operator>>(std::istream &s, value_storage_trivial<T> &v)
  {
    v = value_storage_trivial<T>();
    uint16_t x, y;
    s >> x >> y;
    v._status.status_value = static_cast<detail::status>(x);
    v._status.spare_storage_value = y;
    if(v._status.have_value())
    {
      new(&v._value) decltype(v._value)();  // NOLINT
      s >> v._value;                        // NOLINT
    }
    return s;
  }
  inline std::istream &operator>>(std::istream &s, value_storage_trivial<devoid<void>> &v)
  {
    v = value_storage_trivial<devoid<void>>();
    uint16_t x, y;
    s >> x >> y;
    v._status.status_value = static_cast<detail::status>(x);
    v._status.spare_storage_value = y;
    return s;
  }
  template <class T> inline std::istream &operator>>(std::istream &s, value_storage_nontrivial<T> &v)
  {
    v = value_storage_nontrivial<T>();
    uint16_t x, y;
    s >> x >> y;
    v._status.status_value = static_cast<detail::status>(x);
    v._status.spare_storage_value = y;
    if(v._status.have_value())
    {
      new(&v._value) decltype(v._value)();  // NOLINT
      s >> v._value;                        // NOLINT
    }
    return s;
  }
  BOOST_OUTCOME_TEMPLATE(class T)
  BOOST_OUTCOME_TREQUIRES(BOOST_OUTCOME_TPRED(!std::is_constructible<std::error_code, T>::value))
  inline std::string safe_message(T && /*unused*/) { return {}; }
  inline std::string safe_message(const std::error_code &ec) { return " (" + ec.message() + ")"; }
}  // namespace detail

/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
BOOST_OUTCOME_TEMPLATE(class R, class S, class P)
BOOST_OUTCOME_TREQUIRES(BOOST_OUTCOME_TEXPR(detail::lvalueref<std::istream>() >> detail::lvalueref<R>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::istream>() >> detail::lvalueref<S>()))
inline std::istream &operator>>(std::istream &s, basic_result<R, S, P> &v)
{
  s >> v._iostreams_state();
  if(v.has_error())
  {
    s >> v.assume_error();
  }
  return s;
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
BOOST_OUTCOME_TEMPLATE(class R, class S, class P)
BOOST_OUTCOME_TREQUIRES(BOOST_OUTCOME_TEXPR(detail::lvalueref<std::ostream>() << detail::lvalueref<R>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::ostream>() << detail::lvalueref<S>()))
inline std::ostream &operator<<(std::ostream &s, const basic_result<R, S, P> &v)
{
  s << v._iostreams_state();
  if(v.has_error())
  {
    s << v.assume_error();
  }
  return s;
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
template <class R, class S, class P> inline std::string print(const basic_result<R, S, P> &v)
{
  std::stringstream s;
  if(v.has_value())
  {
    s << v.value();
  }
  if(v.has_error())
  {
    s << v.error() << detail::safe_message(v.error());
  }
  return s.str();
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
template <class S, class P> inline std::string print(const basic_result<void, S, P> &v)
{
  std::stringstream s;
  if(v.has_value())
  {
    s << "(+void)";
  }
  if(v.has_error())
  {
    s << v.error() << detail::safe_message(v.error());
  }
  return s.str();
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
template <class R, class P> inline std::string print(const basic_result<R, void, P> &v)
{
  std::stringstream s;
  if(v.has_value())
  {
    s << v.value();
  }
  if(v.has_error())
  {
    s << "(-void)";
  }
  return s.str();
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
template <class P> inline std::string print(const basic_result<void, void, P> &v)
{
  std::stringstream s;
  if(v.has_value())
  {
    s << "(+void)";
  }
  if(v.has_error())
  {
    s << "(-void)";
  }
  return s.str();
}

/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
BOOST_OUTCOME_TEMPLATE(class R, class S, class P, class N)
BOOST_OUTCOME_TREQUIRES(BOOST_OUTCOME_TEXPR(detail::lvalueref<std::istream>() >> detail::lvalueref<R>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::istream>() >> detail::lvalueref<S>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::istream>() >> detail::lvalueref<P>()))
inline std::istream &operator>>(std::istream &s, outcome<R, S, P, N> &v)
{
  s >> v._iostreams_state();
  if(v.has_error())
  {
    s >> v.assume_error();
  }
  if(v.has_exception())
  {
    s >> v.assume_exception();
  }
  return s;
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
BOOST_OUTCOME_TEMPLATE(class R, class S, class P, class N)
BOOST_OUTCOME_TREQUIRES(BOOST_OUTCOME_TEXPR(detail::lvalueref<std::ostream>() << detail::lvalueref<R>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::ostream>() << detail::lvalueref<S>()), BOOST_OUTCOME_TEXPR(detail::lvalueref<std::ostream>() << detail::lvalueref<P>()))
inline std::ostream &operator<<(std::ostream &s, const outcome<R, S, P, N> &v)
{
  s << v._iostreams_state();
  if(v.has_error())
  {
    s << v.assume_error();
  }
  if(v.has_exception())
  {
    s << v.assume_exception();
  }
  return s;
}
/*! AWAITING HUGO JSON CONVERSION TOOL
SIGNATURE NOT RECOGNISED
*/
template <class R, class S, class P, class N> inline std::string print(const outcome<R, S, P, N> &v)
{
  std::stringstream s;
  int total = static_cast<int>(v.has_value()) + static_cast<int>(v.has_error()) + static_cast<int>(v.has_exception());
  if(total > 1)
  {
    s << "{ ";
  }
  s << print(static_cast<const basic_result<R, S, N> &>(static_cast<const detail::basic_result_final<R, S, N> &>(v)));  // NOLINT
  if(total > 1)
  {
    s << ", ";
  }
  if(v.has_exception())
  {
#ifndef BOOST_NO_EXCEPTIONS
    try
    {
      rethrow_exception(v.exception());
    }
    catch(const std::system_error &e)
    {
      s << "std::system_error code " << e.code() << ": " << e.what();
    }
    catch(const std::exception &e)
    {
      s << "std::exception: " << e.what();
    }
    catch(...)
#endif
    {
      s << "unknown exception";
    }
  }
  if(total > 1)
  {
    s << " }";
  }
  return s.str();
}
BOOST_OUTCOME_V2_NAMESPACE_END

#endif


text:
layout: page
title: About myself
permalink: /myself/
tagline: "Humanity is overrated."
category: "myself"
---
### About myself
I am now a junior student at Zhejiang University. I did an internship in [VIPA](http://eagle.zju.edu.cn/modules/news/index.php?storytopic=11) with professor [Mingli song](http://mypage.zju.edu.cn/msong/0.html).

My research interests lie in generative models and computer vision.

I write [blogs]({{ site.url }}/blogs/) in Chinese occasionally. Here are my [publication list]({{ site.url }}/publications) and [CV]({{ site.url }}/static/resume_cv.pdf).

I am also interested in reading the source code of Tensorflow, welcome to discuss problems regarding to it with me.
Here is my github


text:
class EqualStacks
  attr_accessor :stacks
  def initialize(stacks)
    @stacks = stacks
  end

  def equalize_stacks
    pop_largest_stack until equal_stacks?
    largest_stack.height
  end

  def pop_largest_stack
    largest_stack.pop
  end

  def equal_stacks?
    largest_stack.height == smallest_stack.height
  end

  def largest_stack
    stacks.max_by(&:height)
  end

  def smallest_stack
    stacks.min_by(&:height)
  end
end

# Stack
class Stack
  attr_accessor :heights, :height
  def initialize(heights)
    @heights = heights
    @height = heights.reduce(:+)
  end

  def pop
    @height -= heights.shift
  end
end

_ = gets.chomp
stacks = Array.new(3) { Stack.new(gets.chomp.split(' ').map(&:to_i)) }
puts EqualStacks.new(stacks).equalize_stacks


text:
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {Type} from '@angular/core';
import {SpyChangeDetectorRef} from './spies';
import {ApplicationRef_, ApplicationRef, PLATFORM_CORE_PROVIDERS, APPLICATION_CORE_PROVIDERS} from '@angular/core/src/application_ref';
import {Injector, APP_INITIALIZER, Component, ReflectiveInjector, coreLoadAndBootstrap, PlatformRef, createPlatform, disposePlatform, ComponentResolver, ChangeDetectorRef} from '@angular/core';
import {Console} from '@angular/core/src/console';
import {BaseException} from '../src/facade/exceptions';
import {PromiseWrapper, PromiseCompleter, TimerWrapper} from '../src/facade/async';
import {ComponentFactory, ComponentRef_, ComponentRef} from '@angular/core/src/linker/component_factory';
import {ExceptionHandler} from '../src/facade/exception_handler';

export function main() {
  describe('bootstrap', () => {
    var platform: PlatformRef;
    var errorLogger: _ArrayLogger;
    var someCompFactory: ComponentFactory<any>;

    beforeEach(() => {
      errorLogger = new _ArrayLogger();
      disposePlatform();
      platform = createPlatform(ReflectiveInjector.resolveAndCreate(PLATFORM_CORE_PROVIDERS));
      someCompFactory =
          new _MockComponentFactory(new _MockComponentRef(ReflectiveInjector.resolveAndCreate([])));
    });

    afterEach(() => { disposePlatform(); });

    function createApplication(providers: any[]): ApplicationRef_ {
      var appInjector = ReflectiveInjector.resolveAndCreate(
          [
            APPLICATION_CORE_PROVIDERS, {provide: Console, useValue: new _MockConsole()},
            {provide: ExceptionHandler, useValue: new ExceptionHandler(errorLogger, false)},
            {provide: ComponentResolver, useValue: new _MockComponentResolver(someCompFactory)},
            providers
          ],
          platform.injector);
      return appInjector.get(ApplicationRef);
    }

    describe('ApplicationRef', () => {
      it('should throw when reentering tick', () => {
        var cdRef = <any>new SpyChangeDetectorRef();
        var ref = createApplication([]);
        try {
          ref.registerChangeDetector(cdRef);
          cdRef.spy('detectChanges').andCallFake(() => ref.tick());
          expect(() => ref.tick()).toThrowError('ApplicationRef.tick is called recursively');
        } finally {
          ref.unregisterChangeDetector(cdRef);
        }
      });

      describe('run', () => {
        it('should rethrow errors even if the exceptionHandler is not rethrowing', () => {
          var ref = createApplication([]);
          expect(() => ref.run(() => { throw new BaseException('Test'); })).toThrowError('Test');
        });

        it('should return a promise with rejected errors even if the exceptionHandler is not rethrowing',
           inject(
               [AsyncTestCompleter, Injector], (async: AsyncTestCompleter, injector: Injector) => {
                 var ref = createApplication([]);
                 var promise = ref.run(() => PromiseWrapper.reject('Test', null));
                 PromiseWrapper.catchError(promise, (e) => {
                   expect(e).toEqual('Test');
                   async.done();
                 });
               }));
      });
    });

    describe('coreLoadAndBootstrap', () => {
      it('should wait for asynchronous app initializers',
         inject([AsyncTestCompleter, Injector], (async: AsyncTestCompleter, injector: Injector) => {
           let completer: PromiseCompleter<any> = PromiseWrapper.completer();
           var initializerDone = false;
           TimerWrapper.setTimeout(() => {
             completer.resolve(true);
             initializerDone = true;
           }, 1);
           var app = createApplication(
               [{provide: APP_INITIALIZER, useValue: () => completer.promise, multi: true}]);
           coreLoadAndBootstrap(MyComp6, app.injector).then(_ => {
             expect(initializerDone).toBe(true);
             async.done();
           });
         }));
    });

    describe('coreBootstrap', () => {
      it('should throw if an APP_INITIIALIZER is not yet resolved',
         inject([Injector], (injector: Injector) => {
           var app = createApplication([{
             provide: APP_INITIALIZER,
             useValue: () => PromiseWrapper.completer().promise,
             multi: true
           }]);
           expect(() => app.bootstrap(someCompFactory))
               .toThrowError(
                   'Cannot bootstrap as there are still asynchronous initializers running. Wait for them using waitForAsyncInitializers().');
         }));
    });
  });
}

@Component({selector: 'my-comp', template: ''})
class MyComp6 {
}

class _ArrayLogger {
  res: any[] = [];
  log(s: any): void { this.res.push(s); }
  logError(s: any): void { this.res.push(s); }
  logGroup(s: any): void { this.res.push(s); }
  logGroupEnd(){};
}

class _MockComponentFactory extends ComponentFactory<any> {
  constructor(private _compRef: ComponentRef<any>) { super(null, null, null); }
  create(
      injector: Injector, projectableNodes: any[][] = null,
      rootSelectorOrNode: string|any = null): ComponentRef<any> {
    return this._compRef;
  }
}

class _MockComponentResolver implements ComponentResolver {
  constructor(private _compFactory: ComponentFactory<any>) {}

  resolveComponent(type: Type): Promise<ComponentFactory<any>> {
    return PromiseWrapper.resolve(this._compFactory);
  }
  clearCache() {}
}

class _MockComponentRef extends ComponentRef_<any> {
  constructor(private _injector: Injector) { super(null, null); }
  get injector(): Injector { return this._injector; }
  get changeDetectorRef(): ChangeDetectorRef { return <any>new SpyChangeDetectorRef(); }
  onDestroy(cb: Function) {}
}

class _MockConsole implements Console {
  log(message: string) {}
  warn(message: string) {}
}


text:
.. spelling::

    NLopt

.. index::
  single: unsorted ; NLopt

.. _pkg.NLopt:

NLopt
=====

-  `Official <https://github.com/stevengj/nlopt>`__
-  `Hunterized <https://github.com/hunter-packages/NLopt>`__
-  `Example <https://github.com/cpp-pm/hunter/blob/master/examples/NLopt/CMakeLists.txt>`__
-  Added by `t0p4 <https://github.com/t0p4>`__ (`pr-1617 <https://github.com/ruslo/hunter/pull/1617>`__)

.. literalinclude:: /../examples/NLopt/CMakeLists.txt
  :language: cmake
  :start-after: # DOCUMENTATION_START {
  :end-before: # DOCUMENTATION_END }


text:
namespace blink {

// The set of paint properties applying to a |PaintChunk|. These properties are
// not local-only paint style parameters such as color, but instead represent
// the hierarchy of transforms, clips, effects, etc, that apply to a contiguous
// chunk of display items. A single DisplayItemClient can generate multiple
// properties of the same type and this struct represents the total state of all
// properties for a given |PaintChunk|.
//
// This differs from |ObjectPaintProperties| because it only stores one property
// for each type (e.g., either transform or perspective, but not both).
struct PaintChunkProperties {
    // TODO(pdr): Add clip and scroll properties.
    RefPtr<TransformPaintPropertyNode> transform;
    RefPtr<ClipPaintPropertyNode> clip;
    RefPtr<EffectPaintPropertyNode> effect;
};

// Equality is based only on the pointers and is not 'deep' which would require
// crawling the entire property tree to compute.
inline bool operator==(const PaintChunkProperties& a, const PaintChunkProperties& b)
{
    return a.transform.get() == b.transform.get()
        && a.clip.get() == b.clip.get()
        && a.effect.get() == b.effect.get();
}

inline bool operator!=(const PaintChunkProperties& a, const PaintChunkProperties& b)
{
    return !(a == b);
}

// Redeclared here to avoid ODR issues.
// See platform/testing/PaintPrinters.h.
void PrintTo(const PaintChunkProperties&, std::ostream*);

} // namespace blink

#endif // PaintChunkProperties_h


text:
#ifndef __CCEditBox_h__
#define __CCEditBox_h__

#include "extensions/ExtensionMacros.h"
#include "../CCControlExtension/CCControlExtensions.h"
#include "../../../2d/text_input_node/CCIMEDelegate.h"

NS_CC_EXT_BEGIN

class EditBox;
class EditBoxImpl;

class EditBoxDelegate
{
	public :

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual ~EditBoxDelegate ( KDvoid ) { }

		/**
		 *	This method is called when an edit box gains focus after keyboard is shown.
		 *	@param editBox The edit box object that generated the event.
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid				editBoxEditingDidBegin ( EditBox* pEditBox ) { }

		/**
		 *	This method is called when an edit box loses focus after keyboard is hidden.
		 *	@param editBox The edit box object that generated the event.
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid				editBoxEditingDidEnd ( EditBox* pEditBox) { }

		/**
		 *	This method is called when the edit box text was changed.
		 *	@param editBox The edit box object that generated the event.
		 *	@param text The new text.
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid				editBoxTextChanged ( EditBox* pEditBox, const std::string& sText ) { }

		/**
		 *	This method is called when the return button was pressed or the outside area of keyboard was touched.
		 *	@param editBox The edit box object that generated the event.
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid				editBoxReturn ( EditBox* pEditBox ) = 0;

};

/**
 *	@brief Class for edit box.
 *
 *	You can use this widget to gather small amounts of text from the user.
 */

class EditBox : public ControlButton , public IMEDelegate
{
	public :

		enum class KeyboardReturnType
		{
			DEFAULT,
			DONE,
			SEND,
			SEARCH,
			GO
		};

		/**
		 *	@brief The EditBox::InputMode defines the type of text that the user is allowed
		 *	to enter.
		 */
		enum class InputMode
		{
			/**
			 *	The user is allowed to enter any text, including line breaks.
			 */
			ANY,

			/**
			 *	The user is allowed to enter an e-mail address.
			 */
			EMAIL_ADDRESS,

			/**
			 *	The user is allowed to enter an integer value.
			 */
			NUMERIC,

			/**
			 *	The user is allowed to enter a phone number.
			 */
			PHONE_NUMBER,

			/**
			 *	The user is allowed to enter a URL.
			 */
			URL,

			/**
			 *	The user is allowed to enter a real number value.
			 *	This extends kEditBoxInputModeNumeric by allowing a decimal point.
			 */
			DECIMAL,

			/**
			 *	The user is allowed to enter any text, except for line breaks.
			 */
			SINGLE_LINE,
		};

		/**
		 *	@brief The EditBox::InputFlag defines how the input text is displayed/formatted.
		 */
		enum class InputFlag
		{
			/**
			 *	Indicates that the text entered is confidential data that should be
			 *	obscured whenever possible. This implies EDIT_BOX_INPUT_FLAG_SENSITIVE.
			 */
			PASSWORD,

			/**
			 *	Indicates that the text entered is sensitive data that the
			 *	implementation must never store into a dictionary or table for use
			 *	in predictive, auto-completing, or other accelerated input schemes.
			 *	A credit card number is an example of sensitive data.
			 */
			SENSITIVE,

			/**
			 *	This flag is a hint to the implementation that during text editing,
			 *	the initial letter of each word should be capitalized.
			 */
			INITIAL_CAPS_WORD,

			/**
			 *	This flag is a hint to the implementation that during text editing,
			 *	the initial letter of each sentence should be capitalized.
			 */
			INITIAL_CAPS_SENTENCE,

			/**
			 *	Capitalize all characters automatically.
			 */
			INTIAL_CAPS_ALL_CHARACTERS,
		};

		/**
		 *	create a edit box with size.
		 *	@return An autorelease pointer of EditBox, you don't need to release it only if you retain it again.
		 */
		static EditBox*					create ( const Size& tSize, Scale9Sprite* pNormal9SpriteBg, Scale9Sprite* pPressed9SpriteBg = KD_NULL, Scale9Sprite* pDisabled9SpriteBg = KD_NULL );

		/**
		 *	Constructor.
		 *	@js ctor
		 */
		EditBox ( KDvoid );

		/**
		 *	Destructor.
		 *	@js NA
		 *	@lua NA
		 */
		virtual ~EditBox ( KDvoid );

		/**
		 *	Init edit box with specified size. This method should be invoked right after constructor.
		 *	@param size The size of edit box.
		 */
		KDbool							initWithSizeAndBackgroundSprite ( const Size& tSize, Scale9Sprite* pNormal9SpriteBg );

		/**
		 *	Gets/Sets the delegate for edit box.
		 *	@lua NA
		 */
		KDvoid							setDelegate ( EditBoxDelegate* pDelegate );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		EditBoxDelegate*				getDelegate ( KDvoid );

		/**
		 *	Registers a script function that will be called for EditBox events.
		 *
		 *	This handler will be removed automatically after onExit() called.
		 *	@code
		 *			-- lua sample
		 *	local function editboxEventHandler(eventType)
		 *     if eventType == "began" then
		 *			-- triggered when an edit box gains focus after keyboard is shown
		 *     elseif eventType == "ended" then
		 *			-- triggered when an edit box loses focus after keyboard is hidden.
		 *     elseif eventType == "changed" then
		 *			-- triggered when the edit box text was changed.
		 *     elseif eventType == "return" then
		 *			-- triggered when the return button was pressed or the outside area of keyboard was touched.
		 *     end
		 *	end
		 *
		 *	local editbox = EditBox:create(Size(...), Scale9Sprite:create(...))
		 *	editbox = registerScriptEditBoxHandler(editboxEventHandler)
		 *	@endcode
		 *
		 *	@param handler A number that indicates a lua function.
		 *	@js NA
		 *	@lua NA
		 */
		KDvoid							registerScriptEditBoxHandler ( KDint nHandler );

		/**
		 *	Unregisters a script function that will be called for EditBox events.
		 *	@js NA
		 *	@lua NA
		 */
		KDvoid							unregisterScriptEditBoxHandler ( KDvoid );

		/**
		 *	get a script Handler
		 *	@js NA
		 *	@lua NA
		 */
		KDint							getScriptEditBoxHandler ( KDvoid ) { return m_nScriptEditBoxHandler; }

		/**
		 *	Set the text entered in the edit box.
		 *	@param pText The given text.
		 */
		KDvoid							setText ( const KDchar* pText );

		/**
		 *	Get the text entered in the edit box.
		 *	@return The text entered in the edit box.
		 */
		const KDchar*					getText ( KDvoid );

		/**
		 *	Set the font.
		 *	@param pFontName The font name.
		 *	@param fontSize The font size.
		 */
		KDvoid							setFont ( const KDchar* pFontName, KDint nFontSize );

		/**
		 *	Set the font name.
		 *	@param pFontName The font name.
		 */
		KDvoid							setFontName ( const KDchar* pFontName );

		/**
		 *	Set the font size.
		 *	@param fontSize The font size.
		 */
		KDvoid							setFontSize ( KDint nFontSize );

		/**
		 *	Set the font color of the widget's text.
		 */
		KDvoid							setFontColor ( const Color3B& tColor );

		/**
		 *	Set the placeholder's font.
		 *	@param pFontName The font name.
		 *	@param fontSize The font size.
		 */
		KDvoid							setPlaceholderFont ( const KDchar* pFontName, KDint nFontSize );

		/**
		 *	Set the placeholder's font name.
		 *	@param pFontName The font name.
		 */
		KDvoid							setPlaceholderFontName ( const KDchar* pFontName );

		/**
		 *	Set the placeholder's font size.
		 *	@param fontSize The font size.
		 */
		KDvoid							setPlaceholderFontSize ( KDint nFontSize );

		/**
		 *	Set the font color of the placeholder text when the edit box is empty.
		 *	Not supported on IOS.
		 */
		KDvoid							setPlaceholderFontColor ( const Color3B& tColor );

		/**
		 *	Set a text in the edit box that acts as a placeholder when an
		 *	edit box is empty.
		 *	@param pText The given text.
		 */
		KDvoid							setPlaceHolder ( const KDchar* pText );

		/**
		 *	Get a text in the edit box that acts as a placeholder when an
		 *	edit box is empty.
		 */
		const KDchar*					getPlaceHolder ( KDvoid );

		/**
		 *	Set the input mode of the edit box.
		 *	@param inputMode One of the EditBox::InputMode constants.
		 */
		KDvoid							setInputMode ( InputMode eInputMode );

		/**
		 *	Sets the maximum input length of the edit box.
		 *	Setting this value enables multiline input mode by default.
		 *	Available on Android, iOS and Windows Phone.
		 *
		 *	@param maxLength The maximum length.
		 */
		KDvoid							setMaxLength ( KDint nMaxLength );

		/**
		 *	Gets the maximum input length of the edit box.
		 *
		 *	@return Maximum input length.
		 */
		KDint							getMaxLength ( KDvoid );

		/**
		 *	Set the input flags that are to be applied to the edit box.
		 *	@param inputFlag One of the EditBox::InputFlag constants.
		 */
		KDvoid							setInputFlag ( InputFlag eInputFlag );

		/**
		 *	Set the return type that are to be applied to the edit box.
		 *	@param returnType One of the EditBox::KeyboardReturnType constants.
		 */
		KDvoid							setReturnType ( EditBox::KeyboardReturnType eReturnType );

		/* override functions */
		virtual KDvoid					setPosition ( const Point& tPos );
		virtual KDvoid					setVisible ( KDbool bVisible );
		virtual KDvoid					setContentSize ( const Size& tSize );
		virtual KDvoid					setAnchorPoint ( const Point& tAnchorPoint );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					visit ( KDvoid );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					onEnter ( KDvoid );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					onExit ( KDvoid );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					keyboardWillShow ( IMEKeyboardNotificationInfo& tInfo );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					keyboardDidShow ( IMEKeyboardNotificationInfo& tInfo );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					keyboardWillHide ( IMEKeyboardNotificationInfo& tInfo );

		/**
		 *	@js NA
		 *	@lua NA
		 */
		virtual KDvoid					keyboardDidHide ( IMEKeyboardNotificationInfo& tInfo );

		/**
		 *	callback funtions
		 *	@js NA
		 *	@lua NA
		 */
		KDvoid							touchDownAction ( Object* pSender, Control::EventType eControlEvent );

	protected :

		EditBoxImpl*					m_pEditBoxImpl;
		EditBoxDelegate*				m_pDelegate;

		InputMode						m_eEditBoxInputMode;
		InputFlag						m_eEditBoxInputFlag;
		EditBox::KeyboardReturnType		m_eKeyboardReturnType;

		std::string						m_sText;
		std::string						m_sPlaceHolder;

		std::string						m_sFontName;
		std::string						m_sPlaceholderFontName;

		KDint							m_nFontSize;
		KDint							m_nPlaceholderFontSize;

		Color3B							m_tColText;
		Color3B							m_tColPlaceHolder;

		KDint							m_nMaxLength;
		KDfloat							m_fAdjustHeight;
		KDint							m_nScriptEditBoxHandler;
};

NS_CC_EXT_END

#endif	// __CCEditBox_h__


text:
package com.blazebit.persistence.view.testsuite.update.subview.inverse.onetoone.simple.model;

import com.blazebit.persistence.testsuite.entity.DocumentInfoSimple;
import com.blazebit.persistence.view.CreatableEntityView;
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.UpdatableEntityView;

/**
 *
 * @author Christian Beikov
 * @since 1.3.0
 */
@CreatableEntityView
@UpdatableEntityView
@EntityView(DocumentInfoSimple.class)
public interface UpdatableDocumentInfoView extends DocumentInfoIdView {

    String getSomeInfo();
    void setSomeInfo(String someInfo);

}


text:
param($config, $packageInfo, $installArgs, [ScriptBlock] $installAction)

$webSiteName = $config.siteName
$webSitePath = "IIS:\Sites\$webSiteName"
$webSitePhysicalPath = $config.SitePhysicalPath
$tempDir = "$($env:temp)\$((Get-Date).Ticks)"

New-Item $tempDir -type Directory | Out-Default

if (-not $config.Port) {
    throw "In order to create new website, please specify the port first!"
}

## renew website
if(-not (Test-Path $webSitePath)) {
    Reset-AppPool $config.siteAppPoolName $config.siteAppPoolUser $config.siteAppPoolPassword $installArgs.loadUserProfile
    New-Website -Name $webSiteName -Port $config.Port -ApplicationPool $config.siteAppPoolName -PhysicalPath $tempDir | Out-Default
}

if(-not (Test-Path $webSitePhysicalPath)) {
    New-Item $webSitePhysicalPath -type Directory | Out-Default
}

###renew webapplication
$webapplicationName = $config.applicationName
$webSitePath = "IIS:\Sites\$webapplicationName"
$applicationPath = $config.ApplicationPhysicalPath
$loadUserProfile = $installArgs.loadUserProfile

if(-not (Test-Path $applicationPath)) {
    New-Item $applicationPath -type Directory | Out-Default
}

$tempApplication = Get-Webapplication -site $websiteName -name $webapplicationName
if($tempApplication -eq $null) {
    Reset-AppPool $config.ApplicationAppPoolName $config.ApplicationAppPoolUser $config.ApplicationAppPoolPassword $loadUserProfile
    New-WebApplication -Site $webSiteName -Name $webapplicationName -ApplicationPool $config.ApplicationAppPoolName -PhysicalPath $config.ApplicationPhysicalPath | Out-Default
}

& $installAction

Remove-Item $tempDir -Force -Recurse -ErrorAction SilentlyContinue | Out-Default


text:
(function () {

    "use strict";

    angular
    	.module('KHO_CRM')
    	.controller('GenereteTextToWebsiteController', GenereteTextToWebsiteController);

    GenereteTextToWebsiteController.$inject = [
        '$scope',
        '$http',
        'Todos',
        '$timeout',
        'SetAlertClass',
        '$rootScope',
        'KHO_CRM_CONFIG',
    ];

    function GenereteTextToWebsiteController($scope, $http, Todos, $timeout, SetAlertClass, $rootScope, KHO_CRM_CONFIG) {

    	$scope.users = [];

    	Todos.get().success(function(data) {
$scope.users = data;
               		angular.forEach(data, function(user) {

               			angular.forEach(user.attempt, function(attempt) {
               				attempt.userID = user._id;
               				attempt.name = user.name;
               				attempt.surname = user.surname;
               				attempt.team = user.team;

               				//$scope.users.push(attempt);

               			});

			});

console.log($scope.users);

            }).error(function(err){
                console.log("GET ERROR: " + err);
            });

    }

})();


text:
@interface View2Controller : UIViewController

@end


text:
package nl.littlebluefrog.ld34.logic.statemachine;

import nl.littlebluefrog.ld34.logic.GameLogicController;

/**
 * @author Johan Hutting
 */
public class EndLevel implements StateMachineNode {
    @Override
    public StateMachineNode next(GameLogicController gamelogic) {
        throw new IllegalStateException("should not arrive here");
    }

    @Override
    public StateMachineNode next(int buttonIndex, GameLogicController gamelogic) {
        gamelogic.endLevel();
        return new RollTheDice(gamelogic);
    }
}


text:
package com.google.common.hash;

import com.google.common.annotations.Beta;
import com.google.errorprone.annotations.DoNotMock;
import java.io.Serializable;
import org.checkerframework.checker.nullness.qual.Nullable;

/**
 * An object which can send data from an object of type {@code T} into a {@code PrimitiveSink}.
 * Implementations for common types can be found in {@link Funnels}.
 *
 *
Note that serialization of {@linkplain BloomFilter bloom filters} requires the proper
 * serialization of funnels. When possible, it is recommended that funnels be implemented as a
 * single-element enum to maintain serialization guarantees. See Effective Java (2nd Edition), Item
 * 3: "Enforce the singleton property with a private constructor or an enum type". For example:
 *
 *
{@code
 * public enum PersonFunnel implements Funnel<Person> {
 *   INSTANCE;
 *   public void funnel(Person person, PrimitiveSink into) {
 *     into.putUnencodedChars(person.getFirstName())
 *         .putUnencodedChars(person.getLastName())
 *         .putInt(person.getAge());
 *   }
 * }
 * }

 *
 * @author Dimitris Andreou
 * @since 11.0
 */
@Beta
@DoNotMock("Implement with a lambda")
@ElementTypesAreNonnullByDefault
public interface Funnel<T extends @Nullable Object> extends Serializable {

  /**
   * Sends a stream of data from the {@code from} object into the sink {@code into}. There is no
   * requirement that this data be complete enough to fully reconstitute the object later.
   *
   * @since 12.0 (in Guava 11.0, {@code PrimitiveSink} was named {@code Sink})
   */
  void funnel(@ParametricNullness T from, PrimitiveSink into);
}


text:
<?php

class Rootd_Link_Model_Resource_Node
    extends Mage_Core_Model_Resource_Db_Abstract
{

    /**
     * Initialize table.
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('link/node', 'link_id');
    }

    /**
     * Retrieve select object for load object data.
     *
     * @param string                $field  The field.
     * @param mixed                 $value  The value.
     * @param Rootd_Link_Model_Node $object The link model.
     *
     * @return Zend_Db_Select
     */
    protected function _getLoadSelect($field, $value, $object)
    {
        $select = parent::_getLoadSelect($field, $value, $object);

        if ( !is_null($object->getStoreId()) ) {
            $select->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, $object->getStoreId()))
                ->order('store_id ' . Varien_Db_Select::SQL_DESC)
                ->limit(1);
        }

        return $select;
    }

    /**
     * Load rewrite information for request.
     *
     * @param Rootd_Link_Model_Node $object The link object.
     * @param array|string          $path   The path(s) to load.
     *
     * @return Rootd_Link_Model_Resource_Node
     */
    public function loadByRequestPath(Rootd_Link_Model_Node $object, $path)
    {
        $today = date(
            Varien_Db_Adapter_Pdo_Mysql::DATE_FORMAT,
            Mage::getSingleton('core/date')->timestamp(time())
        );

        if (!is_array($path)) {
            $path = array($path);
        }

        $pathBind = array();

        foreach ($path as $key => $url) {
            $pathBind['path' . $key] =
                $path[$key] = ltrim($url, (Mage::helper('link')->getFrontName() . '/'));
        }

        // Determine column by which to load
        $parts = explode('/', $path[0]);
        if ($parts[0] == 'node') {
            $loadByName = 'link_id';
            $loadBy     = "`main_table`.`{$loadByName}`";
            $pathBind   = array('id0' => $parts[1]);
        } else {
            $loadByName = 'request_path';
            $loadBy     = "`main_table`.`{$loadByName}`";
        }

        $adapter = $this->_getReadAdapter();

        $select = $adapter->select()
            ->from(
                array('main_table' => $this->getMainTable()),
                array('main_table.*', 'options' => new Zend_Db_Expr("'RP'")) // Force permanent redirect option
            )
            ->where($loadBy. ' IN (:' . implode(', :', array_flip($pathBind)) . ')')
            ->where('`main_table`.`store_id` IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId()))
            ->where(
                new Zend_Db_Expr('
                    (`main_table`.`is_active` = 1 AND `main_table`.`active_from` IS NULL AND `main_table`.`active_to` IS NULL) OR
                    (`main_table`.`is_active` = 1 AND `main_table`.`active_from` <= ? AND `main_table`.`active_to` >= ?)'),
                array($today)
            )
            ->joinLeft(
                array('a' => Mage::getResourceSingleton('link/node_attachment')->getMainTable()),
                "`main_table`.`object_id` = `a`.`attachment_id`",
                array()
            );

        //Zend_Debug::dump($select->assemble());exit;

        $items = $adapter->fetchAll($select, $pathBind);

        //Zend_Debug::dump($items);exit;

        // Determine path to use by lowest penalty
        if ($loadByName == 'link_id') {
            $foundItem = array_shift($items);
        } else {
            $mapPenalty     = array_flip(array_values($path)); // Mapping array: lower index = better
            $currentPenalty = null;
            $foundItem      = null;

            foreach ($items as $item) {
                if (!array_key_exists($item['request_path'], $mapPenalty)) {
                    continue;
                }

                $penalty = $mapPenalty[$item['request_path']] << 1 + ($item['store_id'] ? 0 : 1);

                if (!$foundItem || $currentPenalty > $penalty) {
                    $foundItem      = $item;
                    $currentPenalty = $penalty;

                    if (!$currentPenalty) {
                        break; // Found best matching item with zero penalty, no reason to continue
                    }
                }
            }
        }

        //Zend_Debug::dump($foundItem);exit;

        // Set data and finish loading
        if ($foundItem) {
            $object->setData($foundItem);
        }

        $this->unserializeFields($object);
        $this->_afterLoad($object);

        return $this;
    }

    /**
     * Manage the attachment on the link.
     *
     * @param Rootd_Link_Model_Node $object The link object.
     *
     * @return Rootd_Link_Model_Resource_Node
     */
    public function setAttachment($model)
    {
        // Remove existing attachment
        if ($model->getObjectId()) {
            $model->getAttachment()->delete();
        }

        if ($model->getTargetFile()) {
            $attachment = Mage::getModel('link/node_attachment');

            $attachment->setLinkId($model->getId())
                // Currently only supports files
                ->setTypeId(Rootd_Link_Model_Node_Attachment::TYPE_FILE)
                ->setTargetPath($model->getTargetFile());

            $attachment->save();

            $model->setObjectId($attachment->getId())
                ->setAttachment($attachment)
                ->setTargetPath('');
        }

        return $this;
    }

}


text:
package net.safedata.spring.intro.controllers;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(EmptyResultDataAccessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public @ResponseBody String nuAvem(EmptyResultDataAccessException e, HttpServletRequest request) {
        return "n-avem useru' " + request.getParameter("name");
    }
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Game::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->unique()->name,
        'description' => $faker->text(200),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\GameBuild::class, function (Faker\Generator $faker) {
    return [
        'game_id' => function () {
            return factory(App\Game::class)->create()->id;
        },
        'name' => $faker->numerify('v#.##'),
        'description' => $faker->text(200),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\MetricCategory::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->word,
        'description' => $faker->text(200),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\MetricName::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->slug,
        'metric_category_id' => function () {
            return factory(App\MetricCategory::class)->create()->id;
        },
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Device::class, function (Faker\Generator $faker) {
    return [
        'uid' => $faker->unique()->sha1,
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Platform::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->randomElement([
            $faker->numerify('Windows 10 Build #####.##'),
            $faker->numerify('macOS 10.1#'),
            $faker->numerify('GNU/Linux 4.#.#'),
            $faker->numerify('iOS 10.#'),
            $faker->randomElement([
                $faker->numerify('Android Nougat 7.#'),
                $faker->numerify('Android Marshmallow 6.#'),
                $faker->numerify('Android Lollipop 5.#'),
                $faker->numerify('Android KitKat 4.4.#'),
            ]),
        ]),
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Session::class, function (Faker\Generator $faker) {
    return [
        'device_id' => function () {
            return factory(App\Device::class)->create()->id;
        },
        'platform_id' => function () {
            return factory(App\Platform::class)->create()->id;
        },
        'game_build_id' => function () {
            return factory(App\GameBuild::class)->create()->id;
        },
        'ip_address' => $faker->ipv4,
    ];
});

/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Session::class, function (Faker\Generator $faker) {
    return [
        'device_id' => function () {
            return factory(App\Device::class)->create()->id;
        },
        'platform_id' => function () {
            return factory(App\Platform::class)->create()->id;
        },
        'game_build_id' => function () {
            return factory(App\GameBuild::class)->create()->id;
        },
        'ip_address' => $faker->ipv4,
    ];
});

$factory->define(App\Metric::class, function (Faker\Generator $faker) {
    return [
        'session_id' => function () {
            return factory(App\Session::class)->create()->id;
        },
        'metric_name_id' => function () {
            return factory(App\MetricName::class)->create()->id;
        },
        'value' => $faker->randomNumber(3),
        'entries' => $faker->randomDigit(),
    ];
});


text:
import type { NodePath } from '@babel/traverse';
import type { FlowType } from '@babel/types';

/**
 * Gets the most inner valuable TypeAnnotation from path. If no TypeAnnotation
 * can be found null is returned
 */
export default function getTypeAnnotation<T = FlowType>(
  path: NodePath,
): NodePath<T> | null {
  if (!path.has('typeAnnotation')) return null;

  let resultPath = path;

  do {
    resultPath = resultPath.get('typeAnnotation') as NodePath;
  } while (
    resultPath.has('typeAnnotation') &&
    !resultPath.isFlowType() &&
    !resultPath.isTSType()
  );

  // @ts-ignore
  return resultPath;
}


text:
<!DOCTYPE html>

    <title>Payload Enum Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset='utf-8'>

CleanroomLogger Docs (100% documented)

View on GitHub

        CleanroomLogger Reference

        Payload Enum Reference

          Classes

                DailyRotatingLogFileRecorder

                FileLogRecorder

                LogReceptacle

                LogRecorderBase

          Enums

                LogSeverity

          Extensions

                LogSeverity

          Protocols

                LogConfiguration

                LogFilter

                LogFormatter

                LogRecorder

          Structs

                ASLLogRecorder

                DefaultLogConfiguration

                DefaultLogFormatter

                Log

                LogChannel

                LogEntry

                LogSeverityFilter

Payload

Represents the payload contained within a log entry.

                    Value

The payload contains an arbitrary value, or nil.

Declaration

Swift

case Value(Any?)

                    Message

The payload contains a text message.

Declaration

Swift

case Message(String)

                    Trace

The log entry is a trace call and contains no explicit payload.

Declaration

Swift

case Trace

© 2014-2015 Gilt Groupe. All rights reserved. (Last updated: 2015-06-19)

Generated by jazzy ♪♫ v0.2.1, a Realm project.


text:
var initializer = function() {
  $('.toggle-bool-switch').click(function(e) {
    var boolSwitch = $(e.target);

    var objectId = boolSwitch.data('object_id');
    var model = boolSwitch.data('model');
    var field = boolSwitch.data('field');

    var url = boolSwitch.data('url');
    var value = boolSwitch.data('value');
    var successMessage = boolSwitch.data('success_message');
    var data = { id: objectId };
    data[model] = {};
    data[model][field] = !value;

    $.ajax({
      url: url,
      data: data,
      dataType: 'json',
      headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
      error: function() {
        var errorMsg = 'Error: Update Unsuccessful';
        alert(errorMsg);
      },
      success: function() {
        boolSwitch.data('value', !value);
        boolSwitch.toggleClass('on');
        if (!boolSwitch.hasClass('notify-success')) return;
        $(function() {
          setTimeout(alert(successMessage), 500);
        });
      },
      type: 'PATCH',
    });
  });
};

$(initializer);
$(document).on('turbolinks:load turbo:load', initializer);


text:
//
// Copyright 2010-2011 Three Crickets LLC.
//
// The contents of this file are subject to the terms of the Apache License
// version 2.0: http://www.opensource.org/licenses/apache2.0.php
//
// Alternatively, you can obtain a royalty free commercial license with less
// limitations, transferable or non-transferable, directly from Three Crickets
// at http://threecrickets.com/
//

document.executeOnce('/mongo-db/')
document.executeOnce('/constants/')

function handleInit(conversation) {
	conversation.addMediaTypeByName('application/json')
	conversation.addMediaTypeByName('text/plain')
}

function isSystem(collectionName) {
	return (collectionName.substr(0, 7) == 'system.') || (collectionName.substr(0, 4) == 'tmp.')
}
function handlePost(conversation)
{/*passo i dati in post per nasconderli
	*/
	var text = JSON.from(conversation.form,true)
	var pwd = text.loginPassword
	var username =text.loginUsername

	//return JSON.to({uname:text.loginUsername,pwd:text.loginPassword},true)
	var connection = application.globals.get('mongoDbConnection')
		if (null === connection) {
			try {
				connection = MongoDB.connect('127.0.0.1')
				application.globals.put('mongoDbConnection', connect)
			}
			catch (x) {
			}
		}
		var firm = conversation.query.get('firm')
		var databaseName = db_name//'node-mongo-bb'//databaseNames[d]
					var database = connection.getDB(databaseName)
					var children = []
					var systemChildren = []
					var collectionNames = database.collectionNames.toArray()
					var connection = new MongoDB.connect('127.0.0.1')
					var collection = new MongoDB.Collection('users', {db: database, connection: connection})
					var text =conversation.entity.text
					var user = collection.findOne({$and:[{"user":username},{password:pwd}]})
					var session = new MongoDB.Collection('session', {db: database, connection: connection})
					var results={}
					if (null!= user){
						dateObj = new Date()
						/*user.logged_on_y = dateObj.getFullYear()
						user.logged_on_m = dateObj.getMonth()
						user.logged_on_d = dateObj.getDate()+1*/
						user.logged_on = dateObj
						var session_doc = {}
						session_doc.user = user
						//elimino le vecchie sessioni più vecchie di 9 ore
						//session.remove({$where:"new Date()-new Date(this.user.logged_on_y,this.user.logged_on_m,this.user.logged_on_d)>1000*24*60*60"})
						session.remove({$where:"new Date()-this.user.logged_on>60*60*9*1000"})
						session.insert(session_doc)
						session.ensureIndex({logged_on:1})
						//cerco l'ultima sessione creata dall'utente
						var new_session= session.find({'user.id':user.id}).sort({_id:-1}).limit(1).toArray()[0]
						var session_id = new_session._id.toString()
						user.session_id = session_id
						results.user = user
						results.success = true
						return JSON.to(results,true)
					}
					else
					{
						results.success=false
						return JSON.to(results,true)
					}

	//return "{firm: 'Ed Spencer', note: 'ed@sencha.com','paese':'it'}"
	//return JSON.to(results,true)
}


text:
Rails.application.routes.draw do
  resources :posts do
    resources :comments
  end
  controller :sessions do
    get  'login'  => :new
    post 'login'  => :create
    get  'logout' => :destroy
  end
  root :to => 'posts#index'
end


text:
L20n tinker
===========

A fiddle tool for L20n.  Write some L20n code and see the results instantly!

# L20n tinker - main informations

The main HTML file is, of course the index.html. You might find in it the language selection field (#lang) and translation file selection field (#fixture).

Another important thing is the included JS files. The most important is script.js.

# script.js

In script.js you have to find two things:

  - Function: loadFixture() - located in 228 line
  - Event: $('#lang').change() - located in 282 line
  - Const: fixtures - located in 209 line

### fixtures

You can find information where are located files with translations and also a json file:

```js
	default: {
      ftl: 'fixtures/default.ftl',
      json: 'fixtures/default.json',
    },
```

I deleted extension of the ftl file - because I need to add 'lang' value in it.

Oryginal version:

```js
  const fixtures = {
    default: {
      ftl: 'fixtures/default.ftl',
      json: 'fixtures/default.json',
    },
    aboutDialog: {
      resId: '/browser/aboutDialog.ftl',
      ftl: 'fixtures/aboutDialog.ftl',
      json: 'fixtures/aboutDialog.json',
      demo: true,
    },
    aboutSupport: {
      resId: '/global/aboutSupport.ftl',
      ftl: 'fixtures/aboutSupport.ftl',
      json: 'fixtures/aboutSupport.json',
      demo: true,
    },
  };
```

After my modyfications:

```js
  const fixtures = {
    default: {
      ftl: 'fixtures/default',
      json: 'fixtures/default.json',
    },
    aboutDialog: {
      resId: '/browser/aboutDialog.ftl',
      ftl: 'fixtures/aboutDialog',
      json: 'fixtures/aboutDialog.json',
      demo: true,
    },
    aboutSupport: {
      resId: '/global/aboutSupport.ftl',
      ftl: 'fixtures/aboutSupport',
      json: 'fixtures/aboutSupport.json',
      demo: true,
    },
  };
```

### loadFixture()

 And I put value of 'lang' to the path to FTL file. Because I want to get the file with selected language:

 ```js
 fetch(fixtures[name].ftl + '.' + config.lang + '.ftl').then(resp => resp.text()),
 ```

  Oryginal version:

```js
  function loadFixture(name) {
    return Promise.all([
      fetch(fixtures[name].ftl).then(resp => resp.text()),
      fetch(fixtures[name].json).then(resp => resp.text()),
    ]).then(([ftl, args]) => {
      source.setValue(ftl);
      context.setValue(args);
      source.clearSelection();
      context.clearSelection();
      source.gotoLine(0);
    }).then(
      update
    );
  }
  ```

  After my modyfications:

  ```js
  function loadFixture(name) {
    return Promise.all([
      fetch(fixtures[name].ftl + '.' + config.lang + '.ftl').then(resp => resp.text()),
      fetch(fixtures[name].json).then(resp => resp.text()),
    ]).then(([ftl, args]) => {
      source.setValue(ftl);
      context.setValue(args);
      source.clearSelection();
      context.clearSelection();
      source.gotoLine(0);
    }).then(
      update
    );
  }
  ```

  ### $('#lang').change()

  This part is running when user selects the language from select list.

  I added 'name' variable and I get value from '#fixture' field:

  ```js
	const fixture = $('#fixture').val();
	config.fixture = fixture;
  ```

  And than I added a loadFixture function call:

  ```js
    loadFixture(fixture).then(
      () => L20nDemo.update()
    );
  ```

  I deleted update(); function call, because loadFixture has this function call as well.

  Oryginal version:

  ```js
  $('#lang').change(function(evt) {
    config.lang = $(this).val();
    update();
    L20nDemo.update();
  });
  ```

  After my modyfications:

  ```js
  $('#lang').change(function(evt) {
    config.lang = $(this).val();
	const fixture = $('#fixture').val();
	config.fixture = fixture;
	loadFixture(fixture).then(
      () => L20nDemo.update()
    );
  });
  ```

  # FTL files

  We have FTL files located in fixtures folder. They should has file name like this:

  ```
 default.pl.ftl
 default.en-US.ftl
  ```

  The local part of the file name depend from values in #lang field. Right now it looks like this:

  ```html
<select id="lang">
    <option value="en-US" selected>English</option>
    <option value="pl">Polish</option>
</select>
  ```


text:
require File.join(File.dirname(__FILE__), '..', 'lib', 'tadpole')

describe Tadpole::SectionProviders::ERBProvider do
  before do
    Tadpole.template_paths.clear
    Tadpole.register_template_path(File.dirname(__FILE__) + '/examples')
  end

  describe '#render' do
    it "should setup locals through run" do
      Tadpole('erb').run(:a_variable => 1).should == '1'
    end

    it "should setup locals through #render" do
      Tadpole('erb2').run.should == '2'
    end
  end
end


text:
namespace device {

class BluetoothRemoteGattDescriptor;
class BluetoothRemoteGattService;
class MockBluetoothGattDescriptor;
class MockBluetoothGattService;

class MockBluetoothGattCharacteristic
    : public BluetoothRemoteGattCharacteristic {
 public:
  MockBluetoothGattCharacteristic(MockBluetoothGattService* service,
                                  const std::string& identifier,
                                  const BluetoothUUID& uuid,
                                  bool is_local,
                                  Properties properties,
                                  Permissions permissions);
  ~MockBluetoothGattCharacteristic() override;

  MOCK_CONST_METHOD0(GetIdentifier, std::string());
  MOCK_CONST_METHOD0(GetUUID, BluetoothUUID());
  MOCK_CONST_METHOD0(IsLocal, bool());
  MOCK_CONST_METHOD0(GetValue, const std::vector<uint8_t>&());
  MOCK_CONST_METHOD0(GetService, BluetoothRemoteGattService*());
  MOCK_CONST_METHOD0(GetProperties, Properties());
  MOCK_CONST_METHOD0(GetPermissions, Permissions());
  MOCK_CONST_METHOD0(IsNotifying, bool());
  MOCK_CONST_METHOD0(GetDescriptors,
                     std::vector<BluetoothRemoteGattDescriptor*>());
  MOCK_CONST_METHOD1(GetDescriptor,
                     BluetoothRemoteGattDescriptor*(const std::string&));
  MOCK_METHOD1(UpdateValue, bool(const std::vector<uint8_t>&));
#if defined(OS_CHROMEOS)
  void StartNotifySession(NotificationType t,
                          NotifySessionCallback c,
                          ErrorCallback ec) override {
    StartNotifySession_(t, c, ec);
  }
  MOCK_METHOD3(StartNotifySession_,
               void(NotificationType, NotifySessionCallback&, ErrorCallback&));
#endif
  void StartNotifySession(NotifySessionCallback c, ErrorCallback ec) override {
    StartNotifySession_(c, ec);
  }
  MOCK_METHOD2(StartNotifySession_,
               void(NotifySessionCallback&, ErrorCallback&));
  void StopNotifySession(BluetoothGattNotifySession* s,
                         base::OnceClosure c) override {
    StopNotifySession_(s, c);
  }
  MOCK_METHOD2(StopNotifySession_,
               void(BluetoothGattNotifySession*, base::OnceClosure&));
  void ReadRemoteCharacteristic(ValueCallback c, ErrorCallback ec) override {
    ReadRemoteCharacteristic_(c, ec);
  }
  MOCK_METHOD2(ReadRemoteCharacteristic_, void(ValueCallback&, ErrorCallback&));
  void WriteRemoteCharacteristic(const std::vector<uint8_t>& v,
                                 base::OnceClosure c,
                                 ErrorCallback ec) override {
    WriteRemoteCharacteristic_(v, c, ec);
  }
  MOCK_METHOD3(WriteRemoteCharacteristic_,
               void(const std::vector<uint8_t>&,
                    base::OnceClosure&,
                    ErrorCallback&));
#if defined(OS_CHROMEOS)
  void PrepareWriteRemoteCharacteristic(const std::vector<uint8_t>& v,
                                        base::OnceClosure c,
                                        ErrorCallback ec) override {
    PrepareWriteRemoteCharacteristic_(v, c, ec);
  }
  MOCK_METHOD3(PrepareWriteRemoteCharacteristic_,
               void(const std::vector<uint8_t>&,
                    base::OnceClosure&,
                    ErrorCallback&));
#endif
  MOCK_METHOD1(WriteWithoutResponse, bool(base::span<const uint8_t>));

  void AddMockDescriptor(
      std::unique_ptr<MockBluetoothGattDescriptor> mock_descriptor);

 protected:
#if defined(OS_CHROMEOS)
  void SubscribeToNotifications(BluetoothRemoteGattDescriptor* d,
                                NotificationType t,
                                base::OnceClosure c,
                                ErrorCallback ec) override {
    SubscribeToNotifications_(d, t, c, ec);
  }
  MOCK_METHOD4(SubscribeToNotifications_,
               void(BluetoothRemoteGattDescriptor*,
                    NotificationType,
                    base::OnceClosure&,
                    ErrorCallback&));
#else
  void SubscribeToNotifications(BluetoothRemoteGattDescriptor* d,
                                base::OnceClosure c,
                                ErrorCallback ec) override {
    SubscribeToNotifications_(d, c, ec);
  }
  MOCK_METHOD3(SubscribeToNotifications_,
               void(BluetoothRemoteGattDescriptor*,
                    base::OnceClosure&,
                    ErrorCallback&));
#endif
  void UnsubscribeFromNotifications(BluetoothRemoteGattDescriptor* d,
                                    base::OnceClosure c,
                                    ErrorCallback ec) override {
    UnsubscribeFromNotifications_(d, c, ec);
  }
  MOCK_METHOD3(UnsubscribeFromNotifications_,
               void(BluetoothRemoteGattDescriptor*,
                    base::OnceClosure&,
                    ErrorCallback&));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockBluetoothGattCharacteristic);
};

}  // namespace device

#endif  // DEVICE_BLUETOOTH_TEST_MOCK_BLUETOOTH_GATT_CHARACTERISTIC_H_


text:
#import <Foundation/Foundation.h>
#import "KGWebSocket.h"

typedef enum {
    KGPauseStrategy_DO_NOT_UPDATE_DELAY = 0,
    KGPauseStrategy_UPDATE_DELAY        = 1
} KGPauseStrategy;

@interface KGResumableTimer : NSObject

- (id) initWithTarget:(id)target delay:(int)delay updateDelayWhenPaused:(BOOL)update;

- (void) cancel;

- (int) delay;

- (void) pause;

- (void) resume;

- (void) start;

@property (copy) void (^didTimerFire)(id target);

@end