text:
import datetime
import logging

from django.core.management.base import BaseCommand
from osf.models import Identifier

from framework.celery_tasks import app

logger = logging.getLogger(__name__)

@app.task(name='osf.management.commands.sync_doi_metadata', max_retries=5, default_retry_delay=60)
def sync_identifier_doi(identifier_id):
    identifier = Identifier.objects.get(id=identifier_id)
    identifier.referent.request_identifier_update('doi')
    identifier.save()
    logger.info(f' doi update for {identifier.value} complete')

def sync_doi_metadata(modified_date, batch_size=100, dry_run=True, sync_private=False):

    identifiers = Identifier.objects.filter(
        category='doi',
        deleted__isnull=True,
        modified__lte=modified_date,
        object_id__isnull=False,
    )[:batch_size]
    logger.info(f'{"[DRY RUN]: " if dry_run else ""}'
                f'{identifiers.count()} identifiers to mint')

    for identifier in identifiers:
        if not dry_run:
            if (identifier.referent.is_public and not identifier.referent.deleted and not identifier.referent.is_retracted) or sync_private:
                sync_identifier_doi.apply_async(kwargs={'identifier_id': identifier.id})

        logger.info(f'{"[DRY RUN]: " if dry_run else ""}'
                    f' doi minting for {identifier.value} started')

class Command(BaseCommand):
    """ Adds updates all DOIs, will remove metadata for DOI bearing resources that have been withdrawn. """
    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            '--dry_run',
            action='store_true',
            dest='dry_run',
        )
        parser.add_argument(
            '--sync_private',
            action='store_true',
            dest='sync_private',
        )
        parser.add_argument(
            '--batch_size',
            '-b',
            type=int,
            default=100,
            help='number of dois to update in this batch.',
        )
        parser.add_argument(
            '--modified_date',
            '-m',
            type=lambda s: datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f'),
            help='include all dois updated before this date.',
            required=True
        )

    def handle(self, *args, **options):
        dry_run = options.get('dry_run')
        sync_private = options.get('sync_private')
        batch_size = options.get('batch_size')
        modified_date = options.get('modified_date')
        sync_doi_metadata(modified_date, batch_size, dry_run=dry_run, sync_private=sync_private)


text:
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Contains extension methods to <see cref="IdentityBuilder"/> for adding entity framework stores.
/// </summary>
public static class IdentityEntityFrameworkBuilderExtensions
{
    /// <summary>
    /// Adds an Entity Framework implementation of identity information stores.
    /// </summary>
    /// <typeparam name="TContext">The Entity Framework database context to use.</typeparam>
    /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param>
    /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns>
    public static IdentityBuilder AddEntityFrameworkStores<TContext>(this IdentityBuilder builder)
        where TContext : DbContext
    {
        AddStores(builder.Services, builder.UserType, builder.RoleType, typeof(TContext));
        return builder;
    }

    private static void AddStores(IServiceCollection services, Type userType, Type? roleType, Type contextType)
    {
        var identityUserType = FindGenericBaseType(userType, typeof(IdentityUser<>));
        if (identityUserType == null)
        {
            throw new InvalidOperationException(Resources.NotIdentityUser);
        }

        var keyType = identityUserType.GenericTypeArguments[0];

        if (roleType != null)
        {
            var identityRoleType = FindGenericBaseType(roleType, typeof(IdentityRole<>));
            if (identityRoleType == null)
            {
                throw new InvalidOperationException(Resources.NotIdentityRole);
            }

            Type userStoreType;
            Type roleStoreType;
            var identityContext = FindGenericBaseType(contextType, typeof(IdentityDbContext<,,,,,,,>));
            if (identityContext == null)
            {
                // If its a custom DbContext, we can only add the default POCOs
                userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
                roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
            }
            else
            {
                userStoreType = typeof(UserStore<,,,,,,,,>).MakeGenericType(userType, roleType, contextType,
                    identityContext.GenericTypeArguments[2],
                    identityContext.GenericTypeArguments[3],
                    identityContext.GenericTypeArguments[4],
                    identityContext.GenericTypeArguments[5],
                    identityContext.GenericTypeArguments[7],
                    identityContext.GenericTypeArguments[6]);
                roleStoreType = typeof(RoleStore<,,,,>).MakeGenericType(roleType, contextType,
                    identityContext.GenericTypeArguments[2],
                    identityContext.GenericTypeArguments[4],
                    identityContext.GenericTypeArguments[6]);
            }
            services.TryAddScoped(typeof(IUserStore<>).MakeGenericType(userType), userStoreType);
            services.TryAddScoped(typeof(IRoleStore<>).MakeGenericType(roleType), roleStoreType);
        }
        else
        {   // No Roles
            Type userStoreType;
            var identityContext = FindGenericBaseType(contextType, typeof(IdentityUserContext<,,,,>));
            if (identityContext == null)
            {
                // If its a custom DbContext, we can only add the default POCOs
                userStoreType = typeof(UserOnlyStore<,,>).MakeGenericType(userType, contextType, keyType);
            }
            else
            {
                userStoreType = typeof(UserOnlyStore<,,,,,>).MakeGenericType(userType, contextType,
                    identityContext.GenericTypeArguments[1],
                    identityContext.GenericTypeArguments[2],
                    identityContext.GenericTypeArguments[3],
                    identityContext.GenericTypeArguments[4]);
            }
            services.TryAddScoped(typeof(IUserStore<>).MakeGenericType(userType), userStoreType);
        }
    }

    private static Type? FindGenericBaseType(Type currentType, Type genericBaseType)
    {
        Type? type = currentType;
        while (type != null)
        {
            var genericType = type.IsGenericType ? type.GetGenericTypeDefinition() : null;
            if (genericType != null && genericType == genericBaseType)
            {
                return type;
            }
            type = type.BaseType;
        }
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.auth0.json.mgmt.organizations;

import com.auth0.json.JsonMatcher;
import com.auth0.json.JsonTest;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class MembersTest extends JsonTest<Member> {

    @Test
    public void shouldSerialize() throws Exception {
        Member member = new Member();
        member.setEmail("email@domain.com");
        member.setName("name");
        member.setPicture("https://myprofilepic.com");

        String serialized = toJSON(member);
        assertThat(serialized, is(notNullValue()));
        assertThat(serialized, JsonMatcher.hasEntry("email", "email@domain.com"));
        assertThat(serialized, JsonMatcher.hasEntry("name", "name"));
        assertThat(serialized, JsonMatcher.hasEntry("picture", "https://myprofilepic.com"));
    }

    @Test
    public void shouldDeserialize() throws Exception {
        String memberJson = "{\n" +
            "   \"user_id\": \"user_123\",\n" +
            "   \"email\": \"fred@domain.com\",\n" +
            "   \"picture\": \"https://profilepic.com/mypic.png\",\n" +
            "   \"name\": \"fred\"\n" +
            "}";

        Member member = fromJSON(memberJson, Member.class);
        assertThat(member, is(notNullValue()));
        assertThat(member.getUserId(), is("user_123"));
        assertThat(member.getEmail(), is("fred@domain.com"));
        assertThat(member.getPicture(), is("https://profilepic.com/mypic.png"));
        assertThat(member.getName(), is("fred"));

    }
}


text:
package com.BeeFramework.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import com.BeeFramework.example.R;

public class StartActivity extends Activity {
    private Context context;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final View startView = View.inflate(this, R.layout.splash, null);
        setContentView(startView);
        context = this;
        //渐变
        AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f);
        aa.setDuration(2000);
        startView.setAnimation(aa);
        aa.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // TODO Auto-generated method stub
                redirectto();
            }
        }
        );
    }

    private void redirectto() {
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
    }
}


text:
import {Node} from "./node";

export class DoublyLinkedList<T> {
    private head: Node<T> | undefined;
    private tail: Node<T> | undefined;
    private _length: number;

    constructor(){
        this.head = null;
        this.tail = null;
        this._length = 0;
    }

    add(value: T) {
        const node: Node<T> = new Node(value);

        if(this._length) {
            this.tail.setNext(node);
            node.setPrevious(this.tail);
        } else {
            this.head = node;
        }

        this.tail = node;
        this._length++;
        return node;
    }

    getNodeByIndex(index: number): Node<T> {
        let currentNode = this.head,
            length = this._length,
            count = 1;

        if (length === 0 || index > length) {
           throw new Error('Non-existent node in this list.');
        }

        while (count < index) {
            currentNode = currentNode.getNext();
            count++;
        }

        return currentNode;
    }

    remove(index: number): boolean {
        let currentNode = this.head,
            length = this._length,
            beforeNodeToDelete = null,
            afterNodeToDelete = null;

        if (length === 0 || index < 0 || index > length) {
            throw new Error('non-existent node in this list.');
        }

         if (index === 0) {
            this.head = currentNode.getNext();
            this.head.setPrevious(null);
        } else if (index === this._length) {
            this.tail = this.tail.getPrevious();
            this.tail.setNext(null);
        } else {
            currentNode = this.getNodeByIndex(index);
            beforeNodeToDelete = currentNode.getPrevious();
            afterNodeToDelete = currentNode.getNext();

            beforeNodeToDelete.next = afterNodeToDelete;
            afterNodeToDelete.previous = beforeNodeToDelete;
        }

        this._length--;
        return true;
    };

    public toArray(): T[] {
        const arr = [];
        let currentItem = this.head;

        if (currentItem) {
            arr.push(currentItem.get());
            while (currentItem.getNext()) {
                currentItem = currentItem.getNext();
                arr.push(currentItem.get());
            }
        }

        return arr;
    }
}


text:
#include "includes.h"

/**
 *  Set up namespace
 */
namespace Php {

/**
 *  Report this error as a fatal error
 *  @return bool
 */
bool Error::report() const
{
    // report the error
    zend_error(E_ERROR, "%s", what());

    // return true: it was reported
    return true;
}

/**
 *  End of namespace
 */
}


text:
Sedis
==========

