text:
package org.iotivity.cloud.ciserver;

import java.util.HashMap;
import java.util.Iterator;

import org.iotivity.cloud.base.OICConstants;
import org.iotivity.cloud.base.ServerSystem;
import org.iotivity.cloud.base.connector.ConnectorPool;
import org.iotivity.cloud.base.device.CoapDevice;
import org.iotivity.cloud.base.device.Device;
import org.iotivity.cloud.base.device.IRequestChannel;
import org.iotivity.cloud.base.exception.ClientException;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.exception.ServerException.BadRequestException;
import org.iotivity.cloud.base.exception.ServerException.UnAuthorizedException;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.coap.CoapRequest;
import org.iotivity.cloud.base.protocols.coap.CoapResponse;
import org.iotivity.cloud.base.protocols.enums.ContentFormat;
import org.iotivity.cloud.base.protocols.enums.RequestMethod;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.base.server.CoapServer;
import org.iotivity.cloud.base.server.HttpServer;
import org.iotivity.cloud.base.server.Server;
import org.iotivity.cloud.util.Bytes;
import org.iotivity.cloud.util.Cbor;
import org.iotivity.cloud.util.Log;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

/**
 *
 * This class provides a set of APIs to manage all of request
 *
 */

public class DeviceServerSystem extends ServerSystem {

    private Cbor<HashMap<String, Object>> mCbor     = new Cbor<HashMap<String, Object>>();

    IRequestChannel                       mRDServer = null;

    public DeviceServerSystem() {
        mRDServer = ConnectorPool.getConnection("rd");
    }

    /**
     *
     * This class provides a set of APIs to manage device pool.
     *
     */
    public class CoapDevicePool {
        HashMap<String, Device> mMapDevice = new HashMap<>();

        /**
         * API for adding device information into pool.
         *
         * @param device
         *            device to be added
         */
        public void addDevice(Device device) {
            String deviceId = ((CoapDevice) device).getDeviceId();
            synchronized (mMapDevice) {
                mMapDevice.put(deviceId, device);
            }
        }

        /**
         * API for removing device information into pool.
         *
         * @param device
         *            device to be removed
         */
        public void removeDevice(Device device) throws ClientException {
            String deviceId = ((CoapDevice) device).getDeviceId();
            synchronized (mMapDevice) {
                if (mMapDevice.get(deviceId) == device) {
                    mMapDevice.remove(deviceId);
                }
            }
            removeObserveDevice(device);
        }

        private void removeObserveDevice(Device device) throws ClientException {
            Iterator<String> iterator = mMapDevice.keySet().iterator();
            while (iterator.hasNext()) {
                String deviceId = iterator.next();
                CoapDevice getDevice = (CoapDevice) queryDevice(deviceId);
                getDevice.removeObserveChannel(
                        ((CoapDevice) device).getRequestChannel());
            }
        }

        /**
         * API for getting device information.
         *
         * @param deviceId
         *            device id to get device
         */
        public Device queryDevice(String deviceId) {
            Device device = null;
            synchronized (mMapDevice) {
                device = mMapDevice.get(deviceId);
            }
            return device;
        }
    }

    CoapDevicePool mDevicePool = new CoapDevicePool();

    /**
     *
     * This class provides a set of APIs to manage life cycle of coap message.
     *
     */
    @Sharable
    class CoapLifecycleHandler extends ChannelDuplexHandler {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {

            if (msg instanceof CoapRequest) {
                try {
                    CoapDevice coapDevice = (CoapDevice) ctx.channel()
                            .attr(keyDevice).get();

                    if (coapDevice.isExpiredTime()) {
                        throw new UnAuthorizedException("token is expired");
                    }

                    CoapRequest coapRequest = (CoapRequest) msg;
                    IRequestChannel targetChannel = null;
                    if (coapRequest.getUriPath()
                            .contains(Constants.ROUTE_FULL_URI)) {

                        int RouteResourcePathSize = Constants.ROUTE_FULL_URI
                                .split("/").length;
                        CoapDevice targetDevice = (CoapDevice) mDevicePool
                                .queryDevice(coapRequest.getUriPathSegments()
                                        .get(RouteResourcePathSize - 1));
                        targetChannel = targetDevice.getRequestChannel();
                    }
                    switch (coapRequest.getObserve()) {
                        case SUBSCRIBE:
                            coapDevice.addObserveRequest(
                                    Bytes.bytesToLong(coapRequest.getToken()),
                                    coapRequest);
                            coapDevice.addObserveChannel(targetChannel);
                            break;
                        case UNSUBSCRIBE:
                            coapDevice.removeObserveChannel(targetChannel);
                            coapDevice.removeObserveRequest(
                                    Bytes.bytesToLong(coapRequest.getToken()));
                            break;
                        default:
                            break;
                    }

                } catch (Throwable t) {
                    Log.f(ctx.channel(), t);
                    ResponseStatus responseStatus = t instanceof ServerException
                            ? ((ServerException) t).getErrorResponse()
                            : ResponseStatus.INTERNAL_SERVER_ERROR;
                    ctx.writeAndFlush(MessageBuilder
                            .createResponse((CoapRequest) msg, responseStatus));
                    ctx.close();
                }
            }
            ctx.fireChannelRead(msg);
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg,
                ChannelPromise promise) throws Exception {

            boolean bCloseConnection = false;

            if (msg instanceof CoapResponse) {
                // This is CoapResponse
                // Once the response is valid, add this to deviceList
                CoapResponse response = (CoapResponse) msg;

                switch (response.getUriPath()) {
                    case OICConstants.ACCOUNT_SESSION_FULL_URI:
                        if (response.getStatus() != ResponseStatus.CHANGED) {
                            bCloseConnection = true;
                        }
                        break;
                    case OICConstants.ACCOUNT_FULL_URI:
                        if (response.getStatus() == ResponseStatus.DELETED) {
                            bCloseConnection = true;
                        }
                        break;
                }
            }

            ctx.writeAndFlush(msg);

            if (bCloseConnection == true) {
                ctx.close();
            }
        }

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            Device device = ctx.channel().attr(keyDevice).get();
            // Authenticated device connected

            sendDevicePresence(device.getDeviceId(), "on");
            mDevicePool.addDevice(device);

            device.onConnected();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx)
                throws ClientException {
            Device device = ctx.channel().attr(keyDevice).get();
            // Some cases, this event occurs after new device connected using
            // same di.
            // So compare actual value, and remove if same.
            if (device != null) {
                sendDevicePresence(device.getDeviceId(), "off");

                device.onDisconnected();

                mDevicePool.removeDevice(device);
                ctx.channel().attr(keyDevice).remove();

            }
        }

        /**
         * API for sending state to resource directory
         *
         * @param deviceId
         *            device id to be sent to resource directory
         * @param state
         *            device state to be sent to resource directory
         */
        public void sendDevicePresence(String deviceId, String state) {

            Cbor<HashMap<String, Object>> cbor = new Cbor<>();
            HashMap<String, Object> payload = new HashMap<String, Object>();
            payload.put(Constants.REQ_DEVICE_ID, deviceId);
            payload.put(Constants.PRESENCE_STATE, state);
            StringBuffer uriPath = new StringBuffer();
            uriPath.append("/" + Constants.PREFIX_OIC);
            uriPath.append("/" + Constants.DEVICE_PRESENCE_URI);
            mRDServer.sendRequest(MessageBuilder.createRequest(
                    RequestMethod.POST, uriPath.toString(), null,
                    ContentFormat.APPLICATION_CBOR,
                    cbor.encodingPayloadToCbor(payload)), null);
        }
    }

    CoapLifecycleHandler mLifeCycleHandler = new CoapLifecycleHandler();

    @Sharable
    class CoapAuthHandler extends ChannelDuplexHandler {

        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            // Actual channel active should decided after authentication.
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg,
                ChannelPromise promise) {

            try {

                if (!(msg instanceof CoapResponse)) {
                    throw new BadRequestException(
                            "this msg type is not CoapResponse");
                }
                // This is CoapResponse
                // Once the response is valid, add this to deviceList
                CoapResponse response = (CoapResponse) msg;

                switch (response.getUriPath()) {

                    case OICConstants.ACCOUNT_SESSION_FULL_URI:
                        HashMap<String, Object> payloadData = mCbor
                                .parsePayloadFromCbor(response.getPayload(),
                                        HashMap.class);

                        if (response.getStatus() != ResponseStatus.CHANGED) {
                            throw new UnAuthorizedException();
                        }

                        if (payloadData == null) {
                            throw new BadRequestException("payload is empty");
                        }
                        int remainTime = (int) payloadData
                                .get(Constants.EXPIRES_IN);

                        Device device = ctx.channel().attr(keyDevice).get();
                        ((CoapDevice) device).setExpiredPolicy(remainTime);

                        // Remove current auth handler and replace to
                        // LifeCycleHandle
                        ctx.channel().pipeline().replace(this,
                                "LifeCycleHandler", mLifeCycleHandler);

                        // Raise event that we have Authenticated device
                        ctx.fireChannelActive();

                        break;
                }

                ctx.writeAndFlush(msg);

            } catch (Throwable t) {
                Log.f(ctx.channel(), t);
                ctx.writeAndFlush(msg);
                ctx.close();
            }
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {

            try {
                if (!(msg instanceof CoapRequest)) {
                    throw new BadRequestException(
                            "this msg type is not CoapRequest");
                }

                // And check first response is VALID then add or cut
                CoapRequest request = (CoapRequest) msg;

                switch (request.getUriPath()) {
                    // Check whether request is about account
                    case OICConstants.ACCOUNT_FULL_URI:
                    case OICConstants.ACCOUNT_TOKENREFRESH_FULL_URI:

                        if (ctx.channel().attr(keyDevice).get() == null) {
                            // Create device first and pass to upperlayer
                            Device device = new CoapDevice(ctx);
                            ctx.channel().attr(keyDevice).set(device);
                        }

                        break;

                    case OICConstants.ACCOUNT_SESSION_FULL_URI:

                        HashMap<String, Object> authPayload = mCbor
                                .parsePayloadFromCbor(request.getPayload(),
                                        HashMap.class);

                        Device device = ctx.channel().attr(keyDevice).get();

                        if (device == null) {
                            device = new CoapDevice(ctx);
                            ctx.channel().attr(keyDevice).set(device);
                        }

                        if (authPayload == null) {
                            throw new BadRequestException("payload is empty");
                        }

                        ((CoapDevice) device).updateDevice(
                                (String) authPayload.get(Constants.DEVICE_ID),
                                (String) authPayload.get(Constants.USER_ID),
                                (String) authPayload
                                        .get(Constants.ACCESS_TOKEN));

                        break;

                    case OICConstants.KEEP_ALIVE_FULL_URI:
                        // TODO: Pass ping request to upper layer
                        break;

                    default:
                        throw new UnAuthorizedException(
                                "authentication required first");
                }

                ctx.fireChannelRead(msg);

            } catch (Throwable t) {
                ResponseStatus responseStatus = t instanceof ServerException
                        ? ((ServerException) t).getErrorResponse()
                        : ResponseStatus.UNAUTHORIZED;
                ctx.writeAndFlush(MessageBuilder
                        .createResponse((CoapRequest) msg, responseStatus));
                Log.f(ctx.channel(), t);
            }
        }
    }

    @Sharable
    class HttpAuthHandler extends ChannelDuplexHandler {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            // After current channel authenticated, raise to upper layer
        }
    }

    @Override
    public void addServer(Server server) {
        if (server instanceof CoapServer) {
            server.addHandler(new CoapAuthHandler());
        }

        if (server instanceof HttpServer) {
            server.addHandler(new HttpAuthHandler());
        }

        super.addServer(server);
    }

    public CoapDevicePool getDevicePool() {
        return mDevicePool;
    }
}


