text:
<?php

namespace Base\Geospatial;

class BoundingBox implements GeolocationAreaInterface
{
    /**
     * @var GeolocationInterface
     */
    private $topLeft;
    /**
     * @var GeolocationInterface
     */
    private $bottomRight;

    /**
     *                            $topLeft->getLat()
     *                     +------------------------------+
     *                     | $topLeft                     |
     * $topLeft->getLong() |                              | $bottomRight->getLong()
     *                     |                              |
     *                     |                 $bottomRight |
     *                     +------------------------------+
     *                            $bottomRight->getLat()
     */
    public function __construct(GeolocationInterface $topLeft, GeolocationInterface $bottomRight)
    {
        $this->validateBoundingBox($topLeft, $bottomRight);

        $this->topLeft = $topLeft;
        $this->bottomRight = $bottomRight;
    }

    public function contains(GeolocationInterface $geolocation)
    {
        return $this->topLeft->getLong() <= $geolocation->getLong() &&
            $this->topLeft->getLat() >= $geolocation->getLat() &&
            $this->bottomRight->getLong() >= $geolocation->getLong() &&
            $this->bottomRight->getLat() <= $geolocation->getLat();
    }

    /**
     * @param GeolocationInterface $topLeft
     * @param GeolocationInterface $bottomRight
     *
     * @throws \InvalidArgumentException
     */
    private function validateBoundingBox(GeolocationInterface $topLeft, GeolocationInterface $bottomRight)
    {
        if ($topLeft->getLat() < $bottomRight->getLat()) {
            throw new \InvalidArgumentException('$topLeft must have a greater latitude than $bottomRight');
        }

        if ($topLeft->getLong() > $bottomRight->getLong()) {
            throw new \InvalidArgumentException('$topLeft must have a lesser longitude than $bottomRight');
        }
    }

    public static function fromCenterAndDistance(GeolocationInterface $center, Distance $distance)
    {
        $radLat = deg2rad($center->getLat());
        $radLon = deg2rad($center->getLong());

        // angular distance in radians on a great circle
        $radDist = $distance->getMeters() / GeolocationInterface::EARTH_RADIUS;

        $minLat = $radLat - $radDist;
        $maxLat = $radLat + $radDist;

        $deltaLon = asin(sin($radDist) / cos($radLat));

        $minLon = $radLon - $deltaLon;
        //if (minLon < MIN_LON) {minLon += 2d * Math.PI;}

        $maxLon = $radLon + $deltaLon;
        //if (maxLon > MAX_LON) {maxLon -= 2d * Math.PI;}

        $min = new Geolocation(rad2deg($maxLat), rad2deg($minLon));
        $max = new Geolocation(rad2deg($minLat), rad2deg($maxLon));

        return new BoundingBox($min, $max);
    }

    /** @return GeolocationInterface */
    public function getTopLeft()
    {
        return $this->topLeft;
    }

    /** @return GeolocationInterface */
    public function getBottomRight()
    {
        return $this->bottomRight;
    }
}


text:
This is the Microsoft Azure Graph RBAC Client Library.
This package has been tested with Python 2.7, 3.6+.
For a more complete view of Azure libraries, see the [azure sdk python release](https://aka.ms/azsdk/python/all).

# Usage

For code examples, see [Graph RBAC](https://docs.microsoft.com/python/api/overview/azure/active-directory) on docs.microsoft.com.

# Provide Feedback

If you encounter any bugs or have suggestions, please file an issue in the
[Issues](https://github.com/Azure/azure-sdk-for-python/issues)
section of the project.

![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-graphrbac%2FREADME.png)

redpajama_set_name: RedPajamaGithub


text:
@interface FunctionalKeyController ()
@end

@implementation FunctionalKeyController

#pragma mark - Init
- (instancetype)init
{
   if (self = [super init])
   {
      [self setupKeyViews];
   }
   return self;
}

#pragma mark - Class Init
+ (instancetype)controller
{
   FunctionalKeyController* controller = [[[self class] alloc] init];
   return controller;
}

#pragma mark - Setup
- (void)setupKeyViews
{
   // should be overridden!
}

#pragma mark - Update
- (void)updateLetterViewFrames:(CGRect)frame
{
   CGRect letterViewFrame = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
   for (KeyView* letterView in self.keyViewArray)
   {
      [letterView updateFrame:letterViewFrame];
   }
}

#pragma mark - Public
- (void)updateFrame:(CGRect)frame
{
   self.view.frame = frame;
   [self updateLetterViewFrames:frame];
}

- (void)updateMode:(KeyboardMode)mode
{
}

- (KeyView*)keyViewForMode:(KeyboardMode)mode
{
   return nil;
}

@end


text:
package unleashed

import (
	"fmt"
)

type PurchaseOrderService service

type PurchaseOrderLine struct {
	GUID                *string  `json:"Guid,omitempty"`
	LineNumber          *int     `json:"LineNumber,omitempty"`
	Product             *Product `json:"Product,omitempty"`
	DueDate             *string  `json:"DueDate,omitempty"`
	OrderQuantity       *float64 `json:"OrderQuantity,omitempty"`
	UnitPrice           *float64 `json:"UnitPrice,omitempty"`
	LineTotal           *float64 `json:"LineTotal,omitempty"`
	Volume              *float64 `json:"Volume,omitempty"`
	Weight              *float64 `json:"Weight,omitempty"`
	Comments            *string  `json:"Comments,omitempty"`
	ReceiptQuantity     *string  `json:"ReceiptQuantity,omitempty"`
	BCUnitPrice         *float64 `json:"BCUnitPrice,omitempty"`
	BCSubTotal          *float64 `json:"BCSubTotal,omitempty"`
	Tax                 *Tax     `json:"Tax,omitempty"`
	LineTax             *float64 `json:"LineTax,omitempty"`
	LastModifiedOn      *string  `json:"LastModifiedOn,omitempty"`
	DiscountedUnitPrice *float64 `json:"DiscountedUnitPrice,omitempty"`
	DiscountRate        *float64 `json:"DiscountRate,omitempty"`
}

type Supplier struct {
	GUID         *string `json:"Guid,omitempty"`
	SupplierCode *string `json:"SupplierCode,omitempty"`
	SupplierName *string `json:"SupplierName,omitempty"`
}

type PurchaseOrder struct {
	GUID                  *string              `json:"Guid,omitempty"`
	OrderNumber           *string              `json:"OrderNumber,omitempty"`
	OrderDate             *string              `json:"OrderDate,omitempty"`
	RequiredDate          *string              `json:"RequiredDate,omitempty"`
	CompletedDate         *string              `json:"CompletedDate,omitempty"`
	Supplier              *Supplier            `json:"Supplier,omitempty"`
	SupplierRef           *string              `json:"SupplierRef,omitempty"`
	Comments              *string              `json:"Comments,omitempty"`
	Printed               *bool                `json:"Printed,omitempty"`
	OrderStatus           *string              `json:"OrderStatus,omitempty"`
	ReceivedDate          *string              `json:"ReceivedDate,omitempty"`
	DeliveryName          *string              `json:"DeliveryName,omitempty"`
	DeliveryStreetAddress *string              `json:"DeliveryStreetAddress,omitempty"`
	DeliverySuburb        *string              `json:"DeliverySuburb,omitempty"`
	DeliveryRegion        *string              `json:"DeliveryRegion,omitempty"`
	DeliveryCity          *string              `json:"DeliveryCity,omitempty"`
	DeliveryCountry       *string              `json:"DeliveryCountry,omitempty"`
	DeliveryPostCode      *string              `json:"DeliveryPostCode,omitempty"`
	Currency              *Currency            `json:"Currency,omitempty"`
	ExchangeRate          *float64             `json:"ExchangeRate,omitempty"`
	Tax                   *Tax                 `json:"Tax,omitempty"`
	TaxRate               *float64             `json:"TaxRate,omitempty"`
	XeroTaxCode           *string              `json:"XeroTaxCode,omitempty"`
	SubTotal              *float64             `json:"SubTotal,omitempty"`
	TaxTotal              *float64             `json:"TaxTotal,omitempty"`
	Total                 *float64             `json:"Total,omitempty"`
	TotalVolume           *float64             `json:"TotalVolume,omitempty"`
	TotalWeight           *float64             `json:"TotalWeight,omitempty"`
	SupplierInvoiceDate   *string              `json:"SupplierInvoiceDate,omitempty"`
	BCSubTotal            *float64             `json:"BCSubTotal,omitempty"`
	BCTaxTotal            *float64             `json:"BCTaxTotal,omitempty"`
	BCTotal               *float64             `json:"BCTotal,omitempty"`
	PurchaseOrderLines    []*PurchaseOrderLine `json:"PurchaseOrderLines,omitempty"`
	Warehouse             *Warehouse           `json:"Warehouse,omitempty"`
	LastModifiedOn        *string              `json:"LastModifiedOn,omitempty"`
	DiscountRate          *float64             `json:"DiscountRate,omitempty"`
}

type PurchaseOrderList struct {
	Pagination *Pagination      `json:"Pagination"`
	Items      []*PurchaseOrder `json:"Items"`
}

func (i PurchaseOrder) String() string {
	return Stringify(i)
}

func (s *PurchaseOrderService) List(opt *PageOptions, query *map[string]string) (*PurchaseOrderList, *Response, error) {
	u := "purchaseorders"

	purchaseOrders := &PurchaseOrderList{}
	resp, err := s.client.GetRequestData(u, opt, query, purchaseOrders)
	if err != nil {
		return nil, resp, err
	}

	return purchaseOrders, resp, err
}

func (s *PurchaseOrderService) GetPurchaseOrderBy(id string) (*PurchaseOrder, *Response, error) {
	u := "purchaseorders/" + id
	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	purchaseorders := &PurchaseOrder{}
	resp, err := s.client.Do(req, purchaseorders)
	if err != nil {
		return nil, resp, err
	}

	return purchaseorders, resp, err
}

func (s *PurchaseOrderService) CreatePurchaseOrder(purchaseorder *PurchaseOrder) (*PurchaseOrder, *Response, error) {
	u := fmt.Sprintf("purchaseorders/%v", *purchaseorder.GUID)
	req, err := s.client.NewRequest("POST", u, purchaseorder)
	if err != nil {
		return nil, nil, err
	}
	c := new(PurchaseOrder)
	resp, err := s.client.Do(req, c)
	if err != nil {
		return nil, resp, err
	}

	return c, resp, err
}

func (s *PurchaseOrderService) BatchCreatePurchaseOrders(purchaseorders *PurchaseOrderList) (*Response, error) {
	u := "PurchaseOrdersBatch"
	req, err := s.client.NewRequest("POST", u, purchaseorders)
	if err != nil {
		return nil, err
	}
	resp, err := s.client.Do(req, nil)
	if err != nil {
		return resp, err
	}

	return resp, err
}


text:
/**
 * @file
 * @brief エンコード関係
 */

using System;
using System.Text;

/*
 *
 */

namespace ThunderEgg.BrownSugar {

    /// エンコード関係
    public class EncodingTool {

        /// ボム無しUTF8エンコーダー
        public static Encoding UTF8N;

        static EncodingTool() {
            UTF8N = new UTF8Encoding(false);
        }
    }
}


text:
php -d extension=phar.so composer.phar install
mkdir -p tmp
chmod -R 777 tmp


text:
#include "config.h"
#include "modules/quota/WorkerNavigatorStorageQuota.h"

#include "modules/quota/DeprecatedStorageQuota.h"
#include "modules/quota/StorageManager.h"

namespace blink {

WorkerNavigatorStorageQuota::WorkerNavigatorStorageQuota()
{
}

const char* WorkerNavigatorStorageQuota::supplementName()
{
    return "WorkerNavigatorStorageQuota";
}

WorkerNavigatorStorageQuota& WorkerNavigatorStorageQuota::from(WorkerNavigator& navigator)
{
    WorkerNavigatorStorageQuota* supplement = static_cast<WorkerNavigatorStorageQuota*>(HeapSupplement<WorkerNavigator>::from(navigator, supplementName()));
    if (!supplement) {
        supplement = new WorkerNavigatorStorageQuota();
        provideTo(navigator, supplementName(), supplement);
    }
    return *supplement;
}

DeprecatedStorageQuota* WorkerNavigatorStorageQuota::webkitTemporaryStorage(WorkerNavigator& navigator)
{
    return WorkerNavigatorStorageQuota::from(navigator).webkitTemporaryStorage();
}

DeprecatedStorageQuota* WorkerNavigatorStorageQuota::webkitPersistentStorage(WorkerNavigator& navigator)
{
    return WorkerNavigatorStorageQuota::from(navigator).webkitPersistentStorage();
}

StorageManager* WorkerNavigatorStorageQuota::storage(WorkerNavigator& navigator)
{
    return WorkerNavigatorStorageQuota::from(navigator).storage();
}

DeprecatedStorageQuota* WorkerNavigatorStorageQuota::webkitTemporaryStorage() const
{
    if (!m_temporaryStorage)
        m_temporaryStorage = DeprecatedStorageQuota::create(DeprecatedStorageQuota::Temporary);
    return m_temporaryStorage.get();
}

DeprecatedStorageQuota* WorkerNavigatorStorageQuota::webkitPersistentStorage() const
{
    if (!m_persistentStorage)
        m_persistentStorage = DeprecatedStorageQuota::create(DeprecatedStorageQuota::Persistent);
    return m_persistentStorage.get();
}

StorageManager* WorkerNavigatorStorageQuota::storage() const
{
    if (!m_storageManager)
        m_storageManager = new StorageManager();
    return m_storageManager.get();
}

DEFINE_TRACE(WorkerNavigatorStorageQuota)
{
    visitor->trace(m_temporaryStorage);
    visitor->trace(m_persistentStorage);
    visitor->trace(m_storageManager);
    HeapSupplement<WorkerNavigator>::trace(visitor);
}

} // namespace blink


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

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Rio Pescado stubfoot toad factsheet on ARKive - Atelopus balios</title>
        <link rel="canonical" href="http://www.arkive.org/rio-pescado-stubfoot-toad/atelopus-balios/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Rio Pescado stubfoot toad (Atelopus balios)

Kingdom	Animalia

Phylum	Chordata

Class	Amphibia

Order	Anura

Family	Bufonidae

Genus	Atelopus (1)

Classified as Critically Endangered (CR) on the IUCN Red List (1).

Information on the Rio Pescado stubfoot toad is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact:
arkive@wildscreen.org.uk

IUCN Red List (April, 2010)
http://www.iucnredlist.org


text:
using ConsoleR.Server;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;

namespace ConsoleRSample.Web
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            app.UseFileServer();
            app.UseConsoleR();
        }
    }
}


