text:
Radio Thermostat
----------------

The **RadioThermostat** Smart Device handler allows you to connect
[Filtrete 3M-50](http://www.radiothermostat.com/filtrete/products/3M-50/)
WiFi thermostat to the [SmartThings](http://www.smartthings.com) home
automation system.

![Filtrete 3M-50](http://statusbits.github.io/images/Filtrete_3M50.jpg)

Here's a screenshot of the **RadioThermostat** device running inside the
SmartThings iPhone mobile app.

![RadioThermostat Screenshot](http://statusbits.github.io/images/RadioThermostat.jpg)

---

[![PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=ATTTMV7JV2W9W)

*If you enjoy using this software, please show your appreciation by making a small
donation. Thank you for your support!*

---

### Requirements

1. Your Wi-Fi thermostat must be connected to the same local network (LAN) as
your SmartThings hub.
2. It is important that the thermostat's IP address remain unchanged even if
your router is rebooted. This can be accomplished by using your router's
"reserved IP address" feature. Please consult your web router manual on how to
reserve an IP address.
3. Obviously, you need a functioning Internet connection for your hub to
communicate with the SmartThings cloud.

### Installation

**Note:** RadioThermostat is a SmartThings *device handler*. Installing custom
device is a two-step process -- first, you need to install and self-publish
the SmartDevice *Type*, then you need to create an instance of the new
SmartDevice. Both steps must be performed in the SmartThings Web-based
[IDE](https://graph.api.smartthings.com).

**1. Installing RadioThermostat SmartDevice Type**

1. Open [SmartThings IDE](https://graph.api.smartthings.com) in your web
browser and log into your account.
2. Click on the "My Device Types" section in the navigation bar (or open the
[SmartDevices](https://graph.api.smartthings.com/ide/devices) page).
3. On the "\<Your Name\>'s Device Types" page, click on the "+ New SmartDevice"
button on the right.
4. On the "New SmartDevice" page, fill out the mandatory "Name" field. It does
not matter what you type in the name field since it will be overwritten in the
next step anyway. Click the blue "Create" button at the bottom of the page. An
IDE editor window containing device handler template should now open.
5. Copy the **RadioThermostat**
[source code](https://raw.githubusercontent.com/statusbits/smartthings/master/devicetypes/statusbits/radio-thermostat.src/radio-thermostat.groovy)
from GitHub and paste it into the IDE editor window (see previous step). Make
sure you *completely overwrite* contents of the editor window with the source
code copied from the GitHub.
6. Click the blue "Save" button above the editor window.
7. Click the "Publish" button next to it and select "For Me". You have now
self-published your smart device handler.

**2. Installing RadioThermostat SmartDevice**

1. In the [SmartThings IDE](https://graph.api.smartthings.com), click on the
"My Devices" section (or open the [Device List](https://graph.api.smartthings.com/device/list)
page).
2. On the "Device List" page, click on the "+ New Device" button on the right.
3. On the "Create Device" page, enter device name in the mandatory "Name"
field. You can use any name here, for example "Radio Thermostat".
4. Optionally, enter device label in the "Label" field. This is the actual
label that will displayed in the SmartThings mobile app.
5. Fill in the mandatory "Device Network Id" filed. You can enter any string
or number here, since it will be overwritten by the device handler anyway.
6. In the mandatory "Type" field, select "Radio Thermostat" from the drop-down
list.
7. In the mandatory "Version" field, select "Published" from the drop-down
list.
8. In the "Location" field, select location where you want to install new
device.
9. In the "Hub" filed, select the name of your SmartThings hub.
10. Click the blue "Create" button at the bottom of the page.

**3. Refresh Device List in SmartThings Mobile App**

1. Open the SmartThings app on your mobile device, go to the Dashboard and
*log out* of your SmartThings account.
2. Exit and *restart* the SmartThings mobile app.
3. Log back in into your SmartThings account. A new RadioThermostat device
should now appear on the "Things" page.

### Known Issues

None. Please note that as of version 2.0.0, the RadioThermostat device handler
performs polling automatcally and does not require Pollster. :=)

### Revision History

**Version 2.0.1. Released 12/20/2016**
* Fixed iOS mobile app crash when opening newly installed device (Issue #18).
* Fixed error saving settings in Android mobile app.
* Removed secondary control ("Hold" status) from the multi-atibute tile.
* Refresh button now shows connection status: Green - connected, Red -
disconnected.

**Version 2.0.0. Released 12/17/2016**
* Completely redesigned UI using new multi-attribute tile.
* Implemented automatic polling. Pollster is no longer required.
* Check for upper and lower temperature limits when setting heating and
cooling setpoints.

**Version 1.0.3. Released 08/25/2015**
* Fixed an issue with DNI not being updated.

### License

Copyright © 2014 Statusbits.com

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
for more details.

You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.


text:
#ifndef MATRIXLEARNING_H
#define MATRIXLEARNING_H

#include <vector>

#include <mdp/action_impl.h>
#include <mdp/state.h>
#include "learningStrategy.h"

namespace Mdp
{
struct Context;

class MatrixLearning : public LearningStrategy
{
public:
	static constexpr const char *configKey = "matrixLearning";
public:
	MatrixLearning(std::shared_ptr<Context> context);
	void initializeModel();
	void updateModel();
private:
	void updateMatrix();

	state_t previousState;
	action_t previousAction;
	std::vector<std::vector<std::vector<int>>> occurences;
	int nbOfUpdates{0};
};

}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace common\models;

use common\models\query\TagQuery;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%tag}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $frequency
 *
 * @property ProductTag[] $productTags
 * @property Product[] $products
 */
class Tag extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%tag}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'frequency'], 'required'],
            [['frequency'], 'integer'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'frequency' => 'Frequency',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductTags()
    {
        return $this->hasMany(ProductTag::className(), ['tag_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProducts()
    {
        return $this->hasMany(Product::className(), ['id' => 'product_id'])->viaTable('{{%product_tag}}', ['tag_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return TagQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new TagQuery(get_called_class());
    }
}


text:
export function on(elem, type, cb) {
	if (!elem) return console.warn('element not exists');
	if (elem.addEventListener)
		elem.addEventListener(type, cb, false);
	else if (elem.attachEvent)
		elem.attachEvent('on' + type, cb);

	return cb;
}
export function off(elem, type, cb) {
	if (!elem) return console.warn('element not exists');
	if (elem.removeEventListener)
		elem.removeEventListener(type, cb, false);
	else if (elem.detachEvent)
		elem.detachEvent('on' + type, cb);
}
export function createEl(tag='div', attrs = {}, props = {}) {
	var el = document.createElement(tag);
	for (let k in attrs) {
		if (!attrs.hasOwnProperty(k)) continue;

		var attr = attrs[k];
		if (attr === null)
			el.removeAttribute(attr);
		else
			el.setAttribute(k, attr);
	}
	for (let k in props) {
		if (!props.hasOwnProperty(k)) continue;

		el[k] = props[k];
	}
	return el;
}
export function get(id) {
	return document.getElementById(id);
}
export function addClass(elem, classToAdd) {
	if (elem.classList)
		elem.classList.add(classToAdd);
	else if (!hasClass(elem, classToAdd))
		elem.className = elem.className + ' ' + classToAdd;
}
export function removeClass(elem, classToRemove) {
	if (elem.classList)
		elem.classList.remove(classToRemove);
	else
		elem.className = elem.className.replace(classRegExp(classToRemove), ' ');
}
export function toggleClass(elem, classToToggle, assert) {
	assert ? addClass(elem, classToToggle) : removeClass(elem, classToToggle);
}
export function hasClass(elem, classToCheck) {
	if (elem.classList)
		return elem.classList.contains(classToCheck);
	else
		return classRegExp(classToCheck).test(elem.className);
}
function classRegExp(className) {
	return new RegExp('(^|\\s)' + className + '($|\\s)');
}
/**
 * Offset Left
 * getBoundingClientRect technique from
 * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
 *
 * @function findElPosition
 * @param {Element} el Element from which to get offset
 * @return {Object}
 */
export function findElPosition(el) {
	let box;

	if (el.getBoundingClientRect && el.parentNode) {
		box = el.getBoundingClientRect();
	}

	if (!box) {
		return {
			left: 0,
			top: 0
		};
	}

	const docEl = document.documentElement;
	const body = document.body;

	const clientLeft = docEl.clientLeft || body.clientLeft || 0;
	const scrollLeft = window.pageXOffset || body.scrollLeft;
	const left = box.left + scrollLeft - clientLeft;

	const clientTop = docEl.clientTop || body.clientTop || 0;
	const scrollTop = window.pageYOffset || body.scrollTop;
	const top = box.top + scrollTop - clientTop;

	// Android sometimes returns slightly off decimal values, so need to round
	return {
		left: Math.round(left),
		top: Math.round(top)
	};
}
/**
 * Get pointer position in element
 * Returns an object with x and y coordinates.
 * The base on the coordinates are the bottom left of the element.
 *
 * @function getPointerPosition
 * @param {Element} el Element on which to get the pointer position on
 * @param {Event} event Event object
 * @return {Object} This object will have x and y coordinates corresponding to the mouse position
 */
export function getPointerPosition(el, event, pos) {
	let position = {};
	let box = pos || findElPosition(el);
	let boxW = el.offsetWidth;
	let boxH = el.offsetHeight;

	let boxY = box.top;
	let boxX = box.left;
	let pageY = event.pageY || event.clientY;
	let pageX = event.pageX || event.clientX;

	if (event.changedTouches) {
		pageX = event.changedTouches[0].pageX;
		pageY = event.changedTouches[0].pageY;
	}

	position.y = Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH));
	position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));

	return position;
}

export function loadScript(src, callback, attrs) {
	var tag = document.createElement("script");

	tag.onload = tag.onreadystatechange = function() {
		if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
			if (typeof callback == "function") {
				callback();
			}
			tag.onload = tag.onreadystatechange = null;

			if (tag.parentNode) {
				tag.parentNode.removeChild(tag);
			}
		}
	};
	if(attrs){
		for (let k in attrs) {
			if (!attrs.hasOwnProperty(k)) continue;
			var attr = attrs[k];
			if (attr === null)
				tag.removeAttribute(attr);
			else
				tag.setAttribute(k, attr);
		}
	}
	tag.src = src;
	document.getElementsByTagName("head")[0].appendChild(tag);
	//document.getElementsByTagName("body")[0].appendChild(tag);
}

export function getViewportSize(){
	var doc = document;
	var docE = doc.documentElement;
	var body = doc.body;
	return {
		'width': (docE && docE.clientWidth) || (body && body.offsetWidth) || window.innerWidth || 0,
		'height': (docE && docE.clientHeight) || (body && body.offsetHeight) || window.innerHeight || 0
	};
}


text:
<? include("../function/db.php");?>
<?
//Check access
admin_panel_access("settings_watermark");

if($_FILES['watermark']['size']>0)
{
	if(2048*1024>=$_FILES['watermark']['size'])
	{
		if(strtolower(get_file_info($_FILES['watermark']['name'],"extention"))=="png")
		{
			move_uploaded_file($_FILES['watermark']['tmp_name'],$DOCUMENT_ROOT.site_upload_directory."/watermark.png");

			$sql="update settings set svalue='".site_root.site_upload_directory."/watermark.png' where setting_key='watermark_photo'";
			$db->execute($sql);
		}
	}
}

$sql="update settings set svalue=".(int)$_POST["position"]." where setting_key='watermark_position'";
$db->execute($sql);

$db->close();

header("location:watermark.php");

?>


text:
Conductor.card({
  activate: function () {
    var card = this;
    card.consumers.height.autoUpdate = false;

    setTimeout( function () {
      var bigNode = document.createElement("div");
      bigNode.style.width = "600px";
      bigNode.style.height = "700px";

      document.body.style.padding = "1px";
      document.body.style.margin = "2px";
      document.body.style.border = "solid transparent 4px";
      document.body.appendChild(bigNode);
      card.consumers.assertion.send('go');
    });
  }
});


text:
asynctest(
  'browser.tinymce.plugins.codesample.CodeSampleSanityTest',

  [
    'ephox.agar.api.ApproxStructure',
    'ephox.agar.api.Pipeline',
    'ephox.agar.api.RawAssertions',
    'ephox.agar.api.Step',
    'ephox.agar.api.Waiter',
    'ephox.mcagar.api.TinyApis',
    'ephox.mcagar.api.TinyLoader',
    'ephox.mcagar.api.TinyUi',
    'tinymce.plugins.codesample.Plugin',
    'tinymce.themes.modern.Theme'
  ],

  function (
    ApproxStructure, Pipeline, RawAssertions, Step, Waiter, TinyApis, TinyLoader, TinyUi,
    CodePlugin, ModernTheme
  ) {
    var success = arguments[arguments.length - 2];
    var failure = arguments[arguments.length - 1];

    CodePlugin();
    ModernTheme();

    var sInsertTextareaContent = function (value) {
      return Step.sync(function () {
        var textarea = document.querySelector('div[role="dialog"] textarea');
        textarea.value = value;
      });
    };

    TinyLoader.setup(function (editor, onSuccess, onFailure) {
      var tinyUi = TinyUi(editor);
      var tinyApis = TinyApis(editor);

      Pipeline.async({}, [
        tinyUi.sClickOnToolbar('click code button', 'div[aria-label="Insert/Edit code sample"] button'),
        tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"]'),
        sInsertTextareaContent('
a
'),
        tinyUi.sClickOnUi('click OK btn', 'div.mce-primary button'),
        Waiter.sTryUntil('assert content',
          tinyApis.sAssertContentStructure(ApproxStructure.build(function (s, str) {
            return s.element('body', {
              children: [
                s.element('pre', {
                  attrs: {
                    contenteditable: str.is('false')
                  }
                }),
                s.anything()
              ]
            });
          })), 100, 3000)
      ], onSuccess, onFailure);
    }, {
      plugins: 'codesample',
      toolbar: 'codesample',
      skin_url: '/project/src/skins/lightgray/dist/lightgray'
    }, success, failure);
  }
);


text:
/* jshint -W117, -W030, -W106, -W109 */
describe("query_single_condition:", function () {
    'use strict';

    ash.serverIsRunningPrecondition();

    var em;
    var EntityQuery = breeze.EntityQuery;
    var gotResults = ash.gotResults;
    var gotNoResults = ash.gotNoResults;
    var newEm = ash.newEmFactory(ash.northwindServiceName);

    beforeEach(function () {
        em = newEm(); // fresh EntityManager before each test
    });

    ///////////////////////////

    it("where ID equals", function (done) {
        // Prefer EntityManager.fetchEntityByKey or EntityQuery.fromEntityKey; see below
        EntityQuery.from('Customers')
            .where('CustomerID', '==', ash.alfredsID)

            // Filter query operation alternatives
            // see http://www.breezejs.com/sites/all/apidocs/classes/FilterQueryOp.html
            // .where('CustomerID', 'eq', ash.alfredsID)
            // .where('CustomerID', breeze.FilterQueryOp.Equals, ash.alfredsID)

            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            expect(data.results).has.length(1); // exactly one result
            var customer = data.results[0] || {};
            expect(customer).has.property('CompanyName').that.match(/alfreds/i);
        }
    });

    it("where query can return no results as an empty array", function (done) {
        EntityQuery.from('Customers')
            .where('CustomerID', '==', ash.emptyGuid)
            .using(em).execute()
            .then(gotNoResults).then(done, done);
    });

    it("where string property startsWith", function (done) {
        EntityQuery.from('Customers')

            .where('CompanyName', 'startsWith', 'A')
            // .where('CompanyName', breeze.FilterQueryOp.StartsWith, 'A')

            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function (c) {
                var name = c.CompanyName;
                expect(name).to.match(/^[aA]/,
                  'CompanyName {0} does not start with "A"'.format(name));
            });
        }
    });

    it("where numeric property greaterThan", function (done) {
        EntityQuery.from('Orders')

            .where('Freight', '>', 100)
            // .where('Freight', breeze.FilterQueryOp.GreaterThan, 0)

            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function (o) {
                expect(o.Freight).to.be.above(100,
                    'Freight of order {0} to {1} is {2}'
                        .format(o.OrderID, o.ShipName, o.Freight));
            });
        }
    });

    it("where date property is on or after", function (done) {

        // Make sure date is in UTC (like the datetimes in the database)
        // testDate is 1/1/1998 at midnight GMT
        var testDate = new Date(Date.UTC(1998, 0, 1)); // month counts from zero!

        EntityQuery.from('Orders')

            .where('OrderDate', '>=', testDate)
            // .where('Freight', breeze.FilterQueryOp.GreaterThanOrEqual, testDate)

            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function (o) {
                expect(o.OrderDate).to.be.at.least(testDate,
                    'OrderDate of order {0} to {1} is {2}'
                        .format(o.OrderID, o.ShipName, o.OrderDate.toUTCString()));
            });
        }
    });

    /*********************************************************
    * orders placed on or after 1/1/1998, using moment.js
    * This query mimics on in Brian Noyce' PluralSight course
    * both in using moment.js AND in using the FilterQueryOp's symbol name
    *********************************************************/
    it("where date property is on or after (using moment.js)", function (done) {

        // Make sure date is in UTC (like the datetimes in the database)
        // testDate is 1/1/1998 at midnight GMT
        var testDate = moment.utc([1998, 0, 1]); // month counts from zero!

        EntityQuery.from('Orders')
            .where("OrderDate", "GreaterThanOrEqual", testDate)
            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function (o) {
                expect(o.OrderDate).to.be.at.least(testDate,
                    'OrderDate of order {0} to {1} is {2}'
                        .format(o.OrderID, o.ShipName, o.OrderDate.toUTCString()));
            });
        }
    });
    it("where date property is exactly equal", function (done) {

        // Make sure date is in UTC (like the datetimes in the database)
        // testDate is 1/1/1998 at 9am GMT
        var testDate = new Date(Date.UTC(1998, 0, 1, 9)); // month counts from zero!

        EntityQuery.from('Orders')
            .where('OrderDate', '==', testDate)
            .using(em).execute()
            .then(gotNoResults).then(done, done);
    });

    it("where two date properties are compared", function (done) {
        // Looking for Orders shipped after they were required
        EntityQuery.from('Orders')
            .where('ShippedDate', '>=', 'RequiredDate')
            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function (o) {
                expect(o.ShippedDate).to.be.at.least(o.RequiredDate,
                    'For order {0} to {1} ShippedDate {2} is before RequiredDate {3}'
                        .format(o.OrderID, o.ShipName, o.ShippedDate.toUTCString(), o.RequiredDate.toUTCString()));
            });
        }
    });

    it("where two string properties are compared", function (done) {
        EntityQuery.from('Employees')
            .where('FirstName', '==', 'LastName')
            .using(em).execute()
            .then(gotNoResults).then(done, done);
    });

    it("where string property is compared to a value object", function (done) {
        // Breeze will interpret a string value as a property name
        // if the value happens to correspond to a property name
        // Eliminate all possible ambiguity by building a predicate with an object value
        EntityQuery.from('Employees')
            // We're looking for a person with the first name of 'LastName'
            // Hey ... it could happen :-)
            .where('FirstName', '==',
                  { value: 'LastName', isLiteral: true, dataType: breeze.DataType.String })
            .using(em).execute()
            .then(gotNoResults).then(done, done);
    });

    it("where null", function (done) {
        EntityQuery.from('Customers')
            .where('Region', '==', null)
            .using(em).execute()
            // many customers have a null Region
            .then(gotResults).then(done, done);
    });

    it("where not null", function (done) {
        EntityQuery.from('Customers')

            .where('Region', '!=', null)
            //.where('Region', 'ne', null)
            //.where('Region', breeze.FilterQueryOp.NotEquals, null)

            .using(em).execute()
            // many customers have a Region
            .then(gotResults).then(done, done);
    });

    it("where number property is nullable", function (done) {
        // Order.EmployeeID is nullable int; can still filter on it.
        EntityQuery.from('Orders')
            .where('EmployeeID', '==', ash.nancyID)
            .using(em).execute()
            .then(gotResults).then(done, done);
    });

    it("where Guid property is nullable", function (done) {
        // Order.CustomerID is nullable guid; can still filter on it.
        EntityQuery.from('Orders')
            .where('CustomerID', '==', ash.alfredsID)
            .using(em).execute()
            .then(gotResults).then(done, done);
    });

    it("where filter with string function 'contains'", function (done) {
        EntityQuery.from('Customers')
            // looking for customers whose names contain the word 'market', ignoring case
            .where('CompanyName', 'contains', 'market')

            //.where("CompanyName", FilterQueryOp.Contains, 'market');    // Alternatives,
            //.where("substringof(CompanyName,'market')", "eq", true);    // equivalent in OData
            //.where("indexOf(toLower(CompanyName),'market')", "ne", -1); // to this

            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function(c){
                expect(c.CompanyName).to.match(/market/i, c.CompanyName);
            });
        }
    });

    it("where filter with string function 'length'", function (done) {
        EntityQuery.from('Customers')
            .where('length(CompanyName)', '>', 30)
            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function(c){
                expect(c.CompanyName.length).above(30, c.CompanyName);
            });
        }
    });

    it("where filter with string function combinations", function (done) {
        EntityQuery.from('Customers')
            // looking for customers whose names have 'om' as 2nd and 3rd letter, ignoring case
            .where('toUpper(substring(CompanyName, 1, 2))', '==', 'OM')
            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function(c){
                expect(c.CompanyName).to.match(/^.om/i, c.CompanyName);
            });
        }
    });

    it("where filter with date function, e.g. 'year(OrderDate)'", function (done) {

        EntityQuery.from('Orders')
            .where('year(OrderDate)', '==', 1996)
            .using(em).execute().then(success).then(done, done);

        function success(data){
            gotResults(data);
            data.results.forEach(function(o) {
                var order = 'Order {0} - {1}'.format(o.OrderID, o.ShipName);
                expect(o.OrderDate.getFullYear()).to.equal(1996, order);
            });
        }
    });

    it("where property is a ComplexType property", function (done) {
        // Looking for Orders shipped to CA
        var query = EntityQuery.from('Orders')
            .where('ShipTo.Region', '==', 'CA')
            .using(em).execute()
            .then(success).then(done, done);

        function success(data) {
            data.results.forEach(function(o){
                var msg = "({0}) '{1}' has ShipTo.Region of '{2}'".format(
                           o.OrderID, o.ShipName, o.ShipTo.Region);
                expect(o)
                    .has.deep.property('ShipTo.Region')
                    .that.equals('CA', msg);
            });
        }
    });

    // Todo: move to projections spec
    it("where property is a ComplexType property with projection result", function (done) {
        // Looking for Orders shipped to CA
        var query = EntityQuery.from("Orders")
            .where("ShipTo.Region", "==", "CA")
            .expand("Customer")
            .select("OrderID, Customer.CompanyName, ShipTo.Region")
            .using(em).execute()
            .then(success).then(done, done);

        function success(data) {
            data.results.forEach(function(o){
                var msg = "({0}) '{1}' was shipped to '{2}'".format(
                    // Notice that breeze creates projected property names by
                    // flattening the navigation paths using "_" as a separator
                    // (whether path is based on EntityType or ComplexType)
                    o.OrderID, o.Customer_CompanyName, o.ShipTo_Region);
                expect(o)
                    .has.property('ShipTo_Region')
                    .that.equals('CA', msg);
            });
        }
    });

    it("using EntityQuery.fromEntityKey", function (done) {
        // See http://www.breezejs.com/sites/all/apidocs/classes/EntityQuery.html#method_fromEntityKey
        var customerType = em.metadataStore.getEntityType("Customer");
        var key = new breeze.EntityKey(customerType, ash.alfredsID);

        EntityQuery.fromEntityKey(key)
            .using(em).execute()
            .then(success).then(done, done);

        function success(data){
            expect(data.results).has.length(1); // exactly one result
            var customer = data.results[0] || {};
            expect(customer).has.property('CompanyName').that.match(/alfreds/i);
        }
    });

    it("using EntityManager.fetchEntityByKey", function (done) {
        // See http://www.breezejs.com/sites/all/apidocs/classes/EntityManager.html#method_getEntityByKey
        em.fetchEntityByKey('Customer',ash.alfredsID)
            .then(success).then(done, done);

        function success(data){
            // N.B.: the query response data object does NOT have a results property
            expect(data).to.not.have.property('results');
            // it has an 'entity' property
            expect(data)
                .has.property('entity')
                .that.has.property('CompanyName')
                .that.match(/alfreds/i);
        }
    });

});


