text:
package org.platanios.tensorflow.api.io

import org.platanios.tensorflow.api.core.exception.NotFoundException

import java.nio.charset.Charset
import java.nio.file._
import java.util.UUID
import java.util.concurrent.TimeUnit

import scala.collection.compat.immutable.LazyList
import scala.jdk.CollectionConverters._

/** Contains helper functions for dealing with file IO.
  *
  * @author Emmanouil Antonios Platanios
  */
object FileIO {
  // TODO: Replace this with `Files.walkFileTree`.
  /** Walks a directory tree rooted at `dirPath` recursively.
    *
    * Note that exceptions that are thrown while listing directories are ignored.
    *
    * @param  dirPath Path to a directory from which to start traversing.
    * @param  inOrder If `true`, the top-level directories are returned first, otherwise they are returned last.
    * @return Stream over tuples containing: (i) the path for the directory, (ii) a sequence containing all of its
    *         subdirectories, and (iii) a sequence containing all files in that directory.
    */
  def walk(dirPath: Path, inOrder: Boolean = true): LazyList[(Path, Seq[Path], Seq[Path])] = {
    val children: Seq[Path] = {
      try {
        Files.walk(dirPath, 1).iterator().asScala.drop(1).toSeq
      } catch {
        case _: NotFoundException => Seq.empty[Path]
      }
    }
    var files: Seq[Path] = Seq.empty[Path]
    var subDirs: Seq[Path] = Seq.empty[Path]
    children.foreach(child => {
      val fullPath = dirPath.resolve(child)
      if (!Files.isDirectory(fullPath))
        files :+= child
      else
        subDirs :+= child
    })
    val hereStream = LazyList((dirPath, subDirs, files))
    val subDirsStream = subDirs.toList.map(s => walk(dirPath.resolve(s), inOrder))
        .foldLeft(LazyList.empty[(Path, Seq[Path], Seq[Path])])(_ ++ _)
    if (inOrder) {
      hereStream ++ subDirsStream
    } else {
      subDirsStream ++ hereStream
    }
  }

  /** Returns a file's last modified time.
    *
    * @param  path                Path to the file.
    * @param  unit                Time unit in which to return the last modified time. Defaults to [[TimeUnit.SECONDS]].
    * @param  followSymbolicLinks Boolean value indicating whether or not to follow symbolic links. By default, symbolic
    *                             links are followed and the file attribute of the final target of the link is read. If
    *                             `followSymbolicLinks` is set to `false`, then symbolic links are not followed.
    * @return
    */
  def getLastModifiedTime(path: Path, unit: TimeUnit = TimeUnit.SECONDS, followSymbolicLinks: Boolean = true): Long = {
    if (!followSymbolicLinks)
      Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS).to(unit)
    else
      Files.getLastModifiedTime(path).to(unit)
  }

  /** Gets all the matching paths to the path pattern provided.
    *
    * The pattern must follow the TensorFlow path pattern rules and it pattern must match all of a name (i.e., not just
    * a substring). A pattern definition has the following form:
    * {{{
    *   pattern: { term }
    *   term:
    *     '*': matches any sequence of non-'/' characters
    *     '?': matches a single non-'/' character
    *     '[' [ '^' ] { match-list } ']': matches any single character (not) on the list
    *     c: matches character c (c != '*', '?', '\\', '[')
    *     '\\' c: matches character c
    *   character-range:
    *     c: matches character c (c != '\\', '-', ']')
    *     '\\' c: matches character c
    *     lo '-' hi: matches character c for lo <= c <= hi
    * }}}
    *
    * @param  path Path pattern.
    * @return Set of all paths matching the provided path pattern.
    */
  def getMatchingPaths(path: String): Set[Path] = {
    var pathAsString = path
    val separator = FileSystems.getDefault.getSeparator

    // If the separator is the backslash character (i.e., we are on Windows), we replace all separators with forward
    // slash characters to perform the glob detection and then revert back before returning.
    if (separator == "\\") {
      pathAsString = pathAsString.replace("\\", "/")
    }

    // Find the fixed prefix by looking for the first wildcard.
    val (directory, glob) = {
      val wildcard = pathAsString.indexWhere("*?[\\".contains(_))
      val prefix = if (wildcard != -1) pathAsString.substring(0, wildcard) else pathAsString
      val suffix = if (wildcard != -1) pathAsString.substring(wildcard) else ""
      val separatorIndex = prefix.lastIndexOf(if (separator == "\\") "/" else separator)
      val directory = {
        if (separator == "\\") {
          prefix.replace("/", "\\").substring(0, separatorIndex)
        } else {
          prefix.substring(0, separatorIndex)
        }
      }
      val glob = (prefix.substring(separatorIndex + 1) + suffix).replaceAll("([^\\[]*)\\[\\^", "$1\\[!")
      (directory, glob)
    }

    // Get all the matching paths.
    Files.newDirectoryStream(Paths.get(directory), glob).asScala.toSeq.toSet[Path]
  }

  /** Deletes all the matching paths to the path pattern provided.
    *
    * The pattern must follow the TensorFlow path pattern rules and it pattern must match all of a name (i.e., not just
    * a substring). A pattern definition has the following form:
    * {{{
    *   pattern: { term }
    *   term:
    *     '*': matches any sequence of non-'/' characters
    *     '?': matches a single non-'/' character
    *     '[' [ '^' ] { match-list } ']': matches any single character (not) on the list
    *     c: matches character c (c != '*', '?', '\\', '[')
    *     '\\' c: matches character c
    *   character-range:
    *     c: matches character c (c != '\\', '-', ']')
    *     '\\' c: matches character c
    *     lo '-' hi: matches character c for lo <= c <= hi
    * }}}
    *
    * @param  path Path pattern.
    */
  def deleteMatchingPaths(path: String): Unit = {
    getMatchingPaths(path).foreach(Files.delete)
  }

  /** Writes the provided string to the file located at `filePath` as an atomic operation. This means that when
    * `filePath` appears in the filesystem, it will contain all of `content`. With `writeStringToFile()`, it is possible
    * for the file to appear in the filesystem with `content` only partially written.
    *
    * The atomic write is achieved by first writing to a temporary file and then renaming that file.
    */
  def writeStringToFileAtomic(filePath: Path, content: String, overwrite: Boolean = true): Unit = {
    val temporaryFilePath = filePath.resolveSibling(filePath.toString + s".tmp${UUID.randomUUID().toString}")
    Files.write(
      temporaryFilePath,
      content.getBytes(Charset.forName("UTF-8")),
      StandardOpenOption.WRITE,
      StandardOpenOption.CREATE,
      StandardOpenOption.TRUNCATE_EXISTING)
    try {
      if (overwrite)
        Files.move(temporaryFilePath, filePath, StandardCopyOption.REPLACE_EXISTING)
      else
        Files.move(temporaryFilePath, filePath)
    } finally {
      if (Files.exists(temporaryFilePath))
        Files.deleteIfExists(temporaryFilePath)
    }
  }
}


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

namespace Wyam.Core
{
    internal class ExecutionContext : IExecutionContext
    {
        private readonly Engine _engine;
        private readonly Pipeline _pipeline;

        public byte[] RawConfigAssembly => _engine.RawConfigAssembly;
        public IEnumerable<Assembly> Assemblies => _engine.Assemblies;
        public IReadOnlyPipeline Pipeline => new ReadOnlyPipeline(_pipeline);
        public IModule Module { get; internal set; }
        public ITrace Trace => _engine.Trace;
        public IDocumentCollection Documents => _engine.Documents;
        public string RootFolder => _engine.RootFolder;
        public string InputFolder => _engine.InputFolder;
        public string OutputFolder => _engine.OutputFolder;
        public IExecutionCache ExecutionCache => _engine.ExecutionCacheManager.Get(Module, _engine);

        public ExecutionContext(Engine engine, Pipeline pipeline)
        {
            _engine = engine;
            _pipeline = pipeline;
        }

        public IReadOnlyList<IDocument> Execute(IEnumerable<IModule> modules, IEnumerable<IDocument> inputDocuments)
        {
            // Store the document list before executing the child modules and restore it afterwards
            IReadOnlyList<IDocument> documents = _engine.DocumentCollection.Get(_pipeline.Name);
            IReadOnlyList<IDocument> results = _pipeline.Execute(modules, inputDocuments);
            _engine.DocumentCollection.Set(_pipeline.Name, documents);
            return results;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package zilla.libcore.lifecircle;

import android.content.Intent;
import android.os.Bundle;

/**
 * 生命周期管理接口,用于管理注入控件/对象的生命周期。该注释可以用于ZillaFragment和ZillaActivity
 * 用法:@LifeCircleInject
 * 参考:AppExitLife
 * User: chenze
 * Date: 13-10-11
 * Time: 上午10:17
 */
public interface ILifeCircle {

    void onCreate(Bundle savedInstanceState);

    void onResume();

    void onActivityResult(int requestCode, int resultCode, Intent data);

    void onPause();

    void onDestroy();
}


text:
package com.getui.logful.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

public class PackageManagerWrapper {
    private final Context context;

    public PackageManagerWrapper(Context context) {
        this.context = context;
    }

    /**
     * @param permission Manifest.permission to check whether it has been granted.
     * @return true if the permission has been granted to the app, false if it hasn't been granted
     *         or the PackageManager could not be contacted.
     */
    public boolean hasPermission(String permission) {
        final PackageManager pm = context.getPackageManager();
        if (pm == null) {
            return false;
        }

        try {
            return pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
        } catch (RuntimeException e) {
            // To catch RuntimeException("Package manager has died") that can occur on some version
            // of Android,
            // when the remote PackageManager is unavailable. I suspect this sometimes occurs when
            // the App is being reinstalled.
            return false;
        }
    }

    /**
     * @return PackageInfo for the current application or null if the PackageManager could not be
     *         contacted.
     */
    public PackageInfo getPackageInfo() {
        final PackageManager pm = context.getPackageManager();
        if (pm == null) {
            return null;
        }

        try {
            return pm.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            LogUtil.e("PackageManagerWrapper", "NameNotFoundException", e);
            return null;
        } catch (RuntimeException e) {
            // To catch RuntimeException("Package manager has died") that can occur on some version
            // of Android,
            // when the remote PackageManager is unavailable. I suspect this sometimes occurs when
            // the App is being reinstalled.
            return null;
        }
    }
}


text:
<?php
/* @var $this CellarsController */
/* @var $model Cellars */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'id'); ?>
		<?php echo $form->textField($model,'id'); ?>

		<?php echo $form->label($model,'owner_id'); ?>
		<?php echo $form->textField($model,'owner_id'); ?>

		<?php echo $form->label($model,'cellar_name'); ?>
		<?php echo $form->textField($model,'cellar_name',array('size'=>45,'maxlength'=>45)); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
namespace Parser
{
    Flux::Flux( std::string filename ) : yaml( filename )
    {
        for( std::list<Yaml::TableRow>::iterator it = this->yaml.rows.begin(); it != this->yaml.rows.end(); ++it )
        {
            this->rows.push_back( TableRow( *it ) );
        }

        for( std::list<Yaml::Col>::iterator it = this->yaml.cols.begin(); it != this->yaml.cols.end(); ++it )
        {
            Col* col = new Col( *it );
            this->cols.push_back( col );

            for( std::list<TableRow>::iterator it = this->rows.begin(); it != this->rows.end(); ++it )
            {
                ( *it ).anchor( col );
            }
        }
    }