Sedis is a thin wrapper around  [Jedis](https://github.com/xetorthio/jedis/),
the most commonly-used [Redis](http://redis.io) library on the JVM.

Requirements
------------

* Scala 2.11 or 2.10
* Jedis 2.4.2

Getting Started
---------------

**First**, specify Sedis as a dependency:

```xml
<repositories>
    <repository>
        <id>org.sedis</id>
        <url>http://pk11-scratch.googlecode.com/svn/trunk</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.sedis</groupId>
        <artifactId>sedis_${scala.version}</artifactId>
        <version>1.2.2</version>
    </dependency>
</dependencies>
```

**Second**, start using it right away:

```scala
 import org.sedis._
 import redis.clients.jedis._
 val pool = new Pool(new JedisPool(new JedisPoolConfig(), "localhost", 6379, 2000))

 pool.withJedisClient { client =>·
   Dress.up(client).get("single").isDefined.must(be(true))
   Dress.up(client).get("single").get.must(be("foo"))
   val r: List[String] = Dress.up(client).lrange("test",0,2)·
   r.size.must(be(2))
   r.toString.must(be("List(bar, foo)"))
   val s: List[String] = Dress.up(client).sort("test")
   s.size.must(be(2))
   s.toString.must(be("List(bar, foo)"))
}

//or using implicits

import Dress._
pool.withClient { client =>
  client.get("single").isDefined.must(be(true))
  client.get("single").get.must(be("foo"))
  client.lindex("test",0).must(be("bar"))
  val r: List[String] = client.lrange("test",0,2)
  r.size.must(be(2))
  r.toString.must(be("List(bar, foo)"))
  val s: List[String] = client.sort("test")
  s.size.must(be(2))
  s.toString.must(be("List(bar, foo)"))
}
```

you can find all the different enhancement methods [here](https://github.com/pk11/sedis/blob/master/src/main/scala/sedis.scala#L13)

License
-------

Published under The MIT License, see LICENSE


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

  <modelVersion>4.0.0</modelVersion>

  <groupId>org.test</groupId>
  <artifactId>test-build-dynamism</artifactId>
  <version>1</version>

  <properties>
    <myProperty>${pom.build.directory}</myProperty>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>${pom.build.directory}/generated-resources/plexus</directory>
      </resource>
    </resources>

    <filters>
      <filter>${pom.build.directory}/generated-filters.properties</filter>
    </filters>

    <directory>target</directory>

    <sourceDirectory>${pom.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory>${pom.basedir}/src/test/java</testSourceDirectory>
    <scriptSourceDirectory>${pom.basedir}/src/main/scripts</scriptSourceDirectory>

    <outputDirectory>${pom.build.directory}/classes</outputDirectory>
    <testOutputDirectory>${pom.build.directory}/test-classes</testOutputDirectory>
  </build>

</project>


text:
//  Unit test for boost::lexical_cast.
//
//  See http://www.boost.org for most recent version, including documentation.
//
//  Copyright Antony Polukhin, 2011.
//
//  Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).

#include <boost/config.hpp>

#if defined(__INTEL_COMPILER)
#pragma warning(disable: 193 383 488 981 1418 1419)
#elif defined(BOOST_MSVC)
#pragma warning(disable: 4097 4100 4121 4127 4146 4244 4245 4511 4512 4701 4800)
#endif

#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/range/iterator_range.hpp>

using namespace boost;

#if defined(BOOST_NO_STRINGSTREAM) || defined(BOOST_NO_STD_WSTRING)
#define BOOST_LCAST_NO_WCHAR_T
#endif

template <class T>
void do_test_on_empty_input(T& v)
{
    BOOST_CHECK_THROW(lexical_cast<int>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<float>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<double>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<long double>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned int>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned short>(v), bad_lexical_cast);
#if defined(BOOST_HAS_LONG_LONG)
    BOOST_CHECK_THROW(lexical_cast<boost::ulong_long_type>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<boost::long_long_type>(v), bad_lexical_cast);
#elif defined(BOOST_HAS_MS_INT64)
    BOOST_CHECK_THROW(lexical_cast<unsigned __int64>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<__int64>(v), bad_lexical_cast);
#endif
}

void test_empty_iterator_range()
{

    boost::iterator_range<char*> v;
    do_test_on_empty_input(v);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(v), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);

    boost::iterator_range<const char*> cv;
    do_test_on_empty_input(cv);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(cv), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(cv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(cv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(cv), bad_lexical_cast);

    const boost::iterator_range<const char*> ccv;
    do_test_on_empty_input(ccv);
    BOOST_CHECK_EQUAL(lexical_cast<std::string>(ccv), std::string());
    BOOST_CHECK_THROW(lexical_cast<char>(ccv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(ccv), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(ccv), bad_lexical_cast);
}

void test_empty_string()
{
    std::string v;
    do_test_on_empty_input(v);
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);

#ifndef BOOST_LCAST_NO_WCHAR_T
    std::wstring vw;
    do_test_on_empty_input(vw);
    BOOST_CHECK_THROW(lexical_cast<wchar_t>(vw), bad_lexical_cast);
#endif

// Currently, no compiler and STL library fully support char16_t and char32_t
//#ifndef BOOST_NO_CHAR16_T
//    std::basic_string<char16_t> v16w;
//    do_test_on_empty_input(v16w);
//    BOOST_CHECK_THROW(lexical_cast<char16_t>(v16w), bad_lexical_cast);
//#endif
//#ifndef BOOST_NO_CHAR32_T
//    std::basic_string<char32_t> v32w;
//    do_test_on_empty_input(v32w);
//    BOOST_CHECK_THROW(lexical_cast<char32_t>(v32w), bad_lexical_cast);
//#endif
}

struct Escape
{
    Escape(const std::string& s)
        : str_(s)
    {}

    std::string str_;
};

inline std::ostream& operator<< (std::ostream& o, const Escape& rhs)
{
    return o << rhs.str_;
}

void test_empty_user_class()
{
    Escape v("");
    do_test_on_empty_input(v);
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);
}

namespace std {
inline std::ostream & operator<<(std::ostream & out, const std::vector<long> & v)
{
    std::ostream_iterator<long> it(out);
    std::copy(v.begin(), v.end(), it);
    assert(out);
    return out;
}
}

void test_empty_vector()
{
    std::vector<long> v;
    do_test_on_empty_input(v);
    BOOST_CHECK_THROW(lexical_cast<char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<unsigned char>(v), bad_lexical_cast);
    BOOST_CHECK_THROW(lexical_cast<signed char>(v), bad_lexical_cast);
}

struct my_string {
    friend std::ostream &operator<<(std::ostream& sout, my_string const&/* st*/) {
            return sout << "";
    }
};

void test_empty_zero_terminated_string()
{
    my_string st;
    BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(st), std::string());;
}

unit_test::test_suite *init_unit_test_suite(int, char *[])
{
    unit_test::test_suite *suite =
        BOOST_TEST_SUITE("lexical_cast. Empty input unit test");
    suite->add(BOOST_TEST_CASE(&test_empty_iterator_range));
    suite->add(BOOST_TEST_CASE(&test_empty_string));
    suite->add(BOOST_TEST_CASE(&test_empty_user_class));
    suite->add(BOOST_TEST_CASE(&test_empty_vector));
    suite->add(BOOST_TEST_CASE(&test_empty_zero_terminated_string));

    return suite;
}


text:
from rest_framework import serializers
from openbudget.apps.international.utilities import translated_fields
from openbudget.apps.entities import models

class EntityMin(serializers.HyperlinkedModelSerializer):
    """A minimal serializer for use as a nested entity representation."""

    class Meta:
        model = models.Entity
        fields = ['id', 'url']

class DivisionMin(serializers.HyperlinkedModelSerializer):
    """A minimal serializer for use as a nested division representation."""

    class Meta:
        model = models.Division
        fields = ['id', 'url']

class EntityBase(serializers.HyperlinkedModelSerializer):
    """The default serialized representation of entities."""

    parent = EntityMin()
    division = DivisionMin()

    class Meta:
        model = models.Entity
        fields = ['id', 'url', 'name', 'description', 'code', 'parent',
                  'division', 'sheets', 'created_on', 'last_modified']\
                 + translated_fields(model)

class DivisionBase(serializers.HyperlinkedModelSerializer):
    """The default serialized representation of divisions."""

    class Meta:
        model = models.Division
        fields = ['id', 'url', 'name', 'index', 'budgeting', 'domain',
                  'created_on', 'last_modified'] + translated_fields(model)

class DomainBase(serializers.HyperlinkedModelSerializer):
    """The default serialized representation of domains."""

    class Meta:
        model = models.Domain
        fields = ['id', 'url', 'name', 'measurement_system',
                  'ground_surface_unit', 'currency', 'created_on',
                  'last_modified', 'divisions'] + translated_fields(model)

class DomainDetail(DomainBase):
    """A detailed, related representation of domain."""

    divisions = DivisionBase()

class DivisionDetail(DivisionBase):
    """Used to represent a full relational map of a division."""

    domain = DomainBase()
    # don't show self again on nested objects
    del domain.fields['divisions']

    class Meta(DivisionBase.Meta):
        fields = DivisionBase.Meta.fields + ['entities']

class EntityDetail(EntityBase):
    """A detailed, related representation of entities."""
    # preventing circular import
    from openbudget.apps.sheets.serializers.api import SheetBase
    sheets = SheetBase()


text:
package clientv3

import (
	"context"
	"reflect"
	"testing"

	"go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
	"go.etcd.io/etcd/api/v3/version"
	"google.golang.org/grpc/metadata"
)

func TestMetadataWithRequireLeader(t *testing.T) {
	ctx := context.TODO()
	_, ok := metadata.FromOutgoingContext(ctx)
	if ok {
		t.Fatal("expected no outgoing metadata ctx key")
	}

	// add a conflicting key with some other value
	md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, "invalid")
	// add a key, and expect not be overwritten
	md.Set("hello", "1", "2")
	ctx = metadata.NewOutgoingContext(ctx, md)

	// expect overwrites but still keep other keys
	ctx = WithRequireLeader(ctx)
	md, ok = metadata.FromOutgoingContext(ctx)
	if !ok {
		t.Fatal("expected outgoing metadata ctx key")
	}
	if ss := md.Get(rpctypes.MetadataRequireLeaderKey); !reflect.DeepEqual(ss, []string{rpctypes.MetadataHasLeader}) {
		t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataRequireLeaderKey, ss)
	}
	if ss := md.Get("hello"); !reflect.DeepEqual(ss, []string{"1", "2"}) {
		t.Fatalf("unexpected metadata for 'hello' %v", ss)
	}
}

func TestMetadataWithClientAPIVersion(t *testing.T) {
	ctx := withVersion(WithRequireLeader(context.TODO()))

	md, ok := metadata.FromOutgoingContext(ctx)
	if !ok {
		t.Fatal("expected outgoing metadata ctx key")
	}
	if ss := md.Get(rpctypes.MetadataRequireLeaderKey); !reflect.DeepEqual(ss, []string{rpctypes.MetadataHasLeader}) {
		t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataRequireLeaderKey, ss)
	}
	if ss := md.Get(rpctypes.MetadataClientAPIVersionKey); !reflect.DeepEqual(ss, []string{version.APIVersion}) {
		t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataClientAPIVersionKey, ss)
	}
}


text:
<!doctype html>

    <title>March22-AuthoringTool</title>
	<link rel="stylesheet" type="text/css" href="main.css">

    <link href="./js/visjs/vis.min.css" rel="stylesheet" type="text/css"/>

