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

package org.chromium.sync.test.util;

import android.accounts.Account;

import java.util.HashMap;
import java.util.Map;

/**
 * This class is used by the {@link MockAccountManager} to hold information about a given
 * account, such as its password and set of granted auth tokens.
 */
public class AccountHolder {

    private final Account mAccount;

    private final String mPassword;

    private final Map<String, String> mAuthTokens;

    private final Map<String, Boolean> mHasBeenAccepted;

    private final boolean mAlwaysAccept;

    private AccountHolder(Account account, String password, Map<String, String> authTokens,
            Map<String, Boolean> hasBeenAccepted, boolean alwaysAccept) {
        mAlwaysAccept = alwaysAccept;
        if (account == null) {
            throw new IllegalArgumentException("Account can not be null");
        }
        mAccount = account;
        mPassword = password;
        mAuthTokens = authTokens == null ? new HashMap<String, String>() : authTokens;
        mHasBeenAccepted = hasBeenAccepted == null ?
                new HashMap<String, Boolean>() : hasBeenAccepted;
    }

    public Account getAccount() {
        return mAccount;
    }

    public String getPassword() {
        return mPassword;
    }

    public boolean hasAuthTokenRegistered(String authTokenType) {
        return mAuthTokens.containsKey(authTokenType);
    }

    public String getAuthToken(String authTokenType) {
        return mAuthTokens.get(authTokenType);
    }

    public boolean hasBeenAccepted(String authTokenType) {
        return mAlwaysAccept ||
                mHasBeenAccepted.containsKey(authTokenType) && mHasBeenAccepted.get(authTokenType);
    }

    /**
     * Removes an auth token from the auth token map.
     *
     * @param authToken the auth token to remove
     * @return true if the auth token was found
     */
    public boolean removeAuthToken(String authToken) {
        String foundKey = null;
        for (Map.Entry<String, String> tokenEntry : mAuthTokens.entrySet()) {
            if (authToken.equals(tokenEntry.getValue())) {
                foundKey = tokenEntry.getKey();
                break;
            }
        }
        if (foundKey == null) {
            return false;
        } else {
            mAuthTokens.remove(foundKey);
            return true;
        }
    }

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

    @Override
    public boolean equals(Object that) {
        return that != null && that instanceof AccountHolder && mAccount
                .equals(((AccountHolder) that).getAccount());
    }

    public static Builder create() {
        return new Builder();
    }

    public AccountHolder withPassword(String password) {
        return copy().password(password).build();
    }

    public AccountHolder withAuthTokens(Map<String, String> authTokens) {
        return copy().authTokens(authTokens).build();
    }

    public AccountHolder withAuthToken(String authTokenType, String authToken) {
        return copy().authToken(authTokenType, authToken).build();
    }

    public AccountHolder withHasBeenAccepted(String authTokenType, boolean hasBeenAccepted) {
        return copy().hasBeenAccepted(authTokenType, hasBeenAccepted).build();
    }

    public AccountHolder withAlwaysAccept(boolean alwaysAccept) {
        return copy().alwaysAccept(alwaysAccept).build();
    }

    private Builder copy() {
        return create().account(mAccount).password(mPassword).authTokens(mAuthTokens).
                hasBeenAcceptedMap(mHasBeenAccepted).alwaysAccept(mAlwaysAccept);
    }

    public static class Builder {

        private Account mTempAccount;

        private String mTempPassword;

        private Map<String, String> mTempAuthTokens;

        private Map<String, Boolean> mTempHasBeenAccepted;

        private boolean mTempAlwaysAccept;

        public Builder account(Account account) {
            mTempAccount = account;
            return this;
        }

        public Builder password(String password) {
            mTempPassword = password;
            return this;
        }

        public Builder authToken(String authTokenType, String authToken) {
            if (mTempAuthTokens == null) {
                mTempAuthTokens = new HashMap<String, String>();
            }
            mTempAuthTokens.put(authTokenType, authToken);
            return this;
        }

        public Builder authTokens(Map<String, String> authTokens) {
            mTempAuthTokens = authTokens;
            return this;
        }

        public Builder hasBeenAccepted(String authTokenType, boolean hasBeenAccepted) {
            if (mTempHasBeenAccepted == null) {
                mTempHasBeenAccepted = new HashMap<String, Boolean>();
            }
            mTempHasBeenAccepted.put(authTokenType, hasBeenAccepted);
            return this;
        }

        public Builder hasBeenAcceptedMap(Map<String, Boolean> hasBeenAcceptedMap) {
            mTempHasBeenAccepted = hasBeenAcceptedMap;
            return this;
        }

        public Builder alwaysAccept(boolean alwaysAccept) {
            mTempAlwaysAccept = alwaysAccept;
            return this;
        }

        public AccountHolder build() {
            return new AccountHolder(mTempAccount, mTempPassword, mTempAuthTokens,
                    mTempHasBeenAccepted, mTempAlwaysAccept);
        }
    }

}


text:
/**
 * @file libohiboard/source/STM32L0/dac_STM32L0.c
 * @author Niccolò Paolinelli <nico.paolinelli@gmail.com>
 * @brief DAC implementations for STM32L0 series.
 */

#ifdef LIBOHIBOARD_DAC

#ifdef __cplusplus
extern "C" {
#endif

#include "platforms.h"

#if defined (LIBOHIBOARD_STM32L0)

#include "dac.h"

#include "utility.h"
#include "gpio.h"
#include "clock.h"
#include "interrupt.h"

#define DAC_CLOCK_ENABLE(REG,MASK) do {                                         \
                                     UTILITY_SET_REGISTER_BIT(REG,MASK);        \
                                     asm("nop");                                \
                                     (void) UTILITY_READ_REGISTER_BIT(REG,MASK);\
                                   } while (0)

#define DAC_CLOCK_DISABLE(REG,MASK) do {                                         \
                                      UTILITY_CLEAR_REGISTER_BIT(REG,MASK);      \
                                      asm("nop");                                \
                                      (void) UTILITY_READ_REGISTER_BIT(REG,MASK);\
                                    } while (0)

/**
 * Enable selected channel of peripheral
 */
#define DAC_DEVICE_ENABLE(DEVICE,CHANNEL)     \
    UTILITY_SET_REGISTER_BIT(DEVICE->regmap->CR,(DAC_CR_EN1 << ((CHANNEL) & DAC_CHANNEL_SHIFT_MASK)))

/**
 * Disable selected channel of peripheral
 */
#define DAC_DEVICE_DISABLE(DEVICE,CHANNEL)     \
    UTILITY_CLEAR_REGISTER_BIT(DEVICE->regmap->CR,(DAC_CR_EN1 << ((CHANNEL) & DAC_CHANNEL_SHIFT_MASK)))

#define DAC_MAX_PINS                     2

/**
 * Check whether the sample-and-hold mode is valid or not.
 */
#define DAC_VALID_SAMPLE_AND_HOLD(SAH) (((SAH) == UTILITY_STATE_DISABLE) || \
                                        ((SAH) == UTILITY_STATE_ENABLE))

/**
 * Check whether the sample time is into valid range.
 */
#define DAC_VALID_SAH_SAMPLE_TIME(TIME) ((TIME) < 1024ul)

/**
 * Check whether the hold time is into valid range.
 */
#define DAC_VALID_SAH_HOLD_TIME(TIME) ((TIME) < 1024ul)

/**
 * Check whether the refresh time is into valid range.
 */
#define DAC_VALID_SAH_REFRESH_TIME(TIME) ((TIME) < 256ul)

/**
 * Check whether the output buffer condition is valid or not.
 */
#define DAC_VALID_OUTPUT_BUFFER(OUTPUT) (((OUTPUT) == UTILITY_STATE_DISABLE) || \
                                         ((OUTPUT) == UTILITY_STATE_ENABLE))

/**
 * Check whether the internal connection to peripheral condition is valid or not.
 */
#define DAC_VALID_INTERNAL_CONNECTION(CONNECTION) (((CONNECTION) == UTILITY_STATE_DISABLE) || \
                                                   ((CONNECTION) == UTILITY_STATE_ENABLE))

/**
 * Check whether the data align type is valid or not.
 */
#define DAC_VALID_DATA_ALIGN(ALIGN) (((ALIGN) == DAC_DATAALIGN_12BIT_RIGHT) || \
                                     ((ALIGN) == DAC_DATAALIGN_12BIT_LEFT)  || \
                                     ((ALIGN) == DAC_DATAALIGN_8BIT_RIGHT))

/**
 *
 */
typedef struct _Dac_Device
{
    DAC_TypeDef* regmap;                           /**< Device memory pointer */

    volatile uint32_t* rccRegisterPtr;       /**< Register for clock enabling */
    uint32_t rccRegisterEnable;         /**< Register mask for current device */

    Dac_Pins pins[DAC_MAX_PINS];      /**< List of the pin for the peripheral */
    Dac_Channels pinsChannel[DAC_MAX_PINS];
    Gpio_Pins pinsGpio[DAC_MAX_PINS];

    Interrupt_Vector isrNumber;                        /**< ISR vector number */

    Dac_DeviceState state;                      /**< Current peripheral state */

    Dac_Config config;                                /**< User configuration */

    /** Channel configurations */
    Dac_ChannelConfig channelConfig[DAC_MAX_PINS];

} Dac_Device;

#if defined (LIBOHIBOARD_STM32L072)

#define DAC_IS_DEVICE(DEVICE) ((DEVICE) == OB_DAC1)