    void Flux::merge( std::string filename )
    {
        this->yaml.merge( filename );
    }

    void Flux::run()
    {
//         if(!this->downloadFile())
//         {
//             Logger::error("Impossible de télécharger le fichier");
//             return;
//         }
//
//         std::rename(
//             (this->yaml.workdir+"/"+this->yaml.flux_identifier+".tmp").c_str(),
//             (this->yaml.workdir+"/"+this->yaml.flux_identifier).c_str()
//
//         );

        Reader_Abstract* reader = new Reader_CSV( this->yaml.workdir + "/" + this->yaml.flux_identifier, this->yaml.flux_separator );
        char** row = ( char** )reader->row();

        for( std::list<Col*>::iterator it = this->cols.begin(); it != this->cols.end(); ++it )
        {
            ( *it )->anchorCSV( row );
        }

        std::list<TableRow>::iterator it;

        while( reader->nextRow() )
        {
            for( it = this->rows.begin(); it != this->rows.end(); ++it )
            {
                ( *it ).run();
            }
        }
    }

    bool Flux::downloadFile()
    {
        Logger::debug( std::string( "Début téléchargement : " ) + this->yaml.flux_url );

        CURL* curl;
        CURLcode res;
        std::FILE* fp;

        curl = curl_easy_init();

        if( !curl )
        {
            return false;
        }

        fp = std::fopen( ( this->yaml.workdir + "/" + this->yaml.flux_identifier + ".tmp" ).c_str(), "wb" );

        curl_easy_setopt( curl, CURLOPT_URL, this->yaml.flux_url.c_str() );
        curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1L );
        curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, std::fwrite );
        curl_easy_setopt( curl, CURLOPT_WRITEDATA, fp );

        res = curl_easy_perform( curl );

        if( res != CURLE_OK )
        {
            Logger::warning( curl_easy_strerror( res ) );
            curl_easy_cleanup( curl );
            return false;
        }

        curl_easy_cleanup( curl );
        return true;
    }

}


text:
package org.apache.kafka.streams.kstream.internals;

import org.apache.kafka.streams.kstream.Aggregator;
import org.apache.kafka.streams.processor.AbstractProcessor;
import org.apache.kafka.streams.processor.Processor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.KeyValueStore;

public class KTableAggregate<K, V, T> implements KTableProcessorSupplier<K, V, T> {

    private final String storeName;
    private final Aggregator<K, V, T> aggregator;

    private boolean sendOldValues = false;

    public KTableAggregate(String storeName, Aggregator<K, V, T> aggregator) {
        this.storeName = storeName;
        this.aggregator = aggregator;
    }

    @Override
    public void enableSendingOldValues() {
        sendOldValues = true;
    }

    @Override
    public Processor<K, Change<V>> get() {
        return new KTableAggregateProcessor();
    }

    private class KTableAggregateProcessor extends AbstractProcessor<K, Change<V>> {

        private KeyValueStore<K, T> store;

        @SuppressWarnings("unchecked")
        @Override
        public void init(ProcessorContext context) {
            super.init(context);

            store = (KeyValueStore<K, T>) context.getStateStore(storeName);
        }

        @Override
        public void process(K key, Change<V> value) {
            T oldAgg = store.get(key);

            if (oldAgg == null)
                oldAgg = aggregator.initialValue(key);

            T newAgg = oldAgg;

            // first try to remove the old value
            if (value.oldValue != null) {
                newAgg = aggregator.remove(key, value.oldValue, newAgg);
            }

            // then try to add the new new value
            if (value.newValue != null) {
                newAgg = aggregator.add(key, value.newValue, newAgg);
            }

            // update the store with the new value
            store.put(key, newAgg);

            // send the old / new pair
            if (sendOldValues)
                context().forward(key, new Change<>(newAgg, oldAgg));
            else
                context().forward(key, new Change<>(newAgg, null));
        }
    }

    @Override
    public KTableValueGetterSupplier<K, T> view() {

        return new KTableValueGetterSupplier<K, T>() {

            public KTableValueGetter<K, T> get() {
                return new KTableAggregateValueGetter();
            }

        };
    }

    private class KTableAggregateValueGetter implements KTableValueGetter<K, T> {

        private KeyValueStore<K, T> store;

        @SuppressWarnings("unchecked")
        @Override
        public void init(ProcessorContext context) {
            store = (KeyValueStore<K, T>) context.getStateStore(storeName);
        }

        @Override
        public T get(K key) {
            return store.get(key);
        }

    }
}


