text:
Form Elements

                    <input type="text" class="form-control" placeholder="Search for...">

                        <button class="btn btn-default" type="button">Go!</button>

Person create a new person

                    <form id="person-create-edit" ng-submit="submit()" data-parsley-validate class="form-horizontal form-label-left">
                        <input type="text" ng-model="id" id="id" class="ng-hide">

                            First Name *

                                <input type="text" ng-model="firstName" id="first-name" required="required" class="form-control col-md-7 col-xs-12">

                            Last Name *

                                <input type="text" ng-model="lastName" id="last-name" name="last-name" required="required" class="form-control col-md-7 col-xs-12">

                            Email *

                                <input type="text" ng-model="email" id="email" name="email" required="required" class="form-control col-md-7 col-xs-12">

                            Head Referee Level: *

                                <select ng-model="hrLevel" id="hrLevel" class="form-control col-md-6 col-sm-6 col-xs-12" required>
                                    <option value=""></option>
                                    <option value="LEVEL_1">Level 1</option>
                                    <option value="LEVEL_2">Level 2</option>
                                    <option value="LEVEL_3">Level 3</option>
                                    <option value="LEVEL_4">Level 4</option>
                                    <option value="LEVEL_5">Level 5</option>
                                </select>

                            Assistant Referee Level: *

                                <select ng-model="arLevel" id="arLevel" class="form-control col-md-6 col-sm-6 col-xs-12" required>
                                    <option value=""></option>
                                    <option value="LEVEL_1">Level 1</option>
                                    <option value="LEVEL_2">Level 2</option>
                                    <option value="LEVEL_3">Level 3</option>
                                    <option value="LEVEL_4">Level 4</option>
                                    <option value="LEVEL_5">Level 5</option>
                                </select>

                            Snitch Referee Level: *

                                <select ng-model="srLevel" id="srLevel" class="form-control col-md-6 col-sm-6 col-xs-12" required>
                                    <option value=""></option>
                                    <option value="LEVEL_1">Level 1</option>
                                    <option value="LEVEL_2">Level 2</option>
                                    <option value="LEVEL_3">Level 3</option>
                                    <option value="LEVEL_4">Level 4</option>
                                    <option value="LEVEL_5">Level 5</option>
                                </select>

                            Snitch Level:

                                    <select ng-model="snitchLevel" id="snitchLevel" class="form-control col-md-6 col-sm-6 col-xs-12" required>
                                        <option value=""></option>
                                        <option value="LEVEL_1">Level 1</option>
                                        <option value="LEVEL_2">Level 2</option>
                                        <option value="LEVEL_3">Level 3</option>
                                        <option value="LEVEL_4">Level 4</option>
                                        <option value="LEVEL_5">Level 5</option>
                                    </select>

                                Cancel
                                <button type="submit" class="btn btn-success">Submit</button>
                                <input id="submitAndCreateAnother" type="button" value="Submit and Create another" class="btn btn-success" ng-click="submitAndCreateAnother();" />

                    </form>

redpajama_set_name: RedPajamaGithub


text:
package org.txazo.tool.util.web.servlet;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

/**
 * RequestUtils
 */
public abstract class RequestUtils {

    public static String getRequestURL(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String query = request.getQueryString();
        return url + (StringUtils.isBlank(query) ? StringUtils.EMPTY : "?" + query);
    }

    public static String getRequestURL(HttpServletRequest request, String... excludeParams) {
        String url = request.getRequestURL().toString();
        Set<String> excludeParamSet = new HashSet<>();
        if (ArrayUtils.isNotEmpty(excludeParams)) {
            Collections.addAll(excludeParamSet, excludeParams);
        }
        int index = 0;
        String paramName = null;
        StringBuilder paramsString = new StringBuilder();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            paramName = parameterNames.nextElement();
            if (!excludeParamSet.contains(paramName)) {
                paramsString.append(index++ == 0 ? "?" : "&").append(paramName).append("=").append(request.getParameter(paramName));
            }
        }
        return url + paramsString.toString();
    }

}


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

namespace DurableTask.AzureServiceFabric.Integration.Tests
{
    using System;
    using System.Diagnostics;
    using System.Net.Http;
    using System.Threading.Tasks;
    using DurableTask.Core;
    using DurableTask.AzureServiceFabric.Remote;
    using DurableTask.AzureServiceFabric.Service;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    public static class Utilities
    {
        public static TaskHubClient CreateTaskHubClient()
        {
            var partitionProvider = new FabricPartitionEndpointResolver(new Uri(Constants.TestFabricApplicationAddress), new DefaultStringPartitionHashing());
            var httpClientHandler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = (message, certificate, chain, errors) => true
            };
            return new TaskHubClient(new RemoteOrchestrationServiceClient(partitionProvider, httpClientHandler));
        }

        public static async Task ThrowsException<TException>(Func<Task> action, string expectedMessage) where TException : Exception
        {
            try
            {
                await action();
                Assert.Fail($"Method {action.Method} did not throw the expected exception of type {typeof(TException).Name}");
            }
            catch (Exception ex)
            {
                AggregateException aggregate = ex as AggregateException;
                if (aggregate != null)
                {
                    ex = aggregate.InnerException;
                }

                TException expected = ex as TException;
                if (expected == null)
                {
                    Assert.Fail($"Method {action.Method} is expected to throw exception of type {typeof(TException).Name} but has thrown {ex.GetType().Name} instead.");
                }
                else if (!string.Equals(expected.Message, expectedMessage, StringComparison.Ordinal))
                {
                    Assert.Fail($"Method {action.Method} is expected to throw exception with message '{expectedMessage}' but has thrown the message '{expected.Message}' instead.");
                }
            }
        }

        public static async Task<TimeSpan> MeasureAsync(Func<Task> asyncAction)
        {
            var timer = Stopwatch.StartNew();
            await asyncAction();
            timer.Stop();
            return timer.Elapsed;
        }
    }
}


text:
<?php
/**
 * sfEfWidgetFormInputCheckbox represents a custom radio widget
 *
 * @package    sfEfWidgetFormExtraPlugin
 * @subpackage widget
 * @author     Yaismel Miranda Pons <yaismelmp@googlemail.com>
 *             Edier García Gutierrez
 * @version    SVN: $Id$
 */
class sfEfWidgetFormInputRadio extends sfWidgetFormInput
{
  protected static $radio_count = 0;
  /**
   * Constructor.
   *
   * Available options:
   *
   *  - value_attribute_value: The "value" attribute value to set for the checkbox
   *  - group_name: Group name
   *
   * @param array  $options     An array of options
   * @param array  $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormInput
   */
  public function __construct($options = array(), $attributes = array())
  {
    $this->addOption('value_attribute_value');
    $this->addOption('group_name');
    $this->addOption('theme');
    $this->addOption('javascript');

    parent::__construct($options, $attributes);
  }

  /**
   * @param array $options     An array of options
   * @param array $attributes  An array of default HTML attributes
   *
   * @see sfWidgetFormInput
   */
  protected function configure($options = array(), $attributes = array())
  {
    parent::configure($options, $attributes);

    $this->setOption('type', 'radio');
    $this->setOption('group_name', 'rbtn');
    $this->setOption('theme', 'default');
    $this->setOption('javascript', '');

    if (isset($attributes['value']))
    {
      $this->setOption('value_attribute_value', $attributes['value']);
    }
  }

  /**
   * @param  string $name        The element name
   * @param  string $value       The this widget is checked if value is not null
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    $orig_name = $name;
    $name = preg_replace('/(.+?)\[(.+)\]$/', '$1['. $this->getOption('group_name') .'][]', $name);
    $attributes['id'] = $this->generateId($orig_name.self::$radio_count++, $value);

    if (!is_null($value) && $value != false)
    {
      $attributes['checked'] = 'checked';
    }

    if (!isset($attributes['value']) && !is_null($this->getOption('value_attribute_value')))
    {
      $attributes['value'] = $this->getOption('value_attribute_value');
    }

    return parent::render($name, $value, $attributes, $errors) .
    sprintf(<<<EOF
<script type="text/javascript">
  jQuery(document).ready(function() {
    jQuery("input:radio#%s").checkbox(jQuery.extend({}, {
      imagesPath: '/sfEfWidgetFormExtraPlugin/images/',
      cls: 'jquery-radio'
    })).click(function(e){
      %s
    });
  });
</script>
EOF
   , $attributes['id']
   , $this->getOption('javascript'));
  }

  /**
   * Gets the stylesheet paths associated with the widget.
   *
   * @return array An array of stylesheet paths
   */
  public function getStylesheets()
  {
    return array('/sfEfWidgetFormExtraPlugin/css/jquery.radio.'. $this->getOption('theme') .'.css' => 'all');
  }

  /**
   * Gets the JavaScript paths associated with the widget.
   *
   * @return array An array of JavaScript paths
   */
  public function getJavascripts()
  {
    return array('/sfEfWidgetFormExtraPlugin/js/jquery.checkbox.js' => '/sfEfWidgetFormExtraPlugin/js/jquery.checkbox.js');
  }
}