March22-AuthoringTool

	<input id="fileItem" type="button" onclick="CreateLoadMenu()" value="Load">
	<input id="fileItemSave" type="button" onclick="SaveProject()" title="Select Script Files" value="Save">
	<input id="settingsButton" type="button" onclick="Settings.CreateSettingsModal()" value="Settings">
	Hide functions? <input type="checkbox" id="settHideFunctions" onchange="HideFunctionNodes()" style="vertical-align:middle;"></input>

	<input id="compileButton" type="button" onclick="SaveScripts()" value="Compile script files">

Title: <input class="nodeItem" type="text" id="nName" oninput="UpdateSelectedNode()"></input>

Tree level: <input class="nodeItem" type="number" id="nLevel" onchange="UpdateSelectedNode()" onkeyup="UpdateSelectedNode()"></input>

Load a script file or start adding nodes!


text:
Implementing the Notify ChangeTracking Policy
=============================================

.. sectionauthor:: Roman Borschel (roman@code-factory.org)

The NOTIFY change-tracking policy is the most effective
change-tracking policy provided by Doctrine but it requires some
boilerplate code. This recipe will show you how this boilerplate
code should look like. We will implement it on a
`Layer Supertype <http://martinfowler.com/eaaCatalog/layerSupertype.html>`_
for all our domain objects.

Implementing NotifyPropertyChanged
----------------------------------

The NOTIFY policy is based on the assumption that the entities
notify interested listeners of changes to their properties. For
that purpose, a class that wants to use this policy needs to
implement the ``NotifyPropertyChanged`` interface from the
``Doctrine\Common`` namespace.

.. code-block:: php

    <?php

    use Doctrine\Persistence\NotifyPropertyChanged,
        Doctrine\Persistence\PropertyChangedListener;

    abstract class DomainObject implements NotifyPropertyChanged
    {
        private $_listeners = [];

        public function addPropertyChangedListener(PropertyChangedListener $listener): void
        {
            $this->_listeners[] = $listener;
        }

        /** Notifies listeners of a change. */
        protected function _onPropertyChanged($propName, $oldValue, $newValue): void
        {
            if (!empty($this->_listeners)) {
                foreach ($this->_listeners as $listener) {
                    $listener->propertyChanged($this, $propName, $oldValue, $newValue);
                }
            }
        }
    }

Then, in each property setter of concrete, derived domain classes,
you need to invoke \_onPropertyChanged as follows to notify
listeners:

.. code-block:: php

    <?php

    // Mapping not shown, either in annotations or xml as usual
    class MyEntity extends DomainObject
    {
        private $data;
        // ... other fields as usual

        public function setData($data): void
        {
            if ($data != $this->data) { // check: is it actually modified?
                $this->_onPropertyChanged('data', $this->data, $data);
                $this->data = $data;
            }
        }
    }

The check whether the new value is different from the old one is
not mandatory but recommended. That way you can avoid unnecessary
updates and also have full control over when you consider a
property changed.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FirstPersonController.cs" company="nGratis">
//   The MIT License (MIT)
//
//   Copyright (c) 2014 - 2015 Cahya Ong
//
//   Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
//   associated documentation files (the "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//   copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
//   following conditions:
//
//   The above copyright notice and this permission notice shall be included in all copies or substantial
//   portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
//   LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
//   EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
//   THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <author>Cahya Ong - cahya.ong@gmail.com</author>
// <creation_timestamp>Wednesday, 28 October 2015 11:05:08 AM UTC</creation_timestamp>
// --------------------------------------------------------------------------------------------------------------------

using UnityEngine;

public class FirstPersonController : MonoBehaviour
{
    public float walkingSpeed = 5;

