text:
jQuery (Zepto) Geolocator
=================

## Features

jQuery Geolocator is a plugin that takes a list of addresses and gets a distance and directions to each address from your current geolocation position. If available, it uses [W3C Geolocation API (_HTML5 Geolocation_)](http://dev.w3.org/geo/api/spec-source.html) to find your current location, and queries Google Maps API for distances to each address inside your list. If the visitor's browser is old and does not support the Geolocation API, the more inaccurate IP address based geolocation from Google is used.

This plugin is a fork of / based on [HTML5-GeoLocation-jQuery-Plugin by teleject](http://teleject.github.com/HTML5-GeoLocation-jQuery-Plugin/).

### Why did I decide to make a new plugin instead of using the old one?

At first I only wanted to add some options to the original plugin, and fix variables that were leaking into the global scope. I soon realized that there were far more things that I wanted change inside the plugin, so I ended up rewriting many parts of the plugin code.

## Demo

[Click here for a demo](http://krister.fi/jquery.geolocator/#demo)

## Dependencies

To use the plugin the following scripts/libraries are required, and should be included on your page:

- [jQuery](http://jquery.com/) (_requires at least version 1.6_) or [Zepto](http://http://zeptojs.com/) (_needs a custom build like this `rake concat[-detect:-form:data:selector:fx_methods] dist` you can find the mentioned custom build inside the `dist` folder_)
- [Google JS API](https://developers.google.com/loader/#GettingStarted) + [API key](https://code.google.com/apis/console)
- [Google Maps API](https://developers.google.com/maps/documentation/javascript/reference)

## How to use

### 1. Markup

You need to wrap each address inside your list item with [Microformats hCard ADR defined classes](http://microformats.org/wiki/hcard-examples-rfc2426#3.2.1_ADR_Type_Definition), and somewhere inside the list item an element that has `distance` as its classname (that is where the distance for that address is printed). Classnames used in default markup can be changed via plugin options.

__Example markup:__

          2907 E MLK Jr Blvd.,
          Austin,
          TX,
          78702

          Aleksanterinkatu 52
          00100,
          Helsinki
          Finland

If you want, you can optionally set latitude and longitude of the address as [data attributes](http://html5doctor.com/html5-custom-data-attributes/) to `.adr` elements, to get more accurate results:

    ...

You can also have multiple unordered list elements with different addresses inside your `locations` element. However, you should only have one instance of the plugin running, since running multiple instances of the plugin seems to be quite buggy.

### 2. Needed scripts

Before you use the plugin, make sure that you have jQuery (or Zepto), Google JS API, Google Maps and jQuery Geolocator plugin linked inside your `<head>` tag, or before your ending `</body>` tag (_recommended_).

### 3. Javascript

After you have all script tags included, you can call the plugin on a list (unordered list, ul - by default) with your custom options. (Remember to wrap your code in jQuery's or Zepto's [.ready() function](http://api.jquery.com/ready/))

Here we are changing the plugin to use kilometers instead of miles:

You can also use the plugin without manually including Google API script tags, but it is not recommended since it will slow down the time it takes to find geolocation/distances as it has to load the Google APIs after the plugin has been initialized. This can be done with the `apiKey` option:

If you later need to refresh the plugin, you can call it again on the same element without any options:

    $("#locations").geolocator();

## Info about Zepto support

Default build of Zepto.js does not provide all the methods that are needed, so you need to build a custom version of Zepto.

This is the custom build of Zepto that you can find inside the `dist` folder:

```
rake concat[-detect:-form:data:selector:fx_methods] dist
```

## Plugin options: General settings

Following options can be used to customize the plugin:

__sorting__

Set to `false` if you don't want addresses to be sorted by distance automatically. Default: `true`.

__manualCheck__

Set to `true` if you want to disable automatic geolocating, and let the user manually geolocate using a link. Default: `false`.

Example:

    Check geolocation

__notificationStyle__

A notification style for your `'getting geolocation...'` text. `'fade'` or `'show'`. Default: `'show'`.

__apiKey__

An Google API key is needed if you want the plugin to download all Google APIs for you. Default: `null`.

__targetBlank__

Set to `true` to open all `'Show directions'` links in a new browser tab/window. Default: `false`.

__debugMode__

Set to `true` to enable debug mode. This mode logs all Geolocation and Google API errors to you browser's Javascript console. Default: `false`.

## Plugin options: Elements

__checkElem__

Element selector (a link element) for `manualCheck` setting. Default: `'#check'`.

__recheckElem__

Element selector (a link element) to recheck geolocation. Default: `'#recheck'`.

__geodataElem__

Element that displays your own location. Default: `'#geodata'`.

__notificationElem__

Element that displays a `'getting geolocation...'` notification when the plugin is running. Default: `'.notification'`.

__listParentElem__

Parent element for a list (_usually ul or ol_). Default: `'ul'`.

__listElem__

Child element for list items. Default: `'li'`.

__distanceElem__

Element that displays the distance for each address. Has to be a child of `listElem` element. Default: `'.distance'`.

__geoAdrElem__

Element that holds each address. Has to be a child of `listElem` element. [Microformats hCard ADR defined classes](http://microformats.org/wiki/hcard-examples-rfc2426#3.2.1_ADR_Type_Definition). Default: `'.adr'`.

__mapsLinkElem__

Element that is appended to each list item. Has to be a child of `listElem` element. Default: `'.maps-link'`.

__locationsElem__

With this setting you can assign your main element like this `$.geolocator({ locationsElem: '#locations' });`. Default: `null`.

## Plugin options: Language strings

You can change the default texts used by the plugin to your own language.

__distanceBigStr__

Language string for big distance (miles or kilometers). If default string `miles` is changed, kilometers will be used. Default: `'miles'`.

__distanceSmallStr__

Language string for small distance (meters). Default: `'meters'`.

__distanceUnknownStr__

Language string for unknown distance. Default: `'unknown'`.

__notFoundStr__

Language string that is displayed when your location is not found. Default: `'Could not get your location'`.

__mapsLinkStr__

Language string for a Google Maps link that is showed next to each address. Default: `'Show directions'`.

## Plugin options: W3C Geolocation API options

__enableHighAccuracy__

Set to `true` if you want to get the most accurate location estimate possible. Getting geolocation might take longer if enabled. Default: `false`.

__timeout__

The number of milliseconds to wait before timing out. Default: `6000` (6 seconds).

__maximumAge__

Amount of time in milliseconds that the geolocation result is cached. Default: `60000` (1 minute).

## Custom events

The following events are triggered on the element that is running jQuery Geolocator:

* `'geolocator:fail'` when getting geolocation (_Geolocation API or Google_) fails.
* `'geolocator:done'` when the script has finished running, and getting geolocation was successful.
* `'geolocator:own-fail'` when getting your own location failed.
* `'geolocator:own-done'` when getting your own location was successful.

You can listen to the events by using for example jQuery's `.on()` (or `.bind()`):

    $("#locations").on("geolocator:done", function(){
      // do something
    });

## Browser support

The script uses Geolocation API in newer browsers. A fallback to a IP address based geolocation from Google is used in older browsers. It should work in Internet Explorer 7+, Firefox, Safari, Chrome and Opera. Even though the browser support is quite good, the performance might not be that good in older desktop and mobile browsers.

## Reporting issues and bugs

If something is not working for you or you find a bug, please open a new issue at the [issues section](https://github.com/kristerkari/jQuery-Geolocator/issues).

## Developer

Developed by [Krister Kari](https://twitter.com/#!/kristerkari).

## License

This software is released under the [MIT license](http://www.opensource.org/licenses/MIT)

## Changelog

* 1.0.4 (_19.08.2012_) - Added support for Zepto.js
* 1.0.3 (_19.08.2012_) - Added a workaround for Google API limitations and added [Grunt](https://github.com/cowboy/grunt) as a build tool
* 1.0.2 (_01.05.2012_) - added clearTimeout to fix a bug in older browsers, and did a small change to link creation
* 1.0.1 (_27.04.2012_) - 'targetBlank' option for links, support for country names (_.country-name_) and small fixes to loops.
* 1.0.0 (_20.04.2012_) - Initial release


text:
<!DOCTYPE html>

  <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
  <meta name="generator" content="2014.3.1.295"/>
  <title>Staff Register</title>

  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/site_global.css?422415861"/>
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/master_a-master.css?437027330"/>
  <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/staff-register.css?4195896371" id="pagesheet"/>

     <img class="grpelem" id="u2643-4" alt="Banquet Provider Registers" width="519" height="64" src="<?php echo base_url();?>images/u2643-4.png"/>

       <a class="block" href="<?php echo base_url();?>index.php/main">
       <a class="nonblock nontext grpelem" id="u1617-4" href="<?php echo base_url();?>index.php/main"><img id="u1617-4_img" alt="R A H O T A N" width="178" height="30" src="<?php echo base_url();?>images/u1617-4.png"/>

      <a class="nonblock nontext clearfix grpelem" id="u1615-4" href="<?php echo base_url();?>index.php/login/login">
Register

      <a class="nonblock nontext clearfix grpelem" id="u1614-4" href="<?php echo base_url();?>index.php/login/login">
|  Login

First name:

Last name:

          <?php echo form_open('ValidateForm/checkStaffRegister');?>

<input type="text"class="inputs" placeholder="" name="firstname"/>
    	<input type="text"class="inputs" placeholder="" name="lastname"/>

    <select name="sex" class="inputs" style="height:40px;width:290px">
         <option selected="selected" disabled="disabled">-----sex-----</option>
         <option value="m">male</option>
         <option value="f">female</option>
       </select>

    	<input type="text"  name="phone" onkeydown="javascript:backspacerDOWN(this,event);" onkeyup="javascript:backspacerUP(this,event);" class="inputs" placeholder=""/>

<input type="text"class="inputs" placeholder="" name="position" />
    	<input type="text"class="inputs" placeholder="" name="department"/>

<input type="text"class="inputs" placeholder="" name="hiredate" />
    	<select name="salary" class="inputs" style="height:40px;width:290px">
          <option selected="selected" disabled="disabled">-----amount-----</option>
          <option value="less than 10,000">less than 10,000</option>
          <option value="between 10,001 and 15,000">between 10,001 and 15,000</option>
          <option value="between 15,001 and 20,000">between 15,001 and 20,000</option>
          <option value="between 20,001 and 25,000">between 20,001 and 25,000</option>
          <option value="between 25,001 and 30,000">between 25,001 and 30,000</option>
           <option value="more than 30,000">more than 30,000</option>
        </select>

<input type="text"class="inputs" placeholder="" name="email" />
    	<input type="text"class="inputs" placeholder="" name="username"/>

<input type="text"class="inputs" placeholder="" name="password" />
    	<input type="text"class="inputs" placeholder="" name="repassword"/>

Hire date:

Email:

Sex:

Phone:

Position:

Department:

Salary:

Username:

Password:

Re-enter Password:

     <a class="nonblock nontext grpelem" id="u2644" href="<?php echo base_url();?>index.php/login/login"><img id="u2644_states" alt="Cancel" src="<?php echo base_url();?>images/blank.gif"/>
     <input type='image' value='Submit' name='submit' id="u2624_states" alt="Verify" src="<?php echo base_url();?>images/blank.gif"/>

<?php echo form_close();?>

*

*

*

*

*

*

*

*

*

*

required_firstname

required_lastname

required_sex

required_phone

required_position

required_department

required_email

required_username

required_password

required_password

© 2015 RAHOTAN, Group. / School of Information Technology /

King Mongkut's University of Technology Thonburi. All rights reserved.

   <img class="preload" src="<?php echo base_url();?>images/u2644_states-r.png" alt=""/>
   <img class="preload" src="<?php echo base_url();?>images/u2624_states-r.png" alt=""/>

redpajama_set_name: RedPajamaGithub


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_putc_12.c
Label Definition File: CWE253_Incorrect_Check_of_Function_Return_Value.label.xml
Template File: point-flaw-12.tmpl.c
*/
/*
 * @description
 * CWE: 253 Incorrect Check of Return Value
 * Sinks: putc
 *    GoodSink: Correctly check if putwc() failed
 *    BadSink : Incorrectly check if putwc() failed
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifndef OMITBAD

void CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_putc_12_bad()
{
    if(globalReturnsTrueOrFalse())
    {
        /* FLAW: putwc() might fail, in which case the return value will be EOF (-1), but
         * we are checking to see if the return value is 0 */
        if (putwc((wchar_t)L'A', stdout) == 0)
        {
            printLine("putwc failed!");
        }
    }
    else
    {
        /* FIX: check for the correct return value */
        if (putwc((wchar_t)L'A', stdout) == WEOF)
        {
            printLine("putwc failed!");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses the GoodSink on both sides of the "if" statement */
static void good1()
{
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: check for the correct return value */
        if (putwc((wchar_t)L'A', stdout) == WEOF)
        {
            printLine("putwc failed!");
        }
    }
    else
    {
        /* FIX: check for the correct return value */
        if (putwc((wchar_t)L'A', stdout) == WEOF)
        {
            printLine("putwc failed!");
        }
    }
}

void CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_putc_12_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_putc_12_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE253_Incorrect_Check_of_Function_Return_Value__wchar_t_putc_12_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
///////////////////////////////////////////////////////////
// The Henge3D Physics Engine					        //
// Found at https://github.com/bretternst/Henge3D      //
////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Henge3D
{
	/// <summary>
	/// Represents a plane, defined by a point intersecting the plane and a normal direction.
	/// </summary>
	public struct Plane
	{
		public Vector3 P;
		public Vector3 Normal;

		/// <summary>
		/// Construct a new plane.
		/// </summary>
		/// <param name="p">A point intersecting the plane.</param>
		/// <param name="normal">The normalized direction vector that points "up" away from the plane.</param>
		public Plane(Vector3 p, Vector3 normal)
		{
			P = p;
			Normal = normal;
		}

		/// <summary>
		/// Intersects a line with the shape and returns the intersection point, if there is one.
		/// </summary>
		/// <param name="segment">The line segment to intersect.</param>
		/// <param name="p">The point of the intersection.</param>
		/// <returns>Returns a value indicating whether there is an intersection.</returns>
		public bool Intersect(ref Line line, out Vector3 p)
		{
			p = Vector3.Zero;

			float a, d, e, t;
			Vector3.Dot(ref line.P, ref Normal, out a);
			Vector3.Dot(ref P, ref Normal, out d);
			Vector3.Dot(ref Normal, ref line.Direction, out e);
			if (Math.Abs(e) < Constants.Epsilon)
			{
				p = Vector3.Zero;
				return false;
			}
			else
			{
				t = (d - a) / e;
				Vector3.Multiply(ref line.Direction, t, out p);
				Vector3.Add(ref line.P, ref p, out p);
				return true;
			}
		}

		/// <summary>
		/// Intersects a line segment with the shape and returns the intersection point closest to the beginning of the segment.
		/// </summary>
		/// <param name="segment">The line segment to intersect.</param>
		/// <param name="scalar">A value between 0 and 1 indicating how far along the segment the intersection occurs.</param>
		/// <param name="p">The point of the intersection closest to the beginning of the line segment.</param>
		/// <returns>Returns a value indicating whether there is an intersection.</returns>
		public bool Intersect(ref Segment segment, out float scalar, out Vector3 p)
		{
			p = Vector3.Zero;
			scalar = float.NaN;

			float a, d, e;
			Vector3 diff;
			Vector3.Subtract(ref segment.P2, ref segment.P1, out diff);
			Vector3.Dot(ref segment.P1, ref Normal, out a);
			Vector3.Dot(ref P, ref Normal, out d);
			Vector3.Dot(ref Normal, ref diff, out e);
			if (Math.Abs(e) <= Constants.Epsilon) return false;
			scalar = (d - a) / e;
			Vector3.Multiply(ref diff, scalar, out p);
			Vector3.Add(ref segment.P1, ref p, out p);
			return scalar >= 0f && scalar <= 1f;
		}

		/// <summary>
		/// Gets the closest point on the plane to the given point.
		/// </summary>
		/// <param name="p">The point to project onto the plane.</param>
		/// <param name="output">Returns the closest point on the plane.</param>
		public void ClosestPointTo(ref Vector3 p, out Vector3 output)
		{
			float dist;
			Vector3 tmp;
			Vector3.Subtract(ref p, ref P, out tmp);
			Vector3.Dot(ref Normal, ref tmp, out dist);
			Vector3.Multiply(ref Normal, dist, out tmp);
			Vector3.Subtract(ref p, ref tmp, out output);
		}
	}
}


text:
using System;
using System.Transactions;

#endregion

namespace System.Workflow.Runtime.Hosting
{
    [Obsolete("The System.Workflow.* types are deprecated.  Instead, please use the new types from System.Activities.*")]
    public abstract class WorkflowCommitWorkBatchService : WorkflowRuntimeService
    {
        public delegate void CommitWorkBatchCallback();

        virtual internal protected void CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
        {
            Transaction tx = null;
            if (null == Transaction.Current)
                tx = new CommittableTransaction();
            else
                tx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);

            try
            {
                using (TransactionScope ts = new TransactionScope(tx))
                {
                    commitWorkBatchCallback();
                    ts.Complete();
                }

                CommittableTransaction committableTransaction = tx as CommittableTransaction;
                if (committableTransaction != null)
                    committableTransaction.Commit();

                DependentTransaction dependentTransaction = tx as DependentTransaction;
                if (dependentTransaction != null)
                    dependentTransaction.Complete();
            }
            catch (Exception e)
            {
                tx.Rollback(e);
                throw;
            }
            finally
            {
                if (tx != null)
                {
                    tx.Dispose();
                }
            }
        }
    }
}


text:
require './test/helper'
require 'paperclip/schema'
require 'active_support/testing/deprecation'

class SchemaTest < Test::Unit::TestCase
  include ActiveSupport::Testing::Deprecation

  def setup
    rebuild_class
  end

  def teardown
    Dummy.connection.drop_table :dummies rescue nil
  end

  context "within table definition" do
    context "using #has_attached_file" do
      setup do
        ActiveSupport::Deprecation.silenced = false
      end
      should "create attachment columns" do
        Dummy.connection.create_table :dummies, :force => true do |t|
          ActiveSupport::Deprecation.silence do
            t.has_attached_file :avatar
          end
        end
        rebuild_class

        columns = Dummy.columns.map{ |column| [column.name, column.type] }

        assert_includes columns, ['avatar_file_name', :string]
        assert_includes columns, ['avatar_content_type', :string]
        assert_includes columns, ['avatar_file_size', :integer]
        assert_includes columns, ['avatar_updated_at', :datetime]
      end

      should "display deprecation warning" do
        Dummy.connection.create_table :dummies, :force => true do |t|
          assert_deprecated do
            t.has_attached_file :avatar
          end
        end
      end
    end

    context "using #attachment" do
      setup do
        Dummy.connection.create_table :dummies, :force => true do |t|
          t.attachment :avatar
        end
        rebuild_class
      end

      should "create attachment columns" do
        columns = Dummy.columns.map{ |column| [column.name, column.type] }

        assert_includes columns, ['avatar_file_name', :string]
        assert_includes columns, ['avatar_content_type', :string]
        assert_includes columns, ['avatar_file_size', :integer]
        assert_includes columns, ['avatar_updated_at', :datetime]
      end
    end
  end

  context "within schema statement" do
    setup do
      Dummy.connection.create_table :dummies, :force => true
    end

    context "migrating up" do
      context "with single attachment" do
        setup do
          Dummy.connection.add_attachment :dummies, :avatar
          rebuild_class
        end

        should "create attachment columns" do
          columns = Dummy.columns.map{ |column| [column.name, column.type] }

          assert_includes columns, ['avatar_file_name', :string]
          assert_includes columns, ['avatar_content_type', :string]
          assert_includes columns, ['avatar_file_size', :integer]
          assert_includes columns, ['avatar_updated_at', :datetime]
        end
      end

      context "with multiple attachments" do
        setup do
          Dummy.connection.add_attachment :dummies, :avatar, :photo
          rebuild_class
        end

        should "create attachment columns" do
          columns = Dummy.columns.map{ |column| [column.name, column.type] }

          assert_includes columns, ['avatar_file_name', :string]
          assert_includes columns, ['avatar_content_type', :string]
          assert_includes columns, ['avatar_file_size', :integer]
          assert_includes columns, ['avatar_updated_at', :datetime]
          assert_includes columns, ['photo_file_name', :string]
          assert_includes columns, ['photo_content_type', :string]
          assert_includes columns, ['photo_file_size', :integer]
          assert_includes columns, ['photo_updated_at', :datetime]
        end
      end

      context "with no attachment" do
        should "raise an error" do
          assert_raise ArgumentError do
            Dummy.connection.add_attachment :dummies
          rebuild_class
          end
        end
      end
    end

    context "migrating down" do
      setup do
        Dummy.connection.change_table :dummies do |t|
          t.column :avatar_file_name, :string
          t.column :avatar_content_type, :string
          t.column :avatar_file_size, :integer
          t.column :avatar_updated_at, :datetime
        end
      end

      context "using #drop_attached_file" do
        setup do
          ActiveSupport::Deprecation.silenced = false
        end
        should "remove the attachment columns" do
          ActiveSupport::Deprecation.silence do
            Dummy.connection.drop_attached_file :dummies, :avatar
          end
          rebuild_class

          columns = Dummy.columns.map{ |column| [column.name, column.type] }

          assert_not_includes columns, ['avatar_file_name', :string]
          assert_not_includes columns, ['avatar_content_type', :string]
          assert_not_includes columns, ['avatar_file_size', :integer]
          assert_not_includes columns, ['avatar_updated_at', :datetime]
        end

        should "display a deprecation warning" do
          assert_deprecated do
            Dummy.connection.drop_attached_file :dummies, :avatar
          end
        end
      end

      context "using #remove_attachment" do
        context "with single attachment" do
          setup do
            Dummy.connection.remove_attachment :dummies, :avatar
            rebuild_class
          end

          should "remove the attachment columns" do
            columns = Dummy.columns.map{ |column| [column.name, column.type] }

            assert_not_includes columns, ['avatar_file_name', :string]
            assert_not_includes columns, ['avatar_content_type', :string]
            assert_not_includes columns, ['avatar_file_size', :integer]
            assert_not_includes columns, ['avatar_updated_at', :datetime]
          end
        end

        context "with multiple attachments" do
          setup do
            Dummy.connection.change_table :dummies do |t|
              t.column :photo_file_name, :string
              t.column :photo_content_type, :string
              t.column :photo_file_size, :integer
              t.column :photo_updated_at, :datetime
            end

            Dummy.connection.remove_attachment :dummies, :avatar, :photo
            rebuild_class
          end

          should "remove the attachment columns" do
            columns = Dummy.columns.map{ |column| [column.name, column.type] }

            assert_not_includes columns, ['avatar_file_name', :string]
            assert_not_includes columns, ['avatar_content_type', :string]
            assert_not_includes columns, ['avatar_file_size', :integer]
            assert_not_includes columns, ['avatar_updated_at', :datetime]
            assert_not_includes columns, ['photo_file_name', :string]
            assert_not_includes columns, ['photo_content_type', :string]
            assert_not_includes columns, ['photo_file_size', :integer]
            assert_not_includes columns, ['photo_updated_at', :datetime]
          end
        end

        context "with no attachment" do
          should "raise an error" do
            assert_raise ArgumentError do
              Dummy.connection.remove_attachment :dummies
            end
          end
        end
      end
    end
  end
end


text:
package v1

import (
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	duckv1 "github.com/google/knative-gcp/pkg/apis/duck/v1"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"knative.dev/pkg/apis"
)

func TestAuditLogsGetGroupVersionKind(t *testing.T) {
	want := schema.GroupVersionKind{
		Group:   "events.cloud.google.com",
		Version: "v1",
		Kind:    "CloudAuditLogsSource",
	}

	c := &CloudAuditLogsSource{}

	got := c.GetGroupVersionKind()

	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("failed to get expected (-want, +got) = %v", diff)
	}
}

func TestAuditLogsConditionSet(t *testing.T) {
	want := []apis.Condition{{
		Type: SinkReady,
	}, {
		Type: duckv1.TopicReady,
	}, {
		Type: duckv1.PullSubscriptionReady,
	}, {
		Type: apis.ConditionReady,
	}}
	c := &CloudAuditLogsSource{}

	c.ConditionSet().Manage(&c.Status).InitializeConditions()
	var got []apis.Condition = c.Status.GetConditions()

	compareConditionTypes := cmp.Transformer("ConditionType", func(c apis.Condition) apis.ConditionType {
		return c.Type
	})
	sortConditionTypes := cmpopts.SortSlices(func(a, b apis.Condition) bool {
		return a.Type < b.Type
	})
	if diff := cmp.Diff(want, got, sortConditionTypes, compareConditionTypes); diff != "" {
		t.Errorf("failed to get expected (-want, +got) = %v", diff)
	}
}

func TestCloudAuditLogsSourceIdentitySpec(t *testing.T) {
	s := &CloudAuditLogsSource{
		Spec: CloudAuditLogsSourceSpec{
			PubSubSpec: duckv1.PubSubSpec{
				IdentitySpec: duckv1.IdentitySpec{
					ServiceAccountName: "test",
				},
			},
		},
	}
	want := "test"
	got := s.IdentitySpec().ServiceAccountName
	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("failed to get expected (-want, +got) = %v", diff)
	}
}

func TestCloudAuditLogsSourceIdentityStatus(t *testing.T) {
	s := &CloudAuditLogsSource{
		Status: CloudAuditLogsSourceStatus{
			PubSubStatus: duckv1.PubSubStatus{},
		},
	}
	want := &duckv1.IdentityStatus{}
	got := s.IdentityStatus()
	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("failed to get expected (-want, +got) = %v", diff)
	}
}

func TestCloudAuditLogsSource_GetConditionSet(t *testing.T) {
	s := &CloudAuditLogsSource{}

	if got, want := s.GetConditionSet().GetTopLevelConditionType(), apis.ConditionReady; got != want {
		t.Errorf("GetTopLevelCondition=%v, want=%v", got, want)
	}
}

func TestCloudAuditLogsSource_GetStatus(t *testing.T) {
	s := &CloudAuditLogsSource{
		Status: CloudAuditLogsSourceStatus{},
	}
	if got, want := s.GetStatus(), &s.Status.Status; got != want {
		t.Errorf("GetStatus=%v, want=%v", got, want)
	}
}


text:
{-|
Module      : CalcStats
Description : Calculate statistics
Copyright   : (c) Thomas Lang, 2014
License     : BSD-3
Stability   : stable
Portability : Imports Data.Typeable and Data.List

This module does all the statistical computations.
So it takes the arguments and the list of numbers
and generates an output String containing all wished
information. The formulas for the results were mostly
taken from the free online encyclopedia Wikipedia.
-}
module CalcStats ( calculate ) where

import Data.List            ( sort   )
import Data.Typeable        ( typeOf )

-- |Performs the calculation and prints the result
calculate :: (Eq a, Show a, Num a, Floating a, RealFrac a) => [String] -> [a] -> IO ()
calculate args nums = putStrLn $ "Statistical evaluation: \n-----------------------\n\n" ++ buildOutString args nums ""

-- |Builds the ouput String by going through all Parameters
buildOutString :: (Eq a, Show a, Num a, Floating a, RealFrac a) => [String] -> [a] -> String -> String
buildOutString _          []   _   = "The input list is empty, no calculations done."
buildOutString []         _    str = str
buildOutString ("--am":r) nums str = str ++ "Arithmetic Mean: \t\t" ++ show (calcArithM nums) ++ "\n" ++ buildOutString r nums str
buildOutString ("--gm":r) nums str = str ++ "Geometric Mean: \t\t" ++ show (calcGeometricM nums) ++ "\n" ++ buildOutString r nums str
buildOutString ("--hm":r) nums str = if not (any (0==) nums) then str ++ "Harmonic Mean: \t\t\t" ++ show (calcHarmonicM nums) ++ "\n" ++
                                                                  buildOutString r nums str
                                                             else str ++ "Harmonic Mean: \t\t\tCannot be computed because of some '0' numbers\n" ++
                                                                  buildOutString r nums str
buildOutString ("--me":r) nums str = str ++ "Median: \t\t\t" ++ show (calcMedian nums) ++ "\n" ++ buildOutString r nums str
buildOutString ("--ra":r) nums str = str ++ "Range: \t\t\t\t" ++ show (calcRange nums) ++ "\n" ++ buildOutString r nums str
buildOutString ("--ev":r) nums str = str ++ "Empirical Variance: \t\t" ++ show (calcVariance nums) ++ "\n" ++ buildOutString r nums str
buildOutString ("--es":r) nums str = str ++ "Empirical Standard Deviation: \t" ++ show (calcDeviation nums) ++ "\n" ++ buildOutString r nums str
buildOutString args       nums str = buildOutString (tail args) nums str

-- |Rounds the passed value to two digits
round2 :: (RealFrac a, Fractional a) => a  -> a
round2 f = (fromInteger $ round $ f * (10^2)) / (10.0^^2)

-- |Calculates the arithmetic mean of
-- all numbers in the passed list
calcArithM :: (RealFrac a, Fractional a) => [a] -> a
calcArithM l = round2 $ (sum l) / fromIntegral (length l)

-- |Calculates the geometrix mean of
-- all numbers in the passed list
calcGeometricM :: (RealFrac a, Floating a) => [a] -> a
calcGeometricM l = round2 $ (product l) ** (1/(fromIntegral $ length l))

-- |Calculates the harmonic mean of
-- all numbers in the passed list
calcHarmonicM :: (Eq a, RealFrac a, Fractional a) => [a] -> a
calcHarmonicM list = round2 $ (fromIntegral (length list)) / (sum $ map recip list)

-- |Calculates the Median of the passed list, which
-- is the "central" value in the sorted list
calcMedian :: (Ord a, RealFrac a) =>  [a] -> a
calcMedian list = round2 $ calcQuantil list 0.5

-- |Calculates the Quantil with the passed number
-- of the passed list.
--
-- Note: Indexes - 1 in even part, because Haskell
-- list indices start at 0
calcQuantil :: (Ord a, RealFrac a, RealFrac b) =>  [a] -> b -> a
calcQuantil list p | not (isInt ((fromIntegral ll) * p)) = l !! ((ceiling $ (fromIntegral ll) * p) - 1)
                   | otherwise                           = ((l !! (pos - 1)) + (l !! pos)) / 2
             where ll = length list
                   l  = sort list
                   pos = truncate $ (fromIntegral ll) * p

                   isInt :: RealFrac a => a -> Bool
                   isInt x = x == fromInteger (round x)

-- |Calculates the range of all numbers in
-- the passed list, which is defined as
-- the difference of the global maximum
-- and the global minimum
calcRange :: (Ord a, RealFrac a, Num a) => [a] -> a
calcRange list = round2 $ maximum list - minimum list

-- |Calculates the corrected variance of the passed list
calcVariance :: (RealFrac a, Fractional a) => [a] -> a
calcVariance list = round2 $ (sum $ map (\x -> (x - am)^2) list) / fromIntegral (length list - 1)
                    where am = calcArithM list

-- |Calculates the standard deviation of the
-- passed list, which is the square root
-- of the corrected variance of the list
calcDeviation :: (RealFrac a, Floating a) => [a] -> a
calcDeviation list = round2 $ sqrt $ calcVariance list


text:
<?php

namespace garethp\ews\API\Type;

use garethp\ews\API\Type;

/**
 * Class representing UserIdType
 *
 *
 * XSD Type: UserIdType
 *
 * @method string getSID()
 * @method UserIdType setSID(string $sID)
 * @method string getPrimarySmtpAddress()
 * @method UserIdType setPrimarySmtpAddress(string $primarySmtpAddress)
 * @method string getDisplayName()
 * @method UserIdType setDisplayName(string $displayName)
 * @method string getDistinguishedUser()
 * @method UserIdType setDistinguishedUser(string $distinguishedUser)
 * @method string getExternalUserIdentity()
 * @method UserIdType setExternalUserIdentity(string $externalUserIdentity)
 */
class UserIdType extends Type
{

    /**
     * @var string
     */
    protected $sID = null;

    /**
     * @var string
     */
    protected $primarySmtpAddress = null;

    /**
     * @var string
     */
    protected $displayName = null;

    /**
     * @var string
     */
    protected $distinguishedUser = null;

    /**
     * @var string
     */
    protected $externalUserIdentity = null;
}


text:
export default {
  set(id) {
    localStorage.setItem('lastCourse', JSON.stringify(id));
  },
  get() {
    return JSON.parse(localStorage.getItem('lastCourse'));
  }
};


text:
package com.sonaive.v2ex.ui.adapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sonaive.v2ex.R;
import com.sonaive.v2ex.provider.V2exContract;
import com.sonaive.v2ex.widget.PaginationCursorAdapter;

import de.greenrobot.event.EventBus;

/**
 * Created by liutao on 1/5/15.
 */
public class SearchCursorAdapter extends PaginationCursorAdapter<SearchCursorAdapter.ViewHolder> {

    /**
     * Recommended constructor.
     *
     * @param context The context
     * @param c       The cursor from which to get the data.
     * @param flags   Flags used to determine the behavior of the adapter;
     *                Currently it accept {@link #FLAG_REGISTER_CONTENT_OBSERVER}.
     */
    public SearchCursorAdapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, Cursor cursor) {
        if (cursor != null) {
            final String keyword = cursor.getString(cursor.getColumnIndex(V2exContract.Search.SEARCH_KEYWORD));
            holder.keyword.setText(keyword);
            holder.container.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(keyword);
                }
            });
        }
    }

    @Override
    protected void onContentChanged() {
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_history, parent, false);
        // set the view's size, margins, paddings and layout parameters
        return new ViewHolder(v);
    }

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView keyword;
        public LinearLayout container;
        public ViewHolder(View view) {
            super(view);
            keyword = (TextView) view.findViewById(R.id.keyword);
            container = (LinearLayout) view.findViewById(R.id.container);
        }
    }
}


text:
module Oceanarium
  class Event
    attr_accessor :id, :action_status, :droplet_id, :event_type_id, :percentage

    def initialize(option, api_key, client_id)
      if api_key.nil? || client_id.nil?
        raise 'No API key/client ID!'
      else
        if option.is_a?(Hash)
          @object = option
        else
          @object = Oceanarium::Event.find(option)
        end
        if @object.nil?
          self.id = nil
        else
          self.id = @object['id']
          self.action_status = @object['action_status']
          self.droplet_id = @object['droplet_id']
          self.event_type_id = @object['event_type_id']
          self.percentage = @object['percentage']
        end
      end
    end

    # Core API

    def self.find(id)
      @request = Oceanarium::Request.new
      @get = @request.get("/events/#{id}/")
      if @get.parsed_response['status'] == 'OK'
        @get.parsed_response['event']
      end
    end
  end
end


text:
import data_pb2
import sys

def write():
  if len(sys.argv) != 2:
    print ("Usage:", sys.argv[0], "BATCH_DATA")
    sys.exit(-1)

  batch_data = data_pb2.Batch()

  try:
    with open(sys.argv[1], "rb") as f:
      batch_data.ParseFromString(f.read())
  except IOError:
    print (sys.argv[1] + ": File not found.  Creating a new file.")

  # insert new type
  dab_type = batch_data.fea_types
  dab_type.append(data_pb2.DISC)
  dab_type.append(data_pb2.DISC)
  dab_type.append(data_pb2.DISC)

  # def rows
  batch_data.rows = 1000
  # def cols
  batch_data.cols = 1000
  # insert new value
  new_data_value = batch_data.samples.add()
  new_data_value.v = 0.1;
  new_data_value.id = 2; # the last value will be the union type value

  with open(sys.argv[1], "wb") as f:
    f.write(batch_data.SerializeToString())

def read():
  if len(sys.argv) != 2:
    print ("Usage:", sys.argv[0], "BATCH_DATA")
    sys.exit(-1)

  batch_data = data_pb2.Batch()

  with open(sys.argv[1], "rb") as f:
    batch_data.ParseFromString(f.read())

  print("rows: ", batch_data.rows)
  print("cols: ", batch_data.cols)
  print("samples size: ", len(batch_data.samples))
  p_value = batch_data.samples[-1]
  print(" - last value: ", p_value, end="")
  print("fea_types size: ", len(batch_data.fea_types))
  p_type = batch_data.fea_types[-1]
  if p_type == data_pb2.CONT:
    print(" - CONT")
  elif p_type == data_pb2.DISC:
    print(" - DISC")
  elif p_type == data_pb2.RANK:
    print(" - RANK")
  else:
    print("ERROR")

def main():
  #write()
   read()

if __name__ == "__main__":
    main()


text:
require File.expand_path('../integration', __FILE__)

module Adapters
  class Patron < Faraday::TestCase

    def adapter() :patron end

    unless jruby?
      Integration.apply(self, :NonParallel) do
        # https://github.com/toland/patron/issues/34
        undef :test_PATCH_send_url_encoded_params

        # https://github.com/toland/patron/issues/52
        undef :test_GET_with_body

        # no support for SSL peer verification
        undef :test_GET_ssl_fails_with_bad_cert if ssl_mode?
      end

      def test_custom_adapter_config
        conn = create_connection do |session|
          assert_kind_of ::Patron::Session, session
          session.max_redirects = 10
          throw :config_block_called
        end

        assert_throws(:config_block_called) do
          conn.get 'http://8.8.8.8:88'
        end
      end

      def test_connection_timeout
        conn = create_connection(:request => {:timeout => 10, :open_timeout => 1})
        assert_raises Faraday::ConnectionFailed do
          conn.get 'http://8.8.8.8:88'
        end
      end
    end
  end
end


text:
#include "core/layout/TableLayoutAlgorithmAuto.h"

#include "core/layout/LayoutTable.h"
#include "core/layout/LayoutTableCell.h"
#include "core/layout/LayoutTableCol.h"
#include "core/layout/LayoutTableSection.h"
#include "core/layout/TextAutosizer.h"

namespace blink {

TableLayoutAlgorithmAuto::TableLayoutAlgorithmAuto(LayoutTable* table)
    : TableLayoutAlgorithm(table)
    , m_hasPercent(false)
    , m_effectiveLogicalWidthDirty(true)
{
}

TableLayoutAlgorithmAuto::~TableLayoutAlgorithmAuto()
{
}

void TableLayoutAlgorithmAuto::recalcColumn(unsigned effCol)
{
    Layout& columnLayout = m_layoutStruct[effCol];

    LayoutTableCell* fixedContributor = nullptr;
    LayoutTableCell* maxContributor = nullptr;

    for (LayoutObject* child = m_table->children()->firstChild(); child; child = child->nextSibling()) {
        if (child->isLayoutTableCol()) {
            // LayoutTableCols don't have the concept of preferred logical width, but we need to clear their dirty bits
            // so that if we call setPreferredWidthsDirty(true) on a col or one of its descendants, we'll mark it's
            // ancestors as dirty.
            toLayoutTableCol(child)->clearPreferredLogicalWidthsDirtyBits();
        } else if (child->isTableSection()) {
            LayoutTableSection* section = toLayoutTableSection(child);
            unsigned numRows = section->numRows();
            for (unsigned i = 0; i < numRows; i++) {
                LayoutTableSection::CellStruct current = section->cellAt(i, effCol);
                LayoutTableCell* cell = current.primaryCell();

                if (current.inColSpan || !cell)
                    continue;
                columnLayout.columnHasNoCells = false;

                if (cell->maxPreferredLogicalWidth())
                    columnLayout.emptyCellsOnly = false;

                if (cell->colSpan() == 1) {
                    columnLayout.minLogicalWidth = std::max<int>(cell->minPreferredLogicalWidth(), columnLayout.minLogicalWidth);
                    if (cell->maxPreferredLogicalWidth() > columnLayout.maxLogicalWidth) {
                        columnLayout.maxLogicalWidth = cell->maxPreferredLogicalWidth();
                        maxContributor = cell;
                    }

                    // All browsers implement a size limit on the cell's max width.
                    // Our limit is based on KHTML's representation that used 16 bits widths.
                    // FIXME: Other browsers have a lower limit for the cell's max width.
                    const int cCellMaxWidth = 32760;
                    Length cellLogicalWidth = cell->styleOrColLogicalWidth();
                    // FIXME: calc() on tables should be handled consistently with other lengths. See bug: https://crbug.com/382725
                    if (cellLogicalWidth.isCalculated())
                        cellLogicalWidth = Length(); // Make it Auto
                    if (cellLogicalWidth.value() > cCellMaxWidth)
                        cellLogicalWidth.setValue(cCellMaxWidth);
                    if (cellLogicalWidth.isNegative())
                        cellLogicalWidth.setValue(0);
                    switch (cellLogicalWidth.type()) {
                    case Fixed:
                        // ignore width=0
                        if (cellLogicalWidth.isPositive() && !columnLayout.logicalWidth.hasPercent()) {
                            int logicalWidth = cell->adjustBorderBoxLogicalWidthForBoxSizing(cellLogicalWidth.value());
                            if (columnLayout.logicalWidth.isFixed()) {
                                // Nav/IE weirdness
                                if ((logicalWidth > columnLayout.logicalWidth.value())
                                    || ((columnLayout.logicalWidth.value() == logicalWidth) && (maxContributor == cell))) {
                                    columnLayout.logicalWidth.setValue(Fixed, logicalWidth);
                                    fixedContributor = cell;
                                }
                            } else {
                                columnLayout.logicalWidth.setValue(Fixed, logicalWidth);
                                fixedContributor = cell;
                            }
                        }
                        break;
                    case Percent:
                        m_hasPercent = true;
                        // TODO(alancutter): Make this work correctly for calc lengths.
                        if (cellLogicalWidth.isPositive() && (!columnLayout.logicalWidth.hasPercent() || cellLogicalWidth.value() > columnLayout.logicalWidth.value()))
                            columnLayout.logicalWidth = cellLogicalWidth;
                        break;
                    default:
                        break;
                    }
                } else if (!effCol || section->primaryCellAt(i, effCol - 1) != cell) {
                    // If a cell originates in this spanning column ensure we have a min/max width of at least 1px for it.
                    columnLayout.minLogicalWidth = std::max<int>(columnLayout.minLogicalWidth, cell->maxPreferredLogicalWidth() ? 1 : 0);

                    // This spanning cell originates in this column. Insert the cell into spanning cells list.
                    insertSpanCell(cell);
                }
            }
        }
    }

    // Nav/IE weirdness
    if (columnLayout.logicalWidth.isFixed()) {
        if (m_table->document().inQuirksMode() && columnLayout.maxLogicalWidth > columnLayout.logicalWidth.value() && fixedContributor != maxContributor) {
            columnLayout.logicalWidth = Length();
            fixedContributor = nullptr;
        }
    }

    columnLayout.maxLogicalWidth = std::max(columnLayout.maxLogicalWidth, columnLayout.minLogicalWidth);
}

void TableLayoutAlgorithmAuto::fullRecalc()
{
    m_hasPercent = false;
    m_effectiveLogicalWidthDirty = true;

    unsigned nEffCols = m_table->numEffCols();
    m_layoutStruct.resize(nEffCols);
    m_layoutStruct.fill(Layout());
    m_spanCells.fill(0);

    Length groupLogicalWidth;
    unsigned currentColumn = 0;
    for (LayoutTableCol* column = m_table->firstColumn(); column; column = column->nextColumn()) {
        if (column->isTableColumnGroupWithColumnChildren()) {
            groupLogicalWidth = column->style()->logicalWidth();
        } else {
            Length colLogicalWidth = column->style()->logicalWidth();
            // FIXME: calc() on tables should be handled consistently with other lengths. See bug: https://crbug.com/382725
            if (colLogicalWidth.isCalculated() || colLogicalWidth.isAuto())
                colLogicalWidth = groupLogicalWidth;
            // TODO(alancutter): Make this work correctly for calc lengths.
            if ((colLogicalWidth.isFixed() || colLogicalWidth.hasPercent()) && colLogicalWidth.isZero())
                colLogicalWidth = Length();
            unsigned effCol = m_table->colToEffCol(currentColumn);
            unsigned span = column->span();
            if (!colLogicalWidth.isAuto() && span == 1 && effCol < nEffCols && m_table->spanOfEffCol(effCol) == 1) {
                m_layoutStruct[effCol].logicalWidth = colLogicalWidth;
                if (colLogicalWidth.isFixed() && m_layoutStruct[effCol].maxLogicalWidth < colLogicalWidth.value())
                    m_layoutStruct[effCol].maxLogicalWidth = colLogicalWidth.value();
            }
            currentColumn += span;
        }

        // For the last column in a column-group, we invalidate our group logical width.
        if (column->isTableColumn() && !column->nextSibling())
            groupLogicalWidth = Length();
    }

    for (unsigned i = 0; i < nEffCols; i++)
        recalcColumn(i);
}

// FIXME: This needs to be adapted for vertical writing modes.
static bool shouldScaleColumns(LayoutTable* table)
{
    // A special case.  If this table is not fixed width and contained inside
    // a cell, then don't bloat the maxwidth by examining percentage growth.
    bool scale = true;
    while (table) {
        Length tw = table->style()->width();
        if ((tw.isAuto() || tw.hasPercent()) && !table->isOutOfFlowPositioned()) {
            LayoutBlock* cb = table->containingBlock();
            while (cb && !cb->isLayoutView() && !cb->isTableCell()
                && cb->style()->width().isAuto() && !cb->isOutOfFlowPositioned())
                cb = cb->containingBlock();

            table = 0;
            if (cb && cb->isTableCell()
                && (cb->style()->width().isAuto() || cb->style()->width().hasPercent())) {
                LayoutTableCell* cell = toLayoutTableCell(cb);
                if (cell->colSpan() > 1 || cell->table()->style()->width().isAuto())
                    scale = false;
                else
                    table = cell->table();
            }
        } else {
            table = 0;
        }
    }
    return scale;
}

void TableLayoutAlgorithmAuto::computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth)
{
    TextAutosizer::TableLayoutScope textAutosizerTableLayoutScope(m_table);

    fullRecalc();

    int spanMaxLogicalWidth = calcEffectiveLogicalWidth();
    minWidth = 0;
    maxWidth = 0;
    float maxPercent = 0;
    float maxNonPercent = 0;
    bool scaleColumns = shouldScaleColumns(m_table);

    // We substitute 0 percent by (epsilon / percentScaleFactor) percent in two places below to avoid division by zero.
    // FIXME: Handle the 0% cases properly.
    const float epsilon = 1 / 128.0f;

    float remainingPercent = 100;
    for (size_t i = 0; i < m_layoutStruct.size(); ++i) {
        minWidth += m_layoutStruct[i].effectiveMinLogicalWidth;
        maxWidth += m_layoutStruct[i].effectiveMaxLogicalWidth;
        if (scaleColumns) {
            if (m_layoutStruct[i].effectiveLogicalWidth.hasPercent()) {
                float percent = std::min(static_cast<float>(m_layoutStruct[i].effectiveLogicalWidth.percent()), remainingPercent);
                float logicalWidth = static_cast<float>(m_layoutStruct[i].effectiveMaxLogicalWidth) * 100 / std::max(percent, epsilon);
                maxPercent = std::max(logicalWidth,  maxPercent);
                remainingPercent -= percent;
            } else {
                maxNonPercent += m_layoutStruct[i].effectiveMaxLogicalWidth;
            }
        }
    }

    if (scaleColumns) {
        maxNonPercent = maxNonPercent * 100 / std::max(remainingPercent, epsilon);
        maxWidth = std::max<int>(maxWidth, static_cast<int>(std::min(maxNonPercent, static_cast<float>(tableMaxWidth))));
        maxWidth = std::max<int>(maxWidth, static_cast<int>(std::min(maxPercent, static_cast<float>(tableMaxWidth))));
    }

    maxWidth = std::max<int>(maxWidth, spanMaxLogicalWidth);
}

void TableLayoutAlgorithmAuto::applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const
{
    Length tableLogicalWidth = m_table->style()->logicalWidth();
    if (tableLogicalWidth.isFixed() && tableLogicalWidth.isPositive()) {
        // |minWidth| is the result of measuring the intrinsic content's size. Keep it to
        // make sure we are *never* smaller than the actual content.
        LayoutUnit minContentWidth = minWidth;
        // FIXME: This line looks REALLY suspicious as it could allow the minimum
        // preferred logical width to be smaller than the table content. This has
        // to be cross-checked against other browsers.
        minWidth = maxWidth = std::max<int>(minWidth, tableLogicalWidth.value());

        const Length& styleMaxLogicalWidth = m_table->style()->logicalMaxWidth();
        if (styleMaxLogicalWidth.isFixed() && !styleMaxLogicalWidth.isNegative()) {
            minWidth = std::min<int>(minWidth, styleMaxLogicalWidth.value());
            minWidth = std::max(minWidth, minContentWidth);
            maxWidth = minWidth;
        }
    }
}

/*
  This method takes care of colspans.
  effWidth is the same as width for cells without colspans. If we have colspans, they get modified.
 */
int TableLayoutAlgorithmAuto::calcEffectiveLogicalWidth()
{
    int maxLogicalWidth = 0;

    size_t nEffCols = m_layoutStruct.size();
    int spacingInRowDirection = m_table->hBorderSpacing();

    for (size_t i = 0; i < nEffCols; ++i) {
        m_layoutStruct[i].effectiveLogicalWidth = m_layoutStruct[i].logicalWidth;
        m_layoutStruct[i].effectiveMinLogicalWidth = m_layoutStruct[i].minLogicalWidth;
        m_layoutStruct[i].effectiveMaxLogicalWidth = m_layoutStruct[i].maxLogicalWidth;
    }

    for (size_t i = 0; i < m_spanCells.size(); ++i) {
        LayoutTableCell* cell = m_spanCells[i];
        if (!cell)
            break;

        unsigned span = cell->colSpan();

        Length cellLogicalWidth = cell->styleOrColLogicalWidth();
        // FIXME: calc() on tables should be handled consistently with other lengths. See bug: https://crbug.com/382725
        if (cellLogicalWidth.isZero() || cellLogicalWidth.isCalculated())
            cellLogicalWidth = Length(); // Make it Auto

        unsigned effCol = m_table->colToEffCol(cell->col());
        size_t lastCol = effCol;
        int cellMinLogicalWidth = cell->minPreferredLogicalWidth() + spacingInRowDirection;
        int cellMaxLogicalWidth = cell->maxPreferredLogicalWidth() + spacingInRowDirection;
        float totalPercent = 0;
        int spanMinLogicalWidth = 0;
        int spanMaxLogicalWidth = 0;
        bool allColsArePercent = true;
        bool allColsAreFixed = true;
        bool haveAuto = false;
        bool spanHasEmptyCellsOnly = true;
        int fixedWidth = 0;
        while (lastCol < nEffCols && span > 0) {
            Layout& columnLayout = m_layoutStruct[lastCol];
            switch (columnLayout.logicalWidth.type()) {
            case Percent:
                totalPercent += columnLayout.logicalWidth.percent();
                allColsAreFixed = false;
                break;
            case Fixed:
                if (columnLayout.logicalWidth.value() > 0) {
                    fixedWidth += columnLayout.logicalWidth.value();
                    allColsArePercent = false;
                    // IE resets effWidth to Auto here, but this breaks the konqueror about page and seems to be some bad
                    // legacy behaviour anyway. mozilla doesn't do this so I decided we don't neither.
                    break;
                }
                // fall through
            case Auto:
                haveAuto = true;
                // fall through
            default:
                // If the column is a percentage width, do not let the spanning cell overwrite the
                // width value.  This caused a mis-layout on amazon.com.
                // Sample snippet:
                //
<
                //
1	2-3

                //
1	2-3

                //

                // TODO(alancutter): Make this work correctly for calc lengths.
                if (!columnLayout.effectiveLogicalWidth.hasPercent()) {
                    columnLayout.effectiveLogicalWidth = Length();
                    allColsArePercent = false;
                } else {
                    totalPercent += columnLayout.effectiveLogicalWidth.percent();
                }
                allColsAreFixed = false;
            }
            if (!columnLayout.emptyCellsOnly)
                spanHasEmptyCellsOnly = false;
            span -= m_table->spanOfEffCol(lastCol);
            spanMinLogicalWidth += columnLayout.effectiveMinLogicalWidth;
            spanMaxLogicalWidth += columnLayout.effectiveMaxLogicalWidth;
            lastCol++;
            cellMinLogicalWidth -= spacingInRowDirection;
            cellMaxLogicalWidth -= spacingInRowDirection;
        }

        // adjust table max width if needed
        if (cellLogicalWidth.hasPercent()) {
            if (totalPercent > cellLogicalWidth.percent() || allColsArePercent) {
                // can't satify this condition, treat as variable
                cellLogicalWidth = Length();
            } else {
                maxLogicalWidth = std::max(maxLogicalWidth, static_cast<int>(std::max(spanMaxLogicalWidth, cellMaxLogicalWidth) * 100  / cellLogicalWidth.percent()));

                // all non percent columns in the span get percent values to sum up correctly.
                float percentMissing = cellLogicalWidth.percent() - totalPercent;
                int totalWidth = 0;
                for (unsigned pos = effCol; pos < lastCol; ++pos) {
                    if (!m_layoutStruct[pos].effectiveLogicalWidth.hasPercent())
                        totalWidth += m_layoutStruct[pos].clampedEffectiveMaxLogicalWidth();
                }

                for (unsigned pos = effCol; pos < lastCol && totalWidth > 0; ++pos) {
                    if (!m_layoutStruct[pos].effectiveLogicalWidth.hasPercent()) {
                        float percent = percentMissing * static_cast<float>(m_layoutStruct[pos].effectiveMaxLogicalWidth) / totalWidth;
                        totalWidth -= m_layoutStruct[pos].clampedEffectiveMaxLogicalWidth();
                        percentMissing -= percent;
                        if (percent > 0)
                            m_layoutStruct[pos].effectiveLogicalWidth.setValue(Percent, percent);
                        else
                            m_layoutStruct[pos].effectiveLogicalWidth = Length();
                    }
                }
            }
        }

        // make sure minWidth and maxWidth of the spanning cell are honoured
        if (cellMinLogicalWidth > spanMinLogicalWidth) {
            if (allColsAreFixed) {
                for (unsigned pos = effCol; fixedWidth > 0 && pos < lastCol; ++pos) {
                    int cellLogicalWidth = std::max(m_layoutStruct[pos].effectiveMinLogicalWidth, static_cast<int>(cellMinLogicalWidth * m_layoutStruct[pos].logicalWidth.value() / fixedWidth));
                    fixedWidth -= m_layoutStruct[pos].logicalWidth.value();
                    cellMinLogicalWidth -= cellLogicalWidth;
                    m_layoutStruct[pos].effectiveMinLogicalWidth = cellLogicalWidth;
                }
            } else if (allColsArePercent) {
                // In this case, we just split the colspan's min amd max widths following the percentage.
                int allocatedMinLogicalWidth = 0;
                int allocatedMaxLogicalWidth = 0;
                for (unsigned pos = effCol; pos < lastCol; ++pos) {
                    // TODO(alancutter): Make this work correctly for calc lengths.
                    ASSERT(m_layoutStruct[pos].logicalWidth.hasPercent() || m_layoutStruct[pos].effectiveLogicalWidth.hasPercent());
                    // |allColsArePercent| means that either the logicalWidth *or* the effectiveLogicalWidth are percents, handle both of them here.
                    float percent = m_layoutStruct[pos].logicalWidth.hasPercent() ? m_layoutStruct[pos].logicalWidth.percent() : m_layoutStruct[pos].effectiveLogicalWidth.percent();
                    int columnMinLogicalWidth = static_cast<int>(percent * cellMinLogicalWidth / totalPercent);
                    int columnMaxLogicalWidth = static_cast<int>(percent * cellMaxLogicalWidth / totalPercent);
                    m_layoutStruct[pos].effectiveMinLogicalWidth = std::max(m_layoutStruct[pos].effectiveMinLogicalWidth, columnMinLogicalWidth);
                    m_layoutStruct[pos].effectiveMaxLogicalWidth = columnMaxLogicalWidth;
                    allocatedMinLogicalWidth += columnMinLogicalWidth;
                    allocatedMaxLogicalWidth += columnMaxLogicalWidth;
                }
                ASSERT(allocatedMinLogicalWidth <= cellMinLogicalWidth);
                ASSERT(allocatedMaxLogicalWidth <= cellMaxLogicalWidth);
                cellMinLogicalWidth -= allocatedMinLogicalWidth;
                cellMaxLogicalWidth -= allocatedMaxLogicalWidth;
            } else {
                int remainingMaxLogicalWidth = spanMaxLogicalWidth;
                int remainingMinLogicalWidth = spanMinLogicalWidth;

                // Give min to variable first, to fixed second, and to others third.
                for (unsigned pos = effCol; remainingMaxLogicalWidth >= 0 && pos < lastCol; ++pos) {
                    if (m_layoutStruct[pos].logicalWidth.isFixed() && haveAuto && fixedWidth <= cellMinLogicalWidth) {
                        int colMinLogicalWidth = std::max<int>(m_layoutStruct[pos].effectiveMinLogicalWidth, m_layoutStruct[pos].logicalWidth.value());
                        fixedWidth -= m_layoutStruct[pos].logicalWidth.value();
                        remainingMinLogicalWidth -= m_layoutStruct[pos].effectiveMinLogicalWidth;
                        remainingMaxLogicalWidth -= m_layoutStruct[pos].effectiveMaxLogicalWidth;
                        cellMinLogicalWidth -= colMinLogicalWidth;
                        m_layoutStruct[pos].effectiveMinLogicalWidth = colMinLogicalWidth;
                    }
                }

                for (unsigned pos = effCol; remainingMaxLogicalWidth >= 0 && pos < lastCol && remainingMinLogicalWidth < cellMinLogicalWidth; ++pos) {
                    if (!(m_layoutStruct[pos].logicalWidth.isFixed() && haveAuto && fixedWidth <= cellMinLogicalWidth)) {
                        int colMinLogicalWidth = std::max<int>(m_layoutStruct[pos].effectiveMinLogicalWidth, static_cast<int>(remainingMaxLogicalWidth ? cellMinLogicalWidth * static_cast<float>(m_layoutStruct[pos].effectiveMaxLogicalWidth) / remainingMaxLogicalWidth : cellMinLogicalWidth));
                        colMinLogicalWidth = std::min<int>(m_layoutStruct[pos].effectiveMinLogicalWidth + (cellMinLogicalWidth - remainingMinLogicalWidth), colMinLogicalWidth);
                        remainingMaxLogicalWidth -= m_layoutStruct[pos].effectiveMaxLogicalWidth;
                        remainingMinLogicalWidth -= m_layoutStruct[pos].effectiveMinLogicalWidth;
                        cellMinLogicalWidth -= colMinLogicalWidth;
                        m_layoutStruct[pos].effectiveMinLogicalWidth = colMinLogicalWidth;
                    }
                }
            }
        }
        if (!cellLogicalWidth.hasPercent()) {
            if (cellMaxLogicalWidth > spanMaxLogicalWidth) {
                for (unsigned pos = effCol; spanMaxLogicalWidth >= 0 && pos < lastCol; ++pos) {
                    int colMaxLogicalWidth = std::max(m_layoutStruct[pos].effectiveMaxLogicalWidth, static_cast<int>(spanMaxLogicalWidth ? cellMaxLogicalWidth * static_cast<float>(m_layoutStruct[pos].effectiveMaxLogicalWidth) / spanMaxLogicalWidth : cellMaxLogicalWidth));
                    spanMaxLogicalWidth -= m_layoutStruct[pos].effectiveMaxLogicalWidth;
                    cellMaxLogicalWidth -= colMaxLogicalWidth;
                    m_layoutStruct[pos].effectiveMaxLogicalWidth = colMaxLogicalWidth;
                }
            }
        } else {
            for (unsigned pos = effCol; pos < lastCol; ++pos)
                m_layoutStruct[pos].maxLogicalWidth = std::max(m_layoutStruct[pos].maxLogicalWidth, m_layoutStruct[pos].minLogicalWidth);
        }
        // treat span ranges consisting of empty cells only as if they had content
        if (spanHasEmptyCellsOnly) {
            for (unsigned pos = effCol; pos < lastCol; ++pos)
                m_layoutStruct[pos].emptyCellsOnly = false;
        }
    }
    m_effectiveLogicalWidthDirty = false;

    return std::min(maxLogicalWidth, INT_MAX / 2);
}

/* gets all cells that originate in a column and have a cellspan > 1
   Sorts them by increasing cellspan
*/
void TableLayoutAlgorithmAuto::insertSpanCell(LayoutTableCell *cell)
{
    ASSERT_ARG(cell, cell && cell->colSpan() != 1);
    if (!cell || cell->colSpan() == 1)
        return;

    unsigned size = m_spanCells.size();
    if (!size || m_spanCells[size-1] != 0) {
        m_spanCells.grow(size + 10);
        for (unsigned i = 0; i < 10; i++)
            m_spanCells[size+i] = 0;
        size += 10;
    }

    // add them in sort. This is a slow algorithm, and a binary search or a fast sorting after collection would be better
    unsigned pos = 0;
    unsigned span = cell->colSpan();
    while (pos < m_spanCells.size() && m_spanCells[pos] && span > m_spanCells[pos]->colSpan())
        pos++;
    memmove(m_spanCells.data()+pos+1, m_spanCells.data()+pos, (size-pos-1)*sizeof(LayoutTableCell *));
    m_spanCells[pos] = cell;
}

void TableLayoutAlgorithmAuto::layout()
{
    // table layout based on the values collected in the layout structure.
    int tableLogicalWidth = m_table->logicalWidth() - m_table->bordersPaddingAndSpacingInRowDirection();
    int available = tableLogicalWidth;
    size_t nEffCols = m_table->numEffCols();

    // FIXME: It is possible to be called without having properly updated our internal representation.
    // This means that our preferred logical widths were not recomputed as expected.
    if (nEffCols != m_layoutStruct.size()) {
        fullRecalc();
        // FIXME: Table layout shouldn't modify our table structure (but does due to columns and column-groups).
        nEffCols = m_table->numEffCols();
    }

    if (m_effectiveLogicalWidthDirty)
        calcEffectiveLogicalWidth();

    bool havePercent = false;
    int numAuto = 0;
    int numFixed = 0;
    float totalAuto = 0;
    float totalFixed = 0;
    float totalPercent = 0;
    int allocAuto = 0;
    unsigned numAutoEmptyCellsOnly = 0;

    // fill up every cell with its minWidth
    for (size_t i = 0; i < nEffCols; ++i) {
        int cellLogicalWidth = m_layoutStruct[i].effectiveMinLogicalWidth;
        m_layoutStruct[i].computedLogicalWidth = cellLogicalWidth;
        available -= cellLogicalWidth;
        Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
        switch (logicalWidth.type()) {
        case Percent:
            havePercent = true;
            totalPercent += logicalWidth.percent();
            break;
        case Fixed:
            numFixed++;
            totalFixed += m_layoutStruct[i].clampedEffectiveMaxLogicalWidth();
            // fall through
            break;
        case Auto:
            if (m_layoutStruct[i].emptyCellsOnly) {
                numAutoEmptyCellsOnly++;
            } else {
                numAuto++;
                totalAuto += m_layoutStruct[i].clampedEffectiveMaxLogicalWidth();
            }
            if (!m_layoutStruct[i].columnHasNoCells)
                allocAuto += cellLogicalWidth;
            break;
        default:
            break;
        }
    }

    // allocate width to percent cols
    if (available > 0 && havePercent) {
        for (size_t i = 0; i < nEffCols; ++i) {
            Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
            if (logicalWidth.hasPercent()) {
                int cellLogicalWidth = std::max<int>(m_layoutStruct[i].effectiveMinLogicalWidth, minimumValueForLength(logicalWidth, tableLogicalWidth));
                available += m_layoutStruct[i].computedLogicalWidth - cellLogicalWidth;
                m_layoutStruct[i].computedLogicalWidth = cellLogicalWidth;
            }
        }
        if (totalPercent > 100) {
            // remove overallocated space from the last columns
            int excess = tableLogicalWidth * (totalPercent - 100) / 100;
            for (unsigned i = nEffCols; i; ) {
                --i;
                if (m_layoutStruct[i].effectiveLogicalWidth.hasPercent()) {
                    int cellLogicalWidth = m_layoutStruct[i].computedLogicalWidth;
                    int reduction = std::min(cellLogicalWidth,  excess);
                    // the lines below might look inconsistent, but that's the way it's handled in mozilla
                    excess -= reduction;
                    int newLogicalWidth = std::max<int>(m_layoutStruct[i].effectiveMinLogicalWidth, cellLogicalWidth - reduction);
                    available += cellLogicalWidth - newLogicalWidth;
                    m_layoutStruct[i].computedLogicalWidth = newLogicalWidth;
                }
            }
        }
    }

    // then allocate width to fixed cols
    if (available > 0) {
        for (size_t i = 0; i < nEffCols; ++i) {
            Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
            if (logicalWidth.isFixed() && logicalWidth.value() > m_layoutStruct[i].computedLogicalWidth) {
                available += m_layoutStruct[i].computedLogicalWidth - logicalWidth.value();
                m_layoutStruct[i].computedLogicalWidth = logicalWidth.value();
            }
        }
    }

    // Give each auto width column its share of the available width, non-empty columns then empty columns.
    if (available > 0 && (numAuto || numAutoEmptyCellsOnly)) {
        available += allocAuto;
        if (numAuto)
            distributeWidthToColumns<float, Auto, NonEmptyCells, InitialWidth, StartToEnd>(available, totalAuto);
        if (numAutoEmptyCellsOnly)
            distributeWidthToColumns<unsigned, Auto, EmptyCells, InitialWidth, StartToEnd>(available, numAutoEmptyCellsOnly);
    }

    // Any remaining available width expands fixed width, percent width, and non-empty auto width columns, in that order.
    if (available > 0 && numFixed)
        distributeWidthToColumns<float, Fixed, AllCells, ExtraWidth, StartToEnd>(available, totalFixed);

    if (available > 0 && m_hasPercent && totalPercent < 100)
        distributeWidthToColumns<float, Percent, AllCells, ExtraWidth, StartToEnd>(available, totalPercent);

    if (available > 0 && nEffCols > numAutoEmptyCellsOnly) {
        unsigned total = nEffCols - numAutoEmptyCellsOnly;
        // Starting from the last cell is for compatibility with FF/IE - it isn't specified anywhere.
        distributeWidthToColumns<unsigned, Auto, NonEmptyCells, LeftoverWidth, EndToStart>(available, total);
    }

    // If we have overallocated, reduce every cell according to the difference between desired width and minwidth
    // this seems to produce to the pixel exact results with IE. Wonder is some of this also holds for width distributing.
    // This is basically the reverse of how we grew the cells.
    if (available < 0)
        shrinkColumnWidth(Auto, available);
    if (available < 0)
        shrinkColumnWidth(Fixed, available);
    if (available < 0)
        shrinkColumnWidth(Percent, available);

    int pos = 0;
    for (size_t i = 0; i < nEffCols; ++i) {
        m_table->setColumnPosition(i, pos);
        pos += m_layoutStruct[i].computedLogicalWidth + m_table->hBorderSpacing();
    }
    m_table->setColumnPosition(m_table->columnPositions().size() - 1, pos);
}

template<typename Total, LengthType lengthType, CellsToProcess cellsToProcess, DistributionMode distributionMode, DistributionDirection distributionDirection>
void TableLayoutAlgorithmAuto::distributeWidthToColumns(int& available, Total total)
{
    // TODO(alancutter): Make this work correctly for calc lengths.
    int nEffCols = static_cast<int>(m_table->numEffCols());
    bool startToEnd = distributionDirection == StartToEnd;
    for (int i = startToEnd ? 0 : nEffCols - 1; startToEnd ? i < nEffCols : i > -1; startToEnd ? ++i : --i) {
        const Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
        if (cellsToProcess == NonEmptyCells && logicalWidth.isAuto() && m_layoutStruct[i].emptyCellsOnly)
            continue;
        // When allocating width to columns with nothing but empty cells we avoid
        // columns that exist only to flesh out a colspan and have no actual cells.
        if (cellsToProcess == EmptyCells && logicalWidth.isAuto() && (!m_layoutStruct[i].emptyCellsOnly || m_layoutStruct[i].columnHasNoCells))
            continue;
        if (distributionMode != LeftoverWidth && logicalWidth.type() != lengthType)
            continue;

        float factor = 1;
        if (distributionMode != LeftoverWidth) {
            if (lengthType == Percent)
                factor = logicalWidth.percent();
            else if (lengthType == Auto || lengthType == Fixed)
                factor = m_layoutStruct[i].clampedEffectiveMaxLogicalWidth();
        }

        int newWidth = available * factor / total;
        int cellLogicalWidth = (distributionMode == InitialWidth) ? max<int>(m_layoutStruct[i].computedLogicalWidth, newWidth) : newWidth;
        available -= cellLogicalWidth;
        total -= factor;
        m_layoutStruct[i].computedLogicalWidth = (distributionMode == InitialWidth) ? cellLogicalWidth : m_layoutStruct[i].computedLogicalWidth + cellLogicalWidth;

        // If we have run out of width to allocate we're done.
        // TODO(rhogan): Extend this to Fixed as well.
        if (lengthType == Percent && (!available || !total))
            return;
        if (lengthType == Auto && !total)
            return;
    }
}

void TableLayoutAlgorithmAuto::shrinkColumnWidth(const LengthType& lengthType, int& available)
{
    size_t nEffCols = m_table->numEffCols();
    int logicalWidthBeyondMin = 0;
    for (unsigned i = nEffCols; i; ) {
        --i;
        Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
        if (logicalWidth.type() == lengthType)
            logicalWidthBeyondMin += m_layoutStruct[i].computedLogicalWidth - m_layoutStruct[i].effectiveMinLogicalWidth;
    }

    for (unsigned i = nEffCols; i && logicalWidthBeyondMin > 0; ) {
        --i;
        Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
        if (logicalWidth.type() == lengthType) {
            int minMaxDiff = m_layoutStruct[i].computedLogicalWidth - m_layoutStruct[i].effectiveMinLogicalWidth;
            int reduce = available * minMaxDiff / logicalWidthBeyondMin;
            m_layoutStruct[i].computedLogicalWidth += reduce;
            available -= reduce;
            logicalWidthBeyondMin -= minMaxDiff;
            if (available >= 0)
                break;
        }
    }
}
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { forwardRef, Provider, Attribute, Directive } from 'angular2/core';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { Validators, NG_VALIDATORS } from '../validators';
import { NumberWrapper } from "angular2/src/facade/lang";
const REQUIRED_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useValue: Validators.required, multi: true }));
/**
 * A Directive that adds the `required` validator to any controls marked with the
 * `required` attribute, via the {@link NG_VALIDATORS} binding.
 *
 * ### Example
 *
 * ```
 * <input ngControl="fullName" required>
 * ```
 */
export let RequiredValidator = class {
};
RequiredValidator = __decorate([
    Directive({
        selector: '[required][ngControl],[required][ngFormControl],[required][ngModel]',
        providers: [REQUIRED_VALIDATOR]
    }),
    __metadata('design:paramtypes', [])
], RequiredValidator);
/**
 * Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
 *
 * ## Example:
 *
 * {@example common/forms/ts/validators/validators.ts region='min'}
 */
const MIN_LENGTH_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MinLengthValidator), multi: true }));
/**
 * A directive which installs the {@link MinLengthValidator} for any `ngControl`,
 * `ngFormControl`, or control with `ngModel` that also has a `minlength` attribute.
 */
