text:
#include    "pch.h"
#include    "GoalList.h"

namespace Training
{
    //------------------------------------------------------------------------------
    // class methods
    //------------------------------------------------------------------------------
    /* void */  GoalList::GoalList (void)
    {
        // This is done to be sure the goal list iterator is always valid.
        m_iterator = m_goalList.end ();
    }

    //------------------------------------------------------------------------------
    /* void */  GoalList::~GoalList (void)
    {
        // assume that no one else is managing the memory for these goals, and delete
        // them myself.
        for (m_iterator = m_goalList.begin (); m_iterator != m_goalList.end (); m_iterator++)
            delete *m_iterator;
   }

    //------------------------------------------------------------------------------
    bool        GoalList::Start (void)
    {
        // Check to see if we are at the end of the list
        while (m_iterator != m_goalList.end ())
        {
            // start the goal, and check whether or not it is complete
            if ((*m_iterator)->Start () == Goal::c_GoalComplete)
            {
                // the goal is complete, so move to the next goal
                m_iterator++;
            }
            else
            {
                // the goal is not complete, so return false
                return Goal::c_GoalIncomplete;
            }
        }

        // If we got here, then the goal list is complete.
        return Goal::c_GoalComplete;
    }

    //------------------------------------------------------------------------------
    void        GoalList::Stop (void)
    {
        if (m_iterator != m_goalList.end ())
            // stop the current goal in the list
            (*m_iterator)->Stop ();
    }

    //------------------------------------------------------------------------------
    bool        GoalList::Evaluate (void)
    {
        // Check to see if we are at the end of the list
        if (m_iterator != m_goalList.end ())
        {
            // evaluate the goal condition
            if ((*m_iterator)->Evaluate () == true)
            {
                // the goal condition is true, meaning the current goal is complete.
                // move to the next goal and return the result of starting it.
                Stop ();
                m_iterator++;
                return Start ();
            }
            else
            {
                // the goal condition is false, meaning the current goal is not complete.
                // return false to indicate this.
                return Goal::c_GoalIncomplete;
            }
        }

        // If we got here, then the goal list is complete.
        return Goal::c_GoalComplete;
    }

    //------------------------------------------------------------------------------
    void        GoalList::AddGoal (Goal* pGoal)
    {
        // Store the goals in the order they are added. This gives the
        // author some modicum of control over playback order.
        m_goalList.push_back (pGoal);

        // I'm being lazy and getting the list iterator at each addition.
        // This saves having to have a separate method for saying we are
        // done installing new goals and are ready to start traversal.
        m_iterator = m_goalList.begin ();
    }

    //------------------------------------------------------------------------------
}


text:
package de.codecentric.boot.admin.server.ui;

import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;

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

public abstract class AbstractAdminUiApplicationTest {

	private WebTestClient webClient;

	protected void setUp(int port) {
		this.webClient = createWebClient(port);
	}

	@Test
	public void should_return_index() {
		//@formatter:off
		this.webClient.get()
					.uri("/")
					.accept(MediaType.TEXT_HTML, MediaType.ALL)
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentTypeCompatibleWith(MediaType.TEXT_HTML)
					.expectBody(String.class)
					.value((body) -> assertThat(body).contains("<title>Spring Boot Admin</title>"));
		//@formatter:on
	}

	@Test
	public void should_not_return_index_for_logfile() {
		//@formatter:off
		this.webClient.get()
						.uri("/instances/a973ff14be49/actuator/logfile")
						.accept(MediaType.TEXT_HTML, MediaType.ALL)
						.exchange()
						.expectStatus().isEqualTo(HttpStatus.SERVICE_UNAVAILABLE);
		//@formatter:on
	}

	@Test
	public void should_return_api() {
		//@formatter:off
		this.webClient.get()
					.uri("/applications")
					.accept(MediaType.APPLICATION_JSON)
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)
					.expectBody(String.class)
					.value((body) -> assertThat(body).contains("[]"));
		//@formatter:on
	}

	@Test
	public void should_return_index_for_ui_path() {
		//@formatter:off
		this.webClient.get()
					.uri("/applications")
					.accept(MediaType.TEXT_HTML)
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentTypeCompatibleWith(MediaType.TEXT_HTML)
					.expectBody(String.class)
					.value((body) -> assertThat(body).contains("<title>Spring Boot Admin</title>"));
		//@formatter:on
	}

	@Test
	public void should_return_404_for_unknown_path() {
		//@formatter:off
		this.webClient.get()
					.uri("/unknown")
					.accept(MediaType.TEXT_HTML)
					.exchange()
					.expectStatus().isNotFound();
		//@formatter:on
	}

	@Test
	public void should_return_correct_content_type_for_js_extensions() {
		//@formatter:off
		this.webClient.get()
					.uri("/extensions/custom/custom.abcdef.js")
					.header("Accept", "*/*")
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentType(MediaType.parseMediaType("application/javascript"));
		//@formatter:on
	}

	@Test
	public void should_return_correct_content_type_for_css_extensions() {
		//@formatter:off
		this.webClient.get()
					.uri("/extensions/custom/custom.abcdef.css")
					.header("Accept", "text/css,*/*;q=0.1")
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentType(MediaType.parseMediaType("text/css"));
		//@formatter:on
	}

	@Test
	public void should_contain_only_one_language() {
		//@formatter:off
		this.webClient.get()
					.uri("/sba-settings.js")
					.accept(MediaType.ALL)
					.exchange()
					.expectStatus().isOk()
					.expectHeader().contentTypeCompatibleWith("application/javascript")
					.expectBody(String.class)
					.value((body) -> assertThat(body).contains("\"availableLanguages\":[\"de\"]"));
		//@formatter:on
	}

	@Test
	public void should_return_defaults_for_pollTimers() {
		//@formatter:off
		this.webClient.get()
			.uri("/sba-settings.js")
			.accept(MediaType.ALL)
			.exchange()
			.expectStatus().isOk()
			.expectHeader().contentTypeCompatibleWith("application/javascript")
			.expectBody(String.class)
			.value((body) -> assertThat(body).contains("\"pollTimer\""))
			.value((body) -> assertThat(body).contains("\"cache\":2500"));
		//@formatter:on
	}

	protected WebTestClient createWebClient(int port) {
		return WebTestClient.bindToServer().baseUrl("http://localhost:" + port).build();
	}

}

redpajama_set_name: RedPajamaGithub


text:
import { style } from 'typestyle';

export const commitFormClass = style({
  display: 'flex',
  flexWrap: 'wrap',

  marginTop: 'auto',
  padding: '8px',
  paddingTop: '1em',

  alignItems: 'flex-start',

  backgroundColor: 'var(--jp-layout-color1)',
  borderTop: 'var(--jp-border-width) solid var(--jp-border-color2)'
});

export const dirtyStagedFilesWarningBoxClass = style({
  marginBottom: '1em',
  padding: 'var(--jp-code-padding)',

  outline: 'none',
  overflowX: 'auto',

  border: 'var(--jp-border-width) solid var(--jp-border-color2)',
  borderRadius: '3px'
});

export const dirtyStagedFilesWarningBoxHeaderClass = style({
  fontWeight: 'bold',
  marginBottom: '0.5em',
  color: 'var(--jp-warn-color1)',
  padding: 0
});

export const dirtyStagedFilesWarningBoxContentClass = style({
  color: 'var(--jp-warn-color1)',
  padding: 0,
  $nest: {
    '&:last-child': {
      paddingBottom: 0
    }
  }
});

export const commitSummaryClass = style({
  height: '2em',

  marginBottom: '1em',
  padding: 'var(--jp-code-padding)',

  outline: 'none',
  overflowX: 'auto',

  border: 'var(--jp-border-width) solid var(--jp-border-color2)',
  borderRadius: '3px',

  $nest: {
    '&.Mui-error': {
      border: 'calc(2 * var(--jp-border-width)) solid var(--jp-error-color1)'
    }
  }
});

export const commitDescriptionClass = style({
  marginBottom: '1em',
  padding: 'var(--jp-code-padding)',

  outline: 'none',
  overflowX: 'auto',
  resize: 'none',

  border: 'var(--jp-border-width) solid var(--jp-border-color2)',
  borderRadius: '3px',

  $nest: {
    '&>*::placeholder': {
      color: 'var(--jp-ui-font-color3)'
    },
    '&>*::-webkit-input-placeholder': {
      color: 'var(--jp-ui-font-color3)'
    },
    '&>*::-moz-placeholder': {
      color: 'var(--jp-ui-font-color3)'
    },
    '&>*::-ms-input-placeholder': {
      color: 'var(--jp-ui-font-color3)'
    }
  }
});

export const commitButtonClass = style({
  cursor: 'pointer',
  color: 'var(--jp-ui-inverse-font-color1)',
  backgroundColor: 'var(--jp-brand-color1)',

  $nest: {
    '&:hover': {
      backgroundColor: 'var(--jp-brand-color2)'
    }
  }
});

export const commitVariantSelector = style({
  flex: '0 0 20px',
  lineHeight: 'initial',

  $nest: {
    '& .jp-icon3[fill]': {
      fill: 'var(--jp-ui-inverse-font-color1)'
    }
  }
});

export const commitInputWrapperClass = style({
  width: '100%',
  display: 'flex',
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'space-around'
});

export const commitPaperClass = style({
  maxWidth: '250px'
});

export const commitVariantText = style({
  fontSize: 'var(--jp-ui-font-size1)',
  whiteSpace: 'break-spaces'
});

export const commitRoot = style({
  color: 'var(--jp-ui-font-color1)',
  fontSize: 'var(--jp-ui-font-size1)',
  fontFamily: 'var(--jp-ui-font-family)',
  backgroundColor: 'var(--jp-layout-color1)'
});

export const activeStyle = style({
  outline: 'none',
  border: 'var(--jp-border-width) solid var(--jp-brand-color1)'
});

export const disabledStyle = style({
  cursor: 'not-allowed !important',
  color: 'var(--jp-ui-font-color2) !important',
  backgroundColor: 'var(--jp-layout-color3) !important',
  // TypeScript does not know about the value with `!important` flag
  pointerEvents: 'auto !important' as any
});


text:
'use strict';
/* jshint node: true */
/* jshint esnext: true */
/* global describe, beforeAll, afterAll, spyOn, it, expect, fail, jasmine */
const Q = require('q');
const moment = require('moment');
const mockery = require('mockery');