text:
namespace DatabaseManager
{
    partial class ProgressDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.progressBar = new System.Windows.Forms.ProgressBar();
            this.lbxMessages = new System.Windows.Forms.ListBox();
            this.btnClose = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // progressBar
            //
            this.progressBar.Location = new System.Drawing.Point(29, 12);
            this.progressBar.Name = "progressBar";
            this.progressBar.Size = new System.Drawing.Size(226, 23);
            this.progressBar.TabIndex = 0;
            //
            // lbxMessages
            //
            this.lbxMessages.FormattingEnabled = true;
            this.lbxMessages.HorizontalScrollbar = true;
            this.lbxMessages.Location = new System.Drawing.Point(29, 41);
            this.lbxMessages.Name = "lbxMessages";
            this.lbxMessages.Size = new System.Drawing.Size(226, 160);
            this.lbxMessages.TabIndex = 1;
            //
            // btnClose
            //
            this.btnClose.Location = new System.Drawing.Point(105, 207);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new System.Drawing.Size(75, 23);
            this.btnClose.TabIndex = 2;
            this.btnClose.Text = "Close";
            this.btnClose.UseVisualStyleBackColor = true;
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            //
            // ProgressDialog
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 242);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.lbxMessages);
            this.Controls.Add(this.progressBar);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "ProgressDialog";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "ProgressDialog";
            this.ResumeLayout(false);

        }

        #endregion

        public System.Windows.Forms.ProgressBar progressBar;
        public System.Windows.Forms.ListBox lbxMessages;
        public System.Windows.Forms.Button btnClose;
    }
}


text:
{% import "_includes/forms" as forms %}

{% includeCssResource 'supertable/css/SuperTableInput.css' %}

<input type="hidden" name="{{ name }}" value="">

{% set columnSettings = [] %}
{% if settings is defined and settings %}
    {% for col in settings.columns %}
        {% set columnSettings = columnSettings | merge([col]) %}
    {% endfor %}
{% endif %}

                    {% if table %}
                        {% for index, field in table.getFields() %}
                            {% if columnSettings[index] is defined %}
                                {% set width = columnSettings[index].width %}

                                {% if width %}
                                    {% if 'px' not in width and '%' not in width %}
                                        {% set width = width ~ '%' %}
                                    {% endif %}
                                {% endif %}
                            {% endif %}

                                    {{ field.name | t }} {% if field.instructions %}{{ field.instructions | t }}{% endif %}

                        {% endfor %}
                    {% endif %}

                    {% if not settings.staticField %}

                    {% endif %}

                {% set totalNewBlocks = 0 %}

                {% if settings.staticField %}
                    {% if blocks %}
                        {% set blocks = [blocks] %}
                    {% endif %}
                {% endif %}

                {% for block in blocks %}
                    {% set blockId = block.id %}

                    {% if not blockId %}
                        {% set totalNewBlocks = totalNewBlocks + 1 %}
                        {% set blockId = 'new'~totalNewBlocks %}
                    {% endif %}

                            <input type="hidden" name="{{ name }}[{{ blockId }}][type]" value="{{ block.getType() }}">

                        {% include "supertable/fields" with {
                            namespace: name~'['~blockId~'][fields]',
                            element: block,
                            fields: block.getType().getFieldLayout().getFields(),
                            settings: settings,
                        } %}

                {% endfor %}

{{ settings.selectionLabel | default("Add a row") | t }}


text:
/*
 * GetApplicationsRequest.h
 *
 *  Created on: Jul 28, 2014
 *      Author: bwang
 */

#ifndef GETAPPLICATIONSREQUEST_H_
#define GETAPPLICATIONSREQUEST_H_

#include <iostream>
#include <list>

#include "YARN_yarn_service_protos.pb.h"

#include "records/YarnApplicationState.h"

using namespace std;
using namespace hadoop::yarn;

namespace libyarn {

//message GetApplicationsRequestProto {
//  repeated string application_types = 1;
//  repeated YarnApplicationStateProto application_states = 2;
//}

class GetApplicationsRequest {
public:
	GetApplicationsRequest();
	GetApplicationsRequest(const GetApplicationsRequestProto &proto);
	virtual ~GetApplicationsRequest();

	GetApplicationsRequestProto& getProto();

	void setApplicationTypes(list<string> &applicationTypes);
	list<string> getApplicationTypes();

	void setApplicationStates(list<YarnApplicationState> &applicationStates);
	list<YarnApplicationState> getApplicationStates();

private:
	GetApplicationsRequestProto requestProto;
};

} /* namespace libyarn */

#endif /* GETAPPLICATIONSREQUEST_H_ */


text:
package com.evolveum.midpoint.gui.api.component;

import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.model.IModel;

import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.web.component.data.column.CheckBoxHeaderColumn;
import com.evolveum.midpoint.web.component.data.column.ColumnUtils;
import com.evolveum.midpoint.web.component.data.column.LinkColumn;
import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem;
import com.evolveum.midpoint.web.component.util.SelectableBean;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;

public abstract class PopupObjectListPanel<O extends ObjectType> extends ObjectListPanel<O> {
	private static final long serialVersionUID = 1L;

	/**
	 * @param defaultType specifies type of the object that will be selected by default
	 */
	public PopupObjectListPanel(String id, Class<? extends O> defaultType, boolean multiselect, PageBase parentPage) {
		super(id, defaultType, multiselect, parentPage);

	}

	@Override
	protected IColumn<SelectableBean<O>, String> createCheckboxColumn() {
		if (isMultiselect()) {
			return new CheckBoxHeaderColumn<SelectableBean<O>>() {
				private static final long serialVersionUID = 1L;

				@Override
				protected void onUpdateRow(AjaxRequestTarget target, DataTable table, IModel<SelectableBean<O>> rowModel) {
					super.onUpdateRow(target, table, rowModel);
					onUpdateCheckbox(target);
				};

				@Override
				protected void onUpdateHeader(AjaxRequestTarget target, boolean selected, DataTable table) {
					super.onUpdateHeader(target, selected, table);
					onUpdateCheckbox(target);
				}
			};
		}
		return null;
	}

	@Override
	protected IColumn<SelectableBean<O>, String> createNameColumn() {
		if (!isMultiselect()) {
			return new LinkColumn<SelectableBean<O>>(createStringResource("ObjectType.name"),
					ObjectType.F_NAME.getLocalPart(), SelectableBean.F_VALUE + ".name") {
				private static final long serialVersionUID = 1L;

				@Override
				public void onClick(AjaxRequestTarget target, IModel<SelectableBean<O>> rowModel) {
					O object = rowModel.getObject().getValue();
					onSelectPerformed(target, object);

				}
			};
		}

		else {
			return new PropertyColumn(createStringResource("userBrowserDialog.name"),
					ObjectType.F_NAME.getLocalPart(), SelectableBean.F_VALUE + ".name");
		}
	}

	@Override
	protected List<IColumn<SelectableBean<O>, String>> createColumns() {
		return ColumnUtils.getDefaultColumns(getType());
	}

	protected void onSelectPerformed(AjaxRequestTarget target, O object){

	}

	@Override
	protected List<InlineMenuItem> createInlineMenu() {
		return null;
	}

	protected void onUpdateCheckbox(AjaxRequestTarget target){

	}

}


text:
<?xml version="1.0"?>

<include xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_include.xsd">
	<group id="pbxep_paypal" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
	    <attribute type="expanded">0</attribute>
    	Pay by Paypal
        <field id="pp_active" translate="label comment" type="select" sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">
        	Enable
            <config_path>payment/pbxep_paypal/active</config_path>
            <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
        </field>
        <field id="pp_title" translate="label comment" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
        	Title
            <config_path>payment/pbxep_paypal/title</config_path>
            <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
        	<depends>
                <field id="pp_active">1</field>
            </depends>
        </field>
        <field id="pp_sort_order" translate="label comment" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
        	Sort Order
            <config_path>payment/pbxep_paypal/sort_order</config_path>
            <frontend_class>validate-number</frontend_class>
        	<depends>
                <field id="pp_active">1</field>
            </depends>
        </field>
        <field id="pp_action" translate="label comment" type="select" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
        	Debit type
            <config_path>payment/pbxep_paypal/action</config_path>
            <source_model>Paybox\Epayment\Model\Admin\Payment\Actionpaypal</source_model>
        	<depends>
                <field id="pp_active">1</field>
            </depends>
        </field>

        <group id="pbxep_paypal_status" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <attribute type="expanded">0</attribute>
        	Payment status
        	<depends>
                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
            </depends>

	        <field id="pp_status_authorized" translate="label comment" type="select" sortOrder="110" showInDefault="1" showInWebsite="1" showInStore="0">
	        	Once authorized
	            <config_path>payment/pbxep_paypal/status_authorized</config_path>
	            <source_model>Paybox\Epayment\Model\Admin\Order\Status\Pendingpayment</source_model>
	        	<depends>
	                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
	                <field id="pbxep_payments/pbxep_paypal/pp_action">manual</field>
	            </depends>
	        </field>
	        <field id="pp_status_paid" translate="label comment" type="select" sortOrder="120" showInDefault="1" showInWebsite="1" showInStore="0">
	        	Once paid
	            <config_path>payment/pbxep_paypal/status_paid</config_path>
	            <source_model>Paybox\Epayment\Model\Admin\Order\Status\Processing</source_model>
	        	<depends>
	                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
	            </depends>
	        </field>
	        <field id="pp_status_auto_capture" translate="label comment" type="select" sortOrder="112" showInDefault="1" showInWebsite="1" showInStore="0">
	        	Automatic capture status
	            <config_path>payment/pbxep_paypal/status_auto_capture</config_path>
	            <source_model>Paybox\Epayment\Model\Admin\Order\Status\Autocapture</source_model>
	        	<depends>
	                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
	                <field id="pbxep_payments/pbxep_paypal/pp_action">manual</field>
	            </depends>
	        </field>
        </group>

        <group id="pbxep_paypal_conditions" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
            <attribute type="expanded">0</attribute>
        	Conditions
        	<depends>
                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
            </depends>

	        <field id="pp_allowspecific" translate="label comment" type="select" sortOrder="210" showInDefault="1" showInWebsite="1" showInStore="1">
	        	Payment from Applicable Countries
	            <config_path>payment/pbxep_paypal/allowspecific</config_path>
	            <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
	        	<depends>
	                <field id="pbxep_payments/pbxep_paypal/pp_active">1</field>
	            </depends>
	        </field>
	        <field id="pp_specificcountry" translate="label comment" type="multiselect" sortOrder="220" showInDefault="1" showInWebsite="1" showInStore="1">
	        	Payment from Specific Countries
	        	<source_model>Magento\Paypal\Model\System\Config\Source\BuyerCountry</source_model>
	        	<config_path>payment/pbxep_paypal/specificcountry</config_path>
	        	<depends>
	                <field id="allowspecific">1</field>
	                <field id="pbxep_payments/pbxep_cb/active">1</field>
	            </depends>
	        </field>
	        <field id="pp_min_order_total" translate="label comment" type="text" sortOrder="230" showInDefault="1" showInWebsite="1" showInStore="1">
	        	Minimum Order Total
	        	<config_path>payment/pbxep_paypal/min_order_total</config_path>
	        	<depends>
	                <field id="pbxep_payments/pbxep_cb/active">1</field>
	            </depends>
	        </field>
	        <field id="pp_max_order_total" translate="label comment" type="text" sortOrder="240" showInDefault="1" showInWebsite="1" showInStore="1">
	        	Maximum Order Total
	            <config_path>payment/pbxep_paypal/max_order_total</config_path>
	        	<depends>
	                <field id="pbxep_payments/pbxep_cb/active">1</field>
	            </depends>
	        </field>
        </group>
    </group>