export let MinLengthValidator = class {
    constructor(minLength) {
        this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
    }
    validate(c) { return this._validator(c); }
};
MinLengthValidator = __decorate([
    Directive({
        selector: '[minlength][ngControl],[minlength][ngFormControl],[minlength][ngModel]',
        providers: [MIN_LENGTH_VALIDATOR]
    }),
    __param(0, Attribute("minlength")),
    __metadata('design:paramtypes', [String])
], MinLengthValidator);
/**
 * Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}.
 *
 * ## Example:
 *
 * {@example common/forms/ts/validators/validators.ts region='max'}
 */
const MAX_LENGTH_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MaxLengthValidator), multi: true }));
/**
 * A directive which installs the {@link MaxLengthValidator} for any `ngControl, `ngFormControl`,
 * or control with `ngModel` that also has a `maxlength` attribute.
 */
export let MaxLengthValidator = class {
    constructor(maxLength) {
        this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
    }
    validate(c) { return this._validator(c); }
};
MaxLengthValidator = __decorate([
    Directive({
        selector: '[maxlength][ngControl],[maxlength][ngFormControl],[maxlength][ngModel]',
        providers: [MAX_LENGTH_VALIDATOR]
    }),
    __param(0, Attribute("maxlength")),
    __metadata('design:paramtypes', [String])
], MaxLengthValidator);


