text:
package controllers.admin

import play.api.db.slick.Config.driver.simple._
import com.google.inject.Inject
import be.studiocredo.{UserService, NotificationService, UserContextSupport, VenueService}
import be.studiocredo.auth.AuthenticatorService
import models.ids.VenueId
import play.api.libs.json.{JsError, Json}
import models.entities._
import play.api.mvc.Result
import be.studiocredo.util.ServiceReturnValues._
import models.entities.Row
import models.entities.Venue
import models.entities.FloorPlan
import models.entities.SeatId
import scala.Some
import models.entities.Seat

class Floorplans @Inject()(venueService: VenueService, val authService: AuthenticatorService, val notificationService: NotificationService, val userService: UserService) extends AdminController with UserContextSupport {

  import FloorPlanJson._
  val defaultPlan = FloorPlan((1 to 10).map (row => Row((1 to 20).map ( seat => Seat(SeatId(s"$row-$seat"), SeatType.Normal, 1)).toList, 0)).toList)

  def view(id: VenueId) = AuthDBAction { implicit rs =>
    forVenue(id) { venue =>
      Ok(views.html.admin.venueFloorPlan(venue, userContext))
    }
  }

  def ajaxFloorPlan(id: VenueId) = AuthDBAction { implicit rs =>
    forVenue(id) { venue => Ok(Json.toJson(venue.floorplan.getOrElse(defaultPlan))) }
  }

  def ajaxSaveFloorPlan(id: VenueId) = AuthDBAction(parse.json) { implicit rs =>
    rs.body.validate[FloorPlan].map {
      plan => {
        venueService.update(id, plan).fold(
          error => BadRequest(serviceMessage(error)),
          success => Ok("")
        )
      }
    }.recoverTotal {
      e => BadRequest("Er heeft zich een fout voorgedaan:" + JsError.toFlatJson(e))
    }
  }

  def forVenue(id: VenueId)(found: Venue => Result)(implicit s: Session): Result = {
    venueService.get(id) match {
      case Some(venue) => found(venue)
      case None => BadRequest(s"Locatie $id niet gevonden")
    }
  }
}


text:
/**
 * Root Require
 *
 * This is a convenience method that prefixes the require
 * path with the root path so as to help calling the
 * correct file.
 */

"use strict";

/* Node modules */

/* Third-party modules */

/* Files */

global.rootRequire = function (file) {
    return require(require("path").join(process.cwd(), file));
};

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var js = require('default-require-extensions/js');

module.exports = appendTransform;

var count = 0;

function appendTransform(transform, ext, extensions) {
	// Generate a unique key for this transform
	var key = __dirname + count; // eslint-disable-line
	count++;
	ext = ext || '.js';
	extensions = extensions || require.extensions;

	var forwardGet;
	var forwardSet;

	var descriptor = Object.getOwnPropertyDescriptor(extensions, ext) || {value: js, configurable: true};

	if (
		((descriptor.get || descriptor.set) && !(descriptor.get && descriptor.set)) ||
		!descriptor.configurable
	) {
		throw new Error('Somebody did bad things to require.extensions["' + ext + '"]');
	}

	if (descriptor.get) {
		// wrap a previous append-transform install and pass through to the getter/setter pair it created
		forwardGet = function () {
			return descriptor.get();
		};
		forwardSet = function (val) {
			descriptor.set(val);
			return forwardGet();
		};
	} else {
		forwardGet = function () {
			return descriptor.value;
		};
		forwardSet = function (val) {
			descriptor.value = val;
			return val;
		};
	}

	function wrapCustomHook(hook) {
		return function (module, filename) {
			// We wrap every added extension, but we only apply the transform to the one on top of the stack
			if (!module[key]) {
				module[key] = true;

				var originalCompile = module._compile;

				module._compile = function replacementCompile(code, filename) {
					module._compile = originalCompile;
					code = transform(code, filename);
					module._compile(code, filename);
				};
			}

			hook(module, filename);
		};
	}

	// wrap the original
	forwardSet(wrapCustomHook(forwardGet()));

	var hooks = [forwardGet()];

	function setCurrentHook(hook) {
		var restoreIndex = hooks.indexOf(hook);
		if (restoreIndex === -1) {
			hooks.push(forwardSet(wrapCustomHook(hook)));
		} else {
			// we have already scene this hook, and it is being reverted (proxyquire, etc) - don't wrap again.
			hooks.splice(restoreIndex + 1, hooks.length);
			forwardSet(hook);
		}
	}

	Object.defineProperty(extensions, ext, {
		configurable: true,
		enumerable: true,
		get: forwardGet,
		set: setCurrentHook
	});
}


text:
package org.colorcoding.ibas.bobas.common;

import javax.xml.bind.annotation.XmlType;

import org.colorcoding.ibas.bobas.MyConsts;
import org.colorcoding.ibas.bobas.mapping.DbValue;

/**
 * 排序
 */
@XmlType(name = "SortType", namespace = MyConsts.NAMESPACE_BOBAS_COMMON)
public enum SortType {

	/** 降序 */
	@DbValue(value = "D")
	st_Descending,
	/** 升序 */
	@DbValue(value = "A")
	st_Ascending;

	public int getValue() {
		return this.ordinal();
	}

	public static SortType forValue(int value) {
		return values()[value];
	}
}


text:
import org.globus.crux.jsse.SSLConfigurator
import org.globus.security.provider.GlobusProvider
import org.globus.security.stores.ResourceSigningPolicyStoreParameters
import org.globus.security.stores.ResourceSigningPolicyStore
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.conn.scheme.Scheme
import org.apache.http.client.methods.HttpGet

trait Client {
  val valid = "classpath:/mykeystore.properties"
  val invalid = "classpath:/invalidkeystore.properties"

  def validCert = client(5082, valid)
  def invalidCert = client(5082, invalid)

  def client(port:int, keystore:String) = {
    val config = getConfig(keystore)
    val fac = new SSLSocketFactory(config.getSSLContext())
    fac.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    val httpclient = new DefaultHttpClient();
    val scheme = new Scheme("https", fac, port);
    httpclient.getConnectionManager().getSchemeRegistry().register(scheme);
    val httpget = new HttpGet("https://localhost/");
    httpclient.execute(httpget);
  }

  def getConfig(credStoreLocation:String) = {
    val config = new SSLConfigurator();
		config.setCrlLocationPattern(null);
		config.setCrlStoreType(GlobusProvider.CERTSTORE_TYPE);

		config.setCredentialStoreLocation(credStoreLocation);
		config.setCredentialStorePassword("password");
		config.setCredentialStoreType(GlobusProvider.KEYSTORE_TYPE);

		config.setTrustAnchorStoreLocation("classpath:/mytruststore.properties");
		config.setTrustAnchorStorePassword("password");
		config.setTrustAnchorStoreType(GlobusProvider.KEYSTORE_TYPE);

		val policyParams = new ResourceSigningPolicyStoreParameters(
				"classpath:/globus_crux_ca.signing_policy");
		val policyStore = new ResourceSigningPolicyStore(policyParams);

		config.setPolicyStore(policyStore);
		config
  }

}


text:
package org.wso2.carbon.apimgt.rest.api.admin.utils.mappings.throttling;

import org.wso2.carbon.apimgt.api.UnsupportedThrottleLimitTypeException;
import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.rest.api.admin.dto.BlockingConditionDTO;
import org.wso2.carbon.apimgt.rest.api.admin.dto.BlockingConditionListDTO;

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

/**
 * This class is responsible for mapping Block Condition model and its sub components into REST API DTOs and vice-versa
 */
public class BlockingConditionMappingUtil {

    /**
     * Converts a List of Block Condition in to REST API LIST DTO Object
     *
     * @param blockConditionList A List of Block Conditions
     * @return REST API List DTO object derived from Block Condition list
     * @throws UnsupportedThrottleLimitTypeException
     */
    public static BlockingConditionListDTO fromBlockConditionListToListDTO(
            List<BlockConditionsDTO> blockConditionList) throws UnsupportedThrottleLimitTypeException {
        BlockingConditionListDTO listDTO = new BlockingConditionListDTO();
        List<BlockingConditionDTO> blockingConditionDTOList = new ArrayList<>();
        if (blockConditionList != null) {
            for (BlockConditionsDTO blockCondition : blockConditionList) {
                BlockingConditionDTO dto = fromBlockingConditionToDTO(blockCondition);
                blockingConditionDTOList.add(dto);
            }
        }
        listDTO.setCount(blockingConditionDTOList.size());
        listDTO.setList(blockingConditionDTOList);
        return listDTO;
    }

    /**
     * Converts a single Block Condition model object into REST API DTO object
     *
     * @param blockCondition Block condition model object
     * @return Block condition DTO object derived from block condition model object
     * @throws UnsupportedThrottleLimitTypeException
     */
    public static BlockingConditionDTO fromBlockingConditionToDTO(
            BlockConditionsDTO blockCondition) throws UnsupportedThrottleLimitTypeException {
        BlockingConditionDTO dto = new BlockingConditionDTO();
        dto.setConditionId(blockCondition.getUUID());
        dto.setConditionType(blockCondition.getConditionType());

        String conditionValue = blockCondition.getConditionValue();
        if (APIConstants.BLOCKING_CONDITIONS_IP.equals(blockCondition.getConditionType())) {
            int index = conditionValue.indexOf(":");
            if (index > -1) {
                // Removing Tenant Domain from IP
                conditionValue = conditionValue.substring(index + 1, conditionValue.length());
            }
        }
        dto.setConditionValue(conditionValue);
        return dto;
    }

}


text:
using GizmoFort.Connector.ERPNext.ERPTypes.Customer;
using GizmoFort.Connector.ERPNext.ERPTypes.Item;
using GizmoFort.Connector.ERPNext.ERPTypes.Warehouse;
using GizmoFort.Connector.ERPNext.PublicInterfaces.SubServices;

namespace GizmoFort.Connector.ERPNext.PublicInterfaces
{
    public class ERPNextServices
    {
        public ERPNextClient Client { get; }
        public CustomerService CustomerService { get; }
        public ItemService ItemService { get; }
        public WarehouseService WarehouseService { get; }

        public ERPNextServices(string domain, string username, string password)
        {
            this.Client = new ERPNextClient(domain, username, password);
            this.CustomerService = new CustomerService(Client);
            this.ItemService = new ItemService(Client);
            this.WarehouseService = new WarehouseService(Client);
        }
    }
}


text:
using System.Configuration;
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.PhantomJS;
using OpenQA.Selenium.Safari;
using Golem.Core;
using Golem.Tests.PageObjects.Google;
using Golem.WebDriver;