describe('race service', () => {

  let race, dbMock;

  beforeAll(() => {
    mockery.enable({useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false});
    mockery.resetCache();

    dbMock = {
      select: jasmine.createSpy()
    };
    mockery.registerMock('../service/util/dbHelper', dbMock);

    mockery.registerAllowables(['q', 'lodash', 'moment', 'fast-csv', '../domain/timeCalculator']);

    race = require('../../service/race');

  });

  afterAll(() => {
    mockery.deregisterAll();
    mockery.disable();
  });

  it('opens csv files', (done) => {
    race.parse('spec/service/results.csv')
      .then((data) => {
        expect(data[1]).toBe('09:24:04');
        done();
      })
      .catch(done.fail);
  });

  it('returns also formated HH:MM startTimes', (done) => {

    const startTimes = [ { times: `{"block1": 36000, "block2": 37200}` } ];
    dbMock.select.and.returnValue(Q.fcall(() => startTimes));

    race.startTimesAsHHMM().then(formattedTimed => {
      expect(formattedTimed.block1).toBe('10:00');
      expect(formattedTimed.block2).toBe('10:20');
      done();
    }).catch(done.fail);
  });
});


text:
namespace UnicornHack.Data.Creatures;

public static partial class CreatureData
{
    public static readonly Creature Ghost = new Creature
    {
        Name = "ghost",
        Species = Species.Ghost,
        SpeciesClass = SpeciesClass.Undead,
        Abilities = new HashSet<Ability>
        {
            new Ability
            {
                Activation = ActivationType.Targeted,
                Trigger = ActivationType.OnMeleeAttack,
                Range = 1,
                Action = AbilityAction.Touch,
                SuccessCondition = AbilitySuccessCondition.NormalAttack,
                Accuracy = "5+PerceptionModifier()",
                Cooldown = 100,
                Delay = "100*SpeedModifier()",
                Effects = new List<Effect> { new PhysicalDamage { Damage = "10*MightModifier()" } }
            }
        },
        InitialLevel = 10,
        GenerationWeight = "0",
        GenerationFlags = GenerationFlags.NonGenocidable | GenerationFlags.NonPolymorphable,
        Behavior = AIBehavior.Wandering | AIBehavior.Stalking,
        Weight = 0,
        MovementDelay = 300,
        TurningDelay = 300,
        Material = Material.Air,
        Perception = -4,
        Might = -4,
        Speed = -4,
        Armor = 7,
        MagicResistance = 7,
        ColdResistance = 75,
        VoidResistance = 75,
        SlimingImmune = true,
        StoningImmune = true,
        TorsoType = TorsoType.Humanoid,
        UpperExtremities = ExtremityType.GraspingFingers,
        LowerExtremities = ExtremityType.Fingers,
        RespirationType = RespirationType.None,
        LocomotionType = LocomotionType.Walking | LocomotionType.Phasing,
        SlotCapacity = 0,
        Infravision = true
    };
}


text:
@implementation FLAbstractArrayProxy

- (id) init {
    return self;
}

- (NSArray*) array {
    return nil;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSArray* array = [self array];
    for(NSInteger i = array.count - 1; i >= 0; i--) {
        id listener = [array objectAtIndex:i];
        if([listener respondsToSelector:[anInvocation selector]]) {
            [anInvocation invokeWithTarget:listener];
        }
    }
}

- (BOOL) respondsToSelector:(SEL) selector {

    for(id listener in [self array]) {
        if([listener respondsToSelector:selector]) {
            return YES;
        }
    }

    return [super respondsToSelector:selector];
}

- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector {

    NSMethodSignature* signature = nil;
    for(id obj in [self array]) {
        signature = [obj methodSignatureForSelector:selector];
        if(signature) {
            return signature;
        }
    }

    if(!signature) {
        signature = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
    }

    return signature;
}

@end

@implementation FLArrayProxy

- (NSArray*) array {
    return _array;
}

- (id) initWithArray:(NSArray*) array {
    FLAssertNotNil(array);
    _array = FLRetain(array);
    return self;
}

+ (id) arrayProxy:(NSArray*) array {
    return FLAutorelease([[[self class] alloc] initWithArray:array]);
}

#if FL_MRC
- (void)dealloc {
	[_array release];
	[super dealloc];
}
#endif

@end


text:
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Table/Column autocomplete in SQL editors
 *
 * @package PhpMyAdmin
 */

require_once 'libraries/common.inc.php';

if ($GLOBALS['cfg']['EnableAutocompleteForTablesAndColumns']) {
    $db = isset($_POST['db']) ? $_POST['db'] : $GLOBALS['db'];
    $sql_autocomplete = array();
    if ($db) {
        $tableNames = $GLOBALS['dbi']->getTables($db);
        foreach ($tableNames as $tableName) {
            $sql_autocomplete[$tableName] = $GLOBALS['dbi']->getColumns(
                $db, $tableName
            );
        }
    }
} else {
    $sql_autocomplete = true;
}
$response = PMA\libraries\Response::getInstance();
$response->addJSON("tables", json_encode($sql_autocomplete));


text:
package com.evolveum.midpoint.model.impl.scripting.helpers;

import com.evolveum.midpoint.model.api.ModelExecuteOptions;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.model.api.PolicyViolationException;
import com.evolveum.midpoint.model.impl.scripting.ExecutionContext;
import com.evolveum.midpoint.model.impl.scripting.ScriptExecutionException;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.exception.CommunicationException;
import com.evolveum.midpoint.util.exception.ConfigurationException;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SecurityViolationException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;

/**
 * @author mederly
 */
@Component
public class OperationsHelper {

    private static final Trace LOGGER = TraceManager.getTrace(OperationsHelper.class);

    @Autowired
    private ModelService modelService;

    public void applyDelta(ObjectDelta delta, ExecutionContext context, OperationResult result) throws ScriptExecutionException {
        applyDelta(delta, null, context, result);
    }

    public void applyDelta(ObjectDelta delta, ModelExecuteOptions options, ExecutionContext context, OperationResult result) throws ScriptExecutionException {
        try {
            modelService.executeChanges((Collection) Collections.singleton(delta), options, context.getTask(), result);
        } catch (ObjectAlreadyExistsException|ObjectNotFoundException|SchemaException|ExpressionEvaluationException|CommunicationException|ConfigurationException|PolicyViolationException|SecurityViolationException e) {
            throw new ScriptExecutionException("Couldn't modify object: " + e.getMessage(), e);
        }
    }

    public Collection<SelectorOptions<GetOperationOptions>> createGetOptions(boolean noFetch) {
        LOGGER.trace("noFetch = {}", noFetch);
        return noFetch ? SelectorOptions.createCollection(GetOperationOptions.createNoFetch()) : null;
    }

    public <T extends ObjectType> PrismObject<T> getObject(Class<T> type, String oid, boolean noFetch, ExecutionContext context, OperationResult result) throws ScriptExecutionException {
        try {
            return modelService.getObject(type, oid, createGetOptions(noFetch), context.getTask(), result);
        } catch (ConfigurationException|ObjectNotFoundException|SchemaException|CommunicationException|SecurityViolationException e) {
            throw new ScriptExecutionException("Couldn't get object: " + e.getMessage(), e);
        }
    }
}


text:
<?php

namespace sdk\Base\Exception;

use Exception;
use sdk\Base\Debug;
use sdk\Base\Log;
use sdk\Base\Sdk;
use sdk\Http\Exception\HttpException;
use sdk\Http\HttpResponse;
use sdk\Mvc\View;

/**
 * 最基础的异常类。 Translates exceptions using the [I18n] class.
 *
 * @package    Sdk
 * @category   Exceptions
 * @author     YwiSax
 */
class BaseException extends Exception implements ExceptionInterface
{

    /**
     * @var  array  PHP error code => human readable name
     */
    public static $phpErrors = [
        E_ERROR             => 'Fatal Error',
        E_USER_ERROR        => 'User Error',
        E_PARSE             => 'Parse Error',
        E_WARNING           => 'Warning',
        E_USER_WARNING      => 'User Warning',
        E_STRICT            => 'Strict',
        E_NOTICE            => 'Notice',
        E_RECOVERABLE_ERROR => 'Recoverable Error',
        E_DEPRECATED        => 'Deprecated',
    ];

    /**
     * @var  string  error rendering view
     */
    public static $errorView = 'sdk/error';

    /**
     * @var  string  error view content type
     */
    public static $errorViewContentType = 'text/html';

    /**
     * Creates a new translated exception.
     *     throw new BaseException('Something went terrible wrong, :user',
     *         [':user' => $user]);
     *
     * @param   string         $message   error message
     * @param   array          $variables translation variables
     * @param   integer|string $code      the exception code
     * @param   Exception      $previous  Previous exception
     */
    public function __construct($message = "", array $variables = null, $code = 0, Exception $previous = null)
    {
        $message = __($message, $variables);
        parent::__construct($message, (int) $code, $previous);
        $this->code = $code;
    }

    /**
     * Magic object-to-string method.
     *     echo $exception;
     *
     * @uses    BaseException::text
     * @return  string
     */
    public function __toString()
    {
        return self::text($this);
    }

    /**
     * 异常处理器,显示出错信息
     *
     * @param   Exception $e
     *
     * @return  void
     */
    public static function handler(Exception $e)
    {
        $response = self::_handler($e);
        echo $response->sendHeaders()->body;
        exit(1);
    }

    /**
     * 记录异常日志,同时返回一个用户输出异常提示的Response对象
     *
     * @param   Exception $e
     *
     * @return  HttpResponse
     */
    public static function _handler(Exception $e)
    {
        try
        {
            // Log the exception
            self::log($e);

            // Generate the response
            $response = self::response($e);

            return $response;
        }
        catch (Exception $e)
        {
            /**
             * Things are going *really* badly for us, We now have no choice
             * but to bail. Hard.
             */
            // Clean the output buffer if one exists
            ob_get_level() && ob_clean();
            // Set the Status code to 500, and Content-Type to text/plain.
            header('Content-Type: text/plain; charset=' . Sdk::$charset, true, 500);
            echo self::text($e);
            exit(1);
        }
    }

    /**
     * 记录异常信息
     *
     * @param   Exception $e
     */
    public static function log(Exception $e)
    {
        $error = self::text($e);
        Log::error($error);
    }

    /**
     * Get a single line of text representing the exception:
     * Error [ Code ]: Message ~ File [ Line ]
     *
     * @param   Exception $e
     *
     * @return  string
     */
    public static function text(Exception $e)
    {
        return sprintf('%s [ %s ]: %s ~ %s [ %d ]',
            get_class($e), $e->getCode(), strip_tags($e->getMessage()), Debug::path($e->getFile()), $e->getLine());
    }