    public float runningSpeed = 15;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }

        var distance = (Input.GetKey(KeyCode.LeftShift) ? this.runningSpeed : this.walkingSpeed) * Time.deltaTime;

        if (Input.GetKey(KeyCode.A))
        {
            this.transform.Translate(Vector3.left * distance);
        }
        else if (Input.GetKey(KeyCode.D))
        {
            this.transform.Translate(Vector3.right * distance);
        }

        if (Input.GetKey(KeyCode.W))
        {
            this.transform.Translate(Vector3.forward * distance);
        }
        else if (Input.GetKey(KeyCode.S))
        {
            this.transform.Translate(Vector3.back * distance);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="header">Am I A Psycho?</string>
    <string name="app_name">Psycho Test</string>
    <string name="banner_ad_unit_id">ca-app-pub-9840453139309934/9079149609</string>

    <!--> primeira pergunta e repostas<-->
    <string name="primeira_pergunta">I see myself as:</string>
    <string name="primeira_pergunta_resposta_um">Kind</string>
    <string name="primeira_pergunta_resposta_quatro">Happy</string>
    <string name="primeira_pergunta_resposta_cinco">Angry</string>
    <string name="primeira_pergunta_resposta_dois">Smart</string>
    <string name="primeira_pergunta_resposta_tres">Cold</string>
    <string name="next">Next</string>

    <!--> segunda pergunta e repostas<-->
    <string name="segunda_pergunta">When I met someone, I try to:</string>
    <string name="segunda_pergunta_resposta_um">Make this person laugh</string>
    <string name="segunda_pergunta_resposta_quatro">Start a good conversation</string>
    <string name="segunda_pergunta_resposta_cinco">Ask for money</string>
    <string name="segunda_pergunta_resposta_dois">Steal</string>
    <string name="segunda_pergunta_resposta_tres">Use this person to get something</string>

    <!--> terceora pergunta e repostas<-->
    <string name="terceira_pergunta">My family is:</string>
    <string name="terceira_pergunta_resposta_um">The most important thing</string>
    <string name="terceira_pergunta_resposta_quatro">I love them</string>
    <string name="terceira_pergunta_resposta_cinco">I do not know them</string>
    <string name="terceira_pergunta_resposta_dois">I do not care</string>
    <string name="terceira_pergunta_resposta_tres">Family? What is this?</string>

    <!--> quarta pergunta e repostas<-->
    <string name="quarta_pergunta">About animals:</string>
    <string name="quarta_pergunta_resposta_um">I love them</string>
    <string name="quarta_pergunta_resposta_quatro">They are cute</string>
    <string name="quarta_pergunta_resposta_cinco">I hate them</string>
    <string name="quarta_pergunta_resposta_dois">I would rather be away</string>
    <string name="quarta_pergunta_resposta_tres">I am completely obsessed</string>

    <!--> quinta pergunta e repostas<-->
    <string name="quinta_pergunta">When I am dating, and I see someone attractive:</string>
    <string name="quinta_pergunta_resposta_um">I remember that I am dating, and I do nothing</string>
    <string name="quinta_pergunta_resposta_quatro">I run away</string>
    <string name="quinta_pergunta_resposta_cinco">I go to that person and start to talk</string>
    <string name="quinta_pergunta_resposta_dois">I let it happen</string>
    <string name="quinta_pergunta_resposta_tres">I go to that person, and give a kiss</string>

    <!--> sexta pergunta e repostas<-->
    <string name="sexta_pergunta">About friendship:</string>
    <string name="sexta_pergunta_resposta_um">It is essential</string>
    <string name="sexta_pergunta_resposta_quatro">I do not live without it</string>
    <string name="sexta_pergunta_resposta_cinco">I have a few friends</string>
    <string name="sexta_pergunta_resposta_dois">I do not socialize that often</string>
    <string name="sexta_pergunta_resposta_tres">I would rather be away from people</string>

    <!--> setima pergunta e repostas<-->
    <string name="setima_pergunta">About steal:</string>
    <string name="setima_pergunta_resposta_um">I felt like it, but I never did it</string>
    <string name="setima_pergunta_resposta_quatro">I never thought about it.</string>
    <string name="setima_pergunta_resposta_cinco">If you are fooling, I will take you</string>
    <string name="setima_pergunta_resposta_dois">Found is not stolen</string>
    <string name="setima_pergunta_resposta_tres">I take everything I find in front of me</string>

    <!--> oitava pergunta e repostas<-->
    <string name="oitava_pergunta">In my childhood:</string>
    <string name="oitava_pergunta_resposta_um">I used to play in the street</string>
    <string name="oitava_pergunta_resposta_quatro">I watched a lot cartoons</string>
    <string name="oitava_pergunta_resposta_cinco">I was always fighting in school</string>
    <string name="oitava_pergunta_resposta_dois">I did not have childhood</string>
    <string name="oitava_pergunta_resposta_tres">Tortured animals</string>

    <!--> nona pergunta e repostas<-->
    <string name="nona_pergunta">My vocabulary is:</string>
    <string name="nona_pergunta_resposta_um">Normal, but with some slang</string>
    <string name="nona_pergunta_resposta_quatro">I never stopped to think about it</string>
    <string name="nona_pergunta_resposta_cinco">Refined</string>
    <string name="nona_pergunta_resposta_dois">Well rumpled with words unknown by most of the people</string>
    <string name="nona_pergunta_resposta_tres">The greatest, I am superior to almost everyone, people try to overcome me but its impossible</string>

    <!--> decima pergunta e repostas<-->
    <string name="decima_pergunta">I lie:</string>
    <string name="decima_pergunta_resposta_um">No, I am not in favor of lies in any situation.</string>
    <string name="decima_pergunta_resposta_quatro">I only use small lies like that, I was at school when I was actually at a house of a friend.</string>
    <string name="decima_pergunta_resposta_cinco">Depends, I lie only when I really need it.</string>
    <string name="decima_pergunta_resposta_dois">Yes, what is life without a lie? Sometimes it takes a lie here, another there, otherwise things will not go</string>
    <string name="decima_pergunta_resposta_tres">Of course! Lying is the key to have a great life</string>

    <!--> resultados <-->
    <string name="nao_psicopata">You are not a psychopath</string>
    <string name="talvez_seja_psicopata">You have traits of psychopathy, but you are not a psychopath</string>
    <string name="psicopata">You are a psychopath</string>
    <string name="resultado">Result</string>
    <string name="frase_inicial">Do you want to know if you are a psychopath?</string>
    <string name="frase_inicial2">Did they say you were a psychopath?</string>
    <string name="frase_inicial3">Time to know that!</string>
    <string name="iniciar_teste">Begin test</string>
    <string name="selecione_uma_opcao">Please, choose an option</string>
    <string name="reiniciar_teste">Reset test</string>
    <string name="compartilhar_app">Share app</string>
    <string name="compartilhe">What about share the test with your friends?</string>
    <string name="compartilhe_titulo">Share</string>
    <string name="sim">Yes</string>
    <string name="nao">Later</string>
    <string name="mensagem_na_hora_de_compartilhar">Take a look at this app, its a psychopath test!</string>
    <string name="avaliar_app">Rate</string>
    <string name="compartilhar_resultado">Share result</string>
    <string name="compartilhar_resultado_amigos">What about share the result with your friends?</string>
    <string name="meu_resultado_foi">My result was</string>
    <string name="faca_o_teste_tambem">Take the test too</string>
    <string name="desligarmusica">Without music</string>
    <string name="avaliar">Rate the app</string>
    <string name="deseja_avaliar_app">Would you like to rate the app?</string>
</resources>


text:
package com.example.aoc.project_arnold.Adapters;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.aoc.project_arnold.Objects.Record;
import com.example.aoc.project_arnold.R;

import java.util.List;

public class RecordsAdapter extends ArrayAdapter<Record> {
    //Declarations
    private Context c;
    private int layoutId;
    private LayoutInflater inflater;
    private List<Record> data;

    public RecordsAdapter(Context context, int layoutResourceId, List<Record> objects) {
        super(context,layoutResourceId,objects);
        this.c=context;
        this.layoutId=layoutResourceId;
        this.data=objects;
    }

    //Inner class shall hold our views for each row
    public class ViewHolder{
        TextView exercise;
        ImageView img;
        TextView reps;
        TextView kg;
        TextView date;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = ((Activity)c).getLayoutInflater();
        View row = inflater.inflate(layoutId,parent,false);

        TextView  tv_exercise = (TextView) row.findViewById(R.id.tv_records_exercise);
        ImageView  img = (ImageView) row.findViewById(R.id.img_records);
        TextView tv_reps = (TextView) row.findViewById(R.id.tv_records_reps);
        TextView tv_kg = (TextView) row.findViewById(R.id.tv_records_kg);
        TextView  tv_date = (TextView) row.findViewById(R.id.tv_records_date);

        tv_exercise.setText(data.get(position).getExercises());
        img.setImageResource(data.get(position).getImgs());
        tv_reps.setText(data.get(position).getReps());
        tv_kg.setText(data.get(position).getKg());
        tv_date.setText(data.get(position).getDate());

        return row;
    }
}


text:
// Learn more about configuring this file at <https://theintern.github.io/intern/#configuration>.
// These default settings work OK for most people. The options that *must* be changed below are the
// packages, suites, excludeInstrumentation, and (if you want functional tests) functionalSuites
define({
	// The port on which the instrumenting proxy will listen
	proxyPort: 9000,

	// A fully qualified URL to the Intern proxy
	proxyUrl: 'http://localhost:9000/',

	// Default desired capabilities for all environments. Individual capabilities can be overridden by any of the
	// specified browser environments in the `environments` array below as well. See
	// <https://theintern.github.io/intern/#option-capabilities> for links to the different capabilities options for
	// different services.
	//
	// Note that the `build` capability will be filled in with the current commit ID or build tag from the CI
	// environment automatically
	capabilities: {
		'selenium-version': '2.45.0'
	},

	// Browsers to run integration testing against. Note that version numbers must be strings if used with Sauce
	// OnDemand. Options that will be permutated are browserName, version, platform, and platformVersion; any other
	// capabilities options specified for an environment will be copied as-is
	environments: [
		//{ browserName: 'firefox' },
		{ browserName: 'chrome' },
		/*{ browserName: 'internet explorer', version: '11', platform: 'WIN8' },
		{ browserName: 'internet explorer', version: '10', platform: 'WIN8' },
		{ browserName: 'internet explorer', version: '9', platform: 'WINDOWS' },
		{ browserName: 'firefox', version: '37', platform: [ 'WINDOWS', 'MAC' ] },
		{ browserName: 'chrome', version: '39', platform: [ 'WINDOWS', 'MAC' ] },
		{ browserName: 'safari', version: '8', platform: 'MAC' }*/
	],

	tunnel: 'NullTunnel',

	leaveRemoteOpen: 'fail',

	// Maximum number of simultaneous integration tests that should be executed on the remote WebDriver service
	maxConcurrency: 2,

	// Configuration options for the module loader; any AMD configuration options supported by the AMD loader in use
	// can be used here.
	// If you want to use a different loader than the default loader, see
	// <https://theintern.github.io/intern/#option-useLoader> for instruction
	loaderOptions: {
		// Packages that should be registered with the loader in each testing environment
		packages: [
			{ name: 'app', location: 'src/' },
			{ name: 'tests', location: 'tests/' }
		]
	},

	// Non-functional test suite(s) to run in each browser
	suites: [
		'tests/unit/event-emitter',
		'tests/unit/event-listener',
		'tests/unit/extend',
		'tests/unit/record',
		'tests/unit/list',
	],

	// Functional test suite(s) to execute against each browser once non-functional tests are completed
	functionalSuites: [
		'tests/functional/view/view',
		'tests/functional/patch-dom/patch-dom',
	],

	// A regular expression matching URLs to files that should not be included in code coverage analysis
	excludeInstrumentation: /^(?:tests|docs|dist|node_modules)\//
});


text:
package com.thesett.common.util.concurrent;

import java.util.Collection;
import java.util.concurrent.BlockingQueue;

/**
 * BatchSynchQueue is an abstraction of the classic producer/consumer buffer pattern for thread interaction. In this
 * pattern threads can deposit data onto a buffer whilst other threads take data from the buffer and perform usefull
 * work with it. A BatchSynchQueue adds to this the possibility that producers can be blocked until their data is
 * consumed or until a consumer chooses to release the producer some time after consuming the data from the queue.
 *
 *
There are a number of possible advantages to using this technique when compared with having the producers
 * processing their own data:
 *
 *

 *
Data may be deposited asynchronously in the buffer allowing the producers to continue running.

 *
Data may be deposited synchronously in the buffer so that producers wait until their data has been processed
 * before being allowed to continue.

 *
Variable rates of production/consumption can be smoothed over by the buffer as it provides space in memory to
 * hold data between production and consumption.

 *
Consumers may be able to batch data as they consume it leading to more efficient consumption over individual data
 * item consumption where latency associated with the consume operation that can be ammortized. For example, it may be
 * possibly to ammortize the cost of a disk seek over many producers.

 *
Data from seperate threads can be combined together in the buffer, providing a convenient way of spreading work
 * amongst many workers and gathering the results together again.

 *
Different types of queue can be used to hold the buffer, resulting in different processing orders. For example,
 * lifo, fifo, priority heap, etc.

 *

 *
 *
The asynchronous type of producer/consumer buffers is already well supported by the java.util.concurrent package
 * (in Java 5) and there is also a synchronous queue implementation available there too. This interface extends the
 * blocking queue with some more methods for controlling a synchronous blocking queue. In particular it adds additional
 * take methods that can be used to take data from a queue without releasing producers, so that consumers have an
 * opportunity to confirm correct processing of the data before producers are released. It also adds a put method with
 * exceptions so that consumers can signal exception cases back to producers where there are errors in the data.
 *
 *
This type of queue is usefull in situations where consumers can obtain an efficiency gain by batching data from
 * many threads but where synchronous handling of that data is neccessary because producers need to know that their data
 * has been processed before they continue. For example, sending a bundle of messages together, or writing many records
 * to disk at once, may result in improved performance but the originators of the messages or disk records need
 * confirmation that their data has really been sent or saved to disk.
 *
 *
The consumer can put an element back onto the queue or send an error message to the elements producer using the
 * {@link SynchRecord} interface.
 *
 *
The {@link #take()}, {@link #drainTo(java.util.Collection<? super E>)} and
 * {@link #drainTo(java.util.Collection<? super E>, int)} methods from {@link BlockingQueue} should behave as if they
 * have been called with unblock set to false. That is they take elements from the queue but leave the producers
 * blocked. These methods do not return collections of {@link SynchRecord}s so they do not supply an interface through
 * which errors or re-queuings can be applied. If these methods are used then the consumer must succesfully process all
 * the records it takes.
 *
 *
The {@link #put} method should silently swallow any exceptions that consumers attempt to return to the caller. In
 * order to handle exceptions the {@link #tryPut} method must be used.
 *
 *

CRC Card

 *
ResponsibilitiesCollaborations
 *
Handle synchronous puts, with possible exceptions.
 *
Allow consumers to take many records from a queue in a batch.
 *
Allow consumers to decide when to unblock synchronous producers.
 *

 *
 * @author Rupert Smith
 */
public interface BatchSynchQueue<E> extends BlockingQueue<E>
{
    /**
     * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the
     * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}.
     *
     * @param  e The data element to put into the queue.
     *
     * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting
     *                              on its entry in the queue being consumed.
     * @throws SynchException       If a consumer encounters an error whilst processing the data element.
     */
    void tryPut(E e) throws InterruptedException, SynchException;

    /**
     * Takes all available data items from the queue or blocks until some become available. The returned items are
     * wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their producers,
     * where the producers are still blocked.
     *
     * @param  c       The collection to drain the data items into.
     * @param  unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
     *
     * @return A count of the number of elements that were drained from the queue.
     */
    SynchRef drainTo(Collection<SynchRecord<E>> c, boolean unblock);

    /**
     * Takes up to maxElements available data items from the queue or blocks until some become available. The returned
     * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their
     * producers, where the producers are still blocked.
     *
     * @param  c           The collection to drain the data items into.
     * @param  maxElements The maximum number of elements to drain.
     * @param  unblock     If set to <tt>true</tt> the producers for the taken items will be immediately unblocked.
     *
     * @return A count of the number of elements that were drained from the queue.
     */
    SynchRef drainTo(Collection<SynchRecord<E>> c, int maxElements, boolean unblock);
}


text:
global.assert = require('assert');
require('node_modules/string.prototype.codepointat/codepointat.js');

global.Dict = require('js/dict');
global._ = require('node_modules/underscore/underscore.js');
var _ = global._;

// Find the files we need to run.
var finder = require('./finder.js');
var files = finder.find_files_to_run(); // may write to console
if (_.isEmpty(files)) {
    throw "No tests found";
}

// Set up our namespace helpers.
var namespace = require('./namespace.js');
global.set_global = namespace.set_global;
global.patch_builtin = namespace.patch_builtin;
global.add_dependencies = namespace.add_dependencies;
global.stub_out_jquery = namespace.stub_out_jquery;
global.with_overrides = namespace.with_overrides;

// Set up stub helpers.
var stub = require('./stub.js');
global.with_stub = stub.with_stub;

// Set up helpers to render templates.
var render = require('./render.js');
global.make_sure_all_templates_have_been_compiled =
    render.make_sure_all_templates_have_been_compiled;
global.find_included_partials = render.find_included_partials;
global.compile_template = render.compile_template;
global.render_template = render.render_template;
global.walk = render.walk;

// Set up helpers to output HTML
var output = require('./output.js');
global.write_handlebars_output = output.write_handlebars_output;
global.write_test_output = output.write_test_output;
global.append_test_output = output.append_test_output;

// Set up fake jQuery
global.make_zjquery = require('./zjquery.js').make_zjquery;

// Set up fake translation
global.stub_i18n = require('./i18n.js');

var noop = function () {};

output.start_writing();

files.forEach(function (file) {
    global.patch_builtin('setTimeout', noop);
    global.patch_builtin('setInterval', noop);

    console.info('running tests for ' + file.name);
    render.init();
    require(file.full_name);
    namespace.restore();
});

console.info("To see more output, open " + output.index_fn);


text:
from js_helper import _do_test_raw, _do_real_test_raw

def test_pollution():
    """Make sure that the JS namespace pollution tests are done properly."""

    assert not _do_test_raw("""
    a = "foo";
    b = "foo";
    c = "foo";
    """, ignore_pollution=False).failed()

    assert _do_test_raw("""
    a = "foo";
    b = "foo";
    c = "foo";
    d = "foo";
    """, ignore_pollution=False).failed()

def test_pollution_jsm():
    """
    Make sure that JSM files don't have to worry about namespace pollution.
    """

    assert not _do_test_raw("""
    a = "foo";
    b = "foo";
    c = "foo";
    d = "foo";
    """, path='foo.jsm', ignore_pollution=False).failed()

def test_pollution_components():
    """
    Test that the components/ directory is ignored for pollution.
    """

    assert not _do_test_raw("""
    a = "foo";
    b = "foo";
    c = "foo";
    d = "foo";
    """, path='components/foo.jsm', ignore_pollution=False).failed()

def test_pollution_exceptions():
    """
    Make sure that JSM files don't have to worry about namespace pollution.
    """

    assert not _do_test_raw("""
    Cc = "foo";
    Ci = "foo";
    Cu = "foo";
    d = "foo";
    """, path='foo.js', ignore_pollution=False).failed()

def test_pollution_jetpack_bootstrap():
    """
    Test that Jetpack addons and bootstrapped addons are not flagged for
    pollution.
    """

    assert not _do_real_test_raw(
        """
        a = "foo";
        b = "foo";
        c = "foo";
        d = "foo";
        """, path='foo.js',
        metadata={'is_jetpack': True}).failed()

    assert not _do_real_test_raw(
        """
        a = "foo";
        b = "foo";
        c = "foo";
        d = "foo";
        """, path='foo.js',
        resources={'em:bootstrap': 'true'}).failed()

def test_pollution_implicit_from_fun():
    """
    Make sure that implicit variable declarations from within functions are caught.
    Missing a var/let will implicitly declare the variable within the global scope.
    """

    assert not _do_test_raw("""
    (function() {
        var a = "foo";
        var b = "foo";
        var c = "foo";
        var d = "foo";
    })()
    """, ignore_pollution=False).failed()

    assert _do_test_raw("""
    (function() {
        a = "foo";
        b = "foo";
        c = "foo";
        d = "foo";
    })();
    """, ignore_pollution=False).failed()


text:
import controller from './radio-group.controller';

export default {
  template: '<ng-transclude></ng-transclude>',
  controller,
  bindings: {
    name: '@?',
    model: '=?',
    onChange: '&',
  },
  transclude: true,
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/oficina-refatoracao.iml" filepath="$PROJECT_DIR$/.idea/modules/oficina-refatoracao.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/oficina-refatoracao_main.iml" filepath="$PROJECT_DIR$/.idea/modules/oficina-refatoracao_main.iml" group="oficina-refatoracao" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/oficina-refatoracao_test.iml" filepath="$PROJECT_DIR$/.idea/modules/oficina-refatoracao_test.iml" group="oficina-refatoracao" />
    </modules>
  </component>
</project>


text:
package com.headius.android.dex;

import com.android.dex.DexFormat;
import com.android.dx.Version;
import com.android.dx.cf.direct.ClassPathOpener;
import com.android.dx.cf.direct.DirectClassFile;
import com.android.dx.cf.iface.ParseException;
import com.android.dx.command.DxConsole;
import com.android.dx.command.UsageException;
import com.android.dx.dex.DexOptions;
import com.android.dx.dex.cf.CfOptions;
import com.android.dx.dex.cf.CfTranslator;
import com.android.dx.dex.cf.CodeStatistics;
import com.android.dx.dex.code.PositionList;
import com.android.dx.dex.file.ClassDefItem;
import com.android.dx.dex.file.DexFile;
import com.android.dx.dex.file.EncodedMethod;
import com.android.dx.rop.annotation.Annotation;
import com.android.dx.rop.annotation.Annotations;
import com.android.dx.rop.annotation.AnnotationsList;
import com.android.dx.rop.cst.CstNat;
// import com.android.dx.rop.cst.CstUtf8;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;

public class DexClient {
    /** number of warnings during processing */
    private static int warnings = 0;

    /** number of errors during processing */
    private static int errors = 0;

    /** {@code non-null;} output file in-progress */
    private static DexFile outputDex;
    private static DexOptions dexOptions = new DexOptions();
    static {
        dexOptions.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
    }
    private final CfOptions cfOptions;

    public DexClient() {
        outputDex = new DexFile(dexOptions);
        cfOptions = new CfOptions();

        cfOptions.positionInfo = PositionList.LINES;
        cfOptions.localInfo = true;
        cfOptions.strictNameCheck = true;
        cfOptions.optimize = false;
        cfOptions.optimizeListFile = null;
        cfOptions.dontOptimizeListFile = null;
        cfOptions.statistics = false;
    }

    public byte[] classesToDex(String[] names, byte[][] byteArrays) {
      for (int i = 0; i < names.length; i++) {
        String name = names[i];
        byte[] byteArray = byteArrays[i];
        processClass(name, byteArray);
      }

      byte[] outputArray = writeDex();

      return outputArray;
    }

    /**
     * Processes one classfile.
     *
     * @param name {@code non-null;} name of the file, clipped such that it
     * <i>should</i> correspond to the name of the class it contains
     * @param bytes {@code non-null;} contents of the file
     * @return whether processing was successful
     */
    private boolean processClass(String name, byte[] bytes) {
        try {
            ClassDefItem clazz = CfTranslator
                    .translate(new DirectClassFile(bytes, name, true), bytes, cfOptions, dexOptions, outputDex);
            return true;
        } catch (ParseException ex) {
          ex.printStackTrace();
        }

        warnings++;
        return false;
    }

    /**
     * Converts {@link #outputDex} into a {@code byte[]}, write
     * it out to the proper file (if any), and also do whatever human-oriented
     * dumping is required.
     *
     * @return {@code null-ok;} the converted {@code byte[]} or {@code null}
     * if there was a problem
     */
    private byte[] writeDex() {
        byte[] outArray = null;

        OutputStreamWriter out = new OutputStreamWriter(new ByteArrayOutputStream());
        try {
            outArray = outputDex.toDex(out, false);
        } catch (Exception ex) {
          ex.printStackTrace();
        }

        return outArray;
    }

    /**
     * Opens and returns the named file for writing, treating "-" specially.
     *
     * @param name {@code non-null;} the file name
     * @return {@code non-null;} the opened file
     */
    private OutputStream openOutput(String name) throws IOException {
        if (name.equals("-") ||
                name.startsWith("-.")) {
            return System.out;
        }

        return new FileOutputStream(name);
    }

    /**
     * Flushes and closes the given output stream, except if it happens to be
     * {@link System#out} in which case this method does the flush but not
     * the close. This method will also silently do nothing if given a
     * {@code null} argument.
     *
     * @param stream {@code null-ok;} what to close
     */
    private void closeOutput(OutputStream stream) throws IOException {
        if (stream == null) {
            return;
        }

        stream.flush();

        if (stream != System.out) {
            stream.close();
        }
    }
}


text:
<!DOCTYPE HTML>

		<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
		<title>HowTo-Upload-Symbols Document</title>
		<meta id="xcode-display" name="xcode-display" content="render"/>
		<link rel="stylesheet" type="text/css" href="../../css/styles.css" media="all" />
		<link rel="stylesheet" type="text/css" media="print" href="../../css/stylesPrint.css" />
		<meta name="generator" content="appledoc 2.2 (build 963)" />

HockeySDK-iOS 3.5.4

				Bit Stadium GmbH

HowTo-Upload-Symbols Document

Introduction

Mac and iOS crash reports show the stack traces for all running threads of your app of the time a crash occured. But the stack traces only contain memory addresses and don’t show class names, methods, file names and line numbers that are needed to understand them.

To get these memory addresses translated you need to upload a dSYM package to the server, which contains all information required to make this happen. The symbolication process will then check the binary images section of the crash report and grab the UUID of the binary that caused the crash. Next it will get the UUID of the dSYM package to make sure they are identical and process the data if so.

WARNING: Every time you are doing a build, the app binary and the dSYM will get a new unique UUID, no matter if you changed the code or not. So make sure to archive all your binaries and dSYMs that you are using for beta or app store builds!

HowTo

Once you have your app ready for beta testing or even to submit it to the App Store, you need to upload the .dSYM bundle to HockeyApp to enable symbolication. If you have built your app with Xcode4, menu Product > Archive, you can find the .dSYM as follows:

Chose Window > Organizer in Xcode.

Select the tab Archives.

Select your app in the left sidebar.

Right-click on the latest archive and select Show in Finder.

Right-click the .xcarchive in Finder and select Show Package Contents.

You should see a folder named dSYMs which contains your dSYM bundle. If you use Safari, just drag this file from Finder and drop it on to the corresponding drop zone in HockeyApp. If you use another browser, copy the file to a different location, then right-click it and choose Compress YourApp.dSYM. The file will be compressed as a .zip file. Drag & drop this file to HockeyApp.

Mac Desktop Uploader

As an alternative, you can use our HockeyMac app to upload the complete archive in one step. You can even integrate HockeyMac into Xcode to automatically show the upload interface after archiving your app, which would make all steps 1 to 6 not necessary any more!

Check out the Mac Desktop Uploader Guide.

© 2014 Bit Stadium GmbH. All rights reserved. (Last updated: 2014-02-18)

						Generated by appledoc 2.2 (build 963).


text:
function [lat, lon, azi, rk] = eqdazim_inv(lat0, lon0, x, y, ellipsoid)
%EQDAZIM_INV  Inverse azimuthal equidistant projection
%
%   [lat, lon] = EQDAZIM_INV(lat0, lon0, x, y)
%   [lat, lon, azi, rk] = EQDAZIM_INV(lat0, lon0, x, y, ellipsoid)
%
%   performs the inverse azimuthal equidistant projection of points (x,y)
%   to (lat,lon) using (lat0,lon0) as the center of projection.  These
%   input arguments can be scalars or arrays of equal size.  The ellipsoid
%   vector is of the form [a, e], where a is the equatorial radius in
%   meters, e is the eccentricity.  If ellipsoid is omitted, the WGS84
%   ellipsoid (more precisely, the value returned by defaultellipsoid) is
%   used.  projdoc defines the projection and gives the restrictions on
%   the allowed ranges of the arguments.  The forward projection is given
%   by eqdazim_fwd.
%
%   azi and rk give metric properties of the projection at (lat,lon); azi
%   is the azimuth of the geodesic from the center of projection and rk is
%   the reciprocal of the azimuthal scale.  The scale in the radial
%   direction is 1.
%
%   lat0, lon0, lat, lon, azi are in degrees.  The projected coordinates x,
%   y are in meters (more precisely the units used for the equatorial
%   radius).  rk is dimensionless.
%
%   Section 14 of
%
%     C. F. F. Karney, Geodesics on an ellipsoid of revolution (2011),
%     http://arxiv.org/abs/1102.1215
%     Errata: http://geographiclib.sourceforge.net/geod-addenda.html#geod-errata
%
%   describes how to use this projection in the determination of maritime
%   boundaries (finding the median line).
%
%   See also PROJDOC, EQDAZIM_FWD, GEODRECKON, DEFAULTELLIPSOID.

% Copyright (c) Charles Karney (2012-2015) <charles@karney.com>.

  narginchk(4, 5)
  if nargin < 5, ellipsoid = defaultellipsoid; end
  try
    [~] = lat0 + lon0 + x + y;
  catch
    error('lat0, lon0, x, y have incompatible sizes')
  end

  azi0 = atan2dx(x, y);
  s = hypot(x, y);
  [lat, lon, azi, ~, m, ~, ~, sig] = geodreckon(lat0, lon0, s, azi0, ellipsoid);
  rk = m ./ s;
  rk(sig <= 0.01 * sqrt(realmin)) = 1;
end


text:
Extract YAML front-matter from markdown.

## Installation

[npm][]:

```bash
npm install remark-yaml-meta
```

## Usage

Dependencies:

```javascript
var remark = require('remark');
var metaPlugin = require('remark-yaml-meta');
```

Process:

```javascript
var file = remark().use(metaPlugin).process([
    '---',
    'foo:',
    '  bar: true',
    '---',
    ''
].join('\n'));
```

Yields:

```markdown
{
  "foo": {
    "bar": true
  }
}
```

## API

### `remark.use(yamlConfig)`

Passes the configuration at the `remark` field as [parse][parse-settings]
and [stringify][stringify-settings] settings.

Just like [**remark-yaml-config**][remark-yaml-config], but the parsed object
is saved to the `meta` property of the retuned [`VFile`][unified-file].

## License

[MIT][license] © [Chris Gomez][author]

<!-- Definitions -->

[license]: LICENSE

[author]: http://akagomez.com

[npm]: https://docs.npmjs.com/cli/install

[parse-settings]: https://github.com/wooorm/remark/blob/master/packages/remark-parse/readme.md#options

[stringify-settings]: https://github.com/wooorm/remark/blob/master/packages/remark-stringify/readme.md#options

[remark-yaml-config]: https://github.com/wooorm/remark-yaml-config

[unified-file]: https://github.com/wooorm/unified#file


text:
package org.apache.cassandra.utils;

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import org.junit.Test;

public class BytesReadTrackerTest
{

    @Test
    public void testBytesRead() throws Exception
    {
        byte[] testData;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try
        {
            // boolean
            dos.writeBoolean(true);
            // byte
            dos.writeByte(0x1);
            // char
            dos.writeChar('a');
            // short
            dos.writeShort(1);
            // int
            dos.writeInt(1);
            // long
            dos.writeLong(1L);
            // float
            dos.writeFloat(1.0f);
            // double
            dos.writeDouble(1.0d);

            // String
            dos.writeUTF("abc");
            testData = baos.toByteArray();
        }
        finally
        {
            dos.close();
        }

        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(testData));
        BytesReadTracker tracker = new BytesReadTracker(dis);

        try
        {
            // boolean = 1byte
            boolean bool = tracker.readBoolean();
            assertTrue(bool);
            assertEquals(1, tracker.getBytesRead());
            // byte = 1byte
            byte b = tracker.readByte();
            assertEquals(b, 0x1);
            assertEquals(2, tracker.getBytesRead());
            // char = 2byte
            char c = tracker.readChar();
            assertEquals('a', c);
            assertEquals(4, tracker.getBytesRead());
            // short = 2bytes
            short s = tracker.readShort();
            assertEquals(1, s);
            assertEquals((short) 6, tracker.getBytesRead());
            // int = 4bytes
            int i = tracker.readInt();
            assertEquals(1, i);
            assertEquals(10, tracker.getBytesRead());
            // long = 8bytes
            long l = tracker.readLong();
            assertEquals(1L, l);
            assertEquals(18, tracker.getBytesRead());
            // float = 4bytes
            float f = tracker.readFloat();
            assertEquals(1.0f, f, 0);
            assertEquals(22, tracker.getBytesRead());
            // double = 8bytes
            double d = tracker.readDouble();
            assertEquals(1.0d, d, 0);
            assertEquals(30, tracker.getBytesRead());
            // String("abc") = 2(string size) + 3 = 5 bytes
            String str = tracker.readUTF();
            assertEquals("abc", str);
            assertEquals(35, tracker.getBytesRead());

            assertEquals(testData.length, tracker.getBytesRead());
        }
        finally
        {
            dis.close();
        }

        tracker.reset(0);
        assertEquals(0, tracker.getBytesRead());
    }

    @Test
    public void testUnsignedRead() throws Exception
    {
        byte[] testData;

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        try
        {
            // byte
            dos.writeByte(0x1);
            // short
            dos.writeShort(1);
            testData = baos.toByteArray();
        }
        finally
        {
            dos.close();
        }

        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(testData));
        BytesReadTracker tracker = new BytesReadTracker(dis);

        try
        {
            // byte = 1byte
            int b = tracker.readUnsignedByte();
            assertEquals(b, 1);
            assertEquals(1, tracker.getBytesRead());
            // short = 2bytes
            int s = tracker.readUnsignedShort();
            assertEquals(1, s);
            assertEquals(3, tracker.getBytesRead());

            assertEquals(testData.length, tracker.getBytesRead());
        }
        finally
        {
            dis.close();
        }
    }

    @Test
    public void testSkipBytesAndReadFully() throws Exception
    {
        String testStr = "1234567890";
        byte[] testData = testStr.getBytes();

        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(testData));
        BytesReadTracker tracker = new BytesReadTracker(dis);

        try
        {
            // read first 5 bytes
            byte[] out = new byte[5];
            tracker.readFully(out, 0, 5);
            assertEquals("12345", new String(out));
            assertEquals(5, tracker.getBytesRead());

            // then skip 2 bytes
            tracker.skipBytes(2);
            assertEquals(7, tracker.getBytesRead());

            // and read the rest
            out = new byte[3];
            tracker.readFully(out);
            assertEquals("890", new String(out));
            assertEquals(10, tracker.getBytesRead());

            assertEquals(testData.length, tracker.getBytesRead());
        }
        finally
        {
            dis.close();
        }
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testReadLine() throws Exception
    {
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream("1".getBytes()));
        BytesReadTracker tracker = new BytesReadTracker(dis);

        try
        {
            // throws UnsupportedOperationException
            tracker.readLine();
        }
        finally
        {
            dis.close();
        }
    }
}