</include>


text:
function codingPackageJsonp (exports) {
  codingPackageJsonp.data = exports
}

Object.defineProperty(codingPackageJsonp, 'data', {
  set (value) {
    if (this.current && this.current.startsWith('group')) {
      // const groupName = this.current.split('_')[1]
      const values = Array.isArray(value) ? value : [value]
      this.cache = (this.cache || []).concat(values)
    } else {
      this.cache = value
    }
  },
  get () { return this.cache }
})

codingPackageJsonp.groups = {}
codingPackageJsonp.current = ''

window.codingPackageJsonp = codingPackageJsonp


text:
namespace PrimS.Telnet.Sync.CiTests
{
  using System;

  internal class WriteHandler : WriteHandlerBase
  {
    private readonly Action handler;

    public WriteHandler(Func<byte[], bool> check, Action handler)
    {
      Check = check;
      this.handler = handler;
    }

    public override Func<byte[], bool> Check { get; }

    public override void Handle()
    {
      handler();
    }
  }
}


text:
"""
A fake model with multiple FC layers to test CINN on a more complex model.
"""
import paddle
import paddle.fluid as fluid

size = 2
num_layers = 4
paddle.enable_static()

a = fluid.layers.data(name="A", shape=[-1, size], dtype='float32')
label = fluid.layers.data(name="label", shape=[size], dtype='float32')

fc_out = fluid.layers.fc(
    input=a,
    size=size,
    act="relu",
    bias_attr=fluid.ParamAttr(name="fc_bias"),
    num_flatten_dims=1,
)

for i in range(num_layers - 1):
    fc_out = fluid.layers.fc(
        input=fc_out,
        size=size,
        act="relu",
        bias_attr=fluid.ParamAttr(name="fc_bias"),
        num_flatten_dims=1,
    )

cost = fluid.layers.square_error_cost(fc_out, label)
avg_cost = fluid.layers.mean(cost)

optimizer = fluid.optimizer.SGD(learning_rate=0.001)
optimizer.minimize(avg_cost)

cpu = fluid.core.CPUPlace()
loss = exe = fluid.Executor(cpu)

exe.run(fluid.default_startup_program())

fluid.io.save_inference_model("./multi_fc_model", [a.name], [fc_out], exe)
fluid.io.save_inference_model(
    "./multi_fc_model",
    [a.name],
    [fc_out],
    exe,
    None,
    "fc.pdmodel",
    "fc.pdiparams",
)

print('output name', fc_out.name)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Direita</logradouro><bairro>Sé</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>01002000</cep></feed>


text:
package eu.hyvar.mspl.manifest.resource.hymanifest.debug;

public class HymanifestSourceLookupParticipant {
	// The generator for this class is currently disabled by option
	// 'disableDebugSupport' in the .cs file.
}


text:
exports.view = function (req, res) {
    res.render('add-new-account');
};


text:
require "rails_admin_import/engine"
require "rails_admin_import/import"
require "rails_admin_import/config"

module RailsAdminImport
  def self.config(entity = nil, &block)
    if entity
      RailsAdminImport::Config.model(entity, &block)
    elsif block_given? && ENV['SKIP_RAILS_ADMIN_INITIALIZER'] != "true"
      block.call(RailsAdminImport::Config)
    else
      RailsAdminImport::Config
    end
  end

  def self.reset
    RailsAdminImport::Config.reset
  end

  module Helper
    def self.include?(list, value)
      value = value.to_s.downcase
      list.any?{ |other| other.to_s.downcase.casecmp(value) == 0 }
    end
  end
end

require 'rails_admin/config/actions'