text:
package com.amazonaws.services.sagemaker.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.sagemaker.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * LabelingJobStoppingConditionsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class LabelingJobStoppingConditionsMarshaller {

    private static final MarshallingInfo<Integer> MAXHUMANLABELEDOBJECTCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MaxHumanLabeledObjectCount").build();
    private static final MarshallingInfo<Integer> MAXPERCENTAGEOFINPUTDATASETLABELED_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MaxPercentageOfInputDatasetLabeled").build();

    private static final LabelingJobStoppingConditionsMarshaller instance = new LabelingJobStoppingConditionsMarshaller();

    public static LabelingJobStoppingConditionsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(LabelingJobStoppingConditions labelingJobStoppingConditions, ProtocolMarshaller protocolMarshaller) {

        if (labelingJobStoppingConditions == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(labelingJobStoppingConditions.getMaxHumanLabeledObjectCount(), MAXHUMANLABELEDOBJECTCOUNT_BINDING);
            protocolMarshaller.marshall(labelingJobStoppingConditions.getMaxPercentageOfInputDatasetLabeled(), MAXPERCENTAGEOFINPUTDATASETLABELED_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php
require_once("constants.phpm");
require_once("request.phpm");
require_once("constraint.phpm");
require_once("constraintfailure.phpm");

$strTemplateFile = "search.phtml";

$displayHash = Array();

$objRequest = new request();
$blHadProblems = ($objRequest->IsRedirectFollowingConstraintFailure());

$displayHash["HADPROBLEMS"] = $blHadProblems;

if ($blHadProblems) {
  $objFailingRequest =
   $objRequest->GetOriginalRequestObjectFollowingConstraintFailure();
  $arConstraintFailures = $objFailingRequest->GetConstraintFailures();
  $displayHash["PROBLEMS"] = Array();
  for ($i=0; $i<=sizeof($arConstraintFailures)-1; $i++) {
    $objThisConstraintFailure = &$arConstraintFailures[$i];
    $objThisFailingConstraintObject =
         $objThisConstraintFailure->GetFailedConstraintObject();
    $intTypeOfFailure = $objThisFailingConstraintObject->GetConstraintType();
    switch ($intTypeOfFailure) {
      case CT_MINLENGTH:
        $displayHash["PROBLEMS"][] = "Your search term was too short.";
        break;
      case CT_MAXLENGTH:
        $displayHash["PROBLEMS"][] = "Your search term was too long.";
        break;
      case CT_PERMITTEDCHARACTERS:
        $displayHash["PROBLEMS"][] = "Your search term contained characters
        I didn't understand.";
        break;
    };
  };
};

require_once($strTemplateFile);
exit(0);
?>


text:
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0
/* ////////////////////////////////////////////////////////////////////////////
 * Purpose: describe_subscription_filters.cpp demonstrates how to list the subscription filters for an Amazon CloudWatch Logs resource.
 *
 * Prerequisites:
 * A CloudWatch Logs subscription with a filter.
 *
 * Inputs:
 * - log_group_name: The name of the log group.
 *
 * Outputs:
 * This subscription filters are described.
 * ///////////////////////////////////////////////////////////////////////// */
//snippet-start:[cwl.cpp.describe_subscription_filters.inc]
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/logs/CloudWatchLogsClient.h>
#include <aws/logs/model/DescribeSubscriptionFiltersRequest.h>
#include <aws/logs/model/DescribeSubscriptionFiltersResult.h>
#include <iostream>
#include <iomanip>
//snippet-end:[cwl.cpp.describe_subscription_filters.inc]

/**
 * List CloudWatch subscription filters associated with a log group
 */
int main(int argc, char** argv)
{
    if (argc != 2)
    {
        std::cout << "Usage: describe_subscription_filters <log_group_name>"
            << std::endl;
        return 1;
    }

    Aws::String log_group(argv[1]);
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
    //snippet-start:[cwl.cpp.describe_subscription_filters]
        Aws::CloudWatchLogs::CloudWatchLogsClient cwl;
        Aws::CloudWatchLogs::Model::DescribeSubscriptionFiltersRequest request;
        request.SetLogGroupName(log_group);
        request.SetLimit(1);

        bool done = false;
        bool header = false;
        while (!done) {
            auto outcome = cwl.DescribeSubscriptionFilters(
                    request);
            if (!outcome.IsSuccess()) {
                std::cout << "Failed to describe CloudWatch subscription filters "
                    << "for log group " << log_group << ": " <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header) {
                std::cout << std::left << std::setw(32) << "Name" <<
                    std::setw(64) << "FilterPattern" << std::setw(64) <<
                    "DestinationArn" << std::endl;
                header = true;
            }

            const auto &filters = outcome.GetResult().GetSubscriptionFilters();
            for (const auto &filter : filters) {
                std::cout << std::left << std::setw(32) <<
                    filter.GetFilterName() << std::setw(64) <<
                    filter.GetFilterPattern() << std::setw(64) <<
                    filter.GetDestinationArn() << std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
        //snippet-end:[cwl.cpp.describe_subscription_filters]

    }
    Aws::ShutdownAPI(options);
    return 0;
}


text:
import collections
import logging
from enum import Enum
from typing import Any, Dict, Optional

from ray.util.timer import _Timer
from ray.rllib.policy.rnn_sequencing import timeslice_along_seq_lens_with_overlap
from ray.rllib.policy.sample_batch import MultiAgentBatch, SampleBatch
from ray.rllib.utils.annotations import override
from ray.rllib.utils.deprecation import Deprecated
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.replay_buffers.replay_buffer import (
    _ALL_POLICIES,
    ReplayBuffer,
    StorageUnit,
)
from ray.rllib.utils.typing import PolicyID, SampleBatchType
from ray.util.annotations import DeveloperAPI
from ray.util.debug import log_once

logger = logging.getLogger(__name__)

@DeveloperAPI
class ReplayMode(Enum):
    LOCKSTEP = "lockstep"
    INDEPENDENT = "independent"

@DeveloperAPI
def merge_dicts_with_warning(args_on_init, args_on_call):
    """Merge argument dicts, overwriting args_on_call with warning.

    The MultiAgentReplayBuffer supports setting standard arguments for calls
    of methods of the underlying buffers. These arguments can be
    overwritten. Such overwrites trigger a warning to the user.
    """
    for arg_name, arg_value in args_on_call.items():
        if arg_name in args_on_init:
            if log_once("overwrite_argument_{}".format((str(arg_name)))):
                logger.warning(
                    "Replay Buffer was initialized to have "
                    "underlying buffers methods called with "
                    "argument `{}={}`, but was subsequently called "
                    "with `{}={}`.".format(
                        arg_name,
                        args_on_init[arg_name],
                        arg_name,
                        arg_value,
                    )
                )
    return {**args_on_init, **args_on_call}

@DeveloperAPI
class MultiAgentReplayBuffer(ReplayBuffer):
    """A replay buffer shard for multiagent setups.

    This buffer is meant to be run in parallel to distribute experiences
    across `num_shards` shards. Unlike simpler buffers, it holds a set of
    buffers - one for each policy ID.
    """

    def __init__(
        self,
        capacity: int = 10000,
        storage_unit: str = "timesteps",
        num_shards: int = 1,
        replay_mode: str = "independent",
        replay_sequence_override: bool = True,
        replay_sequence_length: int = 1,
        replay_burn_in: int = 0,
        replay_zero_init_states: bool = True,
        underlying_buffer_config: dict = None,
        **kwargs
    ):
        """Initializes a MultiAgentReplayBuffer instance.

        Args:
            capacity: The capacity of the buffer, measured in `storage_unit`.
            storage_unit: Either 'timesteps', 'sequences' or
                'episodes'. Specifies how experiences are stored. If they
                are stored in episodes, replay_sequence_length is ignored.
            num_shards: The number of buffer shards that exist in total
                (including this one).
            replay_mode: One of "independent" or "lockstep". Determines,
                whether batches are sampled independently or to an equal
                amount.
            replay_sequence_override: If True, ignore sequences found in incoming
                batches, slicing them into sequences as specified by
                `replay_sequence_length` and `replay_sequence_burn_in`. This only has
                an effect if storage_unit is `sequences`.
            replay_sequence_length: The sequence length (T) of a single
                sample. If > 1, we will sample B x T from this buffer. This
                only has an effect if storage_unit is 'timesteps'.
            replay_burn_in: This is the number of timesteps
                each sequence overlaps with the previous one to generate a
                better internal state (=state after the burn-in), instead of
                starting from 0.0 each RNN rollout. This only has an effect
                if storage_unit is `sequences`.
            replay_zero_init_states: Whether the initial states in the
                buffer (if replay_sequence_length > 0) are alwayas 0.0 or
                should be updated with the previous train_batch state outputs.
            underlying_buffer_config: A config that contains all necessary
                constructor arguments and arguments for methods to call on
                the underlying buffers.
            ``**kwargs``: Forward compatibility kwargs.
        """
        shard_capacity = capacity // num_shards
        ReplayBuffer.__init__(self, capacity, storage_unit)

        # If the user provides an underlying buffer config, we use to
        # instantiate and interact with underlying buffers
        self.underlying_buffer_config = underlying_buffer_config
        if self.underlying_buffer_config is not None:
            self.underlying_buffer_call_args = self.underlying_buffer_config
        else:
            self.underlying_buffer_call_args = {}
        self.replay_sequence_override = replay_sequence_override
        self.replay_mode = replay_mode
        self.replay_sequence_length = replay_sequence_length
        self.replay_burn_in = replay_burn_in
        self.replay_zero_init_states = replay_zero_init_states
        self.replay_sequence_override = replay_sequence_override

        if (
            replay_sequence_length > 1
            and self.storage_unit is not StorageUnit.SEQUENCES
        ):
            logger.warning(
                "MultiAgentReplayBuffer configured with "
                "`replay_sequence_length={}`, but `storage_unit={}`. "
                "replay_sequence_length will be ignored and set to 1.".format(
                    replay_sequence_length, storage_unit
                )
            )
            self.replay_sequence_length = 1

        if replay_sequence_length == 1 and self.storage_unit is StorageUnit.SEQUENCES:
            logger.warning(
                "MultiAgentReplayBuffer configured with "
                "`replay_sequence_length={}`, but `storage_unit={}`. "
                "This will result in sequences equal to timesteps.".format(
                    replay_sequence_length, storage_unit
                )
            )

        if replay_mode in ["lockstep", ReplayMode.LOCKSTEP]:
            self.replay_mode = ReplayMode.LOCKSTEP
            if self.storage_unit in [StorageUnit.EPISODES, StorageUnit.SEQUENCES]:
                raise ValueError(
                    "MultiAgentReplayBuffer does not support "
                    "lockstep mode with storage unit `episodes`"
                    "or `sequences`."
                )
        elif replay_mode in ["independent", ReplayMode.INDEPENDENT]:
            self.replay_mode = ReplayMode.INDEPENDENT
        else:
            raise ValueError("Unsupported replay mode: {}".format(replay_mode))

        if self.underlying_buffer_config:
            ctor_args = {
                **{"capacity": shard_capacity, "storage_unit": StorageUnit.FRAGMENTS},
                **self.underlying_buffer_config,
            }

            def new_buffer():
                return from_config(self.underlying_buffer_config["type"], ctor_args)

        else:
            # Default case
            def new_buffer():
                self.underlying_buffer_call_args = {}
                return ReplayBuffer(
                    self.capacity,
                    storage_unit=StorageUnit.FRAGMENTS,
                )

        self.replay_buffers = collections.defaultdict(new_buffer)

        # Metrics.
        self.add_batch_timer = _Timer()
        self.replay_timer = _Timer()
        self._num_added = 0

    def __len__(self) -> int:
        """Returns the number of items currently stored in this buffer."""
        return sum(len(buffer._storage) for buffer in self.replay_buffers.values())

    @DeveloperAPI
    @Deprecated(
        old="ReplayBuffer.replay()",
        new="ReplayBuffer.sample(num_items)",
        error=True,
    )
    def replay(self, num_items: int = None, **kwargs) -> Optional[SampleBatchType]:
        """Deprecated in favor of new ReplayBuffer API."""
        pass

    @DeveloperAPI
    @override(ReplayBuffer)
    def add(self, batch: SampleBatchType, **kwargs) -> None:
        """Adds a batch to the appropriate policy's replay buffer.

        Turns the batch into a MultiAgentBatch of the DEFAULT_POLICY_ID if
        it is not a MultiAgentBatch. Subsequently, adds the individual policy
        batches to the storage.

        Args:
            batch : The batch to be added.
            ``**kwargs``: Forward compatibility kwargs.
        """
        if batch is None:
            if log_once("empty_batch_added_to_buffer"):
                logger.info(
                    "A batch that is `None` was added to {}. This can be "
                    "normal at the beginning of execution but might "
                    "indicate an issue.".format(type(self).__name__)
                )
            return
        # Make a copy so the replay buffer doesn't pin plasma memory.
        batch = batch.copy()
        # Handle everything as if multi-agent.
        batch = batch.as_multi_agent()

        with self.add_batch_timer:
            pids_and_batches = self._maybe_split_into_policy_batches(batch)
            for policy_id, sample_batch in pids_and_batches.items():
                self._add_to_underlying_buffer(policy_id, sample_batch, **kwargs)

        self._num_added += batch.count

    @DeveloperAPI
    def _add_to_underlying_buffer(
        self, policy_id: PolicyID, batch: SampleBatchType, **kwargs
    ) -> None:
        """Add a batch of experiences to the underlying buffer of a policy.

        If the storage unit is `timesteps`, cut the batch into timeslices
        before adding them to the appropriate buffer. Otherwise, let the
        underlying buffer decide how slice batches.

        Args:
            policy_id: ID of the policy that corresponds to the underlying
            buffer
            batch: SampleBatch to add to the underlying buffer
            ``**kwargs``: Forward compatibility kwargs.
        """
        # Merge kwargs, overwriting standard call arguments
        kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs)

        # For the storage unit `timesteps`, the underlying buffer will
        # simply store the samples how they arrive. For sequences and
        # episodes, the underlying buffer may split them itself.
        if self.storage_unit is StorageUnit.TIMESTEPS:
            timeslices = batch.timeslices(1)
        elif self.storage_unit is StorageUnit.SEQUENCES:
            timeslices = timeslice_along_seq_lens_with_overlap(
                sample_batch=batch,
                seq_lens=batch.get(SampleBatch.SEQ_LENS)
                if self.replay_sequence_override
                else None,
                zero_pad_max_seq_len=self.replay_sequence_length,
                pre_overlap=self.replay_burn_in,
                zero_init_states=self.replay_zero_init_states,
            )
        elif self.storage_unit == StorageUnit.EPISODES:
            timeslices = []
            for eps in batch.split_by_episode():
                if (
                    eps.get(SampleBatch.T)[0] == 0
                    and eps.get(SampleBatch.DONES)[-1] == True  # noqa E712
                ):
                    # Only add full episodes to the buffer
                    timeslices.append(eps)
                else:
                    if log_once("only_full_episodes"):
                        logger.info(
                            "This buffer uses episodes as a storage "
                            "unit and thus allows only full episodes "
                            "to be added to it. Some samples may be "
                            "dropped."
                        )
        elif self.storage_unit == StorageUnit.FRAGMENTS:
            timeslices = [batch]
        else:
            raise ValueError("Unknown `storage_unit={}`".format(self.storage_unit))

        for slice in timeslices:
            self.replay_buffers[policy_id].add(slice, **kwargs)

    @DeveloperAPI
    @override(ReplayBuffer)
    def sample(
        self, num_items: int, policy_id: Optional[PolicyID] = None, **kwargs
    ) -> Optional[SampleBatchType]:
        """Samples a MultiAgentBatch of `num_items` per one policy's buffer.

        If less than `num_items` records are in the policy's buffer,
        some samples in the results may be repeated to fulfil the batch size
        `num_items` request. Returns an empty batch if there are no items in
        the buffer.

        Args:
            num_items: Number of items to sample from a policy's buffer.
            policy_id: ID of the policy that created the experiences we sample. If
            none is given, sample from all policies.

        Returns:
            Concatenated MultiAgentBatch of items.
            ``**kwargs``: Forward compatibility kwargs.
        """
        # Merge kwargs, overwriting standard call arguments
        kwargs = merge_dicts_with_warning(self.underlying_buffer_call_args, kwargs)

        with self.replay_timer:
            # Lockstep mode: Sample from all policies at the same time an
            # equal amount of steps.
            if self.replay_mode == ReplayMode.LOCKSTEP:
                assert (
                    policy_id is None
                ), "`policy_id` specifier not allowed in `lockstep` mode!"
                # In lockstep mode we sample MultiAgentBatches
                return self.replay_buffers[_ALL_POLICIES].sample(num_items, **kwargs)
            elif policy_id is not None:
                sample = self.replay_buffers[policy_id].sample(num_items, **kwargs)
                return MultiAgentBatch({policy_id: sample}, sample.count)
            else:
                samples = {}
                for policy_id, replay_buffer in self.replay_buffers.items():
                    samples[policy_id] = replay_buffer.sample(num_items, **kwargs)
                return MultiAgentBatch(samples, sum(s.count for s in samples.values()))

    @DeveloperAPI
    @override(ReplayBuffer)
    def stats(self, debug: bool = False) -> Dict:
        """Returns the stats of this buffer and all underlying buffers.

        Args:
            debug: If True, stats of underlying replay buffers will
            be fetched with debug=True.

        Returns:
            stat: Dictionary of buffer stats.
        """
        stat = {
            "add_batch_time_ms": round(1000 * self.add_batch_timer.mean, 3),
            "replay_time_ms": round(1000 * self.replay_timer.mean, 3),
        }
        for policy_id, replay_buffer in self.replay_buffers.items():
            stat.update(
                {"policy_{}".format(policy_id): replay_buffer.stats(debug=debug)}
            )
        return stat

    @DeveloperAPI
    @override(ReplayBuffer)
    def get_state(self) -> Dict[str, Any]:
        """Returns all local state.

        Returns:
            The serializable local state.
        """
        state = {"num_added": self._num_added, "replay_buffers": {}}
        for policy_id, replay_buffer in self.replay_buffers.items():
            state["replay_buffers"][policy_id] = replay_buffer.get_state()
        return state

    @DeveloperAPI
    @override(ReplayBuffer)
    def set_state(self, state: Dict[str, Any]) -> None:
        """Restores all local state to the provided `state`.

        Args:
            state: The new state to set this buffer. Can be obtained by
                calling `self.get_state()`.
        """
        self._num_added = state["num_added"]
        buffer_states = state["replay_buffers"]
        for policy_id in buffer_states.keys():
            self.replay_buffers[policy_id].set_state(buffer_states[policy_id])

    def _maybe_split_into_policy_batches(self, batch: SampleBatchType):
        """Returns a dict of policy IDs and batches, depending on our replay mode.

        This method helps with splitting up MultiAgentBatches only if the
        self.replay_mode requires it.
        """
        if self.replay_mode == ReplayMode.LOCKSTEP:
            return {_ALL_POLICIES: batch}
        else:
            return batch.policy_batches


text:
module DatabaseConnectionHelper
  def with_connection(options)
    connection = ::Sequel.connect(options)
    begin
      yield connection
    ensure
      connection.disconnect
    end
  end

  def with_connection_from_user(user, &block)
    options = ::SequelRails.configuration.environment_for(Rails.env).merge(
      'database' => user.database_name,
      'username' => user.database_username,
      'password' => user.database_password,
      'host' => user.database_host
    )
    with_connection options, &block
  end

  def with_connection_from_api_key(api_key, &block)
    user = api_key.user
    options = ::SequelRails.configuration.environment_for(Rails.env).merge(
      'database' => user.database_name,
      'username' => api_key.db_role,
      'password' => api_key.db_password,
      'host' => user.database_host
    )
    with_connection options, &block
  end
end


text:
package by.hut.flat.calendar.core.DBAdapter;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public final class DBAdapter{
	int id = 0;
	public int state = 0;

	private final Context context;

	private DatabaseHelper DBHelper;
	private SQLiteDatabase db;
	public DBAdapter(Context ctx){
		this.context = ctx;
		DBHelper = new DatabaseHelper(context);
	}

	private static class DatabaseHelper extends SQLiteOpenHelper  {
		DatabaseHelper(Context context) {
			super(context, dbStructure.DATABASE_NAME, null, dbStructure.DATABASE_VERSION);
		}
		@Override
		public void onCreate(SQLiteDatabase db) {
			System.out.println("Create db");
		}
		@Override
		public void onUpgrade(final SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(dbStructure.TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
		}
	}
	public SQLiteDatabase getDB(){
		return db;
	}

	public Context getContext(){
		return this.context;
	}

	/********************************************************************************************************************/
	/****************************************************S T A T I C*****************************************************/
	/********************************************************************************************************************/

	public DBAdapter open() throws SQLException  {
		if (state == 0){
			db = DBHelper.getWritableDatabase();
			state = 1;
		}
		return this;
	}

	public void close(){
		if (state == 1){
			DBHelper.close();
			state = 0;
		}
	}

	public boolean isOpen(){
		return state == 1;
	}

	public void releaseMemory(){
		SQLiteDatabase.releaseMemory();
	}

	public void exec(String str){
		db.rawQuery(str,null);
	}

}


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

/// @file file_io.cc
/// This example demonstrates the use of persistent file I/O

#define __STDC_LIMIT_MACROS
#include <sstream>
#include <string>

#include "ppapi/c/pp_stdint.h"
#include "ppapi/c/ppb_file_io.h"
#include "ppapi/cpp/file_io.h"
#include "ppapi/cpp/file_ref.h"
#include "ppapi/cpp/file_system.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
#include "ppapi/utility/completion_callback_factory.h"

#ifndef INT32_MAX
#define INT32_MAX (0x7FFFFFFF)
#endif

#ifdef WIN32
#undef min
#undef max
#undef PostMessage

// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif

namespace {
/// Used for our simple protocol to communicate with Javascript
const char* const kLoadPrefix = "ld";
const char* const kSavePrefix = "sv";
const char* const kDeletePrefix = "de";
}

/// The Instance class.  One of these exists for each instance of your NaCl
/// module on the web page.  The browser will ask the Module object to create
/// a new Instance for each occurence of the <embed> tag that has these
/// attributes:
///     type="application/x-nacl"
///     src="file_io.nmf"
class FileIoInstance : public pp::Instance {
 public:
  /// The constructor creates the plugin-side instance.
  /// @param[in] instance the handle to the browser-side plugin instance.
  explicit FileIoInstance(PP_Instance instance)
      : pp::Instance(instance),
        callback_factory_(this),
        file_system_(this, PP_FILESYSTEMTYPE_LOCALPERSISTENT),
        file_system_ready_(false) {
  }

  virtual ~FileIoInstance() {
  }

  virtual bool Init(uint32_t /*argc*/, const char* /*argn*/[],
      const char* /*argv*/[]) {
    pp::CompletionCallback callback = callback_factory_.NewCallback(
        &FileIoInstance::FileSystemOpenCallback);
    int32_t rv = file_system_.Open(1024*1024, callback);
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return false;
    }
    return true;
  }

 protected:
  pp::CompletionCallbackFactory<FileIoInstance> callback_factory_;
  pp::FileSystem file_system_;
  bool file_system_ready_;

 private:
  /// Struct to hold various info about a file operation. Our scheme in this
  /// example is to allocate this information on the heap so that is persists
  /// after the asynchronous call until the callback is called, and is
  /// therefore available to the main thread to complete the requested operation
  struct Request {
    pp::FileRef ref;
    pp::FileIO file;
    std::string file_contents;
    int64_t offset;
    PP_FileInfo info;
  };

  /// Handler for messages coming in from the browser via postMessage().  The
  /// @a var_message can contain anything: a JSON string; a string that encodes
  /// method names and arguments; etc.
  ///
  /// Here we use messages to communicate with the user interface
  ///
  /// @param[in] var_message The message posted by the browser.
  virtual void HandleMessage(const pp::Var& var_message) {
    if (!var_message.is_string())
      return;

    // Parse message into: instruction file_name_length file_name [file_text]
    std::string message = var_message.AsString();
    std::string instruction;
    std::string file_name;
    std::stringstream reader(message);
    int file_name_length;

    reader >> instruction >> file_name_length;
    file_name.resize(file_name_length);
    reader.ignore(1);  // Eat the delimiter
    reader.read(&file_name[0], file_name_length);

    if (file_name.length() == 0 || file_name[0] != '/') {
      ShowStatusMessage("File name must begin with /");
      return;
    }

    // Dispatch the instruction
    if (instruction.compare(kLoadPrefix) == 0) {
      Load(file_name);
      return;
    }

    if (instruction.compare(kSavePrefix) == 0) {
      // Read the rest of the message as the file text
      reader.ignore(1);  // Eat the delimiter
      std::string file_text = message.substr(reader.tellg());
      Save(file_name, file_text);
      return;
    }

    if (instruction.compare(kDeletePrefix) == 0) {
      Delete(file_name);
      return;
    }
  }

  bool Save(const std::string& file_name, const std::string& file_contents) {
    if (!file_system_ready_) {
      ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
      return false;
    }

    FileIoInstance::Request* request = new FileIoInstance::Request;
    request->ref = pp::FileRef(file_system_, file_name.c_str());
    request->file = pp::FileIO(this);
    request->file_contents = file_contents;

    pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::SaveOpenCallback, request);
    int32_t rv = request->file.Open(request->ref,
        PP_FILEOPENFLAG_WRITE|PP_FILEOPENFLAG_CREATE|PP_FILEOPENFLAG_TRUNCATE,
        callback);

    // Handle cleanup in the callback if error
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return false;
    }
    return true;
  }

  void SaveOpenCallback(int32_t result, FileIoInstance::Request* request) {
    if (result != PP_OK) {
      ShowErrorMessage("File open for write failed", result);
      delete request;
      return;
    }

    // It is an error to write 0 bytes to the file, however,
    // upon opening we have truncated the file to length 0
    if (request->file_contents.length() == 0) {
      pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::SaveFlushCallback, request);
      int32_t rv = request->file.Flush(callback);

      // Handle cleanup in the callback if error
      if (rv != PP_OK_COMPLETIONPENDING) {
        callback.Run(rv);
        return;
      }
    } else if (request->file_contents.length() <= INT32_MAX) {
      request->offset = 0;
      pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::SaveWriteCallback, request);

      int32_t rv = request->file.Write(request->offset,
          request->file_contents.c_str(),
          request->file_contents.length(), callback);

      // Handle cleanup in the callback if error
      if (rv != PP_OK_COMPLETIONPENDING) {
        callback.Run(rv);
        return;
      }
    } else {
      ShowErrorMessage("File too big", PP_ERROR_FILETOOBIG);
      delete request;
      return;
    }
  }

  void SaveWriteCallback(int32_t bytes_written,
      FileIoInstance::Request* request) {
    // bytes_written is the error code if < 0
    if (bytes_written < 0) {
      ShowErrorMessage("File write failed", bytes_written);
      delete request;
      return;
    }

    // Ensure the content length is something write() can handle
    assert(request->file_contents.length() <= INT32_MAX);

    request->offset += bytes_written;

    if (static_cast<size_t>(request->offset) == request->file_contents.length()
        || bytes_written == 0) {
      // All bytes have been written, flush the write buffer to complete
      pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::SaveFlushCallback, request);
      int32_t rv = request->file.Flush(callback);

      // Handle cleanup in the callback if error
      if (rv != PP_OK_COMPLETIONPENDING) {
        callback.Run(rv);
        return;
      }
    } else {
      // If all the bytes haven't been written call write again with remainder
      pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::SaveWriteCallback, request);
      int32_t rv = request->file.Write(request->offset,
          request->file_contents.c_str() + request->offset,
          request->file_contents.length() - request->offset, callback);

      // Handle cleanup in the callback if error
      if (rv != PP_OK_COMPLETIONPENDING) {
        callback.Run(rv);
        return;
      }
    }
  }

  void SaveFlushCallback(int32_t result, FileIoInstance::Request* request) {
    if (result != PP_OK) {
      ShowErrorMessage("File fail to flush", result);
      delete request;
      return;
    }
    ShowStatusMessage("Save successful");
    delete request;
  }

  bool Load(const std::string& file_name) {
    if (!file_system_ready_) {
      ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
      return false;
    }

    FileIoInstance::Request* request = new FileIoInstance::Request;
    request->ref = pp::FileRef(file_system_, file_name.c_str());
    request->file = pp::FileIO(this);

    pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::LoadOpenCallback, request);
    int32_t rv = request->file.Open(request->ref, PP_FILEOPENFLAG_READ,
        callback);

    // Handle cleanup in the callback if error
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return false;
    }
    return true;
  }

  void LoadOpenCallback(int32_t result, FileIoInstance::Request* request) {
    if (result == PP_ERROR_FILENOTFOUND) {
      ShowStatusMessage("File not found");
      delete request;
      return;
    } else if (result != PP_OK) {
      ShowErrorMessage("File open for read failed", result);
      delete request;
      return;
    }

    pp::CompletionCallback callback = callback_factory_.NewCallback(
          &FileIoInstance::LoadQueryCallback, request);
    int32_t rv = request->file.Query(&request->info, callback);

    // Handle cleanup in the callback if error
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return;
    }
  }

  void LoadQueryCallback(int32_t result, FileIoInstance::Request* request) {
    if (result != PP_OK) {
      ShowErrorMessage("File query failed", result);
      delete request;
      return;
    }

    // FileIO.Read() can only handle int32 sizes
    if (request->info.size > INT32_MAX) {
      ShowErrorMessage("File too big", PP_ERROR_FILETOOBIG);
      delete request;
      return;
    }

    // Allocate a buffer to read the file into
    // Here we must allocate on the heap so FileIO::Read will write to this
    // one and only copy of file_contents
    request->file_contents.resize(request->info.size, '\0');
    request->offset = 0;

    pp::CompletionCallback callback = callback_factory_.NewCallback(
        &FileIoInstance::LoadReadCallback, request);
    int32_t rv = request->file.Read(request->offset,
        &request->file_contents[request->offset],
        request->file_contents.length(), callback);

    // Handle cleanup in the callback if error
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return;
    }
  }

  void LoadReadCallback(int32_t bytes_read, FileIoInstance::Request* request) {
    // If bytes_read < 0 then it indicates the error code
    if (bytes_read < 0) {
      ShowErrorMessage("File read failed", bytes_read);
      delete request;
      return;
    }

    // Ensure the content length is something read() can handle
    assert(request->file_contents.length() <= INT32_MAX);

    request->offset += bytes_read;

    if (static_cast<size_t>(request->offset) == request->file_contents.length()
        || bytes_read == 0) {
      // Done reading, send content to the user interface
      PostMessage(pp::Var("DISP|" + request->file_contents));
      ShowStatusMessage("Load complete");
      delete request;
    } else {
      // Some bytes remain to be read, call read again with remainder
      pp::CompletionCallback callback = callback_factory_.NewCallback(
            &FileIoInstance::LoadReadCallback, request);
      int32_t rv = request->file.Read(request->offset,
          &request->file_contents[request->offset],
          request->file_contents.length() - request->offset, callback);

      // Handle cleanup in the callback if error
      if (rv != PP_OK_COMPLETIONPENDING) {
        callback.Run(rv);
        return;
      }
    }
  }

  bool Delete(const std::string& file_name) {
    if (!file_system_ready_) {
      ShowErrorMessage("File system is not open", PP_ERROR_FAILED);
      return false;
    }

    FileIoInstance::Request* request = new FileIoInstance::Request;
    request->ref = pp::FileRef(file_system_, file_name.c_str());

    pp::CompletionCallback callback = callback_factory_.NewCallback(
        &FileIoInstance::DeleteCallback, request);
    int32_t rv = request->ref.Delete(callback);

    // Handle cleanup in the callback if error
    if (rv != PP_OK_COMPLETIONPENDING) {
      callback.Run(rv);
      return false;
    }
    return true;
  }

  void DeleteCallback(int32_t result, FileIoInstance::Request* request) {
    if (result == PP_ERROR_FILENOTFOUND) {
      ShowStatusMessage("File not found");
      delete request;
      return;
    } else if (result != PP_OK) {
      ShowErrorMessage("Deletion failed", result);
      delete request;
      return;
    }

    ShowStatusMessage("File deleted");
    delete request;
  }

  void FileSystemOpenCallback(int32_t result) {
    if (result != PP_OK) {
      ShowErrorMessage("File system open call failed", result);
      return;
    }

    file_system_ready_ = true;
    // Notify the user interface that we're ready
    PostMessage(pp::Var("READY|"));
  }

  /// Encapsulates our simple javascript communication protocol
  void ShowErrorMessage(const std::string& message, int32_t result) {
    std::stringstream ss;
    ss << "ERR|" << message << " -- Error #: " << result;
    PostMessage(pp::Var(ss.str()));
  }

  /// Encapsulates our simple javascript communication protocol
  void ShowStatusMessage(const std::string& message) {
    std::stringstream ss;
    ss << "STAT|" << message;
    PostMessage(pp::Var(ss.str()));
  }
};

