text:
"""Invocation-side implementation of gRPC Asyncio Python."""

import asyncio
import sys
from typing import Any, Iterable, List, Optional, Sequence

import grpc
from grpc import _common
from grpc import _compression
from grpc import _grpcio_metadata
from grpc._cython import cygrpc

from . import _base_call
from . import _base_channel
from ._call import StreamStreamCall
from ._call import StreamUnaryCall
from ._call import UnaryStreamCall
from ._call import UnaryUnaryCall
from ._interceptor import ClientInterceptor
from ._interceptor import InterceptedStreamStreamCall
from ._interceptor import InterceptedStreamUnaryCall
from ._interceptor import InterceptedUnaryStreamCall
from ._interceptor import InterceptedUnaryUnaryCall
from ._interceptor import StreamStreamClientInterceptor
from ._interceptor import StreamUnaryClientInterceptor
from ._interceptor import UnaryStreamClientInterceptor
from ._interceptor import UnaryUnaryClientInterceptor
from ._metadata import Metadata
from ._typing import ChannelArgumentType
from ._typing import DeserializingFunction
from ._typing import RequestIterableType
from ._typing import SerializingFunction
from ._utils import _timeout_to_deadline

_USER_AGENT = 'grpc-python-asyncio/{}'.format(_grpcio_metadata.__version__)

if sys.version_info[1] < 7:

    def _all_tasks() -> Iterable[asyncio.Task]:
        return asyncio.Task.all_tasks()
else:

    def _all_tasks() -> Iterable[asyncio.Task]:
        return asyncio.all_tasks()

def _augment_channel_arguments(base_options: ChannelArgumentType,
                               compression: Optional[grpc.Compression]):
    compression_channel_argument = _compression.create_channel_option(
        compression)
    user_agent_channel_argument = ((
        cygrpc.ChannelArgKey.primary_user_agent_string,
        _USER_AGENT,
    ),)
    return tuple(base_options
                ) + compression_channel_argument + user_agent_channel_argument

class _BaseMultiCallable:
    """Base class of all multi callable objects.

    Handles the initialization logic and stores common attributes.
    """
    _loop: asyncio.AbstractEventLoop
    _channel: cygrpc.AioChannel
    _method: bytes
    _request_serializer: SerializingFunction
    _response_deserializer: DeserializingFunction
    _interceptors: Optional[Sequence[ClientInterceptor]]
    _loop: asyncio.AbstractEventLoop

    # pylint: disable=too-many-arguments
    def __init__(
        self,
        channel: cygrpc.AioChannel,
        method: bytes,
        request_serializer: SerializingFunction,
        response_deserializer: DeserializingFunction,
        interceptors: Optional[Sequence[ClientInterceptor]],
        loop: asyncio.AbstractEventLoop,
    ) -> None:
        self._loop = loop
        self._channel = channel
        self._method = method
        self._request_serializer = request_serializer
        self._response_deserializer = response_deserializer
        self._interceptors = interceptors

    @staticmethod
    def _init_metadata(
            metadata: Optional[Metadata] = None,
            compression: Optional[grpc.Compression] = None) -> Metadata:
        """Based on the provided values for <metadata> or <compression> initialise the final
        metadata, as it should be used for the current call.
        """
        metadata = metadata or Metadata()
        if compression:
            metadata = Metadata(
                *_compression.augment_metadata(metadata, compression))
        return metadata

class UnaryUnaryMultiCallable(_BaseMultiCallable,
                              _base_channel.UnaryUnaryMultiCallable):

    def __call__(
        self,
        request: Any,
        *,
        timeout: Optional[float] = None,
        metadata: Optional[Metadata] = None,
        credentials: Optional[grpc.CallCredentials] = None,
        wait_for_ready: Optional[bool] = None,
        compression: Optional[grpc.Compression] = None
    ) -> _base_call.UnaryUnaryCall:

        metadata = self._init_metadata(metadata, compression)
        if not self._interceptors:
            call = UnaryUnaryCall(request, _timeout_to_deadline(timeout),
                                  metadata, credentials, wait_for_ready,
                                  self._channel, self._method,
                                  self._request_serializer,
                                  self._response_deserializer, self._loop)
        else:
            call = InterceptedUnaryUnaryCall(
                self._interceptors, request, timeout, metadata, credentials,
                wait_for_ready, self._channel, self._method,
                self._request_serializer, self._response_deserializer,
                self._loop)

        return call

class UnaryStreamMultiCallable(_BaseMultiCallable,
                               _base_channel.UnaryStreamMultiCallable):

    def __call__(
        self,
        request: Any,
        *,
        timeout: Optional[float] = None,
        metadata: Optional[Metadata] = None,
        credentials: Optional[grpc.CallCredentials] = None,
        wait_for_ready: Optional[bool] = None,
        compression: Optional[grpc.Compression] = None
    ) -> _base_call.UnaryStreamCall:

        metadata = self._init_metadata(metadata, compression)
        deadline = _timeout_to_deadline(timeout)

        if not self._interceptors:
            call = UnaryStreamCall(request, deadline, metadata, credentials,
                                   wait_for_ready, self._channel, self._method,
                                   self._request_serializer,
                                   self._response_deserializer, self._loop)
        else:
            call = InterceptedUnaryStreamCall(
                self._interceptors, request, deadline, metadata, credentials,
                wait_for_ready, self._channel, self._method,
                self._request_serializer, self._response_deserializer,
                self._loop)

        return call

class StreamUnaryMultiCallable(_BaseMultiCallable,
                               _base_channel.StreamUnaryMultiCallable):

    def __call__(
        self,
        request_iterator: Optional[RequestIterableType] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Metadata] = None,
        credentials: Optional[grpc.CallCredentials] = None,
        wait_for_ready: Optional[bool] = None,
        compression: Optional[grpc.Compression] = None
    ) -> _base_call.StreamUnaryCall:

        metadata = self._init_metadata(metadata, compression)
        deadline = _timeout_to_deadline(timeout)

        if not self._interceptors:
            call = StreamUnaryCall(request_iterator, deadline, metadata,
                                   credentials, wait_for_ready, self._channel,
                                   self._method, self._request_serializer,
                                   self._response_deserializer, self._loop)
        else:
            call = InterceptedStreamUnaryCall(
                self._interceptors, request_iterator, deadline, metadata,
                credentials, wait_for_ready, self._channel, self._method,
                self._request_serializer, self._response_deserializer,
                self._loop)

        return call

class StreamStreamMultiCallable(_BaseMultiCallable,
                                _base_channel.StreamStreamMultiCallable):

    def __call__(
        self,
        request_iterator: Optional[RequestIterableType] = None,
        timeout: Optional[float] = None,
        metadata: Optional[Metadata] = None,
        credentials: Optional[grpc.CallCredentials] = None,
        wait_for_ready: Optional[bool] = None,
        compression: Optional[grpc.Compression] = None
    ) -> _base_call.StreamStreamCall:

        metadata = self._init_metadata(metadata, compression)
        deadline = _timeout_to_deadline(timeout)

        if not self._interceptors:
            call = StreamStreamCall(request_iterator, deadline, metadata,
                                    credentials, wait_for_ready, self._channel,
                                    self._method, self._request_serializer,
                                    self._response_deserializer, self._loop)
        else:
            call = InterceptedStreamStreamCall(
                self._interceptors, request_iterator, deadline, metadata,
                credentials, wait_for_ready, self._channel, self._method,
                self._request_serializer, self._response_deserializer,
                self._loop)

        return call