text:
@interface PodsDummy_Pods_PagingMenuController : NSObject
@end
@implementation PodsDummy_Pods_PagingMenuController
@end


text:
/** @type {import("../../../").Configuration} */
module.exports = {
	entry: "./index"
};


text:
<?php

namespace Psi\Component\ContentType\Metadata\Driver;

use Metadata\Driver\AbstractFileDriver;
use Psi\Component\ContentType\Metadata\ClassMetadata;
use Psi\Component\ContentType\Metadata\PropertyMetadata;

class XmlDriver extends AbstractFileDriver
{
    const XML_NAMESPACE = 'http://github.com/psiphp/content-type/mapping';

    /**
     * {@inheritdoc}
     */
    public function loadMetadataFromFile(\ReflectionClass $class, $path)
    {
        $classMetadata = new ClassMetadata($class->getName());

        $use = libxml_use_internal_errors(true);
        $dom = new \DOMDocument('1.0');
        $dom->load($path);

        if (!$dom->schemaValidate(__DIR__ . '/../../../schema/mapping.xsd')) {
            $message = array_reduce(libxml_get_errors(), function ($foo, $error) {
                return $error->message;
            });
            throw new \InvalidArgumentException(sprintf(
                'Could not validate XML mapping at "%s": %s',
                $path, $message
            ));
        }
        libxml_use_internal_errors($use);

        $xpath = new \DOMXpath($dom);
        $xpath->registerNamespace('psict', self::XML_NAMESPACE);

        foreach ($xpath->query('//psict:class') as $classEl) {
            $classAttr = $classEl->getAttribute('name');

            if ($classAttr !== $class->getName()) {
                throw new \InvalidArgumentException(sprintf(
                    'Expected class name to be "%s" but it is mapped as "%s"',
                    $class->getName(), $classAttr
                ));
            }

            foreach ($xpath->query('./psict:field', $classEl) as $fieldEl) {
                $shared = $this->extractOptionSet($xpath, $fieldEl, 'shared-options');
                $form = $this->extractOptionSet($xpath, $fieldEl, 'form-options');
                $view = $this->extractOptionSet($xpath, $fieldEl, 'view-options');
                $storage = $this->extractOptionSet($xpath, $fieldEl, 'storage-options');

                $propertyMetadata = new PropertyMetadata(
                    $class->getName(),
                    $fieldEl->getAttribute('name'),
                    $fieldEl->getAttribute('type'),
                    $fieldEl->getAttribute('role'),
                    $fieldEl->getAttribute('group'),
                    [
                        'shared' => $shared,
                        'form' => $form,
                        'view' => $view,
                        'storage' => $storage,
                    ]
                );

                $classMetadata->addPropertyMetadata($propertyMetadata);
            }
        }

        return $classMetadata;
    }

    private function extractOptionSet(\DOMXpath $xpath, \DOMElement $fieldEl, $type)
    {
        foreach ($xpath->query('./psict:' . $type, $fieldEl) as $setEl) {
            return $this->extractOptions($xpath, $setEl);
        }
    }