/// The Module class.  The browser calls the CreateInstance() method to create
/// an instance of your NaCl module on the web page.  The browser creates a new
/// instance for each <embed> tag with type="application/x-nacl".
class FileIoModule : public pp::Module {
 public:
  FileIoModule() : pp::Module() {}
  virtual ~FileIoModule() {}

  /// Create and return a FileIoInstance object.
  /// @param[in] instance The browser-side instance.
  /// @return the plugin-side instance.
  virtual pp::Instance* CreateInstance(PP_Instance instance) {
    return new FileIoInstance(instance);
  }
};

namespace pp {
/// Factory function called by the browser when the module is first loaded.
/// The browser keeps a singleton of this module.  It calls the
/// CreateInstance() method on the object you return to make instances.  There
/// is one instance per <embed> tag on the page.  This is the main binding
/// point for your NaCl module with the browser.
Module* CreateModule() {
  return new FileIoModule();
}
}  // namespace pp


text:
<?php namespace EC\LemonBee;
defined('_ESPADA') or die(NO_ACCESS);

use E, EC;

$site_class = E\Args::Page('site');
if (!class_exists($site_class))
    throw new \Exception("SLemonBee child `{$site_class}` does not exist.");

$site = new $site_class();
$site->lbSetRequiredPermissions([]);