    /**
     * Get a Response object representing the exception
     *
     * @uses    BaseException::text
     *
     * @param   Exception $e
     *
     * @return  HttpResponse
     */
    public static function response(Exception $e)
    {
        try
        {
            // Get the exception information
            $class = get_class($e);
            $code = $e->getCode();
            $message = $e->getMessage();
            $file = $e->getFile();
            $line = $e->getLine();
            $trace = $e->getTrace();

            /**
             * HTTP_Exceptions are constructed in the HTTP_Exception::factory()
             * method. We need to remove that entry from the trace and overwrite
             * the variables from above.
             */
            if ($e instanceof HttpException && $trace[0]['function'] == 'factory')
            {
                extract(array_shift($trace));
            }

            if ($e instanceof \ErrorException)
            {
                /**
                 * If XDebug is installed, and this is a fatal error,
                 * use XDebug to generate the stack trace
                 */
                if (function_exists('xdebug_get_function_stack') && $code == E_ERROR)
                {
                    $trace = array_slice(array_reverse(xdebug_get_function_stack()), 4);

                    foreach ($trace as & $frame)
                    {
                        /**
                         * XDebug pre 2.1.1 does not currently set the call type key
                         * http://bugs.xdebug.org/view.php?id=695
                         */
                        if ( ! isset($frame['type']))
                        {
                            $frame['type'] = '??';
                        }

                        // XDebug also has a different name for the parameters array
                        if (isset($frame['params']) && ! isset($frame['args']))
                        {
                            $frame['args'] = $frame['params'];
                        }
                    }
                }

                if (isset(self::$phpErrors[$code]))
                {
                    // Use the human-readable error name
                    $code = self::$phpErrors[$code];
                }
            }

            /**
             * The stack trace becomes unmanageable inside PHPUnit.
             * The error view ends up several GB in size, taking several minutes to render.
             */
            if (defined('PHPUnit_MAIN_METHOD'))
            {
                $trace = array_slice($trace, 0, 2);
            }

            // Instantiate the error view.
            $view = View::factory(self::$errorView, get_defined_vars());

            // Prepare the response object.
            $response = HttpResponse::factory();

            // Set the response status
            $response->status = ($e instanceof HttpException) ? $e->getCode() : 500;

            // Set the response headers
            $response->headers('Content-Type', self::$errorViewContentType . '; charset=' . Sdk::$charset);

            // Set the response body
            $response->body = $view->render();
        }
        catch (Exception $e)
        {
            /**
             * Things are going badly for us, Lets try to keep things under control by
             * generating a simpler response object.
             */
            $response = HttpResponse::factory();
            $response->status = 500;
            $response->headers('Content-Type', 'text/plain');
            $response->body = self::text($e);
        }

        return $response;
    }

}


text:
import logging
import json as jsonify
from os import path
from urlparse import urljoin
from hashlib import md5

from requests import get, post
from requests.exceptions import HTTPError

from .cached import cache
from .consts import MaterialType, MsgType
from .errors import HttpError, BusinessError
from .wrapper import Custom, IP, User, Token, OpenID, Material, MaterialCount, response

__version__ = '0.1.0'

class Client(object):
    """微信client"""

    logger = logging.getLogger(__name__)
    version = __version__

    cache_token = 'Client.get_token'

    def __init__(self, proto, host, app_id, app_secret, grant_type=None, access_token=None):
        self.proto = proto
        self.host = host
        self.base_url = '{schema}://{host}'.format(
            schema=self.proto, host=self.host)
        self.app_id = app_id
        self.app_secret = app_secret
        self._access_token = access_token
        self.grant_type = grant_type or 'client_credential'

    @property
    def access_token(self):
        self._access_token = self._access_token or self.get_token()
        return self._access_token

    def generate_uuid(self, filepath):
        m = md5()
        m.update(filepath)
        return m.hexdigest()

    def get(self, uri, params=None, **kwargs):
        url = urljoin(self.base_url, uri)
        r = get(url, params, **kwargs)
        try:
            if r.ok:
                json = r.json()
                if 'errcode' in json:
                    raise BusinessError(json)
                return json
        except HTTPError as e:
            raise HttpError(e)

    def post(self, uri, data=None, json=None, **kwargs):
        url = urljoin(self.base_url, uri)
        payload = jsonify.dumps(data, ensure_ascii=False)
        if not isinstance(payload, bytes):
            payload = payload.encode('utf-8')
        r = post(url, payload, json, **kwargs)
        try:
            if r.ok:
                json = r.json()
                code = json.get('errcode')
                if code and code < 1:
                    raise BusinessError(json)
                return json
        except HTTPError as e:
            raise HttpError(e)

    @response(Token)
    @cache(cache_token, time=7200)
    def get_token(self, grant_type=None):
        uri = '/cgi-bin/token'
        grant_type = grant_type or self.grant_type
        params = dict(grant_type=grant_type, appid=self.app_id,
                      secret=self.app_secret)
        return self.get(uri, params=params)

    @response(IP)
    def get_ips(self):
        uri = '/cgi-bin/getcallbackip'
        params = dict(access_token=self.access_token.access_token)
        return self.get(uri, params=params)

    @response(OpenID)
    def get_users(self, next_openid=None):
        """获取关注者列表"""
        uri = '/cgi-bin/user/get'
        params = dict(access_token=self.access_token.access_token,
                      next_openid=next_openid or '')

        return self.get(uri, params=params)

    @response(User)
    def get_user_info(self, openid, lang='zh_CN'):
        """获取关注者信息
            :parameter openid: 关注者的openid
            :parameter lang: 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语
        """
        uri = '/cgi-bin/user/info'
        params = dict(access_token=self.access_token.access_token,
                      openid=openid, lang=lang)

        return self.get(uri, params=params)

    @response(User)
    def get_users_batch(self):
        """
            批量获取用户基本信息
        """
        uri = '/cgi-bin/user/info/batchget'
        params = dict(access_token=self.access_token.access_token)

        return self.post(uri, data=params)

    @response(Material)
    def get_materials(self, material_type=MaterialType.news, offset=0, count=20):
        """
            获取素材列表
            return: {u'item': [], u'total_count': 0, u'item_count': 0}
        """
        uri = '/cgi-bin/material/batchget_material?access_token={}'.format(
            self.access_token.access_token)
        params = dict(type=material_type.value, offset=offset, count=count)
        return self.post(uri, data=params)

    @response(MaterialCount)
    def get_materials_count(self):
        """
            获取素材数量
        """
        uri = '/cgi-bin/material/get_materialcount?access_token={}'.format(
            self.access_token.access_token)

        return self.get(uri)

    @response(MaterialCount)
    def upload_materials(self, filepath, material_type=MaterialType.image):
        """
            上传素材
            1、对于临时素材,每个素材(media_id)会在开发者上传或粉丝发送到微信服务器3天后自动删除(所以用户发送给开发者的素材,若开发者需要,应尽快下载到本地),以节省服务器资源。
            2、media_id是可复用的。
            3、素材的格式大小等要求与公众平台官网一致。具体是,图片大小不超过2M,支持bmp/png/jpeg/jpg/gif格式,语音大小不超过5M,长度不超过60秒,支持mp3/wma/wav/amr格式
            4、需使用https调用本接口。
        """
        uri = '/cgi-bin/media/upload?access_token={}&type={}'.format(
            self.access_token.access_token, material_type.value)
        # 检查文件存在
        if not path.exists(filepath):
            return
        # 文件大小限制
        file_size = path.getsize(filepath)
        if file_size > 5 * 1024 * 1024:
            return

        file_ext = path.splitext(filepath)[1]
        filename = '{}{}'.format(self.generate_uuid(filepath), file_ext)
        files = {'file': (filename, open(filepath, 'rb'),
                          'application/oct-stream', {'Expires': '0'})}
        return self.post(uri, files=files)

    @response(Custom)
    def send_msg(self, content, openid, msg_type=MsgType.text):
        uri = '/cgi-bin/message/custom/send?access_token={}'.format(self.access_token.access_token)
        params = dict(msgtype=msg_type.value, touser=openid)
        if msg_type is MsgType.text:
            params[msg_type.value] = dict(content=content)
        return self.post(uri, data=params)


text:
import os
import sys
import Queue
import thread
import traceback

class AsyncIterate:

    def __init__(self,it):
        self.it=it
        self.instance=None
        self.quitflag=False
        self.q=Queue.Queue(2)

    def __copy__(self):
        return AsyncIterate(self.it)

    def __call__(self,*args,**kwargs):
        assert self.instance is None
        self.instance=self.it(*args,**kwargs)
        if self.instance is not None:
            thread.start_new_thread(self.backend,())
            data=self.q.get()
            while data is not None:
                try:
                    yield data
                except GeneratorExit:
                    #print 'GeneratorExit'
                    self.quitflag=True
                    #self.instance.close()
                    while self.q.get() is not None:
                        pass
                    break
                data=self.q.get()
            #print 'end'
            self.instance=None
            self.quitflag=False

    def backend(self):
        try:
            while True:
                data=self.instance.next()
                if self.quitflag:
                    self.instance.close()
                if data is not None:
                    self.q.put(data)
        except (GeneratorExit,StopIteration):
            self.q.put(None)
        except:
            print "Unexpected error:", sys.exc_info()[0]
            traceback.print_exc()
            os._exit(1)

if __name__=='__main__':
    def myit(n):
        for x in range(n):
            yield x

    iterator=AsyncIterate(myit)

    it=iterator(5)
    for t in it:
        print t
        it.close()
        break
    it=iterator(5)
    for t in it:
        print t


text:
goog.provide('audioCat.state.effect.EffectModel');

goog.require('audioCat.state.effect.EffectCategory');
goog.require('audioCat.state.effect.EffectId');

/**
 * Models the parameters for an effect.
 * @param {audioCat.state.effect.EffectId} effectId The ID of the effect. The
 *     effect model controller uses this ID to map to this model.
 * @param {audioCat.state.effect.EffectCategory} effectCategory The category of
 *     the effect. Is it a filter for instance?
 * @param {string} name The lowercase name of the effect.
 * @param {string} abbreviation The abbreviation of the effect. Used for compact
 *     display.
 * @param {string} description The description of the effect.
 * @constructor
 */