    private function extractOptions(\DOMXPath $xpath, \DOMElement $setEl)
    {
        $options = [];

        foreach ($xpath->query('./psict:option', $setEl) as $optionEl) {
            if ($optionEl->getAttribute('type') === 'collection') {
                $options[$optionEl->getAttribute('name')] = $this->extractOptions($xpath, $optionEl);
                continue;
            }

            $options[$optionEl->getAttribute('name')] = $optionEl->nodeValue;
        }

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function getExtension()
    {
        return 'xml';
    }
}


text:
YAML loader for [webpack](http://webpack.github.io/). Converts YAML to a valid JSON. If you want a JS Object, chain it with [json-loader](https://github.com/webpack/json-loader).

## Installation

`npm install yaml-loader`

## Usage

[Documentation: Using loaders](http://webpack.github.io/docs/using-loaders.html)

Simplest case would be:

``` javascript
var json = require("json!yaml!./file.yml");
// => returns file.yml as javascript object
```

This loader is also useful for getting a valid JSON from YML. For example:

```js
// webpack.config.js
module: {
  loaders: [
    {
      test: /\.yaml$/,
      include: path.resolve('data'),
      loader: 'yaml',
    },
  ],
}
```

and then

```js
// applicatin.js
const actualFilename = require(`file?name=[name].json!./../data/${file}.yaml`);
window.fetch(actualFilename).then(res => {
  // ...
});
```

## License

MIT (http://www.opensource.org/licenses/mit-license.php)


text:
package gov.nih.nci.evs.browser.properties;

import java.util.*;
import org.apache.log4j.*;
import gov.nih.nci.evs.browser.webapp.*;
import gov.nih.nci.evs.utils.*;

/**
 *
 */

/**
 * @author EVS Team (David Yee)
 * @version 1.0
 */

public class AppProperties {
    private static final String PROPERTY_FILE = "NCITermFormPropertiesFile";
    private static final String BUILD_INFO = "NCITERMFORM_BUILD_INFO";
    private static final String APP_VERSION = "APPLICATION_VERSION";
    private static final String ANTHILL_BUILD_TAG_BUILT = "ANTHILL_BUILD_TAG_BUILT";
    private static final String DEBUG_ON = "DEBUG_ON";
    private static final String SEND_EMAIL = "SEND_EMAIL";
    private static final String MAIL_SMTP_SERVER = "MAIL_SMTP_SERVER";
    private static final String NCICB_CONTACT_URL = "NCICB_CONTACT_URL";
    private static final String VOCABULARY_PREFIX = "VOCABULARY_";
    private static final int VOCABULARY_MAX = 20;
    private static final String VOCABULARY_OTHER_EMAIL = "VOCABULARY_OTHER_EMAIL";
    private static final String CADSR_EMAIL = "CADSR_EMAIL";
    private static final String CADSR_SOURCES = "CADSR_SOURCES";
    private static final String CADSR_TYPES = "CADSR_TYPES";
    private static final String CDISC_EMAIL = "CDISC_EMAIL";
    private static final String CDISC_VOCABULARY_PREFIX = "CDISC_VOCABULARY_";
    private static final int CDISC_VOCABULARY_MAX = 20;
    private static final String CDISC_REQUEST_TYPES = "CDISC_REQUEST_TYPES";
    private static final String CDISC_CODES = "CDISC_CODES";
    private static final String CDISC_QUICKLINKS = "CDISC_QUICKLINKS";

    private static AppProperties _appProperties = null;
    private Logger _logger = Logger.getLogger(AppProperties.class);
    private HashMap<String, String> _configurableItemMap;
    private String _buildDate = null;
    private String _appVersion = null;
    private String _buildTag = null;
    private ArrayList<VocabInfo> _defaultVocabList = null;
    private String[] _cadsrEmail = null;
    private String[] _cadsrSourceList = null;
    private String[] _cadsrTypeList = null;
    private String[] _cdiscEmail = null;
    private ArrayList<VocabInfo> _cdiscVocabList = null;
    private String[] _cdiscRequestTypeList = null;
    private String[] _cdiscCodeList = null;
    private ArrayList<QuickLinkInfo> _cdiscQuickLinkList = null;

    private AppProperties() { // Singleton Pattern
        loadProperties();
    }

    static {
		_appProperties = new AppProperties();
	}

    public static AppProperties getInstance() {
		/*
        if (_appProperties == null)
            _appProperties = new AppProperties();
        */
        return _appProperties;
    }

    private void loadProperties() {
        synchronized (AppProperties.class) {
            String propertyFile = System.getProperty(PROPERTY_FILE);
            _logger.info(StringUtils.SEPARATOR);
            _logger.info("AppProperties: " + propertyFile);

            PropertyFileParser parser = new PropertyFileParser(propertyFile);
            parser.run();
            _configurableItemMap = parser.getConfigurableItemMap();
        }
    }

    private String getProperty(String key) {
        String value = (String) _configurableItemMap.get(key);
        if (value == null)
            return null;
        if (value.compareToIgnoreCase("null") == 0)
            return null;
        return value;
    }

    public String getBuildDate() {
        if (_buildDate != null)
            return _buildDate;
        try {
        	_buildDate = getProperty(BUILD_INFO);
            if (_buildDate == null)
            	_buildDate = "null";
        } catch (Exception ex) {
        	_buildDate = ex.getMessage();
        }

        _logger.info("getBuildDate returns " + _buildDate);
        return _buildDate;
    }

    public String getAppVersion() {
        if (_appVersion != null)
            return _appVersion;
        try {
        	_appVersion = getProperty(APP_VERSION);
            if (_appVersion == null)
            	_appVersion = "N/A";
        } catch (Exception ex) {
        	_appVersion = ex.getMessage();
        }

        _logger.info("getAppVersion returns " + _appVersion);
        return _appVersion;
    }

    public String getAnthillBuildTagBuilt() {
        if (_buildTag != null)
            return _buildTag;
        try {
        	_buildTag = getProperty(ANTHILL_BUILD_TAG_BUILT);
            if (_buildTag == null)
            	_buildTag = "trunk";
        } catch (Exception ex) {
        	_buildTag = ex.getMessage();
        }

        _logger.info("getAnthillBuildTagBuilt returns " + _buildTag);
        return _buildTag;
    }

    public boolean isDebugOn() {
        return Boolean.parseBoolean(getProperty(DEBUG_ON));
    }

    public boolean isSendEmail() {
        //if (true) return true;
        return Boolean.parseBoolean(getProperty(SEND_EMAIL));
    }

    public String getContactUrl() {
        return getProperty(NCICB_CONTACT_URL);
    }

    public String[] getContactUsRecipients() {
        String value = getContactUrl();
        return StringUtils.toStrings(value, ";", false);
    }

    public String getMailSmtpServer() {
        return getProperty(MAIL_SMTP_SERVER);
    }

    private ArrayList<VocabInfo> parseVocabList(String prefix, int max,
        boolean appendOthers) {
        ArrayList<VocabInfo> list = new ArrayList<VocabInfo>();
        for (int i=0; i<max; ++i) {
            String value = getProperty(prefix + i);
            VocabInfo vocab = VocabInfo.parse(value);
            if (vocab != null)
                list.add(vocab);
        }
        if (appendOthers) {
            VocabInfo info = new VocabInfo("Other");
            info.addEmail(getProperty(VOCABULARY_OTHER_EMAIL));
            list.add(info);
        }
        return list;
    }

    public ArrayList<VocabInfo> getVocabularies(Prop.Version version) {
        if (version == Prop.Version.CDISC)
            return getVocabulariesCDISC();
        return getVocabulariesDefault();
    }

    private ArrayList<VocabInfo> getVocabulariesDefault() {
        if (_defaultVocabList == null) {
            _defaultVocabList = parseVocabList(VOCABULARY_PREFIX,
                VOCABULARY_MAX, true);
            VocabInfo.debug(_defaultVocabList);
        }
        return _defaultVocabList;
    }

    private ArrayList<VocabInfo> getVocabulariesCDISC() {
        if (_cdiscVocabList == null) {
            _cdiscVocabList = parseVocabList(CDISC_VOCABULARY_PREFIX,
                CDISC_VOCABULARY_MAX, false);
            VocabInfo.debug(_cdiscVocabList);
        }
        return _cdiscVocabList;
    }

    public String[] getVocabularyNames(Prop.Version version) {
        ArrayList<VocabInfo> list = getVocabularies(version);
        Iterator<VocabInfo> iterator = list.iterator();
        ArrayList<String> names = new ArrayList<String>();
        while (iterator.hasNext()) {
            VocabInfo info = iterator.next();
            names.add(info.getName());
        }
        return names.toArray(new String[names.size()]);
    }

    public String getVocabularyName(Prop.Version version, String url) {
        ArrayList<VocabInfo> list = getVocabularies(version);
        Iterator<VocabInfo> iterator = list.iterator();
        while (iterator.hasNext()) {
            VocabInfo info = iterator.next();
            if (info.getUrl().equals(url))
                return info.getDisplayName();
        }
        return null;
    }

    public String[] getVocabularyEmails(Prop.Version version,
        String vocabularyName) {
        ArrayList<VocabInfo> list = getVocabularies(version);
        Iterator<VocabInfo> iterator = list.iterator();
        while (iterator.hasNext()) {
            VocabInfo info = iterator.next();
            if (info.getName().equals(vocabularyName) ||
                info.getDisplayName().equals(vocabularyName)) {
                ArrayList<String> emails = info.getEmails();
                return emails.toArray(new String[emails.size()]);
            }
        }
        return new String[0];
    }

    public String getVocabularyEmailsString(Prop.Version version,
        String vocabularyName) {
        String[] emails = getVocabularyEmails(version, vocabularyName);
        return StringUtils.toString(emails, ";");
    }

    public String[] getList(String propertyName, String[] list, String debugText) {
        if (list != null)
            return list;
        String value = getProperty(propertyName);
        list = StringUtils.toStrings(value, ";", false);
        if (debugText != null)
            ListUtils.debug(_logger, debugText, list);
        return list;
    }

/*
    public String getSources() {
        return getProperty(CADSR_SOURCES);
    }

    public String[] getCADSREmail() {
        if (_cadsrEmail != null)
            return _cadsrEmail;

        String value = getProperty(CADSR_EMAIL);
        String[] list = StringUtils.toStrings(value, ";", false);
        return _cadsrEmail = list;
    }

    public String getCADSREmailString() {
        return getProperty(CADSR_EMAIL);
    }

    public String[] getCADSRSourceList() {
        return _cadsrSourceList = getList(
            CADSR_SOURCES, _cadsrSourceList, "_cadsrSourceList");
    }

    public String getCADSRTypes() {
        return getProperty(CADSR_TYPES);
    }

    public String[] getCADSRTypeList() {
        return _cadsrTypeList = getList(
            CADSR_TYPES, _cadsrTypeList, "_cadsrTypeList");
    }

    public String[] getCDISCEmail() {
        if (_cdiscEmail != null)
            return _cdiscEmail;

        String value = getProperty(CDISC_EMAIL);
        String[] list = StringUtils.toStrings(value, ";", false);
        return _cdiscEmail = list;
    }

    public String getCDISCRequestTypes() {
        return getProperty(CDISC_REQUEST_TYPES);
    }

    public String[] getCDISCRequestTypeList() {
        return _cdiscRequestTypeList = getList(
            CDISC_REQUEST_TYPES, _cdiscRequestTypeList, "_cdiscRequestTypeList");
    }

    public String getCDISCCodes() {
        return getProperty(CDISC_CODES);
    }

    public String[] getCDISCCodeList() {
        return _cdiscCodeList = getList(
            CDISC_CODES, _cdiscCodeList, "_cdiscCodeList");
    }

    public ArrayList<QuickLinkInfo> getCDISCQuickLinks() {
        if (_cdiscQuickLinkList == null) {
            String value = getProperty(CDISC_QUICKLINKS);
            _cdiscQuickLinkList = QuickLinkInfo.parse(value);
        }
        return _cdiscQuickLinkList;
    }
    */
}


text:
param (
[parameter(Mandatory = $true, HelpMessage="Edge Gateway Name")][alias("-edge","e")][ValidateNotNullOrEmpty()][string[]]$egwname,
[parameter(Mandatory = $true, HelpMessage="CSV Path")][alias("-file","f")][ValidateNotNullOrEmpty()][string]$csvFile
)

#Search EdgeGW
try {
$edgeView = Search-Cloud -QueryType EdgeGateway -Name $egwname -ErrorAction Stop | Get-CIView
} catch {
[System.Windows.Forms.MessageBox]::Show("Exception: " + $_.Exception.Message + " - Failed item:" + $_.Exception.ItemName ,"Error.",0,[System.Windows.Forms.MessageBoxIcon]::Exclamation)
Write-Warning "Edge Gateway with name $Edgeview not found"
Exit
}

$webclient = New-Object system.net.webclient
$webclient.Headers.Add("x-vcloud-authorization",$Edgeview.Client.SessionKey)
$webclient.Headers.Add("accept",$EdgeView.Type + ";version=5.5")
[XML]$EGWConfXML = $webclient.DownloadString($EdgeView.href)
$FWRules = $EGWConfXML.EdgeGateway.Configuration.EdgegatewayServiceConfiguration.FirewallService.FirewallRule
$Rules = @()
if ($FWRules){
$FWRules | ForEach-Object {

If ($_.Protocols.udp -And $_.Protocols.tcp) {$protocol = "tcpudp" }
elseif ($_.Protocols.udp) {$protocol = "udp"}
elseif ($_.Protocols.tcp) {$protocol = "tcp"}
elseif ($_.Protocols.any) {$protocol = "any"}
else{ $Protocol = "any"}

$NewRule = new-object PSObject -Property @{
Num = $_.ID;
Descr = $_.Description;
Proto = $Protocol;
SrcIP = $_.SourceIP;
SrcPort = $_.SourcePort;
DstIP = $_.DestinationIP;
DstPortRange = $_.DestinationPortRange;
Policy = $_.Policy;
Direction = "";
isEnabled = $_.IsEnabled;
EnableLogging = $_.EnableLogging;
MatchOnTranslate = $_.MatchOnTranslate;

}
$Rules += $NewRule
}
}

$Rules | Export-CSV -Path $csvFile -NoType


text:
import bg from 'gulp-bg';
import gulp from 'gulp';

// If this doesn't work, while manual Xcode works, try:
// 1) delete ios/build directory
// 2) reset content and settings in iOS simulator
gulp.task('ios', ['native'], bg(
  'react-native', 'run-ios', '--simulator', 'iPhone 5s'
));


text:
package net.novaviper.zeroquest.common.block;

import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.BlockBush;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.util.BlockPos;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumPlantType;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.novaviper.zeroquest.ZeroQuest;
import net.novaviper.zeroquest.client.particle.EntityDustFX;

public class BlockNileBlueFlower extends BlockBush{

	public BlockNileBlueFlower() {
		super();
		this.setCreativeTab(ZeroQuest.ZeroTab);
		this.setLightLevel(0.4F);
		this.setStepSound(soundTypeGrass);
	}

	@Override
    protected boolean canPlaceBlockOn(Block par1)
    {
        return par1 == Blocks.grass
        		|| par1 == Blocks.dirt
        		|| par1 == Blocks.farmland;
    }

    @SideOnly(Side.CLIENT)
    @Override
    public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, Random rand)
    {
        super.randomDisplayTick(worldIn, pos, state, rand);

        if (rand.nextInt(10) == 0)
        {
        	EntityDustFX entityFX = new EntityDustFX(worldIn, (double)((float)pos.getX() + rand.nextFloat()), (double)((float)pos.getY() + 1.1F), (double)((float)pos.getZ() + rand.nextFloat()), 0.0D, 0.0D, 0.0D);
        	FMLClientHandler.instance().getClient().effectRenderer.addEffect(entityFX);
    	}
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using RbtApiDriver;
using Robots;
using RobotMaster.Forms;

namespace RobotMaster
{
    public partial class MainForm : Form
    {
        #region Attributes

        private Robot presentRobot = null;
        private RobotPanel presentRobotPanel = null;

        #endregion

        public MainForm()
        {
            InitializeComponent();
            RbtApi.Connection.StateChanged += Connection_StateChanged;
            RbtApi.Connection.MessageSended += Connection_MessageSended;
            RbtApi.Connection.MessageReceived += Connection_MessageReceived;
            Robots.Sabueso.SabuesoRobot b = new Robots.Sabueso.SabuesoRobot();
        }

        #region Generic form events

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.loadTscbPortName();
            foreach (Robots.RobotIds r in Robots.Robot.GetRobotIds())
            {
                this.tscbRobot.Items.Add(r);
                ToolStripMenuItem miRobot = new ToolStripMenuItem(r.ToString());
                miRobot.Click += miRobot_Click;
                this.miRobots.DropDownItems.Add(miRobot);
            }
            this.tscbRobot.SelectedIndex = 0;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.presentRobotPanel != null)
                this.presentRobotPanel.Close();
            RbtApi.Connection.Disconnect();
        }

        private void pContainer_Resize(object sender, EventArgs e)
        {
            this.adjustRobotPanel();
        }

        private void bClear_Click(object sender, EventArgs e)
        {
            this.tbLog.Text = "";
        }

        #endregion

        #region Main menu events

        private void miExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void mConnection_DropDownOpening(object sender, EventArgs e)
        {
            foreach (ToolStripMenuItem menuItem in this.miPortNames.DropDownItems)
                menuItem.Click -= miPortName_Click;
            this.miPortNames.DropDownItems.Clear();
            foreach (String portName in RbtApi.GetPortNames())
            {
                ToolStripMenuItem miPortName = new ToolStripMenuItem(portName);
                if (portName == RbtApi.Connection.PortName)
                    miPortName.Checked = true;
                this.miPortNames.DropDownItems.Add(miPortName);
                miPortName.Click += miPortName_Click;
            }
        }

        void miPortName_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem miPortName = (ToolStripMenuItem)sender;
            RbtApi.Connection.PortName = miPortName.Text;
            this.tscbPortName.SelectedItem = miPortName.Text;
        }

        void miRobot_Click(object sender, EventArgs e)
        {
            RobotIds robotId = (RobotIds)Enum.Parse(typeof(RobotIds), ((ToolStripMenuItem)sender).Text);
            this.tscbRobot.SelectedItem = robotId;
        }

        void miConnect_Click(object sender, EventArgs e)
        {
            this.connect();
        }

        private void miDisconnect_Click(object sender, EventArgs e)
        {
            this.disconnect();
        }

        private void miAbout_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm();
            aboutForm.ShowDialog();
        }

        #endregion

        #region Tool bar events

        private void tsbConnect_Click(object sender, EventArgs e)
        {
            this.connect();
        }

        private void tsbDisconnect_Click(object sender, EventArgs e)
        {
            this.disconnect();
        }

        private void tscbPortName_DropDown(object sender, EventArgs e)
        {
            this.loadTscbPortName();
        }

        private void tscbPortName_SelectedIndexChanged(object sender, EventArgs e)
        {
            RbtApi.Connection.PortName = this.tscbPortName.SelectedItem.ToString();
        }

        private void tscbRobot_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ToolStripMenuItem item in this.miRobots.DropDownItems)
                if (item.Text == this.tscbRobot.SelectedItem.ToString())
                    item.Checked = true;
                else
                    item.Checked = false;
        }