$site->lbSetPage_LogOut();

\Espada::Initialize($site);


text:
Public Interface IPeopleFinder
	Function GetPeopleInGroup(ByVal groupName As String) As String()
End Interface


text:
package org.hisp.dhis.analytics.event.data;

import static org.hisp.dhis.analytics.event.data.AnalyticsDimensionsTestSupport.allValueTypeDataElements;
import static org.hisp.dhis.analytics.event.data.AnalyticsDimensionsTestSupport.allValueTypeTEAs;
import static org.hisp.dhis.analytics.event.data.DimensionsServiceCommon.AGGREGATE_ALLOWED_VALUE_TYPES;
import static org.hisp.dhis.analytics.event.data.DimensionsServiceCommon.QUERY_DISALLOWED_VALUE_TYPES;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.*;

import org.hisp.dhis.analytics.event.EnrollmentAnalyticsDimensionsService;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class EnrollmentAnalyticsDimensionsServiceTest
{
    private EnrollmentAnalyticsDimensionsService enrollmentAnalyticsDimensionsService;

    @BeforeEach
    void setup()
    {
        ProgramService programService = mock( ProgramService.class );

        Program program = mock( Program.class );

        when( programService.getProgram( any() ) ).thenReturn( program );
        when( program.getDataElements() ).thenReturn( allValueTypeDataElements() );
        when( program.getProgramIndicators() ).thenReturn( Collections.emptySet() );
        when( program.getTrackedEntityAttributes() ).thenReturn( allValueTypeTEAs() );

        enrollmentAnalyticsDimensionsService = new DefaultEnrollmentAnalyticsDimensionsService( programService );

    }

    @Test
    void testQueryDoesntContainDisallowedValueTypes()
    {
        Collection<BaseIdentifiableObject> analyticsDimensions = enrollmentAnalyticsDimensionsService
            .getQueryDimensionsByProgramStageId( "anUid" );

        assertTrue(
            analyticsDimensions
                .stream()
                .filter( b -> b instanceof DataElement )
                .map( de -> ((DataElement) de).getValueType() )
                .noneMatch(
                    QUERY_DISALLOWED_VALUE_TYPES::contains ) );
        assertTrue(
            analyticsDimensions
                .stream()
                .filter( b -> b instanceof TrackedEntityAttribute )
                .map( tea -> ((TrackedEntityAttribute) tea).getValueType() )
                .noneMatch(
                    QUERY_DISALLOWED_VALUE_TYPES::contains ) );
    }

    @Test
    void testAggregateOnlyContainsAllowedValueTypes()
    {
        Collection<BaseIdentifiableObject> analyticsDimensions = enrollmentAnalyticsDimensionsService
            .getAggregateDimensionsByProgramStageId( "anUid" );

        assertTrue(
            analyticsDimensions
                .stream()
                .filter( b -> b instanceof DataElement )
                .map( de -> ((DataElement) de).getValueType() )
                .allMatch(
                    AGGREGATE_ALLOWED_VALUE_TYPES::contains ) );
        assertTrue(
            analyticsDimensions
                .stream()
                .filter( b -> b instanceof TrackedEntityAttribute )
                .map( tea -> ((TrackedEntityAttribute) tea).getValueType() )
                .allMatch(
                    AGGREGATE_ALLOWED_VALUE_TYPES::contains ) );
    }

}


text:
using System.Threading.Tasks;

namespace CitroidForSlack.Api
{
    public interface IBot
	{
		Task InitializeAsync(ICitroid citroid);
		void Exit(ICitroid citroid);
		string Help { get; }
		string Name { get; }
		string Copyright { get; }
		string Version { get; }
	}

}


text:
package com.example.animationtest;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;

public class DropActivity extends AppCompatActivity {

    private LinearLayout mHiddenView;
    private float mDensity;
    private int mHiddenViewMeasuredHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drop);
        mHiddenView = (LinearLayout) findViewById(R.id.hidden_view);
        //获取像素密度
        mDensity = getResources().getDisplayMetrics().density;
        //获取布局的高度
        mHiddenViewMeasuredHeight = (int)(mDensity*40+0.5);
    }

    public void llClick(View view){
        if(mHiddenView.getVisibility() == View.GONE){
            //打开动画
            animateOpen(mHiddenView);
        } else {
            //关闭动画
            animateClose(mHiddenView);
        }
    }

    private void animateOpen(final View view) {
        view.setVisibility(View.VISIBLE);
        ValueAnimator animator = createDropAnimator(view,0,mHiddenViewMeasuredHeight);
        animator.start();
    }

    private void animateClose(final View view){
        int originalHeight = view.getHeight();
        ValueAnimator animator = createDropAnimator(view,originalHeight,0);
        //动画结束后,设置View.Gone,否则Close之后就不能Open了
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);
            }
        });
        animator.start();
    }

    private ValueAnimator createDropAnimator(final View view, int start, int end){
        ValueAnimator animator = ValueAnimator.ofInt(start,end);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int value = (int) valueAnimator.getAnimatedValue();
                ViewGroup.LayoutParams params = view.getLayoutParams();
                params.height = value;
                view.setLayoutParams(params);
            }
        });
        return animator;
    }

    public void btnTest(View view){
        Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
        if(Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
            Log.d("------------->","内存卡存在");
        }else{
            Log.d("------------->","内存卡不存在");
            String path = Environment.getExternalStorageDirectory()+"/zengjie";
            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            Log.d("------------->",Environment.getExternalStorageDirectory().toString());
            Log.d("------------->",Environment.getExternalStorageDirectory().getAbsolutePath());
        }
        Log.d("------------->",getFilesDir().toString());
    }

}