text:
"""OpenAPI core contrib django requests module"""
import re
from typing import Optional

from django.http.request import HttpRequest
from werkzeug.datastructures import Headers
from werkzeug.datastructures import ImmutableMultiDict

from openapi_core.validation.request.datatypes import RequestParameters

# https://docs.djangoproject.com/en/2.2/topics/http/urls/
#
# Currently unsupported are :
#   - nested arguments, e.g.: ^comments/(?:page-(?P<page_number>\d+)/)?$
#   - unnamed regex groups, e.g.: ^articles/([0-9]{4})/$
#   - multiple named parameters between a single pair of slashes
#     e.g.: <page_slug>-<page_id>/edit/
#
# The regex matches everything, except a "/" until "<". Than only the name
# is exported, after which it matches ">" and everything until a "/".
PATH_PARAMETER_PATTERN = r"(?:[^\/]*?)<(?:(?:.*?:))*?(\w+)>(?:[^\/]*)"

class DjangoOpenAPIRequest:

    path_regex = re.compile(PATH_PARAMETER_PATTERN)

    def __init__(self, request: HttpRequest):
        self.request = request

        path = (
            self.request.resolver_match
            and self.request.resolver_match.kwargs
            or {}
        )
        self.parameters = RequestParameters(
            path=path,
            query=ImmutableMultiDict(self.request.GET),
            header=Headers(self.request.headers.items()),
            cookie=ImmutableMultiDict(dict(self.request.COOKIES)),
        )

    @property
    def host_url(self) -> str:
        assert isinstance(self.request._current_scheme_host, str)
        return self.request._current_scheme_host

    @property
    def path(self) -> str:
        assert isinstance(self.request.path, str)
        return self.request.path

    @property
    def path_pattern(self) -> Optional[str]:
        if self.request.resolver_match is None:
            return None

        route = self.path_regex.sub(r"{\1}", self.request.resolver_match.route)
        # Delete start and end marker to allow concatenation.
        if route[:1] == "^":
            route = route[1:]
        if route[-1:] == "$":
            route = route[:-1]
        return "/" + route

    @property
    def method(self) -> str:
        if self.request.method is None:
            return ""
        assert isinstance(self.request.method, str)
        return self.request.method.lower()

    @property
    def body(self) -> str:
        assert isinstance(self.request.body, bytes)
        return self.request.body.decode("utf-8")

    @property
    def mimetype(self) -> str:
        return self.request.content_type or ""