static Dac_Device dac1 =
{
        .regmap              = DAC1,

        .rccRegisterPtr      = &RCC->APB1ENR,
        .rccRegisterEnable   = RCC_APB1ENR_DACEN,

        .pins                =
        {
                               DAC_PINS_PA4,
                               DAC_PINS_PA5,
        },
        .pinsChannel         =
        {
                               DAC_CHANNELS_CH1,
                               DAC_CHANNELS_CH2,
        },
        .pinsGpio            =
        {
                               GPIO_PINS_PA4,
                               GPIO_PINS_PA5,
        },

        .state               = DAC_DEVICESTATE_RESET,
};
Dac_DeviceHandle OB_DAC1 = &dac1;

#endif

/**
 * This function save data into the correct register for specific data
 * alignment.
 *
 * @param[in] dev Dac device handle
 * @param[in] channel The selected channel
 * @param[in] align The alignment type
 * @param[in] data The aligned data to write.
 */
static inline void __attribute__((always_inline)) Dac_setDataAligned (Dac_DeviceHandle dev,
                                                                      Dac_Channels channel,
                                                                      Dac_DataAlign align,
                                                                      uint32_t data)
{
    // Save offset to get correct register
    // The startup position is DAC_DHR12R1
    uint32_t tmp = 0x00000008;
    switch (channel)
    {
    case DAC_CHANNELS_CH1:
        tmp += 0x00000000;
        break;
    case DAC_CHANNELS_CH2:
        tmp += 0x00000006;
        break;
    }
    // Add value of align parameter to found the correct register
    tmp += (uint32_t)align;

    // Get register
    volatile uint32_t* dhrReg = (volatile uint32_t*)((uint32_t)((uint32_t)(&dev->regmap->CR) + tmp));
    *dhrReg = data;
}

System_Errors Dac_init (Dac_DeviceHandle dev, Dac_Config* config)
{
    (void) config;

    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }

    // Enable peripheral clock if needed
    if (dev->state == DAC_DEVICESTATE_RESET)
    {
        // Enable peripheral clock
        DAC_CLOCK_ENABLE(*dev->rccRegisterPtr,dev->rccRegisterEnable);
    }

    dev->state = DAC_DEVICESTATE_READY;
    return ERRORS_NO_ERROR;
}

System_Errors Dac_deInit (Dac_DeviceHandle dev)
{
    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }

    DAC_CLOCK_DISABLE(*dev->rccRegisterPtr,dev->rccRegisterEnable);

    dev->state = DAC_DEVICESTATE_RESET;
    return ERRORS_NO_ERROR;
}

System_Errors Dac_configPin (Dac_DeviceHandle dev, Dac_ChannelConfig* config, Dac_Pins pin)
{
    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }

    ohiassert(DAC_VALID_INTERNAL_CONNECTION(config->internalConnect));
    ohiassert(DAC_VALID_OUTPUT_BUFFER(config->outputBuffer));
    ohiassert(DAC_VALID_DATA_ALIGN(config->align));

    // Select relative channel
    Dac_Channels channel;
    for (uint16_t i = 0; i < DAC_MAX_PINS; ++i)
    {
        if (dev->pins[i] == pin)
        {
            Gpio_configAlternate(dev->pinsGpio[i],
                                 GPIO_ALTERNATE_ANALOG,
                                 0);
            channel = dev->pinsChannel[i];
            break;
        }
    }

    dev->state = DAC_DEVICESTATE_BUSY;

    // Save configuration

    uint32_t tmpreg = 0;

    // Disable wave generation and trigger
    tmpreg = dev->regmap->CR;
    tmpreg &= (~(((uint32_t)(DAC_CR_MAMP1_Msk | DAC_CR_WAVE1_Msk | DAC_CR_TSEL1_Msk | DAC_CR_TEN1_Msk)) << (channel & DAC_CHANNEL_SHIFT_MASK)));

    // Configure Trigger: TSELx and TENx bits
    tmpreg |= ((config->trigger) << (channel & DAC_CHANNEL_SHIFT_MASK));

    // Save CR configuration
    dev->regmap->CR = tmpreg;

    // Save channel configuration
    dev->channelConfig[DAC_CHANNEL_NUMBER(channel)] = *config;

    dev->state = DAC_DEVICESTATE_READY;
    return ERRORS_NO_ERROR;
}

System_Errors Dac_start (Dac_DeviceHandle dev, Dac_Channels channel)
{
    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }
    dev->state = DAC_DEVICESTATE_BUSY;

    // Enable peripheral and selected channel
    DAC_DEVICE_ENABLE(dev,channel);

    // Send software trigger, if needed!
    switch (channel)
    {
    case DAC_CHANNELS_CH1:
        if ((dev->regmap->CR & DAC_TRIGGER_SOFTWARE) == DAC_TRIGGER_SOFTWARE)
        {
            dev->regmap->SWTRIGR |= DAC_SWTRIGR_SWTRIG1;
        }
        break;
    case DAC_CHANNELS_CH2:
        if ((dev->regmap->CR & (DAC_TRIGGER_SOFTWARE << (channel & DAC_CHANNEL_SHIFT_MASK))) ==
            (DAC_TRIGGER_SOFTWARE << (channel & DAC_CHANNEL_SHIFT_MASK)))
        {
            dev->regmap->SWTRIGR |= DAC_SWTRIGR_SWTRIG2;
        }
        break;
    }

    dev->state = DAC_DEVICESTATE_READY;
    return ERRORS_NO_ERROR;
}

System_Errors Dac_stop (Dac_DeviceHandle dev, Dac_Channels channel)
{
    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }
    dev->state = DAC_DEVICESTATE_BUSY;

    // Disable peripheral and selected channel
    DAC_DEVICE_DISABLE(dev,channel);

    dev->state = DAC_DEVICESTATE_READY;
    return ERRORS_NO_ERROR;
}

System_Errors Dac_write (Dac_DeviceHandle dev, Dac_Channels channel, uint32_t value)
{
    // Check the DAC device
    if (dev == NULL)
    {
        return ERRORS_DAC_NO_DEVICE;
    }
    // Check the DAC instance
    if (ohiassert(DAC_IS_DEVICE(dev)) != ERRORS_NO_ERROR)
    {
        return ERRORS_DAC_WRONG_DEVICE;
    }

    Dac_setDataAligned(dev,channel,dev->channelConfig[DAC_CHANNEL_NUMBER(channel)].align,value);

    return ERRORS_NO_ERROR;
}

#endif // LIBOHIBOARD_STM32L0

#ifdef __cplusplus
}
#endif

#endif // LIBOHIBOARD_DAC

redpajama_set_name: RedPajamaGithub


text:
#region Copyright
// <copyright file="TestRemoteType.cs" company="OpenEngSB">
// Licensed to the Austrian Association for Software Tool Integration (AASTI)
// under one or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information regarding copyright
// ownership. The AASTI licenses this file to you 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.
// </copyright>
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Org.Openengsb.Loom.CSharp.Bridge.Implementation.Common;
using Org.Openengsb.Loom.CSharp.Bridge.Implementation.Exceptions;