audioCat.state.effect.EffectModel = function(
    effectId,
    effectCategory,
    name,
    abbreviation,
    description) {
  /**
   * The ID of the effect.
   * @private {audioCat.state.effect.EffectId}
   */
  this.effectId_ = effectId;

  /**
   * The category of the effect.
   * @private {audioCat.state.effect.EffectCategory}
   */
  this.effectCategory_ = effectCategory;

  /**
   * The name of the effect.
   * @private {string}
   */
  this.name_ = name;

  /**
   * The abbreviation of the effect.
   * @private {string}
   */
  this.abbreviation_ = abbreviation;

  /**
   * The description of the effect.
   * @private {string}
   */
  this.description_ = description;
};

/**
 * Creates a default effect instance of this model.
 * @param {!audioCat.state.effect.EffectModelController} effectModelController
 *     Manages the different models of effects.
 * @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
 *     throughout the application.
 * @return {!audioCat.state.effect.Effect} The effect created.
 */
audioCat.state.effect.EffectModel.prototype.createDefaultEffect =
    goog.abstractMethod;

/**
 * @return {audioCat.state.effect.EffectId} The effect ID.
 */
audioCat.state.effect.EffectModel.prototype.getEffectModelId = function() {
  return this.effectId_;
};

/**
 * @return {audioCat.state.effect.EffectCategory} The category of the effect.
 */
audioCat.state.effect.EffectModel.prototype.getEffectCategory = function() {
  return this.effectCategory_;
};

/**
 * @return {string} The name of the effect.
 */
audioCat.state.effect.EffectModel.prototype.getName = function() {
  return this.name_;
};

/**
 * @return {string} The lowercased abbreviation of the effect.
 */
audioCat.state.effect.EffectModel.prototype.getAbbreviation = function() {
  return this.abbreviation_;
};

/**
 * @return {string} The description of the effect.
 */
audioCat.state.effect.EffectModel.prototype.getDescription = function() {
  return this.description_;
};


text:
'use strict';

var gulp = require('gulp');
var debug = require('gulp-debug');

function buildIndex() {
  console.log('building index');

  return gulp
    .src('./source/index.html')
    .pipe(debug({
      verbose: true
    }))
    .pipe(gulp.dest('./public'));
}

gulp.task('build-index', buildIndex);


text:
package brennus;

import brennus.ExpressionBuilder.ExpressionHandler;
import brennus.model.Expression;

final class ArrayIndexExpressionBuilderFactory<T>
    implements
    ExpressionBuilderFactory<T, ArrayIndexExpressionBuilder<T>, ArrayIndexValueExpressionBuilder<T>> {

  @Override
  public ArrayIndexValueExpressionBuilder<T> newValueExpressionBuilder(
      brennus.ExpressionBuilder.ExpressionHandler<T> expressionHandler,
      Expression expression) {
    return new ArrayIndexValueExpressionBuilder<T>(expressionHandler, expression);
  }

  @Override
  public ArrayIndexExpressionBuilder<T> newExpressionBuilder(
      ExpressionHandler<T> expressionHandler) {
    return new ArrayIndexExpressionBuilder<T>(expressionHandler);
  }

}


text:
package com.github.obsessive.simplifyreader.presenter;

import com.github.obsessive.simplifyreader.bean.MusicsListEntity;

/**
 * Author:  Tau.Chen
 * Email:   1076559197@qq.com | tauchen1990@gmail.com
 * Date:    2015/4/16.
 * Description:
 */
public interface MusicsPresenter {

    void loadListData(String requestTag, String keywords, int event_tag);

    void onNextClick();

    void onPrevClick();

    void onStartPlay();

    void onPausePlay();

    void onRePlay();

    void seekTo(int position);

    void onStopPlay();

    void refreshPageInfo(MusicsListEntity entity, int totalDuration);

    void refreshProgress(int progress);

    void refreshSecondProgress(int progress);
}


text:
package org.gradle.api.internal.tasks.testing.logging;

import org.gradle.api.tasks.testing.TestDescriptor;
import org.gradle.api.tasks.testing.TestListener;
import org.gradle.api.tasks.testing.TestResult;
import org.gradle.internal.logging.progress.ProgressLogger;
import org.gradle.internal.logging.progress.ProgressLoggerFactory;
import org.gradle.util.internal.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestCountLogger implements TestListener {
    private final ProgressLoggerFactory factory;
    private ProgressLogger progressLogger;
    private final Logger logger;

    private long totalTests;
    private long failedTests;
    private long skippedTests;
    private boolean hadFailures;

    public TestCountLogger(ProgressLoggerFactory factory) {
        this(factory, LoggerFactory.getLogger(TestCountLogger.class));
    }

    TestCountLogger(ProgressLoggerFactory factory, Logger logger) {
        this.factory = factory;
        this.logger = logger;
    }

    @Override
    public void beforeTest(TestDescriptor testDescriptor) {
    }

    @Override
    public void afterTest(TestDescriptor testDescriptor, TestResult result) {
        totalTests += result.getTestCount();
        failedTests += result.getFailedTestCount();
        skippedTests += result.getSkippedTestCount();
        progressLogger.progress(summary());
    }

    private String summary() {
        StringBuilder builder = new StringBuilder();
        append(builder, totalTests, "test");
        builder.append(" completed");
        if (failedTests > 0) {
            builder.append(", ");
            builder.append(failedTests);
            builder.append(" failed");
        }
        if (skippedTests > 0) {
            builder.append(", ");
            builder.append(skippedTests);
            builder.append(" skipped");
        }
        return builder.toString();
    }

    private void append(StringBuilder dest, long count, String noun) {
        dest.append(count);
        dest.append(" ");
        dest.append(noun);
        if (count != 1) {
            dest.append("s");
        }
    }

    @Override
    public void beforeSuite(TestDescriptor suite) {
        if (suite.getParent() == null) {
            progressLogger = factory.newOperation(TestCountLogger.class);
            progressLogger.setDescription("Run tests");
            progressLogger.started();
            progressLogger.progress(summary());
        }
    }

    @Override
    public void afterSuite(TestDescriptor suite, TestResult result) {
        if (suite.getParent() == null) {
            if (failedTests > 0) {
                logger.error(TextUtil.getPlatformLineSeparator() + summary());
            }
            progressLogger.completed();

            if (result.getResultType() == TestResult.ResultType.FAILURE) {
                hadFailures = true;
            }
        }
    }

    public boolean hadFailures() {
        return hadFailures;
    }

    public long getTotalTests() {
        return totalTests;
    }
}


text:
<?php

date_default_timezone_set('Europe/Berlin');

// set include path
ini_set("include_path", ".:../library/");

// required classes
require_once 'spoon/spoon.php';
require_once 'publicApp/publicApp.php';

$tpl = new SpoonTemplate();
$tpl->setForceCompile(true);
$tpl->setCompileDirectory('./compiled_templates');

/*
 * Start the login magic
 * @joenmaes
 */

// facebook php
require_once 'facebook/facebook.php';

// Create our Application instance
$facebook = new Facebook(array(
  'appId'  => '177481728946474',
  'secret' => '6d5db3a0e538eb5aa7bebe6ae0bb2efe',
  'cookie' => true,
));

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

// facebook javascript
$tpl->assign('appid', $facebook->getAppId());
$tpl->assign('session', json_encode($session));

/*
 * End the login magic
 * @joenmaes
 */

if(SpoonSession::exists('public_uid')){
    //show logout
    $tpl->assign('oLogout', true);
}

//Content layout
$tpl->assign('oNavPubs', true);

$lat = SpoonFilter::getGetValue('lat', null, '');
$long = SpoonFilter::getGetValue('long', null, '');
$pubs = array();

if ($lat !== "" && $long !== "") {
    $tpl->assign('latitude', $lat);
    $tpl->assign('longitude', $long);

    $pubs = Pub::getPubsByLocation($lat, $long);

    $abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for($i = 0; $i< sizeof($pubs); $i++){
        $pub = new Pub($pubs[$i]["pub_id"]);

        $pubs[$i]["letter"] = substr($abc, $i, 1);;

        $pubs[$i]["people"] = $pub->getNumberPeople();
        $pubs[$i]["checkins"] = $pub->getNumberCheckins();
    }
} else {
    $tpl->assign('latitude', '""');
    $tpl->assign('longitude', '""');
}

if($pubs !== null){$tpl->assign('iPubs', $pubs);}
else{$tpl->assign('iPubs', array());}

$tpl->assign('intoHead', '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    <script>
        $(document).ready(function() {
            var longitude = {$longitude};
            var latitude = {$latitude};

            //Reverse Geocoding (Address Lookup)
            var geocoder = new google.maps.Geocoder();

            var latlng = new google.maps.LatLng(latitude, longitude);
            geocoder.geocode({"latLng": latlng}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        document.querySelector(".loc").innerHTML = results[0].formatted_address;
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
            });
        });
    </script>');

// show the output
$tpl->assign('content', $tpl->getContent('templates/pubs.tpl'));
$tpl->display('templates/layout.tpl');
?>


text:
import numpy
import cPickle

import theano
import theano.tensor as T
from mlp.logistic_sgd import LogisticRegression
from mlp.hidden_layer import HiddenLayer
from dA.AutoEncoder import AutoEncoder
from SdA import SdA

from theano.tensor.shared_randomstreams import RandomStreams

from extract_datasets import extract_unlabeled_chunkrange
from load_shared import load_data_unlabeled
from tables import openFile

import os
import sys
import time
from datetime import datetime
from optparse import OptionParser