text:
<?php

/* add the various (yet not existant as of 06/03/2001, nearly though ;) language stuff */
require "lang.php";
require "db_routines.php";

/* unget some bits */
unget($vars["database"]);
unget($vars["table"]);

$db = dbconnect($vars["database"]);

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>MPanel: <?php echo _ADDNEWFIELD_; ?></title>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">

<link rel="stylesheet" href="style.css">

<?php echo _ADDNEWFIELD_; ?>

<?php echo _BACK_; ?>

<td class="td_nav" align="center" onClick="javascript:top.location.href='main.php?database=<?php echo urlencode($vars["database"]); ?>';"><a class="a_nav" href="main.php?database=<?php echo urlencode($vars["database"]); ?>"><?php echo _BACKTOMAINPAGE_; ?>

<?php echo _HELPPAGE_; ?>

<form action="addfield_.php" method="post" name="main">

<?php echo _ADDFIELDINFO_; ?>

<?php echo _FIELDNAME_; ?>	<input type="text" name="name" size="30">

<?php echo _FIELDTYPE_; ?>	<select name="ftype" OnChange="javascript:document.main.fsize.value=alter_size();">
<option value="TINYINT"><?php echo _TINYINT_; ?></option>
<option value="SMALLINT"><?php echo _SMALLINT_; ?></option>
<option value="MEDIUMINT"><?php echo _MEDIUMINT_; ?></option>
<option value="INT"><?php echo _INT_; ?></option>
<option value="BIGINT"><?php echo _BIGINT_; ?></option>
<option value="FLOAT"><?php echo _FLOAT_; ?> (M, D)</option>
<option value="DOUBLE"><?php echo _DOUBLE_; ?> (M, D)</option>
<option value="DECIMAL"><?php echo _DECIMAL_; ?> (M, D)</option>
<option value="CHAR"><?php echo _CHAR_; ?></option>
<option value="VARCHAR"><?php echo _VARCHAR_; ?></option>
<option value="TINYTEXT"><?php echo _TINYTEXT_; ?></option>
<option value="TINYBLOB"><?php echo _TINYBLOB_; ?></option>
<option value="ENUM"><?php echo _ENUM_; ?></option>
<option value="TEXT"><?php echo _TEXT_; ?></option>
<option value="BLOB"><?php echo _BLOB_; ?></option>
<option value="MEDIUMTEXT"><?php echo _MEDIUMTEXT_; ?></option>
<option value="MEDIUMBLOB"><?php echo _MEDIUMBLOB_; ?></option>
<option value="LONGTEXT"><?php echo _LONGTEXT_; ?></option>
<option value="LONGBLOB"><?php echo _LONGBLOB_; ?></option>
<option value="DATETIME"><?php echo _DATETIME_; ?></option>
<option value="DATE"><?php echo _DATE_; ?></option>
<option value="TIME"><?php echo _TIME_; ?></option>
<option value="YEAR"><?php echo _YEAR_; ?></option>
<option value="TIMESTAMP"><?php echo _TIMESTAMP_; ?></option>
</select> (<input type="text" name="fsize" value="1" size="10">)