module RailsAdmin
  module Config
    module Actions
      class Import < Base
        RailsAdmin::Config::Actions.register(self)

        register_instance_option(:collection) do
          true
        end

        register_instance_option(:http_methods) do
          [:get, :post]
        end

        register_instance_option(:link_icon) do
          'icon-folder-open'
        end

        register_instance_option :controller do
          Proc.new do
            @response = {}

            # make sure class has import-related methods
            @abstract_model.model.send :include, ::RailsAdminImport::Import

            if request.post?
              results             = @abstract_model.model.run_import(params, _attr_accessible_role, _current_user)
              @response[:notice]  = results[:success].join("
").html_safe  if results[:success].any?
              @response[:error]   = results[:error].join("
").html_safe    if results[:error].any?
            end

            render :action => @action.template_name
          end
        end
      end
    end
  end
end


text:
import React from 'react';
import ReactDOM from 'react-dom';

// Route
import '/imports/startup/client/routes';


text:
<?php

namespace Phlexible\Component\MediaCache\Worker;

use Phlexible\Component\MediaManager\Volume\ExtendedFileInterface;
use Phlexible\Bundle\MediaCacheBundle\Entity\CacheItem;
use Phlexible\Component\MediaTemplate\Model\TemplateInterface;

/**
 * Abstract worker
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
abstract class AbstractWorker implements WorkerInterface
{
    /**
     * Apply error to cache item
     *
     * @param CacheItem             $cacheItem
     * @param string                $status
     * @param string                $message
     * @param string                $inputFilename
     * @param TemplateInterface     $template
     * @param ExtendedFileInterface $file
     */
    protected function applyError(
        CacheItem $cacheItem,
        $status,
        $message,
        $inputFilename,
        TemplateInterface $template,
        ExtendedFileInterface $file)
    {
        $cacheItem
            ->setCacheStatus($status)
            ->setError($message);

        $this->getLogger()->error($message, array(
            'worker' => get_class($this),
            'templateType' => $template->getType(),
            'templateKey' => $template->getKey(),
            'fileName' => $file->getName(),
            'filePath' => $inputFilename,
            'fileId' => $file->getId(),
            'fileVersion' => $file->getVersion(),
            'fileMimeType' => $file->getMimeType(),
            'fileMediaType' => $file->getMediaType(),
        ));
    }
}


text:
import { getMethodName, waitFor } from "./helpers";
import { createGlue, doneAllGlues, gwObject, startGW } from "../initializer";
import { Glue42Core } from "../../glue";
import { PromiseWrapper } from "../../src/utils/pw";
import { waitForArr } from "../helpers";

describe("reconnect", () => {
    let glueClient: Glue42Core.GlueCore;
    let glueServer: Glue42Core.GlueCore;

    beforeEach(async () => {
        [glueClient, glueServer] = await Promise.all([
            createGlue(), createGlue()
        ]);
    });

    afterEach(async () => {
        await doneAllGlues();
    });

    it("my interop instance is changed after reconnect", async () => {
        const pw = new PromiseWrapper();
        const serverInstance = Object.assign({}, glueServer.interop.instance);
        const compareInstances = (i1: Glue42Core.Interop.Instance, i2: Glue42Core.Interop.Instance) => {
            return i1.instance === i2.instance && i1.peerId === i2.peerId;
        };

        glueServer.connection.disconnected(() => {
            if (!compareInstances(serverInstance, glueServer.interop.instance)) {
                pw.reject(`received reject for unknown server instance`);
            }
        });

        let first = true;
        glueServer.connection.connected(() => {
            if (first) {
                if (!compareInstances(serverInstance, glueServer.interop.instance)) {
                    pw.reject("unexpected initial connect event");
                }
                first = false;
                return;
            }

            if (!compareInstances(serverInstance, glueServer.interop.instance)) {
                pw.resolve();
            } else {
                pw.reject("unexpected connect event");
            }
        });

        await glueServer.connection.reconnect();
        return pw.promise;
    });

    it("my interop method is re-published after reconnect", async () => {
        const name = getMethodName();
        const serverInstance = glueServer.interop.instance.instance;
        const waitForResult = waitForArr(["ma", "mr", "sr", "ma"], true);
        const waitForMethodAdded = waitForArr([1]);

        glueClient.interop.methodAdded((m) => {
            if (m.name === name) {
                waitForResult.fn("ma");
                waitForMethodAdded.fn(1);
            }
        });

        glueClient.interop.methodRemoved((m) => {
            if (m.name === name) {
                waitForResult.fn("mr");
            }
        });

        glueClient.interop.serverRemoved((s) => {
            if (s.instance === serverInstance) {
                waitForResult.fn("sr");
            }
        });

        await glueServer.interop.register(name, () => {
            // TODO - do nothing
        });

        await waitForMethodAdded.promise;

        await Promise.all([
            glueServer.connection.reconnect(),
            glueClient.connection.reconnect()]);

        await waitForResult.promise;

        return Promise.resolve();
    });

    it("my interop method handler is invoked after reconnect", async () => {
        const name = getMethodName();
        glueServer.interop.register(name, () => {
            return { a: 1 };
        });

        Promise.all([
            glueServer.connection.reconnect(),
            glueClient.connection.reconnect()]);

        const result = await glueClient.interop.invoke(name, {});
        if (result.returned.a !== 1) {
            throw new Error(`invalid response`);
        }
    });

    it("server and client can see each other after reconnect", (done) => {
        const name = getMethodName();
        glueServer.interop.register(name, () => {
            // Do nothing
        });

        Promise.all([
            glueServer.connection.reconnect(),
            glueClient.connection.reconnect()]);

        setTimeout(() => {
            let ok = 0;
            glueServer.interop.serverAdded((s) => {
                ok++;
                if (ok === 2) {
                    done();
                }
            });

            glueClient.interop.serverAdded((d) => {
                ok++;
                if (ok === 2) {
                    done();
                }
            });
        }, 1500);
    });

    it("my subscription is re-established after client reconnect", async () => {
        const name = getMethodName();
        const pw = new PromiseWrapper<void>();
        let events = 0;
        const stream = await glueServer.interop.createStream(name, {
            subscriptionAddedHandler: (s) => {
                stream.push({ events: ++events });
            }
        });

        const sub = await glueClient.interop.subscribe(name);
        sub.onData((data) => {
            if (data.data.events === 2) {
                pw.resolve();
            }
        });
        await glueClient.connection.reconnect();

        return pw.promise;
    });

    it("onConnected event is fired after initial connect and after reconnect", async () => {
        const name = getMethodName();
        await glueServer.interop.createStream(name);
        const wf = waitForArr([false, true], true);
        await glueClient.interop.subscribe(name, {
            onConnected: (_server, reconnect) => {
                wf.fn(reconnect);
                if (!reconnect) {
                    // trigger reconnect
                    glueClient.connection.reconnect();
                }
            }
        });

        return wf.promise;
    });

    it("my stream is republished after reconnect", async () => {
        const name = getMethodName();
        await glueServer.interop.createStream(name, {
            subscriptionAddedHandler: () => {
                // TODO
            },
            subscriptionRemovedHandler: () => {
                // TODO
            },
            subscriptionRequestHandler: () => {
                // TODO
            }
        });

        const pw = new PromiseWrapper();
        let events = 0;
        glueClient.interop.methodAdded((m) => {
            if (m.name === name && m.supportsStreaming) {
                events++;
                if (events === 2) {
                    pw.resolve();
                }
            }
        });

        await Promise.all([
            glueServer.connection.reconnect(),
            glueClient.connection.reconnect()]);

        return pw.promise;
    });

    it("my subscription is re-established after client&server reconnect", async () => {
        const name = getMethodName();
        const wfSubscriptionAddedHandler = waitForArr([true, true]);
        const wfOnData = waitForArr([true, true]);
        let events = 0;
        const stream = await glueServer.interop.createStream(name, {
            subscriptionAddedHandler: (_s) => {
                wfSubscriptionAddedHandler.fn(true);
                stream.push({ events: ++events });
            }
        });

        const sub = await glueClient.interop.subscribe(name);
        sub.onData((_d) => {
            wfOnData.fn(true);
        });

        await Promise.all([
            glueClient.connection.reconnect(),
            glueServer.connection.reconnect()
        ]);

        return Promise.all([
            wfOnData.promise,
            wfSubscriptionAddedHandler.promise]);
    });

    it("ws restart - my subscription is re-established after client&server reconnect", async () => {
        const name = getMethodName();
        const wfSubscriptionAddedHandler = waitForArr([true, true]);
        const wfOnData = waitForArr([true, true]);
        let events = 0;
        const stream = await glueServer.interop.createStream(name, {
            subscriptionAddedHandler: (_s) => {
                wfSubscriptionAddedHandler.fn(true);
                stream.push({ events: ++events });
            }
        });

        const sub = await glueClient.interop.subscribe(name);
        sub.onData((_d) => {
            wfOnData.fn(true);
        });

        await gwObject.stop();
        await startGW();

        return Promise.all([
            wfOnData.promise,
            wfSubscriptionAddedHandler.promise]);
    });

});


text:
layout: compress
# Default layout
---

<!DOCTYPE html>

{% include lang.html %}

{% capture prefer_mode %}
  {% if site.theme_mode %}
    mode="{{ site.theme_mode }}"
  {% endif %}
{% endcapture %}

  {% include head.html %}

    {% include sidebar.html %}

    {% include topbar.html %}

        {% include refactor-content.html content=content %}

        {% include footer.html %}

      {% include search-results.html %}

    {% if page.mermaid %}
      {% include mermaid.html %}
    {% endif %}

    {% include search-loader.html %}

    {% include js-selector.html %}


text:
use http2::kind::*;
use http2::flag::*;
use http2::payload::*;

use http2::Error;
use http2::ErrorCode;
use http2::SizeIncrement;
use http2::StreamIdentifier;
use http2::FRAME_HEADER_BYTES;
use http2::encode_u24;

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Frame<'a> {
    pub header: FrameHeader,
    pub payload: Payload<'a>
}

impl<'a> Frame<'a> {
    pub fn parse(header: FrameHeader, buf: &[u8]) -> Result<Frame, Error> {
        Ok(Frame {
            header: header,
            payload: try!(Payload::parse(header, buf))
        })
    }

    /// Encodes this Frame into a buffer.
    pub fn encode(&self, buf: &mut [u8]) -> usize {
        self.header.encode(buf);
        self.payload.encode(&mut buf[FRAME_HEADER_BYTES..]) + FRAME_HEADER_BYTES
    }