def test_mom_wd(filename, num_epochs=10, momentum=0., weight_decay=0., pretrain_lr=0.001, batch_size=10):
    """

    Pretrain an SdA model using momentum, weight-decay, or both
    for the given number of training epochs.  The model is initialized from scratch.

    :type filename: string
    :param filename: the prefix for the name of the file capturing the output of this test

    :type num_epochs: int
    :param num_epochs: number of epoch to do pretraining

    :type momentum: float
    :param momentum: momentum rate for updating parameters when pre-training

    :type weight_decay: float
    :param weight_decay: multiplicative factor for degrading the size of updates to weights
    effectively penalizing larger weights.

    :type pretrain_lr: float
    :param pretrain_lr: learning rate to be used during pre-training

    :type batch_size: int
    :param batch_size: train in mini-batches of this size

    """

    current_dir = os.getcwd()

    os.chdir(options.dir)
    today = datetime.today()
    day = str(today.date())
    hour = str(today.time())
    output_filename = filename + "_sda_pretrain." + day + "." + hour
    output_file = open(output_filename,'w')
    os.chdir(current_dir)
    print >> output_file, "Run on " + str(datetime.now())

    # Get the training data sample from the input file
    data_set_file = openFile(str(options.inputfile), mode = 'r')
    datafiles = extract_unlabeled_chunkrange(data_set_file, num_files = 10)
    train_set_x = load_data_unlabeled(datafiles)
    data_set_file.close()

    # compute number of minibatches for training, validation and testing
    n_train_batches, n_features = train_set_x.get_value(borrow=True).shape
    n_train_batches /= batch_size

    # numpy random generator
    numpy_rng = numpy.random.RandomState(89677)
    print '... building the model'

    sda_model = SdA(numpy_rng=numpy_rng, n_ins=n_features,
              hidden_layers_sizes=[700, 700, 300, 50],
              corruption_levels = [0.2,0.2,0.2,0.2],
              n_outs=3, dA_losses=['squared','xent','xent','xent'])

    #########################
    # PRETRAINING THE MODEL #
    #########################
    print '... getting the pretraining functions'
    pretraining_fns = sda_model.pretraining_functions(train_set_x=train_set_x,
                                                batch_size=batch_size)

    print '... pre-training the model'
    start_time = time.clock()
    ## Pre-train layer-wise
    corruption_levels = [float(options.corruption), float(options.corruption), float(options.corruption), float(options.corruption)]
    for i in xrange(sda_model.n_layers):

        for epoch in xrange(num_epochs):
            # go through the training set
            c = []
            for batch_index in xrange(n_train_batches):
                c.append(pretraining_fns[i](index=batch_index,
                         corruption=corruption_levels[i],
                         lr=pretrain_lr,
                         momentum=momentum,
                         weight_decay=weight_decay))
            print >> output_file, 'Pre-training layer %i, epoch %d, cost ' % (i, epoch),
            print >> output_file, numpy.mean(c)

    end_time = time.clock()

    print >> output_file, ('Pretraining time for file ' +
                          os.path.split(__file__)[1] +
                          ' was %.2fm to go through %i epochs' % (((end_time - start_time) / 60.), (num_epochs / 2)))

    output_file.close()

def test_unpickled_SdA(num_epochs=10, pretrain_lr=0.001, batch_size=10):
    """ Unpickle an SdA from file, continue pre-training for a given number of epochs.

    :type num_epochs: int
    :param num_epochs: number of epoch to do pretraining

    :type pretrain_lr: float
    :param pretrain_lr: learning rate to be used during pre-training

    :type batch_size: int
    :param batch_size: train in mini-batches of this size
    """

    current_dir = os.getcwd()

    os.chdir(options.dir)
    today = datetime.today()
    day = str(today.date())
    hour = str(today.time())
    output_filename = "test_unpickled_stacked_denoising_autoencoder_pretrain." + day + "." + hour
    output_file = open(output_filename,'w')
    os.chdir(current_dir)
    print >> output_file, "Run on " + str(datetime.now())

    # Get the training data sample from the input file
    data_set_file = openFile(str(options.inputfile), mode = 'r')
    datafiles = extract_unlabeled_chunkrange(data_set_file, num_files = 10)
    train_set_x = load_data_unlabeled(datafiles)
    data_set_file.close()

    # compute number of minibatches for training, validation and testing
    n_train_batches, n_features = train_set_x.get_value(borrow=True).shape
    n_train_batches /= batch_size

    # Unpickle the SdA
    print >> output_file, 'Unpickling the model...'
    f = file(options.savefile, 'rb')
    pickled_sda = cPickle.load(f)
    f.close()

    # Train for the remaining
    pretraining_fns = pickled_sda.pretraining_functions(train_set_x=train_set_x,
                                                    batch_size=batch_size)

    print >> output_file, 'Resume training...'
    start_time = time.clock()
    ## Pre-train layer-wise
    corruption_levels = [float(options.corruption), float(options.corruption), float(options.corruption)]
    for i in xrange(pickled_sda.n_layers):
        # pickle the current model, along with the current epoch run
        # TODO: pickling code here.

        for epoch in xrange(num_epochs / 2):
            # go through the training set
            c = []
            for batch_index in xrange(n_train_batches):
                c.append(pretraining_fns[i](index=batch_index,
                         corruption=corruption_levels[i],
                         lr=pretrain_lr))
            print >> output_file, 'Pre-training layer %i, epoch %d, cost ' % (i, epoch),
            print >> output_file, numpy.mean(c)

    end_time = time.clock()
    print >> output_file, ('Pretraining time for file ' +
                          os.path.split(__file__)[1] +
                          ' was %.2fm to go through the remaining %i epochs' % (((end_time - start_time) / 60.), (num_epochs / 2)))

    # Test that the W-matrices for the dA layers are all close to the W-matrices for the MLP layers
    for i in xrange(pickled_sda.n_layers):
        dA_params = pickled_sda.dA_layers[i].get_params()
        MLP_params = pickled_sda.sigmoid_layers[i].get_params()

        if not numpy.allclose(dA_params[0].get_value(), MLP_params[0].get_value()):
            print >> output_file, ("numpy says that Ws in layer %i are not close" % (i))
        if not numpy.allclose(dA_params[1].get_value(), MLP_params[1].get_value()):
            print >> output_file, ("numpy says that the biases in layer %i are not close" % (i))

    output_file.close()

if __name__ == '__main__':
    parser = OptionParser()
    parser.add_option("-d", "--dir", dest="dir", help="test output directory")
    parser.add_option("-i", "--inputfile", dest="inputfile", help="the data (hdf5 file) prepended with an absolute path")
    parser.add_option("-c", "--corruption", dest="corruption", default=0.1, type='float', help="use this amount of corruption for the dAs")
    parser.add_option("-m", "--momentum", dest="momentum", type='float', default=0., help="use this amount of momentum")
    parser.add_option("-w", "--weightdecay", dest="weight_decay", type='float', default=0., help="use this amount of weight decay")
    parser.add_option("-l", "--learningrate", dest="learning_rate", type='float', default=0.01, help="use this learning rate")

    (options, args) = parser.parse_args()

    # test of momentum, no wd
    test_mom_wd(filename="momentum", momentum=options.momentum)

    # test of wd, no momentum
    test_mom_wd(filename="weight_decay", weight_decay=options.weight_decay)

    # test using both
    test_mom_wd(filename="mom_and_wd", momentum=options.momentum, weight_decay=options.weight_decay)

    # test using neither
    test_mom_wd(filename="no_mo_no_wd")


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;

namespace MappingSampleAddIns.AddLayer
{
  /// <summary>
  /// Represents a button that appears on the ribbon that, when clicked,
  /// brings up a dialog to allow you add a layer using a path or a url
  /// </summary>
  /// <remarks>
  /// Few examples:
  /// FeatureClass inside a FileGeodatabase:        C:\Data\MyFileGDB.gdb\Census
  /// A shape file inside a folder:                 \\Machine\SharedFolder\Census.shp
  /// Raster Dataset inside a FileGeodatabase:      C:\Data\MyFileGDB.gdb\DEM
  /// An image file inside a folder:                \\Machine\SharedFolder\Imagery.tif
  /// A map service layer:                          http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer
  /// A feature layer off a map or feature service: http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0
  /// A .lprx or .lpkx file:                        \\Machine\SharedFolder\Fires.lyrx
  /// </remarks>
  internal class AddLayer : Button
  {
    /// <summary>
    /// Brings up a WPF dialog to allow you enter a path or url to a layer
    /// </summary>
    protected override void OnClick()
    {
      AddLayerDlg addlayerDlg = new AddLayerDlg()
          {
            Width = 650,
            Height = 175
          };

      addlayerDlg.ShowDialog();
    }
  }
}


text:
require 'thrift'
require 'thrift_spec_types'

module SpecNamespace
end


text:
using std::vector;
using std::string;

#include "../math/math.h"


text:
package ru.rkhaustov.testtask;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

/**
 * Created by rvkha_000 on 04.05.2017.
 */
public class BracketsTest {
    /**
     * test "()()".
     */
    @Test
    public void whenBracketsFirstThenTrue() {
        Brackets brackets = new Brackets();
        boolean result = brackets.checkBrackets("()()");
        boolean expected = true;
        assertThat(result, is(expected));
    }
    /**
     * test item ))((.
     */
    @Test
    public void whenBracketsSecondThenFalse() {
        Brackets brackets = new Brackets();
        boolean result = brackets.checkBrackets("))((");
        boolean expected = false;
        assertThat(result, is(expected));
    }
    /**
     * test item ())(.
     */
    @Test
    public void whenBracketsThirdThenFalse() {
        Brackets brackets = new Brackets();
        boolean result = brackets.checkBrackets("())(");
        boolean expected = false;
        assertThat(result, is(expected));
    }
    /**
     * test item ())()(().
     */
    @Test
    public void whenBracketsFourthThenFalse() {
        Brackets brackets = new Brackets();
        boolean result = brackets.checkBrackets("())()(()");
        boolean expected = false;
        assertThat(result, is(expected));
    }
    /**
     * test item (((((((())()(())).
     */
    @Test
    public void whenBracketsFiveThenFalse() {
        Brackets brackets = new Brackets();
        boolean result = brackets.checkBrackets("(((((((())()(()))");
        boolean expected = false;
        assertThat(result, is(expected));
    }
}


text:
/* Licensed under the BSD. See License.txt for full text.  */