namespace Golem.Tests
{
    [Parallelizable]
    internal class ParallelTestOne : WebDriverTestBase
    {

        [Test]
        public void TestOne()
        {
            driver.Navigate().GoToUrl("http://www.google.com");
            //Assert.Fail("Failing");
        }

        [Test]
        public void TestTwo()
        {
            driver.Navigate().GoToUrl("http://www.gmail.com");
        }

    }
}


text:
import json

import mock
from flask import request
from flask_login import current_user
from flask_login import login_user
from flask_login import logout_user

import config
import api.decorators
import constants.api
import database.user
import util.testing
from api.decorators import hide_if_logged_in
from api.decorators import optional_login_api
from api.decorators import render_view
from api.decorators import require_form_args
from api.decorators import require_login_api
from api.decorators import require_login_frontend
from modern_paste import app
from uri.main import *

class TestDecorators(util.testing.DatabaseTestCase):
    def test_context_config(self):
        config_constants = api.decorators.context_config()
        for config_item in filter(lambda item: item == item.upper(), dir(config)):
            self.assertIn(config_item, config_constants)

    def test_render_view(self):
        with mock.patch.object(api.decorators, 'render_template') as render_template_mock:
            @render_view
            def template_without_context():
                return 'template name', {}
            template_without_context()
            self.assertEqual(1, render_template_mock.call_count)
            render_template_mock.assert_called_with(
                'template name',
                config=api.decorators.context_config(),
            )

        with mock.patch.object(api.decorators, 'render_template') as render_template_mock:
            @render_view
            def template_with_context():
                return 'template name', {'key': 'value'}
            template_with_context()
            self.assertEqual(1, render_template_mock.call_count)
            render_template_mock.assert_called_with(
                'template name',
                config=api.decorators.context_config(),
                key='value',
            )

        with mock.patch.object(api.decorators, 'render_template') as render_template_mock:
            @render_view
            def template_with_config_context():
                return 'template name', {'config': {'key': 'value'}}
            template_with_config_context()
            self.assertEqual(1, render_template_mock.call_count)
            expect_config = dict(api.decorators.context_config())
            expect_config['key'] = 'value'
            render_template_mock.assert_called_with(
                'template name',
                config=expect_config,
            )

    def test_require_form_args(self):
        with app.test_request_context():
            @require_form_args([])
            def no_required_args():
                return 'success'
            request.get_json = lambda: {}
            self.assertEqual(no_required_args(), 'success')
            request.get_json = lambda: {'extraneous': 'content'}
            self.assertEqual(no_required_args(), 'success')

            @require_form_args(['param'])
            def one_required_arg():
                return 'success'
            request.get_json = lambda: {}
            self.assertEqual(one_required_arg()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'invalid': 'invalid'}
            self.assertEqual(one_required_arg()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param': ''}  # Should reject empty contents
            self.assertEqual(one_required_arg()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param': 'content'}
            self.assertEqual(one_required_arg(), 'success')

            @require_form_args(['param1', 'param2'])
            def two_required_args():
                return 'success'
            request.get_json = lambda: {}
            self.assertEqual(two_required_args()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'invalid': 'invalid'}
            self.assertEqual(two_required_args()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param1': 'content'}
            self.assertEqual(two_required_args()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param1': 'content', 'param2': 'content'}
            self.assertEqual(two_required_args(), 'success')

            @require_form_args(['param'], allow_blank_values=True)
            def blank_values_allowed():
                return 'success'
            request.get_json = lambda: {}
            self.assertEqual(blank_values_allowed()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'invalid': 'invalid'}
            self.assertEqual(blank_values_allowed()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param': ''}
            self.assertEqual(blank_values_allowed(), 'success')
            request.get_json = lambda: {'param': 'content'}
            self.assertEqual(blank_values_allowed(), 'success')

            @require_form_args(['param'], strict_params=True)
            def strict_params_enforced():
                return 'success'
            request.get_json = lambda: {}
            self.assertEqual(strict_params_enforced()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'invalid': 'invalid'}
            self.assertEqual(strict_params_enforced()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param': 'content', 'extraneous': 'content'}
            self.assertEqual(strict_params_enforced()[1], constants.api.INCOMPLETE_PARAMS_FAILURE_CODE)
            request.get_json = lambda: {'param': 'content'}
            self.assertEqual(strict_params_enforced(), 'success')

    def test_require_login_api_credentials(self):
        with app.test_request_context():
            @require_login_api
            def login_required():
                return 'success'
            self.assertEqual(login_required()[1], constants.api.AUTH_FAILURE_CODE)
            user = util.testing.UserFactory.generate(password='password')
            login_user(user)
            self.assertEqual(login_required(), 'success')

            def login_not_required():
                return 'success'
            self.assertEqual(login_not_required(), 'success')
            logout_user()
            self.assertEqual(login_not_required(), 'success')

    def test_require_login_api_key(self):
        with app.test_request_context():
            @require_login_api
            def login_required():
                return 'success'
            self.assertEqual(login_required()[1], constants.api.AUTH_FAILURE_CODE)
            user = util.testing.UserFactory.generate(password='password')
            request.get_json = lambda: {
                'api_key': user.api_key,
            }
            self.assertEqual(login_required(), 'success')

    def test_optional_login_api_key(self):
        with app.test_request_context():
            @optional_login_api
            def login_optional():
                if current_user.is_authenticated:
                    return 'authenticated'
                return 'not authenticated'
            self.assertEqual('not authenticated', login_optional())
            user = util.testing.UserFactory.generate(password='password')
            request.get_json = lambda: {
                'api_key': user.api_key,
            }
            self.assertEqual('authenticated', login_optional())

    def test_optional_login_api_credentials(self):
        with app.test_request_context():
            @optional_login_api
            def login_optional():
                if current_user.is_authenticated:
                    return 'authenticated'
                return 'not authenticated'
            self.assertEqual('not authenticated', login_optional())
            user = util.testing.UserFactory.generate(password='password')
            login_user(user)
            self.assertEqual('authenticated', login_optional())

    def test_optional_login_api_invalid_credentials(self):
        with app.test_request_context():
            @optional_login_api
            def login_optional():
                if current_user.is_authenticated:
                    return 'authenticated'
                return 'not authenticated'
            self.assertEqual('not authenticated', login_optional())
            request.get_json = lambda: {
                'api_key': 'invalid',
            }
            resp, resp_code = login_optional()
            self.assertEqual(constants.api.AUTH_FAILURE, json.loads(resp.data))
            self.assertEqual(constants.api.AUTH_FAILURE_CODE, resp_code)

    def test_optional_login_api_deactivated_user(self):
        with app.test_request_context():
            @optional_login_api
            def login_optional():
                if current_user.is_authenticated:
                    return 'authenticated'
                return 'not authenticated'
            self.assertEqual('not authenticated', login_optional())
            user = util.testing.UserFactory.generate()
            database.user.deactivate_user(user.user_id)
            request.get_json = lambda: {
                'api_key': user.api_key,
            }
            resp, resp_code = login_optional()
            self.assertEqual(constants.api.AUTH_FAILURE, json.loads(resp.data))
            self.assertEqual(constants.api.AUTH_FAILURE_CODE, resp_code)

    def test_require_login_frontend(self):
        with app.test_request_context():
            @require_login_frontend()
            def login_required():
                return 'success'
            self.assertEqual(login_required().status_code, 302)  # Redirect
            user = util.testing.UserFactory.generate(password='password')
            request.get_json = lambda: {
                'username': user.user_id,
                'password': 'password',
            }
            login_user(user)
            self.assertEqual(login_required(), 'success')

            @require_login_frontend(only_if=False)
            def conditional_login_required():
                return 'success'
            self.assertEqual(login_required(), 'success')

    def test_hide_if_logged_in(self):
        with app.test_request_context():
            @hide_if_logged_in(redirect_uri=HomeURI.uri())
            def hidden_if_logged_in():
                return 'success'
            self.assertEqual(hidden_if_logged_in(), 'success')  # Redirect
            user = util.testing.UserFactory.generate(password='password')
            request.get_json = lambda: {
                'username': user.user_id,
                'password': 'password',
            }
            login_user(user)
            self.assertEqual(hidden_if_logged_in().status_code, 302)


text:
package se.nimsa.sbx.log

import se.nimsa.sbx.model.Entity

object LogProtocol {

  sealed trait LogEntryType {
    override def toString: String = this match {
      case LogEntryType.DEFAULT => "DEFAULT"
      case LogEntryType.INFO => "INFO"
      case LogEntryType.WARN => "WARN"
      case LogEntryType.ERROR => "ERROR"
    }
  }

  object LogEntryType {
    case object DEFAULT extends LogEntryType
    case object INFO extends LogEntryType
    case object WARN extends LogEntryType
    case object ERROR extends LogEntryType

    def withName(string: String): LogEntryType = string match {
      case "DEFAULT" => DEFAULT
      case "INFO" => INFO
      case "WARN" => WARN
      case "ERROR" => ERROR
    }
  }

  case class LogEntry(id: Long, created: Long, entryType: LogEntryType, subject: String, message: String) extends Entity

  // Messages
  case class AddLogEntry(logEntry: LogEntry)

  case class GetLogEntries(startIndex: Long, count: Long)
  case class GetLogEntriesBySubject(subject: String, startIndex: Long, count: Long)
  case class GetLogEntriesByType(entryType: LogEntryType, startIndex: Long, count: Long)
  case class GetLogEntriesBySubjectAndType(subject: String, entryType: LogEntryType, startIndex: Long, count: Long)
  case object ClearLog

  case class RemoveLogEntry(logId: Long)

  case class LogEntries(logEntries: Seq[LogEntry])

  case class LogEntryAdded(logEntry: LogEntry)
  case class LogEntryRemoved(logId: Long)
}


text:
#include <stdint.h>
#include <stddef.h>
#include <limits.h>

#include <misc/debug.h>
#include <misc/parse_number.h>
#include <misc/strdup.h>
#include <misc/balloc.h>
#include <system/BTime.h>
#include <ncd/NCDVal.h>
#include <ncd/NCDStringIndex.h>
#include <ncd/NCDModule.h>
#include <ncd/static_strings.h>

#include "value_utils.h"

int ncd_is_none (NCDValRef string)
{
    ASSERT(NCDVal_IsString(string))

    if (NCDVal_IsIdString(string)) {
        return NCDVal_IdStringId(string) == NCD_STRING_NONE;
    } else {
        return NCDVal_StringEquals(string, "<none>");
    }
}

NCDValRef ncd_make_boolean (NCDValMem *mem, int value, NCDStringIndex *string_index)
{
    ASSERT(mem)
    ASSERT(string_index)

    NCD_string_id_t str_id = (value ? NCD_STRING_TRUE : NCD_STRING_FALSE);
    return NCDVal_NewIdString(mem, str_id, string_index);
}

int ncd_read_boolean (NCDValRef val, int *out)
{
    ASSERT(out)

    if (!NCDVal_IsString(val)) {
        return 0;
    }
    if (NCDVal_IsIdString(val)) {
        *out = NCDVal_IdStringId(val) == NCD_STRING_TRUE;
    } else {
        *out = NCDVal_StringEquals(val, "true");
    }
    return 1;
}

int ncd_read_uintmax (NCDValRef val, uintmax_t *out)
{
    ASSERT(out)

    if (!NCDVal_IsString(val)) {
        return 0;
    }

    return parse_unsigned_integer(NCDVal_StringMemRef(val), out);
}

int ncd_read_time (NCDValRef val, btime_t *out)
{
    ASSERT(out)

    uintmax_t n;
    if (!ncd_read_uintmax(val, &n)) {
        return 0;
    }

    if (n > INT64_MAX) {
        return 0;
    }

    *out = n;
    return 1;
}

NCD_string_id_t ncd_get_string_id (NCDValRef string, NCDStringIndex *string_index)
{
    ASSERT(NCDVal_IsString(string))
    ASSERT(string_index)

    if (NCDVal_IsIdString(string)) {
        return NCDVal_IdStringId(string);
    }

    return NCDStringIndex_GetBinMr(string_index, NCDVal_StringMemRef(string));
}

NCDValRef ncd_make_uintmax (NCDValMem *mem, uintmax_t value)
{
    ASSERT(mem)

    int size = compute_decimal_repr_size(value);

    NCDValRef val = NCDVal_NewStringUninitialized(mem, size);

    if (!NCDVal_IsInvalid(val)) {
        char *data = (char *)NCDVal_StringData(val);
        generate_decimal_repr(value, data, size);
    }

    return val;
}

char * ncd_strdup (NCDValRef stringnonulls)
{
    ASSERT(NCDVal_IsStringNoNulls(stringnonulls))

    return MemRef_StrDup(NCDVal_StringMemRef(stringnonulls));
}

int ncd_eval_func_args_ext (NCDCall const *call, size_t start, size_t count, NCDValMem *mem, NCDValRef *out)
{
    ASSERT(start <= NCDCall_ArgCount(call))
    ASSERT(count <= NCDCall_ArgCount(call) - start)

    *out = NCDVal_NewList(mem, count);
    if (NCDVal_IsInvalid(*out)) {
        goto fail;
    }

    for (size_t i = 0; i < count; i++) {
        NCDValRef elem = NCDCall_EvalArg(call, start + i, mem);
        if (NCDVal_IsInvalid(elem)) {
            goto fail;
        }
        if (!NCDVal_ListAppend(*out, elem)) {
            goto fail;
        }
    }

    return 1;

fail:
    return 0;
}

int ncd_eval_func_args (NCDCall const *call, NCDValMem *mem, NCDValRef *out)
{
    return ncd_eval_func_args_ext(call, 0, NCDCall_ArgCount(call), mem, out);
}


text:
using System;
using System.Linq;

namespace Microsoft.WindowsAzure.Management.StorSimple.Models
{
    /// <summary>
    /// This class respresents the iSCSI chap settings.
    /// </summary>
    public partial class MigrationChapSetting
    {
        private string _id;

        /// <summary>
        /// Optional. Gets or sets the Id of the chap settings.
        /// </summary>
        public string Id
        {
            get { return this._id; }
            set { this._id = value; }
        }

        private string _name;

        /// <summary>
        /// Required. Gets or sets the name of the chap setting
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private string _password;

        /// <summary>
        /// Required. Gets or sets the chap password
        /// </summary>
        public string Password
        {
            get { return this._password; }
            set { this._password = value; }
        }

        private string _secretsEncryptionThumbprint;

        /// <summary>
        /// Required. Gets or sets the password encryption thumbprint.
        /// </summary>
        public string SecretsEncryptionThumbprint
        {
            get { return this._secretsEncryptionThumbprint; }
            set { this._secretsEncryptionThumbprint = value; }
        }

        private bool _valid;

        /// <summary>
        /// Required. Gets or sets a value indicating whether the chap is valid
        /// or not.
        /// </summary>
        public bool Valid
        {
            get { return this._valid; }
            set { this._valid = value; }
        }

        /// <summary>
        /// Initializes a new instance of the MigrationChapSetting class.
        /// </summary>
        public MigrationChapSetting()
        {
        }
    }
}


text:
package com.baasbox.android;

import java.util.AbstractSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by aktor on 25/11/15.
 */
class ConcurrentHashSet<T> extends AbstractSet<T> {

    private final ConcurrentHashMap<T,T> mMap;

    ConcurrentHashSet(){
        mMap = new ConcurrentHashMap<>();
    }

    @Override
    public Iterator<T> iterator() {
        return mMap.keySet().iterator();
    }

    @Override
    public int size() {
        return mMap.size();
    }

    @Override
    public boolean contains(Object object) {
        return mMap.get(object) != null;
    }

    @Override
    public boolean add(T object) {
        return mMap.put(object,object)==null;
    }

    @Override
    public boolean remove(Object object) {
        return mMap.remove(object,object);
    }

    @Override
    public void clear() {
        mMap.clear();
    }

}


text:
'use strict';

module.exports = {
	get: 'SENSOR_MULTILEVEL_GET',
	getParser: () => ({
		'Sensor Type': 'Power (version 2)',
		Properties1: {
			Scale: 0,
		},
	}),
	report: 'SENSOR_MULTILEVEL_REPORT',
	reportParser: report => {
		if (report && report.hasOwnProperty('Sensor Type') && report.hasOwnProperty('Sensor Value (Parsed)')) {
			if (report['Sensor Type'] === 'Power (version 2)') return report['Sensor Value (Parsed)'];
		}
		return null;
	},
};


text:
using UnityEngine;
using System.Collections;

namespace Lockstep {
    public enum AgentType {
        Unit,
        Building
    }
}


text:
package sample.dp.singleton;

/**
 * @author soyona
 * @Package sample.dp.singleton
 * @Desc:
 * @date 2018/8/5 16:08
 */
public class SingletonA {
}


text:
	#pragma once
#endif // #ifdef WIN32

#include "Build.h"

#if WINDOWS
	#define TOGGLE_BREAKPOINT() \
		__asm \
		{ \
			int 3 \
		}
#else
	#error TOGGLE_BREAKPOINT isn't defined for the current platform
#endif // #ifdef WINDOWS

#endif


text:
  Diges est
      une commune géographiquement positionnée dans le département de Yonne en Bourgogne. Elle comptait 1 122 habitants en 2008.

Le parc de logements, à Diges, était réparti en 2011 en douze appartements et 561 maisons soit
 un marché plutôt équilibré.

La ville compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.

À coté de Diges sont localisées les communes de
Escamps située à 5 km, 792 habitants,
Toucy située à 7 km, 2 669 habitants,
Parly localisée à 5 km, 776 habitants,
Ouanne localisée à 7 km, 694 habitants,
Pourrain localisée à 2 km, 1 369 habitants,
Escamps à 5 km, 150 habitants,
 entre autres. De plus, Diges est située à seulement 15 km de Auxerre.

À Diges, la valeur moyenne à l'achat d'un appartement s'évalue à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 231 € du m². À la location la valeur moyenne se situe à 0 € du m² mensuel.


text:
from django.contrib import admin
from django.utils.html import format_html, format_html_join

from karspexet.ticket.models import (
    Account,
    Discount,
    PricingModel,
    Reservation,
    Ticket,
    Voucher,
)
from karspexet.utils import admin_change_url

def admin_change_link(obj) -> str:
    if obj is None:
        return ""
    return format_html('{}', admin_change_url(obj), obj)

def show_link(self, obj=None):
    return admin_change_link(obj.show if obj else None)

@admin.register(Reservation)
class ReservationAdmin(admin.ModelAdmin):
    fields = (
        "show_link",
        "related_tickets",
        "reservation_code",
        "finalized",
        ("ticket_price", "total"),
        "session_timeout",
        "tickets",
    )
    search_fields = ("reservation_code",)
    list_select_related = ["show", "show__production"]
    list_display = ("reservation_code", "show", "finalized", "ticket_price", "total", "session_timeout", "tickets")
    list_filter = ("finalized", "show")
    readonly_fields = ("show_link", "reservation_code", "related_tickets")

    show_link = show_link

    def has_add_permission(self, obj):
        return False

    def lookup_allowed(self, key, value):
        return True

    def related_tickets(self, obj=None):
        if obj is None:
            return ""
        tickets = [(admin_change_url(t), f"{t.seat}: {t.account.name}") for t in obj.ticket_set().all()]
        return format_html_join("
", '{1}', tickets)

@admin.register(Ticket)
class TicketAdmin(admin.ModelAdmin):
    fields = (
        "show_link",
        "reservation",
        "ticket_code",
        ("ticket_type", "price"),
        "seat",
        "account",
    )
    search_fields = ("reservation__reservation_code", "ticket_code")
    list_display = ("ticket_code", "show", "price", "ticket_type", "seat", "account")
    raw_id_fields = ("account", "seat")
    readonly_fields = ("show_link", "reservation", "ticket_code")

    show_link = show_link

    def has_add_permission(self, obj):
        return False

    def lookup_allowed(self, key, value):
        return True

    def reservation(self, obj=None):
        return admin_change_link(obj.get_reservation() if obj else None)

class IsUsedFilter(admin.SimpleListFilter):
    title = "used"
    parameter_name = "used"

    def lookups(self, request, model_admin):
        return (("used", "Used"), ("unused", "Unused"))

    def queryset(self, request, queryset):
        if self.value() == "used":
            return queryset.filter(discount__isnull=False)
        elif self.value() == "unused":
            return queryset.filter(discount__isnull=True)
        return queryset

@admin.register(Voucher)
class VoucherAdmin(admin.ModelAdmin):
    list_display = ("code", "amount", "note", "is_used")
    list_filter = (IsUsedFilter, "expiry_date")
    list_select_related = ("discount",)
    fields = (
        ("is_used", "used_by"),
        ("note", "amount"),
        "code",
        "expiry_date",
        "created_by",
    )
    readonly_fields = ("used_by", "is_used")

    def lookup_allowed(self, key, value):
        return True

    def get_changeform_initial_data(self, request):
        return {"created_by": request.user}

    @admin.display(boolean=True)
    def is_used(self, obj):
        if not obj:
            return False
        try:
            return bool(obj.discount)
        except Discount.DoesNotExist:
            return False

    def used_by(self, obj):
        if not obj:
            return ""
        if not obj.discount:
            return ""
        return admin_change_link(obj.discount.reservation)

@admin.register(PricingModel)
class PricingModelAdmin(admin.ModelAdmin):
    list_display = ("_venue", "_from", "prices")
    list_select_related = ["seating_group", "seating_group__venue"]

    @admin.display(description="Venue / Group")
    def _venue(self, obj):
        return f"{obj.seating_group.venue} / {obj.seating_group}"

    @admin.display(description="Valid from")
    def _from(self, obj):
        return f"{obj.valid_from:%Y-%m-%d %H:%M}"

@admin.register(Account)
class AccountAdmin(admin.ModelAdmin):
    list_display = ("name", "email", "phone")


text:
#ifndef _MAKE_RELOADER_H
#define _MAKE_RELOADER_H

#include "../common/utils.h"
#include "ctx.h"
#include "rules.h"

int bm_reloader_run(bm_ctx_t **ctx, bm_rule_exec_func_t rule_exec,
    bc_slist_t *outputs, bc_trie_t *args);
void bm_reloader_stop(int status_code);

#endif /* _MAKE_RELOADER_H */


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Namespace Nth\Permit</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

None

Nth

Permit

Constants

Exceptions

Facades

Helper

Interfaces

Models

Seeds

Services

PHP

Classes

Permit

PermitServiceProvider

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

Namespace

Class

				Tree

Namespace Nth\Permit

Namespaces summary

		Nth\Permit\Constants

		Nth\Permit\Exceptions

		Nth\Permit\Facades

		Nth\Permit\Helper

		Nth\Permit\Interfaces

		Nth\Permit\Models

		Nth\Permit\Seeds

		Nth\Permit\Services

Classes summary

	Permit
	Permission Service

	PermitServiceProvider
	Permit Service Provider

		 API documentation generated by ApiGen 2.8.0


text:
package main

import (
	"net/http"
	"os"

	logger "github.com/darwinfroese/networkobserver/pkg/logging"
	settings "github.com/darwinfroese/networkobserver/pkg/settings"
	websrv "github.com/darwinfroese/networkobserver/pkg/webserver"

	"github.com/darwinfroese/networkobserver/pkg/configuration"
)

// Random default value
var portNumber = "5000"
var loc = settings.AppLocation

func init() {
	cl := loc + "/.cookies"
	logger.WriteString("Removing the existing .cookies file")
	os.Remove(cl)

	// this is here because apparently auth's init() is called before this one is
	if _, err := os.Stat(cl); os.IsNotExist(err) {
		logger.WriteString("Creating a new .cookies file.")
		file, e := os.Create(cl)
		if e != nil {
			logger.WriteString("There was an error creating the .cookies file.")
		}
		file.Close()
	}

	if _, err := os.Stat(loc + "/.password"); os.IsNotExist(err) {
		logger.WriteString("The .password file does not exist. Creating a new .password file.")
		file, e := os.Create(loc + "/.password")
		if e != nil {
			logger.WriteString("There was an error creating the .password file.")
		}
		file.Close()
	}

	logger.WriteString("Setting the port number to " + configuration.GetPortNumber())
	portNumber = ":" + configuration.GetPortNumber()
}

func main() {
	// Base Pages
	http.HandleFunc("/", websrv.Root)
	http.HandleFunc("/checkLogin", websrv.CheckLogin)
	http.HandleFunc("/dashboard", websrv.Dashboard)
	http.HandleFunc("/createaccount", websrv.CreateAccount)
	http.HandleFunc("/account", websrv.HandleAccount)

	// Handlers
	http.HandleFunc("/saveConfig", websrv.SaveConfig)
	http.HandleFunc("/savetest", websrv.SaveTest)
	http.HandleFunc("/teststarted", websrv.TestStarted)
	http.HandleFunc("/logout", websrv.Logout)

	// Dashboard Pages
	http.HandleFunc("/dashboard/configure", websrv.Configure)
	http.HandleFunc("/dashboard/start_test", websrv.StartTest)
	http.HandleFunc("/dashboard/reports", websrv.Reports)

	// Start the Webserver
	http.ListenAndServe(portNumber, nil)
	// Enable SSL and HTTPS connections
	//http.ListenAndServeTLS(portNumber, "cert.pem", "key.pem", nil)
}


text:
Experimental Laravel service for interacting with Tutum's API using tutum-php

---

WIP


text:
package snapshotter

import (
	"testing"

	. "github.com/onsi/gomega"

	coll "istio.io/istio/galley/pkg/config/collection"
	"istio.io/istio/galley/pkg/config/testing/basicmeta"
	"istio.io/istio/galley/pkg/config/testing/data"
	"istio.io/istio/galley/pkg/config/testing/fixtures"
	"istio.io/istio/pkg/config/resource"
	"istio.io/istio/pkg/config/schema/collection"
)

func TestSnapshot_Basics(t *testing.T) {
	g := NewGomegaWithT(t)

	set := coll.NewSet(collection.NewSchemasBuilder().MustAdd(basicmeta.K8SCollection1).Build())
	set.Collection(basicmeta.K8SCollection1.Name()).Set(data.EntryN1I1V1)
	sn := &Snapshot{set: set}

	resources := sn.Resources(basicmeta.K8SCollection1.Name().String())
	g.Expect(resources).To(HaveLen(1))

	r, err := resource.Deserialize(resources[0], basicmeta.K8SCollection1.Resource())
	g.Expect(err).To(BeNil())
	fixtures.ExpectEqual(t, r, data.EntryN1I1V1)

	v := sn.Version(basicmeta.K8SCollection1.Name().String())
	g.Expect(v).To(Equal(basicmeta.K8SCollection1.Name().String() + "/1"))

	expected := `[0] k8s/collection1 (@k8s/collection1/1)
  [0] n1/i1
`
	g.Expect(sn.String()).To(Equal(expected))
}

func TestSnapshot_SerializeError(t *testing.T) {
	g := NewGomegaWithT(t)

	set := coll.NewSet(collection.NewSchemasBuilder().MustAdd(basicmeta.K8SCollection1).Build())
	e := data.Event1Col1AddItem1.Resource.Clone()
	e.Message = nil
	set.Collection(basicmeta.K8SCollection1.Name()).Set(e)
	sn := &Snapshot{set: set}

	resources := sn.Resources(basicmeta.K8SCollection1.Name().String())
	g.Expect(resources).To(HaveLen(0))
}

func TestSnapshot_WrongCollection(t *testing.T) {
	g := NewGomegaWithT(t)

	set := coll.NewSet(collection.NewSchemasBuilder().MustAdd(basicmeta.K8SCollection1).Build())
	set.Collection(basicmeta.K8SCollection1.Name()).Set(data.Event1Col1AddItem1.Resource)
	sn := &Snapshot{set: set}

	g.Expect(sn.Version("foo")).To(Equal(""))
	g.Expect(sn.Resources("foo")).To(BeEmpty())
}


text:
package org.eclipse.jdt.internal.ui.callhierarchy;

import org.eclipse.core.runtime.Assert;

import org.eclipse.jface.action.Action;

import org.eclipse.ui.PlatformUI;

import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;

/**
 * Toggles the orientationof the layout of the call hierarchy
 */
class ToggleOrientationAction extends Action {

    private CallHierarchyViewPart fView;
    private int fActionOrientation;

    public ToggleOrientationAction(CallHierarchyViewPart v, int orientation) {
        super("", AS_RADIO_BUTTON); //$NON-NLS-1$
        if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_HORIZONTAL) {
            setText(CallHierarchyMessages.ToggleOrientationAction_horizontal_label);
            setDescription(CallHierarchyMessages.ToggleOrientationAction_horizontal_description);
            setToolTipText(CallHierarchyMessages.ToggleOrientationAction_horizontal_tooltip);
            JavaPluginImages.setLocalImageDescriptors(this, "th_horizontal.gif"); //$NON-NLS-1$
        } else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_VERTICAL) {
            setText(CallHierarchyMessages.ToggleOrientationAction_vertical_label);
            setDescription(CallHierarchyMessages.ToggleOrientationAction_vertical_description);
            setToolTipText(CallHierarchyMessages.ToggleOrientationAction_vertical_tooltip);
            JavaPluginImages.setLocalImageDescriptors(this, "th_vertical.gif"); //$NON-NLS-1$
		} else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_AUTOMATIC) {
			setText(CallHierarchyMessages.ToggleOrientationAction_automatic_label);
			setDescription(CallHierarchyMessages.ToggleOrientationAction_automatic_description);
			setToolTipText(CallHierarchyMessages.ToggleOrientationAction_automatic_tooltip);
			JavaPluginImages.setLocalImageDescriptors(this, "th_automatic.gif"); //$NON-NLS-1$
        } else if (orientation == CallHierarchyViewPart.VIEW_ORIENTATION_SINGLE) {
            setText(CallHierarchyMessages.ToggleOrientationAction_single_label);
            setDescription(CallHierarchyMessages.ToggleOrientationAction_single_description);
            setToolTipText(CallHierarchyMessages.ToggleOrientationAction_single_tooltip);
            JavaPluginImages.setLocalImageDescriptors(this, "th_single.gif"); //$NON-NLS-1$
        } else {
            Assert.isTrue(false);
        }
        fView= v;
        fActionOrientation= orientation;
        PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION);
    }

    public int getOrientation() {
        return fActionOrientation;
    }

    /*
     * @see Action#actionPerformed
     */
    @Override
	public void run() {
		if (isChecked()) {
			fView.fOrientation= fActionOrientation;
			fView.computeOrientation();
		}
    }

}


text:
<?php namespace Fungku\NetSuite\Classes;

class CampaignChannel extends Record {
	public $name;
	public $eventType;
	public $description;
	public $isInactive;
	public $internalId;
	public $externalId;
	static $paramtypesmap = array(
		"name" => "string",
		"eventType" => "CampaignChannelEventType",
		"description" => "string",
		"isInactive" => "boolean",
		"internalId" => "string",
		"externalId" => "string",
	);
}


text:
import React, { createContext, useContext, useEffect, useState, useCallback, useMemo } from 'react';

import { useRouteParameter, useRoute } from '../../contexts/RouterContext';
import { useMethod } from '../../contexts/ServerContext';
import { useUserId } from '../../contexts/UserContext';
import SetupWizardPage from './SetupWizardPage';

export const finalStep = 'final';

const useStepRouting = () => {
	const param = useRouteParameter('step');
	const userId = useUserId();
	const setupWizardRoute = useRoute('setup-wizard');

	const [currentStep, setCurrentStep] = useState(() => {
		if (param === finalStep) {
			return finalStep;
		}

		const step = parseInt(param, 10);
		if (Number.isFinite(step) && step >= 1) {
			return step;
		}

		return 1;
	});

	useEffect(() => {
		if (!userId) {
			setCurrentStep(1);
		} else if (currentStep === 1) {
			setCurrentStep(2);
		}

		setupWizardRoute.replace({ step: String(currentStep) });
	}, [setupWizardRoute, userId, currentStep]);

	return [currentStep, setCurrentStep];
};

const useParameters = () => {
	const [loaded, setLoaded] = useState(false);
	const [settings, setSettings] = useState([]);
	const [canDeclineServerRegistration, setCapableOfDeclineServerRegistration] = useState(false);
	const getSetupWizardParameters = useMethod('getSetupWizardParameters');

	useEffect(() => {
		let mounted = true;
		const requestParameters = async () => {
			try {
				const {
					settings = [],
					allowStandaloneServer = false,
				} = await getSetupWizardParameters() || {};

				if (!mounted) {
					return;
				}

				setLoaded(true);
				setSettings(settings);
				setCapableOfDeclineServerRegistration(allowStandaloneServer);
			} catch (error) {
				setLoaded(false);
				setSettings([]);
				setCapableOfDeclineServerRegistration(false);
			}
		};

		requestParameters();

		return () => {
			mounted = false;
		};
	}, []);

	return {
		loaded,
		settings,
		canDeclineServerRegistration,
	};
};

const SetupWizardContext = createContext({
	loaded: false,
	settings: [],
	canDeclineServerRegistration: false,
	goToPreviousStep: () => {},
	goToNextStep: () => {},
	goToFinalStep: () => {},
});

function SetupWizardState() {
	const [currentStep, setCurrentStep] = useStepRouting();
	const {
		loaded,
		settings,
		canDeclineServerRegistration,
	} = useParameters();

	const goToPreviousStep = useCallback(() => setCurrentStep((currentStep) => currentStep - 1), []);
	const goToNextStep = useCallback(() => setCurrentStep((currentStep) => currentStep + 1), []);
	const goToFinalStep = useCallback(() => setCurrentStep(finalStep), []);

	const value = useMemo(() => ({
		currentStep,
		loaded,
		settings,
		canDeclineServerRegistration,
		goToPreviousStep,
		goToNextStep,
		goToFinalStep,
	}), [
		currentStep,
		loaded,
		settings,
		canDeclineServerRegistration,
	]);

	return <SetupWizardContext.Provider value={value}>
		<SetupWizardPage currentStep={currentStep} />
	</SetupWizardContext.Provider>;
}

export const useSetupWizardContext = () => useContext(SetupWizardContext);

export default SetupWizardState;


text:
package com.commonsware.empublite;

import android.net.Uri;

import java.io.File;
import java.util.List;

/**
 * Created by dm on 08.01.16.
 */
public class BookContents {
    List<Chapter> chapters;
    File baseDir = null;

    int getChapterCount() {
        return chapters.size();
    }

    String getChapterFile(int position) {
        return chapters.get(position).file;
    }

    String getChapterPath(int position) {
        String file = getChapterFile(position);

        if(baseDir == null) {
            return "file:///android_asset/book/"+file;
        }

        return Uri.fromFile(new File(baseDir, file)).toString();
    }
    void setBaseDir(File baseDir) {
        this.baseDir = baseDir;
    }

    static class Chapter {
        String file;
    }

}


text:
package lint

// FormatterMetadata configuration of a formatter
type FormatterMetadata struct {
	Name        string
	Description string
	Sample      string
}

// Formatter defines an interface for failure formatters
type Formatter interface {
	Format(<-chan Failure, Config) (string, error)
	Name() string
}


text:
package org.most.pipeline;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;

import org.most.DataBundle;
import org.most.MoSTApplication;
import org.most.input.Input;
import org.most.input.InputAudio;

import android.util.Log;

/**
 * This pipeline receives audio data. Currently it does not propagate received
 * data to clients.
 *
 */
public class PipelineRawAudio extends Pipeline {

	private static final String TAG = PipelineRawAudio.class.getSimpleName();

	public PipelineRawAudio(MoSTApplication context) {
		super(context);
	}

	FileOutputStream fos = null;
	FileChannel fc;

	@Override
	public boolean onActivate() {
		/* BEGIN TESTING CODE */
		// try {
		// fos = new FileOutputStream(new
		// File(Environment.getExternalStorageDirectory(), "rawaudio"), true);
		// fc = fos.getChannel();
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }
		/* END TESTING CODE */
		return super.onActivate();
	}

	@Override
	public void onDeactivate() {
		super.onDeactivate();
		Log.d(TAG, "Deactivating");
		// try {
		// fc.close();
		// fos.close();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
	}

	public void onData(DataBundle b) {
		int size = b.getInt(InputAudio.KEY_AUDIODATA_LENGTH);
		/*
		 * data is a reference to the audio data contained in the DataBundle, it
		 * can be used as long as we do not call the b.release() method.
		 */
		short[] data = b.getShortArray(InputAudio.KEY_AUDIODATA);
		Log.d(TAG, String.format("Received %d shorts, first short data: %d",
				size, data[0]));

		/* BEGIN TESTING CODE */
		/*
		 * The following code dumps the received array to the output file as
		 * fast as possible
		 */
		if (fos != null) {
			try {
				byte[] byteData = new byte[size * 2];
				ByteBuffer bb = ByteBuffer.wrap(byteData);
				bb.asShortBuffer().put(data, 0, size);
				fc.write(bb);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		/* END TESTING CODE */
		b.release();
	}

	@Override
	public Set<Input.Type> getInputs() {
		Set<Input.Type> result = new HashSet<Input.Type>();
		result.add(Input.Type.AUDIO);
		return result;
	}

	@Override
	public Type getType() {
		return Type.RAW_AUDIO;
	}

}


text:
package com.google.android.exoplayer2.extractor.ogg;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.fail;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.testutil.FakeExtractorInput;
import com.google.android.exoplayer2.testutil.OggTestData;
import com.google.android.exoplayer2.testutil.TestUtil;
import java.io.EOFException;
import java.io.IOException;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Unit test for {@link DefaultOggSeeker} utility methods. */
@RunWith(AndroidJUnit4.class)
public final class DefaultOggSeekerUtilMethodsTest {

  private final Random random = new Random(0);

  @Test
  public void testSkipToNextPage() throws Exception {
    FakeExtractorInput extractorInput = OggTestData.createInput(
        TestUtil.joinByteArrays(
            TestUtil.buildTestData(4000, random),
            new byte[] {'O', 'g', 'g', 'S'},
            TestUtil.buildTestData(4000, random)
        ), false);
    skipToNextPage(extractorInput);
    assertThat(extractorInput.getPosition()).isEqualTo(4000);
  }

  @Test
  public void testSkipToNextPageOverlap() throws Exception {
    FakeExtractorInput extractorInput = OggTestData.createInput(
        TestUtil.joinByteArrays(
            TestUtil.buildTestData(2046, random),
            new byte[] {'O', 'g', 'g', 'S'},
            TestUtil.buildTestData(4000, random)
        ), false);
    skipToNextPage(extractorInput);
    assertThat(extractorInput.getPosition()).isEqualTo(2046);
  }

  @Test
  public void testSkipToNextPageInputShorterThanPeekLength() throws Exception {
    FakeExtractorInput extractorInput = OggTestData.createInput(
        TestUtil.joinByteArrays(
            new byte[] {'x', 'O', 'g', 'g', 'S'}
        ), false);
    skipToNextPage(extractorInput);
    assertThat(extractorInput.getPosition()).isEqualTo(1);
  }

  @Test
  public void testSkipToNextPageNoMatch() throws Exception {
    FakeExtractorInput extractorInput = OggTestData.createInput(
        new byte[] {'g', 'g', 'S', 'O', 'g', 'g'}, false);
    try {
      skipToNextPage(extractorInput);
      fail();
    } catch (EOFException e) {
      // expected
    }
  }

  private static void skipToNextPage(ExtractorInput extractorInput)
      throws IOException, InterruptedException {
    DefaultOggSeeker oggSeeker =
        new DefaultOggSeeker(
            /* startPosition= */ 0,
            /* endPosition= */ extractorInput.getLength(),
            /* streamReader= */ new FlacReader(),
            /* firstPayloadPageSize= */ 1,
            /* firstPayloadPageGranulePosition= */ 2,
            /* firstPayloadPageIsLastPage= */ false);
    while (true) {
      try {
        oggSeeker.skipToNextPage(extractorInput);
        break;
      } catch (FakeExtractorInput.SimulatedIOException e) { /* ignored */ }
    }
  }

  @Test
  public void testSkipToPageOfGranule() throws IOException, InterruptedException {
    byte[] packet = TestUtil.buildTestData(3 * 254, random);
    byte[] data = TestUtil.joinByteArrays(
        OggTestData.buildOggHeader(0x01, 20000, 1000, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 40000, 1001, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 60000, 1002, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet);
    FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build();

    // expect to be granule of the previous page returned as elapsedSamples
    skipToPageOfGranule(input, 54000, 40000);
    // expect to be at the start of the third page
    assertThat(input.getPosition()).isEqualTo(2 * (30 + (3 * 254)));
  }

  @Test
  public void testSkipToPageOfGranulePreciseMatch() throws IOException, InterruptedException {
    byte[] packet = TestUtil.buildTestData(3 * 254, random);
    byte[] data = TestUtil.joinByteArrays(
        OggTestData.buildOggHeader(0x01, 20000, 1000, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 40000, 1001, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 60000, 1002, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet);
    FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build();

    skipToPageOfGranule(input, 40000, 20000);
    // expect to be at the start of the second page
    assertThat(input.getPosition()).isEqualTo(30 + (3 * 254));
  }

  @Test
  public void testSkipToPageOfGranuleAfterTargetPage() throws IOException, InterruptedException {
    byte[] packet = TestUtil.buildTestData(3 * 254, random);
    byte[] data = TestUtil.joinByteArrays(
        OggTestData.buildOggHeader(0x01, 20000, 1000, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 40000, 1001, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet,
        OggTestData.buildOggHeader(0x04, 60000, 1002, 0x03),
        TestUtil.createByteArray(254, 254, 254), // Laces.
        packet);
    FakeExtractorInput input = new FakeExtractorInput.Builder().setData(data).build();

    skipToPageOfGranule(input, 10000, -1);
    assertThat(input.getPosition()).isEqualTo(0);
  }

  private void skipToPageOfGranule(ExtractorInput input, long granule,
      long elapsedSamplesExpected) throws IOException, InterruptedException {
    DefaultOggSeeker oggSeeker =
        new DefaultOggSeeker(
            /* startPosition= */ 0,
            /* endPosition= */ input.getLength(),
            /* streamReader= */ new FlacReader(),
            /* firstPayloadPageSize= */ 1,
            /* firstPayloadPageGranulePosition= */ 2,
            /* firstPayloadPageIsLastPage= */ false);
    while (true) {
      try {
        assertThat(oggSeeker.skipToPageOfGranule(input, granule, -1))
            .isEqualTo(elapsedSamplesExpected);
        return;
      } catch (FakeExtractorInput.SimulatedIOException e) {
        input.resetPeekPosition();
      }
    }
  }

  @Test
  public void testReadGranuleOfLastPage() throws IOException, InterruptedException {
    FakeExtractorInput input = OggTestData.createInput(TestUtil.joinByteArrays(
        TestUtil.buildTestData(100, random),
        OggTestData.buildOggHeader(0x00, 20000, 66, 3),
        TestUtil.createByteArray(254, 254, 254), // laces
        TestUtil.buildTestData(3 * 254, random),
        OggTestData.buildOggHeader(0x00, 40000, 67, 3),
        TestUtil.createByteArray(254, 254, 254), // laces
        TestUtil.buildTestData(3 * 254, random),
        OggTestData.buildOggHeader(0x05, 60000, 68, 3),
        TestUtil.createByteArray(254, 254, 254), // laces
        TestUtil.buildTestData(3 * 254, random)
    ), false);
    assertReadGranuleOfLastPage(input, 60000);
  }

  @Test
  public void testReadGranuleOfLastPageAfterLastHeader() throws IOException, InterruptedException {
    FakeExtractorInput input = OggTestData.createInput(TestUtil.buildTestData(100, random), false);
    try {
      assertReadGranuleOfLastPage(input, 60000);
      fail();
    } catch (EOFException e) {
      // ignored
    }
  }

  @Test
  public void testReadGranuleOfLastPageWithUnboundedLength()
      throws IOException, InterruptedException {
    FakeExtractorInput input = OggTestData.createInput(new byte[0], true);
    try {
      assertReadGranuleOfLastPage(input, 60000);
      fail();
    } catch (IllegalArgumentException e) {
      // ignored
    }
  }

  private void assertReadGranuleOfLastPage(FakeExtractorInput input, int expected)
      throws IOException, InterruptedException {
    DefaultOggSeeker oggSeeker =
        new DefaultOggSeeker(
            /* startPosition= */ 0,
            /* endPosition= */ input.getLength(),
            /* streamReader= */ new FlacReader(),
            /* firstPayloadPageSize= */ 1,
            /* firstPayloadPageGranulePosition= */ 2,
            /* firstPayloadPageIsLastPage= */ false);
    while (true) {
      try {
        assertThat(oggSeeker.readGranuleOfLastPage(input)).isEqualTo(expected);
        break;
      } catch (FakeExtractorInput.SimulatedIOException e) {
        // ignored
      }
    }
  }

}


text:
{% load transurlvania_tags %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   {% block content %}{% endblock %}
   French Version


text:
package ar.com.quark.render.font;

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

/**
 * FontGlyph encapsulate the information of a character in a {@link Font}.
 */
public final class FontGlyph {
    private final int mID;
    private final int mX;
    private final int mY;
    private final int mWidth;
    private final int mHeight;
    private final int mOffsetX;
    private final int mOffsetY;
    private final int mAdvance;
    private final int mPage;
    private final Map<Integer, Integer> mKerning = new HashMap<>();
    private final float mTextureX1;
    private final float mTextureY1;
    private final float mTextureX2;
    private final float mTextureY2;

    /**
     *
Constructor

     */
    public FontGlyph(int id,
            int x,
            int y,
            int width,
            int height,
            int offsetX,
            int offsetY,
            int advance,
            int page,
            float textureX1,
            float textureY1,
            float textureX2,
            float textureY2) {
        mID = id;
        mX = x;
        mY = y;
        mWidth = width;
        mHeight = height;
        mOffsetX = offsetX;
        mOffsetY = offsetY;
        mAdvance = advance;
        mPage = page;
        mTextureX1 = textureX1;
        mTextureY1 = textureY1;
        mTextureX2 = textureX2;
        mTextureY2 = textureY2;
    }

    /**
     *
Get the x1 coordinate of the character

     *
     * @return the x1 coordinate of the character
     */
    public float getTextureX1Coordinate() {
        return mTextureX1;
    }

    /**
     *
Get the y1 coordinate of the character

     *
     * @return the y1 coordinate of the character
     */
    public float getTextureY1Coordinate() {
        return mTextureY1;
    }

    /**
     *
Get the x2 coordinate of the character

     *
     * @return the x2 coordinate of the character
     */
    public float getTextureX2Coordinate() {
        return mTextureX2;
    }

    /**
     *
Get the y2 coordinate of the character

     *
     * @return the y2 coordinate of the character
     */
    public float getTextureY2Coordinate() {
        return mTextureY2;
    }

    /**
     *
Get the unique identifier of the character

     *
     * @return the unique identifier of the character
     */
    public int getID() {
        return mID;
    }

    /**
     *
Get the x coordinate (in pixel coordinates) of the character

     *
     * @return the x coordinate (in pixel coordinates) of the character
     */
    public int getX() {
        return mX;
    }

    /**
     *
Get the y coordinate (in pixel coordinates) of the character

     *
     * @return the y coordinate (in pixel coordinates) of the character
     */
    public int getY() {
        return mY;
    }

    /**
     *
Get the width (in pixel coordinates) of the character

     *
     * @return the width (in pixel coordinates) of the character
     */
    public int getWidth() {
        return mWidth;
    }

    /**
     *
Get the height (in pixel coordinates) of the character

     *
     * @return the height (in pixel coordinates) of the character
     */
    public int getHeight() {
        return mHeight;
    }

    /**
     *
Get the offset of the x coordinate (in pixel coordinates) of the character

     *
     * @return the offset of the x coordinate (in pixel coordinates) of the character
     */
    public int getOffsetX() {
        return mOffsetX;
    }

    /**
     *
Get the offset of the y coordinate (in pixel coordinates) of the character

     *
     * @return the offset of the y coordinate (in pixel coordinates) of the character
     */
    public int getOffsetY() {
        return mOffsetY;
    }

    /**
     *
Get the advance (in pixel coordinates) of the character

     *
     * @return the advance (in pixel coordinates) of the character
     */
    public int getAdvance() {
        return mAdvance;
    }

    /**
     *
Get the page (image) of the character

     *
     * @return the page (image) of the character
     */
    public int getPage() {
        return mPage;
    }

    /**
     *
Register a new kerning character

     *
     * @param character the kerning's character
     * @param amount    the kerning's amount
     */
    public void addKerning(int character, int amount) {
        mKerning.put(character, amount);
    }

    /**
     *
Get the kerning value of the given character

     *
     * @param character the character to retrieve the kerning from
     *
     * @return the kerning value of the given character
     */
    public int getKerning(int character) {
        return mKerning.containsKey(character) ? mKerning.get(character) : 0;
    }
}


text:
Cordova UnityAds plugin
====================
# Overview #
Show unityads video ad and rewarded video ad (pays high $0.05 per ad view).

[android, ios] [cordova cli] [xdk] [cocoon] [phonegap build service]

Requires unityads account http://unityads.unity3d.com

UnityAds SDK v1.5.6 January 5th, 2016 (android)

UnityAds SDK v1.5.6 January 5th, 2016 (ios)

This is open source cordova plugin.

You can see Cordova Plugins in one page: http://cranberrygame.github.io?referrer=github

# Change log #
```c

1.0.28
	Supported ios callback event.
1.0.32
    Updated SDK v1.5.3
1.0.33
    Updated SDK v1.5.4
1.0.35
    Updated SDK v1.5.6
```
# Install plugin #

## Cordova cli ##
https://cordova.apache.org/docs/en/edge/guide_cli_index.md.html#The%20Command-Line%20Interface - npm install -g cordova@6.0.0
```c
cordova plugin add cordova-plugin-ad-unityads
(when build error, use github url: cordova plugin add cordova plugin add https://github.com/cranberrygame/cordova-plugin-ad-unityads)
```

## Xdk ##
https://software.intel.com/en-us/intel-xdk - Download XDK - XDK PORJECTS - [specific project] - CORDOVA HYBRID MOBILE APP SETTINGS - Plugin Management - Add Plugins to this Project - Third Party Plugins -
```c
Plugin Source: Cordova plugin registry
Plugin ID: cordova-plugin-ad-unityads
```

```c
Fix crosswalk build error:
crosswalk 11 build error so use crosswalk upper version (crosswalk 12 or 14)
```

## Cocoon ##
https://cocoon.io - Create project - [specific project] - Setting - Plugins - Custom - Git Url: https://github.com/cranberrygame/cordova-plugin-ad-unityads.git - INSTALL - Save

## Phonegap build service (config.xml) ##
https://build.phonegap.com/ - Apps - [specific project] - Update code - Zip file including config.xml
```c
<gap:plugin name="cordova-plugin-ad-unityads" source="npm" />
```

## Construct2 ##
Download construct2 plugin

https://dl.dropboxusercontent.com/u/186681453/pluginsforcordova/index.html

How to install c2 native plugins in xdk, cocoon and cordova cli

https://plus.google.com/102658703990850475314/posts/XS5jjEApJYV

# Server setting #
```c
```

# API #
```javascript
var gameId = "REPLACE_THIS_WITH_YOUR_GAME_ID";
var videoAdPlacementId = "defaultZone";
var rewardedVideoAdPlacementId = "rewardedVideoZone";
var isTest = true;
/*
var gameId;
var videoAdPlacementId;
var rewardedVideoAdPlacementId;
var isTest = true;
//android
if (navigator.userAgent.match(/Android/i)) {
	gameId = "REPLACE_THIS_WITH_YOUR_GAME_ID";
	videoAdPlacementId = "defaultZone";
	rewardedVideoAdPlacementId = "rewardedVideoZone";
}
//ios
else if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
	gameId = "REPLACE_THIS_WITH_YOUR_GAME_ID";
	videoAdPlacementId = "defaultZone";
	rewardedVideoAdPlacementId = "rewardedVideoZone";
}
*/

document.addEventListener("deviceready", function(){
	//if no license key, 2% ad traffic share for dev support.
	//you can get paid license key: https://cranberrygame.github.io/request_cordova_ad_plugin_paid_license_key
	//window.unityads.setLicenseKey("yourEmailId@yourEmaildDamin.com", "yourLicenseKey");

	window.unityads.setUp(gameId, videoAdPlacementId, rewardedVideoAdPlacementId, isTest);

	//
	window.unityads.onVideoAdLoaded = function() {
		alert('onVideoAdLoaded');
	};
	window.unityads.onVideoAdShown = function() {
		alert('onVideoAdShown');
	};
	window.unityads.onVideoAdHidden = function() {
		alert('onVideoAdHidden');
	};
	//
	window.unityads.onRewardedVideoAdLoaded = function() {
		alert('onRewardedVideoAdLoaded');
	};
	window.unityads.onRewardedVideoAdShown = function() {
		alert('onRewardedVideoAdShown');
	};
	window.unityads.onRewardedVideoAdHidden = function() {
		alert('onRewardedVideoAdHidden');
	};
	window.unityads.onRewardedVideoAdCompleted = function() {
		alert('onRewardedVideoAdCompleted');
	};
}, false);

window.unityads.showVideoAd();

window.unityads.showRewardedVideoAd();

alert(window.unityads.loadedVideoAd());//boolean: true or false
alert(window.unityads.loadedRewardedVideoAd());//boolean: true or false

alert(window.unityads.isShowingVideoAd());//boolean: true or false
alert(window.unityads.isShowingRewardedVideoAd());//boolean: true or false
```
# Examples #
example/basic/index.html

# Test #

[![](http://img.youtube.com/vi/L_TgOf-XwDY/0.jpg)](https://www.youtube.com/watch?v=L_TgOf-XwDY&feature=youtu.be "Youtube")

You can also run following test apk.
https://dl.dropboxusercontent.com/u/186681453/pluginsforcordova/unityads/apk.html

# Useful links #

Cordova Plugins

http://cranberrygame.github.io?referrer=github

# Credits #


text:
package io.github.jeddict.relation.mapper.widget.column.embedded;

import io.github.jeddict.util.StringUtils;
import io.github.jeddict.relation.mapper.widget.column.ColumnWidget;
import io.github.jeddict.relation.mapper.spec.DBEmbeddedAttributeColumn;
import io.github.jeddict.relation.mapper.initializer.RelationMapperScene;
import static io.github.jeddict.relation.mapper.initializer.RelationMapperUtil.inDev;
import io.github.jeddict.jpa.spec.AttributeOverride;
import io.github.jeddict.jpa.spec.Column;
import io.github.jeddict.jpa.spec.ElementCollection;
import io.github.jeddict.jpa.spec.extend.Attribute;
import io.github.jeddict.jpa.spec.extend.ColumnHandler;
import io.github.jeddict.jpa.spec.extend.PersistenceBaseAttribute;
import org.netbeans.modeler.specification.model.document.property.ElementPropertySet;
import org.netbeans.modeler.widget.node.IPNodeWidget;
import org.netbeans.modeler.widget.pin.info.PinWidgetInfo;
import org.netbeans.modeler.widget.properties.handler.PropertyChangeListener;

public class EmbeddedAttributeColumnWidget<E extends DBEmbeddedAttributeColumn> extends ColumnWidget<E> {

    public EmbeddedAttributeColumnWidget(RelationMapperScene scene, IPNodeWidget nodeWidget, PinWidgetInfo pinWidgetInfo) {
        super(scene, nodeWidget, pinWidgetInfo);

    }

    @Override
    protected String evaluateName() {
        AttributeOverride attributeOverride = this.getBaseElementSpec().getAttributeOverride();
        Attribute refAttribute = this.getBaseElementSpec().getAttribute();
        if (this.getBaseElementSpec().getAttribute() instanceof ElementCollection) {
            inDev();
        }
        if (refAttribute instanceof ColumnHandler) {
            ColumnHandler baseRefAttribute = (ColumnHandler) refAttribute;
            Column column = baseRefAttribute.getColumn();

            if (StringUtils.isNotBlank(attributeOverride.getColumn().getName())) {
                return attributeOverride.getColumn().getName();
            } else if (StringUtils.isNotBlank(column.getName())) {
                return column.getName();
            } else {
                return baseRefAttribute.getDefaultColumnName();
            }
        } else {
            throw new IllegalStateException("Invalid attribute type : " + refAttribute.getClass().getSimpleName());
        }
    }

    @Override
    protected void updateName(String newName) {
        if (this.getBaseElementSpec().getAttribute() instanceof ElementCollection) {
            inDev();
        } else {
            AttributeOverride attributeOverride = this.getBaseElementSpec().getAttributeOverride();
            attributeOverride.getColumn().setName(newName);
        }
    }

    @Override
    public void createPropertySet(ElementPropertySet set) {
        Attribute refAttribute = this.getBaseElementSpec().getAttribute();
        if (refAttribute instanceof PersistenceBaseAttribute) {
            PersistenceBaseAttribute baseRefAttribute = (PersistenceBaseAttribute) refAttribute;
            set.createPropertySet("EMBEDDABLE_COLUMN", this, baseRefAttribute.getColumn(), getPropertyChangeListeners());

            AttributeOverride attributeOverride = this.getBaseElementSpec().getAttributeOverride();
            set.createPropertySet("ATTRIBUTE_OVERRIDE", "ATTR_OVERRIDE", this, attributeOverride.getColumn(), getPropertyChangeListeners());
        } else if (this.getBaseElementSpec().getAttribute() instanceof ElementCollection) {
            //in dev
        }
        this.addPropertyChangeListener("column_name", (PropertyChangeListener<String>) (oldValue, value) -> setMultiPropertyName(value));
        this.addPropertyChangeListener("attr_override_column_name", (PropertyChangeListener<String>) (oldValue, value) -> setMultiPropertyName(value));
        this.addPropertyChangeListener("table_name", (PropertyChangeListener<String>) (oldValue, value) -> validateTableName(value));
        this.addPropertyChangeListener("attr_override_table_name", (PropertyChangeListener<String>) (oldValue, value) -> validateTableName(value));
    }
}


text:
from django.conf import settings
from django.http import FileResponse
from django.utils.translation import ugettext_lazy as _

from rest_framework.exceptions import ValidationError, NotFound

from daiquiri.core.adapter import DatabaseAdapter
from daiquiri.core.adapter.stream import BaseServiceAdapter
from daiquiri.core.utils import import_class, make_query_dict_upper_case
from daiquiri.core.generators import generate_votable

def ConeSearchAdapter():
    return import_class(settings.CONESEARCH_ADAPTER)()

class BaseConeSearchAdapter(BaseServiceAdapter):

    keys = ['RA', 'DEC', 'SR']

    ranges = {
        'RA': {
            'min': 0,
            'max': 360
        },
        'DEC': {
            'min': -90,
            'max': 90
        },
        'SR': {
            'min': 0,
            'max': 10
        }
    }

    defaults = {
        'RA': 20,
        'DEC': 20,
        'SR': 10,
    }

    columns = [
        {
            'name': 'id',
            'ucd': 'meta.id; meta.main',
            'datatype': 'char',
            'arraysize': '*'
        },
        {
            'name': 'RA',
            'ucd': 'pos.eq.ra; meta.main',
            'datatype': 'double'
        },
        {
            'name': 'DEC',
            'ucd': 'pos.eq.dec; meta.main',
            'datatype': 'double'
        }
    ]

    max_records = 10000

    def get_resources(self):
        raise NotImplementedError()

    def clean(self, request, resource):
        raise NotImplementedError()

    def clean_args(self, data, errors):
        # parse RA, DEC, and SR arguments
        self.args = {}
        for key in ['RA', 'DEC', 'SR']:
            try:
                value = float(data[key])

                if self.ranges[key]['min'] <= value <= self.ranges[key]['max']:
                    self.args[key] = value
                else:
                    errors[key] = [_('This value must be between %(min)g and %(max)g.' % self.ranges[key])]

            except KeyError:
                errors[key] = [_('This field may not be blank.')]

            except ValueError:
                errors[key] = [_('This field must be a float.')]

    def stream(self):
        return FileResponse(generate_votable(DatabaseAdapter().fetchall(self.sql, self.args), self.columns), content_type='application/xml')

class SimpleConeSearchAdapter(BaseConeSearchAdapter):

    def get_resources(self):
        return [settings.CONESEARCH_TABLE]

    def clean(self, request, resource):
        if resource not in self.get_resources():
            raise NotFound()

        adapter = DatabaseAdapter()

        self.sql = '''
SELECT %(id_field)s, %(ra_field)s, %(dec_field)s
FROM %(schema)s.%(table)s
WHERE
    %(ra_field)s BETWEEN (%%(RA)s - 0.5 * %%(SR)s) AND (%%(RA)s + 0.5 * %%(SR)s)
AND
    %(dec_field)s BETWEEN (%%(DEC)s - 0.5 * %%(SR)s) AND (%%(DEC)s + 0.5 * %%(SR)s)
LIMIT %(limit)s
''' % {
            'id_field': adapter.escape_identifier('id'),
            'ra_field': adapter.escape_identifier('ra'),
            'dec_field': adapter.escape_identifier('dec'),
            'schema': settings.CONESEARCH_SCHEMA,
            'table': settings.CONESEARCH_TABLE,
            'limit': self.max_records
        }

        self.args, errors = self.parse_query_dict(request)

        if errors:
            raise ValidationError(errors)

class TableConeSearchAdapter(BaseConeSearchAdapter):

    def clean(self, request, resource):
        from daiquiri.metadata.models import Schema, Table

        resources = self.get_resources()

        if resource not in resources:
            raise NotFound

        schema_name = resources[resource]['schema_name']
        table_name = resources[resource]['table_name']

        data = make_query_dict_upper_case(request.GET)
        errors = {}

        # check if the user is allowed to access the schema
        try:
            schema = Schema.objects.filter_by_access_level(request.user).get(name=schema_name)
        except Schema.DoesNotExist:
            raise NotFound

        # check if the user is allowed to access the table
        try:
            table = Table.objects.filter_by_access_level(request.user).filter(schema=schema).get(name=table_name)
        except Table.DoesNotExist:
            raise NotFound

        # fetch the columns accoring to the verbosity
        verb = data.get('VERB', '2')

        if verb == '1':
            self.columns = table.columns.filter(name__in=resources[resource]['column_names']).values()
        elif verb == '2':
            self.columns = table.columns.filter(principal=True).values()
        elif verb == '3':
            self.columns = table.columns.values()
        else:
            errors['VERB'] = [_('This field must be 1, 2, or 3.')]

        # construct sql query
        adapter = DatabaseAdapter()
        escaped_column_names = [adapter.escape_identifier(column['name']) for column in self.columns]
        self.sql = self.sql_pattern % {
            'schema': adapter.escape_identifier(schema_name),
            'table': adapter.escape_identifier(table_name),
            'columns': ', '.join(escaped_column_names)
        }

        # parse RA, DEC, and SR arguments
        self.args = {}
        for key in ['RA', 'DEC', 'SR']:
            try:
                value = float(data[key])

                if self.ranges[key]['min'] <= value <= self.ranges[key]['max']:
                    self.args[key] = value
                else:
                    errors[key] = [_('This value must be between %(min)g and %(max)g.' % self.ranges[key])]

            except KeyError:
                errors[key] = [_('This field may not be blank.')]

            except ValueError:
                errors[key] = [_('This field must be a float.')]

        if errors:
            raise ValidationError(errors)


text:
<?php

namespace BackEndBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * ProductPacks
 *
 * @ORM\Table(name="product_packs")
 * @ORM\Entity
 */
class ProductPacks
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="user_id", type="integer", nullable=false)
     */
    private $userId;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="price", type="decimal", precision=7, scale=2, nullable=true)
     */
    private $price;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="blob", nullable=true)
     */
    private $description;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set userId
     *
     * @param integer $userId
     * @return ProductPacks
     */
    public function setUserId($userId)
    {
        $this->userId = $userId;

        return $this;
    }

    /**
     * Get userId
     *
     * @return integer
     */
    public function getUserId()
    {
        return $this->userId;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return ProductPacks
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set price
     *
     * @param string $price
     * @return ProductPacks
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return string
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return ProductPacks
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
}


text:
layout: post
title:  "Hardware is exciting again!"
date:   2016-02-18 00:05:26 -0500
categories: intro
---

# I used to not care about hardware.

I'm one of those typical programmers who cares about algorithms and
software design. I like math and statically typed functional
languages, although I choose Python for most tasks. I couldn't care
less about the latest graphics card or javascript framework. Trends
are beneath me!

But lately things have changed. Something big is happening. I'm not
overstating things when I say that the new hardware available is
different in kind, not just in degree. To take advantage of it
requires redesigning a lot of our systems at a fundamental level.
And that's exciting!

### The new hardware is not just "the same but better"

One example is GPU computing: massive fine-grained parallelism with
limited memory, no deep pipelines, no out-of-order execution, and no
sophisticated cache hierarchy. It's like we had to throw out many of
the microarchitectural tricks that worked for CPUs before we could get
great performance in this different paradigm. And this paradigm is
good for a different type of problem than what CPUs are good for.

Another example is fast non-volatile memory. Traditionally, there is
huge gap in performance between RAM and hard drives. The latency of
accessing a hard drive is 2-3 orders of magnitude greater than that of
accessing main memory, but hard drives have 1-2 orders of magnitude
more capacity. The new SSDs are a genuinely new category of memory
that sits between the two in terms of latency, throughput and
capacity.

The assumption that permanent storage is much slower than RAM is baked
into the design of filesystems, kernel system calls, the virtual
memory system and the design of data centers. We're finding out that
the overhead of the context switch for a syscall is too great when the
SSD returns with data immediately. And the new memory is expensive, so
it makes sense to saturate it using several CPUS. That's a complete
reversal of the usual design where several hard drives are controlled
by a single CPU.

### This has incredibly deep consequences for our programs

It used to be the case that we could expect software to get faster
every year with no extra work -- we could piggyback off of hardware
improvements. That's not true any more. The hardware's still getting
better, but not at running the old kinds of software (by much).

To take advantage of the new hardware, we need to redesign all the way
down to our algorithms. We need to rewrite large parts of the OS
kernel and standard libraries. Our high-level languages are
inappropriate and don't expose the new functionality so we're stuck
with C/C++ for now. What will a high-level equivalent of CUDA look
like?

### Learning from data

At the same time, we have an exciting new use for all this power:
statistical machine learning. The massive success of machine learning
in the last decade can be summarized like so: use simple models on
gigantic datasets.

Well, the models have to be sufficiently general (flexible) to be
effective across many problems. And they have to be computationally
tractable otherwise we couldn't train them on huge datasets.

For example, neural networks are linear classifiers connected in a
graph, trained using gradient descent. Linear classifiers are about
the simplest model imaginable (few parameters), but connecting several
of them in a graph increases flexibility (inevitably accompanied by an
increase in the number of parameters).

To nail down the right values of all those parameters you use a large
number of training examples. This can be expressed as a mathematical
optimization problem:

$$
\min_{parameters} error(model, data)
$$

There is no general efficient algorithm for such optimization problems
but there are ways to find approximate solutions quickly if you can
compute the first derivatives of the error with respect to all the
parameters of the model (this imposes restrictions on what kinds of
models are admissible: not all models are differentiable). And there
is no general efficient algorithm to compute derivatives.

### Lots of data

But for the special case of linear classifiers connected in a graph,
there's an algorithm called _backpropagation_ that makes it efficient
to compute gradients for large networks and truly _huge_ datasets. And
that's why neural networks work.

It's an amazing paradox that mathematicians are working to explain:
dumb algorithms paired with huge amounts of data make for very smart
models, much smarter than anyone has been able to create with
traditional methods. This is in contrast to the previous incarnation
of AI, which used the expressive power of LISP to create very smart
algorithms known as "expert systems". While this line of research
contributed fundamental advances in areas like combinatorial
optimization and programming language theory, it did not succeed at
tasks like driving vehicles or translation.

For me, this is the heart of what makes performance interesting again:
it yields better results, because you can use more data to train. And
in this new world, you have to get close to the hardware if you want
performance.


text:
package com.amazonaws.services.servermigration.model;

import javax.annotation.Generated;

/**
 * Capabilities for a Connector
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ConnectorCapability {

    VSPHERE("VSPHERE");

    private String value;

    private ConnectorCapability(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ConnectorCapability corresponding to the value
     */
    public static ConnectorCapability fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ConnectorCapability enumEntry : ConnectorCapability.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
using System;
using ZKWeb.Plugins.Common.Admin.src.Domain.Filters;
using ZKWeb.Plugins.Common.Base.src.Domain.Uow.Extensions;
using ZKWeb.Plugins.Common.Base.src.Domain.Uow.Interfaces;
using ZKWeb.Web;

namespace ZKWeb.Plugins.Common.Admin.src.Components.ActionFilters {
	/// <summary>
	/// 自动检查和设置实体的所属用户
	/// </summary>
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
	public class CheckOwnerAttribute : ActionFilterAttribute {
		/// <summary>
		/// 启用所属用户使用的查询和操作过滤器
		/// </summary>
		public override Func<IActionResult> Filter(Func<IActionResult> action) {
			return () => {
				var uow = Application.Ioc.Resolve<IUnitOfWork>();
				var filter = new OwnerFilter();
				using (uow.Scope())
				using (uow.EnableQueryFilter(filter))
				using (uow.EnableOperationFilter(filter)) {
					return action();
				}
			};
		}
	}
}


text:
<paths xmlns:android="http://schemas.android.com/apk/res/android">

	<external-path
		name="test-external-root"
		path="StreamProviderTests/"/>

	<external-files-path dir="Documents" name="test-external-files"/>
	<external-files-path dir="Music" name="test-music-files"/>

	<external-public-path dir="Download" name="test-download-files"/>

	<external-cache-path name="test-external-cache"/>

	<cache-path name="test-cache"/>

	<files-path name="test-standard" path="foo"/>

	<files-path name="test-read-only" path="ro" readOnly="true"/>

	<dir-path name="test-dir" dir="app_data" path="ic_launcher.png" readOnly="true"/>

	<raw-resource
		name="test-raw"
		path="something"/>

  <asset
    name="test-asset"
    path="ic_launcher.png"/>

  <asset
    name="test-largeasset"/>

</paths>


text:
'use strict';

var adminPolicy = require('../policies/device.server.policy'),
  farmZoneController = require('../controllers/farm.zone.controller');
var auth = require('../../../users/server/controllers/users/users.authentication.server.controller');
module.exports = function (app) {
  app.route('/v1/farm/:farm_id')
    .all(auth.isAuthenticatedByJWT) // check the user is authenticated through jwt
    .delete(farmZoneController.removeFarmZone)
    .put(farmZoneController.updateFarmZone);

  app.route('/v1/farm').all(auth.isAuthenticatedByJWT)
    .post(farmZoneController.createFarmZone)
    .get(farmZoneController.getFarmZones);

  app.route('/v1/farm/:farm_id/system').get(farmZoneController.getFarmZoneSystem);
  app.route('/v1/farm/:farm_id').get(farmZoneController.getFarmZone);
  app.route('/v1/farm/:farm_id/system/:system_id/command').post(farmZoneController.modeFarmSystem);
  app.route('/v1/farm/:farm_id/system/:system_id/command').post(farmZoneController.controlFarmSystem);
  app.route('/v1/farm/:farm_id/system/:system_id/status').get(farmZoneController.getFarmSystemStatus);
};


text:
class HeatSourceListDecorator
  def initialize(heat_source_list)
    @heat_source_list = heat_source_list
  end

  def decorate
    @heat_source_list.sorted_asset_list.map do |part|
      entity = Technology.find_by_key!(part.fetch(:key))

      InstalledHeatSource.new(part.merge(entity.attributes))
    end
  end
end


text:
<?php

namespace Mothership\StateMachine;

/**
 * Interface StatusInterface.
 *
 * @category  Mothership
 *
 * @author    Maurizio Brioschi <brioschi@mothership.de>
 * @author    Don Bosco van Hoi <vanhoi@mothership.de>
 * @copyright 2016 Mothership GmbH
 *
 * @link      http://www.mothership.de/
 */
interface StatusInterface
{
    // There can only be on state 'initial'
    const TYPE_INITIAL = 'initial';

    // There also can only be one state final
    const TYPE_FINAL = 'final';

    // All other states must be normal
    const TYPE_NORMAL = 'normal';

    // only for exception states
    const TYPE_EXCEPTION = 'exception';

    /**
     * Returns the state name.
     *
     * @return string
     */
    public function getName();

    /**
     * Returns the state type.
     *
     * @return string
     */
    public function getType();

    /**
     * Returns the available transitions.
     *
     * @return array
     */
    public function getTransitions();

    /**
     * Returns optional state properties.
     *
     * @return mixed
     */
    public function getProperties();
}