    /// How many bytes this Frame will use in a buffer when encoding.
    pub fn encoded_len(&self) -> usize {
        FRAME_HEADER_BYTES + self.payload.encoded_len()
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct FrameHeader {
    pub length: u32,
    pub kind: Kind,
    pub flag: Flag,
    pub id: StreamIdentifier,
}

impl FrameHeader {
    #[inline]
    pub fn parse(buf: &[u8]) -> Result<FrameHeader, Error> {
        if buf.len() < FRAME_HEADER_BYTES {
            return Err(Error::Short);
        }

        Ok(FrameHeader {
            length: ((buf[0] as u32) << 16) | ((buf[1] as u32) << 8) | buf[2] as u32,
            kind: Kind::new(buf[3]),
            flag: try!(Flag::new(buf[4]).map_err(|()| { Error::BadFlag(buf[4]) })),
            id: StreamIdentifier::parse(&buf[5..])
        })
    }

    #[inline]
    pub fn encode(&self, buf: &mut [u8]) {
        encode_u24(buf, self.length);
        buf[3] = self.kind.encode();
        buf[4] = self.flag.bits();
        self.id.encode(&mut buf[5..]);
    }
}


text:
using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public static class CoroutineAnimations {

    public static IEnumerator Interpolate(float duration, Action<float> onProgress, bool fixedUpdate = false) {
        for (float p = 0; p < 1; p += (fixedUpdate? Time.fixedDeltaTime : Time.deltaTime) / duration ) {
            onProgress(p);
            yield return fixedUpdate? new WaitForFixedUpdate() : null;
        }
        onProgress(1);
    }

    public static Task Interpolate(this MonoBehaviour b, float duration, Action<float> onProgress, bool fixedUpdate = false, CancellationToken cancellation = default(CancellationToken)) {
        var cr = InterpolateCR(duration, onProgress, fixedUpdate, cancellation);
        if (!fixedUpdate)
            return b.RunTask(cr);
        return Task.Factory.StartNew(cr);
    }

    static IEnumerator InterpolateCR(float duration, Action<float> onProgress, bool fixedUpdate = false, CancellationToken cancellation = default(CancellationToken)) {
        for (float p = 0; p < 1 && !cancellation.IsCancellationRequested; p += (fixedUpdate? Time.fixedDeltaTime : Time.deltaTime) / duration ) {
            onProgress(p);
            yield return fixedUpdate? new WaitForFixedUpdate() : null;
        }
        if (!cancellation.IsCancellationRequested) {
            onProgress(1);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Threading;
using System.Reflection;
using Greet.DataStructureV4.ResultsStorage;
using Greet.DataStructureV4.Entities;
using Greet.DataStructureV4;
using Greet.DataStructureV4.Interfaces;
using Greet.Model;
using Greet.UnitLib3;
using Greet.ConvenienceLib;

namespace CalculatorBatch
{
    /// <summary>
    /// This program loads a data file, runs the calculations and exports the results in a text file
    ///
    /// Example
    /// CalculatorBatch.exe "Default 2015.greet" 1995,2000,2005,2010,2015,2020,2025,2030,2035,2040 p5555,m0,p1
    ///
    /// Will run the simulations for all the years 1995 to 2040 with a 5 year interval and save the results for the pathway which has the id 5555, the mix with the id=0 and the mix with the id=1
    /// </summary>
    class Program
    {
        /// <summary>
        /// Program entry point
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            #region preproceiing parsing the user inputs
            Console.WriteLine("Parsing given parameters...");
            //Using the filename provided as the first argument
            string fileName = args[0];

            //Using the years defined in the second argument
            string years = args[1];
            string[] yearsSplit = years.Split(',');
            List<int> yearsList = new List<int>();
            int temp;
            foreach (string y in yearsSplit)
                if (int.TryParse(y, out temp))
                    yearsList.Add(temp);

            //Using the pathways and mix id provided in the third argument
            string pm = args[2];
            string[] pms = pm.Split(',');
            List<InputResourceReference> inRef = new List<InputResourceReference>();
            foreach (string s in pms)
            {
                if (s[0] == 'p')
                {//this is a pathway reference
                    if (int.TryParse(s.Substring(1, s.Length - 1), out temp))
                    {
                        InputResourceReference pRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Pathway);
                        inRef.Add(pRef);
                    }
                }
                else if (s[0] == 'm')
                {//this is a mix reference
                    if (int.TryParse(s.Substring(1, s.Length - 1), out temp))
                    {
                        InputResourceReference mRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Mix);
                        inRef.Add(mRef);
                    }
                }
            }
            #endregion

            #region loading units file and data file
            Console.WriteLine("Building units context...");
            //Build units context before loading the database
            Units.BuildContext();

            Console.WriteLine("Loading datafile...");
            //Loading the database
            GProject project = new GProject();
            project.Load(fileName);
            #endregion

            #region preprocessing the pathways/mixes we want to record by finding their main output resource
            //Assign main output resource IDs to all the inputsResourceReferences
            foreach (InputResourceReference iref in inRef)
            {
                if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Pathway)
                {
                    if (project.Dataset.PathwaysData.ContainsKey(iref.SourceMixOrPathwayID))
                        iref.ResourceId = project.Dataset.PathwaysData[iref.SourceMixOrPathwayID].MainOutputResourceID;
                }
                else if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Mix)
                {
                    if (project.Dataset.MixesData.ContainsKey(iref.SourceMixOrPathwayID))
                        iref.ResourceId = project.Dataset.MixesData[iref.SourceMixOrPathwayID].MainOutputResourceID;
                }
            }
            #endregion

            #region running the calculations for each year and storing the results
            //Creating a new instance of a dictionary used to store results of the simulations
            Dictionary<InputResourceReference, Dictionary<int, Results>> savedResults = new Dictionary<InputResourceReference, Dictionary<int, Results>>();

            //Running simulations for every provided years
            foreach (int simulationYear in yearsList)
            {
                Console.WriteLine("Running calculations for year " + simulationYear);
                //Set the current year for simulations
                BasicParameters.SelectedYear = project.Dataset.ParametersData.CreateUnregisteredParameter(project.Dataset, "", simulationYear);
                Calculator calc = new Calculator();

                //Run the simulations for the loaded project and defined year, we need to wait completion as the RunCalculationMethod is Async
                var manualEvent = new ManualResetEvent(false);
                calc.CalculationDoneEvent += () => manualEvent.Set();
                calc.RunCalculations(project);
                manualEvent.WaitOne();

                //Loop over all the pathways and mixes ID that we wish to save
                foreach (InputResourceReference pathMixToSave in inRef)
                {
                    if (!savedResults.ContainsKey(pathMixToSave))
                        savedResults.Add(pathMixToSave, new Dictionary<int, Results>());
                    if(!savedResults[pathMixToSave].ContainsKey(simulationYear))
                    {
                        //Pull the results and add them to the dictionary used to store results
                        Results results;
                        if(pathMixToSave.SourceType == Enumerators.SourceType.Pathway)
                            results = Convenience.Clone(project.Dataset.PathwaysData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results);
                        else
                            results = Convenience.Clone(project.Dataset.MixesData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results);
                        savedResults[pathMixToSave].Add(simulationYear, results);
                    }
                }
            }
            #endregion

            #region exporting all the results in a text file per pathway and per mix
            //Export all the desired results to an Excel spreadsheet
            Console.WriteLine("Export all selected results...");
            string preferedMass = "g";
            string preferedEnergy = "Btu";
            string preferedVolume = "gal";

            foreach (KeyValuePair<InputResourceReference, Dictionary<int, Results>> pair in savedResults)
            {
                DataTable dt = new DataTable();
                List<string> resGroups = new List<string>() { "Total Energy", "Fossil Fuel", "Coal Fuel", "Natural Gas Fuel", "Petroleum Fuel", "Water" };
                List<string> pollutants = new List<string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O", "CO2", "CO2_Biogenic" };
                List<string> polGroups = new List<string>() { "GHG-100" };
                List<string> urbanPoll = new List<string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O" };

                Results resultsFU = pair.Value.Values.FirstOrDefault();
                string functionalUnit = "Per ";
                if (resultsFU != null)
                    functionalUnit += GetPreferedVisualizationFunctionalUnitString(project.Dataset, resultsFU, pair.Key.ResourceId);

                dt.Columns.Add("Items " + functionalUnit);
                foreach (int simulationYear in pair.Value.Keys)
                    dt.Columns.Add(simulationYear.ToString());
                List<string> rowString = new List<string>();

                #region total energy and energy groups
                foreach (string resGrp in resGroups)
                {
                    rowString = new List<string>();
                    if (resGrp=="Water")
                        rowString.Add(resGrp+" ("+preferedVolume+")");
                    else
                        rowString.Add(resGrp + " (" + preferedEnergy + ")");

                    foreach (int simulationYear in pair.Value.Keys)
                    {
                        Results results = pair.Value[simulationYear];
                        double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId);

                        if (resGrp == "Total Energy")
                        {
                            LightValue totalE = results.wellToProductEnem.materialsAmounts.TotalEnergy();
                            rowString.Add(NiceValueWithAttribute(totalE * amountRatio, preferedEnergy));
                        }
                        else
                        {
                            Dictionary<int, IValue> resGroupes = results.WellToProductResourcesGroups(project.Dataset);
                            Group resGrpSelected = project.Dataset.ResourcesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp);
                            if (resGrpSelected != null)
                            {
                                int resGrpId = resGrpSelected.Id;
                                LightValue groupValue = new LightValue(resGroupes[resGrpId].Value, resGroupes[resGrpId].UnitExpression);
                                if (groupValue.Dim == DimensionUtils.ENERGY)
                                    rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedEnergy));
                                else
                                    rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedVolume));
                            }
                            else
                                rowString.Add("0");
                        }
                    }
                    dt.Rows.Add(rowString.ToArray());
                }
                #endregion

                #region wtp emissions
                foreach (string poll in pollutants)
                {
                    rowString = new List<string>();
                    rowString.Add(poll+" ("+preferedMass+")");
                    foreach (int simulationYear in pair.Value.Keys)
                    {
                        Results results = pair.Value[simulationYear];
                        double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId);

                        int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id;
                        rowString.Add(NiceValueWithAttribute(
                            new LightValue(results.wellToProductEnem.emissions[polId], DimensionUtils.MASS) * amountRatio
                            , preferedMass));
                    }
                    dt.Rows.Add(rowString.ToArray());
                }
                #endregion

                #region wtp Groups (here only GHG 100)
                foreach (string resGrp in polGroups)
                {
                    rowString = new List<string>();
                    rowString.Add(resGrp+ " ("+ preferedMass+")");
                    foreach (int simulationYear in pair.Value.Keys)
                    {
                        Results results = pair.Value[simulationYear];
                        double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId);

                        Dictionary<int, IValue> emGroupes = pair.Value[simulationYear].WellToProductEmissionsGroups(project.Dataset);
                        Group resGrpSelected = project.Dataset.GasesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp);
                        if (resGrpSelected != null)
                        {
                            int grpId = resGrpSelected.Id;
                            rowString.Add(NiceValueWithAttribute(new LightValue(emGroupes[grpId].Value, emGroupes[grpId].UnitExpression) * amountRatio, preferedMass));
                        }
                        else
                            rowString.Add("0");
                    }
                    dt.Rows.Add(rowString.ToArray());
                }
                #endregion

                #region urban emissions
                foreach (string poll in pollutants)
                {
                    rowString = new List<string>();
                    rowString.Add("Urban " +poll+" ("+preferedMass+")");
                    foreach (int simulationYear in pair.Value.Keys)
                    {
                        Results results = pair.Value[simulationYear];
                        double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId);

                        int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id;
                        rowString.Add(NiceValueWithAttribute(new LightValue(results.wellToProductUrbanEmission[polId], DimensionUtils.MASS) * amountRatio, preferedMass));
                    }
                    dt.Rows.Add(rowString.ToArray());
                }
                #endregion

                string value = ConvertDataTableToString(dt);
                System.IO.File.WriteAllText("Results-" + pair.Key.SourceType.ToString() + "-" + pair.Key.SourceMixOrPathwayID.ToString() + ".txt", value);
            }
            #endregion
            Console.ReadKey();
        }

        /// <summary>
        /// Creates a human readable string representing a data table
        /// </summary>
        /// <param name="dataTable">Data table to be converted as a string</param>
        /// <returns>String representing the data table</returns>
        public static string ConvertDataTableToString(DataTable dataTable)
        {
            var output = new StringBuilder();

            // Write Column titles
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                var text = dataTable.Columns[i].ColumnName;
                output.Append(text + "\t");
            }
            output.Append("\n");

            // Write Rows
            foreach (DataRow row in dataTable.Rows)
            {
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    var text = row[i].ToString();
                    output.Append(text + "\t");
                }
                output.Append("\n");
            }
            string fullString = output.ToString();
            return fullString.Replace("\t\n", Environment.NewLine);
        }

        /// <summary>
        /// Returns the coefficient to be used in order to display the results according to the preferences of the IResult
        /// object used to create the instance of this object. Returns the prefered functional unit divided by the functional unit.
        ///
        /// In case of the FunctionalUnit is null or the PreferedUnit is null, this method returns a ratio of 1. This is usefull to
        /// display the Inputs results and the TransportationSteps results which are accounted for all outputs and not a specific one.
        /// In these cases instead of defining a PreferedUnit for each output we prefer to define none to make things simpler (see InputResult.GetResults)
        ///
        /// Before display all results must be multiplied by this coefficient
        ///
        /// May return a NullReferenceExeption if the IResult object does not define FunctinoalUnit, PreferedDisplayedUnit or PreferedDisplayedAmount
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        internal static double GetFunctionalRatio(GData data, Results results, int producedResourceId)
        {
            if (results != null && results.CustomFunctionalUnitPreference != null && results.CustomFunctionalUnitPreference.PreferredUnitExpression != null)
            {
                LightValue functionalUnit = new LightValue(1.0, results.BottomDim);
                LightValue preferedFunctionalUnit = GetPreferedVisualizationFunctionalUnit(data, results, producedResourceId);

                switch (preferedFunctionalUnit.Dim)
                {
                    case DimensionUtils.MASS: // HARDCODED
                        {
                            functionalUnit = data.ResourcesData[producedResourceId].ConvertToMass(functionalUnit);
                        } break;
                    case DimensionUtils.ENERGY: // HARDCODED
                        {
                            functionalUnit = data.ResourcesData[producedResourceId].ConvertToEnergy(functionalUnit);
                        } break;
                    case DimensionUtils.VOLUME: // HARDCODED
                        {
                            functionalUnit = data.ResourcesData[producedResourceId].ConvertToVolume(functionalUnit);
                        } break;
                }
                return preferedFunctionalUnit.Value / functionalUnit.Value;
            }
            else
                return 1;
        }

        /// <summary>
        /// Returns the functional unit to be used on display: User prefered, default million btu or functional unit of the
        /// process in case of the database does not contains enough information to convert to one million btu
        /// </summary>
        /// <param name="data"></param>
        /// <param name="results"></param>
        /// <param name="producedResourceId"></param>
        /// <returns></returns>
        internal static LightValue GetPreferedVisualizationFunctionalUnit(GData data, Results results, int producedResourceId)
        {
            LightValue preferedFunctionalUnit;
            if (results.CustomFunctionalUnitPreference.enabled)
                preferedFunctionalUnit = new LightValue(results.CustomFunctionalUnitPreference.Amount, results.CustomFunctionalUnitPreference.PreferredUnitExpression);
            else if (data.ResourcesData[producedResourceId].CanConvertTo(DimensionUtils.ENERGY, new LightValue(1.0, results.BottomDim)))
                preferedFunctionalUnit = new LightValue(1, "MJ");
            else
                preferedFunctionalUnit = new LightValue(1.0, results.BottomDim);
            return preferedFunctionalUnit;
        }

        /// <summary>
        /// Returns the functional unit to be used on display: User prefered, default million btu or functional unit of the
        /// process in case of the database does not contains enough information to convert to one million btu
        /// </summary>
        /// <param name="data"></param>
        /// <param name="results"></param>
        /// <param name="producedResourceId"></param>
        /// <returns></returns>
        internal static string GetPreferedVisualizationFunctionalUnitString(GData data, Results results, int producedResourceId)
        {
            string preferedFunctionalUnit = "";
            try
            {
                if (results.CustomFunctionalUnitPreference.enabled)
                    preferedFunctionalUnit = results.CustomFunctionalUnitPreference.Amount.ToString() + " " + results.CustomFunctionalUnitPreference.PreferredUnitExpression;
                else if (data.ResourcesData[producedResourceId].CanConvertTo(DimensionUtils.ENERGY, new LightValue(1.0, results.BottomDim)))
                    preferedFunctionalUnit = "1 MJ";
                else
                {
                    AQuantity qty = Units.QuantityList.ByDim(results.BottomDim);
                    preferedFunctionalUnit = "1 " + qty.SiUnit.Expression;
                }
            }
            catch { }

            return preferedFunctionalUnit;
        }

        internal static string NiceValueWithAttribute(LightValue value, string preferedExpression = "")
        {
            double automaticScalingSlope = 1;
            string overrideUnitAttribute = "";
            return GuiUtils.FormatSIValue(value.Value
                , 2 //DEFINES THE FORMATTING FOR VALUES
                , out overrideUnitAttribute
                , out automaticScalingSlope
                , false
                , 16 //DEFINES HOW MANY DIGITS YOU WANT TO SEE
                , value.Dim
                , preferedExpression);// +" " + overrideUnitAttribute;
        }
    }
}