text:
// Copyright (c) 2015, tandasat. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.

//
// This module defines utility functions.
//
#include "stdafx.h"
#include "util.h"

////////////////////////////////////////////////////////////////////////////////
//
// macro utilities
//

////////////////////////////////////////////////////////////////////////////////
//
// constants and macros
//

// Masks to select bits used for getting PTEs.
#ifdef _AMD64_
static const auto UTILP_PXI_MASK = 0x1ff;
static const auto UTILP_PPI_MASK = 0x3ffff;
static const auto UTILP_PDI_MASK = 0x7ffffff;
static const auto UTILP_PTI_MASK = 0xfffffffff;
#else
static const auto UTILP_PDI_MASK = 0xffffffff;
static const auto UTILP_PTI_MASK = 0xffffffff;
#endif

#if defined(_AMD64_) && !defined(PXE_BASE)
#define PXE_BASE 0xFFFFF6FB7DBED000UI64
#define PXE_SELFMAP 0xFFFFF6FB7DBEDF68UI64
#define PPE_BASE 0xFFFFF6FB7DA00000UI64
#define PDE_BASE 0xFFFFF6FB40000000UI64
#define PTE_BASE 0xFFFFF68000000000UI64

#define PXE_TOP 0xFFFFF6FB7DBEDFFFUI64
#define PPE_TOP 0xFFFFF6FB7DBFFFFFUI64
#define PDE_TOP 0xFFFFF6FB7FFFFFFFUI64
#define PTE_TOP 0xFFFFF6FFFFFFFFFFUI64