text:
from __future__ import absolute_import, division, print_function
from jaspyx.context.function import FunctionContext

class ModuleContext(FunctionContext):
    def __init__(self):
        super(ModuleContext, self).__init__(None, arg_names=['__module__'])
        self.scope.prefix.append('__module__')


text:
CREATE EXTENSION test_ddl_deparse;

CREATE OR REPLACE FUNCTION test_ddl_deparse()
  RETURNS event_trigger LANGUAGE plpgsql AS
$$
DECLARE
	r record;
	r2 record;
	cmdtype text;
	objtype text;
	tag text;
BEGIN
	FOR r IN SELECT * FROM pg_event_trigger_ddl_commands()
	LOOP
		-- verify that tags match
		tag = public.get_command_tag(r.command);
		IF tag <> r.command_tag THEN
			RAISE NOTICE 'tag % doesn''t match %', tag, r.command_tag;
		END IF;

		-- log the operation
		cmdtype = public.get_command_type(r.command);
		IF cmdtype <> 'grant' THEN
			RAISE NOTICE 'DDL test: type %, tag %', cmdtype, tag;
		ELSE
			RAISE NOTICE 'DDL test: type %, object type %', cmdtype, r.object_type;
		END IF;

		-- if alter table, log more
		IF cmdtype = 'alter table' THEN
			FOR r2 IN SELECT *
						FROM unnest(public.get_altertable_subcmdtypes(r.command))
			LOOP
				RAISE NOTICE '  subcommand: %', r2.unnest;
			END LOOP;
		END IF;
	END LOOP;
END;
$$;

CREATE EVENT TRIGGER test_ddl_deparse
ON ddl_command_end EXECUTE PROCEDURE test_ddl_deparse();


text:
package mltk.predictor.tree;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import mltk.core.Attribute;
import mltk.core.Instances;
import mltk.core.InstancesTestHelper;

public class DecisionTableLearnerTest {

	@Test
	public void testDecisionTableLearner1() {
		DecisionTableLearner rtLearner = new DecisionTableLearner();
		rtLearner.setConstructionMode(DecisionTableLearner.Mode.ONE_PASS_GREEDY);
		rtLearner.setMaxDepth(2);

		Instances instances = InstancesTestHelper.getInstance().getDenseRegressionDataset();
		DecisionTable rt = rtLearner.build(instances);
		int[] attributeIndices = rt.getAttributeIndices();
		Assert.assertEquals(2, attributeIndices.length);
		Assert.assertEquals(0, attributeIndices[0]);
	}

	@Test
	public void testDecisionTableLearner2() {
		DecisionTableLearner rtLearner = new DecisionTableLearner();
		rtLearner.setConstructionMode(DecisionTableLearner.Mode.ONE_PASS_GREEDY);
		rtLearner.setMaxDepth(2);

		Instances instances = InstancesTestHelper.getInstance()
				.getDenseRegressionDataset().copy();
		// Apply feature selection
		List<Attribute> attributes = instances.getAttributes(1);
		instances.setAttributes(attributes);
		DecisionTable rt = rtLearner.build(instances);
		int[] attributeIndices = rt.getAttributeIndices();
		Assert.assertEquals(2, attributeIndices.length);
		Assert.assertEquals(1, attributeIndices[0]);
	}

}


text:
package oauth2_test

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"github.com/ory/hydra/internal/testhelpers"

	"github.com/go-openapi/strfmt"

	"github.com/ory/hydra/internal/httpclient/client/admin"
	"github.com/ory/hydra/internal/httpclient/models"

	"github.com/ory/hydra/jwk"
	"github.com/ory/hydra/x"

	"github.com/ory/hydra/driver/config"
	"github.com/ory/hydra/internal"
	"github.com/ory/x/urlx"

	"github.com/golang/mock/gomock"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	jwt2 "github.com/ory/fosite/token/jwt"

	"github.com/ory/fosite"
	"github.com/ory/fosite/handler/openid"
	"github.com/ory/fosite/token/jwt"
	"github.com/ory/hydra/client"
	hydra "github.com/ory/hydra/internal/httpclient/client"
	"github.com/ory/hydra/oauth2"
)

var lifespan = time.Hour

func TestHandlerDeleteHandler(t *testing.T) {
	conf := internal.NewConfigurationWithDefaults()
	conf.MustSet(config.KeyIssuerURL, "http://hydra.localhost")
	reg := internal.NewRegistryMemory(t, conf)

	cm := reg.ClientManager()
	store := reg.OAuth2Storage()

	h := oauth2.NewHandler(reg, conf)

	deleteRequest := &fosite.Request{
		ID:             "del-1",
		RequestedAt:    time.Now().Round(time.Second),
		Client:         &client.Client{OutfacingID: "foobar"},
		RequestedScope: fosite.Arguments{"fa", "ba"},
		GrantedScope:   fosite.Arguments{"fa", "ba"},
		Form:           url.Values{"foo": []string{"bar", "baz"}},
		Session:        &oauth2.Session{DefaultSession: &openid.DefaultSession{Subject: "bar"}},
	}
	require.NoError(t, cm.CreateClient(context.Background(), deleteRequest.Client.(*client.Client)))
	require.NoError(t, store.CreateAccessTokenSession(context.Background(), deleteRequest.ID, deleteRequest))

	r := x.NewRouterAdmin()
	h.SetRoutes(r, r.RouterPublic(), func(h http.Handler) http.Handler {
		return h
	})
	ts := httptest.NewServer(r)
	defer ts.Close()

	c := hydra.NewHTTPClientWithConfig(nil, &hydra.TransportConfig{Schemes: []string{"http"}, Host: urlx.ParseOrPanic(ts.URL).Host})
	_, err := c.Admin.DeleteOAuth2Token(admin.NewDeleteOAuth2TokenParams().WithClientID("foobar"))
	require.NoError(t, err)

	ds := new(oauth2.Session)
	ctx := context.Background()
	_, err = store.GetAccessTokenSession(ctx, "del-1", ds)
	require.Error(t, err, "not_found")
}

func TestHandlerFlushHandler(t *testing.T) {

	t.Run("case=not-after", func(t *testing.T) {
		ctx := context.Background()

		// Setup database and tests
		jt := testhelpers.NewConsentJanitorTestHelper(t.Name())
		reg, err := jt.GetRegistry(ctx, t.Name())
		require.NoError(t, err)

		// Setup rest server
		h := oauth2.NewHandler(reg, jt.GetConfig())

		r := x.NewRouterAdmin()
		h.SetRoutes(r, r.RouterPublic(), func(h http.Handler) http.Handler {
			return h
		})

		ts := httptest.NewServer(r)
		defer ts.Close()
		c := hydra.NewHTTPClientWithConfig(nil, &hydra.TransportConfig{Schemes: []string{"http"}, Host: urlx.ParseOrPanic(ts.URL).Host})

		// Get the notAfter test cycles
		notAfterTests := testhelpers.NewConsentJanitorTestHelper(t.Name()).GetNotAfterTestCycles()

		for k, v := range notAfterTests {
			t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) {
				ctx := context.Background()
				jt := testhelpers.NewConsentJanitorTestHelper(t.Name())

				notAfter := time.Now().Round(time.Second).Add(-v)

				t.Run("step=setup-access-token", jt.AccessTokenNotAfterSetup(ctx, reg.ClientManager(), reg.OAuth2Storage()))
				t.Run("step=setup-refresh-token", jt.RefreshTokenNotAfterSetup(ctx, reg.ClientManager(), reg.OAuth2Storage()))

				t.Run("step=cleanup", func(t *testing.T) {
					_, err := c.Admin.FlushInactiveOAuth2Tokens(admin.NewFlushInactiveOAuth2TokensParams().WithBody(&models.FlushInactiveOAuth2TokensRequest{NotAfter: strfmt.DateTime(notAfter)}))
					require.NoError(t, err)
				})

				t.Run("step=validate-access-token", jt.AccessTokenNotAfterValidate(ctx, notAfter, reg.OAuth2Storage()))
				t.Run("step=validate-refresh-token", jt.RefreshTokenNotAfterValidate(ctx, notAfter, reg.OAuth2Storage()))
			})
		}

	})
}