text:
#include<iostream>
#include "Constants.h"
#include "CommunicationLogger.h"
using namespace std;

CommunicationLogger* CommunicationLogger::pCommLogSingleton= NULL;

CommunicationLogger::CommunicationLogger()
{
}
/*
	funciton: getInstance
	purpose: singleton for communication logger.
*/
CommunicationLogger* CommunicationLogger::GetInstance()
{
	if (pCommLogSingleton== NULL) {
		pCommLogSingleton = new CommunicationLogger();
	}
	return pCommLogSingleton;
}


text:
<?php

namespace OC\BusinessRules\UseCases\Course\Workflow;

use OC\BusinessRules\Gateways\Course\Course\CourseGatewaySpy;
use OC\BusinessRules\Gateways\Course\Course\CourseNotFoundCourseGatewayStub;
use OC\BusinessRules\UseCases\Course\Workflow\DTO\PublishCourseRequestDTO;

/**
 * @author Romain Kuzniak <romain.kuzniak@openclassrooms.com>
 */
abstract class PublishCourseTest extends \PHPUnit_Framework_TestCase
{
    const NON_EXISTING_COURSE_ID = 999;

    const COURSE_1_ID = 1;

    /**
     * @var PublishCourse
     */
    protected $useCase;

    /**
     * @var CourseGatewaySpy
     */
    protected $courseGateway;

    /**
     * @test
     * @expectedException \OC\BusinessRules\Exceptions\Course\Course\CourseNotFoundException
     */
    public function NonExistingCourse_ThrowException()
    {
        $this->useCase->setCourseGateway(new CourseNotFoundCourseGatewayStub());
        $this->useCase->execute(
            new PublishCourseRequestDTO(self::NON_EXISTING_COURSE_ID)
        );
    }

    /**
     * @test
     */
    public function ChangeCourseStatus()
    {
        $gateway = new CourseGatewaySpy();
        $this->useCase->setCourseGateway($gateway);
        $this->useCase->execute(
            new PublishCourseRequestDTO(self::COURSE_1_ID)
        );
        $this->assertEquals(self::COURSE_1_ID, $gateway->courseId);
    }

    protected function setUp()
    {
        $this->courseGateway = new CourseGatewaySpy();
        $this->useCase->setCourseGateway($this->courseGateway);
    }

}


text:
.class final Lorg/apache/harmony/security/asn1/ASN1StringType$7;
.super Lorg/apache/harmony/security/asn1/ASN1StringType$ASN1StringUTF8Type;
.source "ASN1StringType.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/apache/harmony/security/asn1/ASN1StringType;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>(I)V
    .locals 0
    .param p1, "x0"    # I

    .prologue
    .line 67
    invoke-direct {p0, p1}, Lorg/apache/harmony/security/asn1/ASN1StringType$ASN1StringUTF8Type;-><init>(I)V

    return-void
.end method


text:
import os, sys 		# low level handling, such as command line stuff
import string			# string methods available
import re					# regular expressions
from low import *	# custom functions, written by myself

# =============================================================================
def get_translatedfasta_from_gb( file ):
	"""
	"""

	def write_output( source, hash ):
		L = [ ">",hash.get('protein_id'),"|",hash.get('db_xref')]
		if hash.has_key('product'): L.append("|"+hash.get('product'))
		L.append(" ("+source+")")
		print string.join(L,'')
		print hash.get('translation')

	fo = open(file)
	# read general infos
	source = ''
	for line in fo:
		if re.search('FEATURES',line): break
		if re.match('SOURCE',line):
			source = re.search('SOURCE\s+(.*)\n',line).group(1)

	# read gene infos
	hash = {}
	hit = 0
	for line in fo:
		if not re.match('                     ',line):
			if len(hash) > 0:	write_output( source, hash )
			hash = {}
			hit = 0
		if re.match('     CDS',line): hit = 1

		if hit:
			# catch everything except translation sequence
			if re.search('/(\S+)=".*"',line):
				hash[re.search('/(\S+)=".*"',line).group(1)] = re.search('/\S+="(.*)"',line).group(1)
			# catch translation sequence
			if re.search('/translation=',line):
				hash['translation'] = re.search('/translation="(.*)\n',line).group(1)
			elif hash.has_key('translation'): hash['translation'] += re.search("([a-zA-Z]+)",line).group(1)
	if len(hash) > 0: write_output( source, hash )
	fo.close()

# =============================================================================
# === MAIN ====================================================================
# =============================================================================

if len( sys.argv ) == 1:
	print "no arguments provided. you need to specify the gb file(s) to parse."
	sys.exit(1)

for file in sys.argv[1:]:
	if not file_exists(file):
		print "gb file not found (or is a dir):", file
		continue
	get_translatedfasta_from_gb( file )


text:
using Avalonia.Svg.Skia;
using ReactiveUI;
using SkiaSharp;
using System.Reactive;
using System.Reactive.Linq;
using System.Windows.Input;
using Zametek.Common.ProjectPlan;
using Zametek.Contract.ProjectPlan;
using Zametek.Utility;