class Channel(_base_channel.Channel):
    _loop: asyncio.AbstractEventLoop
    _channel: cygrpc.AioChannel
    _unary_unary_interceptors: List[UnaryUnaryClientInterceptor]
    _unary_stream_interceptors: List[UnaryStreamClientInterceptor]
    _stream_unary_interceptors: List[StreamUnaryClientInterceptor]
    _stream_stream_interceptors: List[StreamStreamClientInterceptor]

    def __init__(self, target: str, options: ChannelArgumentType,
                 credentials: Optional[grpc.ChannelCredentials],
                 compression: Optional[grpc.Compression],
                 interceptors: Optional[Sequence[ClientInterceptor]]):
        """Constructor.

        Args:
          target: The target to which to connect.
          options: Configuration options for the channel.
          credentials: A cygrpc.ChannelCredentials or None.
          compression: An optional value indicating the compression method to be
            used over the lifetime of the channel.
          interceptors: An optional list of interceptors that would be used for
            intercepting any RPC executed with that channel.
        """
        self._unary_unary_interceptors = []
        self._unary_stream_interceptors = []
        self._stream_unary_interceptors = []
        self._stream_stream_interceptors = []

        if interceptors is not None:
            for interceptor in interceptors:
                if isinstance(interceptor, UnaryUnaryClientInterceptor):
                    self._unary_unary_interceptors.append(interceptor)
                elif isinstance(interceptor, UnaryStreamClientInterceptor):
                    self._unary_stream_interceptors.append(interceptor)
                elif isinstance(interceptor, StreamUnaryClientInterceptor):
                    self._stream_unary_interceptors.append(interceptor)
                elif isinstance(interceptor, StreamStreamClientInterceptor):
                    self._stream_stream_interceptors.append(interceptor)
                else:
                    raise ValueError(
                        "Interceptor {} must be ".format(interceptor) +
                        "{} or ".format(UnaryUnaryClientInterceptor.__name__) +
                        "{} or ".format(UnaryStreamClientInterceptor.__name__) +
                        "{} or ".format(StreamUnaryClientInterceptor.__name__) +
                        "{}. ".format(StreamStreamClientInterceptor.__name__))

        self._loop = cygrpc.get_working_loop()
        self._channel = cygrpc.AioChannel(
            _common.encode(target),
            _augment_channel_arguments(options, compression), credentials,
            self._loop)

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self._close(None)

    async def _close(self, grace):  # pylint: disable=too-many-branches
        if self._channel.closed():
            return

        # No new calls will be accepted by the Cython channel.
        self._channel.closing()

        # Iterate through running tasks
        tasks = _all_tasks()
        calls = []
        call_tasks = []
        for task in tasks:
            try:
                stack = task.get_stack(limit=1)
            except AttributeError as attribute_error:
                # NOTE(lidiz) tl;dr: If the Task is created with a CPython
                # object, it will trigger AttributeError.
                #
                # In the global finalizer, the event loop schedules
                # a CPython PyAsyncGenAThrow object.
                # https://github.com/python/cpython/blob/00e45877e33d32bb61aa13a2033e3bba370bda4d/Lib/asyncio/base_events.py#L484
                #
                # However, the PyAsyncGenAThrow object is written in C and
                # failed to include the normal Python frame objects. Hence,
                # this exception is a false negative, and it is safe to ignore
                # the failure. It is fixed by https://github.com/python/cpython/pull/18669,
                # but not available until 3.9 or 3.8.3. So, we have to keep it
                # for a while.
                # TODO(lidiz) drop this hack after 3.8 deprecation
                if 'frame' in str(attribute_error):
                    continue
                else:
                    raise

            # If the Task is created by a C-extension, the stack will be empty.
            if not stack:
                continue

            # Locate ones created by `aio.Call`.
            frame = stack[0]
            candidate = frame.f_locals.get('self')
            if candidate:
                if isinstance(candidate, _base_call.Call):
                    if hasattr(candidate, '_channel'):
                        # For intercepted Call object
                        if candidate._channel is not self._channel:
                            continue
                    elif hasattr(candidate, '_cython_call'):
                        # For normal Call object
                        if candidate._cython_call._channel is not self._channel:
                            continue
                    else:
                        # Unidentified Call object
                        raise cygrpc.InternalError(
                            f'Unrecognized call object: {candidate}')

                    calls.append(candidate)
                    call_tasks.append(task)

        # If needed, try to wait for them to finish.
        # Call objects are not always awaitables.
        if grace and call_tasks:
            await asyncio.wait(call_tasks, timeout=grace, loop=self._loop)

        # Time to cancel existing calls.
        for call in calls:
            call.cancel()

        # Destroy the channel
        self._channel.close()

    async def close(self, grace: Optional[float] = None):
        await self._close(grace)

    def get_state(self,
                  try_to_connect: bool = False) -> grpc.ChannelConnectivity:
        result = self._channel.check_connectivity_state(try_to_connect)
        return _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[result]

    async def wait_for_state_change(
        self,
        last_observed_state: grpc.ChannelConnectivity,
    ) -> None:
        assert await self._channel.watch_connectivity_state(
            last_observed_state.value[0], None)

    async def channel_ready(self) -> None:
        state = self.get_state(try_to_connect=True)
        while state != grpc.ChannelConnectivity.READY:
            await self.wait_for_state_change(state)
            state = self.get_state(try_to_connect=True)

    def unary_unary(
        self,
        method: str,
        request_serializer: Optional[SerializingFunction] = None,
        response_deserializer: Optional[DeserializingFunction] = None
    ) -> UnaryUnaryMultiCallable:
        return UnaryUnaryMultiCallable(self._channel, _common.encode(method),
                                       request_serializer,
                                       response_deserializer,
                                       self._unary_unary_interceptors,
                                       self._loop)

    def unary_stream(
        self,
        method: str,
        request_serializer: Optional[SerializingFunction] = None,
        response_deserializer: Optional[DeserializingFunction] = None
    ) -> UnaryStreamMultiCallable:
        return UnaryStreamMultiCallable(self._channel, _common.encode(method),
                                        request_serializer,
                                        response_deserializer,
                                        self._unary_stream_interceptors,
                                        self._loop)

    def stream_unary(
        self,
        method: str,
        request_serializer: Optional[SerializingFunction] = None,
        response_deserializer: Optional[DeserializingFunction] = None
    ) -> StreamUnaryMultiCallable:
        return StreamUnaryMultiCallable(self._channel, _common.encode(method),
                                        request_serializer,
                                        response_deserializer,
                                        self._stream_unary_interceptors,
                                        self._loop)

    def stream_stream(
        self,
        method: str,
        request_serializer: Optional[SerializingFunction] = None,
        response_deserializer: Optional[DeserializingFunction] = None
    ) -> StreamStreamMultiCallable:
        return StreamStreamMultiCallable(self._channel, _common.encode(method),
                                         request_serializer,
                                         response_deserializer,
                                         self._stream_stream_interceptors,
                                         self._loop)

def insecure_channel(
        target: str,
        options: Optional[ChannelArgumentType] = None,
        compression: Optional[grpc.Compression] = None,
        interceptors: Optional[Sequence[ClientInterceptor]] = None):
    """Creates an insecure asynchronous Channel to a server.

    Args:
      target: The server address
      options: An optional list of key-value pairs (:term:`channel_arguments`
        in gRPC Core runtime) to configure the channel.
      compression: An optional value indicating the compression method to be
        used over the lifetime of the channel. This is an EXPERIMENTAL option.
      interceptors: An optional sequence of interceptors that will be executed for
        any call executed with this channel.

    Returns:
      A Channel.
    """
    return Channel(target, () if options is None else options, None,
                   compression, interceptors)

def secure_channel(target: str,
                   credentials: grpc.ChannelCredentials,
                   options: Optional[ChannelArgumentType] = None,
                   compression: Optional[grpc.Compression] = None,
                   interceptors: Optional[Sequence[ClientInterceptor]] = None):
    """Creates a secure asynchronous Channel to a server.

    Args:
      target: The server address.
      credentials: A ChannelCredentials instance.
      options: An optional list of key-value pairs (:term:`channel_arguments`
        in gRPC Core runtime) to configure the channel.
      compression: An optional value indicating the compression method to be
        used over the lifetime of the channel. This is an EXPERIMENTAL option.
      interceptors: An optional sequence of interceptors that will be executed for
        any call executed with this channel.

    Returns:
      An aio.Channel.
    """
    return Channel(target, () if options is None else options,
                   credentials._credentials, compression, interceptors)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

001
019
020package com.garygregory.jcommander.converters.xml.datatype;
021
022import javax.xml.datatype.DatatypeConfigurationException;
023import javax.xml.datatype.DatatypeFactory;
024import javax.xml.datatype.Duration;
025
026import com.garygregory.jcommander.converters.AbstractBaseConverter;
027
028/**
029 * Converts a {@link String} into a {@link Duration}.
030 * <p>
031 * For a description of the format, see {@link DatatypeFactory#newDuration(String)}.
032 * </p>
033 *
034 * <p>
035 * Example:
036 * </p>
037 *
038 * <pre class="prettyprint">
039 * <code class="language-java">&#64;Parameter(names = { "--duration" }, converter = DurationConverter.class)
040 * private Duration duration;</code>
041 * </pre>
042 * <p>
043 *
044 * @see Duration
045 * @see DatatypeFactory#newDuration(String)
046 *
047 * @since 1.0.0
048 * @author <a href="mailto:ggregory@garygregory.com">Gary Gregory</a>
049 */
050public class DurationConverter extends AbstractBaseConverter<Duration> {
051
052    /**
053     * Constructs a converter.
054     *
055     * @param optionName
056     *            The option name, may be null.
057     */
058    public DurationConverter(final String optionName) {
059        super(optionName, Duration.class);
060    }
061
062    @Override
063    protected Duration convertImpl(final String value) throws DatatypeConfigurationException {
064        return DatatypeFactory.newInstance().newDuration(value);
065    }
066
067}

redpajama_set_name: RedPajamaGithub


text:
package com.angkorteam.fintech.pages.client.common;

import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import com.angkorteam.fintech.widget.WebMarkupContainer;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.angkorteam.fintech.Page;
import com.angkorteam.fintech.Session;
import com.angkorteam.fintech.dto.ClientEnum;
import com.angkorteam.fintech.dto.Function;
import com.angkorteam.fintech.dto.builder.loan.UndoDisburseBuilder;
import com.angkorteam.fintech.helper.ClientHelper;
import com.angkorteam.fintech.layout.Size;
import com.angkorteam.fintech.widget.TextFeedbackPanel;
import com.angkorteam.fintech.widget.WebMarkupBlock;
import com.angkorteam.framework.wicket.markup.html.form.Button;
import com.angkorteam.framework.wicket.markup.html.form.Form;
import io.github.openunirest.http.JsonNode;

@AuthorizeInstantiation(Function.ALL_FUNCTION)
public class LoanAccountUndoDisbursePage extends Page {

    protected ClientEnum client;

    protected String clientId;
    protected String groupId;
    protected String centerId;

    protected String loanId;

    protected Form<Void> form;
    protected Button saveButton;
    protected BookmarkablePageLink<Void> closeLink;

    protected WebMarkupBlock noteBlock;
    protected WebMarkupContainer noteIContainer;
    protected String noteValue;
    protected TextArea<String> noteField;
    protected TextFeedbackPanel noteFeedback;

    @Override
    protected void initComponent() {
        this.form = new Form<>("form");
        add(this.form);

        this.saveButton = new Button("saveButton");
        this.saveButton.setOnSubmit(this::saveButtonSubmit);
        this.form.add(this.saveButton);

        PageParameters parameters = new PageParameters();
        parameters.add("client", this.client.name());
        parameters.add("loanId", this.loanId);
        if (this.client == ClientEnum.Client) {
            parameters.add("clientId", this.clientId);
        } else if (this.client == ClientEnum.Center) {
            parameters.add("centerId", this.centerId);
        } else if (this.client == ClientEnum.Group) {
            parameters.add("groupId", this.groupId);
        } else {
            throw new WicketRuntimeException("Unknown " + this.client);
        }

        this.closeLink = new BookmarkablePageLink<>("closeLink", LoanAccountPreviewPage.class, parameters);
        this.form.add(this.closeLink);

        initNoteBlock();
    }

    @Override
    protected void configureMetaData() {
    }

    protected void initNoteBlock() {
        this.noteBlock = new WebMarkupBlock("noteBlock", Size.Six_6);
        this.form.add(this.noteBlock);
        this.noteIContainer = new WebMarkupContainer("noteIContainer");
        this.noteBlock.add(this.noteIContainer);
        this.noteField = new TextArea<>("noteField", new PropertyModel<>(this, "noteValue"));
        this.noteField.setLabel(Model.of("Note"));
        this.noteIContainer.add(this.noteField);
        this.noteFeedback = new TextFeedbackPanel("noteFeedback", this.noteField);
        this.noteIContainer.add(this.noteFeedback);
    }

    @Override
    protected void initData() {
        this.client = ClientEnum.valueOf(getPageParameters().get("client").toString());

        this.clientId = getPageParameters().get("clientId").toString();
        this.groupId = getPageParameters().get("groupId").toString();
        this.centerId = getPageParameters().get("centerId").toString();

        this.loanId = getPageParameters().get("loanId").toString();
    }