func TestUserinfo(t *testing.T) {
	conf := internal.NewConfigurationWithDefaults()
	conf.MustSet(config.KeyScopeStrategy, "")
	conf.MustSet(config.KeyAuthCodeLifespan, lifespan)
	conf.MustSet(config.KeyIssuerURL, "http://hydra.localhost")
	reg := internal.NewRegistryMemory(t, conf)
	internal.MustEnsureRegistryKeys(reg, x.OpenIDConnectKeyName)

	ctrl := gomock.NewController(t)
	op := NewMockOAuth2Provider(ctrl)
	defer ctrl.Finish()
	reg.WithOAuth2Provider(op)

	h := reg.OAuth2Handler()

	router := x.NewRouterAdmin()
	h.SetRoutes(router, router.RouterPublic(), func(h http.Handler) http.Handler {
		return h
	})
	ts := httptest.NewServer(router)
	defer ts.Close()

	for k, tc := range []struct {
		setup                func(t *testing.T)
		checkForSuccess      func(t *testing.T, body []byte)
		checkForUnauthorized func(t *testing.T, body []byte, header http.Header)
		expectStatusCode     int
	}{
		{
			setup: func(t *testing.T) {
				op.EXPECT().IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).Return(fosite.AccessToken, nil, errors.New("asdf"))
			},
			expectStatusCode: http.StatusInternalServerError,
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					Return(fosite.RefreshToken, nil, nil)
			},
			checkForUnauthorized: func(t *testing.T, body []byte, headers http.Header) {
				assert.True(t, headers.Get("WWW-Authenticate") == `Bearer error="invalid_token",error_description="Only access tokens are allowed in the authorization header."`, "%s", headers)
			},
			expectStatusCode: http.StatusUnauthorized,
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					Return(fosite.AccessToken, nil, fosite.ErrRequestUnauthorized)
			},
			checkForUnauthorized: func(t *testing.T, body []byte, headers http.Header) {
				assert.True(t, headers.Get("WWW-Authenticate") == `Bearer error="request_unauthorized",error_description="The request could not be authorized. Check that you provided valid credentials in the right format."`, "%s", headers)
			},
			expectStatusCode: http.StatusUnauthorized,
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, session fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
						session = &oauth2.Session{
							DefaultSession: &openid.DefaultSession{
								Claims: &jwt.IDTokenClaims{
									Subject: "alice",
								},
								Headers: new(jwt.Headers),
								Subject: "alice",
							},
							Extra: map[string]interface{}{},
						}

						return fosite.AccessToken, &fosite.AccessRequest{
							Request: fosite.Request{
								Client: &client.Client{
									OutfacingID: "foobar",
								},
								Session: session,
							},
						}, nil
					})
			},
			expectStatusCode: http.StatusOK,
			checkForSuccess: func(t *testing.T, body []byte) {
				bodyString := string(body)
				assert.True(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
				assert.True(t, strings.Contains(bodyString, `"aud":["foobar"]`), "%s", body)
			},
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, session fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
						session = &oauth2.Session{
							DefaultSession: &openid.DefaultSession{
								Claims: &jwt.IDTokenClaims{
									Subject:  "another-alice",
									Audience: []string{"something-else"},
								},
								Headers: new(jwt.Headers),
								Subject: "alice",
							},
							Extra: map[string]interface{}{},
						}

						return fosite.AccessToken, &fosite.AccessRequest{
							Request: fosite.Request{
								Client: &client.Client{
									OutfacingID: "foobar",
								},
								Session: session,
							},
						}, nil
					})
			},
			expectStatusCode: http.StatusOK,
			checkForSuccess: func(t *testing.T, body []byte) {
				bodyString := string(body)
				assert.False(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
				assert.True(t, strings.Contains(bodyString, `"sub":"another-alice"`), "%s", body)
				assert.True(t, strings.Contains(bodyString, `"aud":["something-else","foobar"]`), "%s", body)
			},
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, session fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
						session = &oauth2.Session{
							DefaultSession: &openid.DefaultSession{
								Claims: &jwt.IDTokenClaims{
									Subject:  "alice",
									Audience: []string{"foobar"},
								},
								Headers: new(jwt.Headers),
								Subject: "alice",
							},
							Extra: map[string]interface{}{},
						}

						return fosite.AccessToken, &fosite.AccessRequest{
							Request: fosite.Request{
								Client: &client.Client{
									OutfacingID:               "foobar",
									UserinfoSignedResponseAlg: "none",
								},
								Session: session,
							},
						}, nil
					})
			},
			expectStatusCode: http.StatusOK,
			checkForSuccess: func(t *testing.T, body []byte) {
				bodyString := string(body)
				assert.True(t, strings.Contains(bodyString, `"sub":"alice"`), "%s", body)
				assert.True(t, strings.Contains(bodyString, `"aud":["foobar"]`), "%s", body)
			},
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, session fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
						session = &oauth2.Session{
							DefaultSession: &openid.DefaultSession{
								Claims: &jwt.IDTokenClaims{
									Subject: "alice",
								},
								Headers: new(jwt.Headers),
								Subject: "alice",
							},
							Extra: map[string]interface{}{},
						}

						return fosite.AccessToken, &fosite.AccessRequest{
							Request: fosite.Request{
								Client: &client.Client{
									UserinfoSignedResponseAlg: "asdfasdf",
								},
								Session: session,
							},
						}, nil
					})
			},
			expectStatusCode: http.StatusInternalServerError,
		},
		{
			setup: func(t *testing.T) {
				op.EXPECT().
					IntrospectToken(gomock.Any(), gomock.Eq("access-token"), gomock.Eq(fosite.AccessToken), gomock.Any()).
					DoAndReturn(func(_ context.Context, _ string, _ fosite.TokenType, session fosite.Session, _ ...string) (fosite.TokenType, fosite.AccessRequester, error) {
						session = &oauth2.Session{
							DefaultSession: &openid.DefaultSession{
								Claims: &jwt.IDTokenClaims{
									Subject: "alice",
								},
								Headers: new(jwt.Headers),
								Subject: "alice",
							},
							Extra: map[string]interface{}{},
						}

						return fosite.AccessToken, &fosite.AccessRequest{
							Request: fosite.Request{
								Client: &client.Client{
									OutfacingID:               "foobar-client",
									UserinfoSignedResponseAlg: "RS256",
								},
								Session: session,
							},
						}, nil
					})
			},
			expectStatusCode: http.StatusOK,
			checkForSuccess: func(t *testing.T, body []byte) {
				claims, err := jwt2.Parse(string(body), func(token *jwt2.Token) (interface{}, error) {
					keys, err := reg.KeyManager().GetKeySet(context.Background(), x.OpenIDConnectKeyName)
					require.NoError(t, err)
					t.Logf("%+v", keys)
					key, err := jwk.FindPublicKey(keys)
					return jwk.MustRSAPublic(key), nil
				})
				require.NoError(t, err)
				assert.EqualValues(t, "alice", claims.Claims["sub"])
				assert.EqualValues(t, []interface{}{"foobar-client"}, claims.Claims["aud"], "%#v", claims.Claims)
				assert.NotEmpty(t, claims.Claims["jti"])
			},
		},
	} {
		t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) {
			tc.setup(t)

			req, err := http.NewRequest("GET", ts.URL+"/userinfo", nil)
			require.NoError(t, err)
			req.Header.Set("Authorization", "Bearer access-token")
			resp, err := http.DefaultClient.Do(req)
			require.NoError(t, err)
			defer resp.Body.Close()
			require.EqualValues(t, tc.expectStatusCode, resp.StatusCode)
			body, err := ioutil.ReadAll(resp.Body)
			require.NoError(t, err)
			if tc.expectStatusCode == http.StatusOK {
				tc.checkForSuccess(t, body)
			} else if tc.expectStatusCode == http.StatusUnauthorized {
				tc.checkForUnauthorized(t, body, resp.Header)
			}
		})
	}
}

func TestHandlerWellKnown(t *testing.T) {
	conf := internal.NewConfigurationWithDefaults()
	conf.MustSet(config.KeyScopeStrategy, "DEPRECATED_HIERARCHICAL_SCOPE_STRATEGY")
	conf.MustSet(config.KeyIssuerURL, "http://hydra.localhost")
	conf.MustSet(config.KeySubjectTypesSupported, []string{"pairwise", "public"})
	conf.MustSet(config.KeyOIDCDiscoverySupportedClaims, []string{"sub"})
	conf.MustSet(config.KeyOAuth2ClientRegistrationURL, "http://client-register/registration")
	conf.MustSet(config.KeyOIDCDiscoveryUserinfoEndpoint, "/userinfo")
	reg := internal.NewRegistryMemory(t, conf)

	h := oauth2.NewHandler(reg, conf)

	r := x.NewRouterAdmin()
	h.SetRoutes(r, r.RouterPublic(), func(h http.Handler) http.Handler {
		return h
	})
	ts := httptest.NewServer(r)
	defer ts.Close()

	res, err := http.Get(ts.URL + "/.well-known/openid-configuration")
	require.NoError(t, err)
	defer res.Body.Close()

	trueConfig := oauth2.WellKnown{
		Issuer:                                 strings.TrimRight(conf.IssuerURL().String(), "/") + "/",
		AuthURL:                                conf.OAuth2AuthURL().String(),
		TokenURL:                               conf.OAuth2TokenURL().String(),
		JWKsURI:                                conf.JWKSURL().String(),
		RevocationEndpoint:                     urlx.AppendPaths(conf.IssuerURL(), oauth2.RevocationPath).String(),
		RegistrationEndpoint:                   conf.OAuth2ClientRegistrationURL().String(),
		SubjectTypes:                           []string{"pairwise", "public"},
		ResponseTypes:                          []string{"code", "code id_token", "id_token", "token id_token", "token", "token id_token code"},
		ClaimsSupported:                        conf.OIDCDiscoverySupportedClaims(),
		ScopesSupported:                        conf.OIDCDiscoverySupportedScope(),
		UserinfoEndpoint:                       conf.OIDCDiscoveryUserinfoEndpoint().String(),
		TokenEndpointAuthMethodsSupported:      []string{"client_secret_post", "client_secret_basic", "private_key_jwt", "none"},
		GrantTypesSupported:                    []string{"authorization_code", "implicit", "client_credentials", "refresh_token"},
		ResponseModesSupported:                 []string{"query", "fragment"},
		IDTokenSigningAlgValuesSupported:       []string{"RS256"},
		UserinfoSigningAlgValuesSupported:      []string{"none", "RS256"},
		RequestParameterSupported:              true,
		RequestURIParameterSupported:           true,
		RequireRequestURIRegistration:          true,
		BackChannelLogoutSupported:             true,
		BackChannelLogoutSessionSupported:      true,
		FrontChannelLogoutSupported:            true,
		FrontChannelLogoutSessionSupported:     true,
		EndSessionEndpoint:                     urlx.AppendPaths(conf.IssuerURL(), oauth2.LogoutPath).String(),
		RequestObjectSigningAlgValuesSupported: []string{"RS256", "none"},
		CodeChallengeMethodsSupported:          []string{"plain", "S256"},
	}
	var wellKnownResp oauth2.WellKnown
	err = json.NewDecoder(res.Body).Decode(&wellKnownResp)
	require.NoError(t, err, "problem decoding wellknown json response: %+v", err)
	assert.EqualValues(t, trueConfig, wellKnownResp)
}


text:
require 'require_all'
require_rel 'ruby_tdms'


text:
package net.sourceforge.mayfly.datastore.types;

import net.sourceforge.mayfly.datastore.Cell;
import net.sourceforge.mayfly.datastore.LongCell;
import net.sourceforge.mayfly.evaluation.Value;

public class IntegerDataType extends DataType {

    private final String dumpName;

    /**
     * @internal
     * For convenience within tests.
     */
    public IntegerDataType() {
        this("undumpable_type");
    }

    public IntegerDataType(String dumpName) {
        this.dumpName = dumpName;
    }

    @Override
    public Cell coerce(Value value, String columnName) {
        return genericCoerce(value, columnName, dumpName.toLowerCase(),
            LongCell.class);
    }

    @Override
    public String dumpName() {
        return dumpName;
    }

}


text:
"""
Test couchauth interfaces.
"""

import unittest
from pyramid_couchauth.interfaces import IIdentifier

class TestIIdentifier(unittest.TestCase):

    """Test the IIdentifier class."""

    def test_class(self):
        """Verify the class implements Interface."""
        self.assertTrue(hasattr(IIdentifier, 'names'),
            'class has no names attribute')
        self.assertTrue(hasattr(IIdentifier.names, '__call__'),
            'class names attribute is not callable')

    def test_names(self):
        """Verify the interface defines the correct methods."""
        names = set(['forget', 'identify', 'remember'])
        self.assertEqual(set(IIdentifier.names()), names,
            'class methods incorrect')

    def verify_method(self, method, params, kwargs):
        """Verify a method signature."""
        sig = IIdentifier.getDescriptionFor(method).getSignatureInfo()
        self.assertEqual(len(sig['positional']), params,
            'method %s contains invalid arguments' % method)
        self.assertEqual(sig['kwargs'] is not None, kwargs,
            'method %s contains invalid kwargs' % method)

    def test_identify(self):
        """Verify the method signature of identify."""
        self.verify_method('identify', 2, False)

    def test_remember(self):
        """Verify the method signature of remember."""
        self.verify_method('remember', 3, True)

    def test_forget(self):
        """Verify the method signature of forget."""
        self.verify_method('forget', 2, False)


text:
import {
	IGroup
} from "beam-interactive-node2";

import { Event } from "./common/utils/Event";

import { InteractiveWrapper } from "./InteractiveWrapper";
import { InteractiveScene } from "./InteractiveScene";
import { InteractiveUser } from "./InteractiveUser";

export class InteractiveGroup {

	public readonly wrapper: InteractiveWrapper;
	private internal?: IGroup;
	public readonly id?: string;
	public readonly temporary: boolean;
	public readonly scene: InteractiveScene;
	// protected readonly internal: ?;
	private userMap: Map<number, InteractiveUser> = new Map();

	public readonly onUserEnterEvent: Event<(user: InteractiveUser) => void> = new Event<any>();
	public readonly onUserLeaveEvent: Event<(user: InteractiveUser) => void> = new Event<any>();