text:
///import core
///commands 悬浮工具栏
///commandsName  AutoFloat,autoFloatEnabled
///commandsTitle  悬浮工具栏
/**
 *  modified by chengchao01
 *  注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
 */
UE.plugins["autofloat"] = function() {
  var me = this,
    lang = me.getLang();
  me.setOpt({
    topOffset: 0
  });
  var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
    topOffset = me.options.topOffset;

  //如果不固定toolbar的位置,则直接退出
  if (!optsAutoFloatEnabled) {
    return;
  }
  var uiUtils = UE.ui.uiUtils,
    LteIE6 = browser.ie && browser.version <= 6,
    quirks = browser.quirks;

  function checkHasUI() {
    if (!UE.ui) {
      alert(lang.autofloatMsg);
      return 0;
    }
    return 1;
  }
  function fixIE6FixedPos() {
    var docStyle = document.body.style;
    docStyle.backgroundImage = 'url("about:blank")';
    docStyle.backgroundAttachment = "fixed";
  }
  var bakCssText,
    placeHolder = document.createElement("div"),
    toolbarBox,
    orgTop,
    getPosition,
    flag = true; //ie7模式下需要偏移
  function setFloating() {
    var toobarBoxPos = domUtils.getXY(toolbarBox),
      origalFloat = domUtils.getComputedStyle(toolbarBox, "position"),
      origalLeft = domUtils.getComputedStyle(toolbarBox, "left");
    toolbarBox.style.width = toolbarBox.offsetWidth + "px";
    toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
    toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
    if (LteIE6 || (quirks && browser.ie)) {
      if (toolbarBox.style.position != "absolute") {
        toolbarBox.style.position = "absolute";
      }
      toolbarBox.style.top =
        (document.body.scrollTop || document.documentElement.scrollTop) -
        orgTop +
        topOffset +
        "px";
    } else {
      if (browser.ie7Compat && flag) {
        flag = false;
        toolbarBox.style.left =
          domUtils.getXY(toolbarBox).x -
          document.documentElement.getBoundingClientRect().left +
          2 +
          "px";
      }
      if (toolbarBox.style.position != "fixed") {
        toolbarBox.style.position = "fixed";
        toolbarBox.style.top = topOffset + "px";
        (origalFloat == "absolute" || origalFloat == "relative") &&
          parseFloat(origalLeft) &&
          (toolbarBox.style.left = toobarBoxPos.x + "px");
      }
    }
  }
  function unsetFloating() {
    flag = true;
    if (placeHolder.parentNode) {
      placeHolder.parentNode.removeChild(placeHolder);
    }

    toolbarBox.style.cssText = bakCssText;
  }

  function updateFloating() {
    var rect3 = getPosition(me.container);
    var offset = me.options.toolbarTopOffset || 0;
    if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
      setFloating();
    } else {
      unsetFloating();
    }
  }
  var defer_updateFloating = utils.defer(
    function() {
      updateFloating();
    },
    browser.ie ? 200 : 100,
    true
  );

  me.addListener("destroy", function() {
    domUtils.un(window, ["scroll", "resize"], updateFloating);
    me.removeListener("keydown", defer_updateFloating);
  });

  me.addListener("ready", function() {
    if (checkHasUI(me)) {
      //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
      if (!me.ui) {
        return;
      }
      getPosition = uiUtils.getClientRect;
      toolbarBox = me.ui.getDom("toolbarbox");
      orgTop = getPosition(toolbarBox).top;
      bakCssText = toolbarBox.style.cssText;
      placeHolder.style.height = toolbarBox.offsetHeight + "px";
      if (LteIE6) {
        fixIE6FixedPos();
      }
      domUtils.on(window, ["scroll", "resize"], updateFloating);
      me.addListener("keydown", defer_updateFloating);

      me.addListener("beforefullscreenchange", function(t, enabled) {
        if (enabled) {
          unsetFloating();
        }
      });
      me.addListener("fullscreenchanged", function(t, enabled) {
        if (!enabled) {
          updateFloating();
        }
      });
      me.addListener("sourcemodechanged", function(t, enabled) {
        setTimeout(function() {
          updateFloating();
        }, 0);
      });
      me.addListener("clearDoc", function() {
        setTimeout(function() {
          updateFloating();
        }, 0);
      });
    }
  });
};