text:
import time
from ..utils.log import log, INFO, ERROR, PASS
from ..utils.isaac import sign_up_to_isaac
from ..utils.i_selenium import assert_tab
from ..utils.i_selenium import wait_for_xpath_element
from ..tests import TestWithDependency
from selenium.common.exceptions import TimeoutException, NoSuchElementException

__all__ = ["signup_uppercase"]

#####
# Test : Signup Email Case Sensitivity
#####
@TestWithDependency("SIGNUP_UPPERCASE", ["LOGIN", "SIGNUP"])
def signup_uppercase(driver, Users, ISAAC_WEB, WAIT_DUR, **kwargs):
    """Test if users can sign up with the uppercase form of an already existing email.

        - 'driver' should be a Selenium WebDriver.
        - 'Users' must be a TestUsers object.
        - 'ISAAC_WEB' is the string URL of the Isaac website to be tested.
        - 'WAIT_DUR' is the time in seconds to wait for JavaScript to run/load.
    """
    assert_tab(driver, ISAAC_WEB)
    driver.get(ISAAC_WEB + "/logout")
    log(INFO, "Logging out any logged in user.")
    time.sleep(WAIT_DUR)
    try:
        login_tab = driver.find_element_by_id("login-tab")
        login_tab.click()
        time.sleep(WAIT_DUR)
    except NoSuchElementException:
        log(ERROR, "Can't access login tab; can't continue!")
        return False
    try:
        log(INFO, "Try to sign up with uppercase version of already used email.")
        assert not sign_up_to_isaac(driver, Users.Guerrilla.email.upper(), Users.Guerrilla.firstname, Users.Guerrilla.lastname, Users.Guerrilla.password, suppress=True, wait_dur=WAIT_DUR)
        wait_for_xpath_element(driver, "//h4[contains(text(), 'Registration Failed')]/span[contains(text(), 'An account already exists with the e-mail address')]")
        time.sleep(WAIT_DUR)
        log(INFO, "Couldn't sign up, as expected.")
        driver.get(ISAAC_WEB)
        log(INFO, "Got: %s" % ISAAC_WEB)
        time.sleep(WAIT_DUR)
        log(PASS, "Cannot sign up with uppercase form of existing email.")
        return True
    except TimeoutException:
        log(ERROR, "Sign up with uppercase password failed with wrong error message!")
        return False
    except AssertionError:
        log(ERROR, "Sign up successful despite being uppercase form of existing account!")
        return False

redpajama_set_name: RedPajamaGithub


text:
package com.siyeh.ig.controlflow;

import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiConditionalExpression;
import com.intellij.psi.PsiExpression;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.EquivalenceChecker;
import org.jetbrains.annotations.NotNull;

public class ConditionalExpressionWithIdenticalBranchesInspection
        extends BaseInspection {

    @NotNull
    public String getDisplayName() {
        return InspectionGadgetsBundle.message(
                "conditional.expression.with.identical.branches.display.name");
    }

    @NotNull
    protected String buildErrorString(Object... infos) {
        return InspectionGadgetsBundle.message(
                "conditional.expression.with.identical.branches.problem.descriptor");
    }

    public InspectionGadgetsFix buildFix(Object... infos) {
        return new CollapseConditional();
    }

    private static class CollapseConditional extends InspectionGadgetsFix {

        @NotNull
        public String getName() {
            return InspectionGadgetsBundle.message(
                    "conditional.expression.with.identical.branches.collapse.quickfix");
        }

        public void doFix(Project project, ProblemDescriptor descriptor)
                throws IncorrectOperationException {
            final PsiConditionalExpression expression =
                    (PsiConditionalExpression)descriptor.getPsiElement();

            final PsiExpression thenExpression = expression.getThenExpression();
            assert thenExpression != null;
            final String bodyText = thenExpression.getText();
            replaceExpression(expression, bodyText);
        }
    }

    public BaseInspectionVisitor buildVisitor() {
        return new ConditionalExpressionWithIdenticalBranchesVisitor();
    }

    private static class ConditionalExpressionWithIdenticalBranchesVisitor
            extends BaseInspectionVisitor {

        @Override public void visitConditionalExpression(
                PsiConditionalExpression expression) {
            super.visitConditionalExpression(expression);
            final PsiExpression thenExpression = expression.getThenExpression();
            final PsiExpression elseExpression = expression.getElseExpression();
            if (EquivalenceChecker.expressionsAreEquivalent(thenExpression,
                    elseExpression)) {
                registerError(expression);
            }
        }
    }
}


text:
#include "ruy/have_built_path_for.h"
#include "ruy/opt_set.h"

namespace ruy {

#if RUY_PLATFORM_X86
// IMPORTANT:
// These patterns must match those in the pack and kernel cc files.
#if !(RUY_PLATFORM_AVX512 && RUY_OPT(ASM))

bool HaveBuiltPathForAvx512() { return false; }

#else  // RUY_PLATFORM_AVX512 && RUY_OPT(ASM)

bool HaveBuiltPathForAvx512() { return true; }

#endif  // RUY_PLATFORM_AVX512 && RUY_OPT(ASM)
#endif  // RUY_PLATFORM_X86

}  // namespace ruy


text:
      NALD reference

      65432123

      Region

      Anglian

      Site description

      Great Ouse at Bedford College (Heat pump - cooling only)

      Purpose

      {{ pData.Purpose1 }}

      Return period

      01 April 2018 to 31 March 2019

      Abstraction period

      01 April to 31 September


text:
//
//  RKURL.m
//  RestKit
//
//  Created by Jeff Arena on 10/18/10.
//  Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "RKURL.h"
#import "RKClient.h"
#import "NSURL+RKAdditions.h"
#import "NSString+RKAdditions.h"
#import "NSDictionary+RKAdditions.h"
#import "RKLog.h"

@interface RKURL ()
@property (nonatomic, copy, readwrite) NSURL *baseURL;
@property (nonatomic, copy, readwrite) NSString *resourcePath;
@end

@implementation RKURL

@synthesize baseURL;
@synthesize resourcePath;

+ (id)URLWithBaseURL:(NSURL *)baseURL {
    return [self URLWithBaseURL:baseURL resourcePath:nil queryParameters:nil];
}

+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath {
    return [self URLWithBaseURL:baseURL resourcePath:resourcePath queryParameters:nil];
}

+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters {
    return [[[self alloc] initWithBaseURL:baseURL resourcePath:resourcePath queryParameters:queryParameters] autorelease];
}

+ (id)URLWithBaseURLString:(NSString *)baseURLString {
    return [self URLWithBaseURLString:baseURLString resourcePath:nil queryParameters:nil];
}

+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath {
    return [self URLWithBaseURLString:baseURLString resourcePath:resourcePath queryParameters:nil];
}

+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters {
    return [self URLWithBaseURL:[NSURL URLWithString:baseURLString] resourcePath:resourcePath queryParameters:queryParameters];
}

// Designated initializer. Note this diverges from NSURL due to a bug in Cocoa. We can't
// call initWithString:relativeToURL: from a subclass.
- (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters {
    // Merge any existing query parameters with the incoming dictionary
    NSDictionary *resourcePathQueryParameters = [theResourcePath queryParameters];
    NSMutableDictionary *mergedQueryParameters = [NSMutableDictionary dictionaryWithDictionary:[theBaseURL queryParameters]];
    [mergedQueryParameters addEntriesFromDictionary:resourcePathQueryParameters];
    [mergedQueryParameters addEntriesFromDictionary:theQueryParameters];

    // Build the new URL path
    NSRange queryCharacterRange = [theResourcePath rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"?"]];
    NSString *resourcePathWithoutQueryString = (queryCharacterRange.location == NSNotFound) ? theResourcePath : [theResourcePath substringToIndex:queryCharacterRange.location];
    NSString *baseURLPath = [[theBaseURL path] isEqualToString:@"/"] ? @"" : [[theBaseURL path] stringByStandardizingPath];
    NSString *completePath = resourcePathWithoutQueryString ? [baseURLPath stringByAppendingString:resourcePathWithoutQueryString] : baseURLPath;
    NSString* completePathWithQuery = [completePath stringByAppendingQueryParameters:mergedQueryParameters];

    // NOTE: You can't safely use initWithString:relativeToURL: in a NSURL subclass, see http://www.openradar.me/9729706
    // So we unfortunately convert into an NSURL before going back into an NSString -> RKURL
    NSURL* completeURL = [NSURL URLWithString:completePathWithQuery relativeToURL:theBaseURL];
    if (!completeURL) {
        RKLogError(@"Failed to build RKURL by appending resourcePath and query parameters '%@' to baseURL '%@'", theResourcePath, theBaseURL);
        [self release];
        return nil;
    }

    self = [self initWithString:[completeURL absoluteString]];
    if (self) {
        self.baseURL = theBaseURL;
        self.resourcePath = theResourcePath;
    }

    return self;
}

- (void)dealloc {
    [baseURL release];
    baseURL = nil;
    [resourcePath release];
    resourcePath = nil;

    [super dealloc];
}

- (NSDictionary *)queryParameters {
    if (self.query) {
        return [NSDictionary dictionaryWithURLEncodedString:self.query];
    }
    return nil;
}

- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath {
    return [RKURL URLWithBaseURL:self resourcePath:theResourcePath];
}

- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters {
    return [RKURL URLWithBaseURL:self resourcePath:theResourcePath queryParameters:theQueryParameters];
}

- (RKURL *)URLByAppendingQueryParameters:(NSDictionary *)theQueryParameters {
    return [RKURL URLWithBaseURL:self resourcePath:nil queryParameters:theQueryParameters];
}