$(document).ready(function() {

    $(".add_volunteer").click(function() {

        id = $(this).attr("id");
        title = $("#" + id + "_stu_title").html();

        button = "<button id='' type='button' class='btn btn-danger btn-xs pull-right remove_volunteer'></button>"
        $("#volunteer_list").append("
" + button + title + "
");

        $(".remove_volunteer").on("click", function(){
            $(this).parent().remove();
        });
    });

    $(".add_activity").click(function() {

        id = $(this).attr("id");
        title = $("#" + id + "_act_title").html();

        button = "<button id='' type='button' class='btn btn-danger btn-xs pull-right remove_activity'></button>"
        $("#activity_list").append("
" + button + title + "
");

        $(".remove_activity").on("click", function(){
            $(this).parent().remove();
        });
    });

    $("#schedule_assign").click(function() {

        activity_ids = "";
        student_ids = "";

        $("#activity_list").find('li').each(function(){
            id = $(this).attr("id");
            activity_ids += id + ",";
        });

        $("#volunteer_list").find('li').each(function(){
            id = $(this).attr("id");
            student_ids += id + ",";
        });

        activity_ids = activity_ids.substring(0, activity_ids.length - 1);
        student_ids = student_ids.substring(0, student_ids.length - 1);

        bootbox.confirm("Are you sure you want to schedule these volunteers?", function(result) {
            if (result == true) {

                $.ajax({
                    type : "POST",
                    url : "php/schedule.php",
                    data : {
                        activity_ids : activity_ids,
                        student_ids : student_ids
                    }
                }).done(function(msg) {
                    if (msg == "true") {
                        setTimeout(function() {
                            bootbox.alert("Volunteers have been scheduled.", function() {
                                location.reload();
                            });
                        }, 1000);

                    } else {
                        bootbox.alert("Please make sure you have selected at least one volunteer and one activity.");
                    }
                });

            }
        });

    });
});


text:
use glib::{Cast, IsA, Object};
use gtk::{prelude::ContainerExt, prelude::WidgetExt};

use crate::state::EventStream;
use super::{Component, DisplayVariant, StreamHandle, create_widget, init_component};
use crate::widget::Widget;

/// Struct for relm containers to add GTK+ and relm `Widget`s.
pub struct ContainerComponent<WIDGET: Container + Widget> {
    component: Component<WIDGET>,
    /// The default container of this component.
    pub container: WIDGET::Container,
    /// Additional containers used for multi-containers. This can be () if not needed.
    pub containers: WIDGET::Containers,
}

impl<WIDGET: Container + Widget> ContainerComponent<WIDGET> {
    #[doc(hidden)]
    pub fn new(component: Component<WIDGET>, container: WIDGET::Container, containers: WIDGET::Containers) -> Self {
        ContainerComponent {
            component,
            container,
            containers,
        }
    }

    /// Add a GTK+ widget to a relm container.
    pub fn add<CHILDWIDGET: IsA<gtk::Widget>>(&self, widget: &CHILDWIDGET) {
        self.container.add(widget);
    }

    /// Add a relm widget to a relm container.
    pub fn add_widget<CHILDWIDGET>(&self, model_param: CHILDWIDGET::ModelParam)
        -> Component<CHILDWIDGET>
        where CHILDWIDGET: Widget + 'static,
              WIDGET::Container: ContainerExt + IsA<gtk::Widget> + IsA<Object>,
    {
        let (component, widget, child_relm) = create_widget::<CHILDWIDGET>(model_param);
        let container = WIDGET::add_widget(self, &component);
        widget.on_add(container);
        init_component::<CHILDWIDGET>(component.owned_stream(), widget, &child_relm);
        component
    }

    /// Emit a message of the widget stream.
    pub fn emit(&self, msg: WIDGET::Msg) {
        self.owned_stream().emit(msg);
    }

    /// Get the event stream of the component.
    /// This is used internally by the library.
    pub fn owned_stream(&self) -> &EventStream<WIDGET::Msg> {
        self.component.owned_stream()
    }

    /// Get the event stream of the component.
    /// This is used internally by the library.
    pub fn stream(&self) -> StreamHandle<WIDGET::Msg> {
        self.component.stream()
    }

    // TODO: add delete methods?

    /// Get the widget of the component.
    pub fn widget(&self) -> &WIDGET::Root {
        self.component.widget()
    }
}

/// Trait to implement relm container widget.
pub trait Container: Widget {
    /// The type of the containing widget, i.e. where the child widgets will be added.
    type Container: Clone + IsA<gtk::Container> + IsA<Object> + IsA<gtk::Widget>;
    /// Type to contain the additional container widgets.
    // TODO: put that in yet another trait?
    type Containers: Clone;

    /// Add a relm widget to this container.
    /// Return the widget that will be send to Widget::on_add().
    fn add_widget<WIDGET: Widget>(container: &ContainerComponent<Self>, component: &Component<WIDGET>)
        -> gtk::Container
    {
        container.container.add(component.widget());
        container.container.clone().upcast()
    }

    /// Get the containing widget, i.e. the widget where the children will be added.
    fn container(&self) -> &Self::Container;

    /// Get additional container widgets.
    /// This is useful to create a multi-container.
    fn other_containers(&self) -> Self::Containers;
}

/// Extension trait for GTK+ containers to add and remove relm `Widget`s.
pub trait ContainerWidget {
    /// Add a relm `Container` to the current GTK+ container.
    ///
    /// # Note
    ///
    /// The returned `ContainerComponent` must be stored in a `Widget`. If it is not stored, a
    /// communication receiver will be droped which will cause events to be ignored for this
    /// widget.
    fn add_container<CHILDWIDGET>(&self, model_param: CHILDWIDGET::ModelParam)
            -> ContainerComponent<CHILDWIDGET>
        where CHILDWIDGET: Container + Widget + 'static,
              CHILDWIDGET::Msg: DisplayVariant + 'static,
              CHILDWIDGET::Root: IsA<gtk::Widget> + IsA<Object> + WidgetExt;

    /// Add a relm `Widget` to the current GTK+ container.
    ///
    /// # Note
    ///
    /// The returned `Component` must be stored in a `Widget`. If it is not stored, a communication
    /// receiver will be droped which will cause events to be ignored for this widget.
    fn add_widget<CHILDWIDGET>(&self, model_param: CHILDWIDGET::ModelParam)
            -> Component<CHILDWIDGET>
        where CHILDWIDGET: Widget + 'static,
              CHILDWIDGET::Msg: DisplayVariant + 'static,
              CHILDWIDGET::Root: IsA<gtk::Widget> + IsA<Object> + WidgetExt;

    /// Remove a relm `Widget` from the current GTK+ container.
    fn remove_widget<CHILDWIDGET>(&self, component: Component<CHILDWIDGET>)
        where CHILDWIDGET: Widget,
              CHILDWIDGET::Root: IsA<gtk::Widget>;
}

impl<W: Clone + ContainerExt + IsA<gtk::Widget> + IsA<Object>> ContainerWidget for W {
    fn add_container<CHILDWIDGET>(&self, model_param: CHILDWIDGET::ModelParam)
            -> ContainerComponent<CHILDWIDGET>
        where CHILDWIDGET: Container + Widget + 'static,
              CHILDWIDGET::Msg: DisplayVariant + 'static,
              CHILDWIDGET::Root: IsA<gtk::Widget> + IsA<Object> + WidgetExt,
    {
        let (component, widget, child_relm) = create_widget::<CHILDWIDGET>(model_param);
        let container = widget.container().clone();
        let containers = widget.other_containers();
        let root = widget.root();
        self.add(&root);
        widget.on_add(self.clone());
        init_component::<CHILDWIDGET>(component.owned_stream(), widget, &child_relm);
        ContainerComponent::new(component, container, containers)
    }

    fn add_widget<CHILDWIDGET>(&self, model_param: CHILDWIDGET::ModelParam)
            -> Component<CHILDWIDGET>
        where CHILDWIDGET: Widget + 'static,
              CHILDWIDGET::Msg: DisplayVariant + 'static,
              CHILDWIDGET::Root: IsA<gtk::Widget> + IsA<Object> + WidgetExt,
    {
        let (component, widget, child_relm) = create_widget::<CHILDWIDGET>(model_param);
        self.add(component.widget());
        widget.on_add(self.clone());
        init_component::<CHILDWIDGET>(component.owned_stream(), widget, &child_relm);
        component
    }

    // TODO: we're probably not calling remove_widget() when removing a relm widget from a gtk
    // widget.
    fn remove_widget<WIDGET>(&self, component: Component<WIDGET>)
        where WIDGET: Widget,
              WIDGET::Root: IsA<gtk::Widget>,
    {
        self.remove(component.widget());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EgovaDAO;
using Tools;

public partial class Government_AppBHGD_BatchList : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadList();
            BindDll();
        }
    }

    private void LoadList()
    {
        EgovaDB db = new EgovaDB();
        var dbbatch = from b in db.TC_BHGD_Batch
                      join f in db.TC_BHGD_PrjItemMappingBatch on b.FId equals f.FBatchId
                      //join q in db.TC_BZGD_Record on f.FPrjItemId equals q.FPrjItemId
                      select new
                      {
                          FId = b.FId,
                          FYear = b.FYear,
                          FBatchNumber = b.FBatchNumber,
                          工程名称 = db.TC_BZGD_Record.FirstOrDefault(t => t.FPrjItemId == f.FPrjItemId).ProjectName,
                          申报单位 = "",
                          审批环节 = "未读取"
                      };
        gv_list.DataSource = dbbatch;
        gv_list.DataBind();
    }

    private void BindDll() {
        EgovaDB db = new EgovaDB();
        var yearlist = from q in db.TC_BHGD_Batch
                       group q by q.FYear into p
                       select new { FYear = p.Key};

        ddlYear.DataTextField = "FYear";
        ddlYear.DataValueField = "FYear";
        ddlYear.DataSource = yearlist;
        ddlYear.DataBind();

    }

    public void BtnQuery(object sender, EventArgs e)
    {
        LoadList();
    }

    protected void App_List_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemIndex > -1)
        {
            e.Item.Cells[1].Text =
                (e.Item.ItemIndex + 1 + this.Pager1.PageSize*(this.Pager1.CurrentPageIndex - 1)).ToString();
            string fId = EConvert.ToString(DataBinder.Eval(e.Item.DataItem, "FID"));

            e.Item.Cells[2].Text = "" + e.Item.Cells[2].Text + "";
        }
    }
    //分页面控件翻页事件
    protected void Pager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
    {
        Pager1.CurrentPageIndex = e.NewPageIndex;
        LoadList();
    }

    public void BtnDel_Click(object sender,EventArgs e)
    {
        EgovaDB dbContext = new EgovaDB();
        pageTool tool = new pageTool(this.Page);
        tool.DelInfoFromGrid(gv_list, dbContext.TC_BHGD_Batch, tool_Deleting);
        LoadList();
    }

    private void tool_Deleting(IList<string> FIdList, System.Data.Linq.DataContext context)
    {
        EgovaDB db = new EgovaDB();
        var mapping = from d in  db.TC_BHGD_PrjItemMappingBatch
                      where FIdList.ToArray().Contains(d.FBatchId)
                      select d;
        db.TC_BHGD_PrjItemMappingBatch.DeleteOnSubmit(mapping.FirstOrDefault());
        db.SubmitChanges();
    }
}


text:
#ifndef M3_PWR_EC_H
#define M3_PWR_EC_H