text: <link rel="stylesheet" href="{{ "/style.css" | prepend: site.baseurl }}" />


text:
package com.vowovrz.spring_01.beans_10.factory;

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

public class StaticCarFactory {

	// 静态工厂方法配置bean
	private static Map<String, Car> cars = new HashMap<String, Car>();

	static {
		cars.put("audi", new Car("audi", 39566f));
		cars.put("dasauto", new Car("dasauto", 30303030f));
	}

	public static Car getCar(String name) {
		return cars.get(name);
	}
}


text:
package com.cg.wrapper;
/*@author SmitaBrijesh*/
public class WrapperTest {
	public static void main (String args[ ]) {
		int i=10;//declaring int data

		Integer iObj= new Integer(i);//boxing
		fun(iObj);
		fun(100);//auto-boxing

	}
	public static void fun (Integer iObj) {
		System.out.println ("The value is : " + iObj.intValue());//unboxing
	}
}
/*Wrapper class provides the mechanism to converts primitives into object
and objects into primitive.
Java5 onwards autoboxing features converts objects into primitives automatically
and auto-unboxing automatically converts primitives to objects
There is a list of eight final wrapper class in java.lang package
1>Number
	1>int 	-Integer	5>float		-Float
	2>byte	-Byte		6>double	-Double
	3>short -Short
	4>long  -Long

7>boolean	-Boolean
8>char		-Character

================================Usage of Wrapper======================
1>String to different data type formats(parsing operation
*/


text:
__all__ = ["InvalidCredentialsException"]

class InvalidCredentialsException(Exception):
    pass

class NoHostsConnectedToException(Exception):
    pass


text:
require 'json'

module Charta
  # Represents a Geometry with SRID
  class GeoJSON
    attr_reader :srid

    def initialize(data, srid = :WGS84)
      srid ||= :WGS84
      @json = self.class.flatten(data.is_a?(Hash) ? data : JSON.parse(data))
      lsrid = @json['crs']['properties']['name'] if @json.is_a?(Hash) &&
                                                    @json['crs'].is_a?(Hash) &&
                                                    @json['crs']['properties'].is_a?(Hash)
      lsrid ||= srid
      @srid = ::Charta.find_srid(lsrid)
    end

    def geom
      Charta.new_geometry(to_ewkt)
    end

    def to_hash
      @json
    end

    def to_ewkt
      "SRID=#{@srid};" + self.class.object_to_ewkt(@json)
    end

    def valid?
      to_ewkt
      true
    rescue
      false
    end

    class << self
      # Test is given data is a valid GeoJSON
      def valid?(data, srid = :WGS84)
        new(data, srid).valid?
      rescue
        false
      end

      # Force coordinates to 2D
      def flatten(hash)
        if hash['type'] == 'FeatureCollection'
          flatten_feature_collection(hash)
        elsif hash['type'] == 'Feature'
          flatten_feature(hash)
        else
          flatten_geometry(hash)
        end
      end

      def flatten_feature_collection(hash)
        hash.merge('features' => hash['features'].map { |f| flatten_feature(f) })
      end

      def flatten_feature(hash)
        hash.merge('geometry' => flatten_geometry(hash['geometry']))
      end

      def flatten_geometry(hash)
        coordinates = hash['coordinates']
        flattened =
          case hash['type']
          when 'Point' then
            flatten_position(coordinates)
          when 'MultiPoint', 'LineString'
            coordinates.map { |p| flatten_position(p) }
          when 'MultiLineString', 'Polygon'
            coordinates.map { |l| l.map { |p| flatten_position(p) } }
          when 'MultiPolygon'
            coordinates.map { |m| m.map { |l| l.map { |p| flatten_position(p) } } }
          when 'GeometryCollection' then
            return hash.merge('geometries' => hash['geometries'].map { |g| flatten_geometry(g) })
          else
            raise StandardError, "Cannot handle: #{hash['type'].inspect}. In #{hash.inspect}"
          end

        hash.merge('coordinates' => flattened)
      end

      def flatten_position(position)
        position[0..1]
      end

      def object_to_ewkt(hash)
        type = hash[:type] || hash['type']
        send("#{type.gsub(/(.)([A-Z])/, '\1_\2').downcase}_to_ewkt", hash)
      end

      def feature_collection_to_ewkt(hash)
        return 'GEOMETRYCOLLECTION EMPTY' if hash['features'].nil?
        'GEOMETRYCOLLECTION(' + hash['features'].collect do |feature|
          object_to_ewkt(feature)
        end.join(', ') + ')'
      end

      def geometry_collection_to_ewkt(hash)
        return 'GEOMETRYCOLLECTION EMPTY' if hash['geometries'].nil?
        'GEOMETRYCOLLECTION(' + hash['geometries'].collect do |feature|
          object_to_ewkt(feature)
        end.join(', ') + ')'
      end

      def feature_to_ewkt(hash)
        object_to_ewkt(hash['geometry'])
      end

      def point_to_ewkt(hash)
        return 'POINT EMPTY' if hash['coordinates'].nil?
        'POINT(' + hash['coordinates'].join(' ') + ')'
      end

      def line_string_to_ewkt(hash)
        return 'LINESTRING EMPTY' if hash['coordinates'].nil?
        'LINESTRING(' + hash['coordinates'].collect do |point|
          point.join(' ')
        end.join(', ') + ')'
      end

      def polygon_to_ewkt(hash)
        return 'POLYGON EMPTY' if hash['coordinates'].nil?
        'POLYGON(' + hash['coordinates'].collect do |hole|
          '(' + hole.collect do |point|
            point.join(' ')
          end.join(', ') + ')'
        end.join(', ') + ')'
      end

      def multi_point_to_ewkt(hash)
        return 'MULTIPOINT EMPTY' if hash['coordinates'].nil?
        'MULTIPOINT(' + hash['coordinates'].collect do |point|
          '(' + point.join(' ') + ')'
        end.join(', ') + ')'
      end

      def multi_line_string_to_ewkt(hash)
        return 'MULTILINESTRING EMPTY' if hash['coordinates'].nil?
        'MULTILINESTRING(' + hash['coordinates'].collect do |line|
          '(' + line.collect do |point|
            point.join(' ')
          end.join(', ') + ')'
        end.join(', ') + ')'
      end

      def multipolygon_to_ewkt(hash)
        return 'MULTIPOLYGON EMPTY' if hash['coordinates'].nil?
        'MULTIPOLYGON(' + hash['coordinates'].collect do |polygon|
          '(' + polygon.collect do |hole|
            '(' + hole.collect do |point|
              point.join(' ')
            end.join(', ') + ')'
          end.join(', ') + ')'
        end.join(', ') + ')'
      end

      # for PostGIS ST_ASGeoJSON compatibility
      def multi_polygon_to_ewkt(hash)
        return 'MULTIPOLYGON EMPTY' if hash['coordinates'].nil?
        'MULTIPOLYGON(' + hash['coordinates'].collect do |polygon|
          '(' + polygon.collect do |hole|
            '(' + hole.collect do |point|
              point.join(' ')
            end.join(', ') + ')'
          end.join(', ') + ')'
        end.join(', ') + ')'
      end
    end
  end
end


text:
from collections import OrderedDict
from api.symbolic import LinearExpr
from hyperedge import *
from transforms import *
import numpy as np