    protected void saveButtonSubmit(Button button) {
        UndoDisburseBuilder builder = new UndoDisburseBuilder();
        builder.withId(this.loanId);
        builder.withNote(this.noteValue);

        JsonNode node = ClientHelper.undoDisburseLoanAccount((Session) getSession(), builder.build());

        if (reportError(node)) {
            return;
        }

        PageParameters parameters = new PageParameters();
        parameters.add("client", this.client.name());
        parameters.add("loanId", this.loanId);
        if (this.client == ClientEnum.Client) {
            parameters.add("clientId", this.clientId);
        } else if (this.client == ClientEnum.Center) {
            parameters.add("centerId", this.centerId);
        } else if (this.client == ClientEnum.Group) {
            parameters.add("groupId", this.groupId);
        } else {
            throw new WicketRuntimeException("Unknown " + this.client);
        }
        setResponsePage(LoanAccountPreviewPage.class, parameters);
    }

}


text:
/*
 * I2CDevice.h
 *
 *  Created on: Feb 25, 2015
 *      Author: mailmindlin
 */

#ifndef IO_BSC_I2CDEVICE_H_
#define IO_BSC_I2CDEVICE_H_

#include "../../std/x-stdint.h"
#ifndef IO_BSC_BSC_H_
#include "BSC.h"
#endif

namespace Peripherals {
class I2CDevice {
public:
	void writeBytes(uint16_t len, uint8_t* data);
	void readBytes(uint16_t len, uint8_t* buffer);
	void xreadMem(uint8_t pos, uint16_t len, uint8_t* buffer);
	void xwriteMem(uint8_t pos, uint16_t len, uint8_t* data);
	const uint8_t getAddress() const;
	const BSC* getController() const;
	~I2CDevice();
protected:
	I2CDevice(uint8_t addr, BSC* controller);
	Peripherals::BSC* controller;
	const uint8_t addr;
};
}
#endif /* IO_BSC_I2CDEVICE_H_ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
  <testsuite name="fastlane.lanes">

      <testcase classname="fastlane.lanes" name="0: Verifying required fastlane version" time="0.000553">

      </testcase>

      <testcase classname="fastlane.lanes" name="1: scan" time="20.205407">

      </testcase>

  </testsuite>
</testsuites>


text:
'use strict';

var getExamples    = require('../lib/examples').get;
var renderExamples = require('../lib/examples').render;
var pkgMeta        = require('../lib/package-meta')('handlebars-intl');

module.exports = function (route) {
    route.name = 'handlebars';

    route.get(function (req, res, next) {
        var isProduction = req.app.get('env') === 'production';

        getExamples('handlebars', {cache: isProduction})
            .then(function (examples) {
                res.expose(examples, 'examples');
                res.expose('integration', 'pageType');

                res.render('handlebars', {
                    activeMenuItem    : route.name,
                    usesHandlebarsIntl: true,
                    package           : pkgMeta,
                    examples          : renderExamples(examples, res.intl)
                });
            }).catch(next);
    });
};


text:
namespace Incoding.Extensions
{
    #region << Using >>

    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq.Expressions;
    using System.Reflection;

    #endregion

    public static class ExpressionEqualExtensions
    {
        #region Factory constructors

        public static FieldInfo GetFieldFromMember(MemberExpression memberExpression)
        {
            Guard.NotNull("memberExpression", memberExpression);
            Guard.NotNull("memberExpression.Member", memberExpression.Member);

            return memberExpression.Member.DeclaringType.GetField(memberExpression.Member.Name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        }

        [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Positive false")]
        public static bool IsExpressionEqual(this Expression left, Expression right)
        {
            if (!left.IsReferenceEquals(right))
                return false;

            if (left.NodeType == ExpressionType.MemberAccess && right.NodeType == ExpressionType.Constant)
                return IsMemberVsConstant((MemberExpression)left, (ConstantExpression)right);

            if (left.NodeType == ExpressionType.Constant && right.NodeType == ExpressionType.MemberAccess)
                return IsMemberVsConstant((MemberExpression)right, (ConstantExpression)left);

            if (left.NodeType != right.NodeType)
                return false;

            if (left.NodeType == ExpressionType.Parameter)
                return IsParameter((ParameterExpression)left, (ParameterExpression)right);
            if (left.NodeType == ExpressionType.Invoke)
                return IsInvoke((InvocationExpression)left, (InvocationExpression)right);
            if (left.NodeType == ExpressionType.Convert)
                return IsConvert((UnaryExpression)left, (UnaryExpression)right);
            if (left.NodeType == ExpressionType.Constant)
                return IsConstant((ConstantExpression)left, (ConstantExpression)right);
            if (left.NodeType == ExpressionType.Call)
                return IsCall((MethodCallExpression)left, (MethodCallExpression)right);
            if (left.NodeType == ExpressionType.Lambda)
                return IsLambda((LambdaExpression)left, (LambdaExpression)right);
            if (left.NodeType.IsAnyEquals(ExpressionType.Equal, ExpressionType.NotEqual, ExpressionType.LessThan, ExpressionType.LessThanOrEqual, ExpressionType.GreaterThan, ExpressionType.GreaterThanOrEqual, ExpressionType.AndAlso, ExpressionType.OrElse))
                return IsEqual((BinaryExpression)left, (BinaryExpression)right);
            if (left.NodeType == ExpressionType.MemberAccess)
            {
                var leftTempMember = (MemberExpression)left;
                var rightTempMember = (MemberExpression)right;
                bool leftIsConstant = leftTempMember.Expression != null && leftTempMember.Expression.NodeType == ExpressionType.Constant;
                bool rigthIsConstant = rightTempMember.Expression != null && rightTempMember.Expression.NodeType == ExpressionType.Constant;

                if (leftIsConstant && rigthIsConstant)
                {
                    var leftTuple = new Tuple<string, ConstantExpression>(leftTempMember.Member.Name, (ConstantExpression)leftTempMember.Expression);
                    var rightTuple = new Tuple<string, ConstantExpression>(rightTempMember.Member.Name, (ConstantExpression)rightTempMember.Expression);
                    return IsConstantAsMember(leftTuple, rightTuple);
                }

                return IsMemberAccess(leftTempMember, rightTempMember);
            }

            return left.NodeType.ToString().Equals(right.NodeType.ToString());
        }

        #endregion

        static bool IsConstantAsMember(Tuple<string, ConstantExpression> leftTuple, Tuple<string, ConstantExpression> rightTuple)
        {
            var leftValue = leftTuple.Item2.Value.TryGetValue(leftTuple.Item1);
            var rightValue = rightTuple.Item2.Value.TryGetValue(rightTuple.Item1);
            return leftValue.Equals(rightValue);
        }

        static bool IsMemberVsConstant(MemberExpression left, ConstantExpression right)
        {
            if (left.Expression == null)
            {
                var fieldInfo = GetFieldFromMember(left);
                var test = fieldInfo.GetValue(null);
                return test.Equals(right.Value);
            }

            object value;
            if (left.Expression.NodeType == ExpressionType.MemberAccess)
            {
                var deepLeft = left.Expression as MemberExpression;

                if (deepLeft.Expression == null)
                {
                    var field = GetFieldFromMember(deepLeft);
                    value = field.GetValue(deepLeft);
                }
                else
                    value = deepLeft.Expression.TryGetValue("Value").TryGetValue(deepLeft.Member.Name);
            }
            else
                value = left.Expression.TryGetValue("Value");

            return value.TryGetValue(left.Member.Name).Equals(right.Value);
        }

        static bool IsParameter(ParameterExpression left, ParameterExpression right)
        {
            return left.Type == right.Type;
        }

        static bool IsInvoke(InvocationExpression left, InvocationExpression right)
        {
            if (left.Arguments.Count != right.Arguments.Count)
                return false;

            for (int i = 0; i < left.Arguments.Count; i++)
            {
                var leftArgument = left.Arguments[i];
                var rightArgument = right.Arguments[i];
                if (!leftArgument.IsExpressionEqual(rightArgument))
                    return false;
            }

            return true;
        }

        static bool IsConvert(UnaryExpression left, UnaryExpression right)
        {
            if (left.Method != null && right.Method != null)
            {
                if (!left.Method.Name.Equals(right.Method.Name))
                    return false;
            }

            return left.Operand.IsExpressionEqual(right.Operand);
        }

        static bool IsConstant(ConstantExpression left, ConstantExpression right)
        {
            return left.Value.Equals(right.Value);
        }

        static bool IsCall(MethodCallExpression left, MethodCallExpression right)
        {
            if (left.Object != null || right.Object != null)
            {
                if (!left.Object.IsExpressionEqual(right.Object))
                    return false;
            }

            return left.Method.Name.Equals(right.Method.Name);
        }

        static bool IsLambda(LambdaExpression left, LambdaExpression right)
        {
            return IsExpressionEqual(left.Body, right.Body);
        }

        static bool IsEqual(BinaryExpression left, BinaryExpression right)
        {
            if (!left.Method.IsReferenceEquals(right.Method))
                return false;

            if (left.Method != null && right.Method != null)
            {
                if (!left.Method.Name.Equals(right.Method.Name))
                    return false;
            }

            return left.Left.IsExpressionEqual(right.Left) && left.Right.IsExpressionEqual(right.Right);
        }

        static bool IsMemberAccess(MemberExpression left, MemberExpression right)
        {
            if (left.Expression != null && right.Expression != null)
            {
                if (!left.Expression.IsExpressionEqual(right.Expression))
                    return false;
            }

            return left.Member.Equals(right.Member);
        }
    }
}


text:
'use strict';

var fetchFeed = require('../fetch-feed');
var filterFeed = require('../filter-feed');
var url = require('url');

function transformMeta(root) {
  root.transformContent('title', { to: 'Ray Wenderlich (filtered)' });
}

function transformTitle(entry) {
  function replace(match) {
    return match.replace(' [FREE]', '');
  }
  entry.transformContent('title', { to: replace });
}

module.exports = function(config, request, response) {
  config.originalURL = 'https://www.raywenderlich.com/feed?max-results=1';
  config.url = url.format({
    protocol: 'http', host: request.headers.host, pathname: config.name
  });

  fetchFeed({
    url: config.originalURL,
    onResponse: function(resFetch, data) {
      response.setHeader('Content-Type', resFetch.headers['content-type']);

      filterFeed({
        config: config,
        data: data,
        findId: function(entry) { return entry.find('id'); },
        guardReposts: false,
        transformEntry: transformTitle,
        transformMeta: transformMeta,
        verbose: true,
        onDone: function(data) {
          response.end(data);
        }
      });
    },
    onError: function(e) {
      response.end(e.message);
    }
  });
};


text:
/**
 *
 */
package org.geneontology.minerva.validation;

import java.util.HashSet;
import java.util.Set;

/**
 * @author bgood
 *
 */
public class ShexViolation extends Violation {