#include "m3rt/base/component.h"
#include "m3rt/base/component_ec.h"
#include "m3/hardware/pwr_ec.pb.h"
#include <google/protobuf/message.h>

namespace m3{
using namespace std;

class M3PwrEc : public  m3rt::M3ComponentEc{
	public:
		M3PwrEc(): toggle(0),m3rt::M3ComponentEc()
		{
			RegisterVersion("default",DEFAULT);	//RBL
			RegisterVersion("iss",ISS);		//ISS. Same as DEFAULT
			RegisterVersion("hrl",HRL);
			RegisterPdo("pwr_pdo_v0",PWR_PDO_V0);	//HRL
			RegisterPdo("pwr_pdo_v1",PWR_PDO_V1);	//RBL
			RegisterPdo("pwr_pdo_v2",PWR_PDO_V2);	//Dropped mode_remote functionality
			enable_buzzer=0;
		}
		google::protobuf::Message * GetCommand(){return &command;}
		google::protobuf::Message * GetStatus(){return &status;}
		google::protobuf::Message * GetParam(){return &param;}
		void SetEnableBuzzer(int val){enable_buzzer=val;}
	protected:
		bool ReadConfig(const char * filename);
		M3EtherCATStatus * GetEcStatus(){return status.mutable_ethercat();}
		size_t GetStatusPdoSize();
		size_t GetCommandPdoSize();
		void SetStatusFromPdo(unsigned char * data);
		void SetPdoFromCommand(unsigned char * data);

	protected:
		enum {PWR_PDO_V1, PWR_PDO_V2,PWR_PDO_V0};
		enum {DEFAULT,ISS,HRL};
		M3BaseStatus * GetBaseStatus(){return status.mutable_base();}
		M3PwrEcStatus status;
		M3PwrEcCommand command;
		M3PwrEcParam param;
		int tmp_cnt;
		int enable_buzzer;
		int toggle;
};

}
#endif


text:
*Proof of Concept*

This project was created with no third party library in client side.

## Install dependencies

Run `npm install`.

## Development

Run `gulp` to start the stack.


text:
=============================================================
PhenoteFX: A tool for annotating the Human Phenotype Ontology
=============================================================

PhenoteFX is a Desktop Java App  for working with  Human Phenotype Ontology (HPO) Annotation data. It
is designed to help curators revise or create phenotype annotation records for Human Phenotype Ontology (HPO)
rare disease data. PhenoteFX is currently at version 0.4.5.

.. figure:: img/PhenoteOverview.png
    :scale: 50 %
    :alt: PhenoteFX - overview

--------
Feedback
--------

The best place to leave feedback, ask questions, and report bugs is the `PhenoteFX Issue Tracker <https://github.com/monarch-initiative/PhenoteFX/issues>`_.

.. toctree::
    :caption: Installation & Tutorial
    :name: tutorial
    :maxdepth: 1
    :hidden:

    install
    tutorial_setup
    tutorial_local_hpo
    tutorial_working

.. toctree::
    :caption: Project Info
    :name: project-info
    :maxdepth: 1
    :hidden:

    contributing
    authors
    history
    license
  #  release_howto


text:
package org.innovateuk.ifs.util;

import org.innovateuk.ifs.commons.resource.PageResource;
import org.springframework.data.domain.Page;

import java.util.function.Function;
import java.util.stream.Collectors;

public class PageUtil {

    public static <R> PageResource<R> toPageResource(Page<R> page) {
        return new PageResource<R>(
                page.getTotalElements(),
                page.getTotalPages(),
                page.getContent(),
                page.getNumber(),
                page.getSize()
        );
    }

    public static <R, D> PageResource<R> toPageResource(Page<D> page, Function<D, R> mapper) {
        return new PageResource<R>(
                page.getTotalElements(),
                page.getTotalPages(),
                page.getContent().stream().map(mapper).collect(Collectors.toList()),
                page.getNumber(),
                page.getSize()
        );
    }
}


text:
Edit Article

    <form name="articleForm" class="form-horizontal" ng-submit="update(articleForm.$valid)" novalidate>
      <fieldset>

          Title
          <input name="title" type="text" ng-model="article.title" id="title" class="form-control" placeholder="Title" required>

Article title is required.

          Content
          <textarea name="content" ng-model="article.content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>

          Fragment
          <textarea name="content" ng-model="article.fragment" id="content" class="form-control" cols="30" rows="10" placeholder="Fragment"></textarea>

          New Fragment
          <textarea name="content" ng-model="article.fragment" id="content" class="form-control" cols="30" rows="10" placeholder="Fragment"></textarea>
          <input type="radio" ng-model="article.fragmentType" name="fragmentType" value="text" checked> Text

          <input type="radio" ng-model="article.fragmentType" name="fragmentType" value="link"> Link

          <input type="radio" ng-model="article.fragmentType" name="fragmentType" value="audio"> Audio

          <input type="radio" ng-model="article.fragmentType" name="fragmentType" value="video"> Video

          <input type="radio" ng-model="article.fragmentType" name="fragmentType" value="image"> Image

          <input type="submit" value="Update" class="btn btn-default">

      </fieldset>
    </form>


text:
/**
 * This is Free Software. See COPYING for information.
 */
#ifndef _PATH_FINDER_INTERFACE_HPP_
#define _PATH_FINDER_INTERFACE_HPP_

class Puzzle;

/**
 * Computes path from cells in a puzzle
 */
class PathFinderInterface {

public:

  virtual ~PathFinderInterface() {
  }

  virtual int find_path(Puzzle * o_p_puzzle,
			int i_i0, int i_j0,
			int i_i1, int i_j1,
			int move_type) = 0;

};

#endif // _PATH_FINDER_INTERFACE_HPP_


text:
<?php

// +----------------------------------------------------------------------+
// | OpenConf                                                             |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2017 Zakon Group LLC.  All Rights Reserved.       |
// +----------------------------------------------------------------------+
// | This source file is subject to the OpenConf License, available on    |
// | the OpenConf web site: www.OpenConf.com                              |
// +----------------------------------------------------------------------+

require_once "../include.php";

beginChairSession();

if (!OCC_ADVANCED_CONFIG) {
	$res = array('error' => 'Advanced configuration disabled');
}
elseif (!validToken('chair')) { // Check for valid submission
	$res = array('error' => 'Invalid Token');
}
elseif (isset($_POST['m']) && (($_POST['m'] == 'OC') || in_array($_POST['m'], $OC_activeModulesAR)) && isset($_POST['s']) && array_key_exists($_POST['s'], $OC_configAR)) {
	$q = "SELECT * FROM `" . OCC_TABLE_CONFIG . "` WHERE `module`='" . safeSQLstr(urldecode($_POST['m'])) . "' AND `setting`='" . safeSQLstr(urldecode($_POST['s'])) . "'";
	if ($r = ocsql_query($q)) {
		if (ocsql_num_rows($r) != 1) {
			$res = array('error' => 'Setting not found');
		} else {
			$res = array(
				'error' => '',
				'setting' => ocsql_fetch_assoc($r)
			);
		}
	} else {
		$res = array('error' => 'DB Error: ' . safeHTMLstr(ocsql_error()));
	}
} else {
	$res = array('error' => 'Invalid module or setting');
}

echo json_encode($res);

exit;

?>


text:
var express = require('express');
var router = express.Router();
var userService = require('app/services/user.service');
router.post('/authenticate', authenticateUser);
router.post('/register', register);
router.get('/currentUser', currentUser);
router.get('/token', currentUserToken);
module.exports = router;