#define PDE_KTBASE_AMD64 PPE_BASE

#define PTI_SHIFT 12
#define PDI_SHIFT 21
#define PPI_SHIFT 30
#define PXI_SHIFT 39
#endif

////////////////////////////////////////////////////////////////////////////////
//
// types
//

struct WINDOWS_RT_PTE {
  ULONG NoExecute : 1;
  ULONG Present : 1;
  ULONG Unknown1 : 5;
  ULONG Writable : 1;
  ULONG Unknown2 : 4;
  ULONG PageFrameNumber : 20;
};
static_assert(sizeof(WINDOWS_RT_PTE) == 4, "Size check");

struct WINDOWS_AMD64_PTE {
  ULONG64 Present : 1;
  ULONG64 Write : 1;
  ULONG64 Owner : 1;
  ULONG64 WriteThrough : 1;
  ULONG64 CacheDisable : 1;
  ULONG64 Accessed : 1;
  ULONG64 Dirty : 1;
  ULONG64 LargePage : 1;
  ULONG64 Global : 1;
  ULONG64 CopyOnWrite : 1;
  ULONG64 Prototype : 1;
  ULONG64 reserved0 : 1;
  ULONG64 PageFrameNumber : 28;
  ULONG64 reserved1 : 12;
  ULONG64 SoftwareWsIndex : 11;
  ULONG64 NoExecute : 1;
};
static_assert(sizeof(WINDOWS_AMD64_PTE) == 8, "Size check");

#ifdef _AMD64_
using HARDWARE_PTE = WINDOWS_AMD64_PTE;
#else
using HARDWARE_PTE = WINDOWS_RT_PTE;
#endif