        #endregion

        #region Scroll bar Events

        private void verticalScroll_Scroll(object sender, ScrollEventArgs e)
        {
            int yLocation = ((this.pContainer.Height - this.presentRobotPanel.Height) * this.verticalScroll.Value) / this.verticalScroll.Maximum;
            this.presentRobotPanel.Location = new Point(this.presentRobotPanel.Location.X, yLocation);
        }

        private void horizontalScroll_Scroll(object sender, ScrollEventArgs e)
        {
            int xLocation = (this.pContainer.Width - this.presentRobotPanel.Width) * this.horizontalScroll.Value / this.horizontalScroll.Maximum;
            this.presentRobotPanel.Location = new Point(xLocation, this.presentRobotPanel.Location.Y);
        }

        #endregion

        #region Connection events

        void Connection_StateChanged(object sender, EventArgs e)
        {
            if (RbtApi.Connection.Connected)
            {
                this.slConnection.Text = "Connected";
                this.tscbPortName.Enabled = this.miPortNames.Enabled = false;
                this.tsbConnect.Enabled = this.miConnect.Enabled = false;
                this.tsbDisconnect.Enabled = this.miDisconnect.Enabled = true;
                this.tscbRobot.Enabled = false;
                foreach (ToolStripMenuItem miRobot in this.miRobots.DropDownItems)
                    miRobot.Enabled = false;
            }
            else
            {
                this.slConnection.Text = "Disconnected";
                this.tscbPortName.Enabled = this.miPortNames.Enabled = true;
                this.tsbConnect.Enabled = this.miConnect.Enabled = true;
                this.tsbDisconnect.Enabled = this.miDisconnect.Enabled = false;
                this.tscbRobot.Enabled = true;
                foreach (ToolStripMenuItem miRobot in this.miRobots.DropDownItems)
                    miRobot.Enabled = true;
            }
        }

        void Connection_MessageSended(object sender, RbtApiEventArgs args)
        {
            this.BeginInvoke(new RbtApiEventHandler(this.printLog), new object[] { sender, args });
        }

        void Connection_MessageReceived(object sender, RbtApiEventArgs args)
        {
            this.BeginInvoke(new RbtApiEventHandler(this.printLog), new object[] { sender, args });
        }

        #endregion

        #region Private methods

        private void loadTscbPortName()
        {
            this.tscbPortName.Items.Clear();
            foreach (String portName in RbtApi.GetPortNames())
            {
                this.tscbPortName.Items.Add(portName);
                if (RbtApi.Connection.PortName == portName)
                    this.tscbPortName.SelectedItem = portName;
            }
        }