<?php echo _MODIFIERS_; ?>
<input type="checkbox" name="isauto_increment" value="1">AUTO_INCREMENT (All INT types)

<input type="checkbox" name="isbinary" value="1">BINARY (CHAR, VARCHAR)

<input type="checkbox" name="isnot_null" value="1">NOT NULL (All types)

<input type="checkbox" name="isprimary_key" value="1">PRIMARY KEY (All types)

<input type="checkbox" name="isunsigned" value="1">UNSIGNED (Numeric types)

<input type="checkbox" name="iszerofill" value="1">ZERO FILL (Numeric types)

<input type="text" name="isdefault" value="" size="10">DEFAULT (All, except BLOB, TEXT)
<input type="hidden" name="database" value=<?php echo tag($vars["database"]); ?>>
<input type="hidden" name="table" value=<?php echo tag($vars["table"]); ?>>

<?php
        $q = @mysql_query("DESC ".$vars["table"]);
        if(@mysql_num_rows($q) > 1) {
?>

<?php echo _ADDFIELDAFTER_; ?>	<select name="putafter"><option value=""><?php echo _TABLEEND_; ?></option><?php
		while(list($tablename) = @mysql_fetch_row($q)) {
			echo "<option value=", tag($tablename), ">", $tablename, "</option>\n";
		}
?></select>

<?php
	} else {
		echo "<input type=\"hidden\" name=\"putafter\" value=\"\">\n";
	}
?>

<input type="submit" value=<?php echo tag(_OK_); ?>>

</form>


text:
using System;
using UnityEngine;

namespace DefaultNamespace
{
  public class CommonTest : MonoBehaviour
  {
    private Action action = AnotherMethodName;

    private static void AnotherMethodName()
    {
      var test = new CommonTest();
      test.AnotherMethodNameA();
    }

    private void AnotherMethodNameA()
    {
      Test();

      void F()
      {
        GetComponent<CommonTest>();
      }

      void Test()
      {
        F();
      }
    }

    private void Update()
    {
      action();
    }
  }
}