////////////////////////////////////////////////////////////////////////////////
//
// prototypes
//

EXTERN_C void NTAPI KeSweepIcacheRange(_In_ BOOLEAN AllProcessors,
                                       _In_ PVOID BaseAddress,
                                       _In_ ULONG Length);

#ifdef _AMD64_
EXTERN_C static HARDWARE_PTE *UtilpAddressToPxe(_In_ const void *Address);

EXTERN_C static HARDWARE_PTE *UtilpAddressToPpe(_In_ const void *Address);
#endif

EXTERN_C static HARDWARE_PTE *UtilpAddressToPde(_In_ const void *Address);

EXTERN_C static HARDWARE_PTE *UtilpAddressToPte(_In_ const void *Address);

////////////////////////////////////////////////////////////////////////////////
//
// variables
//

////////////////////////////////////////////////////////////////////////////////
//
// implementations
//

// Execute a given callback routine on all processors in DPC_LEVEL. Returns
// STATUS_SUCCESS when all callback returned STATUS_SUCCESS as well. When
// one of callbacks returns anything but STATUS_SUCCESS, this function stops
// to call remaining callbacks and returns the value.
_Use_decl_annotations_ EXTERN_C NTSTATUS
UtilForEachProcessor(NTSTATUS (*CallbackRoutine)(void *), void *Context) {
  const auto numberOfProcessors = KeQueryActiveProcessorCount(nullptr);
  for (ULONG processorNumber = 0; processorNumber < numberOfProcessors;
       processorNumber++) {
    // Switch the current processor
    const auto oldAffinity = KeSetSystemAffinityThreadEx(
        static_cast<KAFFINITY>(1ull << processorNumber));
    const auto oldIrql = KeRaiseIrqlToDpcLevel();

    // Execute callback
    const auto status = CallbackRoutine(Context);

    KeLowerIrql(oldIrql);
    KeRevertToUserAffinityThreadEx(oldAffinity);
    if (!NT_SUCCESS(status)) {
      return status;
    }
  }
  return STATUS_SUCCESS;
}

// Sleep the current thread's execution for Millisecond milli-seconds.
ALLOC_TEXT(PAGED, UtilSleep)
_Use_decl_annotations_ EXTERN_C NTSTATUS UtilSleep(LONG Millisecond) {
  PAGED_CODE();

  LARGE_INTEGER interval = {};
  interval.QuadPart = -(10000 * Millisecond);  // msec
  return KeDelayExecutionThread(KernelMode, FALSE, &interval);
}

// memmem().
_Use_decl_annotations_ EXTERN_C void *UtilMemMem(const void *SearchBase,
                                                 SIZE_T SearchSize,
                                                 const void *Pattern,
                                                 SIZE_T PatternSize) {
  if (PatternSize > SearchSize) {
    return nullptr;
  }
  auto searchBase = static_cast<const char *>(SearchBase);
  for (size_t i = 0; i <= SearchSize - PatternSize; i++) {
    if (!memcmp(Pattern, &searchBase[i], PatternSize)) {
      return const_cast<char *>(&searchBase[i]);
    }
  }
  return nullptr;
}

// Invalidates an instruction cache for the specified region.
_Use_decl_annotations_ EXTERN_C void UtilInvalidateInstructionCache(
    void *BaseAddress, SIZE_T Length) {
#ifdef _AMD64_
  UNREFERENCED_PARAMETER(BaseAddress);
  UNREFERENCED_PARAMETER(Length);
  __faststorefence();
#else
  KeSweepIcacheRange(TRUE, BaseAddress, Length);
#endif
}

// Does memcpy safely even if Destination is a read only region.
_Use_decl_annotations_ EXTERN_C NTSTATUS UtilForceMemCpy(void *Destination,
                                                         const void *Source,
                                                         SIZE_T Length) {
  auto mdl = IoAllocateMdl(Destination, static_cast<ULONG>(Length), FALSE,
                           FALSE, nullptr);
  if (!mdl) {
    return STATUS_INSUFFICIENT_RESOURCES;
  }
  MmBuildMdlForNonPagedPool(mdl);

#pragma warning(push)
#pragma warning(disable : 28145)
  //
  // Following MmMapLockedPagesSpecifyCache() call causes bug check in case
  // you are using Driver Verifier. The reason is explained as follows:
  //
  // A driver must not try to create more than one system-address-space
  // mapping for an MDL. Additionally, because an MDL that is built by the
  // MmBuildMdlForNonPagedPool routine is already mapped to the system
  // address space, a driver must not try to map this MDL into the system
  // address space again by using the MmMapLockedPagesSpecifyCache routine.
  // -- MSDN
  //
  // This flag modification hacks Driver Verifier's check and prevent leading
  // bug check.
  //
  mdl->MdlFlags &= ~MDL_SOURCE_IS_NONPAGED_POOL;
  mdl->MdlFlags |= MDL_PAGES_LOCKED;
#pragma warning(pop)

  auto writableDest = MmMapLockedPagesSpecifyCache(
      mdl, KernelMode, MmCached, nullptr, FALSE, NormalPagePriority);
  if (!writableDest) {
    IoFreeMdl(mdl);
    return STATUS_INSUFFICIENT_RESOURCES;
  }
  memcpy(writableDest, Source, Length);
  MmUnmapLockedPages(writableDest, mdl);
  IoFreeMdl(mdl);
  return STATUS_SUCCESS;
}

// Return true if the given address is accessible. It does not prevent a race
// condition.
_Use_decl_annotations_ EXTERN_C bool UtilIsAccessibleAddress(
    const void *Address) {
#ifdef _AMD64_
  const auto pxe = UtilpAddressToPxe(Address);
  const auto ppe = UtilpAddressToPpe(Address);
  const auto pde = UtilpAddressToPde(Address);
  const auto pte = UtilpAddressToPte(Address);
  if ((!pxe->Present) || (!ppe->Present) || (!pde->Present) ||
      (!pde->LargePage && (!pte || !pte->Present))) {
    return false;
  }
#else
  const auto pde = UtilpAddressToPde(Address);
  const auto pte = UtilpAddressToPte(Address);
  if (!pde->Present || !pde->PageFrameNumber || !pte->Present ||
      !pte->PageFrameNumber) {
    return false;
  }
#endif
  return true;
}

/*
Virtual Address Interpretation For Handling PTEs

-- On x64
Sign extension                     16 bits
Page map level 4 selector           9 bits
Page directory pointer selector     9 bits
Page directory selector             9 bits
Page table selector                 9 bits
Byte within page                   12 bits
11111111 11111111 11111000 10000000 00000011 01010011 00001010 00011000
^^^^^^^^ ^^^^^^^^ ~~~~~~~~ ~^^^^^^^ ^^~~~~~~ ~~~^^^^^ ^^^^~~~~ ~~~~~~~~
Sign extension    PML4      PDPT      PD        PT        Offset

-- On ARM
Page directory selector            10 bits
Page table selector                10 bits
Byte within page                   12 bits
10000011 01100000 11010010 01110101
~~~~~~~~ ~~^^^^^^ ^^^^~~~~ ~~~~~~~~
PD         PT         Offset

*/

#ifdef _AMD64_

// Return an address of PXE
_Use_decl_annotations_ EXTERN_C static HARDWARE_PTE *UtilpAddressToPxe(
    const void *Address) {
  const auto addr = reinterpret_cast<ULONG_PTR>(Address);
  const auto index = (addr >> PXI_SHIFT) & UTILP_PXI_MASK;
  const auto offset = index * sizeof(HARDWARE_PTE);
  return reinterpret_cast<HARDWARE_PTE *>(PXE_BASE + offset);
}

// Return an address of PPE
_Use_decl_annotations_ EXTERN_C static HARDWARE_PTE *UtilpAddressToPpe(
    const void *Address) {
  const auto addr = reinterpret_cast<ULONG_PTR>(Address);
  const auto index = (addr >> PPI_SHIFT) & UTILP_PPI_MASK;
  const auto offset = index * sizeof(HARDWARE_PTE);
  return reinterpret_cast<HARDWARE_PTE *>(PPE_BASE + offset);
}

#endif

// Return an address of PDE
_Use_decl_annotations_ EXTERN_C static HARDWARE_PTE *UtilpAddressToPde(
    const void *Address) {
  const auto addr = reinterpret_cast<ULONG_PTR>(Address);
  const auto index = (addr >> PDI_SHIFT) & UTILP_PDI_MASK;
  const auto offset = index * sizeof(HARDWARE_PTE);
  return reinterpret_cast<HARDWARE_PTE *>(PDE_BASE + offset);
}

// Return an address of PTE
_Use_decl_annotations_ EXTERN_C static HARDWARE_PTE *UtilpAddressToPte(
    const void *Address) {
  const auto addr = reinterpret_cast<ULONG_PTR>(Address);
  const auto index = (addr >> PTI_SHIFT) & UTILP_PTI_MASK;
  const auto offset = index * sizeof(HARDWARE_PTE);
  return reinterpret_cast<HARDWARE_PTE *>(PTE_BASE + offset);
}


text:
from ._bolt_socket import (
    AsyncBoltSocket,
    BoltSocket,
)
from ._util import (
    AsyncNetworkUtil,
    NetworkUtil,
)

__all__ = [
    "AsyncBoltSocket",
    "AsyncNetworkUtil",
    "BoltSocket",
    "NetworkUtil",
]


text:
<?php

use yii\grid\CheckboxColumn;
use yii\jui\DatePicker;
use yii\grid\ActionColumn;
use modules\themes\admin\widgets\Box;
use modules\direction\Module;
use modules\themes\admin\widgets\GridView;
use modules\direction\models\Direction;
use \yii\helpers\Html;
use modules\themes\Module as ThemeModule;

$this->title = Module::t('direction', 'BACKEND_INDEX_TITLE');
$this->params['subtitle'] = Module::t('direction', 'BACKEND_INDEX_SUBTITLE');
$this->params['breadcrumbs'] = [
    $this->title
];
$id = Yii::$app->getRequest()->get('id');
$gridId = 'direction-grid';

$filterModel = $id ? false : $searchModel;

$gridConfig = [
    'id' => $gridId,
    'dataProvider' => $dataProvider,
    'filterModel' => $filterModel,
    'pjax'=>true,
    'pjaxSettings'=>[
        'neverTimeout'=>true,
        'options'=>[
            'id'=>'pjax-direction',
            'enablePushState' => false,
            'options'=>[
                'class' => 'pjax-wraper'
            ],
        ],
    ],
    'columns' => [
        [
            'class' => CheckboxColumn::classname()
        ],
        'id',
        'name',
        [
            'attribute' => 'parentName',
            'value' => function ($model) {
                return $model->getParentName();
            }
        ],
    ]
];