namespace BridgeTests.Tests
{
    [TestClass]
    [ExcludeFromCodeCoverageAttribute]
    public class TestRemoteType
    {
        #region Tests
        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaDoubleTypeWhenAskingTheLocalType()
        {
            ParameterInfo[] pr = typeof(BridgeTests.TestClasses.TestClassLocalType).GetMethod("hasDoubleSpecified").GetParameters();
            RemoteType lt = new RemoteType("java.lang.Double", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(Double).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaDoubleTypeWhenAskingTheLocalTypeAndNoParameterInfoArePresent()
        {
            ParameterInfo[] pr = null;
            RemoteType lt = new RemoteType("java.lang.DoubleExtend", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(Double).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaFloatTypeWhenAskingTheLocalType()
        {
            ParameterInfo[] pr = typeof(BridgeTests.TestClasses.TestClassLocalType).GetMethod("hasFloatSpecified").GetParameters();
            RemoteType lt = new RemoteType("java.lang.Float", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(float).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaFloatTypeWhenAskingTheLocalTypeAndNoParameterInfoArePresent()
        {
            ParameterInfo[] pr = null;
            RemoteType lt = new RemoteType("java.lang.FloatExtend", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(float).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaIntTypeWhenAskingTheLocalType()
        {
            ParameterInfo[] pr = typeof(BridgeTests.TestClasses.TestClassLocalType).GetMethod("hasIntSpecified").GetParameters();
            RemoteType lt = new RemoteType("java.lang.Integer", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(int).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaIntTypeWhenAskingTheLocalTypeAndNoParameterInfoArePresent()
        {
            ParameterInfo[] pr = null;
            RemoteType lt = new RemoteType("java.lang.IntegerExtend", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(int).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaStringTypeWhenAskingTheLocalType()
        {
            ParameterInfo[] pr = typeof(BridgeTests.TestClasses.TestClassLocalType).GetMethod("hasStringSpecified").GetParameters();
            RemoteType lt = new RemoteType("java.lang.String", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(String).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaStringTypeWhenAskingTheLocalTypeAndNoParameterInfoArePresent()
        {
            ParameterInfo[] pr = null;
            RemoteType lt = new RemoteType("java.lang.String", pr);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(String).FullName);
        }

        [TestMethod]
        public void TestIfRemoteTypeReturnstheCorrectJavaStringTypeWhenAskingTheLocalTypeAndNoParameterInfoArePresentAndTheInputContainsADollar()
        {
            RemoteType lt = new RemoteType("org.openengsb$String", null);

            Assert.AreEqual<String>(lt.LocalTypeFullName, typeof(String).FullName);
        }

        [TestMethod]
        [ExpectedException(typeof(BridgeException))]
        public void TestIfRemoteTypeReturnstheExceptionIfTheInputIsInvalid()
        {
            ParameterInfo[] pr = null;
            RemoteType lt = new RemoteType("WONG", pr);
        }
        #endregion
    }
}


text:
'use strict';

const PORT = process.env.PORT || 3000;

const SOURCE_DIR = process.env.SOURCE_DIR || './src';
const BUILD_DIR = process.env.BUILD_DIR || 'build';
const DIST_DIR = process.env.DIST_DIR || 'dist';

const assign = require('lodash.assign');
const browserify = require('browserify');
const browserSync = require('browser-sync').create();
const bundleCollapser = require('bundle-collapser/plugin');
const buffer = require('vinyl-buffer');
const del = require('del');
const envify = require('envify/custom');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const watchify = require('watchify');

const gulp = require('gulp');
const $ = require('gulp-load-plugins')();

const replaceAll = require('./replaceAll');

let production = false;

function onError(error) {
  $.util.log(error.message);
  this.emit('end');
}

gulp.task('browser-sync', () => {
  return browserSync.init({
    browser: [],
    port: PORT,
    server: {
      baseDir: './' + BUILD_DIR
    }
  });
});

gulp.task('js', () => {
  let bundler = browserify(SOURCE_DIR + '/js/index.js',
    assign({
      debug: !production
    }, production ? null : watchify.args));

  bundler.transform(envify({
    _: 'purge',
    NODE_ENV: production ? 'production' : 'development'
  }));

  if (production) {
    bundler.plugin(bundleCollapser);
  } else {
    bundler = watchify(bundler);
  }

  function rebundle() {
    return bundler.bundle()
      .on('error', onError)
      .pipe(source('bundle.js'))
      .pipe(buffer())
      .pipe($.if(production, $.uglify()))
      .pipe($.if(production, replaceAll()))
      .pipe(gulp.dest(BUILD_DIR + '/js'))
      .pipe($.if(!production, browserSync.reload({ stream: true })));
  }

  bundler
    .on('log', $.util.log)
    .on('update', rebundle);

  return rebundle();
});

gulp.task('html', () => {
  return gulp.src(SOURCE_DIR + '/*.html')
    .pipe($.if(production, $.htmlmin({
      collapseWhitespace: true,
      removeAttributeQuotes: true,
      removeComments: true,
      minifyCSS: true
    })))
    .pipe(gulp.dest(BUILD_DIR))
    .pipe($.if(!production, browserSync.reload({ stream: true })));
});

gulp.task('clean', () => del([BUILD_DIR]));

gulp.task('watch', () => gulp.watch([SOURCE_DIR + '/*.html'], ['html']));

gulp.task('default', ['clean'], cb => {
  return runSequence(
    ['html', 'js'],
    ['browser-sync', 'watch'],
    cb
  );
});

gulp.task('build', ['clean'], cb => {
  production = true;
  return runSequence(
    ['html', 'js'],
    cb
  );
});

gulp.task('compress', () => {
  return gulp.src(BUILD_DIR + '/**/*')
    .pipe($.zip('build.zip'))
    .pipe($.size())
    .pipe($.size({ pretty: false }))
    .pipe($.micro({ limit: 13 * 1024 }))
    .pipe(gulp.dest(DIST_DIR));
});

gulp.task('dist', cb => runSequence('build', 'compress', cb));


text:
package org.dasein.cloud.utils.requester.fluent;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.dasein.cloud.utils.requester.*;
import org.dasein.cloud.utils.requester.streamprocessors.*;
import org.json.JSONObject;
import org.w3c.dom.Document;

import javax.annotation.Nonnull;

/**
 * DaseinRequest class is a wrapper for Apache HTTP client.
 *
 *

 *
 *     String result = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).execute();
 *     Document resultAsDocument = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).withDocumentProcessor().execute();
 *
 *

 *
 * @author Vlad Munthiu
* */

public class DaseinRequest implements CompositeRequester {
    private HttpClientBuilder httpClientBuilder;
    private HttpUriRequest httpUriRequestBuilder;
    private HttpProxyConfig httpProxyConfig;

    public DaseinRequest(@Nonnull HttpClientBuilder httpClientBuilder, @Nonnull HttpUriRequest httpUriRequestBuilder, @Nonnull String httpProxyHost, @Nonnull Integer httpProxyPort){
        if(httpClientBuilder == null)
            throw new IllegalArgumentException("Parameter httpClientBuilder cannot be null.");

        if(httpUriRequestBuilder == null)
            throw new IllegalArgumentException("Parameter httpUriRequestBuilder cannot be null");

        this.httpClientBuilder = httpClientBuilder;
        this.httpUriRequestBuilder = httpUriRequestBuilder;
        this.httpProxyConfig = new HttpProxyConfig(httpProxyHost, httpProxyPort);
    }
    /**
     * Constructs a new DaseinRequest instance, ready to execute http calls to a specified Uri.
     *
     * @param httpClientBuilder HTTP client builder
     * @param httpUriRequestBuilder HTTP URI request builder
    **/
    public DaseinRequest(@Nonnull HttpClientBuilder httpClientBuilder, @Nonnull HttpUriRequest httpUriRequestBuilder){
        if(httpClientBuilder == null)
            throw new IllegalArgumentException("Parameter httpClientBuilder cannot be null.");

        if(httpUriRequestBuilder == null)
            throw new IllegalArgumentException("Parameter httpUriRequestBuilder cannot be null");

        this.httpClientBuilder = httpClientBuilder;
        this.httpUriRequestBuilder = httpUriRequestBuilder;
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a XML stream processor that, once the HTTP request has been
     * finished, will perform a deserialization of the XML response into the specified type T.
     *
     *

     *     DaseinDriverType result = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).withXmlProcessor(DaseinDriverType.class).execute();
     *

     *
     * @param classType the type of the expected model
     * @return an instance of the classType type representing the response XML
    **/
    @Override
    public <T> Requester<T> withXmlProcessor(@Nonnull Class<T> classType) {
        if(classType == null)
            throw new IllegalArgumentException("Parameter classType cannot be null");

        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<T>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<T>(new XmlStreamToObjectProcessor(), classType));
        } else {
            return new DaseinRequestExecutor<T>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<T>(new XmlStreamToObjectProcessor(), classType), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a XML stream processor that, once the HTTP request has been
     * finished, will perform a deserialization of the XML response into the specified type T. A valid instance of a
     * ObjectMapper should be passed in, so that a mapping from a driver model type ( T ) to a Dasein Core
     * model( V ) to be performed after the response is received.
     *
     *

     *     DaseinCoreType result = new DaseinRequest(cloudProvider, httpClientBuilder, httpUriRequestBuilder)
     *                  .withXmlProcessor(new ObjectMapper<DaseinDriverType, DaseinCoreType>() {
     *                           @Override
     *                           public DaseinCoreType mapFrom(DaseinDriverType entity) {
     *                                  //map entity to a new instance of DaseinCoreType
     *                           }
     *                      DaseinDriverType.class).execute();
     *

     *
     * @param mapper an implementation of {@link org.dasein.cloud.utils.requester.ObjectMapper} interface
     * @param classType the type of the expected model
     * @return an instance of the V type which should be a Dasien Core type.
     **/
    @Override
    public <T, V> Requester<V> withXmlProcessor(@Nonnull ObjectMapper<T, V> mapper, @Nonnull Class<T> classType) {
        if(mapper == null)
            throw new IllegalArgumentException("Parameter mapper cannot be null");

        if(classType == null)
            throw new IllegalArgumentException("Parameter classType cannot be null");

        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<V>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandlerWithMapper<T, V>(new XmlStreamToObjectProcessor(), mapper, classType));
        } else {
            return new DaseinRequestExecutor<V>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandlerWithMapper<T, V>(new XmlStreamToObjectProcessor(), mapper, classType), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a JSON stream processor that, once the HTTP request has been
     * finished will perform a deserialization of the JSON response into the specified type T.
     *
     *

     *     DaseinDriverType result = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).withJsonProcessor(DaseinDriverType.class).execute();
     *

     *
     * @param classType the type of the expected model
     * @return an instance of the classType type representing the response JSON
     **/
    @Override
    public <T> Requester<T> withJsonProcessor(@Nonnull Class<T> classType) {
        if(classType == null)
            throw new IllegalArgumentException("Parameter classType cannot be null");

        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<T>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<T>(new JsonStreamToObjectProcessor(), classType));
        } else {
            return new DaseinRequestExecutor<T>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<T>(new JsonStreamToObjectProcessor(), classType), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a JSON stream processor that, once the HTTP request has been
     * finished, will perform a deserialization of the JSON response into the specified type T. A valid instance of a
     * ObjectMapper should be passed in, so that a mapping from a driver model type ( T ) to a Dasein Core
     * model( V ) to be performed after the response is received.
     *
     *

     *     DaseinCoreType result = new DaseinRequest(cloudProvider, httpClientBuilder, httpUriRequestBuilder)
     *                  .withJsonProcessor(new ObjectMapper<DaseinDriverType, DaseinCoreType>() {
     *                           @Override
     *                           public DaseinCoreType mapFrom(DaseinDriverType entity) {
     *                                  //map entity to a new instance of DaseinCoreType
     *                           }
     *                      DaseinDriverType.class).execute();
     *

     *
     * @param mapper an implementation of {@link org.dasein.cloud.utils.requester.ObjectMapper} interface
     * @param classType the type of the expected model
     * @return an instance of the V type which should be a Dasien Core type.
     **/
    @Override
    public <T, V> Requester<V> withJsonProcessor(@Nonnull ObjectMapper<T, V> mapper, @Nonnull Class<T> classType) {
        if(mapper == null)
            throw new IllegalArgumentException("Parameter mapper cannot be null");

        if(classType == null)
            throw new IllegalArgumentException("Parameter classType cannot be null");

        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<V>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandlerWithMapper<T, V>(new JsonStreamToObjectProcessor(), mapper, classType));
        } else {
            return new DaseinRequestExecutor<V>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandlerWithMapper<T, V>(new JsonStreamToObjectProcessor(), mapper, classType), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a stream processor that, once the HTTP request has been
     * finished, will try to parse the response stream into a valid XML Document object.
     *
     *

     *     Document documentResult = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).withDocumentProcessor().execute();
     *

    **/
    @Override
    public <T> DaseinRequestExecutor<Document> withDocumentProcessor() {
        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<Document>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<Document>(new StreamToDocumentProcessor(), Document.class));
        } else {
            return new DaseinRequestExecutor<Document>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<Document>(new StreamToDocumentProcessor(), Document.class), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Constructs a instance of a DaseinRequestExecutor with a stream processor that, once the HTTP request has been
     * finished, will try to parse the response stream into a valid JSONObject object.
     *
     *

     *     JSONObject jsonResult = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).withJSONObjectProcessor().execute();
     *

     **/
    @Override
    public <T> DaseinRequestExecutor<JSONObject> withJSONObjectProcessor() {
        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<JSONObject>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<JSONObject>(new StreamToJSONObjectProcessor(), JSONObject.class));
        } else {
            return new DaseinRequestExecutor<JSONObject>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<JSONObject>(new StreamToJSONObjectProcessor(), JSONObject.class), httpProxyConfig.getHost(), httpProxyConfig.getPort());
        }
    }

    /**
     * Executes a HTTP request using a string processor for the response.
     *
     *

     *     String result = new DaseinRequest(httpClientBuilder, httpUriRequestBuilder).execute();
     *

     *
     * @return a string representing the response of the current HTTP call.
    **/
    @Override
    public String execute() throws DaseinRequestException {
        if(httpProxyConfig == null) {
            return new DaseinRequestExecutor<String>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<String>(new StreamToStringProcessor(), String.class)).execute();
        } else {
            return new DaseinRequestExecutor<String>(this.httpClientBuilder, this.httpUriRequestBuilder,
                    new DaseinResponseHandler<String>(new StreamToStringProcessor(), String.class), httpProxyConfig.getHost(), httpProxyConfig.getPort()).execute();
        }
    }
}


text:
<?php
/**
 * @LICENSE_TEXT
 */

namespace Che\CrackPack\Console\Command\Repository;

use Che\CrackPack\Package\OverriddenPackageLoader;
use Composer\Json\JsonFile;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Loader\JsonLoader;
use Composer\Package\Loader\ValidatingArrayLoader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class AddPackageCommand
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class AddPackageCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('repository:add')
            ->addArgument('file', InputArgument::REQUIRED)
            ->addArgument('repository', InputArgument::OPTIONAL, '', 'packages.json')
            ->addOption('url', null, InputOption::VALUE_OPTIONAL)
            ->addOption('package-name', null, InputOption::VALUE_OPTIONAL)
            ->addOption('package-version', null, InputOption::VALUE_OPTIONAL)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $file = $input->getArgument('file');
        if (!is_readable($file)) {
            throw new \RuntimeException(sprintf('Can not open file "%s"', $file));
        }

        $url = $input->getOption('url') ?: realpath($file);

        $overrides = [
            'dist' => [
                'type' => 'tar',
                'url' => $url,
                'shasum' => sha1_file($file)
            ]
        ];
        foreach (['name', 'version'] as $parameter) {
            if ($value = $input->getOption('package-'.$parameter)) {
                $overrides[$parameter] = $value;
            }
        }

        $loader = new JsonLoader(new OverriddenPackageLoader(new ValidatingArrayLoader(new ArrayLoader(), false), $overrides));
        $package = $loader->load(sprintf('phar://%s/composer.json', $file));

        $repositoryFile = new JsonFile($input->getArgument('repository'));
        $repo = $repositoryFile->exists() ? $repositoryFile->read() : [];

        $dumper = new ArrayDumper();
        $repo['packages'][$package->getName()][$package->getVersion()] = $dumper->dump($package);

        $repositoryFile->write($repo);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.maven.plugin.assembly.test</groupId>
    <artifactId>it-project-parent</artifactId>
    <version>1</version>
  </parent>

  <groupId>org.test</groupId>
  <artifactId>configured-handler</artifactId>
  <version>1</version>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>

        <configuration>
          <descriptors>
            <descriptor>src/assemble/bin.xml</descriptor>
          </descriptors>
        </configuration>

        <executions>
          <execution>
            <id>assembly</id>
            <phase>validate</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
class ComfortableMexicanSofa::Content::Tag::TextArea < ComfortableMexicanSofa::Content::Tag::Fragment

  def form_field(object_name, view, index)
    name    = "#{object_name}[fragments_attributes][#{index}][content]"
    options = { id: form_field_id, data: { "cms-cm-mode" => "text/html" } }
    input   = view.send(:text_area_tag, name, content, options)

    yield input
  end

end

ComfortableMexicanSofa::Content::Renderer.register_tag(
  :textarea, ComfortableMexicanSofa::Content::Tag::TextArea
)


text:
package com.faforever.client.mod.event;

import com.faforever.client.domain.ModVersionBean;

public class ModUploadedEvent {
  private final ModVersionBean modVersionInfo;

  public ModUploadedEvent(ModVersionBean modVersionInfo) {
    this.modVersionInfo = modVersionInfo;
  }

  public ModVersionBean getModVersionInfo() {
    return modVersionInfo;
  }
}


text:
'use strict';

var should = require('should'),
	request = require('supertest'),
	app = require('../../server'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Service = mongoose.model('Service'),
	agent = request.agent(app);

/**
 * Globals
 */
var credentials, user, service;

/**
 * Service routes tests
 */
describe('Service CRUD tests', function() {
	beforeEach(function(done) {
		// Create user credentials
		credentials = {
			username: 'username',
			password: 'password'
		};

		// Create a new user
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: credentials.username,
			password: credentials.password,
			provider: 'local'
		});

		// Save a user to the test db and create new Service
		user.save(function() {
			service = {
				name: 'Service Name'
			};

			done();
		});
	});

	it('should be able to save Service instance if logged in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Service
				agent.post('/services')
					.send(service)
					.expect(200)
					.end(function(serviceSaveErr, serviceSaveRes) {
						// Handle Service save error
						if (serviceSaveErr) done(serviceSaveErr);

						// Get a list of Services
						agent.get('/services')
							.end(function(servicesGetErr, servicesGetRes) {
								// Handle Service save error
								if (servicesGetErr) done(servicesGetErr);

								// Get Services list
								var services = servicesGetRes.body;

								// Set assertions
								(services[0].user._id).should.equal(userId);
								(services[0].name).should.match('Service Name');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to save Service instance if not logged in', function(done) {
		agent.post('/services')
			.send(service)
			.expect(401)
			.end(function(serviceSaveErr, serviceSaveRes) {
				// Call the assertion callback
				done(serviceSaveErr);
			});
	});

	it('should not be able to save Service instance if no name is provided', function(done) {
		// Invalidate name field
		service.name = '';

		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Service
				agent.post('/services')
					.send(service)
					.expect(400)
					.end(function(serviceSaveErr, serviceSaveRes) {
						// Set message assertion
						(serviceSaveRes.body.message).should.match('Please fill Service name');

						// Handle Service save error
						done(serviceSaveErr);
					});
			});
	});

	it('should be able to update Service instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Service
				agent.post('/services')
					.send(service)
					.expect(200)
					.end(function(serviceSaveErr, serviceSaveRes) {
						// Handle Service save error
						if (serviceSaveErr) done(serviceSaveErr);

						// Update Service name
						service.name = 'WHY YOU GOTTA BE SO MEAN?';

						// Update existing Service
						agent.put('/services/' + serviceSaveRes.body._id)
							.send(service)
							.expect(200)
							.end(function(serviceUpdateErr, serviceUpdateRes) {
								// Handle Service update error
								if (serviceUpdateErr) done(serviceUpdateErr);

								// Set assertions
								(serviceUpdateRes.body._id).should.equal(serviceSaveRes.body._id);
								(serviceUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should be able to get a list of Services if not signed in', function(done) {
		// Create new Service model instance
		var serviceObj = new Service(service);

		// Save the Service
		serviceObj.save(function() {
			// Request Services
			request(app).get('/services')
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Array.with.lengthOf(1);

					// Call the assertion callback
					done();
				});

		});
	});

	it('should be able to get a single Service if not signed in', function(done) {
		// Create new Service model instance
		var serviceObj = new Service(service);

		// Save the Service
		serviceObj.save(function() {
			request(app).get('/services/' + serviceObj._id)
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Object.with.property('name', service.name);

					// Call the assertion callback
					done();
				});
		});
	});

	it('should be able to delete Service instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Service
				agent.post('/services')
					.send(service)
					.expect(200)
					.end(function(serviceSaveErr, serviceSaveRes) {
						// Handle Service save error
						if (serviceSaveErr) done(serviceSaveErr);

						// Delete existing Service
						agent.delete('/services/' + serviceSaveRes.body._id)
							.send(service)
							.expect(200)
							.end(function(serviceDeleteErr, serviceDeleteRes) {
								// Handle Service error error
								if (serviceDeleteErr) done(serviceDeleteErr);

								// Set assertions
								(serviceDeleteRes.body._id).should.equal(serviceSaveRes.body._id);

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to delete Service instance if not signed in', function(done) {
		// Set Service user
		service.user = user;

		// Create new Service model instance
		var serviceObj = new Service(service);

		// Save the Service
		serviceObj.save(function() {
			// Try deleting Service
			request(app).delete('/services/' + serviceObj._id)
			.expect(401)
			.end(function(serviceDeleteErr, serviceDeleteRes) {
				// Set message assertion
				(serviceDeleteRes.body.message).should.match('User is not logged in');

				// Handle Service error error
				done(serviceDeleteErr);
			});

		});
	});

	afterEach(function(done) {
		User.remove().exec();
		Service.remove().exec();
		done();
	});
});


text:
'use strict';

function enumerate(values, prefix) {
  prefix = prefix == null ? '' : prefix;

  return values.reduce(function (enumeration, value) {
    enumeration[value] = prefix + value;

    return enumeration;
  }, {});
}

module.exports = enumerate;


text:
"use strict";

const sinon = require("sinon");
const validateCredentials = require("../../../lib/credentials/certificate/validate");

let fakeCredentials;

describe("validateCredentials", function() {
	let credentials;
	beforeEach(function() {
		credentials = fakeCredentials();
	});

	describe("with valid credentials", function() {
		it("returns", function() {
			expect(function() {
				validateCredentials(credentials);
			}).to.not.throw();
		});
	});

	describe("with mismatched key and certificate", function() {
		it("throws", function() {
			sinon.stub(credentials.certificates[0]._key, "fingerprint").returns("fingerprint2");

			expect(function() {
				validateCredentials(credentials);
			}).to.throw(/certificate and key do not match/);
		});
	});

	describe("with expired certificate", function() {
		it("throws", function() {
			sinon.stub(credentials.certificates[0], "validity")
				.returns({
					notBefore: new Date(Date.now() - 100000),
					notAfter: new Date(Date.now() - 10000)
				});

			expect(function() {
				validateCredentials(credentials);
			}).to.throw(/certificate has expired/);
		});
	});

	describe("with incorrect environment", function() {
		it("throws with sandbox cert in production", function() {
			sinon.stub(credentials.certificates[0], "environment")
				.returns({
					production: false,
					sandbox: true
				});

			expect(function() {
				validateCredentials(credentials);
			}).to.throw("certificate does not support configured environment, production: true");
		});

		it("throws with production cert in sandbox", function() {
			sinon.stub(credentials.certificates[0], "environment")
				.returns({
					production: true,
					sandbox: false
				});
			credentials.production = false;

			expect(function() {
				validateCredentials(credentials);
			}).to.throw("certificate does not support configured environment, production: false");
		});
	});

	describe("with missing production flag", function() {
		it("does not throw", function() {
			sinon.stub(credentials.certificates[0], "environment")
				.returns({
					production: true,
					sandbox: false
				});
			credentials.production = undefined;

			expect(function() {
				validateCredentials(credentials);
			}).to.not.throw();
		});
	});

	describe("with certificate supporting both environments", function() {
		it("does not throw", function() {
			sinon.stub(credentials.certificates[0], "environment")
				.returns({
					production: true,
					sandbox: true
				});
			credentials.production = false;

			expect(function() {
				validateCredentials(credentials);
			}).to.not.throw();
		});
	});
});

fakeCredentials = function() {
	return {
		key: {
			_fingerprint: "fingerprint1",
			fingerprint: function() { return this._fingerprint; },
		},
		certificates: [{
			_key: {
				_fingerprint: "fingerprint1",
				fingerprint: function() { return this._fingerprint; },
			},
			_validity: {
				notBefore: new Date(Date.now() - 100000),
				notAfter: new Date(Date.now() + 100000)
			},
			key: function() { return this._key; },
			validity: function() {
				return this._validity;
			},
			environment: function() {
				return { production: true, sandbox: false };
			}
		}],
		production: true
	};
};


text:
package com.andriell.game.base;

/**
 * Created by Андрей on 08.12.2016.
 */

public class SpriteRouteLissajous extends SpriteRoute {
    int circleX = 1;
    int circleY = 1;
    public SpriteRouteLissajous(int size) {
        super(size);
    }

    @Override
    public float[] newXY(float t) {
        float[] r = new float[2];
        r[0] = (float) (getWidth() * (Math.cos(t / circleY) + 1)) / 2 + getX();
        r[1] = (float) (getHeight() * (Math.sin(t / circleX) + 1)) / 2 + getY();
        return r;
    }

    @Override
    public void setSpeed(float speed) {
        super.setSpeed(speed / 1000);
    }

    public int getCircleX() {
        return circleX;
    }

    public void setCircleX(int circleX) {
        this.circleX = circleX;
    }

    public int getCircleY() {
        return circleY;
    }

    public void setCircleY(int circleY) {
        this.circleY = circleY;
    }
}


text:
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License:
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#--------------------------------------------------------------------------

from datetime import datetime

import numbers
import re
import sys
import json
try:
        import ConfigParser
except ImportError:
        import configparser as ConfigParser

from os import path

try:
    from cStringIO import BytesIO
except ImportError:
    from io import BytesIO

from azureml.errors import (
    AzureMLConflictHttpError,
    AzureMLError,
    AzureMLHttpError,
    UnsupportedDatasetTypeError,
    _not_none,
    _not_none_or_empty,
)
from azureml.http import (
    _RestClient,
    __author__,
    __version__,
)
from azureml.serialization import (
    DataTypeIds,
    deserialize_dataframe,
    serialize_dataframe,
    is_supported,
)

_GLOBAL_WORKSPACE_ID = '506153734175476c4f62416c57734963'

class Endpoints(object):
    """Constants for the known REST API endpoints."""
    default = 'https://studio.azureml.net'
    management_default = 'https://management.azureml.net'

class Dataset(object):
    """Abstract base class for Azure ML datasets."""
    pass

class SourceDataset(Dataset):
    """Metadata for a dataset and methods to read its contents."""

    def __init__(self, workspace=None, metadata=None):
        """
        INTERNAL USE ONLY. Initialize a dataset.

        Parameters
        ----------
        workspace : Workspace
            Parent workspace of the dataset.
        metadata : dict
            Dictionary of dataset metadata as returned by the REST API.
        """
        _not_none('metadata', metadata)
        _not_none('workspace', workspace)

        self.workspace = workspace
        self._metadata = metadata

        if is_supported(self.data_type_id):
            self.to_dataframe = self._to_dataframe

        if not self.is_example:
            self.update_from_raw_data = self._update_from_raw_data
            self.update_from_dataframe = self._update_from_dataframe

    @staticmethod
    def _metadata_repr(metadata):
        val = metadata['Name']
        if sys.version_info < (3,):
            return val.encode('ascii','ignore')
        else:
            return val

    def __repr__(self):
        return SourceDataset._metadata_repr(self._metadata)

    def open(self):
        '''Open and return a stream for the dataset contents.'''
        return self.workspace._rest.open_dataset_contents(self.contents_url)

    def read_as_binary(self):
        '''Read and return the dataset contents as binary.'''
        return self.workspace._rest.read_dataset_contents_binary(self.contents_url)

    def read_as_text(self):
        '''Read and return the dataset contents as text.'''
        return self.workspace._rest.read_dataset_contents_text(self.contents_url)

    def _to_dataframe(self):
        """Read and return the dataset contents as a pandas DataFrame."""
        with self.open() as reader:
            return deserialize_dataframe(reader, self.data_type_id)

    def _update_from_dataframe(self, dataframe, data_type_id=None, name=None,
                              description=None):
        """
        Serialize the specified DataFrame and replace the existing dataset.

        Parameters
        ----------
        dataframe : pandas.DataFrame
            Data to serialize.
        data_type_id : str, optional
            Format to serialize to.
            If None, the existing format is preserved.
            Supported formats are:
                'PlainText'
                'GenericCSV'
                'GenericTSV'
                'GenericCSVNoHeader'
                'GenericTSVNoHeader'
            See the azureml.DataTypeIds class for constants.
        name : str, optional
            Name for the dataset.
            If None, the name of the existing dataset is used.
        description : str, optional
            Description for the dataset.
            If None, the name of the existing dataset is used.
        """
        _not_none('dataframe', dataframe)

        if data_type_id is None:
            data_type_id = self.data_type_id
        if name is None:
            name = self.name
        if description is None:
            description = self.description

        try:
            output = BytesIO()
            serialize_dataframe(output, data_type_id, dataframe)
            raw_data = output.getvalue()
        finally:
            output.close()

        self._upload_and_refresh(raw_data, data_type_id, name, description)

    def _update_from_raw_data(self, raw_data, data_type_id=None, name=None,
                             description=None):
        """
        Upload already serialized raw data and replace the existing dataset.

        Parameters
        ----------
        raw_data: bytes
            Dataset contents to upload.
        data_type_id : str
            Serialization format of the raw data.
            If None, the format of the existing dataset is used.
            Supported formats are:
                'PlainText'
                'GenericCSV'
                'GenericTSV'
                'GenericCSVNoHeader'
                'GenericTSVNoHeader'
                'ARFF'
            See the azureml.DataTypeIds class for constants.
        name : str, optional
            Name for the dataset.
            If None, the name of the existing dataset is used.
        description : str, optional
            Description for the dataset.
            If None, the name of the existing dataset is used.
        """
        _not_none('raw_data', raw_data)

        if data_type_id is None:
            data_type_id = self.data_type_id
        if name is None:
            name = self.name
        if description is None:
            description = self.description

        self._upload_and_refresh(raw_data, data_type_id, name, description)

    def _upload_and_refresh(self, raw_data, data_type_id, name, description):
        dataset_id = self.workspace._rest.upload_dataset(
            self.workspace.workspace_id,
            name,
            description,
            data_type_id,
            raw_data,
            self.family_id
        )

        self._metadata = self.workspace._rest.get_dataset(
            self.workspace.workspace_id,
            dataset_id
        )

    class Location(object):
        def __init__(self, metadata):
            self._metadata = metadata

        @property
        def base_uri(self):
            """TODO."""
            return self._metadata['BaseUri']

        @property
        def size(self):
            """TODO."""
            return self._metadata['Size']

        @property
        def endpoint_type(self):
            """TODO."""
            return self._metadata['EndpointType']

        @property
        def credential_container(self):
            """TODO."""
            return self._metadata['CredentialContainer']

        @property
        def access_credential(self):
            """TODO."""
            return self._metadata['AccessCredential']

        @property
        def location(self):
            """TODO."""
            return self._metadata['Location']

        @property
        def file_type(self):
            """TODO."""
            return self._metadata['FileType']

        @property
        def is_auxiliary(self):
            """TODO."""
            return self._metadata['IsAuxiliary']

        @property
        def name(self):
            """TODO."""
            return self._metadata['Name']

    @property
    def visualize_end_point(self):
        """TODO."""
        return SourceDataset.Location(self._metadata['VisualizeEndPoint'])

    @property
    def schema_end_point(self):
        """TODO."""
        return SourceDataset.Location(self._metadata['SchemaEndPoint'])

    @property
    def schema_status(self):
        """TODO."""
        return self._metadata['SchemaStatus']

    @property
    def dataset_id(self):
        """Unique identifier for the dataset."""
        return self._metadata['Id']

    @property
    def name(self):
        """Unique name for the dataset."""
        return self._metadata['Name']

    @property
    def data_type_id(self):
        """
        Serialization format for the dataset.
        See the azureml.DataTypeIds class for constants.
        """
        return self._metadata['DataTypeId']

    @property
    def description(self):
        """Description for the dataset."""
        return self._metadata['Description']

    @property
    def resource_upload_id(self):
        """TODO."""
        return self._metadata['ResourceUploadId']

    @property
    def family_id(self):
        """TODO."""
        return self._metadata['FamilyId']

    @property
    def size(self):
        """Size in bytes of the serialized dataset contents."""
        return self._metadata['Size']

    @property
    def source_origin(self):
        """TODO."""
        return self._metadata['SourceOrigin']

    @property
    def created_date(self):
        # Example format of date to parse:
        # /Date(1418444668177)/
        match = re.search(r"/Date\((\d+)\)/", self._metadata['CreatedDate'])
        return datetime.fromtimestamp(int(match.group(1)) / 1000.0)

    @property
    def owner(self):
        """TODO."""
        return self._metadata['Owner']

    @property
    def experiment_id(self):
        """TODO."""
        return self._metadata['ExperimentId']

    @property
    def client_version(self):
        """TODO."""
        return self._metadata['ClientVersion']

    @property
    def promoted_from(self):
        """TODO."""
        return self._metadata['PromotedFrom']

    @property
    def uploaded_from_filename(self):
        """TODO."""
        return self._metadata['UploadedFromFilename']

    @property
    def service_version(self):
        """TODO."""
        return self._metadata['ServiceVersion']

    @property
    def is_latest(self):
        """TODO."""
        return self._metadata['IsLatest']

    @property
    def category(self):
        """TODO."""
        return self._metadata['Category']

    @property
    def download_location(self):
        """TODO."""
        return SourceDataset.Location(self._metadata['DownloadLocation'])

    @property
    def is_deprecated(self):
        """TODO."""
        return self._metadata['IsDeprecated']

    @property
    def culture(self):
        """TODO."""
        return self._metadata['Culture']

    @property
    def batch(self):
        """TODO."""
        return self._metadata['Batch']

    @property
    def created_date_ticks(self):
        """TODO."""
        return self._metadata['CreatedDateTicks']

    @property
    def contents_url(self):
        """Full URL to the dataset contents."""
        loc = self.download_location
        return loc.base_uri + loc.location + loc.access_credential

    @property
    def is_example(self):
        """True for an example dataset, False for user created."""
        return self.dataset_id.startswith(_GLOBAL_WORKSPACE_ID)

class Datasets(object):
    def __init__(self, workspace, example_filter=None):
        """
        INTERNAL USE ONLY. Initialize a dataset collection.

        Parameters
        ----------
        workspace : Workspace
            Parent workspace of the datasets.
        example_filter : bool
            True to include only examples.
            False to include only user-created.
            None to include all.
        """
        _not_none('workspace', workspace)

        self.workspace = workspace
        self._example_filter = example_filter

    def __repr__(self):
        return '\n'.join((SourceDataset._metadata_repr(dataset) for dataset in self._get_datasets()))

    def __iter__(self):
        for dataset in self._get_datasets():
            yield self._create_dataset(dataset)

    def __len__(self):
        return sum(1 for _ in self._get_datasets())

    def __getitem__(self, index):
        '''Retrieve a dataset by index or by name (case-sensitive).'''
        _not_none('index', index)

        datasets = self._get_datasets()
        if isinstance(index, numbers.Integral):
            return self._create_dataset(list(datasets)[index])
        else:
            for dataset in datasets:
                if dataset['Name'] == index:
                    return self._create_dataset(dataset)

        raise IndexError('A data set named "{}" does not exist'.format(index))

    def add_from_dataframe(self, dataframe, data_type_id, name, description):
        """
        Serialize the specified DataFrame and upload it as a new dataset.

        Parameters
        ----------
        dataframe : pandas.DataFrame
            Data to serialize.
        data_type_id : str
            Format to serialize to.
            Supported formats are:
                'PlainText'
                'GenericCSV'
                'GenericTSV'
                'GenericCSVNoHeader'
                'GenericTSVNoHeader'
            See the azureml.DataTypeIds class for constants.
        name : str
            Name for the new dataset.
        description : str
            Description for the new dataset.

        Returns
        -------
        SourceDataset
            Dataset that was just created.
            Use open(), read_as_binary(), read_as_text() or to_dataframe() on
            the dataset object to get its contents as a stream, bytes, str or
            pandas DataFrame.
        """
        _not_none('dataframe', dataframe)
        _not_none_or_empty('data_type_id', data_type_id)
        _not_none_or_empty('name', name)
        _not_none_or_empty('description', description)

        try:
            output = BytesIO()
            serialize_dataframe(output, data_type_id, dataframe)
            raw_data = output.getvalue()
        finally:
            output.close()

        return self._upload(raw_data, data_type_id, name, description)

    def add_from_raw_data(self, raw_data, data_type_id, name, description):
        """
        Upload already serialized raw data as a new dataset.

        Parameters
        ----------
        raw_data: bytes
            Dataset contents to upload.
        data_type_id : str
            Serialization format of the raw data.
            Supported formats are:
                'PlainText'
                'GenericCSV'
                'GenericTSV'
                'GenericCSVNoHeader'
                'GenericTSVNoHeader'
                'ARFF'
            See the azureml.DataTypeIds class for constants.
        name : str
            Name for the new dataset.
        description : str
            Description for the new dataset.

        Returns
        -------
        SourceDataset
            Dataset that was just created.
            Use open(), read_as_binary(), read_as_text() or to_dataframe() on
            the dataset object to get its contents as a stream, bytes, str or
            pandas DataFrame.
        """
        _not_none('raw_data', raw_data)
        _not_none_or_empty('data_type_id', data_type_id)
        _not_none_or_empty('name', name)
        _not_none_or_empty('description', description)

        return self._upload(raw_data, data_type_id, name, description)

    def _upload(self, raw_data, data_type_id, name, description):
        dataset_id = self.workspace._rest.upload_dataset(
            self.workspace.workspace_id, name, description, data_type_id,
            raw_data, None)

        metadata = self.workspace._rest.get_dataset(
            self.workspace.workspace_id, dataset_id)

        return self._create_dataset(metadata)

    def _get_datasets(self):
        datasets = self.workspace._rest.get_datasets(self.workspace.workspace_id)
        return datasets if self._example_filter is None else \
            (d for d in datasets if d['Id'].startswith(
                _GLOBAL_WORKSPACE_ID) == self._example_filter)

    def _create_dataset(self, metadata):
        return SourceDataset(self.workspace, metadata)

class IntermediateDataset(Dataset):
    """Represents an intermediate dataset and methods to read its contents."""

    def __init__(self, workspace, experiment, node_id, port_name, data_type_id):
        """
        INTERNAL USE ONLY. Initialize an intermediate dataset.

        Parameters
        ----------
        workspace : Workspace
            Parent workspace of the dataset.
        experiment : Experiment
            Parent experiment of the dataset.
        node_id : str
            Module node id from the experiment graph.
        port_name : str
            Output port of the module.
        data_type_id : str
            Serialization format of the raw data.
            See the azureml.DataTypeIds class for constants.
        """
        _not_none('workspace', workspace)
        _not_none('experiment', experiment)
        _not_none_or_empty('node_id', node_id)
        _not_none_or_empty('port_name', port_name)
        _not_none_or_empty('data_type_id', data_type_id)

        self.workspace = workspace
        self.experiment = experiment
        self.node_id = node_id
        self.port_name = port_name
        self.data_type_id = data_type_id

        if is_supported(self.data_type_id):
            self.to_dataframe = self._to_dataframe

    def open(self):
        '''Open and return a stream for the dataset contents.'''
        return self.workspace._rest.open_intermediate_dataset_contents(
            self.workspace.workspace_id,
            self.experiment.experiment_id,
            self.node_id,
            self.port_name
        )

    def read_as_binary(self):
        '''Read and return the dataset contents as binary.'''
        return self.workspace._rest.read_intermediate_dataset_contents_binary(
            self.workspace.workspace_id,
            self.experiment.experiment_id,
            self.node_id,
            self.port_name
        )

    def read_as_text(self):
        '''Read and return the dataset contents as text.'''
        return self.workspace._rest.read_intermediate_dataset_contents_text(
            self.workspace.workspace_id,
            self.experiment.experiment_id,
            self.node_id,
            self.port_name
        )

    def _to_dataframe(self):
        """Read and return the dataset contents as a pandas DataFrame."""
        #TODO: figure out why passing in the opened stream directly gives invalid data
        data = self.read_as_binary()
        reader = BytesIO(data)
        return deserialize_dataframe(reader, self.data_type_id)

class Experiment(object):

    def __init__(self, workspace, metadata):
        """
        INTERNAL USE ONLY. Initialize an experiment.

        Parameters
        ----------
        workspace : Workspace
            Parent workspace of the experiment.
        metadata : dict
            Dictionary of experiment metadata as returned by the REST API.
        """
        _not_none('workspace', workspace)
        _not_none('metadata', metadata)

        self.workspace = workspace
        self._metadata = metadata

    @staticmethod
    def _metadata_repr(metadata):
        val = u'{0}\t{1}'.format(metadata['ExperimentId'], metadata['Description'])
        if sys.version_info < (3,):
            return val.encode('ascii','ignore')
        else:
            return val

    def __repr__(self):
        return Experiment._metadata_repr(self._metadata)

    class Status(object):
        def __init__(self, metadata):
            self._metadata = metadata

        @property
        def status_code(self):
            """TODO."""
            return self._metadata['StatusCode']

        @property
        def status_detail(self):
            """TODO."""
            return self._metadata['StatusDetail']

        @property
        def creation_time(self):
            """TODO."""
            # Example format of date to parse:
            # /Date(1418444668177)/
            match = re.search(r"/Date\((\d+)\)/", self._metadata['CreationTime'])
            return datetime.fromtimestamp(int(match.group(1)) / 1000.0)

    @property
    def status(self):
        """TODO."""
        return Experiment.Status(self._metadata['Status'])

    @property
    def description(self):
        """TODO."""
        return self._metadata['Description']

    @property
    def creator(self):
        """TODO."""
        return self._metadata['Creator']

    @property
    def experiment_id(self):
        """TODO."""
        return self._metadata['ExperimentId']

    @property
    def job_id(self):
        """TODO."""
        return self._metadata['JobId']

    @property
    def version_id(self):
        """TODO."""
        return self._metadata['VersionId']

    @property
    def etag(self):
        """TODO."""
        return self._metadata['Etag']

    @property
    def run_id(self):
        """TODO."""
        return self._metadata['RunId']

    @property
    def is_archived(self):
        """TODO."""
        return self._metadata['IsArchived']

    @property
    def is_example(self):
        """True for an example experiment, False for user created."""
        return self.experiment_id.startswith(_GLOBAL_WORKSPACE_ID)

    def get_intermediate_dataset(self, node_id, port_name, data_type_id):
        """
        Get an intermediate dataset.

        Parameters
        ----------
        node_id : str
            Module node id from the experiment graph.
        port_name : str
            Output port of the module.
        data_type_id : str
            Serialization format of the raw data.
            See the azureml.DataTypeIds class for constants.

        Returns
        -------
        IntermediateDataset
            Dataset object.
            Use open(), read_as_binary(), read_as_text() or to_dataframe() on
            the dataset object to get its contents as a stream, bytes, str or
            pandas DataFrame.
        """
        return IntermediateDataset(self.workspace, self, node_id, port_name, data_type_id)

class Experiments(object):
    def __init__(self, workspace, example_filter=None):
        """
        INTERNAL USE ONLY. Initialize an experiment collection.

        Parameters
        ----------
        workspace : Workspace
            Parent workspace of the experiments.
        example_filter : bool
            True to include only examples.
            False to include only user-created.
            None to include all.
        """
        _not_none('workspace', workspace)

        self.workspace = workspace
        self._example_filter = example_filter

    def __repr__(self):
        return '\n'.join((Experiment._metadata_repr(experiment) for experiment in self._get_experiments()))

    def __iter__(self):
        for experiment in self._get_experiments():
            yield self._create_experiment(experiment)

    def __len__(self):
        return sum(1 for _ in self._get_experiments())

    def __getitem__(self, index):
        '''Retrieve an experiment by index or by id.'''
        _not_none('index', index)

        experiments = self._get_experiments()
        if isinstance(index, numbers.Integral):
            return self._create_experiment(list(experiments)[index])
        else:
            for experiment in experiments:
                if experiment['ExperimentId'] == index:
                    return self._create_experiment(experiment)

        raise IndexError('An experiment with the id "{}" does not exist'.format(index))

    def _get_experiments(self):
        experiments = self.workspace._rest.get_experiments(self.workspace.workspace_id)
        return experiments if self._example_filter is None else \
            (e for e in experiments if e['ExperimentId'].startswith(_GLOBAL_WORKSPACE_ID) == self._example_filter)

    def _create_experiment(self, metadata):
        return Experiment(self.workspace, metadata)

_CONFIG_WORKSPACE_SECTION = 'workspace'
_CONFIG_WORKSPACE_ID = 'id'
_CONFIG_AUTHORIZATION_TOKEN = 'authorization_token'
_CONFIG_API_ENDPOINT = 'api_endpoint'
_CONFIG_MANAGEMENT_ENDPOINT = 'management_endpoint'

def _get_workspace_info(workspace_id, authorization_token, endpoint, management_endpoint):
    if workspace_id is None or authorization_token is None or endpoint is None or management_endpoint is None:
        # read the settings from config
        jsonConfig = path.expanduser('~/.azureml/settings.json')
        if path.exists(jsonConfig):
            with open(jsonConfig) as cfgFile:
                config = json.load(cfgFile)
                if _CONFIG_WORKSPACE_SECTION in config:
                    ws = config[_CONFIG_WORKSPACE_SECTION]
                    workspace_id = ws.get(_CONFIG_WORKSPACE_ID, workspace_id)
                    authorization_token = ws.get(_CONFIG_AUTHORIZATION_TOKEN, authorization_token)
                    endpoint = ws.get(_CONFIG_API_ENDPOINT, endpoint)
                    management_endpoint = ws.get(_CONFIG_MANAGEMENT_ENDPOINT, management_endpoint)
        else:
            config = ConfigParser.ConfigParser()
            config.read(path.expanduser('~/.azureml/settings.ini'))

            if config.has_section(_CONFIG_WORKSPACE_SECTION):
                if workspace_id is None and config.has_option(_CONFIG_WORKSPACE_SECTION, _CONFIG_WORKSPACE_ID):
                    workspace_id = config.get(_CONFIG_WORKSPACE_SECTION, _CONFIG_WORKSPACE_ID)
                if authorization_token is None and config.has_option(_CONFIG_WORKSPACE_SECTION, _CONFIG_AUTHORIZATION_TOKEN):
                    authorization_token = config.get(_CONFIG_WORKSPACE_SECTION, _CONFIG_AUTHORIZATION_TOKEN)
                if endpoint is None and config.has_option(_CONFIG_WORKSPACE_SECTION, _CONFIG_API_ENDPOINT):
                    endpoint = config.get(_CONFIG_WORKSPACE_SECTION, _CONFIG_API_ENDPOINT)
                if management_endpoint is None and config.has_option(_CONFIG_WORKSPACE_SECTION, _CONFIG_MANAGEMENT_ENDPOINT):
                    management_endpoint = config.get(_CONFIG_WORKSPACE_SECTION, _CONFIG_MANAGEMENT_ENDPOINT)

        if workspace_id is None:
            raise ValueError('workspace_id not provided and not available via config')
        if authorization_token is None:
            raise ValueError('authorization_token not provided and not available via config')
        if endpoint is None:
            endpoint = Endpoints.default
        if management_endpoint is None:
            management_endpoint = Endpoints.management_default

    return workspace_id, authorization_token, endpoint, management_endpoint

class Workspace(object):

    def __init__(self, workspace_id = None, authorization_token = None, endpoint=None):
        """
        Initialize a workspace.

        Parameters
        ----------
        workspace_id : str
            Unique identifier for the existing workspace. Can be obtained from
            the URL in ML Studio when editing a workspace.
        authorization_token: str
            Access token for the workspace. Can be the primary or secondary
            token managed in ML Studio.
        endpoint: str
            URL of the endpoint to connect to. Specify this only if you host
            ML Studio on your own server(s).

        Parameters that are omitted will be read from ~/.azureml/settings.ini:
        [workspace]
        id = abcd1234
        authorization_token = abcd1234
        endpoint = https://studio.azureml.net
        """
        workspace_id, authorization_token, endpoint, management_endpoint = _get_workspace_info(workspace_id, authorization_token, endpoint, None)

        _not_none_or_empty('workspace_id', workspace_id)
        _not_none_or_empty('authorization_token', authorization_token)
        _not_none_or_empty('endpoint', endpoint)

        self.workspace_id = workspace_id
        self.authorization_token = authorization_token
        self.api_endpoint = endpoint
        self.management_endpoint = management_endpoint
        self._rest = _RestClient(endpoint, authorization_token)
        self.datasets = Datasets(workspace=self)
        self.user_datasets = Datasets(workspace=self, example_filter=False)
        self.example_datasets = Datasets(workspace=self, example_filter=True)
        self.experiments = Experiments(workspace=self)
        self.user_experiments = Experiments(workspace=self, example_filter=False)
        self.example_experiments = Experiments(workspace=self, example_filter=True)

_manglingPattern = re.compile(r'[\W_]+')

def _mangled(name):
    result = _manglingPattern.sub('_', name)
    return result.lower()


text:
class PrefRegistrySimple;

namespace chromeos {

class InlineLoginHandlerChromeOS : public InlineLoginHandler {
 public:
  explicit InlineLoginHandlerChromeOS(
      const base::RepeatingClosure& close_dialog_closure);

  InlineLoginHandlerChromeOS(const InlineLoginHandlerChromeOS&) = delete;
  InlineLoginHandlerChromeOS& operator=(const InlineLoginHandlerChromeOS&) =
      delete;

  ~InlineLoginHandlerChromeOS() override;

  static void RegisterProfilePrefs(PrefRegistrySimple* registry);

  // InlineLoginHandler overrides.
  void RegisterMessages() override;
  void SetExtraInitParams(base::DictionaryValue& params) override;
  void CompleteLogin(const CompleteLoginParams& params) override;
  void HandleDialogClose(const base::ListValue* args) override;

 private:
  // A callback for `GetAccounts` invoked from `CompleteLogin`.
  void OnGetAccountsToCompleteLogin(
      const CompleteLoginParams& params,
      const std::vector<::account_manager::Account>& accounts);
  // Creates a `SigninHelper` instance to complete login of the new account.
  void CreateSigninHelper(const CompleteLoginParams& params,
                          std::unique_ptr<SigninHelper::ArcHelper> arc_helper);
  void ShowIncognitoAndCloseDialog(const base::ListValue* args);
  void GetAccountsInSession(const base::ListValue* args);
  void OnGetAccounts(const std::string& callback_id,
                     const std::vector<::account_manager::Account>& accounts);
  void GetAccountsNotAvailableInArc(const base::Value::List& args);
  void ContinueGetAccountsNotAvailableInArc(
      const std::string& callback_id,
      const std::vector<::account_manager::Account>& accounts);
  void FinishGetAccountsNotAvailableInArc(
      const std::string& callback_id,
      const std::vector<::account_manager::Account>& accounts,
      const base::flat_set<account_manager::Account>& arc_accounts);
  void MakeAvailableInArcAndCloseDialog(const base::Value::List& args);
  void HandleSkipWelcomePage(const base::ListValue* args);
  void OpenGuestWindowAndCloseDialog(const base::Value::List& args);

  base::RepeatingClosure close_dialog_closure_;
  base::WeakPtrFactory<InlineLoginHandlerChromeOS> weak_factory_{this};
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_UI_WEBUI_SIGNIN_INLINE_LOGIN_HANDLER_CHROMEOS_H_


text:
module RuboCop
  module Cop
    module InternalAffairs
      # Use `RUBY` for heredoc delimiter of example Ruby code.
      #
      # Some editors may apply better syntax highlighting by using appropriate language names for
      # the delimiter.
      #
      # @example
      #  # bad
      #  expect_offense(<<~CODE)
      #    example_ruby_code
      #  CODE
      #
      #  # good
      #  expect_offense(<<~RUBY)
      #    example_ruby_code
      #  RUBY
      class ExampleHeredocDelimiter < Base
        extend AutoCorrector

        EXPECTED_HEREDOC_DELIMITER = 'RUBY'

        MSG = 'Use `RUBY` for heredoc delimiter of example Ruby code.'

        RESTRICT_ON_SEND = %i[
          expect_correction
          expect_no_corrections
          expect_no_offenses
          expect_offense
        ].freeze

        # @param node [RuboCop::AST::SendNode]
        # @return [void]
        def on_send(node)
          heredoc_node = heredoc_node_from(node)
          return unless heredoc_node
          return if expected_heredoc_delimiter?(heredoc_node)
          return if expected_heredoc_delimiter_in_body?(heredoc_node)

          add_offense(heredoc_node) do |corrector|
            autocorrect(corrector, heredoc_node)
          end
        end

        private

        # @param corrector [RuboCop::Cop::Corrector]
        # @param node [RuboCop::AST::StrNode]
        # @return [void]
        def autocorrect(corrector, node)
          [
            heredoc_openning_delimiter_range_from(node),
            heredoc_closing_delimiter_range_from(node)
          ].each do |range|
            corrector.replace(range, EXPECTED_HEREDOC_DELIMITER)
          end
        end

        # @param node [RuboCop::AST::StrNode]
        # @return [Boolean]
        def expected_heredoc_delimiter_in_body?(node)
          node.location.heredoc_body.source.lines.any? do |line|
            line.strip == EXPECTED_HEREDOC_DELIMITER
          end
        end

        # @param node [RuboCop::AST::StrNode]
        # @return [Boolean]
        def expected_heredoc_delimiter?(node)
          heredoc_delimiter_string_from(node) == EXPECTED_HEREDOC_DELIMITER
        end

        # @param node [RuboCop::AST::SendNode]
        # @return [RuboCop::AST::StrNode, nil]
        def heredoc_node_from(node)
          return unless node.first_argument.respond_to?(:heredoc?)
          return unless node.first_argument.heredoc?

          node.first_argument
        end

        # @param node [RuboCop::AST::StrNode]
        # @return [String]
        def heredoc_delimiter_string_from(node)
          node.source[Heredoc::OPENING_DELIMITER, 2]
        end

        # @param node [RuboCop::AST::StrNode]
        # @return [Parser::Source::Range]
        def heredoc_openning_delimiter_range_from(node)
          match_data = node.source.match(Heredoc::OPENING_DELIMITER)
          node.location.expression.begin.adjust(
            begin_pos: match_data.begin(2),
            end_pos: match_data.end(2)
          )
        end

        # @param node [RuboCop::AST::StrNode]
        # @return [Parser::Source::Range]
        def heredoc_closing_delimiter_range_from(node)
          node.location.heredoc_end.end.adjust(
            begin_pos: -heredoc_delimiter_string_from(node).length
          )
        end
      end
    end
  end
end


text:
#ifndef __ZLLANGUAGEDETECTOR_H__
#define __ZLLANGUAGEDETECTOR_H__

#include <vector>
#include <string>

//#include <shared_ptr.h>

class ZLStatisticsBasedMatcher;

class ZLLanguageDetector {

public:
	struct LanguageInfo {
		LanguageInfo(const std::string &language, const std::string &encoding);
		const std::string Language;
		const std::string Encoding;
	};

public:
	ZLLanguageDetector();
	~ZLLanguageDetector();

	shared_ptr<LanguageInfo> findInfo(const char *buffer, std::size_t length, int matchingCriterion = 0);
	shared_ptr<LanguageInfo> findInfoForEncoding(const std::string &encoding, const char *buffer, std::size_t length, int matchingCriterion = 0);

private:
	typedef std::vector<shared_ptr<ZLStatisticsBasedMatcher> > SBVector;
	SBVector myMatchers;
};

#endif /* __ZLLANGUAGEDETECTOR_H__ */


text:
<?php

namespace app;

use alkemann\h2l\{ Request, Response, Router, Log };
use alkemann\h2l\exceptions\InvalidUrl;
use alkemann\h2l\util\Http;
use alkemann\jsonapi\exceptions\InvalidRequestContainer;
use alkemann\jsonapi\response\{Result, Error};
use alkemann\jsonapi\Controller;
use app\People;

class Api extends Controller
{
    static $routes = [
        // Url                              function            request method
        ['%^/api/v1/people/(?<id>\d+)%',    'person',           Http::GET],
        ['%^/api/v1/people/(?<id>\d+)%',    'update_person',    Http::PATCH],
        ['/api/v1/people',                  'new_person',       Http::POST],
        ['/api/v1/people',                  'people',           Http::GET],
        ['/api/v1/version',                 'version',          Http::GET],
    ];

    public function new_person(Request $request): ?Response
    {
        $person = $this->populateModelFromRequest(People::class, $request);
        $person->save();
        return (new Result($person, Http::CODE_CREATED))
            ->withLocation($request->fullUrl('/api/v1/people/' . $person->id))
            ;
    }

    public function update_person(Request $request): ?Response
    {
        $person = People::get($request->param('id'));
        if (!$person) {
            return new Error([], Http::CODE_NOT_FOUND);
        }
        $data = $this->getValidatedRequestDataForModel(People::class, $request);
        $person->save($data);
        return new Result($person);
    }

    public function person(Request $r): ?Response
    {
        $person = People::get($r->param('id'));
        return new Result($person);
    }

    public function people(Request $r): ?Response
    {
        $data = People::find();
        return (new Result($data))
            ->withLinks(['self' => $r->fullUrl()])
            ;
    }

    public static function version(Request $r): Response
    {
        return new Result(['v' => '1.0']);
    }
}