    Set<ShexExplanation> explanations;

    /**
     *
     */
    public ShexViolation(String node) {
        super(node);
        explanations = new HashSet<ShexExplanation>();
    }

    public Set<ShexExplanation> getExplanations() {
        return explanations;
    }

    public void setExplanations(Set<ShexExplanation> explanations) {
        this.explanations = explanations;
    }

    public void addExplanation(ShexExplanation explanation) {
        this.explanations.add(explanation);
    }

}


text:
Package grace provides a graceful net listener and a http server base on the net listener.

## Platform

| OS | Status |
|----------|----------|
| ubuntu 14.04 | worked well |
| windows 7 | test pass(but not graceful) |

## Install

go get -v gopkg.in/orivil/grace.v1

## Example Graceful Tcp Server

```GO
package main

import (
    "gopkg.in/orivil/grace.v1"
    "net"
    "log"
    "fmt"
)

func main() {

    // ListenSignal listens system signals and watches the executable file events.
    // it will automatically restart the server when it got signal or file event.
    //
    // listen signal is an custom option, some times if we need to restart or stop
    // server manually, we can directly use the method Restart() or Stop().
    grace.ListenSignal()

    err := grace.ListenNetAndServe("tcp", ":8081", func(c net.Conn) {

        for {

            data := make([]byte, 1024)
            n, err := c.Read(data)
            if err != nil {
                log.Println(err)
                return
            }
            fmt.Println(string(data[0:n]))
        }
    })

    log.Fatal(err)
}
```

## Example Graceful Http Server

```GO
package main

import (
	"io"
	"log"
	"gopkg.in/orivil/grace.v1"
	"net/http"
)

func main() {

    grace.ListenSignal()

	http.HandleFunc("/", func (w http.ResponseWriter, req *http.Request) {

        io.WriteString(w, "hello, world!\n")
    })

	err := grace.ListenAndServe(":12345", nil)
	if err != nil {
		log.Fatal(err)
	}
}
```

## Graceful Restart With Command

> restart: `kill -HUP $pid`
>
> stop: `kill $pid`

## Automatic Graceful Restart

e.g.:

> open 1st terminal and build project: `go build server.go`
>
> open 2nd terminal and run server: `./server`
>
> open 1st terminal and rebuild build project: `go build server.go`

How does it work?

> the program will detected the executable file event, if the file was updated,
then will start a new child process with the new executable file, and after that
the parent process will wait to exit until all opened connects closed.

## Contributors

https://github.com/orivil/grace/graphs/contributors

## License

Released under the [MIT License](https://github.com/orivil/grace/blob/master/LICENSE).


text:
```
What is e^(1.000000001)?
```

PlaidCTF has a series about `X is hard`, where `X` is a math operator.

So, like the past years, we should find some `bug` in operator that made the result `wrong`. And this year's `bug` is [logarithms bug](http://www.datamath.org/Story/LogarithmBug.htm).

### zipper - Misc (50 pts)

Given a zip file, try to unzip it, but failed.

Open it as hexdump, we can see that the filename is blank, and the bytes that defined the length of filename seem strange.

After using this [link](https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip.html) to know about PKzip file structure and re-checking the hexdump, quickly, we see that the filename will have a length of 8.

Then change the byte that define the filename len to "0800", and change the filename to any string with length of 8 (i choose `flag.txt`)

Extract the new zip file and capture the flag.

One-line solution:

```python
open("flag.zip", "w").write(open("zipper.zip").read().replace(")#", "\x08\x00").replace("\x00"*8+"\x55\x54", "flag.txtUT"))
```

### Down the Reversing - Hole Misc (50 pts)

```
$ file reversing-hole_c344571f488311a2553d2cbac6fa0d35.exe
reversing-hole_c344571f488311a2553d2cbac6fa0d35.exe: MS-DOS executable, MZ for MS-DOS
```

Just run it on dosbox give us flag:

![](https://raw.githubusercontent.com/quandqn/quandqn.github.io/master/images/2017/plaidctf/screen-shot-2017-04-24-at-2.16.31-AM.png)

### Multicast - Crypto (175 pts)

`e = 5`, so small, maybe we can solve this task by using Hastad broadcast attack.

Check out this [link](https://www.wikiwand.com/en/Coppersmith%27s_attack#/Generalizations) for more information about Hastad broadcast attack.

Solution [here](https://gist.github.com/quandqn/17ccdfde1dbfdcfe935600789121efc1):

```python
f = open('data.txt').read().strip()

f = f.split('\n')
f = map(int, f)
ai = f[0::4]
bi = f[1::4]
ci = f[2::4]
ni = f[3::4]

def mul(ni):
	res = 1
	for n in ni:
		res *= n
	return res

N = mul(ni)

Ti = [[1,0,0,0,0],
	[0,1,0,0,0],
	[0,0,1,0,0],
	[0,0,0,1,0],
	[0,0,0,0,1]]

P.<x> = PolynomialRing(Zmod(N))

# Find coefficient

T = []
for t in Ti:
	tmp = crt(t,ni)
	T.append(tmp)

f = 0
for i in range(len(ai)):
	f += (i+1)*T[i]*( (ai[i]*x + bi[i])^5 - ci[i])

f = f.monic()
X = var('X')

# The flag is less than 512 bits
flag = f.small_roots(X=2^512, beta=0.5)

print flag
```


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

[assembly: AssemblyTitle("ExtraStandard.Validation.Extra11")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyProduct("Validierungsfunktionen für eXTra 1.1")]

[assembly: ComVisible(false)]
[assembly: Guid("41021e4a-eb30-46ca-9a97-b847e0a22c41")]


text:
namespace RazorJam.Insightly.Models
{
   using Newtonsoft.Json;

   [JsonObject(MemberSerialization.OptIn)]
   public class FileAttachment : IInsightlyObject
   {
      [JsonProperty(PropertyName = "FILE_ID", NullValueHandling = NullValueHandling.Ignore)]
      public int FileId { get; set; }

      [JsonProperty(PropertyName = "FILE_NAME", NullValueHandling = NullValueHandling.Ignore)]
      public string FileName { get; set; }

      [JsonProperty(PropertyName = "CONTENT_TYPE", NullValueHandling = NullValueHandling.Ignore)]
      public string ContentType { get; set; }

      [JsonProperty(PropertyName = "FILE_SIZE", NullValueHandling = NullValueHandling.Ignore)]
      public int FileSize { get; set; }

      [JsonProperty(PropertyName = "FILE_CATEGORY_ID", NullValueHandling = NullValueHandling.Ignore)]
      public int FileCategoryId { get; set; }

      [JsonProperty(PropertyName = "OWNER_USER_ID", NullValueHandling = NullValueHandling.Ignore)]
      public int OwnerUserId { get; set; }

      [JsonProperty(PropertyName = "DATE_CREATED_UTC", NullValueHandling = NullValueHandling.Ignore)]
      public string DateCreatedUtc { get; set; }

      [JsonProperty(PropertyName = "DATE_UPDATED_UTC", NullValueHandling = NullValueHandling.Ignore)]
      public string DateUpdatedUtc { get; set; }

      [JsonProperty(PropertyName = "URL", NullValueHandling = NullValueHandling.Ignore)]
      public string Url { get; set; }
   }
}


text:
package io.github.fbiville.trainings.neo4j._1_core_api;

import io.github.fbiville.trainings.neo4j.internal.GraphTests;
import io.github.fbiville.trainings.neo4j.internal.MonkeyIslandGraph;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;

import java.util.Iterator;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.assertj.core.api.Assertions.fail;

/**
 * This class focuses on the basic read operations.
 */
public class _3_GraphReadTest extends GraphTests {

    /*
     * This method is executed before each test, on an empty graph database
     * This is going to be the same graph for every following test.
     *
     * Take some time to understand what is being inserted!
     */
    @Before
    public void prepare() {
        MonkeyIslandGraph.create(graphDb);
    }

    @Test
    public void should_find_all_character_nodes() {
        try (Transaction ignored = graphDb.beginTx()) {
            Iterator<Node> allNodes = null; /*TODO: find all nodes*/
            fail("You should find all nodes");

            assertThat(allNodes)
                .hasSize(4)
                .extracting(node -> (String) node.getProperty("name"))
                .containsOnly("Guybrush Threepwood", "Elaine Marley", "LeChuck", "Largo LaGrande");
        }
    }

    @Test
    public void should_find_all_heroes() {
        try (Transaction ignored = graphDb.beginTx()) {
            Iterator<Node> allNodes = null/*TODO: find all heroes*/;
            fail("You should find all heroes");

            assertThat(allNodes)
                .hasSize(2)
                .extracting(node -> (String) node.getProperty("name"))
                .containsOnly("Guybrush Threepwood", "Elaine Marley");
        }
    }

    @Test
    public void should_find_all_villains() {
        try (Transaction ignored = graphDb.beginTx()) {
            Iterator<Node> allNodes = null/*TODO: find all villains*/;
            fail("You should find all villains");

            assertThat(allNodes)
                .hasSize(2)
                .extracting(node -> (String) node.getProperty("name"))
                .containsOnly("LeChuck", "Largo LaGrande");
        }
    }

    @Test
    public void should_find_all_relationship_types() {
        try (Transaction ignored = graphDb.beginTx()) {
            Iterable<RelationshipType> allRelationships = null/*TODO: find all relationships*/;
            fail("You should find all relationships");

            assertThat(allRelationships)
                .hasSize(4)
                .extracting(RelationshipType::name)
                .containsOnly("LOVES", "FIGHTS", "HATES", "APPEARS_IN");
        }
    }

    @Test
    public void should_find_largo_by_label_and_property() {
        try (Transaction ignored = graphDb.beginTx()) {
            Node largo = null/*TODO: find Largo LaGrande node*/;
            fail("You should find a Largo LaGrande node");

            assertThat(largo.getLabels())
                .extracting(Label::name)
                .containsOnly("Character", "Villain");
            assertThat(largo.getAllProperties()).containsOnly(
                entry("name", "Largo LaGrande"),
                entry("in_first_opus", false)
            );
            assertThat(largo.getRelationships())
                .extracting(Relationship::getType)
                .extracting(RelationshipType::name)
                .containsOnly("FIGHTS", "HATES", "APPEARS_IN");
        }
    }

    @Test
    public void should_find_characters_appearing_in_first_opus() {
        try (Transaction ignored = graphDb.beginTx()) {
            Iterator<Node> firstOpusCharacters = null/*TODO: find all first opus character nodes*/;
            fail("You should find all character nodes appearing in the first opus");

            assertThat(firstOpusCharacters)
                .extracting(node -> (String) node.getProperty("name"))
                .containsOnly("Guybrush Threepwood", "Elaine Marley", "LeChuck");
        }
    }
}


text:
describe('M.I18NItem', function () {

    it('M.I18NItem', function () {

        // Basic
        assert.isDefined(M.I18NItem);
        assert.isDefined(M.I18NItem._type);

        assert.isObject(M.I18NItem);
        assert.isString(M.I18NItem._type);
        assert.equal(M.I18NItem._type, 'M.I18NItem');

        // METHODS
        assert.isDefined(M.I18NItem.create);

        assert.isFunction(M.I18NItem.create);

        // PROPERTIES
        assert.isDefined(M.I18NItem.key);
        assert.isDefined(M.I18NItem.placeholder);

        assert.isNull(M.I18NItem.key);
        assert.isNull(M.I18NItem.placeholder);

        // CALLS
        var testItem1 = M.I18NItem.create('test.key');
        assert.equal(testItem1.key, 'test.key');
        assert.isNull(testItem1.placeholder);

        var testItem2 = M.I18NItem.create('test.key {{name}}', {name: 'Tom'});
        assert.equal(testItem2.key, 'test.key {{name}}');
        assert.isObject(testItem2.placeholder);
        assert.equal(testItem2.placeholder.name, 'Tom');

        var testItem3 = M.I18NItem.create();
        assert.isNull(testItem3);
    });

});


text:
package org.gearvrf.controls.menu.rotation;

import org.gearvrf.GVRAndroidResource;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.animation.GVRAnimation;
import org.gearvrf.animation.GVROnFinish;
import org.gearvrf.animation.GVRRotationByAxisAnimation;
import org.gearvrf.controls.MainScript;
import org.gearvrf.controls.R;
import org.gearvrf.controls.anim.StarPreviewInfo;

public class RotationGroup extends GVRSceneObject {
    private static final float SCALE_FACTOR = 0.7f;
    GVRSceneObject star;
    GVRSceneObject base;
    private GVRSceneObject place;

    public RotationGroup(GVRContext gvrContext) {
        super(gvrContext);

        place = new GVRSceneObject(gvrContext);

        addChildObject(place);
        createStar();
        createBase();
        place.getTransform().setScale(SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR);
        place.addChildObject(star);
        place.addChildObject(base);

        StarPreviewInfo.putStarReference(place);
    }

    private void createBase() {

        GVRAndroidResource baseTextRes = new GVRAndroidResource(getGVRContext(),
                R.drawable.direction_rotation);

        base = new GVRSceneObject(getGVRContext(), 1, 1, getGVRContext().loadTexture(baseTextRes));

        base.getTransform().rotateByAxis(90, 0, 0, 1);
        base.getTransform().rotateByAxis(-90, 1, 0, 0);
    }

    private void createStar() {

        GVRAndroidResource starMeshRes = new GVRAndroidResource(getGVRContext(), R.raw.star);
        GVRAndroidResource starTextRes = new GVRAndroidResource(getGVRContext(),
                R.drawable.star_diffuse);

        star = new GVRSceneObject(getGVRContext(), starMeshRes, starTextRes);
        star.getTransform().setPositionY(0.5f);
    }

    public void rotate(final float angleFactor) {

        GVRRotationByAxisAnimation rotationAnimation = new GVRRotationByAxisAnimation(place, 0.1f, angleFactor, 0, 1, 0);

        rotationAnimation.setOnFinish(new GVROnFinish() {

            @Override
            public void finished(GVRAnimation arg0) {

                MainScript.enableAnimationStar();

                if(angleFactor > 0){

                    StarPreviewInfo.changeRotationFactor(StarPreviewInfo.Direction.left);
                } else {

                    StarPreviewInfo.changeRotationFactor(StarPreviewInfo.Direction.right);
                }
            }
        });

        rotationAnimation.start(getGVRContext().getAnimationEngine());
    }
}


text:
package org.apache.tiles.mvel;

import java.util.Arrays;
import static org.easymock.EasyMock.*;
import static org.easymock.classextension.EasyMock.*;
import static org.junit.Assert.*;

import org.apache.tiles.context.TilesRequestContextHolder;
import org.apache.tiles.request.ApplicationContext;
import org.apache.tiles.request.Request;
import org.junit.Before;
import org.junit.Test;
import org.mvel2.UnresolveablePropertyException;
import org.mvel2.integration.VariableResolver;
import org.mvel2.integration.VariableResolverFactory;

/**
 * Tests {@link ReadOnlyVariableResolverFactory}.
 *
 * @version $Rev$ $Date$
 */
public class ReadOnlyVariableResolverFactoryTest {

    /**
     * The Tiles request.
     */
    private Request request;

    /**
     * The Tiles application context.
     */
    private ApplicationContext applicationContext;

    /**
     * The object to test.
     */
    private ReadOnlyVariableResolverFactory factory;

    /**
     * Sets up the object.
     */
    @Before
    public void setUp() {
        request = createMock(Request.class);
        expect(request.getAvailableScopes()).andReturn(
                Arrays.asList(new String[]{"request", "session", "application"})).anyTimes();
        TilesRequestContextHolder holder = new TilesRequestContextHolder();
        holder.setTilesRequestContext(request);
        applicationContext = createMock(ApplicationContext.class);
        factory = createMockBuilder(ReadOnlyVariableResolverFactory.class).withConstructor(holder).createMock();
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#createVariable(String, Object)}.
     */
    @Test(expected = UnsupportedOperationException.class)
    public void testCreateVariableStringObject() {
        replay(factory, request, applicationContext);
        try {
            factory.createVariable("myName", "myValue");
        } finally {
            verify(factory, request, applicationContext);
        }
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#createVariable(String, Object)}.
     */
    @Test
    public void testCreateVariableStringObjectNextFactory() {
        VariableResolverFactory nextFactory = createMock(VariableResolverFactory.class);
        VariableResolver resolver = createMock(VariableResolver.class);

        expect(nextFactory.createVariable("myName", "myValue")).andReturn(resolver);

        replay(factory, request, applicationContext, nextFactory, resolver);
        factory.setNextFactory(nextFactory);
        assertEquals(resolver, factory.createVariable("myName", "myValue"));
        verify(factory, request, applicationContext, nextFactory, resolver);
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#createVariable(String, Object, Class)}.
     */
    @Test(expected = UnsupportedOperationException.class)
    public void testCreateVariableStringObjectClassOfQ() {
        replay(factory, request, applicationContext);
        try {
            factory.createVariable("myName", "myValue", String.class);
        } finally {
            verify(factory, request, applicationContext);
        }
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#createVariable(String, Object, Class)}.
     */
    @Test
    public void testCreateVariableStringObjectClassNextFactory() {
        VariableResolverFactory nextFactory = createMock(VariableResolverFactory.class);
        VariableResolver resolver = createMock(VariableResolver.class);

        expect(nextFactory.createVariable("myName", "myValue", String.class)).andReturn(resolver);

        replay(factory, request, applicationContext, nextFactory, resolver);
        factory.setNextFactory(nextFactory);
        assertEquals(resolver, factory.createVariable("myName", "myValue", String.class));
        verify(factory, request, applicationContext, nextFactory, resolver);
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#isResolveable(String)}.
     */
    @Test
    public void testIsResolveable() {
        expect(factory.isTarget("whatever")).andReturn(true);

        replay(factory, request, applicationContext);
        assertTrue(factory.isResolveable("whatever"));
        verify(factory, request, applicationContext);
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#getVariableResolver(String)}.
     */
    @Test
    public void testGetVariableResolver() {
        VariableResolverFactory nextFactory = createMock(VariableResolverFactory.class);
        VariableResolver nextResolver = createMock(VariableResolver.class);
        VariableResolver requestResolver = createMock(VariableResolver.class);
        VariableResolver applicationResolver = createMock(VariableResolver.class);
        expect(nextFactory.getVariableResolver("other")).andReturn(nextResolver);
        expect(nextFactory.isResolveable("other")).andReturn(true);
        expect(factory.isTarget("requestScope")).andReturn(true).anyTimes();
        expect(factory.isTarget("applicationScope")).andReturn(true).anyTimes();
        expect(factory.isTarget("other")).andReturn(false).anyTimes();
        expect(factory.createVariableResolver("requestScope")).andReturn(requestResolver);
        expect(factory.createVariableResolver("applicationScope")).andReturn(applicationResolver);

        replay(factory, request, applicationContext, nextFactory, nextResolver, requestResolver, applicationResolver);
        factory.setNextFactory(nextFactory);
        VariableResolver resolver = factory.getVariableResolver("requestScope");
        assertEquals(requestResolver, resolver);
        resolver = factory.getVariableResolver("requestScope"); // again to test caching
        assertEquals(requestResolver, resolver);
        resolver = factory.getVariableResolver("applicationScope");
        assertEquals(applicationResolver, resolver);
        resolver = factory.getVariableResolver("other");
        assertEquals(nextResolver, resolver);
        verify(factory, request, applicationContext, nextFactory, nextResolver, requestResolver, applicationResolver);
    }

    /**
     * Test method for {@link ScopeVariableResolverFactory#getVariableResolver(String)}.
     */
    @Test(expected = UnresolveablePropertyException.class)
    public void testGetVariableResolverNotResolvable() {
        VariableResolverFactory nextFactory = createMock(VariableResolverFactory.class);

        expect(factory.isTarget("other")).andReturn(false).anyTimes();
        expect(nextFactory.isResolveable("other")).andReturn(false);

        replay(factory, request, applicationContext, nextFactory);
        try {
            factory.setNextFactory(nextFactory);
            factory.getVariableResolver("other");
        } finally {
            verify(factory, request, applicationContext, nextFactory);
        }
    }
}


text:
module AlpacaBuildTool
  ##
  # VisualStudioProject provides project representation and methods
  # to modify it's AssemblyVersion.cs file
  class Project
    attr_accessor :name, :file, :dir

    ##
    # Creates instance of class
    #
    # +line+:: line from .sln file with project information
    # +dir+:: solution directory
    #
    #   s = AlpacaBuildTool::VisualStudioProject.new(
    #     'Project("{FAE04EC0...5254043711}"'
    #     'd:\')
    #     # => #<**:VisualStudioProject:** @file="d:/sln1/some.csproj" **>
    def initialize(line, dir)
      items = line.gsub(/".*?"/).to_a
      _, @name, file, _ = items.map { |item| item.to_s.gsub('"', '') }
      dir = File.expand_path(dir)
      @dir = File.dirname(File.join(dir, file))
      @file = File.join(dir, file)
    end

    ##
    # Overrides *to_s* method to provide nice convertion to string
    def to_s
      "{#{@name};#{@file}}"
    end

    ##
    # Updates AssemblyInfo.cs file under the project with new_version
    #
    # +new_version+:: version that need to be used as assembly version
    # and assembly file version
    def update_version(new_version)
      info_file = File.join(@dir, 'Properties', 'AssemblyInfo.cs')
      content = IO.readlines(info_file)
      open(info_file, 'w') do |io|
        content.each { |line| io.write replace_version(line, new_version) }
      end
    end

    private

    def replace_version(line, new_version)
      line = line.gsub(/AssemblyVersion\("(.*?)"\)/,
                       "AssemblyVersion(\"#{new_version}\")")
      line.gsub(/AssemblyFileVersion\("(.*?)"\)/,
                "AssemblyFileVersion(\"#{new_version}\")")
    end
  end
end


text:
<!DOCTYPE html>

<TITLE>Manpage of fsdaemon_selinux</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

fsdaemon_selinux

Section: fsdaemon SELinux Policy documentation (8)
Updated: fsdaemon
Index
Return to Main Contents

NAME

fsdaemon_selinux - Security Enhanced Linux Policy for the fsdaemon processes

DESCRIPTION

FILE CONTEXTS

SELinux requires files to have an extended attribute to define the file type.

You can see the context of a file using the -Z option to lsP
Policy governs the access confined processes have to these files.
SELinux fsdaemon policy is very flexible allowing users to setup their fsdaemon processes in as secure a method as possible.

The following file types are defined for fsdaemon:

fsdaemon_exec_t

- Set files with the fsdaemon_exec_t type, if you want to transition an executable to the fsdaemon_t domain.

fsdaemon_initrc_exec_t

- Set files with the fsdaemon_initrc_exec_t type, if you want to transition an executable to the fsdaemon_initrc_t domain.

fsdaemon_tmp_t

- Set files with the fsdaemon_tmp_t type, if you want to store fsdaemon temporary files in the /tmp directories.

fsdaemon_var_run_t

- Set files with the fsdaemon_var_run_t type, if you want to store the fsdaemon files under the /run directory.

Note: File context can be temporarily modified with the chcon command.  If you want to permanently change the file context you need to use the
semanage fcontext

command.  This will modify the SELinux labeling database.  You will need to use
restorecon

to apply the labels.

PROCESS TYPES

SELinux defines process types (domains) for each process running on the system

You can see the context of a process using the -Z option to psP
Policy governs the access confined processes have to files.
SELinux fsdaemon policy is very flexible allowing users to setup their fsdaemon processes in as secure a method as possible.

The following process types are defined for fsdaemon:

fsdaemon_t

Note:
semanage permissive -a PROCESS_TYPE

can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated.

COMMANDS

semanage fcontext

can also be used to manipulate default file context mappings.

semanage permissive

can also be used to manipulate whether or not a process type is permissive.

semanage module

can also be used to enable/disable/install/remove policy modules.

system-config-selinux

is a GUI tool available to customize SELinux policy settings.

AUTHOR<TT>  </TT>

This manual page was autogenerated by genman.py.

SEE ALSO

selinux(8), fsdaemon(8), semanage(8), restorecon(8), chcon(1)

Index

NAME

DESCRIPTION

FILE CONTEXTS

PROCESS TYPES

COMMANDS

AUTHOR<TT>  </TT>

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:26 GMT, December 24, 2015


text:
{-# LANGUAGE UnicodeSyntax #-}

{-|
Module      : LinearRegression
Description : Gradient Descent
Copyright   : (c) Fabrício Olivetti, 2017
License     : GPL-3
Maintainer  : fabricio.olivetti@gmail.com

Applies gradient descent to a linear regression problem.
-}

module LogisticRegression where

import Control.Parallel.Strategies
import Data.List (foldl')
import Data.List.Split (chunksOf)

import Vector

-- |'parseFile' parses a space separated file
-- to a list of lists of Double
parseFile :: String -> ([[Double]], [Double])
parseFile file = ((map fst dataset), (map snd dataset))
  where
    dataset = map parseLine (lines file)
    parseLine l = splitN (doubled l)
    splitN  l = (1 : (init l), last l) -- add bias +1
    doubled l  = map toDouble (words l)
    toDouble  w = read w :: Double

gradDesc :: [[Double]] -> [Double] -> Double -> Int -> [Double]
gradDesc x y α it = gradDesc' x y w0 α it
  where
    w0 = take (length' $ head x) [0.01,0.01..]

gradDesc' :: [[Double]] -> [Double] -> [Double] -> Double -> Int -> [Double]
gradDesc' x y w α it
  | convergiu = w
  | otherwise = gradDesc' x y w' α (it-1)
  where
    w'        = w .+. (α *. nabla)
    nabla     = mediaVetor $ map (\(yi, xi) -> yi *. xi) $ zip (y .-. y') x
    y'        = map (\xi -> sigmoid $ dotprod w xi) x
    convergiu = (erro' < 1e-6) || (it==0)
    erro'     = erro x y w

sigmoid z = 1.0 / (1.0 + exp (-z))

erro x y w = mean $ (y .-. y') .^ 2
  where
    y' = map (dotprod w) x

accuracy :: [[Double]] -> [Double] -> [Double] -> Double
accuracy x y w = (length' correct) / (length' x)
  where
    correct  = filter (uncurry (==)) $ zip y yhat
    yhat     = map fhat x
    fhat xi  = round' $ sigmoid $ sum $ w .*. xi

    round' x = fromIntegral $ round $ x

mean :: [Double] -> Double
mean l = (sum l) / (length' l)


text:
"""
Trains a simple deep NN on the MNIST dataset.

Allows to use multiple models (basic fully conncted layers, convolution layers).

Based on some basic example from Keras. Forked from:
https://github.com/fchollet/keras/tree/master/examples

This is a basic example how to wrap the code as Sacred Experiment
(https://github.com/IDSIA/sacred).

How to use:

# help
$ python mnist.py --help

# normal run
$ python mnist.py

# print the configuration values
$ python mnist.py print_config

# change some parameters
$ python mnist.py with nb_epoch=10 model_fc.nb_layers=4 model_fc.dropout=0.5

# change the architecture
$ python mnist.py with model_arch='conv' model_conv.nb_filters=30
"""

from keras.datasets import mnist
from keras.layers.core import Activation, Dense, Dropout, Flatten, Reshape
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.models import Sequential
from keras.utils import np_utils
from sacred import Experiment, Ingredient
from sacred.utils import apply_backspaces_and_linefeeds
from tempfile import NamedTemporaryFile

from sanctuary.keras.callbacks import TrainingHistoryToSacredInfo

dataset_ingredient = Ingredient('dataset')
net_fc_ingredient = Ingredient('model_fc')
net_conv_ingredient = Ingredient('model_conv')

ex = Experiment('mnist', ingredients=[
    dataset_ingredient,
    net_fc_ingredient,
    net_conv_ingredient
])
# ignore the intermediate progressbar characters
ex.captured_out_filter = apply_backspaces_and_linefeeds

@dataset_ingredient.capture
def load_data(nb_classes=10):
    # the data, shuffled and split between train and test sets
    (X_train, y_train), (X_test, y_test) = mnist.load_data()

    def prepare_X(X):
        return X.astype('float32') / 255

    X_train, X_test = [prepare_X(X) for X in (X_train, X_test)]
    print(X_train.shape[0], 'train samples')
    print(X_test.shape[0], 'test samples')

    # convert class vectors to binary class matrices
    Y_train = np_utils.to_categorical(y_train, nb_classes)
    Y_test = np_utils.to_categorical(y_test, nb_classes)

    return X_train, Y_train, X_test, Y_test

@net_fc_ingredient.config
def net_fc_ingredient_config():
    input_shape=(28, 28)
    nb_classes=10
    nb_layers=3
    layer_width=512
    dropout=0.2
    activation='relu'

@net_fc_ingredient.capture
def create_fc_model(input_shape, nb_classes, nb_layers, layer_width, dropout, activation):
    model = Sequential()
    model.add(Reshape((input_shape[0] * input_shape[1],), input_shape=input_shape))
    for i in range(nb_layers - 1):
        model.add(Dense(layer_width))
        model.add(Activation(activation))
        if dropout > 0:
            model.add(Dropout(dropout))
    model.add(Dense(nb_classes))
    model.add(Activation('softmax'))

    model.summary()

    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    return model

@net_conv_ingredient.config
def net_conv_ingredient_config():
    input_shape=(28, 28)
    nb_classes=10
    nb_conv_blocks=1
    dropout=0.2
    activation='relu'
    # number of convolutional filters to use
    nb_filters = 32
    # size of pooling area for max pooling
    pool_size = (2, 2)
    # convolution kernel size
    kernel_size = (3, 3)
    fc_layer_width = 128

@net_conv_ingredient.capture
def create_conv_model(input_shape, nb_classes, nb_conv_blocks,
        nb_filters, pool_size, kernel_size, dropout, activation,
        fc_layer_width):
    model = Sequential()
    nb_rows, nb_cols = input_shape
    # add one dimension for the convolution filters
    model.add(Reshape((nb_rows, nb_cols, 1), input_shape=input_shape))
    for i in range(nb_conv_blocks):
        model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                                border_mode='valid'))
        model.add(Activation(activation))
        model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
        model.add(Activation(activation))
        model.add(MaxPooling2D(pool_size=pool_size))
        if dropout > 0:
            model.add(Dropout(dropout))
    model.add(Flatten())
    model.add(Dense(fc_layer_width))
    model.add(Activation(activation))
    model.add(Dropout(dropout))
    model.add(Dense(nb_classes))
    model.add(Activation('softmax'))

    model.summary()

    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    return model

@ex.capture
def create_model(model_arch):
    if model_arch == 'fc':
        return create_fc_model()
    elif model_arch == 'conv':
        return create_conv_model()

def save_model(model):
    """
    Saved the model as an Sacred artifact.
    """
    with NamedTemporaryFile(suffix='_model.h5') as model_file:
        model.save(model_file.name)
        ex.add_artifact(model_file.name)

@ex.config
def ex_config():
    batch_size = 128
    nb_epoch = 20
    model_arch = 'fc'

@ex.automain
def main(_run, batch_size, nb_epoch, model_arch):
    X_train, Y_train, X_test, Y_test = load_data()
    model = create_model()

    history = model.fit(X_train, Y_train,
                        batch_size=batch_size, nb_epoch=nb_epoch,
                        verbose=1, validation_data=(X_test, Y_test),
                        callbacks=[TrainingHistoryToSacredInfo(_run)])

    save_model(model)

    score = model.evaluate(X_test, Y_test, verbose=0)

    return {
        'history': history.history,
        'test_loss': score[0],
        'test_accuracy': score[1]
    }


text:
<?php
/**
 * Zencoder API client interface.
 *
 * @category Services
 * @package  Services_Zencoder
 * @author   Michael Christopher <m@zencoder.com>
 * @version  Release: 2.1.2
 * @license  http://creativecommons.org/licenses/MIT/MIT
 * @link     http://github.com/zencoder/zencoder-php
 */

class Services_Zencoder_Notification extends Services_Zencoder_Object
{
    /**
    * The job that the notification references
    *
    * @var Services_Zencoder_Job
    */
    public $job;

    public function __construct($params)
    {
        if(empty($params->job)) $params->job = new stdClass();
        if(!empty($params->input)) $params->job->input_media_file = $params->input;
        if(!empty($params->outputs) && is_array($params->outputs)) {
            foreach ($params->outputs as $output) $params->job->outputs[] = $output;
        } else {
            if(!empty($params->output)) $params->job->outputs[] = $params->output;
        }
        $this->job = new Services_Zencoder_Job($params->job);
    }
}


text:
create or replace function to_englishtsquery(text text) returns tsquery as $$
begin
    return plainto_tsquery('english', text);
end;
$$ language plpgsql immutable;

create or replace function to_germantsquery(text text) returns tsquery as $$
begin
    return plainto_tsquery('german', text);
end;
$$ language plpgsql immutable;


text:
var express = require('express');
var path = require('path');
var app = express();
var port = 5006;

app.set('port', port);
app.listen(app.get('port'));

app.use(express.static(path.join(__dirname, '/')));

console.log(`running on port ${port}`);


text:
namespace ZincDB {
	describe("Dispatcher:", () => {
		describe("TokenizedDispatcher:", () => {
			it("Executes handler when exec is called and passes correct arguments", async () => {
				const dispatcher = new TokenizedDispatcher((request, options) => {
					expect(request.token).toBeDefined();
					expect(request.target).toEqual("target");
					expect(request.operation).toEqual("hi");
					expect(request.args).toEqual([1, 2, 3]);

					dispatcher.announceResponse({
						token: request.token,
						target: request.target,
						operation: request.operation,
						result: 1234
					});
				});

				expect(await dispatcher.exec("target", "hi", [1, 2, 3])).toEqual(1234);
				expect(await dispatcher.exec("target", "hi", [1, 2, 3])).toEqual(1234);
			});
		});
	});
}


text:
package net.minecraft.src.nucleareal.animalcrossing.untispacingchest;

import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;

public class SlotUntiSpacingChest extends Slot
{
	public SlotUntiSpacingChest(IInventory inventory, int slotIndex, int xPos, int yPos)
	{
		super(inventory, slotIndex, xPos, yPos);
	}
}


text:
using System.ComponentModel;
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global

namespace MidiStream.Enums
{
    public enum MidiType : short
    {
        Sequential,
        Synchronous,
        Asynchronous
    }

    public enum MetaType : byte
    {
        SequenceNumber = 0x00,
        Text = 0x01,
        CopyrightNotice = 0x02,
        TrackName = 0x03,
        InstrumentName = 0x04,
        Lyrics = 0x05,
        Marker = 0x06,
        CuePoint = 0x07,
        ChannelPrefix = 0x20,
        EndOfTrack = 0x2F,
        SetTempo = 0x51,
        SMPTE_Offset = 0x54,
        TimeSignature = 0x58,
        KeySignature = 0x59,
        SequencerSpecific = 0x7F,
        Reset = 0xFF
    }

    public enum VoiceType : byte
    {
        NoteOff = 0x80,
        NoteOn = 0x90,
        KeyPressure = 0xA0,
        Controller = 0xB0,
        ProgramChange = 0xC0,
        ChannelPressure = 0xD0,
        PitchWheel = 0xE0
    }

    public enum SystemCommon : byte
    {
        SysexMessage = 0xF0,
        MidiTimeCodeQuarterFrame = 0xF1,
        SongPositionPointer = 0xF2,
        SongSelect = 0xF3,
        TuneRequest = 0xF6
    }

    public enum SystemRealtime : byte
    {
        MIDIClock = 0xF8,
        MIDIStart = 0xFA,
        MIDIContinue = 0xFB,
        MIDIStop = 0xFC,
        ActiveSense = 0xFE,
        Reset = 0xFF
    }

    public enum Controller : byte
    {
        // Coarse

        BankSelect_Coarse,
        ModulationWheel_Coarse,
        BreathController_Coarse,
        FootController_Coarse = 4,
        PortamentoTime_Coarse,
        DataEntry_Coarse,
        ChannelVolume_Coarse,
        Balance_Coarse,
        Pan_Coarse = 10,
        Expression_Coarse,

        EffectControl1_Coarse,
        EffectControl2_Coarse,

        GeneralPurposeController1_Coarse = 16,
        GeneralPurposeController2_Coarse = 17,
        GeneralPurposeController3_Coarse = 18,
        GeneralPurposeController4_Coarse = 19,

        // Fine

        BankSelect_Fine = 32,
        ModulationWheel_Fine,
        BreathController_Fine,
        FootController_Fine = 36,
        PortamentoTime_Fine,
        DataEntry_Fine,
        ChannelVolume_Fine,
        Balance_Fine,
        Pan_Fine = 42,
        Expression_Fine,

        EffectControl1_Fine,
        EffectControl2_Fine,

        // Pedals

        HoldPedal1 = 64,
        DamperPedal1 = 64,
        SustainPedal1 = 64,

        PortamentoPedal,
        SostenutoPedal,
        SoftPedal,
        LegatoPedal,

        HoldPedal2 = 69,
        DamperPedal2 = 69,
        SustainPedal2 = 69,

        // other controllers

        SoundController1,
        SoundController2,
        SoundController3,
        SoundController4,
        SoundController5,
        SoundController6,
        SoundController7,
        SoundController8,
        SoundController9,
        SoundController10,

        GeneralPurposeController5,
        GeneralPurposeController6,
        GeneralPurposeController7,
        GeneralPurposeController8,

        PortamentoControl,
        HighResolutionVelocityPrefix = 88,

        Effect1Depth = 91,
        Effect2Depth,
        Effect3Depth,
        Effect4Depth,
        Effect5Depth,

        ExternalEffectDepth = 91,
        TremoloDepth,
        ChorusDepth,
        CelesteDepth,
        PhaserLevel,

        DataButtonIncrement,
        DataButtonDecrement,

        NonRegisteredParameter_Coarse,
        NonRegisteredParameter_Fine,
        RegisteredParameter_Coarse,
        RegisteredParameter_Fine,

        AllSoundOff = 120,
        AllControllersOff,
        LocalControl,
        AllNotesOff,
        OmniModeOff,
        OmniModeOn,
        MonoOperationAndAllNotesOff,
        MonoOperationAndAllNotesOn
    }

    public enum DivisionType
    {
        PPQN,
        FPS
    }

    public enum FramesPerSecond
    {
        _24_FPS = 24,
        _25_FPS = 25,
        _30_FPS = 30,
        _30_FPS_Drop = 29
    }

    internal enum MidiException
    {
        [Description("Not a midi file")]
        NotMidi,
        [Description("Could not find track header")]
        TrackMissing,
        [Description("End of stream reached unexpectedly.")]
        EndOfStream,
        [Description("Could not find end of the track.")]
        TrackNotComplete,
        [Description("This file is not supported")]
        NotSupported,
        [Description("file contains invalid midi message.")]
        InvalidMessage,
        [Description("status byte was omitted but it was not recognized")]
        UnknownStatus,
        [Description("Variable Length Quantity (VLQ) overflow")]
        VLQ_Overflow
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.redwings.wingsweather"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="org.redwings.wingsweather.activity.ChooseAreaActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="org.redwings.wingsweather.activity.WeatherActivity"></activity>
        <service android:name="org.redwings.wingsweather.service.AutoUpdateService"></service>
        <receiver android:name="org.redwings.wingsweather.receiver.AutoUpdateReceiver"></receiver>
    </application>

</manifest>


text:
namespace System.Data {
    using System;
    using System.Data;
    using System.Diagnostics;

    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    internal interface IFilter {
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        bool Invoke(DataRow row, DataRowVersion version);
    }
}


text:
import { useContext } from "react";
import * as React from "react";
import { graphql } from "react-relay"

import { CollectionsRailQuery } from "v2/__generated__/CollectionsRailQuery.graphql"
import { SystemContext } from "v2/System"
import { renderWithLoadProgress } from "v2/System/Relay/renderWithLoadProgress"
import { SystemQueryRenderer } from "v2/System/Relay/SystemQueryRenderer"
import { CollectionsRailFragmentContainer as CollectionsRail } from "./CollectionsRail"

interface Props {
  articleId?: string
  showOnEditorial?: boolean
}

export const CollectionsRailContent: React.FC<Props> = passedProps => {
  const { relayEnvironment } = useContext(SystemContext)
  return (
    <SystemQueryRenderer<CollectionsRailQuery>
      lazyLoad
      environment={relayEnvironment}
      variables={{
        showOnEditorial: true,
        size: 4,
        randomizationSeed: passedProps.articleId,
      }}
      query={graphql`
        query CollectionsRailQuery(
          $showOnEditorial: Boolean
          $size: Int
          $randomizationSeed: String
        ) {
          collections: marketingCollections(
            showOnEditorial: $showOnEditorial
            size: $size
            randomizationSeed: $randomizationSeed
          ) {
            ...CollectionsRail_collections
          }
        }
      `}
      render={renderWithLoadProgress(CollectionsRail)}
      cacheConfig={{ force: true }}
    />
  )
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<document id="DDI-DrugBank.d732">
    <sentence id="DDI-DrugBank.d732.s0" text="CHEMET is not known to interact with other drugs including iron supplements; ">
        <entity id="DDI-DrugBank.d732.s0.e0" charOffset="0-5"
            type="brand" text="CHEMET"/>
        <entity id="DDI-DrugBank.d732.s0.e1" charOffset="59-62"
            type="drug" text="iron"/>
        <pair id="DDI-DrugBank.d732.s0.p0" e1="DDI-DrugBank.d732.s0.e0"
            e2="DDI-DrugBank.d732.s0.e1" ddi="false"/>
    </sentence>
    <sentence id="DDI-DrugBank.d732.s1" text="interactions have not been systematically studied. "/>
    <sentence id="DDI-DrugBank.d732.s2" text="Concomitant administration of CHEMET with other chelation therapy, such as CaNa 2 EDTA is not recommended. ">
        <entity id="DDI-DrugBank.d732.s2.e0" charOffset="30-35"
            type="brand" text="CHEMET"/>
        <entity id="DDI-DrugBank.d732.s2.e1" charOffset="75-85"
            type="drug" text="CaNa 2 EDTA"/>
        <pair id="DDI-DrugBank.d732.s2.p0" e1="DDI-DrugBank.d732.s2.e0"
            e2="DDI-DrugBank.d732.s2.e1" ddi="true" type="advise"/>
    </sentence>
    <sentence id="DDI-DrugBank.d732.s3" text="Drug/Laboratory Tests Interaction: Succimer may interfere with serum and urinary laboratory tests. ">
        <entity id="DDI-DrugBank.d732.s3.e0" charOffset="35-42"
            type="drug" text="Succimer"/>
    </sentence>
    <sentence id="DDI-DrugBank.d732.s4" text="In vitro studies have shown succimer to cause false positive results for ketones in urine using nitroprusside reagents such as Ketostix    and falsely decreased measurements of serum uric acid and CPK.">
        <entity id="DDI-DrugBank.d732.s4.e0" charOffset="28-35"
            type="drug" text="succimer"/>
    </sentence>
</document>


text:
namespace mbus {

RetryTransientErrorsPolicy::RetryTransientErrorsPolicy() :
    _enabled(true),
    _baseDelay(0.001)
{}

RetryTransientErrorsPolicy::~RetryTransientErrorsPolicy() = default;

RetryTransientErrorsPolicy &
RetryTransientErrorsPolicy::setEnabled(bool enabled) {
    _enabled = enabled;
    return *this;
}

RetryTransientErrorsPolicy &
RetryTransientErrorsPolicy::setBaseDelay(double baseDelay) {
    _baseDelay = baseDelay;
    return *this;
}

bool
RetryTransientErrorsPolicy::canRetry(uint32_t errorCode) const {
    return _enabled.load(std::memory_order_relaxed) && errorCode < ErrorCode::FATAL_ERROR;
}

double
RetryTransientErrorsPolicy::getRetryDelay(uint32_t retry) const {
    uint64_t retryMultiplier = 0l;
    if (retry > 1) {
        retryMultiplier = 1L << std::min(20u, retry-1);
    }
    return std::min(10.0, _baseDelay.load(std::memory_order_relaxed) * retryMultiplier);
}

}


text:
// This is a generated file. Not intended for manual editing.
package org.intellij.xquery.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface XQuerySchemaElementTest extends XQueryPsiElement {

  @Nullable
  XQueryElementDeclaration getElementDeclaration();

}


text:
/**
 * Created by ScrumTools on 9/13/14.
 */
'use strict';

var http = require('http');
var socketio = require('socket.io');

module.exports = function (app) {

    var io;
    var server;
    // Attach Socket.io
    if (process.env.NODE_ENV === 'secure') {
        io = socketio.listen(app);
    } else {
        server = http.createServer(app);
        io = socketio.listen(server);
        app.set('server', server);
    }

    // Socket.io NameSpace Stories
    var nspStories = io.of('/stories');
    nspStories.on('connection', function (socket) {

        socket.on('story.room', function (room) {
            socket.join(room);
        });

        socket.on('story.created', function (data) {
            socket.broadcast.to(data.room).emit('on.story.created', data.story);
        });

        socket.on('story.deleted', function (data) {
            socket.broadcast.to(data.room).emit('on.story.deleted', data);
        });

        socket.on('story.updated', function (data) {
            socket.broadcast.to(data.room).emit('on.story.updated', data.story);
        });

        socket.on('story.moved', function (data) {
            socket.broadcast.to(data.room).emit('on.story.moved', data);
        });
    });

    // Socket.io NameSpace Sprints
    var nspSprints = io.of('/sprints');
    nspSprints.on('connection', function (socket) {

        socket.on('sprint.room', function (room) {
            socket.join(room);
        });

        //Sprint
        socket.on('sprint.updated', function (data) {
            socket.broadcast.to(data.room).emit('on.sprint.updated', data.sprint);
        });

        //Phases
        socket.on('phase.created', function (data) {
            socket.broadcast.to(data.room).emit('on.phase.created', data.phase);
        });

        socket.on('phase.updated', function (data) {
            socket.broadcast.to(data.room).emit('on.phase.updated', data.phase);
        });

        socket.on('phase.deleted', function (data) {
            socket.broadcast.to(data.room).emit('on.phase.deleted', data);
        });

        //Stories
        socket.on('story.updated', function (data) {
            socket.broadcast.to(data.room).emit('on.story.updated', data.story);
        });

        socket.on('story.returned', function (data) {
            socket.broadcast.to(data.room).emit('on.story.returned', data);
        });

        //Tasks
        socket.on('task.created', function (data) {
            nspSprints.to(data.room).emit('on.task.created', data.task);
        });

        socket.on('task.updated', function (data) {
            socket.broadcast.to(data.room).emit('on.task.updated', data.task);
        });

        socket.on('task.returned', function (data) {
            socket.broadcast.to(data.room).emit('on.task.returned', data);
        });

        socket.on('task.moved', function (data) {
            socket.broadcast.to(data.room).emit('on.task.moved', data.task);
        });

        socket.on('task.deleted', function (data) {
            socket.broadcast.to(data.room).emit('on.task.deleted', data);
        });
    });
};


text:
<core:FragmentDefinition
   xmlns="sap.m"
   xmlns:core="sap.ui.core" >
   <Dialog
      id="helloDialog"
      title="Hello {/recipient/name}">
       <content>
         <core:Icon
            src="sap-icon://hello-world"
            size="6rem"
            class="sapUiMediumMargin"/>
      </content>
       <beginButton>
           <Button
               text="OK"
               press="onCloseDialog"/>
       </beginButton>

   </Dialog>
</core:FragmentDefinition>


text:
{{vm.content.block1}}

					<button type="button" ui-sref="apply" class="btn btn-success cta">{{staticContent.ctat}}</button>

{{vm.content.block3}}

{{vm.content.block4}}

{{vm.content.block5}}

{{vm.content.block6}}

							<form name="snapRequired" ng-submit="vm.submitChecks()" class="snapRequired">

										I am 18 years or older.

										I have a checking account, and it has been open for at least 90 days.

										In the last 30 days, my checking account has had at least five deposits or withdrawals with no non-sufficient-fund fees.

										I have had a steady source of income for the past six months.

										I currently make at least $1,000 of personal income per month.

										I deposit the majority of my income into my checking account.

										<button type="submit" class="btn btn-success btn-lg">{{staticContent.ctas}}</button>

							</form>

{{staticContent.sfsl}}

					<form name="formContainer" ng-submit="vm.findLocation()">

							<input type="text" class="form-control input-lg text-center" placeholder="Zip Code" ng-model="findLocation.zipCode">
							<button type="submit" class="btn btn-primary btn-lg btn-block">{{staticContent.sfsb}}</button>

					</form>


text:
ENV['FOG_RC'] = ENV['FOG_RC'] || File.expand_path('../.fog', __FILE__)

## From fog-core
require 'minitest/autorun'
require "minitest/spec"
require 'fog/test_helpers'
require 'fog/hadoop'
require "simplecov"
require 'coveralls'

require File.expand_path './api_stub', __dir__

SimpleCov.start
Coveralls.wear!
if ENV['FOG_MOCK'] == 'true'
  Fog.mock!
end

if Fog.mock?
  Fog.credentials = {
    hadoop_yarn_api_url: 'http://localhost:8088',
    hadoop_hdfs_api_url: 'http://localhost:50070'
  }.merge(Fog.credentials)
end

def hadoop_yarn_service
  Fog::Hadoop[:yarn]
end

def hadoop_hdfs_service
  Fog::Hadoop[:hdfs]
end


text:
package javax.management.relation;

import java.util.ArrayList; // for Javadoc
import java.util.List;

import java.io.Serializable;

/**
 * The RelationType interface has to be implemented by any class expected to
 * represent a relation type.
 *
 * @since 1.5
 */
public interface RelationType extends Serializable {

    //
    // Accessors
    //

    /**
     * Returns the relation type name.
     *
     * @return the relation type name.
     */
    public String getRelationTypeName();

    /**
     * Returns the list of role definitions (ArrayList of RoleInfo objects).
     *
     * @return an {@link ArrayList} of {@link RoleInfo}.
     */
    public List<RoleInfo> getRoleInfos();

    /**
     * Returns the role info (RoleInfo object) for the given role info name
     * (null if not found).
     *
     * @param roleInfoName  role info name
     *
     * @return RoleInfo object providing role definition
     * does not exist
     *
     * @exception IllegalArgumentException  if null parameter
     * @exception RoleInfoNotFoundException  if no role info with that name in
     * relation type.
     */
    public RoleInfo getRoleInfo(String roleInfoName)
        throws IllegalArgumentException,
               RoleInfoNotFoundException;
}