namespace Zametek.ViewModel.ProjectPlan
{
    public class ArrowGraphManagerViewModel
        : ToolViewModelBase, IArrowGraphManagerViewModel, IDisposable
    {
        #region Fields

        private readonly object m_Lock;

        private static readonly IList<IFileFilter> s_ExportFileFilters =
            new List<IFileFilter>
            {
                new FileFilter
                {
                    Name = Resource.ProjectPlan.Filters.Filter_ImageJpegFileType,
                    Extensions = new List<string>
                    {
                        Resource.ProjectPlan.Filters.Filter_ImageJpegFileExtension
                    }
                },
                new FileFilter
                {
                    Name = Resource.ProjectPlan.Filters.Filter_ImagePngFileType,
                    Extensions = new List<string>
                    {
                        Resource.ProjectPlan.Filters.Filter_ImagePngFileExtension
                    }
                },
                new FileFilter
                {
                    Name = Resource.ProjectPlan.Filters.Filter_GraphMLFileType,
                    Extensions = new List<string>
                    {
                        Resource.ProjectPlan.Filters.Filter_GraphMLFileExtension
                    }
                },
                new FileFilter
                {
                    Name = Resource.ProjectPlan.Filters.Filter_GraphVizFileType,
                    Extensions = new List<string>
                    {
                        Resource.ProjectPlan.Filters.Filter_GraphVizFileExtension
                    }
                }
            };

        private readonly ICoreViewModel m_CoreViewModel;
        private readonly ISettingService m_SettingService;
        private readonly IDialogService m_DialogService;
        private readonly IArrowGraphSerializer m_ArrowGraphExport;

        private readonly IDisposable? m_BuildArrowGraphDataSub;
        private readonly IDisposable? m_BuildArrowGraphImageSub;

        #endregion

        #region Ctors

        public ArrowGraphManagerViewModel(
            ICoreViewModel coreViewModel,//!!,
            ISettingService settingService,//!!,
            IDialogService dialogService,//!!,
            IArrowGraphSerializer arrowGraphExport)//!!)
        {
            m_Lock = new object();
            m_CoreViewModel = coreViewModel;
            m_SettingService = settingService;
            m_DialogService = dialogService;
            m_ArrowGraphExport = arrowGraphExport;

            m_ArrowGraphData = string.Empty;
            m_ArrowGraphImage = new SvgImage();

            {
                ReactiveCommand<Unit, Unit> saveArrowGraphImageFileCommand = ReactiveCommand.CreateFromTask(SaveArrowGraphImageFileAsync);
                SaveArrowGraphImageFileCommand = saveArrowGraphImageFileCommand;
            }

            m_IsBusy = this
                .WhenAnyValue(mm => mm.m_CoreViewModel.IsBusy)
                .ToProperty(this, mm => mm.IsBusy);

            m_HasStaleOutputs = this
                .WhenAnyValue(mm => mm.m_CoreViewModel.HasStaleOutputs)
                .ToProperty(this, mm => mm.HasStaleOutputs);

            m_HasCompilationErrors = this
                .WhenAnyValue(mm => mm.m_CoreViewModel.HasCompilationErrors)
                .ToProperty(this, mm => mm.HasCompilationErrors);

            m_BuildArrowGraphDataSub = this
                .WhenAnyValue(agm => agm.m_CoreViewModel.ArrowGraph, agm => agm.m_CoreViewModel.ArrowGraphSettings)
                .ObserveOn(RxApp.TaskpoolScheduler)
                .Subscribe(async result => ArrowGraphData = await BuildArrowGraphDiagramDataAsync(result.Item1, result.Item2));

            m_BuildArrowGraphImageSub = this
                .WhenAnyValue(agm => agm.ArrowGraphData)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(async data => ArrowGraphImage = await BuildArrowGraphDiagramImageAsync(data));

            Id = Resource.ProjectPlan.Titles.Title_ArrowGraphView;
            Title = Resource.ProjectPlan.Titles.Title_ArrowGraphView;
        }

        #endregion

        #region Properties

        private SvgImage m_ArrowGraphImage;
        public SvgImage ArrowGraphImage
        {
            get => m_ArrowGraphImage;
            private set
            {
                lock (m_Lock) this.RaiseAndSetIfChanged(ref m_ArrowGraphImage, value);
            }
        }

        #endregion

        #region Private Methods

        private async Task<string> BuildArrowGraphDiagramDataAsync(
            ArrowGraphModel arrowGraphModel,
            ArrowGraphSettingsModel arrowGraphSettingsModel)
        {
            try
            {
                lock (m_Lock)
                {
                    byte[] data = m_ArrowGraphExport.BuildArrowGraphSvgData(arrowGraphModel, arrowGraphSettingsModel);
                    return data.ByteArrayToString();
                }
            }
            catch (Exception ex)
            {
                await m_DialogService.ShowErrorAsync(
                    Resource.ProjectPlan.Titles.Title_Error,
                    ex.Message);
            }

            return string.Empty;
        }

        private async Task<SvgImage> BuildArrowGraphDiagramImageAsync(string arrowGraphData)
        {
            if (string.IsNullOrWhiteSpace(arrowGraphData))
            {
                return new SvgImage();
            }

            try
            {
                lock (m_Lock)
                {
                    var source = new SvgSource();
                    source.FromSvg(arrowGraphData);
                    return new SvgImage
                    {
                        Source = source
                    };
                }
            }
            catch (Exception ex)
            {
                await m_DialogService.ShowErrorAsync(
                    Resource.ProjectPlan.Titles.Title_Error,
                    ex.Message);
            }

            return new SvgImage();
        }

        private async Task SaveArrowGraphImageFileInternalAsync(string? filename)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                await m_DialogService.ShowErrorAsync(
                    Resource.ProjectPlan.Titles.Title_Error,
                    Resource.ProjectPlan.Messages.Message_EmptyFilename);
            }
            else
            {
                string fileExtension = Path.GetExtension(filename);
                byte[]? data = null;

                fileExtension.ValueSwitchOn()
                    .Case($".{Resource.ProjectPlan.Filters.Filter_ImageJpegFileExtension}", _ =>
                    {
                        ArrowGraphImage.Source?.Save(filename, SKColors.White, SKEncodedImageFormat.Jpeg, scaleX: 2, scaleY: 2);
                    })
                    .Case($".{Resource.ProjectPlan.Filters.Filter_ImagePngFileExtension}", _ =>
                    {
                        ArrowGraphImage.Source?.Save(filename, SKColors.White, SKEncodedImageFormat.Png, scaleX: 2, scaleY: 2);
                    })
                    .Case($".{Resource.ProjectPlan.Filters.Filter_GraphMLFileExtension}", _ =>
                    {
                        data = m_ArrowGraphExport.BuildArrowGraphMLData(m_CoreViewModel.ArrowGraph, m_CoreViewModel.ArrowGraphSettings);
                    })
                    .Case($".{Resource.ProjectPlan.Filters.Filter_GraphVizFileExtension}", _ =>
                    {
                        data = m_ArrowGraphExport.BuildArrowGraphVizData(m_CoreViewModel.ArrowGraph, m_CoreViewModel.ArrowGraphSettings);
                    })
                    .Default(_ => throw new ArgumentOutOfRangeException(nameof(filename), @$"{Resource.ProjectPlan.Messages.Message_UnableToSaveFile} {filename}"));

                if (data is not null)
                {
                    using var stream = File.OpenWrite(filename);
                    await stream.WriteAsync(data);
                }
            }
        }

        private async Task SaveArrowGraphImageFileAsync()
        {
            try
            {
                string projectTitle = m_SettingService.ProjectTitle;
                string directory = m_SettingService.ProjectDirectory;
                string? filename = await m_DialogService.ShowSaveFileDialogAsync(projectTitle, directory, s_ExportFileFilters);

                if (!string.IsNullOrWhiteSpace(filename))
                {
                    await SaveArrowGraphImageFileInternalAsync(filename);
                }
            }
            catch (Exception ex)
            {
                await m_DialogService.ShowErrorAsync(
                    Resource.ProjectPlan.Titles.Title_Error,
                    ex.Message);
            }
        }

        #endregion

        #region IArrowGraphManagerViewModel Members

        private readonly ObservableAsPropertyHelper<bool> m_IsBusy;
        public bool IsBusy => m_IsBusy.Value;

        private readonly ObservableAsPropertyHelper<bool> m_HasStaleOutputs;
        public bool HasStaleOutputs => m_HasStaleOutputs.Value;

        private readonly ObservableAsPropertyHelper<bool> m_HasCompilationErrors;
        public bool HasCompilationErrors => m_HasCompilationErrors.Value;

        private string m_ArrowGraphData;
        public string ArrowGraphData
        {
            get => m_ArrowGraphData;
            private set
            {
                lock (m_Lock) this.RaiseAndSetIfChanged(ref m_ArrowGraphData, value);
            }
        }

        public ICommand SaveArrowGraphImageFileCommand { get; }

        #endregion

        #region IDisposable Members

        private bool m_Disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (m_Disposed)
            {
                return;
            }

            if (disposing)
            {
                // TODO: dispose managed state (managed objects).
                m_BuildArrowGraphDataSub?.Dispose();
                m_BuildArrowGraphImageSub?.Dispose();
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            m_Disposed = true;
        }

        public void Dispose()
        {
            // Dispose of unmanaged resources.
            Dispose(true);
            // Suppress finalization.
            GC.SuppressFinalize(this);
        }

        #endregion
    }
}