	constructor(wrapper: InteractiveWrapper, scene: InteractiveScene, id?: string) {
		this.wrapper = wrapper;
		this.id = id;
		this.scene = scene;
		this.temporary = (id === undefined);
	}

	async destroy() {
		for (var [key, user] of this.userMap) {
			await user.move(this.wrapper.defaultGroup);
		}
		this.userMap.clear();
		if (this.isValid) {
			this.internal = undefined;
			(this as any).id = undefined;
			this.onUserEnterEvent.clearCallbacks();
			this.onUserLeaveEvent.clearCallbacks();
		}
	}

	get isValid() {
		return this.internal !== undefined;
	}

	getUsers() {
		return this.userMap;
	}

	getUsersCount() {
		return this.userMap.size;
	}

	addUser(user: InteractiveUser) {
		if (!this.userMap.has(user.userID)) {
			this.userMap.set(user.userID, user);
			this.onUserEnterEvent.execute(user);
		}
	}

	removeUser(user: InteractiveUser) {
		if (this.userMap.delete(user.userID)) {
			if (user.connected) {
				this.onUserLeaveEvent.execute(user);
			}
		}
	}

	async move(scene: InteractiveScene) {
		(this as any).scene = scene;
		await this.wrapper.moveGroup(this, scene);
	}

	/**********************************************************************/
	beamGroupInit(internal: IGroup) {
		this.internal = internal;
		if (this.temporary) {
			(this as any).id = this.internal.groupID;
		}
	}

	beamGroupDestroy() {
		this.internal = undefined;
	}
}


text:
@interface OptinManager : NSObject

@end


text:
multistart
==========

Command concurrently connected clients

multistart is a client-server system for concurrent command
execution across multiple clients. You start a server, then
connect one or more clients to it. After that, a connection
through `nc' (or the commander.py script) can be used to send
commands which are executed on each client, as close to
concurrently as possible.

The commander script will wait for a specified number of
clients to send a return status before issuing the next
command, so these scripts can be used to run automated tests
across many hosts.

The basic mechanism of action uses the asyncore and asynchat
Python standard library modules to define a line-oriented
protocol for sending commands and returning exit statuses.

The commands are synchronised by having the server issue the
command to each host, and timing how long it takes to complete
transmission of the command to all hosts. A start command is
then sent, with a start time some multiple of the time taken
to send commands to clients. If the client clocks are
synchronised (e.g. with NTP), this means the command will
be started at approximately the same time on each host.

This is most suited for tasks which take a long time to complete,
relative to the transmission time, though obviously it can
also be used to perform start-up and tear-down steps before
or after a test.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
K. svenska Vetensk-Akad. Handl. 40: 95 (1819)

#### Original name
Hysterium pulicare var. lenticulare Fr.

### Remarks
null


text:
<!DOCTYPE html>

    <title>MVVM</title>
    <meta charset="utf-8">
    <link href="../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../styles/kendo.common.min.css" rel="stylesheet">
    <link href="../../styles/kendo.rtl.min.css" rel="stylesheet">
    <link href="../../styles/kendo.default.min.css" rel="stylesheet">
    <link href="../../styles/kendo.dataviz.min.css" rel="stylesheet">
    <link href="../../styles/kendo.dataviz.default.min.css" rel="stylesheet">

        Back

Enter some content

            <textarea data-role="editor"
                      data-tools="['bold',
                                   'italic',
                                   'underline',
                                   'strikethrough',
                                   'justifyLeft',
                                   'justifyCenter',
                                   'justifyRight',
                                   'justifyFull']"
                      data-bind="visible: isVisible,
                                 value: html,
                                 events: { change: onChange }"
                      style="width: 480px; height: 200px;"></textarea>

Console

Configuration

                <input type="checkbox" data-bind="checked: isVisible">Visible

Information

            Kendo UI Editor supports the
            events,
            value and
            visible bindings.


text:
#ifndef CR_STATE_POINT_H
#define CR_STATE_POINT_H

#include "state/cr_statetypes.h"

#include <iprt/cdefs.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct {
	CRbitvalue enableSmooth[CR_MAX_BITARRAY];
	CRbitvalue size[CR_MAX_BITARRAY];
#ifdef CR_ARB_point_parameters
	CRbitvalue minSize[CR_MAX_BITARRAY];
	CRbitvalue maxSize[CR_MAX_BITARRAY];
	CRbitvalue fadeThresholdSize[CR_MAX_BITARRAY];
	CRbitvalue distanceAttenuation[CR_MAX_BITARRAY];
#endif
#ifdef CR_ARB_point_sprite
	CRbitvalue enableSprite[CR_MAX_BITARRAY];
	CRbitvalue coordReplacement[CR_MAX_TEXTURE_UNITS][CR_MAX_BITARRAY];
#endif
	CRbitvalue spriteCoordOrigin[CR_MAX_BITARRAY];
	CRbitvalue dirty[CR_MAX_BITARRAY];
} CRPointBits;

typedef struct {
	GLboolean	pointSmooth;
	GLfloat		pointSize;
#ifdef CR_ARB_point_parameters
	GLfloat		minSize, maxSize;
	GLfloat		fadeThresholdSize;
	GLfloat		distanceAttenuation[3];
#endif
#ifdef CR_ARB_point_sprite
	GLboolean pointSprite;
	GLboolean coordReplacement[CR_MAX_TEXTURE_UNITS];
#endif
    GLfloat spriteCoordOrigin;
    GLfloat reserved; /* added to make sure alignment of sttructures following CRPointState in CRContext does not change */
} CRPointState;

DECLEXPORT(void) crStatePointInit (CRContext *ctx);

DECLEXPORT(void) crStatePointDiff(CRPointBits *bb, CRbitvalue *bitID,
                                  CRContext *fromCtx, CRContext *toCtx);
DECLEXPORT(void) crStatePointSwitch(CRPointBits *bb, CRbitvalue *bitID,
                                    CRContext *fromCtx, CRContext *toCtx);

#ifdef __cplusplus
}
#endif

#endif /* CR_STATE_POINT_H */


text:
package org.geokey;

import org.junit.Assert;
import org.junit.Test;

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

import static org.geokey.TestData.*;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.number.IsCloseTo.*;

/**
 * Created by mriley on 8/17/16.
 */
public class KeyTest {

	@Test
	public void testGeoKeyWrite() {
		Assert.assertEquals(TEST_GEOHASH_STRING, new GeoKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).toString());
		Assert.assertEquals(TEST_GEOHASH_STRING.substring(0, 9), new GeoKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).toString(9));
		byte[] bytes = new GeoKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).toBytes();
		Assert.assertArrayEquals(Arrays.toString(bytes), TEST_GEOHASH_BYTES, bytes);
	}

	@Test(expected = RuntimeException.class)
	public void testGeoKeyWriteError() {
		new GeoKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).toString(new Appendable() {
			@Override
			public Appendable append(CharSequence csq) throws IOException {
				throw new IOException();
			}

			@Override
			public Appendable append(CharSequence csq, int start, int end) throws IOException {
				throw new IOException();
			}

			@Override
			public Appendable append(char c) throws IOException {
				throw new IOException();
			}
		});
	}

	@Test
	public void testGeoKeyRead() {
		GeoKey gk = new GeoKey(TEST_GEOHASH_STRING);
		Assert.assertEquals(TEST_LATITUDE, gk.getLatitude(), .001);
		Assert.assertEquals(TEST_LONGITUDE, gk.getLongitude(), .001);
		gk = new GeoKey(TEST_GEOHASH_BYTES);
		Assert.assertEquals(TEST_LATITUDE, gk.getLatitude(), .001);
		Assert.assertEquals(TEST_LONGITUDE, gk.getLongitude(), .001);
	}

	@Test
	public void testGeoTimeKeyWrite() {
		Assert.assertEquals(TEST_GEOTIME_STRING, new GeoTimeKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).setTime(TEST_TIME).toString());
		byte[] bytes = new GeoTimeKey().setLatitude(TEST_LATITUDE).setLongitude(TEST_LONGITUDE).setTime(TEST_TIME).toBytes();
		Assert.assertArrayEquals(Arrays.toString(bytes), TEST_GEOTIME_BYTES, bytes);
	}

	@Test
	public void testGeoTimesKeyRead() {
		GeoTimeKey gk = new GeoTimeKey(TEST_GEOTIME_STRING);
		Assert.assertEquals(TEST_LATITUDE, gk.getLatitude(), .001);
		Assert.assertEquals(TEST_LONGITUDE, gk.getLongitude(), .001);
		Assert.assertThat((double)gk.getTime(), is(closeTo(TEST_TIME, 1)));
		gk = new GeoTimeKey(TEST_GEOTIME_BYTES);
		Assert.assertEquals(TEST_LATITUDE, gk.getLatitude(), .001);
		Assert.assertEquals(TEST_LONGITUDE, gk.getLongitude(), .001);
		Assert.assertThat((double)gk.getTime(), is(closeTo(TEST_TIME, 1)));
	}
}


text:
var path = require('path');
var yargs = require('yargs').argv;
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');

yargs.env = yargs.env || {};
var baseDir = path.resolve(__dirname, 'src/main/webapp');
var outPath = path.resolve(__dirname, yargs.env.out || 'dist');
var isProdMode = yargs.p || false;
var config = {
  entry: [
    'whatwg-fetch',
    'babel-polyfill',
    path.resolve(baseDir, 'js/index.js'),
    path.resolve(baseDir, 'style/index.styl')
  ],
  output: {
    path: outPath,
    filename: 'index.js',
    publicPath: '/'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        query: {
          cacheDirectory: true,
          presets: ['react', 'es2015'],
          plugins: [
            'transform-class-properties',
            'transform-object-rest-spread',
            'transform-exponentiation-operator'
          ]
        },
        include: [path.join(__dirname, 'src')]
      },
      {
        test: /\.styl/,
        loaders: ['style-loader', 'css-loader', 'stylus-loader']
      },
      {
        test: /\.png$/,
        loaders: ['file-loader']
      }
    ]
  },
  resolve: {
    alias: {
      'src': path.resolve(__dirname, 'src/main/webapp/js') // for testing
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(baseDir, 'public/index.ejs'),
      inject: false,
      title: 'SLAB'
    }),
    new CopyWebpackPlugin(
      [
        {
          from: path.resolve(baseDir, 'public'),
          to: 'public'
        }
      ],
      {
        ignore: [
          '*.ejs'
        ]
      }
    ),
    new webpack.ProvidePlugin({
      'React': 'react'
    }),
    new webpack.NamedModulesPlugin()
  ],
  devServer: {
    contentBase: outPath,
    compress: true,
    port: 9001,
    historyApiFallback: true,
    proxy: {
      '/api': 'http://localhost:' + (yargs.env.serverPort || 8080)
    },
    hot: !isProdMode
  },
  devtool: isProdMode ? 'source-map' : 'eval-source-map'
};

if (!isProdMode) {
  config.plugins.push(new webpack.NamedModulesPlugin());
  config.plugins.push(new webpack.HotModuleReplacementPlugin());
}

module.exports = config;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Acurtis sericeus subsp. antarcticus Singer

### Remarks
null