$boxButtons = $actions = [];
$showActions = false;

$boxButtons[] = '{create}';
$buttons['create'] = [
    'url' => ['create', 'parent_id'=>$id],
    'icon' => 'fa-plus',
    'options' => [
        'class' => 'btn-default',
        'title' => ThemeModule::t('themes-admin', 'Box-Create')
    ]
];

$actions[] = '{update}';
$showActions = $showActions || true;

$gridButtons = [];
$boxButtons[] = '{batch-delete}';
//    $actions[] = '{delete}';
$actions[] = '{delete}';
$gridButtons['delete'] = function ($url, $model) {
    return Html::a('', ['delete', 'id' => $model->id],
        [
            'class' => 'grid-action',
            'data' => [
                'confirm' => ThemeModule::t('themes-admin','Are you sure you want to delete this item?'),
                'method' => 'post',
                'pjax' => '0',
            ],
        ]);
};
$showActions = $showActions || true;

if ($showActions === true) {
    $gridConfig['columns'][] = [
        'class' => ActionColumn::className(),
        'template' => implode(' ', $actions),
        'buttons'=>$gridButtons,
    ];
}
$boxButtons = !empty($boxButtons) ? implode(' ', $boxButtons) : null; ?>

        <?php Box::begin(
            [
                'title' => $this->params['subtitle'],
                'bodyOptions' => [
                    'class' => 'table-responsive'
                ],
                'buttonsTemplate' => $boxButtons,
                'buttons' => $buttons,
                'grid' => $gridId
            ]
        ); ?>
        <?= GridView::widget($gridConfig); ?>
        <?php Box::end(); ?>


text:
<?php

namespace Anax\Votes;

/**
 * Comment Votes controller
 *
 * Communicates with the mapping table, which maps user with a comment
 * in the database.
 * Handles all comment voting tasks between user and the related comment.
 *
 * Inherits from Vote class.
 */
class CommentVotesController extends Vote
{
    /**
     * Initialize the controller.
     *
     * Initializes the comment vote model, the comment model
     * and the question model.
     *
     * @return void
     */
    public function initialize()
    {
        $this->commentVotes = new \Anax\Votes\CommentVote();
        $this->commentVotes->setDI($this->di);

        $this->comments = new \Anax\Comments\Comment();
        $this->comments->setDI($this->di);

        $this->questions = new \Anax\Questions\Question();
        $this->questions->setDI($this->di);
    }

    /**
     * Gets the user ID for a specific comment in DB.
     *
     * Gets the ID of the comment writer in DB.
     *
     * @param  int $id  the id of the comment.
     *
     * @return int      the ID of the comment writer.
     */
    protected function getUserId($id)
    {
        $userId = $this->comments->query('U.id')
            ->join('user2comment AS U2C', 'U2C.idComment = lf_comment.id')
            ->join('user AS U', 'U2C.idUser = U.id')
            ->where('lf_comment.id = ?')
            ->execute([$id]);

        $userId = empty($userId) ? false : $userId[0]->id;

        return $userId;
    }

    /**
     * Checks if the voter has already voted on the comment.
     *
     * Checks in the mapping table in DB, if voter has already voted on the
     * comment.
     *
     * @param  int  $id         the id of the comment.
     * @param  int  $userId     the user id of the voter.
     *
     * @return boolean          true if user already has voted, false otherwise.
     */
    protected function hasUserVoted($id, $userId)
    {
        $id = $this->commentVotes->query('lf_commentvote.id')
            ->where('lf_commentvote.idComment = ? AND lf_commentvote.idUser = ?')
            ->execute([$id, $userId]);

        $hasVoted = empty($id) ? false : true;

        return $hasVoted;
    }

    /**
     * Adds that a user has voted on a comment.
     *
     * Maps a user id to a comment id, which marks that a user has voted on
     * a comment.
     *
     * @param int $id       the id of the comment.
     * @param int $userId   the user id of the voter.
     */
    protected function addUserAsVoter($id, $userId)
    {
        $isSaved = $this->commentVotes->create(array(
            'idComment'  => $id,
            'idUser'    => $userId,
        ));

        return $isSaved;
    }

    /**
     * Increases the score counter for a comment.
     *
     * Gets the score in DB and increases the score with one. Saves the new
     * score in DB.
     * The score is used to rank the comment.
     *
     * @param  int $id  the comment id for the comment to rank.
     *
     * @return boolean  true if the increased value could be saved in DB, false
     *                  otherwise.
     */
    protected function increaseScoreCounter($id)
    {
        $score = $this->getScoreNumber($id);
        $score = $score === false ? 0 : ++$score;

        $isSaved = $this->comments->save(array(
            'id'        => $id,
            'score'     => $score,
        ));

        return $isSaved;
    }

    /**
     * Gets the comment ranking score from DB.
     *
     * Gets the comment ranking score from DB, if found. If not, false is
     * returned.
     *
     * @param  int $id  the id of the comment.
     * @return int | false  the ranking score for the comment. False, if not found.
     */
    protected function getScoreNumber($id)
    {
        $score = $this->comments->query('score')
            ->where('id = ?')
            ->execute([$id]);

        $score = empty($score) ? false : $score[0]->score;

        return $score;
    }

    /**
     * Gets the related question ID for the comment.
     *
     * Gets the question ID for which the comment belongs to. Handles both if
     * a comment belongs directly to a comment or via an answer (belongs to an
     * answer).
     *
     * @param  int $id      the ID of the comment.
     * @return int | false  the question ID which the comment belongs to, if found.
     *                      False otherwise.
     */
    protected function getQuestionId($id)
    {
        $answerId = $this->getAnswerIdFromCommentId($id);
        if ($answerId === false) {
            $questionId = $this->getQuestionIdFromCommentId($id);
        } else {
            $questionId = $this->getQuestionIdFromAnswerId($answerId);
        }

        return $questionId;
    }

    /**
     * Helper method to get the related answer ID from a comment ID in DB.
     *
     * Gets the related answer ID if the comment belongs to an answer.
     *
     * @param  int $commentId   the comment ID.
     *
     * @return int | false      the answer ID if comment belongs to an
     *                          answer, false otherwise.
     */
    private function getAnswerIdFromCommentId($commentId)
    {
        $answerId = $this->comments->query('A.id')
            ->join('answer2comment AS A2C', 'A2C.idComment = lf_comment.id')
            ->join('answer AS A', 'A2C.idAnswer = A.id')
            ->where('lf_comment.id = ?')
            ->execute([$commentId]);

        $answerId = empty($answerId) ? false : $answerId[0]->id;

        return $answerId;
    }

    /**
     * Helper method to get the related question ID from a comment ID in DB.
     *
     * Gets the related question ID if the comment belongs to a question.
     *
     * @param  int $commentId   the comment ID.
     *
     * @return int | false      the question ID if comment belongs to a
     *                          comment, false otherwise.
     */
    private function getQuestionIdFromCommentId($commentId)
    {
        $questionId = $this->comments->query('Q.id')
            ->join('question2comment AS Q2C', 'Q2C.idComment = lf_comment.id')
            ->join('question AS Q', 'Q2C.idQuestion = Q.id')
            ->where('lf_comment.id = ?')
            ->execute([$commentId]);

        $questionId = empty($questionId) ? false : $questionId[0]->id;

        return $questionId;
    }

    /**
     * Helper function to get related question ID from the answer ID in DB.
     *
     * Gets the related question ID from the answer ID. Used when a comment
     * belongs to an answer.
     *
     * @param  int $answerId    the answer ID.
     * @return int | false      the question ID, if the answer belongs to a
     *                          question. False otherwise.
     */
    private function getQuestionIdFromAnswerId($answerId)
    {
        $questionId = $this->questions->query('lf_question.id')
            ->join('question2answer AS Q2A', 'Q2A.idQuestion = lf_question.id')
            ->join('answer AS A', 'Q2A.idAnswer = A.id')
            ->where('A.id = ?')
            ->execute([$answerId]);

        $questionId = empty($questionId) ? false : $questionId[0]->id;

        return $questionId;
    }

    /**
     * Decreases the score counter for comment.
     *
     * Gets the score in DB and decreases the score with one. Saves the new
     * score in DB.
     * The score is used to rank the comment.
     *
     * @param  int $id  the comment id for the comment to rank.
     *
     * @return boolean  true if the decreased value could be saved in DB, false
     *                  otherwise.
     */
    protected function decreaseScoreCounter($id)
    {
        $score = $this->getScoreNumber($id);
        $score = $score === false ? 0 : --$score;

        $isSaved = $this->comments->save(array(
            'id'        => $id,
            'score'     => $score,
        ));

        return $isSaved;
    }
}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>evanq.game</groupId>
    <artifactId>wrapper</artifactId>
    <version>1</version>
  </parent>
  <groupId>evanq.game</groupId>
  <artifactId>game-base</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>game-base</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.hibernateVersion>4.2.3.Final</project.hibernateVersion>

  </properties>
  <dependencies>
    <dependency>
    	<groupId>evanq.game</groupId>
    	<artifactId>game-helper</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    </dependency>

    <!-- //数据库{{{
	 -->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.173</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${project.hibernateVersion}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-proxool</artifactId>
			<version>${project.hibernateVersion}</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-ehcache</artifactId>
			<version>${project.hibernateVersion}</version>
		</dependency>

	  <!--
	 //数据库}}}
	  -->

  </dependencies>
	<build>
		<plugins>
			<plugin>
				<dependencies>
				  <dependency>
                            <groupId>ant-contrib</groupId>
                            <artifactId>ant-contrib</artifactId>
                            <version>1.0b3</version>
                            <exclusions>
                                <exclusion>
                                    <groupId>ant</groupId>
                                    <artifactId>ant</artifactId>
                                </exclusion>
                            </exclusions>
                        </dependency>
                        <dependency>
                            <groupId>org.apache.ant</groupId>
                            <artifactId>ant-nodeps</artifactId>
                            <version>1.8.1</version>
                        </dependency>
				</dependencies>
				<artifactId>maven-antrun-plugin</artifactId>
				<version>1.7</version>
				<executions>
					<execution>
						<phase>prepare-package</phase>
						<configuration>
							<project name="game-net-api" default="removeClass">
								<taskdef resource="net/sf/antcontrib/antcontrib.properties" classpath="maven.plugin.classpath" />
								<target name="removeClass"  >
									<!-- Place any Ant task here. You can add anything you can add between
										<target> and </target> in a build.xml.
										-->
						            <echo>Removing game/module/rpg/impl class</echo>
						            <delete dir="target/classes/evanq/game/module/rpg/impl" />

								</target>
							</project>
						</configuration>
						<goals>
							<goal>run</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<description>根据业务涉及model与 引擎</description>
</project>