- (RKURL *)URLByReplacingResourcePath:(NSString *)newResourcePath {
    return [RKURL URLWithBaseURL:self.baseURL resourcePath:newResourcePath];
}

- (RKURL *)URLByInterpolatingResourcePathWithObject:(id)object {
    return [self URLByReplacingResourcePath:[self.resourcePath interpolateWithObject:object]];
}

#pragma mark - NSURL Overloads

/*
 Overload implementations from NSURL. We consider a naked string to be initialized
 with a baseURL == self. Otherwise appending/replacing resourcePath will not work.
 */

+ (id)URLWithString:(NSString *)URLString {
    return [self URLWithBaseURLString:URLString];
}

- (id)initWithString:(NSString *)URLString {
    self = [super initWithString:URLString];
    if (self) {
        self.baseURL = self;
    }

    return self;
}

@end


text:
"""Store package.

Contains all packages and modules dealing with user metadata.

.. packageauthor:: Dave Zimmelman <zimmed@zimmed.io>

Exports:

"""

from .db import db, DBLookupError
from core.datamodel import DataModelController

class ControllerCollection(object):

    MAX_CACHE = 100

    def __init__(self, store, max_cache=None):
        if not max_cache:
            max_cache = self.__class__.MAX_CACHE
        self._max_cache = max_cache
        self._controllers = []
        self._ctrl_map = {}
        self._store = store

    def prune(self):
        while len(self._controllers) > self._max_cache:
            c = self._controllers.pop()
            print 'Pruning: ' + repr(c)
            del self._ctrl_map[c.uid]
            self._store.save(c.__class__, c.model)

    def shift_down(self, index):
        for k in self._ctrl_map.iterkeys():
            if self._ctrl_map[k] > index:
                self._ctrl_map[k] -= 1

    def shift_up(self):
        for k in self._ctrl_map.iterkeys():
            self._ctrl_map[k] += 1

    def insert(self, ctrl):
        if ctrl.uid in self._ctrl_map.iterkeys():
            return
        self._controllers.insert(0, ctrl)
        self.shift_up()
        self._ctrl_map[ctrl.uid] = 0
        self.prune()

    def get(self, uid):
        index = self._ctrl_map[uid]
        return self._controllers[index]

    def remove(self, uid):
        index = self._ctrl_map[uid]
        del self._controllers[index]
        del self._ctrl_map[uid]
        self.shift_down(index)