class Face():
  allNames = []

  def __init__(self, name, pts, edgeNames=None, edgeAngles=None, allEdges=None, decorations=None):
    if name:
      self.name = name
    else:
      self.name = "" # "face%03d" % len(Face.allNames)
    Face.allNames.append(self.name)

    self.pts2d = list(pts)

    self.edges = [None] * len(pts)
    self.renameEdges(edgeNames, edgeAngles, allEdges)
    if decorations:
      self.decorations = decorations
    else:
      self.decorations = []

  def renameEdges(self, edgeNames=None, edgeAngles=None, allEdges=None):
    if edgeNames:
      if edgeAngles is None:
        edgeAngles = [None] * len(edgeNames)
      for (index, name) in enumerate(edgeNames):
        self.setEdge(index, name, edgeAngles[index], allEdges)
    return self

  def setEdge(self, index, name=None, angle=None, allEdges=None):
    if name is None:
      return self
    try:
      if self.edges[index].name == name:
        if angle is not None:
          self.edges[index].setAngle(angle)
        return self
    except:
      pass

    self.disconnect(index)

    e = HyperEdge.edge(allEdges, name, self, angle)
    self.edges[index] = e

    return self

  def replaceEdge(self, oldEdge, newEdge):
    for (i, e) in enumerate(self.edges):
      if e is oldEdge:
        self.disconnect(i)
        self.edges[i] = newEdge
        newEdge.join(self)
    return self

  def edgeLength(self, edgeIndex):
    pt1 = np.array(self.pts2d[edgeIndex-1])
    pt2 = np.array(self.pts2d[edgeIndex])

    d = pt2 - pt1
    if isinstance(d[0], LinearExpr) or isinstance(d[1], LinearExpr):
        return LinearExpr.hypot(d[0], d[1])
    else:
        return np.linalg.norm(d)

  def rotate(self, n=1):
    for i in range(n):
      self.edges.append(self.edges.pop(0))
      self.pts2d.append(self.pts2d.pop(0))

    return self

  def flip(self):
    newEdges = []
    newPts = []
    while self.edges:
      newEdges.append(self.edges.pop())
      newPts.append(self.pts2d.pop())
    newEdges.insert(0, newEdges.pop())
    self.edges = newEdges
    self.pts2d = newPts
    # XXX TODO: flip orientation of edges
    return self

  def transform(self, scale=1, angle=0, origin=(0,0)):
    r = np.array([[np.cos(angle), -np.sin(angle)],
                  [np.sin(angle),  np.cos(angle)]]) * scale
    o = np.transpose(np.array(origin))

    pts = np.transpose(np.dot(r, np.transpose(np.array(self.pts2d)))) + o
    self.pts2d = [tuple(x) for x in pts]
    for (i, d) in enumerate(self.decorations):
      pts = np.transpose(np.dot(r, np.transpose(np.array(d[0])))) + o
      self.decorations[i] = ([tuple(x) for x in pts], d[1])

  def disconnectFrom(self, edgename):
    for (i, e) in enumerate(self.edges):
      if edgename == e.name:
        return self.disconnect(i)
    return self

  def disconnectAll(self):
    for i in range(len(self.edges)):
      self.disconnect(i)
    return self

  def disconnect(self, index):
    e = self.edges[index]

    if e is None:
      return self

    self.edges[index] = None
    e.remove(self)
    return self

  def allNeighbors(self):
    n = []
    for es in self.neighbors():
      n.extend(es)
    return n

  def neighbors(self):
    n = []
    for e in self.edges:
      if e is None:
        n.append([])
      else:
        n.append([f.name for f in e.faces if f.name != self.name])
    return n

  def copy(self, name):
    return Face(name, self.pts2d, decorations=self.decorations)

  def matches(self, other):
    if len(self.pts2d) != len(other.pts2d):
      return False
    #XXX TODO: verify congruence
    bothpts = zip(self.pts2d, other.pts2d)
    return True

  def addDecoration(self, pts):
    self.decorations.append(pts)

  def preTransform(self, edge):
    index = self.edges.index(edge)
    return np.dot(RotateOntoX(self.pts2d[index-1], self.pts2d[index]), MoveToOrigin(self.pts2d[index]))

  def triangulate(self, edgeFrom):
    pts4d = np.transpose(np.array([np.array(list(x) + [0,1]) for x in self.pts2d]))

    d4d = []
    edges = []
    for d in ( x[0] for x in self.decorations if x[1] == "hole" ):
      d4d.append(np.transpose(np.array([np.array(list(x) + [0,1]) for x in d])))

    if edgeFrom is not None:
      r = self.preTransform(edgeFrom)
      pts4d = np.dot(r, pts4d)
      for i,d in enumerate(d4d):
        d4d[i] = np.dot(r, d)

    pts2d = pts4d[0:2]

    vertices = [x for x in np.transpose(pts2d)]
    segments = [np.array((i, (i+1) % len(vertices))) for i in range(len(vertices))]
    holes = []
    for d2d in d4d:
      for i in range(len(d2d)):
        edges.append([d2d[:,i-1], d2d[:,i], None])
      d = np.transpose(d2d[0:2])
      segments.extend( [len(vertices)+np.array(((i+1) % len(d), i)) for i in range(len(d))] )
      vertices.extend( [x for x in d] )
      holes.append( sum(d)/len(d) )

    if holes:
      A = dict(vertices=np.array(vertices), segments=np.array(segments), holes=np.array(holes))
      '''
      import triangle.plot
      import matplotlib.pyplot as plt
      triangle.plot.compare(plt, A, A)
      plt.show()
      '''
    else:
      A = dict(vertices=np.array(vertices), segments=np.array(segments))

    '''
    B = triangle.triangulate(A, opts='p')
    faces = [np.transpose(np.array(
               [list(B['vertices'][x]) + [0,1] for x in (face[0], face[1], face[2])]
             )) for face in B['triangles']]
    return faces, pts2d, pts4d, cutedges
    '''
    return A, pts2d, pts4d, edges

  def getAll3DFaces(self, edgeFrom, transform, allFaces, allEdges, facesTouched, fold=True):
    if self in facesTouched:
      # TODO : verify that it connects appropriately along alternate path
      print "Repeated face : " + self.name
      return

    facesTouched.append(self)

    #faces, pts2d, pts4d = self.triangulate(edgeFrom)
    #allFaces.extend([np.dot(transform, x) for x in faces])
    '''
    for f in faces:
      allFaces.extend([np.dot(transform, x) for x in inflate(f)])
    '''
    A, pts2d, pts4d, edges = self.triangulate(edgeFrom)
    allFaces.append((transform, A, self.name))
    allEdges.extend([(np.dot(transform, x[0]), np.dot(transform, x[1]), x[2]) for x in edges])
    pts4d = np.dot(transform, pts4d)

    for (i, e) in enumerate(self.edges):
      # XXX hack: don't follow small edges
      if e is None or len(e.faces) <= 1 or self.edgeLength(i) <= 0.01:
        if self.edgeLength(i) <= 0.01:
          print "skipping short edge"
        allEdges.append([pts4d[:,i-1], pts4d[:,i], None])
        continue
      da = e.faces[self]
      # XXX : Assumes both faces have opposite edge orientation
      #       Only works for non-hyper edges -- need to store edge orientation info for a +/- da
      for (f, a) in ((f, a+da) for (f, a) in e.faces.iteritems() if f not in facesTouched):
        allEdges.append([pts4d[:,i-1], pts4d[:,i], a])

    for (i, e) in enumerate(self.edges):
      # XXX hack: don't follow small edges
      if e is None or len(e.faces) <= 1 or self.edgeLength(i) <= 0.01:
        continue

      pt1 = pts2d[:,i-1]
      pt2 = pts2d[:,i]
      da = e.faces[self]

      # TODO : Only skip self and the face that you came from to verify multi-connected edges
      # XXX : Assumes both faces have opposite edge orientation
      #       Only works for non-hyper edges -- need to store edge orientation info for a +/- da
      for (f, a) in ((f, a+da) for (f, a) in e.faces.iteritems() if f not in facesTouched):
        r = np.eye(4)
        if fold:
          r = RotateX(np.deg2rad(a))
        x = RotateXTo(pt2, pt1)
        r = np.dot(x, r)
        r = np.dot(MoveOriginTo(pt1), r)
        f.getAll3DFaces(e, np.dot(transform, r), allFaces, allEdges, facesTouched, fold)

  def __eq__(self, other):
    return self.name == other.name

  def __hash__(self):
    return self.name.__hash__()

if __name__ == "__main__":
  ae = []

  f1 = Face("one"  , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("12", "13", "15", "14"), allEdges = ae)
  f2 = Face("two"  , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("12", "24", "26", "23"), allEdges = ae)
  f3 = Face("three", ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("13", "23", "36", "35"), allEdges = ae)
  f4 = Face("four" , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("14", "45", "46", "24"), allEdges = ae)
  f5 = Face("five" , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("15", "35", "56", "45"), allEdges = ae)
  f6 = Face("six"  , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("26", "46", "56", "36"), allEdges = ae)

  print f1.pts2d
  f1.transform(scale=2, angle=np.deg2rad(45), origin=(1,1))
  print f1.pts2d
  '''
  f1.rotate()
  f1.flip()
  f1.rotate(2)
  f1.flip()
  f1.rotate()

  print [str(x) for x in f2.edges]
  print f2.edges
  e = f1.edges[0]
  e.remove(f1)

  print
  print f1.neighbors()
  print f2.neighbors()
  print f3.neighbors()
  print f4.neighbors()
  print f5.neighbors()
  print f6.neighbors()

  f1.disconnectAll()
  print
  print f1.neighbors()
  print f2.neighbors()
  print f3.neighbors()
  print f4.neighbors()
  print f5.neighbors()
  print f6.neighbors()

  f1.setEdge(0, "12", ae)
  print
  print f1.neighbors()
  print f2.neighbors()
  print f3.neighbors()
  print f4.neighbors()
  print f5.neighbors()
  print f6.neighbors()

  loopedges = []
  loop = Face("loop"  , ((1,0), (1,1), (0,1), (0,0)), edgeNames = ("join", "left", "join", "right"), allEdges = loopedges)
  print loopedges
  print [str(x) for x in loop.edges]
  for e in loopedges:
    print e.faces
  '''