function authenticateUser(req, res) {
    userService.authenticate(req.body.username, req.body.password)
        .then(function (token) {
            if (token) {
                req.session.token = token;
                res.sendStatus(200);
            } else {
                res.sendStatus(401);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}
function register(req, res) {
    userService.create(req.body)
        .then(function () {
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}
function currentUser(req, res) {
    userService.getById(req.user.sub)
        .then(function (user) {
            if (user) {
                res.send(user);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
}
function currentUserToken(req, res) {
    res.send(req.session.token);
}


text:
NSString *const kSFAErrorMessage = @"mesage";
NSString *const kSFAErrorType = @"errorType";

@implementation SFAError

- (SFAErrorType)errorType {
    return ((NSNumber *)self.userInfo[kSFAErrorType]).intValue;
}

+ (instancetype)errorWithMessage:(NSString *)message type:(SFAErrorType)errorType;
{
    NSMutableDictionary *dictionary = [NSMutableDictionary new];
    if (message) {
        dictionary[kSFAErrorMessage] = message;
    }
    dictionary[kSFAErrorType] = [NSNumber numberWithInteger:errorType];
    return [[[self class] alloc] initWithDomain:NSStringFromClass([self class]) code:0 userInfo:[dictionary copy]];
}

+ (instancetype)errorWithMessage:(NSString *)message type:(SFAErrorType)errorType domain:(NSString *)domain code:(NSInteger)code userInfo:(NSDictionary *)dict {
    return [self errorWithMessage:message type:errorType domain:domain code:code underlyingError:nil userInfo:dict];
}

+ (instancetype)errorWithMessage:(NSString *)message type:(SFAErrorType)errorType domain:(NSString *)domain code:(NSInteger)code underlyingError:(NSError *)error userInfo:(NSDictionary *)dict {
    NSMutableDictionary *userInfoDict = [dict mutableCopy];
    if (!userInfoDict) {
        userInfoDict = [NSMutableDictionary new];
    }
    if (message) {
        userInfoDict[kSFAErrorMessage] = message;
    }
    if (error) {
        userInfoDict[NSUnderlyingErrorKey] = error;
    }
    userInfoDict[kSFAErrorType] = [NSNumber numberWithInteger:errorType];

    return [[[self class] alloc] initWithDomain:domain code:code userInfo:[userInfoDict copy]];
}

- (NSError *)underlyingError {
    return self.userInfo[NSUnderlyingErrorKey];
}

- (NSString *)userFriendlyErrorMessage {
    return self.underlyingError.localizedFailureReason ? : self.underlyingError.localizedDescription ? : self.message;
}

- (NSString *)message {
    return self.userInfo[kSFAErrorMessage];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"\n%@:%@\n%@:%ld\n%@:%ld\n%@:%@ : %@", SFADomain, self.domain, SFAType, (long)self.errorType, SFACode, (long)self.code, SFAMessage, self.message, [self userFriendlyErrorMessage]];
}

@end


text:
/*
 * 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.
 */
package wvlet.airframe.surface

object QuoteParamTest {
  case class QP(`system-+=type`: String)
}

class QuoteParamTest extends SurfaceSpec {
  import QuoteParamTest._

  test("read quoted params") {
    val s   = Surface.of[QP]
    val obj = QP("A")
    val p   = s.params.head
    assertEquals(p.get(obj), obj.`system-+=type`)
  }
}


text:
using AWSAppender.Core.Services;
using AWSAppender.SNS.Model;

namespace AWSAppender.SNS.Parsers
{

    public interface ISNSEventMessageParser : IEventMessageParser<SNSDatum>
    {
        string DefaultTopic { get; set; }
        string DefaultMessage { get; set; }
        //int? DefaultDelaySeconds { get; set; }
    }
}


text:
using System;
using Vstack.Common;

namespace Vstack.Externals.ShipHawk.Model
{
    public class Rate
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string Id { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string Carrier { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string CarrierCode { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string ServiceName { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string ServiceLevel { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public decimal Price { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public DateTime EstDeliveryDate { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string OriginNetworkLocationId { get; private set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = SuppressionJustifications.CalledWithReflection)]
        public string DestinationNetworkLocationId { get; private set; }
    }
}


text:
@interface ImageLibraryViewController () <CropImageViewControllerDelegate>

@property (nonatomic, strong) PHFetchResult *result;

@end

@implementation ImageLibraryViewController

- (instancetype) init {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(100, 100);

    return [super initWithCollectionViewLayout:layout];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];

    self.collectionView.backgroundColor = [UIColor whiteColor];

    UIImage *cancelImage = [UIImage imageNamed:@"x"];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithImage:cancelImage style:UIBarButtonItemStyleDone target:self action:@selector(cancelPressed:)];
    self.navigationItem.leftBarButtonItem = cancelButton;
}

- (void) cancelPressed:(UIBarButtonItem *)sender {
    [self.delegate imageLibraryViewController:self didCompleteWithImage:nil];
}

- (void) loadAssets {
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

    [self.collectionView reloadData];

    self.result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:options];
}

- (void) viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    CGFloat width = CGRectGetWidth(self.view.frame);
    CGFloat minWidth = 100;
    NSInteger divisor = width / minWidth;
    CGFloat cellSize = width / divisor;

    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    flowLayout.itemSize = CGSizeMake(cellSize, cellSize);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self loadAssets];
                });
            }
        }];
    } else if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        [self loadAssets];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.result.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSInteger imageViewTag = 54321;

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:imageViewTag];

    if (!imageView) {
        imageView = [[UIImageView alloc] initWithFrame:cell.contentView.bounds];
        imageView.tag = imageViewTag;
        imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [cell.contentView addSubview:imageView];
    }

    if (cell.tag != 0) {
        [[PHImageManager defaultManager] cancelImageRequest:(PHImageRequestID)cell.tag];
    }

    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.collectionViewLayout;
    PHAsset *asset = self.result[indexPath.row];

    cell.tag = [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:flowLayout.itemSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage *result, NSDictionary *info) {
        UICollectionViewCell *cellToUpdate = [collectionView cellForItemAtIndexPath:indexPath];

        if (cellToUpdate) {
            UIImageView *imageView = (UIImageView *)[cellToUpdate.contentView viewWithTag:imageViewTag];
            imageView.image = result;
        }
    }];

    return cell;
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PHAsset *asset = self.result[indexPath.row];

    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    options.synchronous = YES;

    [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage *resultImage, NSDictionary *info)
     {
         CropImageViewController *cropVC = [[CropImageViewController alloc] initWithImage:resultImage];
         cropVC.delegate = self;
         [self.navigationController pushViewController:cropVC animated:YES];
     }];

}

#pragma mark - CropImageViewControllerDelegate

- (void) cropControllerFinishedWithImage:(UIImage *)croppedImage {
    [self.delegate imageLibraryViewController:self didCompleteWithImage:croppedImage];
}
@end


text:
using System;
using System.Drawing;

namespace stRrd.Graph
{
	internal class Legend : Comment
	{
		private Color color		= Color.White;
		private int refPlotDef	= -1;

		internal Legend( string text ) : base (text)
		{
			this.commentType = Comment.CMT_LEGEND;
		}

		internal Legend( string text, Color color ) : base (text)
		{
			if (text == null )
				this.commentType = Comment.CMT_NOLEGEND;
			else
                this.commentType = Comment.CMT_LEGEND;
			this.color = color;
		}

		internal Legend( string text, Color color, int referredPlotDef) : this (text, color)
		{
			refPlotDef = referredPlotDef;
		}

		internal Color Color
		{
			get
			{
				return color;
			}
		}

		internal int PlotDefIndex
		{
			get
			{
				return refPlotDef;
			}
		}

	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      This file is part of the Smart Developer Hub Project:
        http://www.smartdeveloperhub.org/

      Center for Open Middleware
        http://www.centeropenmiddleware.com/
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Copyright (C) 2015-2016 Center for Open Middleware.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      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.
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
      Artifact    : org.smartdeveloperhub.harvesters.ci.backend:ci-backend-core:0.3.0
      Bundle      : ci-backend-core-0.3.0.jar
    #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#

-->
<persistence
	xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
	version="2.1">
	<persistence-unit
		name="unitTests"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
		<mapping-file>backend.core.orm.xml</mapping-file>
		<properties>
			<!-- Default HSQLDB connection settings -->
			<property name="javax.persistence.jdbc.driver"   value="org.hsqldb.jdbc.JDBCDriver"/>
			<property name="javax.persistence.jdbc.url"      value="jdbc:hsqldb:mem:testDB"/>
			<property name="javax.persistence.jdbc.user"     value="sa"/>
			<property name="javax.persistence.jdbc.password" value=""/>

			<!-- DDL Script generation settings -->
			<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.create-target" value="target/ut-jpa21-model-source-create.ddl" />
			<property name="javax.persistence.schema-generation.scripts.drop-target" value="target/ut-jpa21-model-source-drop.ddl" />

			<!-- Settings for loading data at startup -->
			<property name="javax.persistence.sql-load-script-source" value="ut-insert.sql" />

			<!-- JDBC connection pool (use the built-in) -->
			<property name="connection.pool_size" value="1"/>

			<!-- SQL dialect -->
			<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

			<!-- Enable Hibernate's automatic session context management -->
			<property name="hibernate.current_session_context_class" value="thread"/>

			<!-- Disable the second-level cache -->
			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.internal.NoCacheProvider"/>

			<!-- Echo all executed SQL to stdout -->
			<property name="hibernate.show_sql" value="false"/>
			<!-- Pretty print echoed SQL -->
			<property name="hibernate.format_sql" value="true"/>

			<!-- Drop and re-create the database schema on startup -->
			<property name="hibernate.hbm2ddl.auto" value="update"/>
		</properties>
	</persistence-unit>
	<persistence-unit
		name="itTests"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
		<mapping-file>backend.core.orm.xml</mapping-file>
		<properties>
			<!-- Default HSQLDB connection settings -->
			<property name="javax.persistence.jdbc.driver"   value="org.hsqldb.jdbc.JDBCDriver"/>
			<property name="javax.persistence.jdbc.url"      value="jdbc:hsqldb:file:target/smoke_test.db;sql.enforce_strict_size=true;hsqldb.tx=locks;hsqldb.write_delay=false;hsqldb.default_table_type=CACHED"/>
			<property name="javax.persistence.jdbc.user"     value="sa"/>
			<property name="javax.persistence.jdbc.password" value=""/>

			<!-- DDL Script generation settings -->
			<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.create-target" value="target/it-jpa21-model-source-create.ddl" />
			<property name="javax.persistence.schema-generation.scripts.drop-target" value="target/it-jpa21-model-source-drop.ddl" />

			<!-- Settings for loading data at startup -->
			<property name="javax.persistence.sql-load-script-source" value="it-insert.sql" />

			<!-- JDBC connection pool (use the built-in) -->
			<property name="connection.pool_size" value="1"/>

			<!-- SQL dialect -->
			<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

			<!-- Enable Hibernate's automatic session context management -->
			<property name="hibernate.current_session_context_class" value="thread"/>

			<!-- Disable the second-level cache -->
			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.internal.NoCacheProvider"/>

<!--
			<property name="hibernate.connection.isolation" value="8"/>
 -->

			<!-- Echo all executed SQL to stdout -->
			<property name="hibernate.show_sql" value="false"/>
			<!-- Pretty print echoed SQL -->
			<property name="hibernate.format_sql" value="true"/>

			<!-- Drop and re-create the database schema on startup -->
			<property name="hibernate.hbm2ddl.auto" value="update"/>
		</properties>
	</persistence-unit>
	<persistence-unit
		name="itTestsDerby"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
		<mapping-file>backend.core.orm.xml</mapping-file>
		<properties>
			<!-- Default HSQLDB connection settings -->
			<property name="javax.persistence.jdbc.driver"   value="org.apache.derby.jdbc.EmbeddedDriver"/>
			<property name="javax.persistence.jdbc.url"      value="jdbc:derby:target/smokeTestDB;create=true"/>
			<property name="javax.persistence.jdbc.user"     value="username"/>
			<property name="javax.persistence.jdbc.password" value="password"/>

			<!-- DDL Script generation settings -->
			<property name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create" />
			<property name="javax.persistence.schema-generation.scripts.create-target" value="target/it-jpa21-model-source-create.ddl" />
			<property name="javax.persistence.schema-generation.scripts.drop-target" value="target/it-jpa21-model-source-drop.ddl" />

			<!-- Settings for loading data at startup -->
			<property name="javax.persistence.sql-load-script-source" value="it-insert.sql" />

			<!-- JDBC connection pool (use the built-in) -->
			<property name="connection.pool_size" value="1"/>

			<!-- SQL dialect -->
			<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>

			<!-- Enable Hibernate's automatic session context management -->
			<property name="hibernate.current_session_context_class" value="thread"/>

			<!-- Disable the second-level cache -->
			<property name="hibernate.cache.provider_class" value="org.hibernate.cache.internal.NoCacheProvider"/>

<!--
			<property name="hibernate.connection.isolation" value="8"/>
 -->

			<!-- Echo all executed SQL to stdout -->
			<property name="hibernate.show_sql" value="false"/>
			<!-- Pretty print echoed SQL -->
			<property name="hibernate.format_sql" value="true"/>

			<!-- Drop and re-create the database schema on startup -->
			<property name="hibernate.hbm2ddl.auto" value="update"/>
		</properties>
	</persistence-unit>
</persistence>