text:
[![Actions Status](https://github.com/dalance/gip/workflows/Regression/badge.svg)](https://github.com/dalance/gip/actions)
[![Crates.io](https://img.shields.io/crates/v/gip.svg)](https://crates.io/crates/gip)
[![Docs.rs](https://docs.rs/gip/badge.svg)](https://docs.rs/gip)
[![codecov](https://codecov.io/gh/dalance/gip/branch/master/graph/badge.svg)](https://codecov.io/gh/dalance/gip)

**gip** is a command-line tool and Rust library to check global IP address.

## Install
Download from [release page](https://github.com/dalance/gip/releases/latest), and extract to the directory in PATH.

Alternatively you can install by [cargo](https://crates.io).

```
cargo install gip
```

## Usage

```
gip 0.3.2-pre
dalance <dalance@gmail.com>
A library and command-line frontend to check global IP address

USAGE:
    gip [FLAGS] [OPTIONS]

FLAGS:
    -4, --v4         IPv4 address ( default )
    -6, --v6         IPv6 address
    -p, --plane      Show by plane text ( default )
    -s, --string     Show by plane text without line break
    -j, --json       Show by JSON
    -l, --list       Show provider list
    -v, --verbose    Show verbose message
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --timeout <timeout>      Timeout per each provider by milliseconds [default: 1000]
        --json-key <json_key>    Key string of JSON format [default: ip]
        --proxy <proxy>          Proxy for HTTP access ( "host:port" )
```

## Providers
Currently built-in service providers are the followings.

- [ipv6-test.com](http://ipv6-test.com) ( v4 /v6 )
- [ident.me/tnedi.me](http://api.ident.me) ( v4 / v6 )
- [test-ipv6.com](http://test-ipv6.com) ( v4 / v6 )
- [opendns.com](https://www.opendns.com) ( v4 / v6 )
- [akamai.com](https://developer.akamai.com) ( v4 / v6 )

If you want to change providers, providers can be set by `$HOME/.gip.toml` like the following.

```
[[providers]]
    name     = "ident.me"
    ptype    = "IPv4"
    protocol = "HttpPlane"
    url      = "http://v4.ident.me/"
    key      = []

[[providers]]
    name     = "test-ipv6"
    ptype    = "IPv4"
    protocol = "HttpJson"
    url      = "http://ipv4.test-ipv6.com/ip/"
    key      = ["ip"]
    padding  = "callback"

[[providers]]
    name     = "opendns.com"
    ptype    = "IPv4"
    protocol = "Dns"
    url      = "myip.opendns.com@resolver1.opendns.com"
    key      = []
```

## Library

**gip** is provided as Rust library.

```Cargo.toml
gip = "0.7.1"
```

[Documentation](https://docs.rs/gip)

## License

Licensed under either of

 * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
 * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache-2.0
license, shall be dual licensed as above, without any additional terms or
conditions.


text:
// Appends a CSS file to a document.
FCKTools.AppendStyleSheet = function( documentElement, cssFileUrl )
{
	return documentElement.createStyleSheet( cssFileUrl ) ;
}

// Removes all attributes and values from the element.
FCKTools.ClearElementAttributes = function( element )
{
	element.clearAttributes() ;
}

FCKTools.GetAllChildrenIds = function( parentElement )
{
	var aIds = new Array() ;
	for ( var i = 0 ; i < parentElement.all.length ; i++ )
	{
		var sId = parentElement.all[i].id ;
		if ( sId && sId.length > 0 )
			aIds[ aIds.length ] = sId ;
	}
	return aIds ;
}

FCKTools.RemoveOuterTags = function( e )
{
	e.insertAdjacentHTML( 'beforeBegin', e.innerHTML ) ;
	e.parentNode.removeChild( e ) ;
}

FCKTools.CreateXmlObject = function( object )
{
	var aObjs ;

	switch ( object )
	{
		case 'XmlHttp' :
			aObjs = [ 'MSXML2.XmlHttp', 'Microsoft.XmlHttp' ] ;
			break ;

		case 'DOMDocument' :
			aObjs = [ 'MSXML2.DOMDocument', 'Microsoft.XmlDom' ] ;
			break ;
	}

	for ( var i = 0 ; i < 2 ; i++ )
	{
		try { return new ActiveXObject( aObjs[i] ) ; }
		catch (e)
		{}
	}

	if ( FCKLang.NoActiveX )
	{
		alert( FCKLang.NoActiveX ) ;
		FCKLang.NoActiveX = null ;
	}
}


text:
"""
Tests the Table class which contains metadata
"""
import sys
sys.path.append('code')

from pdftables import get_tables

from nose.tools import *

def test_it_includes_page_numbers():
    """
    page_number is 1-indexed, as defined in the PDF format
    table_number is 1-indexed
    """
    fh = open('fixtures/sample_data/AnimalExampleTables.pdf', 'rb')
    result = get_tables(fh)
    assert_equals(result[0].total_pages, 4)
    assert_equals(result[0].page_number, 2)
    assert_equals(result[1].total_pages, 4)
    assert_equals(result[1].page_number, 3)
    assert_equals(result[2].total_pages, 4)
    assert_equals(result[2].page_number, 4)

def test_it_includes_table_numbers():
    fh = open('fixtures/sample_data/AnimalExampleTables.pdf', 'rb')
    result = get_tables(fh)
    assert_equals(result[0].table_number_on_page, 1)
    assert_equals(result[0].total_tables_on_page, 1)


text:
package com.github.thecoldwine.sigrun.formats;

/**
 * Factory of SEG-Y formats.
 *
 * Currently only rev 1 format is supported.
 *
 * Created by maksenov on 2017-03-30.
 */
public class SEGYFormatFactory {
    public static SEGYRevision Revision1() {
        return new SEGYRevision1();
    }
}


text:
package org.ognl.test.objects;

/**
 *
 */
public interface Inherited {

    String getMyString();
}


text:
/*
 * BOF: src/domain/store/main.js
 * This file is the 'index' file of the store.
 */

// @flow

import { createStore } from "redux";
import { reduceApp } from "domain/store/reduce/main";

import type { State } from "domain/store/state/main";

// Create the store and make it an importable constant
export const store = createStore(reduceApp);

// We use this wrapper function so that we can have type checking
export function state() : State {
  return store.getState();
}

/*
 * EOF: src/domain/store/main.js
 */


text:
body {
	margin: 3em 9em;
	}
header {
	width: 50%;
	margin: 2em auto 4em auto;
	padding: 2em 1em;
	background-color: maroon;
	color: white;
	color: beige;
	border-radius: 20px;
	box-shadow: 2px 2px 2px 2px silver;
	}
 header > p {
 	font-size: 1.3em;
}

header, figure {
 	text-align: center;
}

article {
	overflow: auto;
	margin: 0.3em 1em;

		}

	article p {
		width: 40%;
		float: left;
		padding: 0em 1em;
		box-sizing: border-box;
		}

	article figure {
		width: 60%;
		float: left;
		margin: 0px;
		box-sizing: border-box;
	}

		article figure img {
			width: 100%;
		}

/*
footer {
 	margin-top:  2em;
 	border-top: solid 1px silver;
 	color: maroon;
 	}
 	footer p {
 		margin: 0.2em;
 	}
*/

footer {
    height: 10%;
    min-height: 160px;
    border: solid 1px black;
    box-shadow: 2px -3px 3px 1px silver;
    position: fixed;
    bottom: 2%;
    left: 1%;
    right: 1%;
    background-color: hsla(60,55%,91%,0.7) ;/*beige con transparencia*/
	}
	footer h2 {
        width: 60%;
        margin: 0.2em auto;
        text-align: center;
    }
    footer p {
       text-align: center;
    }
    footer a.container {
	    width: 10%;
	    margin-left: 3%;
	    margin-right: 3%;
	    float:left;
	}
	footer div.icono {
        height: 50px;
		width: 50px;
		margin: 1em auto;
		border: solid 1px black;
	}
	footer div#facebook {background-color: silver;
	    background: url(../img/social-header.png);
        background-position: 150px 205px; /* x px / y px de la esquina superior del icono*/
    }
    footer div#twiter {
        background-color: silver;
        background: url(../img/social-header.png);
        background-position: 250px 50px; /*Icono 5-1*/
    }
    footer div#linkedin {
        background-color: silver;
        background: url(../img/social-header.png);
        background-position: 450px 100px; /*Icono 9-2*/
    }
    footer div#google {
        background-color: silver;
        background: url(../img/social-header.png);
        background-position: 300px 154px; /*Icono 6-3*/
    }
    footer div#tumblr {
        background-color: silver;
        background: url(../img/social-header.png);
        background-position: 300px 50px; /*Icono 6-1*/
    }
    footer div#youtube {
        background-color: silver;
        background: url(../img/social-header.png);
        background-position: 50px 50px; /*Icono 1-1*/
    }


text:
from test_framework.test_framework import SequenceTestFramework
from test_framework.util import *
import os
import shutil

class BIP65Test(SequenceTestFramework):

    def setup_network(self):
        self.nodes = []
        self.nodes.append(start_node(0, self.options.tmpdir, []))
        self.nodes.append(start_node(1, self.options.tmpdir, ["-blockversion=3"]))
        self.nodes.append(start_node(2, self.options.tmpdir, ["-blockversion=4"]))
        connect_nodes(self.nodes[1], 0)
        connect_nodes(self.nodes[2], 0)
        self.is_network_split = False
        self.sync_all()

    def run_test(self):
        cnt = self.nodes[0].getblockcount()

        # Mine some old-version blocks
        self.nodes[1].setgenerate(True, 100)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 100):
            raise AssertionError("Failed to mine 100 version=3 blocks")

        # Mine 750 new-version blocks
        for i in xrange(15):
            self.nodes[2].setgenerate(True, 50)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 850):
            raise AssertionError("Failed to mine 750 version=4 blocks")

        # TODO: check that new CHECKLOCKTIMEVERIFY rules are not enforced

        # Mine 1 new-version block
        self.nodes[2].setgenerate(True, 1)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 851):
            raise AssertionFailure("Failed to mine a version=4 blocks")

        # TODO: check that new CHECKLOCKTIMEVERIFY rules are enforced

        # Mine 198 new-version blocks
        for i in xrange(2):
            self.nodes[2].setgenerate(True, 99)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 1049):
            raise AssertionError("Failed to mine 198 version=4 blocks")

        # Mine 1 old-version block
        self.nodes[1].setgenerate(True, 1)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 1050):
            raise AssertionError("Failed to mine a version=3 block after 949 version=4 blocks")

        # Mine 1 new-version blocks
        self.nodes[2].setgenerate(True, 1)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 1051):
            raise AssertionError("Failed to mine a version=4 block")

        # Mine 1 old-version blocks
        try:
            self.nodes[1].setgenerate(True, 1)
            raise AssertionError("Succeeded to mine a version=3 block after 950 version=4 blocks")
        except JSONRPCException:
            pass
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 1051):
            raise AssertionError("Accepted a version=3 block after 950 version=4 blocks")

        # Mine 1 new-version blocks
        self.nodes[2].setgenerate(True, 1)
        self.sync_all()
        if (self.nodes[0].getblockcount() != cnt + 1052):
            raise AssertionError("Failed to mine a version=4 block")

if __name__ == '__main__':
    BIP65Test().main()


text:
'use strict';

var Session = require('../').Session;
var Competition = require('../').Competition;
var Hand = require('../').Hand;
var Card = require('../').card;
var seat = require('../').seat;
var expect = require('chai').expect;
var fs = require('fs');

describe('Session', function() {

    it('should be part of a competition', function() {
        var session = new Session();
        expect(session).to.have.property('competition')
            .that.is.instanceof(Competition);
    });

    it('should have a site', function() {
        var session = new Session();
        expect(session).to.have.property('site')
            .that.is.a('string');
    });

    it('should have a date', function() {
        var session = new Session();
        expect(session).to.have.property('date')
            .that.is.a('string');
    });

    it('should have boards', function() {
        var session = new Session();
        expect(session).to.have.property('boards')
            .that.is.instanceof(Array);
    });

    it('should have games', function() {
        var session = new Session();
        expect(session).to.have.property('games')
            .that.is.instanceof(Array);
    });

    // Only available on platforms that supports streaming.
    if (Object.getOwnPropertyNames(fs).length !== 0) {
        describe('import PBN', function() {

        it('should return a new Session', function(done) {
            var stream = fs.createReadStream('./test/sample/Schiphol.pbn');
            Session.importPbn(stream, function(err, session) {
                expect(session).is.instanceof(Session);
                done();
            });
        });

        it('should return an Error', function(done) {
            Session.importPbn('[Session test]', function(err) { // test should be in quotes
                expect(err).is.instanceof(Error);
                done();
            });
        });

        it('should process mandatory tags', function(done) {
            var stream = fs.createReadStream('./test/sample/Schiphol.pbn');
            Session.importPbn(stream, function(err, session) {
                if (err) return done(err);
                expect(session.competition).to.have.property('name', 'International Amsterdam Airport Schiphol Bridgetournament');
                expect(session).to.have.property('site', 'Amsterdam, The Netherlands NLD');
                expect(session).to.have.property('date', '1995.06.10');

                expect(session).to.have.property('boards').of.length(1);
                expect(session.boards[0]).to.have.property('dealer', seat.north);
                expect(session.boards[0]).to.have.property('vulnerability', 'Nil');
                expect(session.boards[0]).to.have.property('hands');
                expect(session.boards[0].hands).to.have.property(seat.north);
                expect(session.boards[0].hands).to.have.property(seat.south);
                expect(session.boards[0].hands).to.have.property(seat.east);
                expect(session.boards[0].hands).to.have.property(seat.west);
                expect(session.boards[0].hands[seat.north].cards.toString()).to.equal('6H,3H,AD,KD,QD,9D,8D,7D,AC,9C,7C,3C,2C');
                expect(session.boards[0].hands[seat.west].cards.toString()).to.equal('KS,QS,TS,2S,AH,TH,JD,6D,5D,4D,2D,8C,5C');

                expect(session.boards[0].deal()).to.equal('N:.63.AKQ987.A9732 A8654.KQ5.T.QJT6 J973.J98742.3.K4 KQT2.AT.J6542.85');

                expect(session).to.have.property('games').of.length(1);
                expect(session.games[0].auction).to.have.property('dealer', seat.north);
                expect(session.games[0].players).to.have.property(seat.north, 'Westra');
                expect(session.games[0].players).to.have.property(seat.south, 'Leufkens');
                expect(session.games[0].players).to.have.property(seat.east, 'Kalish');
                expect(session.games[0].players).to.have.property(seat.west, 'Podgor');
                expect(session.games[0].contract.toString()).to.equal('5HX by S');
                expect(session.games[0].lead()).to.equal(Card.SK);
                // TODO: Scoring
                expect(session.games[0].made).to.equal(-2);
                done();
            });
        });

        it('should process board records only', function(done) {
            var stream = fs.createReadStream('./test/sample/Hand_Trophy_Pairs.pbn');
            Session.importPbn(stream, function(err, session) {
                if (err) return done(err);
                expect(session.competition).to.have.property('name', '160816TuE');
                expect(session).to.have.property('site', '');
                expect(session).to.have.property('date', '2016.08.16');
                expect(session).to.have.property('boards').of.length(26);
                expect(session).to.have.property('games').of.length(0);
                expect(session.boards[23-1]).to.have.property('dealer', seat.south);
                expect(session.boards[23-1]).to.have.property('vulnerability', 'All');
                // TODO: Deal
                // TODO: Scoring
                done();
            });
        });

        it('should ignore tags with value "?"', function(done) {
            var stream = fs.createReadStream('./test/sample/kgb.pbn');
            Session.importPbn(stream, function(err, session) {
                if (err) return done(err);
                expect(session.competition).to.have.property('name', '');
                expect(session).to.have.property('site', '');
                expect(session).to.have.property('date', '');
                expect(session).to.have.property('boards').of.length(99);
                expect(session).to.have.property('games').of.length(0);
                done();
            });
        });

        it('should process Auction section', function(done) {
            var stream = fs.createReadStream('./test/sample/Schiphol.pbn');
            Session.importPbn(stream, function(err, session) {
                if (err) return done(err);
                expect(session).to.have.property('games').of.length(1);
                var auction = session.games[0].auction;
                expect(auction).to.have.property('dealer', seat.north);
                expect(auction.isClosed()).to.equal(true);
                expect(auction.contract().toString()).to.equal('5HX by S');
                done();
            });
        });

        it('should process Play section', function(done) {
            var stream = fs.createReadStream('./test/sample/Schiphol.pbn');
            Session.importPbn(stream, function(err, session) {
                if (err) return done(err);
                expect(session).to.have.property('games').of.length(1);
                expect(session.games[0]).to.have.property('tricks').of.length(7);
                var tricks = session.games[0].tricks;
                expect(tricks[0].leader().symbol).to.equal('W');
                expect(tricks[1].leader().symbol).to.equal('N');
                done();
            });
        });

        it('should process multiple board definitions', function(done) {
            var stream = fs.createReadStream('./test/sample/AlsReg6-Final.pbn');
            Session.importPbn(stream, function(err, session) {
                expect(err).to.equal(null);
                expect(session).to.be.instanceof(Session);
                expect(session.boards[0].deal()).to.equal('N:AJ4.T7.AT652.KJ2 K73.A985432.Q9.7 985..KJ84.AQT654 QT62.KQJ6.73.983');
                done();
            });
        });

        });

        describe('import PBN with a promise', function() {

        it('should then return a new Session', function(done) {
            var stream = fs.createReadStream('./test/sample/AlsReg6-Final.pbn');
            Session
                .importPbn(stream)
                .then(function(session) {
                    expect(session).is.instanceof(Session);
                    done();
                })
                .catch(done)
            ;
        });

        it('should catch error', function(done) {
            Session
                .importPbn('[Session test]') // test should be in quotes
                .then(function(session) {
                    done('did not reject');
                })
                .catch(function(err) {
                    expect(err).is.instanceof(Error);
                    done();
                })
            ;
        });
    });

    }

    it('should generate boards', function() {
        var session = Session.generateBoards(16);
        expect(session)
            .to.have.property('boards')
            .that.has.length(16);

        for (var i = 0; i < 16; ++i) {
            var board = session.boards[i];
            expect(board.hands).has.property(seat.north).and.instanceOf(Hand).and.has.property('cards').and.has.lengthOf(13);
            expect(board.hands).has.property(seat.south).and.instanceOf(Hand).and.has.property('cards').and.has.lengthOf(13);
            expect(board.hands).has.property(seat.east).and.instanceOf(Hand).and.has.property('cards').and.has.lengthOf(13);
            expect(board.hands).has.property(seat.west).and.instanceOf(Hand).and.has.property('cards').and.has.lengthOf(13);
        }
    });

});


text:
/* See LICENSE for licensing information */

/**
 * \file tor_api.h
 * \brief Public C API for the Tor network service.
 *
 * This interface is intended for use by programs that need to link Tor as
 * a library, and launch it in a separate thread.  If you have the ability
 * to run Tor as a separate executable, you should probably do that instead
 * of embedding it as a library.
 *
 * To use this API, first construct a tor_main_configuration_t object using
 * tor_main_configuration_new().  Then, you use one or more other function
 * calls (such as tor_main_configuration_set_command_line() to configure how
 * Tor should be run.  Finally, you pass the configuration object to
 * tor_run_main().
 *
 * At this point, tor_run_main() will block its thread to run a Tor daemon;
 * when the Tor daemon exits, it will return.  See notes on bugs and
 * limitations below.
 *
 * There is no other public C API to Tor: calling any C Tor function not
 * documented in this file is not guaranteed to be stable.
 **/

#ifndef TOR_API_H
#define TOR_API_H

typedef struct tor_main_configuration_t tor_main_configuration_t;

/**
 * Create and return a new tor_main_configuration().
 */
tor_main_configuration_t *tor_main_configuration_new(void);

/**
 * Set the command-line arguments in cfg.
 *
 * The argc and argv values here are as for main().  The
 * contents of the argv pointer must remain unchanged until tor_run_main() has
 * finished and you call tor_main_configuration_free().
 *
 * Return 0 on success, -1 on failure.
 */
int tor_main_configuration_set_command_line(tor_main_configuration_t *cfg,
                                            int argc, char *argv[]);

#ifdef _WIN32
typedef SOCKET tor_control_socket_t;
#define INVALID_TOR_CONTROL_SOCKET INVALID_SOCKET
#else
typedef int tor_control_socket_t;
#define INVALID_TOR_CONTROL_SOCKET (-1)
#endif /* defined(_WIN32) */

/** DOCDOC */
tor_control_socket_t tor_main_configuration_setup_control_socket(
                                          tor_main_configuration_t *cfg);

/**
 * Release all storage held in cfg.
 *
 * Once you have passed a tor_main_configuration_t to tor_run_main(), you
 * must not free it until tor_run_main() has finished.
 */
void tor_main_configuration_free(tor_main_configuration_t *cfg);

/**
 * Return the name and version of the software implementing the tor_api
 * functionality.  Current implementors are "tor" and "libtorrunner".
 *
 * Note that if you're using libtorrunner, you'll see the version of
 * libtorrunner, not the version of Tor that it's invoking for you.
 *
 * Added in Tor 0.3.5.1-alpha.
 *
 * Example return values include "tor 0.3.5.1-alpha" when linked directly
 * against tor, and "libtorrunner 0.3.5.1-alpha" when linked against
 * libtorrunner while it is invoking an arbitrary version of Tor.  HOWEVER,
 * the user MUST NOT depend on any particular format or contents of this
 * string: there may be other things that implement Tor in the future.
 **/
const char *tor_api_get_provider_version(void);

/**
 * Run the tor process, as if from the command line.
 *
 * The command line arguments from tor_main_configuration_set_command_line()
 * are taken as if they had been passed to main().
 *
 * This function will not return until Tor is done running.  It returns zero
 * on success, and nonzero on failure.
 *
 * If you want to control when Tor exits, make sure to configure a control
 * socket. The OwningControllerFD option may be helpful there.
 *
 * BUG 23847: Sometimes, if you call tor_main a second time (after it has
 * returned), Tor may crash or behave strangely.  We have fixed all issues of
 * this type that we could find, but more may remain.
 *
 * LIMITATION: You cannot run more than one instance of Tor in the same
 * process at the same time. Concurrent calls will cause undefined behavior.
 * We do not currently have plans to change this.
 *
 * LIMITATION: While we will try to fix any problems found here, you
 * should be aware that Tor was originally written to run as its own
 * process, and that the functionality of this file was added later.  If
 * you find any bugs or strange behavior, please report them, and we'll
 * try to straighten them out.
 */
int tor_run_main(const tor_main_configuration_t *);

/**
 * Run the tor process, as if from the command line.
 *
 * @deprecated Using this function from outside Tor is deprecated; you should
 * use tor_run_main() instead.
 *
 * BUGS: This function has all the same bugs as tor_run_main().
 *
 * LIMITATIONS: This function has all the limitations of tor_run_main().
 */
int tor_main(int argc, char **argv);

#endif /* !defined(TOR_API_H) */


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>metageta.formats.digitalglobe.Dataset</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Trees

         Indices

         Help

MetaGETA (Metadata Gathering, Extraction and Transformation)

        Package metageta ::
        Package formats ::
        Module digitalglobe ::
        Class Dataset

[hide private]

[frames] | no frames]

Class Dataset

source code

         object --+
                  |
__dataset__.Dataset --+
                      |
    __default__.Dataset --+
                          |
                         Dataset

Subclass of __default__.Dataset class so we get a load of metadata
  populated automatically

        Instance Methods
        [hide private]

          __init__(self,
        f)

      In case subclasses don't override...

            source code

          __getmetadata__(self)

      Read Metadata for an Digital Globe format image as GDAL doesn't quite
      get it all...

            source code

          __gettilevrt__(self,
        f,
        imddata)

            source code

          __getimddata__(self,
        f)

            source code

      str

          getoverview(self,
        outfile=None,
        width=800,
        format='JPG')

      Generate overviews for Digital Globe imagery

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

      Inherited from __dataset__.Dataset

          __classproperty__(fcn)

      The class property decorator function

            source code

          __getfilelist__(self,
        *args,
        **kwargs)

      Get all files that have the same name (sans .ext), or are related
      according to gdalinfo.

            source code

          __setfileinfo__(self,
        f)

            source code

        Static Methods
        [hide private]

      Inherited from __dataset__.Dataset

      a new object with type S, a subtype of T

          __new__(self,
        f)

            source code

        Instance Variables
        [hide private]

      Inherited from __dataset__.Dataset

        _stretch

      self._stretch allows subclasses to control overview generation
      somewhat self._stretch = (stretch_type,rgb_bands,stretch_args) See overviews.getoverview for appropriate values.

        Properties
        [hide private]

Inherited from object:
      __class__

      Inherited from __dataset__.Dataset

        extent

        filelist

        metadata

        Method Details
        [hide private]

__init__(self,
        f)

(Constructor)

  	source code

In case subclasses don't override...

Overrides:
        object.__init__

(inherited documentation)

__getmetadata__(self)

  	source code

Read Metadata for an Digital Globe format image as GDAL doesn't quite
  get it all...

Parameters:

f - a filepath to the dataset or a VRT XML string

Returns:

None

Overrides:
        __dataset__.Dataset.__getmetadata__

To Do:
        Fix QB GDA94 Geographic CS "Unknown datum" problem

getoverview(self,
        outfile=None,
        width=800,
        format='JPG')

  	source code

Generate overviews for Digital Globe imagery

Parameters:

outfile (str) - a filepath to the output overview image. If supplied, format is
          determined from the file extension

width (int) - image width

format (str) - format to generate overview image, one of
          ['JPG','PNG','GIF','BMP','TIF']. Not required if outfile is
          supplied.

Returns: str

filepath (if outfile is supplied)/binary image data (if outfile
          is not supplied)

Overrides:
        __dataset__.Dataset.getoverview

         Trees

         Indices

         Help

MetaGETA (Metadata Gathering, Extraction and Transformation)

      http://epydoc.sourceforge.net


text:
🏗 Plugin Development Guide
============================

Sylius plugins are one of the most powerful ways to extend Sylius functionalities. They're not bounded by Sylius release cycle and can be
developed quicker and more effectively. They also allow sharing our (developers) work in an open-source community, which is not possible with
regular application customizations.

BDD methodology says the most accurate way to explain some process is using an example.
With respect to that rule, let's create some simple first plugin together!

.. toctree::
   :hidden:

   idea
   installation
   naming
   specification
   implementation
   summary

.. include:: /book/plugins/guide/map.rst.inc

.. seealso::

    :doc:`/book/plugins/index`
        The collection of Sylius Plugins and basic introduction to the concept of plugins.
    :doc:`/customization/index`
        Sylius customization techniques available to use also in plugins.


text:
'use strict';

var url = 'https://www.openice.info/files/github-downloads-data.txt';

function getDownloadsData (url, callback) {
    function parseDownloads (data) {
        var formattedData = data.map(function (obj) {
            var newInsert = [];
            obj.assets.forEach(function (value, index, array) {
                var newObj = {};
                newObj.dateRetrieved = obj.dateRetrieved;
                newObj.series = value.name;
                newObj.download_count = value.download_count;
                newInsert.push(newObj);
            });
            return newInsert;
        });

        var flattenedData = formattedData.reduce(function (a, b) {
            return a.concat(b);
        });

        callback(flattenedData);
    }

    d3.json(url, function (err, data) {
        if (err) {
            d3.json('example-data.json', function (err, data) {
                if (err) throw err;
                console.log('Using backup data');
                parseDownloads(data);
            });
        } else {
            parseDownloads(data);
        }
    });
}

function graph (data) {
    var assets = d3.nest().key(function (d) { return d.series; }).entries(data);

    data.forEach(function (value) {
        value.dateRetrieved = d3.time.format.iso.parse(value.dateRetrieved);
        value.download_count = +value.download_count;
    });

    var th = window.innerHeight * 0.75;
    var tw = window.innerWidth * 0.75;

    (window.innerWidth < 700) ? tw = 700 : tw;

    var margin = { top:75, right:200, bottom:75, left:75 };

    var h = th - (margin.top + margin.bottom);
    var w = tw - (margin.left + margin.right);

    var xScale = d3.time.scale()
                    .range([0, w])
                    .domain(d3.extent(data, function(d) { return d.dateRetrieved; }));
    var yScale = d3.scale.linear()
                    .range([h, 0]);

    var xAxis = d3.svg.axis()
                      .scale(xScale)
                      .orient("bottom")
                      .tickSize(-h, 0);

    var yAxis = d3.svg.axis()
                      .scale(yScale)
                      .orient("left");

    var stack = d3.layout.stack()
                  .offset("zero")
                  .values(function (d) { return d.values; })
                  .x(function (d) { return xScale(d.dateRetrieved); })
                  .y(function (d) { return d.download_count; })
                  .order("reverse");
    stack(assets);

    var maxy = 0;
    assets.forEach(function (v) {
        v.values.forEach(function (d) { maxy = ((d.y + d.y0) > maxy ? (d.y + d.y0) : maxy); });
    });
    yScale.domain([0, maxy]);

    var area = d3.svg.area()
                 .interpolate("linear")
                 .x(function (d) { return xScale(d.dateRetrieved); })
                 .y0(function (d) { return yScale(d.y0); })
                 .y1(function (d) { return yScale(d.y0 + d.y); });

    var line = d3.svg.line()
                     .interpolate("linear")
                     .x(function(d) { return xScale(d.dateRetrieved); })
                     .y(function(d) { return yScale(d.download_count); });

    var color = d3.scale.category20();

    var svg = d3.select("#graph-container")
                .append("svg")
                .attr("width", tw)
                .attr("height", th)
              .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var asset = svg.selectAll(".asset")
                   .data(assets)
                 .enter().append("g")
                   .attr("class", "asset");

    asset.append("path")
         .attr("class", "path")
         .attr("d", function (d) { return area(d.values); })
         .style("fill", function (d) { return color(d.key); })
         .style("stroke", "#333");

    svg.append("g")
       .attr("class", "x axis")
       .attr("transform", "translate(0," + h + ")")
       .call(xAxis);

    svg.append("g")
       .attr("class", "y axis")
       .call(yAxis)
     .append("text")
       .attr("transform", "rotate(-90)")
       .attr("dy", "-3em")
       .style("text-anchor", "end")
       .text("download_count");

    asset.append("text")
         .datum(function(d) { return { key: d.key, values: d.values[d.values.length - 1] }; })
         .attr("transform", function(d) { return "translate(" + xScale(d.values.dateRetrieved) + "," + yScale(d.values.y + d.values.y0) + ")"; })
         .attr("x", 3)
         .attr("dy", ".35em")
         .text(function(d) { return d.key; })
         .style("fill", function (d, i) { return color(d.key); });
}

getDownloadsData(url, function (data) {
    graph(data);
});


text:
package com.microsoft.azure.management.containerservice.v2019_04_01;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for OSType.
 */
public final class OSType extends ExpandableStringEnum<OSType> {
    /** Static value Linux for OSType. */
    public static final OSType LINUX = fromString("Linux");

    /** Static value Windows for OSType. */
    public static final OSType WINDOWS = fromString("Windows");

    /**
     * Creates or finds a OSType from its string representation.
     * @param name a name to look for
     * @return the corresponding OSType
     */
    @JsonCreator
    public static OSType fromString(String name) {
        return fromString(name, OSType.class);
    }

    /**
     * @return known OSType values
     */
    public static Collection<OSType> values() {
        return values(OSType.class);
    }
}


text: {{ note.text }}


text:
import FormState from '../FormState';
import {Values} from '../../FormStorage';

interface EventFormState extends FormState {
  values: Values;
  prevValues: Values;
}

export default interface FormStorageEventData {
  // TODO: почему бы событие не назвать formStorage
  target: 'form';
  // TODO: ??? Why ???
  event: 'storage';
  // TODO: новый стейт не нужен, его и так можно получить
  state: EventFormState;
  prevState: EventFormState;
  error?: Error;
}


text:
A user-defined component given to a `Route` as the `component` prop. The
router will inject properties into your component when its rendered.

Injected Props
--------------

### `children`

The matched child route elements to be rendered.

#### Example

```js
React.render((
  <Router history={HashHistory}>
    <Route path="/" component={App}>
      <Route path="groups" components={Groups}/>
      <Route path="users" components={Users}/>
    </Route>
  </Router>
), element);

var App = React.createClass({
  render () {
    return (
      <div>
        {/* this will be either <Users> or <Groups> */}
        {this.props.children}
      </div>
    );
  }
});
```

### Named Components

When a route has multiple components, the elements are available by name
on props. All route components can participate in the nesting.

#### Example

```js
React.render((
  <Router history={HashHistory}>
    <Route path="/" component={App}>
      <Route path="groups" components={{main: Groups, sidebar: GroupsSidebar}}/>
      <Route path="users" components={{main: Users, sidebar: UsersSidebar}}>
        <Route path="users/:userId" components={Profile}/>
      </Route>
    </Route>
  </Router>
), element);

var App = React.createClass({
  render () {
    // the matched child route components become props in the parent
    return (
      <div>
        <div className="Main">
          {/* this will either be <Groups> or <Users> */}
          {this.props.main}
        </div>
        <div className="Sidebar">
          {/* this will either be <GroupsSidebar> or <UsersSidebar> */}
          {this.props.sidebar}
        </div>
      </div>
    );
  }
});

var Users = React.createClass({
  render () {
    return (
      <div>
        {/* if at "/users/123" this will be <Profile> */}
        {/* UsersSidebar will also get <Profile> as this.props.children,
            you pick where it renders */}
        {this.props.children}
      </div>
    );
  }
});
```

### `params`

The dynamic segments of the url.

### `routeParams`

Subset of the dynamic segments of the url that relate to the route the
component belongs to. For example, if the route path is `users/:userId`
and the url is `/users/123/portfolios/345` then `props.routeParams` will be
`{userId: '123'}`, and `route.params` will be `{userId: '123',
portfolioId: 345}`.

### `location`

The [location][location] matched.

### `route`

The matched [Route][Route] the component belongs to.

Examples
--------

```js
// given a route like this:
<Route path="/course/:courseId/students" component={Students}/>

// and a url like this:
"/course/123/students?sort=name"

var Students = React.createClass({
  render () {
    this.props.params.courseId; // "123"
    this.props.location.query.sort; // "name"
    // ...
  }
});
```

  [transition]:#TODO
  [Route]:#TODO
  [location]:#TODO


text:
if [ "$UIMA_HOME" = "" ]
then
  echo UIMA_HOME environment variable is not set
  exit 1
fi

# set default ActiveMQ home
if [ "$ACTIVEMQ_HOME" = "" ]
then
  ACTIVEMQ_HOME=$UIMA_HOME/apache-activemq-5.4.1
fi

if [ "$JAVA_HOME" = "" ]
then
  UIMA_JAVA_CALL=java
else
  UIMA_JAVA_CALL="$JAVA_HOME/bin/java"
fi

#Set jar search order of: UIMA_CLASSPATH uima activemq(optional) tomcat(optional) CLASSPATH
UIMA_CLASSPATH=$UIMA_CLASSPATH:$UIMA_HOME/examples/resources
UIMA_CLASSPATH=$UIMA_CLASSPATH:$UIMA_HOME/lib
if [ -e "$ACTIVEMQ_HOME" ]
then
	UIMA_CLASSPATH=$UIMA_CLASSPATH:$ACTIVEMQ_HOME:$ACTIVEMQ_HOME/lib:$ACTIVEMQ_HOME/lib/optional
fi

# -n: true if string has non-zero length
if [ -n "$CATALINA_HOME" ]
then
	UIMA_CLASSPATH=$UIMA_CLASSPATH:$CATALINA_HOME/webapps/axis/WEB-INF/lib:$CATALINA_HOME/webapps/axis/WEB-INF/classes
fi

UIMA_CLASSPATH=$UIMA_CLASSPATH:$CLASSPATH

#set LD_LIBRARY_PATH to support running C++ annotators
if [ "$UIMACPP_HOME" = "" ]
then
  UIMACPP_HOME=$UIMA_HOME/uimacpp
fi

# The exports here are done in 2 lines because on some shells (dash)
# (used by Ubuntu) blanks in the substitutions (e.g., a dir whose name
# includes a blank) causes a failure
PATH=$UIMACPP_HOME/bin:$UIMACPP_HOME/examples/tutorial/src:$PATH
export PATH

LD_LIBRARY_PATH=$UIMACPP_HOME/lib:$UIMACPP_HOME/examples/tutorial/src:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

#also set DYLD_LIBRARY_PATH, used by Mac OSX
DYLD_LIBRARY_PATH=$UIMACPP_HOME/lib:$UIMACPP_HOME/examples/tutorial/src:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH

#also set default values for VNS_HOST and VNS_PORT
if [ "$VNS_HOST" = "" ];
then
  VNS_HOST=localhost
fi
if [ "$VNS_PORT" = "" ];
then
  VNS_PORT=9000
fi
#also set default value for UIMA_LOGGER_CONFIG_FILE
if [ "$UIMA_LOGGER_CONFIG_FILE" = "" ]
then
  UIMA_LOGGER_CONFIG_FILE=$UIMA_HOME/config/Logger.properties
fi
#set default JVM opts
if [ "$UIMA_JVM_OPTS" = "" ]
then
  UIMA_JVM_OPTS="-Xms128M -Xmx800M"
fi

# Check if Uima AS is installed, and if so set the default log4j configuration file
if [ -e "$UIMA_HOME"/as_config ]
then
	LOG4J_CONFIG_FILE=-Dlog4j.configuration=file:$UIMA_HOME/as_config/uimaAsLog4j.properties
else
#   Define a variable with an arbitrary no op value
	LOG4J_CONFIG_FILE=-DNoOp
fi

if [ "$UIMA_CVDMAN" = "" ]
then
  UIMA_CVDMAN=-Duima.tools.cvd.manpath.notset
fi

# Finally load the jars and run the class
"$UIMA_JAVA_CALL" -DVNS_HOST=$VNS_HOST -DVNS_PORT=$VNS_PORT "-Duima.home=$UIMA_HOME" "-Duima.datapath=$UIMA_DATAPATH" "-Djava.util.logging.config.file=$UIMA_LOGGER_CONFIG_FILE" "$UIMA_CVDMAN" $UIMA_JVM_OPTS "-Duima.use_jul_as_default_uima_logger" "$LOG4J_CONFIG_FILE" -DUimaBootstrapSuppressClassPathDisplay -Dorg.apache.uima.jarpath="$UIMA_CLASSPATH" -jar "$UIMA_HOME/lib/uimaj-bootstrap.jar" $@


text:
@implementation ArticleDetailModel

@end


text:
USE TelerikAcademy

SELECT FirstName + ' ' + LastName AS FullName, Salary
FROM Employees
WHERE Salary > 50000
ORDER BY Salary DESC


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `SelectionCache` struct in crate `rustc_typeck`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, SelectionCache">

    <title>rustc_typeck::middle::traits::SelectionCache - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc_typeck::<wbr>middle::<wbr>traits

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Struct rustc_typeck::<wbr>middle::<wbr>traits::<wbr>SelectionCache<wbr>Unstable
            [-] [+]
        [src]

pub struct SelectionCache<'tcx> {
    // some fields omitted
}

Methods

impl<'tcx> SelectionCache<'tcx>

fn new() -> SelectionCache<'tcx>

Trait Implementations

Derived Implementations

impl<'tcx> Clone for SelectionCache<'tcx>

fn clone(&self) -> SelectionCache<'tcx>

fn clone_from(&mut self, source: &Self)

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
namespace Springboard365.Xrm.Plugins.Core.Test
{
    using System;
    using Microsoft.Xrm.Sdk;

    public class DummyUnlockSalesOrderPricingPlugin : UnlockSalesOrderPricingPlugin
    {
        public IOrganizationService OrganizationService { get; private set; }

        public IPluginExecutionContext PluginExecutionContext { get; private set; }

        public ITracingService TracingService { get; private set; }

        public Guid SalesOrderId { get; private set; }

        protected override void Execute(
            IOrganizationService organizationService,
            IPluginExecutionContext pluginExecutionContext,
            ITracingService tracingService,
            Guid salesOrderId)
        {
            OrganizationService = organizationService;
            PluginExecutionContext = pluginExecutionContext;
            TracingService = tracingService;
            SalesOrderId = salesOrderId;
        }
    }
}


text:
class ChatNotificationService < Service
  include ChatMessage

  default_value_for :category, 'chat'

  prop_accessor :webhook, :username, :channel
  boolean_accessor :notify_only_broken_builds, :notify_only_broken_pipelines

  validates :webhook, presence: true, url: true, if: :activated?

  def initialize_properties
    # Custom serialized properties initialization
    self.supported_events.each { |event| self.class.prop_accessor(event_channel_name(event)) }

    if properties.nil?
      self.properties = {}
      self.notify_only_broken_builds = true
      self.notify_only_broken_pipelines = true
    end
  end

  def can_test?
    valid?
  end

  def self.supported_events
    %w[push issue confidential_issue merge_request note tag_push
       build pipeline wiki_page]
  end

  def execute(data)
    return unless supported_events.include?(data[:object_kind])
    return unless webhook.present?

    object_kind = data[:object_kind]

    data = data.merge(
      project_url: project_url,
      project_name: project_name
    )

    # WebHook events often have an 'update' event that follows a 'open' or
    # 'close' action. Ignore update events for now to prevent duplicate
    # messages from arriving.

    message = get_message(object_kind, data)

    return false unless message

    channel_name = get_channel_field(object_kind).presence || channel

    opts = {}
    opts[:channel] = channel_name if channel_name
    opts[:username] = username if username

    notifier = Slack::Notifier.new(webhook, opts)
    notifier.ping(message.pretext, attachments: message.attachments, fallback: message.fallback)

    true
  end

  def event_channel_names
    supported_events.map { |event| event_channel_name(event) }
  end

  def event_field(event)
    fields.find { |field| field[:name] == event_channel_name(event) }
  end

  def global_fields
    fields.reject { |field| field[:name].end_with?('channel') }
  end

  def default_channel_placeholder
    raise NotImplementedError
  end

  private

  def get_message(object_kind, data)
    case object_kind
    when "push", "tag_push"
      ChatMessage::PushMessage.new(data)
    when "issue"
      ChatMessage::IssueMessage.new(data) unless is_update?(data)
    when "merge_request"
      ChatMessage::MergeMessage.new(data) unless is_update?(data)
    when "note"
      ChatMessage::NoteMessage.new(data)
    when "build"
      ChatMessage::BuildMessage.new(data) if should_build_be_notified?(data)
    when "pipeline"
      ChatMessage::PipelineMessage.new(data) if should_pipeline_be_notified?(data)
    when "wiki_page"
      ChatMessage::WikiPageMessage.new(data)
    end
  end

  def get_channel_field(event)
    field_name = event_channel_name(event)
    self.public_send(field_name)
  end

  def build_event_channels
    supported_events.reduce([]) do |channels, event|
      channels << { type: 'text', name: event_channel_name(event), placeholder: default_channel_placeholder }
    end
  end

  def event_channel_name(event)
    "#{event}_channel"
  end

  def project_name
    project.name_with_namespace.gsub(/\s/, '')
  end

  def project_url
    project.web_url
  end

  def is_update?(data)
    data[:object_attributes][:action] == 'update'
  end

  def should_build_be_notified?(data)
    case data[:commit][:status]
    when 'success'
      !notify_only_broken_builds?
    when 'failed'
      true
    else
      false
    end
  end

  def should_pipeline_be_notified?(data)
    case data[:object_attributes][:status]
    when 'success'
      !notify_only_broken_pipelines?
    when 'failed'
      true
    else
      false
    end
  end
end


text:
#ifndef CETHER_INTF_H
#define CETHER_INTF_H

#include "BaseDefines.h"
#include "pppoe.h"
#include <string>

#define ETHER_INTF_NAME_SIZE 16

class CPPPOE;

/* An Ethernet interface */
class CEtherIntf
{
public:
    CEtherIntf(CPPPOE &pppoe);
    virtual ~CEtherIntf();

    CPPPOE &GetPppoe();
    void GetIntfName(CHAR acIntfName[ETHER_INTF_NAME_SIZE+1]);
    void SetIntfName(const CHAR acIntfName[ETHER_INTF_NAME_SIZE+1]);
    void GetIntfMac(BYTE acIntfMac[ETH_ALEN]);
    WORD16 GetIntfMtu() {return m_mtu;}
    void SetIntfMtu(WORD16 mtu) {m_mtu = mtu;}
    WORD32 GetIntfIp() {return m_ip;}
    void SetIntfIp(WORD32 ip) { m_ip = ip;}
    void SetIntfIp(std::string &ip);

    // SetIntfXXXByName() should be called after calling SetIntfName("xxxxx").
    int SetIntfMacByName();

private:
    CPPPOE &m_pppoe;
    CHAR m_name[ETHER_INTF_NAME_SIZE+1];	/* Interface name */
    BYTE m_mac[ETH_ALEN];       /* MAC address */
    WORD16 m_mtu;               /* MTU of interface. MTU¸øת·¢Óã¬ÓÉÈ«¾ÖÅäÖÃÀ´É趨 */
    WORD32 m_ip;                /* Ip address. In network byte order. */
};

#endif // CETHER_INTF_H