class DataStore(object):

    _CACHE = {}
    _db = None

    @classmethod
    # __new__ is automatically setting both first and second args to class.
    #   no idea why.
    def __new__(cls, _, db_host='localhost',
                db_port=27017,
                db_name='zimmed-test1'):
        if not cls._db:
            cls._db = db(db_host, db_port, db_name)
        return cls

    def __init__(self, *args, **kwargs):
        pass

    @classmethod
    def _key(cls, doc_type):
        if type(doc_type) is str:
            return doc_type
        elif type(doc_type) is type:
            return doc_type.__name__
        else:
            raise ValueError('Invalid doc_type supplied to ModelStore.')

    @classmethod
    def uid(cls, doc_type):
        doc_type = cls._key(doc_type)
        return cls._db.generate_uid(doc_type)

    @classmethod
    def get_controller(cls, doc_type, uid):
        if not issubclass(doc_type, DataModelController):
            raise TypeError("`doc_type` must be a sub class of "
                            "DataModelController.")
        key = cls._key(doc_type)
        ctrl = cls.get_strict_controller(key, uid)
        if not ctrl:
            model = cls.get_strict_model(key, uid)
            if not model:
                raise DBLookupError("Object does not exist: " + key + ' -- ' + uid)
            ctrl = doc_type.restore(cls, model)
        return ctrl

    @classmethod
    def get_model(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        ctrl = cls.get_strict_controller(doc_type, uid)
        if ctrl:
            return ctrl.model
        return cls.get_strict_model(doc_type, uid)

    @classmethod
    def get_model_data(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        ctrl = cls.get_strict_controller(doc_type, uid)
        if ctrl:
            return dict(ctrl.model)
        return cls._db.get_model_data(doc_type, uid)

    @classmethod
    def get_strict_controller(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        try:
            return cls._CACHE[doc_type].get(uid)
        except KeyError:
            return None

    @classmethod
    def set_controller(cls, doc_type, ctrl):
        doc_type = cls._key(doc_type)
        if doc_type not in cls._CACHE:
            cls._CACHE[doc_type] = ControllerCollection(cls)
        return cls._CACHE[doc_type].insert(ctrl)

    @classmethod
    def delete_controller(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        try:
            cls._CACHE[doc_type].remove(uid)
            return True
        except KeyError:
            return False

    @classmethod
    def save(cls, doc_type, model):
        doc_type = cls._key(doc_type)
        cls._db.upsert_model(doc_type, model)

    @classmethod
    def store_model(cls, doc_type, model):
        doc_type = cls._key(doc_type)
        cls._db.insert_model(doc_type, model)

    @classmethod
    def update_model(cls, doc_type, model):
        doc_type = cls._key(doc_type)
        cls._db.update_model(doc_type, model)

    @classmethod
    def delete_model(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        cls._db.remove_model(doc_type, uid)

    @classmethod
    def get_strict_model(cls, doc_type, uid):
        doc_type = cls._key(doc_type)
        return cls._db.get_model(doc_type, uid)

# ----------------------------------------------------------------------------
__version__ = 0.2
__license__ = "MIT"
__credits__ = ["zimmed"]
# ----------------------------------------------------------------------------


text:
<?php

namespace Tests\Feature\integration\shoppingcart;

use App\Library\ShoppingCart\ShoppingCartAdd;
use App\Library\ShoppingCart\ShoppingCartInterface;
use Syscover\ShoppingCart\Facades\CartProvider;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class AddToShoppingCartTest extends AbstractShoppingCart
{
    use DatabaseTransactions, \SetUpProductsTrait;

    protected function setUp()
    {
        parent::setUp();
        $this->shoppingCart = new ShoppingCartAdd($this->products[0], CartProvider::instance());
        $this->shoppingCart->setQuantity(5);
        $this->message = $this->shoppingCart->getResult();
    }

    /**
     * @group shoppingcart
     * @test
     */
    public function it_must_be_able_to_add_a_product_to_the_shopping_cart()
    {
        $this->assertEquals(1, CartProvider::instance()->getCartItems()->count());
    }

    /**
     * @group shoppingcart
     * @test
     */
    public function it_must_be_able_to_set_the_quantity_of_the_item()
    {
        $this->assertEquals(5, CartProvider::instance()->getCartItems()->first()->quantity);
    }

    /**
     * @group shoppingcart
     * @test
     */
    public function it_must_return_a_user_message()
    {
        $this->assertEquals('You added book to your cart!', $this->message);
    }

    /**
     * @group shoppingcart
     * @test
     */
    public function it_must_find_the_tax_related_to_the_product()
    {
        $tax = CartProvider::instance()->getCartItems()->first()->taxRules;
        $rate = $this->products[0]->tax()->first()->percent * 100;
        $this->assertEquals($rate, $tax->first()->taxRate);
    }
}


text:
package me.smartco.akstore.store.service;

import me.smartco.akstore.common.model.Account;
import me.smartco.akstore.store.mongodb.core.AccountRepository;
import me.smartco.akstore.store.mongodb.mall.*;
import me.smartco.akstore.store.mongodb.market.DispatchOrderRepository;
import me.smartco.akstore.store.mongodb.market.DispatchProductRepository;
import me.smartco.akstore.store.mongodb.partner.Partner;
import me.smartco.akstore.store.mongodb.partner.PartnerStaff;
import me.smartco.akstore.store.mongodb.partner.Shop;
import me.smartco.akstore.store.mongodb.partner.ShopRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by libin on 14-11-12.
 */
@Component
public class PartnerService extends AbstractService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private DispatchOrderRepository dispatchOrderRepository;

    @Autowired
    private DispatchProductRepository dispatchProductRepository;

    @Autowired
    private AdvertisementRepository advertisementRepository;

    public PartnerStaff createPartnerFromUser(String userId,String username, String name, String mobile){
        Account account = new Account(name, Account.AccountType.partner);
        accountRepository.save(account);
        return createPartnerFromAccount(account,userId,username,name,mobile);
    }

    public PartnerStaff createPartnerFromAccount(Account account,String userId,String username,String name,String mobile){
        Partner partner = new Partner(account,name);
        partnerRepository.save(partner);
        PartnerStaff partnerStaff = new PartnerStaff(username,userId,partner);
        partnerStaff.setMobile(mobile);
        return partnerStaffRepository.save(partnerStaff);
    }

    public Shop createShop4Partner(Partner partner,String name){
        Shop shop=new Shop(name,partner);
        return shopRepository.save(shop);
    }

    public AccountRepository getAccountRepository() {
        return accountRepository;
    }

    public void setAccountRepository(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    public ShopRepository getShopRepository() {
        return shopRepository;
    }

    public void setShopRepository(ShopRepository shopRepository) {
        this.shopRepository = shopRepository;
    }

    public ProductRepository getProductRepository() {
        return productRepository;
    }

    public void setProductRepository(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public DispatchOrderRepository getDispatchOrderRepository() {
        return dispatchOrderRepository;
    }

    public DispatchProductRepository getDispatchProductRepository() {
        return dispatchProductRepository;
    }

    public AdvertisementRepository getAdvertisementRepository() {
        return advertisementRepository;
    }

}


text:
using Foundation;
using System.CodeDom.Compiler;

namespace Toggl.iOS
{
	[Register ("OnboardingStepView")]
	partial class OnboardingPageView
	{
		[Outlet]
		UIKit.UIView ContentView { get; set; }

		[Outlet]
		UIKit.UILabel MessageLabel { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (MessageLabel != null) {
				MessageLabel.Dispose ();
				MessageLabel = null;
			}

			if (ContentView != null) {
				ContentView.Dispose ();
				ContentView = null;
			}
		}
	}
}


text:
//
//  AppDelegate.m
//  Empty CocoaLibSpotify Project
//
//  Created by Daniel Kennett on 02/08/2012.

/*
 This project is a simple project that does nothing but set up a basic CocoaLibSpotify
 application. This can be used to quickly get started with a new project that uses CocoaLibSpotify.
 */

#import "AppDelegate.h"
#import "CocoaLibSpotify.h"
#import "ViewController.h"

#define SP_LIBSPOTIFY_DEBUG_LOGGING 0

#error Please get an appkey.c file from developer.spotify.com and remove this error before building.
#include "appkey.c"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
	    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
	} else {
	    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
	}
	self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];

	NSString *userAgent = [[[NSBundle mainBundle] infoDictionary] valueForKey:(__bridge NSString *)kCFBundleIdentifierKey];
	NSData *appKey = [NSData dataWithBytes:&g_appkey length:g_appkey_size];

	NSError *error = nil;
	[SPSession initializeSharedSessionWithApplicationKey:appKey
											   userAgent:userAgent
										   loadingPolicy:SPAsyncLoadingManual
												   error:&error];
	if (error != nil) {
		NSLog(@"CocoaLibSpotify init failed: %@", error);
		abort();
	}

	[[SPSession sharedSession] setDelegate:self];

	SPLoginViewController *controller = [SPLoginViewController loginControllerForSession:[SPSession sharedSession]];
	controller.allowsCancel = NO;
	// ^ To allow the user to cancel (i.e., your application doesn't require a logged-in Spotify user, set this to YES.
	[self.viewController presentModalViewController:controller animated:NO];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
	// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
	// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
	// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
	// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
	__block UIBackgroundTaskIdentifier identifier = [application beginBackgroundTaskWithExpirationHandler:^{
		[[UIApplication sharedApplication] endBackgroundTask:identifier];
	}];

	[[SPSession sharedSession] flushCaches:^{
		if (identifier != UIBackgroundTaskInvalid)
			[[UIApplication sharedApplication] endBackgroundTask:identifier];
	}];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
	// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
	// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
	// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -
#pragma mark SPSessionDelegate Methods

-(void)sessionDidLoginSuccessfully:(SPSession *)aSession {
	// Called after a successful login.

	[SPAsyncLoading waitUntilLoaded:aSession timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {
		[SPAsyncLoading waitUntilLoaded:aSession.user timeout:kSPAsyncLoadingDefaultTimeout then:^(NSArray *loadedItems, NSArray *notLoadedItems) {

			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Hello %@!", aSession.user.displayName]
															message:@"You should ask the developer of this app to make it do something!"
														   delegate:nil
												  cancelButtonTitle:@"OK"
												  otherButtonTitles:nil];
			[alert show];
		}];
	}];
}

-(void)session:(SPSession *)aSession didFailToLoginWithError:(NSError *)error {
	// Called after a failed login. SPLoginViewController will deal with this for us.
}

-(void)sessionDidLogOut:(SPSession *)aSession; {
	// Called after a logout has been completed.
}

-(void)session:(SPSession *)aSession didGenerateLoginCredentials:(NSString *)credential forUserName:(NSString *)userName {

	// Called when login credentials are created. If you want to save user logins, uncomment the code below.

	/*
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSMutableDictionary *storedCredentials = [[defaults valueForKey:@"SpotifyUsers"] mutableCopy];

	if (storedCredentials == nil)
		storedCredentials = [NSMutableDictionary dictionary];

	[storedCredentials setValue:credential forKey:userName];
	[defaults setValue:storedCredentials forKey:@"SpotifyUsers"];
	 */
}

-(void)session:(SPSession *)aSession didEncounterNetworkError:(NSError *)error; {
	if (SP_LIBSPOTIFY_DEBUG_LOGGING != 0)
		NSLog(@"CocoaLS NETWORK ERROR: %@", error);
}

-(void)session:(SPSession *)aSession didLogMessage:(NSString *)aMessage; {
	if (SP_LIBSPOTIFY_DEBUG_LOGGING != 0)
		NSLog(@"CocoaLS DEBUG: %@", aMessage);
}

-(void)sessionDidChangeMetadata:(SPSession *)aSession; {
	// Called when metadata has been updated somewhere in the
	// CocoaLibSpotify object model. You don't normally need to do
	// anything here. KVO on the metadata you're interested in instead.
}

-(void)session:(SPSession *)aSession recievedMessageForUser:(NSString *)aMessage; {
	// Called when the Spotify service wants to relay a piece of information to the user.
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:aMessage
													message:@"This message was sent to you from the Spotify service."
												   delegate:nil
										  cancelButtonTitle:@"OK"
										  otherButtonTitles:nil];
	[alert show];
}

@end


text:
require 'spec_helper'
module Finitio
  describe MultiRelationType, "name" do

    let(:heading){
      Heading.new([
        Attribute.new(:a, byte),
        Attribute.new(:b, byte, false)
      ])
    }

    subject{ type.name }

    context 'when not provided' do
      let(:type){ MultiRelationType.new(heading) }

      it{ should eq("{{a: Byte, b :? Byte}}") }
    end

    context 'when provided' do
      let(:type){ MultiRelationType.new(heading, "colors") }

      it{ should eq("colors") }
    end

  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>gem5: GenericTimer Class Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

Related Pages

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Alphabetical List

Class List

Class Hierarchy

Class Members

GenericTimer Class Reference
Wrapper around the actual counters and timers of the Generic Timer extension.
More...

#include <generic_timer.hh>

Inheritance diagram for GenericTimer:

<map name="GenericTimer_map">
<area href="classSimObject.html" alt="SimObject" shape="rect" coords="105,56,200,80">
<area href="classEventManager.html" alt="EventManager" shape="rect" coords="0,0,95,24">
<area href="classSerializable.html" alt="Serializable" shape="rect" coords="105,0,200,24">
<area href="classDrainable.html" alt="Drainable" shape="rect" coords="210,0,305,24">
</map>
List of all members.

Public Types

typedef GenericTimerParams 	Params

Public Member Functions

const Params * 	params () const

 	GenericTimer (Params *p)

 	Ctor.

SystemCounter * 	getSystemCounter ()

 	Returns a pointer to the system counter.

ArchTimer * 	getArchTimer (int cpu_id)

 	Returns a pointer to the architected timer for cpu_id.

virtual void 	serialize (std::ostream &os)

virtual void 	unserialize (Checkpoint *cp, const std::string &section)

Protected Attributes

BaseGic * 	_gic

 	Pointer to the GIC, needed to trigger timer interrupts.

SystemCounter 	_systemCounter

 	System counter.

ArchTimer 	_archTimers [CPU_MAX]

 	Per-CPU architected timers.

Static Protected Attributes

static const int 	CPU_MAX = 8

Classes

class  	ArchTimer

 	Per-CPU architected timer.  More...

class  	SystemCounter

 	Global system counter.  More...

Detailed Description

Wrapper around the actual counters and timers of the Generic Timer extension.

Definition at line 58 of file generic_timer.hh.

Member Typedef Documentation

          typedef GenericTimerParams GenericTimer::Params

Reimplemented from SimObject.

Definition at line 179 of file generic_timer.hh.

Constructor & Destructor Documentation

          GenericTimer::GenericTimer
          (
          Params *
           p
           )

Ctor.

Definition at line 164 of file generic_timer.cc.

References _archTimers, GenericTimer::ArchTimer::_counter, GenericTimer::ArchTimer::_cpuNum, GenericTimer::ArchTimer::_intNum, GenericTimer::ArchTimer::_parent, _systemCounter, CPU_MAX, ArmISA::i, and SimObject::name().

Member Function Documentation

          ArchTimer* GenericTimer::getArchTimer
          (
          int
           cpu_id
           )
           [inline]

Returns a pointer to the architected timer for cpu_id.

Definition at line 193 of file generic_timer.hh.

References _archTimers.

Referenced by ArmSystem::getArchTimer().

          SystemCounter* GenericTimer::getSystemCounter
          (

           )
           [inline]

Returns a pointer to the system counter.

Definition at line 190 of file generic_timer.hh.

References _systemCounter.

Referenced by ArmSystem::getSystemCounter().

          const Params* GenericTimer::params
          (

           )
           const [inline]

Reimplemented from SimObject.

Definition at line 181 of file generic_timer.hh.

References SimObject::_params.

          void GenericTimer::serialize
          (
          std::ostream &
           os
           )
           [virtual]

Reimplemented from Serializable.

Definition at line 181 of file generic_timer.cc.

References _archTimers, _systemCounter, CPU_MAX, csprintf(), ArmISA::i, SimObject::name(), Serializable::nameOut(), GenericTimer::ArchTimer::serialize(), and GenericTimer::SystemCounter::serialize().

          void GenericTimer::unserialize
          (
          Checkpoint *
           cp,

          const std::string &
           section

          )
          		 [virtual]

Reimplemented from Serializable.

Definition at line 192 of file generic_timer.cc.

References _archTimers, _systemCounter, CPU_MAX, csprintf(), ArmISA::i, and GenericTimer::SystemCounter::unserialize().

Member Data Documentation

          ArchTimer GenericTimer::_archTimers[CPU_MAX] [protected]

Per-CPU architected timers.

Definition at line 176 of file generic_timer.hh.

Referenced by GenericTimer(), getArchTimer(), serialize(), and unserialize().

          BaseGic* GenericTimer::_gic [protected]

Pointer to the GIC, needed to trigger timer interrupts.

Definition at line 171 of file generic_timer.hh.

Referenced by GenericTimer::ArchTimer::counterLimitReached().

          SystemCounter GenericTimer::_systemCounter [protected]

System counter.

Definition at line 173 of file generic_timer.hh.

Referenced by GenericTimer(), getSystemCounter(), serialize(), and unserialize().

          const int GenericTimer::CPU_MAX = 8 [static, protected]

Definition at line 168 of file generic_timer.hh.

Referenced by GenericTimer(), serialize(), and unserialize().

The documentation for this class was generated from the following files:

dev/arm/generic_timer.hh
dev/arm/generic_timer.cc

<address style="align: right;">
Generated on Fri Apr 17 12:39:39 2015 for gem5 by  doxygen 1.4.7</address>


text:
<?php declare(strict_types=1);
/**
 * This file is part of CREY Framework.
 * (c) 2016 Matthias Kaschubowski, All rights reserved.
 *
 * The applied license is stored at the root directory of this package.
 */

namespace Crey\Guardian\Abstracts;

use Crey\Guardian\Contracts\ResourceContract;
use Crey\Guardian\Contracts\RoleContract;

/**
 * Class AbstractRole
 *
 * @package grey.guardian
 * @author Matthias Kaschubowski
 */
abstract class AbstractRole implements RoleContract
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var \SplObjectStorage
     */
    protected $inheritedRoles;

    /**
     * @var \SplObjectStorage
     */
    protected $resources;

    /**
     * returns the name of the role
     *
     * @return string
     */
    abstract public function getName(): string;

    /**
     * inherits roles
     *
     * @param RoleContract[] ...$roles
     * @return mixed
     */
    public function inherit(RoleContract ... $roles)
    {
        foreach ( $roles as $role ) {
            if ( ! $this->inheritedRoles->contains($role) ) {
                $this->inheritedRoles->attach($role);
            }
        }
    }

    /**
     * Removes the inheritance of a specific role.
     *
     * @param RoleContract $role
     * @return mixed
     */
    public function forget(RoleContract $role)
    {
        if ( $this->inheritedRoles->contains($role) ) {
            $this->inheritedRoles->detach($role);
        }
    }

    /**
     * checks whether this role inherits the given role or not.
     *
     * @param RoleContract $role
     * @return bool
     */
    public function inheritsFrom(RoleContract $role): bool
    {
        if ( ! $this->inheritedRoles->contains($role) ) {
            foreach ( $this->inheritedRoles as $inheritedRole ) {
                /** @var RoleContract $inheritedRole */
                if ( $inheritedRole->inheritsFrom($role) ) {
                    return true;
                }
            }

            return false;
        }

        return true;
    }

    /**
     * checks whether this role has access to a resource, optionally provided action strings
     * filter this check to the given actions only. No given actions provides a general check
     * that does return true when only one action in the resource was granted to this role.
     *
     * @param ResourceContract $resource
     * @param \string[] ...$actions
     * @return mixed
     */
    public function hasAccessTo(ResourceContract $resource, string ... $actions)
    {
        if ( empty($actions) ) {
            foreach ( $resource->getActionIterator() as $action => $role ) {
                if ( $this->inheritsFrom($role) ) {
                    return true;
                }
            }

            return false;
        }

        foreach ( $actions as $action ) {
            $role = $resource->getActionRole($action);

            if ( ! $this->inheritsFrom($role) ) {
                return false;
            }
        }

        return true;
    }

    /**
     * PHP's debug info implementation to cascade the properties to a set of information
     * that are necessary for development
     *
     * @return array
     */
    public function __debugInfo()
    {
        $inheritedRoles = iterator_to_array($this->inheritedRoles);

        $meta = ['name' => $this->getName()];

        if ( ! empty($inheritedRoles) ) {
            $meta['inherited Roles'] = $inheritedRoles;
        }

        return $meta;
    }

}


text:
package org.apache.geronimo.gshell.commands.ssh;

import org.apache.geronimo.gshell.clp.Argument;
import org.apache.geronimo.gshell.clp.Option;
import org.apache.geronimo.gshell.command.CommandAction;
import org.apache.geronimo.gshell.command.CommandContext;
import org.apache.geronimo.gshell.i18n.MessageSource;
import org.apache.geronimo.gshell.io.IO;
import org.apache.geronimo.gshell.io.PromptReader;
import org.apache.geronimo.gshell.spring.BeanContainer;
import org.apache.geronimo.gshell.spring.BeanContainerAware;
import org.apache.sshd.SshClient;
import org.apache.sshd.ClientSession;
import org.apache.sshd.ClientChannel;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.common.util.NoCloseInputStream;
import org.apache.sshd.common.util.NoCloseOutputStream;
import org.apache.sshd.common.future.CloseFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Connect to a SSH server.
 *
 * @version $Rev$ $Date$
 */
public class SshAction
    implements CommandAction, BeanContainerAware
{
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Option(name="-l", aliases={"--username"})
    private String username;

    @Option(name="-P", aliases={"--password"})
    private String password;

    @Argument(required=true)
    private String hostname;

    @Option(name="-p", aliases={"--port"})
    private int port = 22;

    private BeanContainer container;

    public void setBeanContainer(final BeanContainer container) {
        assert container != null;
        this.container = container;
    }

    /**
     * Helper to validate that prompted username or password is not null or empty.
     */
    private class UsernamePasswordValidator
        implements PromptReader.Validator
    {
        private String type;

        private int count = 0;

        private int max = 3;

        public UsernamePasswordValidator(final String type) {
            assert type != null;

            this.type = type;
        }

        public boolean isValid(final String value) {
            count++;

            if (value != null && value.trim().length() > 0) {
                return true;
            }

            if (count >= max) {
                throw new RuntimeException("Too many attempts; failed to prompt user for " + type + " after " + max + " tries");
            }

            return false;
        }
    }

    public Object execute(final CommandContext context) throws Exception {
        assert context != null;
        IO io = context.getIo();
        MessageSource messages = context.getCommand().getMessages();

        //
        // TODO: Parse hostname for <username>@<hostname>
        //

        io.info(messages.format("info.connecting", hostname, port));

        // If the username/password was not configured via cli, then prompt the user for the values
        if (username == null || password == null) {
            PromptReader prompter = new PromptReader(io);
            String text;

            log.debug("Prompting user for credentials");

            if (username == null) {
                text = messages.getMessage("prompt.username");
                username = prompter.readLine(text + ": ", new UsernamePasswordValidator(text));
            }

            if (password == null) {
                text = messages.getMessage("prompt.password");
                password = prompter.readPassword(text + ": ", new UsernamePasswordValidator(text));
            }
        }

        // Create the client from prototype
        SshClient client = container.getBean(SshClient.class);
        log.debug("Created client: {}", client);
        client.start();

        try {
            ConnectFuture future = client.connect(hostname, port);
            future.await();
            ClientSession session = future.getSession();

            try {
                io.info(messages.getMessage("info.connected"));

                session.authPassword(username, password);
                int ret = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
                if ((ret & ClientSession.AUTHED) == 0) {
                    io.err.println("Authentication failed");
                    return Result.FAILURE;
                }

                ClientChannel channel = session.createChannel("shell");
                channel.setIn(new NoCloseInputStream(io.inputStream));
                channel.setOut(new NoCloseOutputStream(io.outputStream));
                channel.setErr(new NoCloseOutputStream(io.errorStream));
                channel.open();
                channel.waitFor(ClientChannel.CLOSED, 0);
            } finally {
                session.close(false);

            }
        } finally {
            client.stop();
        }

        io.verbose(messages.getMessage("verbose.disconnected"));

        return Result.SUCCESS;
    }
}


text:
import locale
import logging

from streamlink.compat import is_py2

try:
    from iso639 import languages
    from iso3166 import countries

    PYCOUNTRY = False
except ImportError:  # pragma: no cover
    from pycountry import languages, countries

    PYCOUNTRY = True

DEFAULT_LANGUAGE = "en"
DEFAULT_COUNTRY = "US"
DEFAULT_LANGUAGE_CODE = "{0}_{1}".format(DEFAULT_LANGUAGE, DEFAULT_COUNTRY)

log = logging.getLogger(__name__)

class Country(object):
    def __init__(self, alpha2, alpha3, numeric, name, official_name=None):
        self.alpha2 = alpha2
        self.alpha3 = alpha3
        self.numeric = numeric
        self.name = name
        self.official_name = official_name

    @classmethod
    def get(cls, country):
        try:
            if PYCOUNTRY:
                c = countries.lookup(country)
                return Country(c.alpha_2, c.alpha_3, c.numeric, c.name, getattr(c, "official_name", c.name))
            else:
                c = countries.get(country)
                return Country(c.alpha2, c.alpha3, c.numeric, c.name, c.apolitical_name)
        except (LookupError, KeyError):
            raise LookupError("Invalid country code: {0}".format(country))

    def __eq__(self, other):
        return ((self.alpha2 and self.alpha2 == other.alpha2) or
                (self.alpha3 and self.alpha3 == other.alpha3) or
                (self.numeric and self.numeric == other.numeric))

    def __str__(self):
        if is_py2:
            return self.__unicode__().encode("utf8")
        else:
            return self.__unicode__()

    def __unicode__(self):
        return u"Country({0!r}, {1!r}, {2!r}, {3!r}, official_name={4!r})".format(self.alpha2,
                                                                                self.alpha3,
                                                                                self.numeric,
                                                                                self.name,
                                                                                self.official_name)

class Language(object):
    def __init__(self, alpha2, alpha3, name, bibliographic=None):
        self.alpha2 = alpha2
        self.alpha3 = alpha3
        self.name = name
        self.bibliographic = bibliographic

    @classmethod
    def get(cls, language):
        try:
            if PYCOUNTRY:
                c = languages.lookup(language)
                return Language(c.alpha_2, c.alpha_3, c.name, getattr(c, "bibliographic", None))
            else:
                l = None
                if len(language) == 2:
                    l = languages.get(alpha2=language)
                elif len(language) == 3:
                    for code_type in ['part2b', 'part2t', 'part3']:
                        try:
                            l = languages.get(**{code_type: language})
                            break
                        except KeyError:
                            pass
                    if not l:
                        raise KeyError(language)
                else:
                    raise KeyError(language)
                return Language(l.alpha2, l.part3, l.name, l.part2b or l.part2t)
        except (LookupError, KeyError):
            raise LookupError("Invalid language code: {0}".format(language))

    def __eq__(self, other):
        return ((self.alpha2 and self.alpha2 == other.alpha2) or
                (self.alpha3 and self.alpha3 == other.alpha3) or
                (self.bibliographic and self.bibliographic == other.bibliographic))

    def __str__(self):
        if is_py2:
            return self.__unicode__().encode("utf8")
        else:
            return self.__unicode__()

    def __unicode__(self):
        return u"Language({0!r}, {1!r}, {2!r}, bibliographic={3!r})".format(self.alpha2,
                                                                            self.alpha3,
                                                                            self.name,
                                                                            self.bibliographic)

class Localization(object):
    def __init__(self, language_code=None):
        self._language_code = None
        self.country = None
        self.language = None
        self.explicit = bool(language_code)
        self.language_code = language_code

    @property
    def language_code(self):
        return self._language_code

    def _parse_locale_code(self, language_code):
        parts = language_code.split("_", 1)
        if len(parts) != 2 or len(parts[0]) != 2 or len(parts[1]) != 2:
            raise LookupError("Invalid language code: {0}".format(language_code))
        return self.get_language(parts[0]), self.get_country(parts[1])

    @language_code.setter
    def language_code(self, language_code):
        is_system_locale = language_code is None
        if language_code is None:
            try:
                language_code, _ = locale.getdefaultlocale()
            except ValueError:
                language_code = None
            if language_code is None or language_code == "C":
                # cannot be determined
                language_code = DEFAULT_LANGUAGE

        try:
            self.language, self.country = self._parse_locale_code(language_code)
            self._language_code = language_code
        except LookupError:
            if is_system_locale:
                # If the system locale returns an invalid code, use the default
                self.language = self.get_language(DEFAULT_LANGUAGE)
                self.country = self.get_country(DEFAULT_COUNTRY)
                self._language_code = DEFAULT_LANGUAGE_CODE
            else:
                raise
        log.debug("Language code: {0}".format(self._language_code))

    def equivalent(self, language=None, country=None):
        equivalent = True
        try:
            equivalent = equivalent and (not language or self.language == self.get_language(language))
            equivalent = equivalent and (not country or self.country == self.get_country(country))
        except LookupError:
            # if an unknown language/country code is given they cannot equivalent
            return False

        return equivalent

    @classmethod
    def get_country(cls, country):
        return Country.get(country)

    @classmethod
    def get_language(cls, language):
        return Language.get(language)


text:
$(document).bind("mobileinit", function(){
    //$.mobile.ajaxEnabled = false;
    //$.mobile.pushStateEnabled = false;
});


text:
package com.hotels.styx.api.exceptions;

/**
 * A marker interface for exceptions that indicates that the operation that caused the exception can be retried.
 */
public interface IsRetryableException {
}


text:
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Auth0
{
    [DataContract]
    public class ProvisioningTicket
    {
        public string strategy { get; set; }
        public Dictionary<string, string> options { get; set; }
    }
}


text:
package org.apache.hadoop.hive.common.ndv.hll;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import org.apache.hadoop.hive.metastore.annotation.MetastoreUnitTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(value = Parameterized.class)
@Category(MetastoreUnitTest.class)
public class TestHLLNoBias {

  // 1.5% tolerance for long range bias (when no bias enabled) and 5% when (no
  // bias is disabled) and
  // 0.5% for short range bias
  private float noBiaslongRangeTolerance = 2.0f;
  private float biasedlongRangeTolerance = 5.0f;
  private float shortRangeTolerance = 0.5f;

  private int size;

  public TestHLLNoBias(int n) {
    this.size = n;
  }

  @Parameters
  public static Collection<Object[]> data() {
    Object[][] data = new Object[][] { { 30000 }, { 41000 }, { 50000 }, { 60000 }, { 75000 },
        { 80000 }, { 81920 } };
    return Arrays.asList(data);
  }

  @Test
  public void testHLLAdd() {
    Random rand = new Random(size);
    HyperLogLog hll = HyperLogLog.builder().build();
    int size = 100;
    for (int i = 0; i < size; i++) {
      hll.addLong(rand.nextLong());
    }
    double threshold = size > 40000 ? noBiaslongRangeTolerance : shortRangeTolerance;
    double delta = threshold * size / 100;
    assertEquals((double) size, (double) hll.count(), delta);
  }

  @Test
  public void testHLLAddHalfDistinct() {
    Random rand = new Random(size);
    HyperLogLog hll = HyperLogLog.builder().build();
    int unique = size / 2;
    Set<Long> hashset = new HashSet<>();
    for (int i = 0; i < size; i++) {
      long val = rand.nextInt(unique);
      hashset.add(val);
      hll.addLong(val);
    }
    double threshold = size > 40000 ? noBiaslongRangeTolerance : shortRangeTolerance;
    double delta = threshold * hashset.size() / 100;
    assertEquals((double) hashset.size(), (double) hll.count(), delta);
  }

  @Test
  public void testHLLNoBiasDisabled() {
    Random rand = new Random(size);
    HyperLogLog hll = HyperLogLog.builder().enableNoBias(false).build();
    int size = 100;
    for (int i = 0; i < size; i++) {
      hll.addLong(rand.nextLong());
    }
    double threshold = size > 40000 ? biasedlongRangeTolerance : shortRangeTolerance;
    double delta = threshold * size / 100;
    assertEquals((double) size, (double) hll.count(), delta);
  }

  @Test
  public void testHLLNoBiasDisabledHalfDistinct() {
    Random rand = new Random(size);
    HyperLogLog hll = HyperLogLog.builder().enableNoBias(false).build();
    int unique = size / 2;
    Set<Long> hashset = new HashSet<>();
    for (int i = 0; i < size; i++) {
      long val = rand.nextInt(unique);
      hashset.add(val);
      hll.addLong(val);
    }
    double threshold = size > 40000 ? biasedlongRangeTolerance : shortRangeTolerance;
    double delta = threshold * hashset.size() / 100;
    assertEquals((double) hashset.size(), (double) hll.count(), delta);
  }

}


text:
#pragma once

#include <QtCore/QString>
#include <QtCore/QPersistentModelIndex>

#include <qrkernel/ids.h>

namespace qReal {

/// Interface for getting data from the repo by plugins' classes.
class ElementRepoInterface
{
public:
	virtual ~ElementRepoInterface() {}
	virtual QString logicalProperty(const QString &roleName) const = 0;
	virtual qReal::Id id() const = 0;
	virtual QString name() const = 0;
};

}


text:
layout: base
title: Project Showcase
lang: en
---

Project Showcase

    All projects...

...load...

      {% for sitepage in site.pages %}
      {% if sitepage.showcase AND sitepage.layout == 'project' %}

          {% include project-teaser.html %}

      {% endif %}
      {% endfor %}

    All projects...


text:
package gkvlite

import (
	"encoding/binary"
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
)

// A persistable item.
type Item struct {
	Transient interface{} // For any ephemeral data.
	Key, Val  []byte      // Val may be nil if not fetched into memory yet.
	Priority  int32       // Use rand.Int31() for probabilistic balancing.
}

var itemLocGL = sync.RWMutex{}

// A persistable item and its persistence location.
type itemLoc struct {
	loc  *ploc // can be nil if item is dirty (not yet persisted).
	item *Item // can be nil if item is not fetched into memory yet.
}

var empty_itemLoc = &itemLoc{}

// Number of Key bytes plus number of Val bytes.
func (i *Item) NumBytes(c *Collection) int {
	return len(i.Key) + i.NumValBytes(c)
}

func (i *Item) NumValBytes(c *Collection) int {
	if c.store.callbacks.ItemValLength != nil {
		return c.store.callbacks.ItemValLength(c, i)
	}
	return len(i.Val)
}

// The returned Item will not have been allocated through the optional
// StoreCallbacks.ItemAlloc() callback.
func (i *Item) Copy() *Item {
	return &Item{
		Key:       i.Key,
		Val:       i.Val,
		Priority:  i.Priority,
		Transient: i.Transient,
	}
}

func (i *itemLoc) Loc() *ploc {
	itemLocGL.RLock()
	defer itemLocGL.RUnlock()
	return i.loc
}

func (i *itemLoc) setLoc(n *ploc) {
	itemLocGL.Lock()
	defer itemLocGL.Unlock()
	i.loc = n
}

func (i *itemLoc) Item() *Item {
	itemLocGL.RLock()
	defer itemLocGL.RUnlock()
	return i.item
}

func (i *itemLoc) casItem(o, n *Item) bool {
	itemLocGL.Lock()
	defer itemLocGL.Unlock()
	if i.item == o {
		i.item = n
		return true
	}
	return false
}

func (i *itemLoc) Copy(src *itemLoc) {
	if src == nil {
		i.Copy(empty_itemLoc)
		return
	}

	itemLocGL.Lock()
	defer itemLocGL.Unlock()
	// NOTE: This trick only works because of the global lock. No reason to lock
	// src independently of i.
	i.loc = src.loc
	i.item = src.item
}

const itemLoc_hdrLength int = 4 + 4 + 4 + 4

func (i *itemLoc) write(c *Collection) (err error) {
	if i.Loc().isEmpty() {
		iItem := i.Item()
		if iItem == nil {
			return errors.New("itemLoc.write with nil item")
		}
		if c.store.callbacks.BeforeItemWrite != nil {
			iItem, err = c.store.callbacks.BeforeItemWrite(c, iItem)
			if err != nil {
				return err
			}
		}
		offset := atomic.LoadInt64(&c.store.size)
		hlength := itemLoc_hdrLength + len(iItem.Key)
		vlength := iItem.NumValBytes(c)
		ilength := hlength + vlength
		b := make([]byte, hlength)
		pos := 0
		binary.BigEndian.PutUint32(b[pos:pos+4], uint32(ilength))
		pos += 4
		binary.BigEndian.PutUint32(b[pos:pos+4], uint32(len(iItem.Key)))
		pos += 4
		binary.BigEndian.PutUint32(b[pos:pos+4], uint32(vlength))
		pos += 4
		binary.BigEndian.PutUint32(b[pos:pos+4], uint32(iItem.Priority))
		pos += 4
		pos += copy(b[pos:], iItem.Key)
		if pos != hlength {
			return fmt.Errorf("itemLoc.write() pos: %v didn't match hlength: %v",
				pos, hlength)
		}
		if _, err := c.store.file.WriteAt(b, offset); err != nil {
			return err
		}
		err := c.store.ItemValWrite(c, iItem, c.store.file, offset+int64(pos))
		if err != nil {
			return err
		}
		atomic.StoreInt64(&c.store.size, offset+int64(ilength))
		i.setLoc(&ploc{Offset: offset, Length: uint32(ilength)})
	}
	return nil
}

func (iloc *itemLoc) read(c *Collection, withValue bool) (icur *Item, err error) {
	if iloc == nil {
		return nil, nil
	}
	icur = iloc.Item()
	if icur == nil || (icur.Val == nil && withValue) {
		loc := iloc.Loc()
		if loc.isEmpty() {
			return nil, nil
		}
		if loc.Length < uint32(itemLoc_hdrLength) {
			return nil, fmt.Errorf("unexpected item loc.Length: %v < %v",
				loc.Length, itemLoc_hdrLength)
		}
		b := make([]byte, itemLoc_hdrLength)
		if _, err := c.store.file.ReadAt(b, loc.Offset); err != nil {
			return nil, err
		}
		pos := 0
		length := binary.BigEndian.Uint32(b[pos : pos+4])
		pos += 4
		keyLength := binary.BigEndian.Uint32(b[pos : pos+4])
		pos += 4
		valLength := binary.BigEndian.Uint32(b[pos : pos+4])
		pos += 4
		i := c.store.ItemAlloc(c, keyLength)
		if i == nil {
			return nil, errors.New("ItemAlloc() failed")
		}
		i.Priority = int32(binary.BigEndian.Uint32(b[pos : pos+4]))
		pos += 4
		if length != uint32(itemLoc_hdrLength)+uint32(keyLength)+valLength {
			c.store.ItemDecRef(c, i)
			return nil, errors.New("mismatched itemLoc lengths")
		}
		if pos != itemLoc_hdrLength {
			c.store.ItemDecRef(c, i)
			return nil, fmt.Errorf("read pos != itemLoc_hdrLength, %v != %v",
				pos, itemLoc_hdrLength)
		}
		if _, err := c.store.file.ReadAt(i.Key,
			loc.Offset+int64(itemLoc_hdrLength)); err != nil {
			c.store.ItemDecRef(c, i)
			return nil, err
		}
		if withValue {
			err := c.store.ItemValRead(c, i, c.store.file,
				loc.Offset+int64(itemLoc_hdrLength)+int64(keyLength), valLength)
			if err != nil {
				c.store.ItemDecRef(c, i)
				return nil, err
			}
		}
		if c.store.callbacks.AfterItemRead != nil {
			i, err = c.store.callbacks.AfterItemRead(c, i)
			if err != nil {
				c.store.ItemDecRef(c, i)
				return nil, err
			}
		}
		if !iloc.casItem(icur, i) {
			c.store.ItemDecRef(c, i)
			return iloc.read(c, withValue)
		}
		if icur != nil {
			c.store.ItemDecRef(c, icur)
		}
		icur = i
	}
	return icur, nil
}

func (iloc *itemLoc) NumBytes(c *Collection) int {
	loc := iloc.Loc()
	if loc.isEmpty() {
		i := iloc.Item()
		if i == nil {
			return 0
		}
		return i.NumBytes(c)
	}
	return int(loc.Length) - itemLoc_hdrLength
}


text:
package home;

import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import org.bytedeco.javacpp.opencv_core.Mat;

public class Tests {
	String exampleImgUrl1Name = "http://i.imgur.com/dHq0BlN.png";
	String exampleImgUrl2Name = "http://i.imgur.com/apUNp99.png";
	String exampleImgUrl3Name = "http://i.imgur.com/1ogON.jpg";
	URL example1 = null;
	URL example2 = null;

	@Test
	public void testSameImages() {
		try {
			example1 = new URL(exampleImgUrl1Name);
			example2 = new URL(exampleImgUrl1Name);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			String local1 = FileDownloader.downloadFromUrl(example1, UUID.randomUUID().toString());
			String local2 = FileDownloader.downloadFromUrl(example2, UUID.randomUUID().toString());
			Mat src1 = home.Main.toMat(local1);
			Mat src2 = home.Main.toMat(local2);
			Boolean same = home.Main.areSame(src1, src2);
			// Free mem.
			src1.deallocate();
			src2.deallocate();
			src1.close();
			src2.close();
			assertTrue(same);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testDiffImages() {
		try {
			example1 = new URL(exampleImgUrl1Name);
			example2 = new URL(exampleImgUrl2Name);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			String local1 = FileDownloader.downloadFromUrl(example1, UUID.randomUUID().toString());
			String local2 = FileDownloader.downloadFromUrl(example2, UUID.randomUUID().toString());
			Mat src1 = home.Main.toMat(local1);
			Mat src2 = home.Main.toMat(local2);
			Boolean same = home.Main.areSame(src1, src2);
			// Free mem.
			src1.deallocate();
			src2.deallocate();
			src1.close();
			src2.close();
			assertFalse(same);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testDiffDim() {
		try {
			example1 = new URL(exampleImgUrl1Name);
			example2 = new URL(exampleImgUrl3Name);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			String local1 = FileDownloader.downloadFromUrl(example1, UUID.randomUUID().toString());
			String local2 = FileDownloader.downloadFromUrl(example2, UUID.randomUUID().toString());
			Mat src1 = home.Main.toMat(local1);
			Mat src2 = home.Main.toMat(local2);
			Boolean same = home.Main.areSame(src1, src2);
			// Free mem.
			src1.deallocate();
			src2.deallocate();
			src1.close();
			src2.close();
			assertFalse(same);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


text:
package de.tum.p2p.onion.forwarding.api.netty.handler;

import de.tum.p2p.proto.message.onion.forwarding.api.OnionTunnelDataMessage;
import de.tum.p2p.onion.forwarding.OnionForwarder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class OnionTunnelDataMessageHandler extends SimpleChannelInboundHandler<OnionTunnelDataMessage> {

    private OnionForwarder onionForwarder;

    public OnionTunnelDataMessageHandler(OnionForwarder onionForwarder) {
        this.onionForwarder = onionForwarder;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, OnionTunnelDataMessage msg) throws Exception {
        onionForwarder.forward(msg.getTunnelId(), msg.getData());
    }
}


text:
package org.apache.jena.sparql.algebra.op;

import java.util.ArrayList ;
import java.util.Iterator ;
import java.util.List ;

import org.apache.jena.sparql.algebra.Op ;
import org.apache.jena.sparql.algebra.Transform ;
import org.apache.jena.sparql.util.NodeIsomorphismMap ;

public abstract class OpN extends OpBase
{
    private List<Op> elements = new ArrayList<>() ;

    protected OpN()         { elements = new ArrayList<>() ; }
    protected OpN(List<Op> x)   { elements = x ; }

    /** Accumulate an op in the OpN.
     *  This exists to help building OpN in teh first place.
     *  Once built, an OpN, like any Op should be treated as immutable
     *  with no calls change the sub ops contents.
     *  No calls to .add.
     */
    public void add(Op op) { elements.add(op) ; }
    public Op get(int idx) { return elements.get(idx) ; }

    public abstract Op apply(Transform transform, List<Op> elts) ;
    public abstract OpN copy(List<Op> elts) ;

    // Tests the sub-elements for equalTo.
    protected boolean equalsSubOps(OpN op, NodeIsomorphismMap labelMap)
    {
        if (elements.size() != op.elements.size() )
            return false ;

        Iterator<Op> iter1 = elements.listIterator() ;
        Iterator<Op> iter2 = op.elements.listIterator() ;

        for ( ; iter1.hasNext() ; )
        {
            Op op1 = iter1.next();
            Op op2 = iter2.next();
            if ( ! op1.equalTo(op2, labelMap) )
                return false ;
        }
        return true ;
    }

    public int size()                   { return elements.size() ; }

    @Override
    public int hashCode()               { return elements.hashCode() ; }

    public List<Op> getElements()           { return elements ; }

    public Iterator<Op> iterator()          { return elements.iterator() ; }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Motorola Moto E (2nd Gen)
 *
 * DEVICE: otus_ds
 * MODEL: XT1021
 */
final class otus5fds_xt1021 {
    public static final String DATA = "Motorola|Moto E (2nd Gen)|";
}


text:
#ifndef _ASM_PROC_CACHE_H
#define _ASM_PROC_CACHE_H

/*
 * L1 cache
 */
#define L1_CACHE_NWAYS		4		/* number of ways in caches */
#define L1_CACHE_NENTRIES	128		/* number of entries in each way */
#define L1_CACHE_BYTES		32		/* bytes per entry */
#define L1_CACHE_SHIFT		5		/* shift for bytes per entry */
#define L1_CACHE_WAYDISP	0x1000		/* distance from one way to the next */

#define L1_CACHE_TAG_VALID	0x00000001	/* cache tag valid bit */
#define L1_CACHE_TAG_DIRTY	0x00000008	/* data cache tag dirty bit */
#define L1_CACHE_TAG_ENTRY	0x00000fe0	/* cache tag entry address mask */
#define L1_CACHE_TAG_ADDRESS	0xfffff000	/* cache tag line address mask */
#define L1_CACHE_TAG_MASK	+(L1_CACHE_TAG_ADDRESS|L1_CACHE_TAG_ENTRY)

/*
 * specification of the interval between interrupt checking intervals whilst
 * managing the cache with the interrupts disabled
 */
#define MN10300_DCACHE_INV_RANGE_INTR_LOG2_INTERVAL	4

/*
 * The size of range at which it becomes more economical to just flush the
 * whole cache rather than trying to flush the specified range.
 */
#define MN10300_DCACHE_FLUSH_BORDER \
	+(L1_CACHE_NWAYS * L1_CACHE_NENTRIES * L1_CACHE_BYTES)
#define MN10300_DCACHE_FLUSH_INV_BORDER	\
	+(L1_CACHE_NWAYS * L1_CACHE_NENTRIES * L1_CACHE_BYTES)

#endif /* _ASM_PROC_CACHE_H */


text:
namespace WTF {
template <>
struct CrossThreadCopier<blink::V8WorkerMemoryReporter::WorkerMemoryUsage>
    : public CrossThreadCopierPassThrough<
          blink::V8WorkerMemoryReporter::WorkerMemoryUsage> {
  STATIC_ONLY(CrossThreadCopier);
};
}  // namespace WTF

namespace blink {

const base::TimeDelta V8WorkerMemoryReporter::kTimeout = base::Seconds(60);

namespace {

// TODO(906991): Remove this once PlzDedicatedWorker ships. Until then
// the browser does not know URLs of dedicated workers, so we pass them
// together with the measurement result. We limit the max length of the
// URLs to reduce memory allocations and the traffic between the renderer
// and the browser processes.
constexpr size_t kMaxReportedUrlLength = 2000;

// This delegate is provided to v8::Isolate::MeasureMemory API.
// V8 calls MeasurementComplete with the measurement result.
//
// All functions of this delegate are called on the worker thread.
class WorkerMeasurementDelegate : public v8::MeasureMemoryDelegate {
 public:
  WorkerMeasurementDelegate(
      base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter,
      WorkerThread* worker_thread,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : worker_memory_reporter_(std::move(worker_memory_reporter)),
        worker_thread_(worker_thread),
        task_runner_(task_runner) {
    DCHECK(worker_thread_->IsCurrentThread());
  }

  ~WorkerMeasurementDelegate() override;

  // v8::MeasureMemoryDelegate overrides.
  bool ShouldMeasure(v8::Local<v8::Context> context) override { return true; }
  void MeasurementComplete(
      const std::vector<std::pair<v8::Local<v8::Context>, size_t>>&
          context_sizes,
      size_t unattributed_size) override;

 private:
  void NotifyMeasurementSuccess(
      std::unique_ptr<V8WorkerMemoryReporter::WorkerMemoryUsage> memory_usage);
  void NotifyMeasurementFailure();
  base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter_;
  WorkerThread* worker_thread_;
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  bool did_notify_ = false;
};

WorkerMeasurementDelegate::~WorkerMeasurementDelegate() {
  DCHECK(worker_thread_->IsCurrentThread());
  if (!did_notify_) {
    // This may happen if the worker shuts down before completing
    // memory measurement.
    NotifyMeasurementFailure();
  }
}

void WorkerMeasurementDelegate::MeasurementComplete(
    const std::vector<std::pair<v8::Local<v8::Context>, size_t>>& context_sizes,
    size_t unattributed_size) {
  DCHECK(worker_thread_->IsCurrentThread());
  WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
  DCHECK(global_scope);
  DCHECK_LE(context_sizes.size(), 1u);
  size_t bytes = unattributed_size;
  for (auto& context_size : context_sizes) {
    bytes += context_size.second;
  }
  auto* worker_global_scope = To<WorkerGlobalScope>(global_scope);
  auto memory_usage =
      std::make_unique<V8WorkerMemoryReporter::WorkerMemoryUsage>();
  memory_usage->token = worker_global_scope->GetWorkerToken();
  memory_usage->bytes = bytes;
  if (worker_global_scope->IsUrlValid() &&
      worker_global_scope->Url().GetString().length() < kMaxReportedUrlLength) {
    memory_usage->url = worker_global_scope->Url();
  }
  NotifyMeasurementSuccess(std::move(memory_usage));
}

void WorkerMeasurementDelegate::NotifyMeasurementFailure() {
  DCHECK(worker_thread_->IsCurrentThread());
  DCHECK(!did_notify_);
  V8WorkerMemoryReporter::NotifyMeasurementFailure(worker_thread_, task_runner_,
                                                   worker_memory_reporter_);
  did_notify_ = true;
}

void WorkerMeasurementDelegate::NotifyMeasurementSuccess(
    std::unique_ptr<V8WorkerMemoryReporter::WorkerMemoryUsage> memory_usage) {
  DCHECK(worker_thread_->IsCurrentThread());
  DCHECK(!did_notify_);
  V8WorkerMemoryReporter::NotifyMeasurementSuccess(worker_thread_, task_runner_,
                                                   worker_memory_reporter_,
                                                   std::move(memory_usage));
  did_notify_ = true;
}

}  // anonymous namespace

// static
void V8WorkerMemoryReporter::GetMemoryUsage(ResultCallback callback,
                                            v8::MeasureMemoryExecution mode) {
  DCHECK(IsMainThread());
  // The private constructor prevents us from using std::make_unique here.
  std::unique_ptr<V8WorkerMemoryReporter> worker_memory_reporter(
      new V8WorkerMemoryReporter(std::move(callback)));
  auto main_thread_task_runner =
      Thread::MainThread()->GetTaskRunner(MainThreadTaskRunnerRestricted());
  // Worker tasks get a weak pointer to the instance for passing it back
  // to the main thread in OnMeasurementSuccess and OnMeasurementFailure.
  // Worker tasks never dereference the weak pointer.
  unsigned worker_count = WorkerThread::CallOnAllWorkerThreads(
      &V8WorkerMemoryReporter::StartMeasurement, TaskType::kInternalDefault,
      main_thread_task_runner, worker_memory_reporter->GetWeakPtr(), mode);
  if (worker_count == 0) {
    main_thread_task_runner->PostTask(
        FROM_HERE, WTF::Bind(&V8WorkerMemoryReporter::InvokeCallback,
                             std::move(worker_memory_reporter)));
    return;
  }
  worker_memory_reporter->SetWorkerCount(worker_count);
  // Transfer the ownership of the instance to the timeout task.
  main_thread_task_runner->PostDelayedTask(
      FROM_HERE,
      WTF::Bind(&V8WorkerMemoryReporter::OnTimeout,
                std::move(worker_memory_reporter)),
      kTimeout);
}

// static
void V8WorkerMemoryReporter::StartMeasurement(
    WorkerThread* worker_thread,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter,
    v8::MeasureMemoryExecution measurement_mode) {
  DCHECK(worker_thread->IsCurrentThread());
  WorkerOrWorkletGlobalScope* global_scope = worker_thread->GlobalScope();
  DCHECK(global_scope);
  v8::Isolate* isolate = worker_thread->GetIsolate();
  if (global_scope->IsWorkerGlobalScope()) {
    auto delegate = std::make_unique<WorkerMeasurementDelegate>(
        std::move(worker_memory_reporter), worker_thread,
        std::move(task_runner));
    isolate->MeasureMemory(std::move(delegate), measurement_mode);
  } else {
    // TODO(ulan): Add support for worklets once we get tokens for them. We
    // need to careful to not trigger GC on a worklet because usually worklets
    // are soft real-time and are written to avoid GC.
    // For now we simply notify a failure so that the main thread doesn't wait
    // for a response from the worklet.
    NotifyMeasurementFailure(worker_thread, std::move(task_runner),
                             worker_memory_reporter);
  }
}

// static
void V8WorkerMemoryReporter::NotifyMeasurementSuccess(
    WorkerThread* worker_thread,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter,
    std::unique_ptr<WorkerMemoryUsage> memory_usage) {
  DCHECK(worker_thread->IsCurrentThread());
  PostCrossThreadTask(
      *task_runner, FROM_HERE,
      CrossThreadBindOnce(&V8WorkerMemoryReporter::OnMeasurementSuccess,
                          worker_memory_reporter, std::move(memory_usage)));
}

// static
void V8WorkerMemoryReporter::NotifyMeasurementFailure(
    WorkerThread* worker_thread,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter) {
  DCHECK(worker_thread->IsCurrentThread());
  PostCrossThreadTask(
      *task_runner, FROM_HERE,
      CrossThreadBindOnce(&V8WorkerMemoryReporter::OnMeasurementFailure,
                          worker_memory_reporter));
}

void V8WorkerMemoryReporter::OnMeasurementFailure() {
  DCHECK(IsMainThread());
  if (state_ == State::kDone)
    return;
  ++failure_count_;
  if (success_count_ + failure_count_ == worker_count_) {
    InvokeCallback();
    DCHECK_EQ(state_, State::kDone);
  }
}

void V8WorkerMemoryReporter::OnMeasurementSuccess(
    std::unique_ptr<WorkerMemoryUsage> memory_usage) {
  DCHECK(IsMainThread());
  if (state_ == State::kDone)
    return;
  result_.workers.emplace_back(*memory_usage);
  ++success_count_;
  if (success_count_ + failure_count_ == worker_count_) {
    InvokeCallback();
    DCHECK_EQ(state_, State::kDone);
  }
}

void V8WorkerMemoryReporter::SetWorkerCount(unsigned worker_count) {
  DCHECK(IsMainThread());
  DCHECK_EQ(0u, worker_count_);
  worker_count_ = worker_count;
}

void V8WorkerMemoryReporter::OnTimeout() {
  DCHECK(IsMainThread());
  if (state_ == State::kDone)
    return;
  InvokeCallback();
  DCHECK_EQ(state_, State::kDone);
}

void V8WorkerMemoryReporter::InvokeCallback() {
  DCHECK(IsMainThread());
  DCHECK_EQ(state_, State::kWaiting);
  std::move(callback_).Run(std::move(result_));
  state_ = State::kDone;
}

}  // namespace blink


text:
if [ -z "$BASH_VERSION" -a -z "$ZSH_VERSION" ] ; then
    echo This script only works with bash or zsh as the interactive shell.
    echo Please retry with bash or zsh.
    return 1
fi

function setupGitSubmodules() {
    local choice=$1
    if [[ $2 == "accept-eula" ]] ; then
        local eula=true
    fi
    echo "You selected target $choice"

    local targets=(
        "dragonboard-410c"
        "koelsch"
        "minnowboard"
        "porter"
        "qemux86-64"
        "r-car-m3-starter-kit"
        "r-car-h3-starter-kit"
        "raspberrypi2"
        "raspberrypi3"
        "silk")
    local supported=(
        "minnowboard"
        "qemux86-64"
        "r-car-m3-starter-kit"
        "r-car-h3-starter-kit"
        "raspberrypi2"
        "raspberrypi3")
    local modules=()
    local target=""

    for i in ${targets[@]}
    do
        if [[ $i == $choice ]]
        then
            target=$choice
            echo "$target is a valid target"
            break
        fi
    done

    if test -z "$target" ; then
        echo "An invalid or empty target name was given: $choice  Available targets are:"
        printf '%s\n' "${targets[@]}"
        echo -e "\nUsage: source init.sh <target> [accept-eula] [-f]"
        return 1
    else
        if [[ ! ${supported[@]} =~ "$target" ]] && [[ ${!#} != "-f" ]]; then
            echo "However currently, only the following targets are officially supported:"
            printf '%s\n' "${supported[@]}"
            echo "You can try to run it anyway by adding -f flag, or use a supported target"
            echo "or check if your hardware was fully supported on an earlier release:"
            echo "   git checkout origin/gdp-<version> and then re-run"
            echo "   source init.sh $machine"
            return 1
        fi
    fi

    if [[ "$target" == "dragonboard-410c" ]] && test -z "$eula" ; then
        echo "Building GDP for DragonBoard 410c requires Qualcomm EULA acceptance."
        echo "See http://git.yoctoproject.org/cgit/cgit.cgi/meta-qcom/tree/conf/EULA for details."
        echo "Please re-run init.sh with additional 'accept-eula' argument"
        return 1
    fi

    echo "Generating bitbake configuration files for $target"

    cp gdp-src-build/conf/templates/${target}.local.conf gdp-src-build/conf/local.conf
    cp gdp-src-build/conf/templates/${target}.bblayers.conf gdp-src-build/conf/bblayers.conf

    # Accept EULA in local.conf
    if [[ $target == "dragonboard-410c" ]] ; then
        echo "ACCEPT_EULA_dragonboard-410c = "'"1"'"" >> gdp-src-build/conf/local.conf
    fi

    echo "Local & bblayers conf set for $target"

    # Define hardware-dependent layers.
    # Multiple layers can be specified for a target if space-separated.
    declare -A bsparr
    bsparr["qemux86-64"]=""
    bsparr["minnowboard"]="meta-intel"
    bsparr["raspberrypi2"]="meta-raspberrypi"
    bsparr["raspberrypi3"]="meta-raspberrypi"
    bsparr["koelsch"]="meta-renesas"
    bsparr["porter"]="meta-renesas"
    bsparr["silk"]="meta-renesas"
    bsparr["dragonboard-410c"]="meta-qcom"
    bsparr["r-car-m3-starter-kit"]="meta-linaro meta-renesas meta-ivi-renesas"
    bsparr["r-car-h3-starter-kit"]="meta-linaro meta-renesas meta-ivi-renesas"

    # This looks somewhat complex but the intention is to clone only needed
    # submodules.  The module list is calculated as : all the submodules we
    # have (as reported by git) *minus* BSP-related layers that are NOT
    # relevant for the chosen $target.  In other words - loop through all BSP
    # layers and delete them from array unless they are the layer (or layers)
    # defined for this $target.
    modules=($(git submodule | awk '{ print $2 }'))

    for i in ${bsparr[@]}; do
        local found=false

        # Multiple BSP layers per target are supported so loop over them just in case
        for bsp in ${bsparr[${target}]} ; do
            if [[ $i == $bsp ]] ; then
                found=true
            fi
        done

        if ! $found ; then
            # This BSP is not for the $target, so delete it from the list
            modules=(${modules[@]//*$i*})
        fi
    done

    git submodule init "${modules[@]}"

    git submodule sync "${modules[@]}"

    git submodule update "${modules[@]}"

    return 0
}

if setupGitSubmodules $1 $2 $3 ; then
    source poky/oe-init-build-env gdp-src-build
    echo
    echo "Now run:  bitbake genivi-dev-platform"
else
    return 1
fi


text:
@interface XMPPXOAuth2Google : NSObject <XMPPSASLAuthentication>

-(id)initWithStream:(XMPPStream *)stream accessToken:(NSString *)accessToken;

@end

@interface XMPPStream (XMPPXOAuth2Google)

- (BOOL)supportsXOAuth2GoogleAuthentication;

- (BOOL)authenticateWithGoogleAccessToken:(NSString *)accessToken error:(NSError **)errPtr;

@end