        private void connect()
        {
            byte id;
            try
            {
                id = RbtApi.Connection.Connect();
            }
            catch (RbtApiException e)
            {
                this.disconnect();
                MessageBox.Show(e.Message, "Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (!Robot.CheckRobotId(id))
            {
                this.disconnect();
                MessageBox.Show("Robot id received do not exist", "Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            RobotIds robotId = (RobotIds)id;
            if (robotId != (RobotIds)this.tscbRobot.SelectedItem)
            {
                if (DialogResult.No == MessageBox.Show("Detected robot is different than selected. Do you want to continue with detected robot?\r\n\tRobot selected: " + this.tscbRobot.SelectedItem + "\r\n\tRobot detected: " + robotId, "Connect", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    this.disconnect();
                    return;
                }
                else
                    this.tscbRobot.SelectedItem = robotId;
            }
            this.presentRobot = Robot.GetRobot((RobotIds)id);
            this.presentRobotPanel = RobotPanel.GetRobotPanel(this.presentRobot);
            this.presentRobotPanel.Location = new Point(0, 0);
            this.pContainer.Controls.Add(this.presentRobotPanel);
            this.adjustRobotPanel();
        }

        private void disconnect()
        {
            RbtApi.Connection.Disconnect();
            this.presentRobot = null;
            this.pContainer.Controls.Remove(this.presentRobotPanel);
            this.presentRobotPanel = null;
        }

        private void printLog(object sender, RbtApiEventArgs args)
        {
            if ((args.Packet is RbtApiEvent) && !this.chShowEvents.Checked)
                return;
            if (this.tbLog.Text != "")
                this.tbLog.AppendText("\r\n");
            this.tbLog.AppendText(args.DateTime.Hour.ToString("00") + ":" + args.DateTime.Minute.ToString("00") + ":" + args.DateTime.Second.ToString("00") + "." + args.DateTime.Millisecond.ToString("000"));
            this.tbLog.SelectionFont = new Font(tbLog.Font, FontStyle.Bold);
            if (args.Packet is RbtApiCommand)
                this.tbLog.AppendText(" TX >> ");
            else
                this.tbLog.AppendText(" RX << ");
            this.tbLog.SelectionFont = new Font(tbLog.Font, FontStyle.Regular);
            this.tbLog.AppendText(args.Packet.ToString());
            this.tbLog.ScrollToCaret();
        }

        private void adjustRobotPanel()
        {
            if (this.presentRobotPanel != null)
            {
                int xLocation = 0;
                if (this.pContainer.Width > this.presentRobotPanel.Width)
                {
                    xLocation = (this.pContainer.Width - this.presentRobotPanel.Width) / 2;
                    this.horizontalScroll.Enabled = false;
                }
                else
                {
                    xLocation = (this.pContainer.Width - this.presentRobotPanel.Width) * this.horizontalScroll.Value / this.horizontalScroll.Maximum;
                    this.horizontalScroll.Maximum = ((this.presentRobotPanel.Width - this.pContainer.Width) / 100) + 1;
                    this.horizontalScroll.Enabled = true;
                }
                if (this.pContainer.Height > this.presentRobotPanel.Height)
                    this.verticalScroll.Enabled = false;
                else
                {
                    this.verticalScroll.Maximum = ((this.presentRobotPanel.Height - this.pContainer.Height) / 100) + 1;
                    this.verticalScroll.Enabled = true;
                }
                int yLocation = 0;
                if (this.verticalScroll.Enabled)
                    yLocation = (this.pContainer.Height - this.presentRobotPanel.Height) * this.verticalScroll.Value / this.verticalScroll.Maximum;
                this.presentRobotPanel.Location = new Point(xLocation, yLocation);
            }
        }

        #endregion

    }
}


text:
<?php

namespace Concrete\Core\User\Exception;

/**
 * An interface implemented by all "User" exceptions
 */
interface UserException
{

}


text:
ofxQt
=====================================

Introduction
------------

License
-------
[MIT License](https://en.wikipedia.org/wiki/MIT_License)

Installation
------------

- Install Qt, let it fall at the default folder (c:\Qt)
- In VS, extensions: install Qt VS Tool.

### How to turn an PG generated project to a Qt project (Visual Studio):
- Run Project generator and add Qt addon.
- open .vcxproj file and modify the tag:

>     <PropertyGroup Label="Globals">
>     <Keyword>Win32Proj</Keyword>

to :

>     <PropertyGroup Label="Globals">
>     <Keyword>Qt4VSv1.0</Keyword>

- Right click on project, Convert to Qt VS Tool project
- Select project properties/C++/General and add:

> $(QTDIR)\include\;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGui;$(QTDIR)\include\QtOpenGL;$(QTDIR)\include\QtUiTools;$(QTDIR)\include\QtWidgets;.\GeneratedFiles;..\src\;

- Right click on project\properties\Linker and add:

**General\Additional Library Directories:**
> $(QTDIR)\lib

**Input\Additional dependencies:Debug:**
> Qt5Cored.lib;Qt5Guid.lib;Qt5OpenGLd.lib;opengl32.lib;glu32.lib;Qt5UiToolsd.lib;Qt5Widgetsd.lib;%(AdditionalDependencies)

**Release:**
> Qt5Core.lib;Qt5Gui.lib;Qt5OpenGL.lib;opengl32.lib;glu32.lib;Qt5UiTools.lib;Qt5Widgets.lib;%(AdditionalDependencies)

- If you get linker errors its because Qt VS extension is not really good. Try deleting all generated files, both in the phisical HD and in the VS project. Also the following folders.

>     bin\
>     obj\
>     GeneratedFiles\

Also remove the .ui files from the project and add them again, this must add a custom pre build step runner by Qt compiler. It turns ObjectName.ui files to ui_ObjectName.h files. Then build again. Good "luck"!

Dependencies
------------
- Qt
- ofxGUI (examples only)

Compatibility
------------

Known issues
------------

Version history
------------

Screenshots
------------
![Image of Of_inside_Qt](https://github.com/jordiexvision/ofxQt/blob/master/screenshots/Of_inside_Qt.png)

![Image of ofAppQtWindow](https://github.com/jordiexvision/ofxQt/blob/master/screenshots/ofAppQtWindow.png)


text:
module UseCases
  module Argument
    class GetQuestionArgument < ArgumentUseCase

      def call
        raise "Please provide at least one user" if request.user_ids.empty?
        Response.new(argument: build_argument(request.question_id, request.user_ids))
      end

      private

      def build_argument(question_id, user_ids)
        argument_builder(question_id, user_ids).conclusion_level_argument
      end

    end
  end
end


text:
#include <stdlib.h>
#include <string.h>
#ifndef _RTT
#include <stdio.h>
#endif

#ifdef unix
#include <unistd.h>
#endif
#include <assert.h>

#include "simapi.h"
#include "portable.h"

#include "../clib/fpi_tgt.inl"

static const char utt_basi[] = "$Id: utt_basi.c,v 1.6.6.8 2007/10/15 18:06:24 dahan Exp $";

CA_Utterance *CA_AllocateUtterance(void)
{
  CA_Utterance *hUtt = NULL;
  TRY_CA_EXCEPT

  hUtt = (CA_Utterance *) CALLOC_CLR(1, sizeof(CA_Utterance), "ca.hUtt");
  hUtt->ca_rtti = CA_UTTERANCE_SIGNATURE;
  return (hUtt);

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_FreeUtterance(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);

  FREE((char *) hUtt);
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

int CA_InitUtteranceForFrontend(CA_Utterance *hUtt,
                                CA_FrontendInputParams *hFrontPar)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  ASSERT(hFrontPar > 0);
  if (hUtt->data.utt_type != 0)
    SERVICE_ERROR(UTTERANCE_ALREADY_INITIALISED);

  init_utterance(&hUtt->data, LIVE_INPUT, 3*hFrontPar->mel_dim,  /* TODO: change to proper function */
                 DEFAULT_BUFFER_SIZE, KEEP_FRAMES,
                 hFrontPar->mel_dim, 1);
  if (hFrontPar->do_skip_even_frames)
    set_voicing_durations(&hUtt->data, hFrontPar->voice_duration / 2,
                          hFrontPar->quiet_duration / 2,
                          hFrontPar->unsure_duration / 2,
                          hFrontPar->start_windback / 2);
  else
    set_voicing_durations(&hUtt->data, hFrontPar->voice_duration,
                          hFrontPar->quiet_duration,
                          hFrontPar->unsure_duration,
                          hFrontPar->start_windback);
  return (0);

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)

}

void CA_ClearUtterance(CA_Utterance *hUtt)
{

  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type == 0)
  {
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);
  }

  if (hUtt->data.utt_type == LIVE_INPUT)
  {
    free_utterance(&hUtt->data);
    hUtt->data.utt_type = 0;
  }
  else
  {
    SERVICE_ERROR(UTTERANCE_UNKNOWN);
  }
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

int CA_AdvanceUtteranceFrame(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  int status_code;

  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  status_code = advance_utterance_frame(&hUtt->data);
  return (status_code);

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

int CA_UtteranceHasVoicing(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  return (hUtt->data.gen_utt.frame->voicingDetected);

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_UnlockUtteranceForInput(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);
  ASSERT(!isFrameBufferActive(hUtt->data.gen_utt.frame));
  startFrameCollection(hUtt->data.gen_utt.frame);
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_LockUtteranceFromInput(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);
  ASSERT(isFrameBufferActive(hUtt->data.gen_utt.frame));

  stopFrameCollection(hUtt->data.gen_utt.frame);
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_ResetVoicing(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  clearEndOfUtterance(hUtt->data.gen_utt.frame);
  clearC0Entries(hUtt->data.gen_utt.frame);
  startFrameCollection(hUtt->data.gen_utt.frame);
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_FlushUtteranceFrames(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  setRECframePtr(hUtt->data.gen_utt.frame, 0, 0);
  releaseBlockedFramesInBuffer(hUtt->data.gen_utt.frame);
  hUtt->data.gen_utt.last_push = NULL;
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

void CA_SetEndOfUtteranceByLevelTimeout(CA_Utterance *hUtt, long timeout, long holdOff)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  setupEndOfUtterance(hUtt->data.gen_utt.frame, timeout, holdOff);
  return;

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}

int CA_UtteranceHasEnded(CA_Utterance *hUtt)
{
  TRY_CA_EXCEPT
  ASSERT(hUtt);
  if (hUtt->data.utt_type != LIVE_INPUT)
    SERVICE_ERROR(UTTERANCE_NOT_INITIALISED);

  return (utterance_ended(&hUtt->data));

  BEG_CATCH_CA_EXCEPT
  END_CATCH_CA_EXCEPT(hUtt)
}


text:
package com.android.tools.idea.designer;

import com.intellij.designer.model.MetaModel;
import com.intellij.designer.model.VariationPaletteItem;
import com.intellij.designer.palette.PaletteItem;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;

public class AndroidVariationPaletteItem extends VariationPaletteItem {
  private ResizePolicy myResizePolicy;
  private FillPolicy myFillPolicy;

  public AndroidVariationPaletteItem(PaletteItem defaultItem, MetaModel model, Element element) {
    super(defaultItem, model, element);

    String resize = element.getAttributeValue(AndroidMetaModel.ATTR_RESIZE);
    if (resize != null) {
      myResizePolicy = ResizePolicy.get(resize);
    }

    String fill = element.getAttributeValue(AndroidMetaModel.ATTR_FILL);
    if (fill != null) {
      myFillPolicy = FillPolicy.get(fill);
    }
  }

  @Nullable
  public ResizePolicy getResizePolicy() {
    return myResizePolicy;
  }

  public FillPolicy getFillPolicy() {
    return myFillPolicy;
  }
}


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

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Geta.VippyWrapper")]
[assembly: AssemblyDescription("This is a .NET wrapper around Vippy's public REST API. This wrapper contains all the public endpoints available at: http://vippy.co/developers/rest.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Geta AS")]
[assembly: AssemblyProduct("Geta.VippyWrapper")]
[assembly: AssemblyCopyright("Copyright © Geta AS 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0ca70e9d-942f-4318-9aa0-54a42d3c71fd")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
from django.db import models
from django.db.models.signals import post_init
import reversion
from django.contrib.auth.models import User

from mptt.models import MPTTModel, TreeForeignKey
from pint import UnitRegistry, UndefinedUnitError

@reversion.register()
class ItemType(MPTTModel):
    """
    Provides a tree based model of types, each which can have parents/children
    """
    name = models.CharField(max_length=150, unique=True, db_index=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class Meta:
        permissions = (
            ('view_itemtype', 'View item type',),
        )

    def has_children(self):
        return True if self.get_descendant_count() > 0 else False

    def display_name(self):
        if self.level > 0:
            return '{} {}'.format('\u00a0\u00a0\u00a0' * self.level, self.name)
        return self.name

    def root(self):
        if self.parent:
            return self.parent.get_root().name
        return self.name

    def __str__(self):
        return self.name

@reversion.register()
class Tag(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

@reversion.register()
class AmountMeasure(models.Model):
    """
    A measurement and corrosponding postfix
    """
    name = models.CharField(max_length=100, unique=True, db_index=True)
    symbol = models.CharField(max_length=10, unique=True, db_index=True)

    class Meta:
        ordering = ['-id']
        permissions = (
            ('view_amountmeasure', 'View measure',),
        )

    def __str__(self):
        return "{} ({})".format(self.name, self.symbol)

@reversion.register()
class Location(MPTTModel):
    """
    Provides a physical location for an item
    """
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=12, unique=True, null=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class Meta:
        ordering = ['tree_id', '-lft']
        permissions = (
            ('view_location', 'View location',),
        )

    def has_children(self):
        return True if self.get_descendant_count() > 0 else False

    def display_name(self):
        if self.level > 0:
            return '{} {} ({})'.format('\u00a0\u00a0\u00a0' * self.level, self.name, self.code)
        return '{} ({})'.format(self.name, self.code)

    def __str__(self):
        if self.parent:
            return '{} ({})'.format(self.name, self.parent.name)
        return self.name

@reversion.register()
class Set(models.Model):
    """
    A named set of items in the inventory
    """
    name = models.CharField(max_length=40)
    is_public = models.BooleanField(default=False)
    is_partset = models.BooleanField(default=False)

    class Meta:
        ordering = ['-id']
        permissions = (
            ('view_set', 'View item set',),
        )

    def number_of_items(self):
        return self.items.count()

    def __str__(self):
        return self.name

@reversion.register()
class Item(models.Model):
    """
    Represents an item in a inventory
    """
    name = models.CharField(max_length=200, db_index=True)
    identifier = models.CharField(max_length=200, null=True, blank=True, db_index=True)
    barcode = models.CharField(max_length=128, null=True, blank=True, db_index=True, unique=True)
    description = models.TextField(blank=True, null=True)
    item_type = TreeForeignKey(ItemType)

    tags = models.ManyToManyField(Tag, blank=True)

    in_inventory = models.BooleanField(default=False)
    amount_available = models.FloatField(default=0)
    amount_measure = models.ForeignKey(AmountMeasure)
    concentration = models.FloatField(default=0)
    concentration_measure = models.ForeignKey(AmountMeasure,
                                              blank=True, null=True,
                                              related_name='concentration_measure')
    location = TreeForeignKey(Location)

    # Add an optional "wells" for recording the number of items that can fit on it, if any
    wells = models.IntegerField(default=0)

    added_by = models.ForeignKey(User)
    added_on = models.DateTimeField(auto_now_add=True)
    last_updated_on = models.DateTimeField(auto_now=True)

    sets = models.ManyToManyField(Set, related_name='items', blank=True)

    created_from = models.ManyToManyField('self', blank=True, symmetrical=False)

    class Meta:
        ordering = ['-id']
        permissions = (
            ('view_item', 'View item',),
        )

    def get_tags(self):
        return ", ".join([t.name for t in self.tags.all()])

    def location_path(self):
        return ' > '.join([x.name for x in self.location.get_ancestors(include_self=True)])

    def save(self, *args, **kwargs):
        if self.amount_available > 0:
            self.in_inventory = True
        super(Item, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

@reversion.register()
class ItemProperty(models.Model):
    """
    Represents a singular user defined property of an item
    """
    item = models.ForeignKey(Item, related_name='properties')
    name = models.CharField(max_length=200, db_index=True)
    value = models.TextField(db_index=True)

    def __str__(self):
        return self.name

@reversion.register()
class ItemTransfer(models.Model):
    """
    Represents an amount of item in transfer for task
    """
    item = models.ForeignKey(Item, related_name='transfers')
    # The amount originally taken from the inventory
    amount_taken = models.FloatField(default=0)
    # The amount now available in this transfer
    amount_available = models.FloatField(default=0)
    # The amount to take from this transfer (set initially as amount_taken)
    amount_to_take = models.FloatField(default=0)
    amount_measure = models.ForeignKey(AmountMeasure)
    run_identifier = models.UUIDField(blank=True, null=True, db_index=True)
    barcode = models.CharField(max_length=20, blank=True, null=True, db_index=True)
    coordinates = models.CharField(max_length=2, blank=True, null=True)

    # Link the current transfer to a another ItemTransfer e.g. a plate
    # Can then use this to construct a "plate view"
    linked_transfer = models.ForeignKey('self', blank=True, null=True)

    # Location -> not yet implemented
    # location = models.ForeignKey(Location, default=get_default_location)

    date_created = models.DateTimeField(auto_now_add=True)

    # You're adding not taking away
    is_addition = models.BooleanField(default=False)

    # The transfer has taken out from the inventory; It might not yet be finished
    # so we need a way of knowing if we should take stuff out or not
    has_taken = models.BooleanField(default=False, db_index=True)

    # The transfer has completed and there is nothing left, this is now just
    # a history entry
    transfer_complete = models.BooleanField(default=False, db_index=True)

    class Meta:
        ordering = ['-date_created']

    def item_name(self):
        return self.item.name

    def save(self, *args, **kwargs):
        # Match some fields
        if self.pk is None:
            if self.amount_available == 0:
                self.amount_available = self.amount_taken
            self.amount_to_take = self.amount_taken
        # Link to an existing ItemTransfer with the given barcode
        if self.barcode:
            try:
                linked = ItemTransfer.objects.get(barcode=self.barcode, transfer_complete=False)
            except:
                pass
            else:
                self.linked_transfer = linked
        super(ItemTransfer, self).save(*args, **kwargs)

    def _as_measured_value(self, amount, measure, ureg):
        """
        Convert if possible to a value with units
        """
        try:
            value = amount * ureg(measure)
        except UndefinedUnitError:
            value = amount * ureg.count
        return value

    def check_transfer(self):
        ureg = UnitRegistry()
        existing = self._as_measured_value(self.item.amount_available,
                                           self.item.amount_measure.symbol,
                                           ureg)
        to_take = self._as_measured_value(self.amount_taken,
                                          self.amount_measure.symbol,
                                          ureg)
        if not self.is_addition and existing < to_take:
            missing = ((existing - to_take) * -1)
            return (False, missing)
        return (True, 0)

    def do_transfer(self, ureg=False):
        """
        Alter the item to reflect new amount
        """
        if not ureg:
            ureg = UnitRegistry()
        # Check if it is taking stuff from inventory or not
        # Note: if something has been taken you cannot put it
        # back
        if not self.has_taken:
            existing = self._as_measured_value(self.item.amount_available,
                                               self.item.amount_measure.symbol,
                                               ureg)
            to_take = self._as_measured_value(self.amount_taken,
                                              self.amount_measure.symbol,
                                              ureg)
            if self.is_addition:
                new_amount = existing + to_take
            else:
                if existing > to_take:
                    new_amount = existing - to_take
                else:
                    return False
            self.item.amount_available = new_amount.magnitude
            self.item.save()
            self.amount_available = self.amount_available - to_take.magnitude
        else:
            # We take from the transfer not the actual item since we've
            # already got it from the item
            existing = self._as_measured_value(self.amount_available,
                                               self.amount_measure.symbol,
                                               ureg)
            to_take = self._as_measured_value(self.amount_to_take,
                                              self.amount_measure.symbol,
                                              ureg)
            if self.is_addition:
                new_amount = existing + to_take
            else:
                if existing > to_take:
                    new_amount = existing - to_take
                else:
                    return False
            self.amount_available = new_amount.magnitude
        self.save()
        return True

    def do_complete(self, ureg=False):
        """
        Check if there is anything left available, if not complete.
        """
        if self.amount_available == 0:
            self.transfer_complete = True
        self.has_taken = True
        self.save()

    def __str__(self):
        return '{} {}/{}'.format(self.item.name, self.barcode, self.coordinates)

def initItemTransfer(**kwargs):
    """
    Extra init stuff for creating ItemTransfers
    """
    instance = kwargs.get('instance')
    # Convience, these are identical values at creation
    if instance.pk is None:
        instance.amount_available = instance.amount_taken
        instance.amount_to_take = instance.amount_taken
post_init.connect(initItemTransfer, ItemTransfer)


text:
  <form id="{{formId()}}">

      問題の形式を選択して下さい

      問題形式
      <select id="question_type_{{random}}" class="browser-default" name="question_type"
              (change)="chengeType($event.target.value)"
              [(ngModel)]="question.type">
        <option value disabled selected>追加する問題の形式を選択して下さい</option>
        <option *ngFor="let type of questionAttributeTypes" value="{{type.value}}">{{type.name}}</option>
      </select>

      初期難易度
      <input id="difficulty_area_{{random}}"
                type="text"
                class="difficulty_area"
                name="difficulty"
                [(ngModel)]="question.difficulty"/>

      問題文

        R
        G
        B

          Link:
          <input data-wysihtml5-dialog-field="href" value="http://" class="text">
          OK Cancel

          Image:
          <input type="file" (change)="fileEvent($event)" />
          <button
            onclick="return false;"
            (click)="uploadfile(f)">Upload file!</button>

      <textarea id="{{editorId()}}"
              class="issue-editor issue_area" name="text"
              [(ngModel)]="question.text"
      ></textarea>

      Hint
      <textarea id="hint_area_{{random}}" class="hint_area" name="hint"
                [(ngModel)]="question.hint"></textarea>

      解説文
      <textarea id="explanation_area_{{random}}" class="explanation_area" name="explanation"
                [(ngModel)]="question.explanation"></textarea>

        <button class="waves-effect green add-question waves-light btn"
                type="submit"
                *ngSwitchCase="true"
        >
          追加
        </button>

      <button class="waves-effect green add-question waves-light btn"
              type="submit"
              *ngSwitchDefault
      >
        更新
      </button>

回答と得点

          <answer-form [answer]="answer"></answer-form>

            選択肢を追加

出典

            <input
              type="text"
              id="reference_value" [(ngModel)]="reference.value" />

        <button class="waves-effect add-question waves-light blue btn"
                (click)="addReference()"
                onclick="return false;"
        >出典追加</button>

        <button class="waves-effect green add-question waves-light btn"
                type="submit"
                *ngSwitchCase="true"
        >
          追加
        </button>

      <button class="waves-effect green add-question waves-light btn"
              type="submit"
              *ngSwitchDefault
      >
        更新
      </button>

  </form>


text:
/*
 * role: logger controller
 * desc: used to control the logging framework
 */
(function (window) {
  'use strict';

  // define factory
  angular.module('common').factory('logger',
    ['$log', 'config', logger]);

  // create factory
  function logger($log) {
    var service = {
      forSource: forSource,
      log: log,
      logError: logError,
      logSuccess: logSuccess,
      logWarning: logWarning
    };

    return service;

    // #region public members
    function forSource(src) {
      return {
        log: function (m, d, s) { log(m, d, src, s); },
        logError: function (m, d, s) { logError(m, d, src, s); },
        logSuccess: function (m, d, s) { logSuccess(m, d, src, s); },
        logWarning: function (m, d, s) { logWarning(m, d, src, s); }
      };
    }

    function log(message, data, source, showNotification) {
      writeLog(message, data, source, showNotification, "info");
    }

    function logError(message, data, source, showNotification) {
      writeLog(message, data, source, showNotification, "error");
    }

    function logSuccess(message, data, source, showNotification) {
      writeLog(message, data, source, showNotification, "success");
    }

    function logWarning(message, data, source, showNotification) {
      writeLog(message, data, source, showNotification, "warning");
    }
    // #endregion

    // #region private members
    // universal method for writing notifications
    function writeLog(message, data, source, showNotification, notificationType) {
      showNotification = showNotification == null ? true : showNotification;

      // write to angular log, & specify error if it is an error
      var write = (notificationType === 'error') ? $log.error : $log.log;
      source = source ? '[' + source + '] ' : '';
      write(source, message, data);

      if (showNotification) {
        if (notificationType === 'error') {
          toastr.error(message);
        } else if (notificationType === 'warning') {
          toastr.warning(message);
        } else if (notificationType === 'success') {
          toastr.success(message);
        }

      }
    }
    // #endregion
  }
})(this);


text:
using System;
using Csla;
using Csla.Serialization;

namespace cslalighttest.ViewModelTests
{
  [Serializable]
  public class TestChild : BusinessBase<TestChild>
  {
    #region Business Methods

    // example with private backing field
    public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(p => p.Id);
    private int _Id = IdProperty.DefaultValue;
    public int Id
    {
      get { return GetProperty(IdProperty, _Id); }
      set { SetProperty(IdProperty, ref _Id, value); }
    }

    // example with managed backing field
    public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name);
    public string Name
    {
      get { return GetProperty(NameProperty); }
      set { SetProperty(NameProperty, value); }
    }

    #endregion

    #region Factory Methods

    internal static TestChild NewEditableChild()
    {
      return Csla.DataPortal.CreateChild<TestChild>();
    }

    internal static TestChild GetEditableChild(object childData)
    {
      return Csla.DataPortal.FetchChild<TestChild>(childData);
    }

    #endregion

    #region Data Access

    [RunLocal]
    protected override void Child_Create()
    {
      // omit this override if you have no defaults to set
      base.Child_Create();
    }

    [RunLocal]
    private void Child_Fetch(object childData)
    {
    }

    [RunLocal]
    private void Child_Insert(object parent)
    {
    }

    [RunLocal]
    private void Child_Update(object parent)
    {
    }

    [RunLocal]
    private void Child_DeleteSelf(object parent)
    {
    }

    #endregion
  }
}


text:
import React, { Component } from 'react';
import PubSub from 'pubsub-js';

export default class CustomSelect extends Component {
  constructor() {
    super();
    this.state = {
      errorMessage: ''
    };
  }

  componentDidMount() {
    PubSub.subscribe('input-error', (topic, error) => {
      if (error.field === this.props.name) {
        this.setState({ errorMessage: error.defaultMessage });
      }
    });
    PubSub.subscribe('input-error-clear', (topic, message) => {
      this.setState({ errorMessage: '' });
    });
  }

  render() {
    return (

        {this.props.label}
        <select id={this.props.id} name={this.props.name} value={this.props.value} onChange={this.props.onChange}>
          <option value="">Select one</option>
          {this.props.options.map(opt => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
        </select>
        {this.state.errorMessage}

    );
  }
}


text:
define([
    'underscore',
    'Magento_Ui/js/lib/collapsible'
], function (_, Collapsible) {
    'use strict';

    return Collapsible.extend({
        defaults: {
            listens: {
                '${ $.provider }:data.validate': 'onValidate'
            },
            collapsible: false,
            opened: true
        },

        /**
         * Invokes initElement method of parent class, calls 'initActivation' method
         * passing element to it.
         * @param {Object} elem
         * @returns {Object} - reference to instance
         */
        initElement: function (elem) {
            this._super()
                .initActivation(elem);

            return this;
        },

        /**
         * Activates element if one is first or if one has 'active' propert
         * set to true.
         *
         * @param  {Object} elem
         * @returns {Object} - reference to instance
         */
        initActivation: function (elem) {
            var elems   = this.elems(),
                isFirst = !elems.indexOf(elem);

            if (isFirst || elem.active()) {
                elem.activate();
            }

            return this;
        },

        /**
         * Delegates 'validate' method on element, then reads 'invalid' property
         * of params storage, and if defined, activates element, sets
         * 'allValid' property of instance to false and sets invalid's
         * 'focused' property to true.
         *
         * @param {Object} elem
         */
        validate: function (elem) {
            var result  = elem.delegate('validate'),
                invalid;

            invalid = _.find(result, function (item) {
                return !item.valid;
            });

            if (invalid) {
                elem.activate();
                invalid.target.focused(true);
            }

            return invalid;
        },

        /**
         * Sets 'allValid' property of instance to true, then calls 'validate' method
         * of instance for each element.
         */
        onValidate: function () {
            this.elems.sortBy(function (elem) {
                return !elem.active();
            }).some(this.validate, this);
        }
    });
});


text:
using System.Xml.Serialization;

using LinqToTwitter.Common;

using LitJson;

namespace LinqToTwitter
{
    /// <summary>
    /// Response from Twitter for previous and next pages
    /// </summary>
    /// <remarks>
    /// To use a cursor, start by setting the cursor to -1
    /// and then use one of these response cursors to move
    /// backwards or forwards in paged results.
    /// </remarks>
    public class Cursors
    {
        public Cursors() {}
        internal Cursors(JsonData cursors)
        {
            Next = cursors.GetValue<ulong>("next_cursor").ToString();
            Previous = cursors.GetValue<ulong>("previous_cursor").ToString();
        }

        /// <summary>
        /// Use this value to retrieve the next page
        /// </summary>
        [XmlIgnore]
        public string Next { get; internal set; }

        /// <summary>
        /// Use this value to go back to the previous page
        /// </summary>
        [XmlIgnore]
        public string Previous { get; internal set; }
    }
}


text:
package de.tor.tribes.ui.renderer;

import de.tor.tribes.types.ext.Village;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import org.jdesktop.swingx.renderer.DefaultTableRenderer;

/**
 *
 * @author Torridity
 */
public class VillageCellRenderer extends DefaultTableRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        JLabel label = (JLabel) c;
        Village vil = (Village) value;
        if (vil != null) {
            label.setText(vil.toString());
            label.setToolTipText(vil.getToolTipText());
        } else {
            label.setText("Unbekanntes Dorf");
            label.setToolTipText("Unbekanntes Dorf");
        }
        return label;
    }
}


text:
package com.qreal.web.model.diagram;

import javax.persistence.*;
import java.io.Serializable;

/**
 * Created by vladzx on 17.11.14.
 */
@Entity
@Table(name = "vertices")
public class LinkVertex implements Serializable {

    @Id
    @Column(name = "vertex_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long vertexId;

    @Column(name = "x")
    private double x;

    @Column(name = "y")
    private double y;

    @Column(name = "number")
    private int number;

    public double getX() {
        return x;
    }

    public void setX(double x) {
        this.x = x;
    }

    public double getY() {
        return y;
    }

    public void setY(double y) {
        this.y = y;
    }

    public Long getVertexId() {
        return vertexId;
    }

    public void setVertexId(Long vertexId) {
        this.vertexId = vertexId;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}


text:
require_relative 'globals'
require_relative 'tunes/tunes_client'

module Spaceship
  class Client
    def handle_two_step_or_factor(response)
      # extract `x-apple-id-session-id` and `scnt` from response, to be used by `update_request_headers`
      @x_apple_id_session_id = response["x-apple-id-session-id"]
      @scnt = response["scnt"]

      # get authentication options
      r = request(:get) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth")
        update_request_headers(req)
      end

      if r.body.kind_of?(Hash) && r.body["trustedDevices"].kind_of?(Array)
        handle_two_step(r)
      elsif r.body.kind_of?(Hash) && r.body["trustedPhoneNumbers"].kind_of?(Array) && r.body["trustedPhoneNumbers"].first.kind_of?(Hash)
        handle_two_factor(r)
      else
        raise "Although response from Apple indicated activated Two-step Verification or Two-factor Authentication, spaceship didn't know how to handle this response: #{r.body}"
      end
    end

    def handle_two_step(response)
      if response.body.fetch("securityCode", {})["tooManyCodesLock"].to_s.length > 0
        raise Tunes::Error.new, "Too many verification codes have been sent. Enter the last code you received, use one of your devices, or try again later."
      end

      puts("Two-step Verification (4 digits code) is enabled for account '#{self.user}'")
      puts("More information about Two-step Verification: https://support.apple.com/en-us/HT204152")
      puts("")

      puts("Please select a trusted device to verify your identity")
      available = response.body["trustedDevices"].collect do |current|
        "#{current['name']}\t#{current['modelName'] || 'SMS'}\t(#{current['id']})"
      end
      result = choose(*available)

      device_id = result.match(/.*\t.*\t\((.*)\)/)[1]
      handle_two_step_for_device(device_id)
    end

    # this is extracted into its own method so it can be called multiple times (see end)
    def handle_two_step_for_device(device_id)
      # Request token to device
      r = request(:put) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
        update_request_headers(req)
      end

      # we use `Spaceship::TunesClient.new.handle_itc_response`
      # since this might be from the Dev Portal, but for 2 step
      Spaceship::TunesClient.new.handle_itc_response(r.body)

      puts("Successfully requested notification")
      code = ask("Please enter the 4 digit code: ")
      puts("Requesting session...")

      # Send token to server to get a valid session
      r = request(:post) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/verify/device/#{device_id}/securitycode")
        req.headers['Content-Type'] = 'application/json'
        req.body = { "code" => code.to_s }.to_json
        update_request_headers(req)
      end

      begin
        Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
      rescue => ex
        # If the code was entered wrong
        # {
        #   "securityCode": {
        #     "code": "1234"
        #   },
        #   "securityCodeLocked": false,
        #   "recoveryKeyLocked": false,
        #   "recoveryKeySupported": true,
        #   "manageTrustedDevicesLinkName": "appleid.apple.com",
        #   "suppressResend": false,
        #   "authType": "hsa",
        #   "accountLocked": false,
        #   "validationErrors": [{
        #     "code": "-21669",
        #     "title": "Incorrect Verification Code",
        #     "message": "Incorrect verification code."
        #   }]
        # }
        if ex.to_s.include?("verification code") # to have a nicer output
          puts("Error: Incorrect verification code")
          return handle_two_step_for_device(device_id)
        end

        raise ex
      end

      store_session

      return true
    end

    def handle_two_factor(response, depth = 0)
      if depth == 0
        puts("Two-factor Authentication (6 digits code) is enabled for account '#{self.user}'")
        puts("More information about Two-factor Authentication: https://support.apple.com/en-us/HT204915")
        puts("")

        two_factor_url = "https://github.com/fastlane/fastlane/tree/master/spaceship#2-step-verification"
        puts("If you're running this in a non-interactive session (e.g. server or CI)")
        puts("check out #{two_factor_url}")
      end

      # "verification code" has already be pushed to devices

      security_code = response.body["securityCode"]
      # "securityCode": {
      # 	"length": 6,
      # 	"tooManyCodesSent": false,
      # 	"tooManyCodesValidated": false,
      # 	"securityCodeLocked": false
      # },
      code_length = security_code["length"]

      puts("")
      env_2fa_sms_default_phone_number = ENV["SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER"]

      if env_2fa_sms_default_phone_number
        raise Tunes::Error.new, "Environment variable SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER is set, but empty." if env_2fa_sms_default_phone_number.empty?

        puts("Environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` is set, automatically requesting 2FA token via SMS to that number")
        puts("SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER = #{env_2fa_sms_default_phone_number}")
        puts("")

        phone_number = env_2fa_sms_default_phone_number
        phone_id = phone_id_from_number(response.body["trustedPhoneNumbers"], phone_number)
        push_mode = push_mode_from_masked_number(response.body["trustedPhoneNumbers"], phone_number)
        # don't request sms if no trusted devices and env default is the only trusted number,
        # code was automatically sent
        should_request_code = !sms_automatically_sent(response)
        code_type = 'phone'
        body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, should_request_code)
      elsif sms_automatically_sent(response) # sms fallback, code was automatically sent
        fallback_number = response.body["trustedPhoneNumbers"].first
        phone_number = fallback_number["numberWithDialCode"]
        phone_id = fallback_number["id"]
        push_mode = fallback_number['pushMode']

        code_type = 'phone'
        body = request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode, false)
      elsif sms_fallback(response) # sms fallback but code wasn't sent bec > 1 phone number
        code_type = 'phone'
        body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
      else
        puts("(Input `sms` to escape this prompt and select a trusted phone number to send the code as a text message)")
        puts("")
        puts("(You can also set the environment variable `SPACESHIP_2FA_SMS_DEFAULT_PHONE_NUMBER` to automate this)")
        puts("(Read more at: https://github.com/fastlane/fastlane/blob/master/spaceship/docs/Authentication.md#auto-select-sms-via-spaceship_2fa_sms_default_phone_number)")
        puts("")

        code = ask_for_2fa_code("Please enter the #{code_length} digit code:")
        code_type = 'trusteddevice'
        body = { "securityCode" => { "code" => code.to_s } }.to_json

        # User exited by entering `sms` and wants to choose phone number for SMS
        if code == 'sms'
          code_type = 'phone'
          body = request_two_factor_code_from_phone_choose(response.body["trustedPhoneNumbers"], code_length)
        end
      end

      puts("Requesting session...")

      # Send "verification code" back to server to get a valid session
      r = request(:post) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/verify/#{code_type}/securitycode")
        req.headers['Content-Type'] = 'application/json'
        req.body = body
        update_request_headers(req)
      end

      begin
        # we use `Spaceship::TunesClient.new.handle_itc_response`
        # since this might be from the Dev Portal, but for 2 factor
        Spaceship::TunesClient.new.handle_itc_response(r.body) # this will fail if the code is invalid
      rescue => ex
        # If the code was entered wrong
        # {
        #   "service_errors": [{
        #     "code": "-21669",
        #     "title": "Incorrect Verification Code",
        #     "message": "Incorrect verification code."
        #   }],
        #   "hasError": true
        # }

        if ex.to_s.include?("verification code") # to have a nicer output
          puts("Error: Incorrect verification code")
          depth += 1
          return handle_two_factor(response, depth)
        end

        raise ex
      end

      store_session

      return true
    end

    # For reference in case auth behavior changes:
    # The "noTrustedDevices" field is only present
    # in the response for `GET /appleauth/auth`

    # Account is not signed into any devices that can display a verification code
    def sms_fallback(response)
      response.body["noTrustedDevices"]
    end

    # see `sms_fallback` + account has only one trusted number for receiving an sms
    def sms_automatically_sent(response)
      (response.body["trustedPhoneNumbers"] || []).count == 1 && sms_fallback(response)
    end

    # extracted into its own method for testing
    def ask_for_2fa_code(text)
      ask(text)
    end

    # extracted into its own method for testing
    def choose_phone_number(opts)
      choose(*opts)
    end

    def phone_id_from_number(phone_numbers, phone_number)
      characters_to_remove_from_phone_numbers = ' \-()"'

      # start with e.g. +49 162 1234585 or +1-123-456-7866
      phone_number = phone_number.tr(characters_to_remove_from_phone_numbers, '')
      # cleaned: +491621234585 or +11234567866

      phone_numbers.each do |phone|
        # rubocop:disable Style/AsciiComments
        # start with: +49 •••• •••••85 or +1 (•••) •••-••66
        number_with_dialcode_masked = phone['numberWithDialCode'].tr(characters_to_remove_from_phone_numbers, '')
        # cleaned: +49•••••••••85 or +1••••••••66
        # rubocop:enable Style/AsciiComments

        maskings_count = number_with_dialcode_masked.count('•') # => 9 or 8
        pattern = /^([0-9+]{2,4})([•]{#{maskings_count}})([0-9]{2})$/
        # following regex: range from maskings_count-2 because sometimes the masked number has 1 or 2 dots more than the actual number
        # e.g. https://github.com/fastlane/fastlane/issues/14969
        replacement = "\\1([0-9]{#{maskings_count - 2},#{maskings_count}})\\3"
        number_with_dialcode_regex_part = number_with_dialcode_masked.gsub(pattern, replacement)
        # => +49([0-9]{8,9})85 or +1([0-9]{7,8})66

        backslash = '\\'
        number_with_dialcode_regex_part = backslash + number_with_dialcode_regex_part
        number_with_dialcode_regex = /^#{number_with_dialcode_regex_part}$/
        # => /^\+49([0-9]{8})85$/ or /^\+1([0-9]{7,8})66$/

        return phone['id'] if phone_number =~ number_with_dialcode_regex
        # +491621234585 matches /^\+49([0-9]{8})85$/
      end

      # Handle case of phone_number not existing in phone_numbers because ENV var is wrong or matcher is broken
      raise Tunes::Error.new, %(
Could not find a matching phone number to #{phone_number} in #{phone_numbers}.
Make sure your environment variable is set to the correct phone number.
If it is, please open an issue at https://github.com/fastlane/fastlane/issues/new and include this output so we can fix our matcher. Thanks.
)
    end

    def phone_id_from_masked_number(phone_numbers, masked_number)
      phone_numbers.each do |phone|
        return phone['id'] if phone['numberWithDialCode'] == masked_number
      end
    end

    def push_mode_from_masked_number(phone_numbers, masked_number)
      phone_numbers.each do |phone|
        return phone['pushMode'] if phone['numberWithDialCode'] == masked_number
      end

      # If no pushMode was supplied, assume sms
      return "sms"
    end

    def request_two_factor_code_from_phone_choose(phone_numbers, code_length)
      puts("Please select a trusted phone number to send code to:")

      available = phone_numbers.collect do |current|
        current['numberWithDialCode']
      end
      chosen = choose_phone_number(available)
      phone_id = phone_id_from_masked_number(phone_numbers, chosen)
      push_mode = push_mode_from_masked_number(phone_numbers, chosen)

      request_two_factor_code_from_phone(phone_id, chosen, code_length, push_mode)
    end

    # this is used in two places: after choosing a phone number and when a phone number is set via ENV var
    def request_two_factor_code_from_phone(phone_id, phone_number, code_length, push_mode = "sms", should_request_code = true)
      if should_request_code
        # Request code
        r = request(:put) do |req|
          req.url("https://idmsa.apple.com/appleauth/auth/verify/phone")
          req.headers['Content-Type'] = 'application/json'
          req.body = { "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
          update_request_headers(req)
        end

        # we use `Spaceship::TunesClient.new.handle_itc_response`
        # since this might be from the Dev Portal, but for 2 step
        Spaceship::TunesClient.new.handle_itc_response(r.body)

        puts("Successfully requested text message to #{phone_number}")
      end

      code = ask_for_2fa_code("Please enter the #{code_length} digit code you received at #{phone_number}:")

      return { "securityCode" => { "code" => code.to_s }, "phoneNumber" => { "id" => phone_id }, "mode" => push_mode }.to_json
    end

    def store_session
      # If the request was successful, r.body is actually nil
      # The previous request will fail if the user isn't on a team
      # on App Store Connect, but it still works, so we're good

      # Tell iTC that we are trustworthy (obviously)
      # This will update our local cookies to something new
      # They probably have a longer time to live than the other poor cookies
      # Changed Keys
      # - myacinfo
      # - DES5c148586dfd451e55afb0175f62418f91
      # We actually only care about the DES value

      request(:get) do |req|
        req.url("https://idmsa.apple.com/appleauth/auth/2sv/trust")
        update_request_headers(req)
      end
      # This request will fail if the user isn't added to a team on iTC
      # However we don't really care, this request will still return the
      # correct DES... cookie

      self.store_cookie
    end

    # Responsible for setting all required header attributes for the requests
    # to succeed
    def update_request_headers(req)
      req.headers["X-Apple-Id-Session-Id"] = @x_apple_id_session_id
      req.headers["X-Apple-Widget-Key"] = self.itc_service_key
      req.headers["Accept"] = "application/json"
      req.headers["scnt"] = @scnt
    end
  end
end


text:
using System;

namespace AkariSolver
{
	/// <summary>
	/// Error dialog.
	/// </summary>
    public partial class ErrorDialog : Gtk.Dialog
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AkariSolver.ErrorDialog"/> class.
        /// </summary>
        /// <param name="mode">Mode.</param>
        public ErrorDialog(int mode)
        {
            this.Build();
            switch (mode)
            {
                case 1:
                    ErrorLabel1.Text = "Not solved!";
                    break;
                case 2:
                    ErrorLabel1.Text = "Parameters out of bounds!";
                    break;
                default:
                    ErrorLabel1.Text = "Critical error! Contact developer!";
                    break;
            }
        }

        /// <summary>
        /// Raises the button ok clicked event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        protected void OnButtonOkClicked(object sender, EventArgs e)
        {
            this.Destroy();
        }
    }
}


text:
package org.apache.camel.zipkin.http;

import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.zipkin.ZipkinTracer;
import org.junit.Test;

/**
 * Integration test requires running Zipkin running
 *
 *
The easiest way to run is locally:
 *
{@code
 * curl -sSL https://zipkin.io/quickstart.sh | bash -s
 * java -jar zipkin.jar
 * }

 *
 *
This test has to be run with environment variables set. For example:
 *
{@code
 * ZIPKIN_COLLECTOR_HTTP_SERVICE_HOST=localhost
 * ZIPKIN_COLLECTOR_HTTP_SERVICE_PORT=9411
 * }

 */
public class ZipkinAutoConfigureHttp extends CamelTestSupport {

    private ZipkinTracer zipkin;

    @Override
    protected CamelContext createCamelContext() throws Exception {
        CamelContext context = super.createCamelContext();

        zipkin = new ZipkinTracer();
        // we have one route as service
        zipkin.addClientServiceMapping("seda:cat", "cat");
        zipkin.addServerServiceMapping("seda:cat", "cat");
        // should auto configure as we have not setup a span reporter
        // NOTE: this won't work unless you have an auto-configuration file in src/test/resources

        // attaching ourself to CamelContext
        zipkin.init(context);

        return context;
    }

    @Test
    public void testZipkinRoute() throws Exception {
        template.requestBody("direct:start", "Hello Cat");
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").to("seda:cat");

                from("seda:cat").routeId("cat")
                        .log("routing at ${routeId}")
                        .delay(simple("${random(1000,2000)}"));
            }
        };
    }
}