content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
remove didcommit from scheduler
fb30d235dbcf94f3ee5acc6ed5444132cf76028d
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> let isUnmounting: boolean = false; <ide> <ide> // Use these to prevent an infinite loop of nested updates <del> let didCommit = false; <ide> let nestedSyncUpdates = 0; <ide> let NESTED_SYNC_UPDATE_LIMIT = 1000; <ide> <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> priorityContext = nextPriorityLevel; <ide> <ide> if ( <del> didCommit && <del> (nextPriorityLevel === TaskPriority || <del> nextPriorityLevel === SynchronousPriority) <add> nextPriorityLevel === TaskPriority || <add> nextPriorityLevel === SynchronousPriority <ide> ) { <ide> invariant( <ide> nestedSyncUpdates++ <= NESTED_SYNC_UPDATE_LIMIT, <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> // local to this function is because errors that occur during cWU are <ide> // captured elsewhere, to prevent the unmount from being interrupted. <ide> isCommitting = true; <del> didCommit = true; <ide> if (__DEV__) { <ide> startCommitTimer(); <ide> } <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> firstUncaughtError = null; <ide> capturedErrors = null; <ide> failedBoundaries = null; <del> didCommit = false; <ide> nestedSyncUpdates = 0; <ide> if (__DEV__) { <ide> stopWorkLoopTimer();
1
Java
Java
fix window state comparison in dahandlermapping
9b10d38e41150fdbd4120e1058a34c5b986dd849
<ide><path>spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java <ide> /* <del> * Copyright 2002-2011 the original author or authors. <add> * Copyright 2002-2012 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public int compareTo(Object other) { <ide> } <ide> else if (other instanceof RenderMappingPredicate) { <ide> RenderMappingPredicate otherRender = (RenderMappingPredicate) other; <del> boolean hasWindowState = "".equals(this.windowState); <del> boolean otherHasWindowState = "".equals(otherRender.windowState); <add> boolean hasWindowState = (this.windowState != null); <add> boolean otherHasWindowState = (otherRender.windowState != null); <ide> if (hasWindowState != otherHasWindowState) { <ide> return (hasWindowState ? -1 : 1); <ide> }
1
Javascript
Javascript
fix instrumentation and add render instruments
299cdf8d5efd7107fc8c68869867402fa5b94421
<ide><path>packages/ember-handlebars/lib/views/handlebars_bound_view.js <ide> require('ember-handlebars/views/metamorph_view'); <ide> @private <ide> */ <ide> Ember._HandlebarsBoundView = Ember._MetamorphView.extend({ <add> instrumentName: 'render.boundHandlebars', <ide> <ide> /** <ide> The function used to determine if the `displayTemplate` or <ide><path>packages/ember-metal/lib/instrumentation.js <ide> Ember.Instrumentation.instrument = function(name, payload, callback, binding) { <ide> listeners = populateListeners(name); <ide> } <ide> <del> if (listeners.length === 0) { return; } <add> if (listeners.length === 0) { return callback.call(binding); } <ide> <del> var beforeValues = [], listener, i, l; <add> var beforeValues = [], listener, ret, i, l; <ide> <ide> try { <ide> for (i=0, l=listeners.length; i<l; i++) { <ide> listener = listeners[i]; <ide> beforeValues[i] = listener.before(name, new Date(), payload); <ide> } <ide> <del> callback.call(binding); <add> ret = callback.call(binding); <ide> } catch(e) { <ide> payload = payload || {}; <ide> payload.exception = e; <ide> Ember.Instrumentation.instrument = function(name, payload, callback, binding) { <ide> listener.after(name, new Date(), payload, beforeValues[i]); <ide> } <ide> } <add> <add> return ret; <ide> }; <ide> <ide> Ember.Instrumentation.subscribe = function(pattern, object) { <ide><path>packages/ember-views/lib/views/container_view.js <ide> Ember.ContainerView = Ember.View.extend({ <ide> }); <ide> }, <ide> <add> instrumentName: 'render.container', <add> <ide> /** <ide> @private <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> be used. <ide> */ <ide> renderToBuffer: function(parentBuffer, bufferOperation) { <add> var name = get(this, 'instrumentName'), <add> details = this.instrumentDetails({}); <add> <add> return Ember.instrument(name, details, function() { <add> return this._renderToBuffer(parentBuffer, bufferOperation); <add> }, this); <add> }, <add> <add> instrumentName: 'render.view', <add> <add> instrumentDetails: function(hash) { <add> hash.template = get(this, 'templateName'); <add> hash.type = this.constructor.toString(); <add> }, <add> <add> _renderToBuffer: function(parentBuffer, bufferOperation) { <ide> var buffer; <ide> <ide> Ember.run.sync();
4
PHP
PHP
remove old schema object
d28a200699171e043bcc31051e93fe5376cc8569
<ide><path>lib/Cake/Model/Schema.php <del><?php <del>/** <del> * Schema database management for CakePHP. <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Model <del> * @since CakePHP(tm) v 1.2.0.5550 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Model; <del> <del>use Cake\Core\App; <del>use Cake\Core\Configure; <del>use Cake\Core\Object; <del>use Cake\Core\Plugin; <del>use Cake\Error; <del>use Cake\Utility\ClassRegistry; <del>use Cake\Utility\File; <del>use Cake\Utility\Inflector; <del> <del>/** <del> * Base Class for Schema management <del> * <del> * @package Cake.Model <del> */ <del>class Schema extends Object { <del> <del>/** <del> * Name of the schema <del> * <del> * @var string <del> */ <del> public $name = null; <del> <del>/** <del> * Path to write location <del> * <del> * @var string <del> */ <del> public $path = null; <del> <del>/** <del> * File to write <del> * <del> * @var string <del> */ <del> public $file = 'schema.php'; <del> <del>/** <del> * Connection used for read <del> * <del> * @var string <del> */ <del> public $connection = 'default'; <del> <del>/** <del> * plugin name. <del> * <del> * @var string <del> */ <del> public $plugin = null; <del> <del>/** <del> * Set of tables <del> * <del> * @var array <del> */ <del> public $tables = array(); <del> <del>/** <del> * Constructor <del> * <del> * @param array $options optional load object properties <del> */ <del> public function __construct($options = array()) { <del> parent::__construct(); <del> <del> if (empty($options['name'])) { <del> $this->name = preg_replace('/schema$/i', '', get_class($this)); <del> } <del> if (!empty($options['plugin'])) { <del> $this->plugin = $options['plugin']; <del> } <del> <del> if (strtolower($this->name) === 'cake') { <del> $this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir'))); <del> } <del> <del> if (empty($options['path'])) { <del> $this->path = APP . 'Config/Schema'; <del> } <del> <del> $options = array_merge(get_object_vars($this), $options); <del> $this->build($options); <del> } <del> <del>/** <del> * Builds schema object properties <del> * <del> * @param array $data loaded object properties <del> * @return void <del> */ <del> public function build($data) { <del> $file = null; <del> foreach ($data as $key => $val) { <del> if (!empty($val)) { <del> if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) { <del> if ($key[0] === '_') { <del> continue; <del> } <del> $this->tables[$key] = $val; <del> unset($this->{$key}); <del> } elseif ($key !== 'tables') { <del> if ($key === 'name' && $val !== $this->name && !isset($data['file'])) { <del> $file = Inflector::underscore($val) . '.php'; <del> } <del> $this->{$key} = $val; <del> } <del> } <del> } <del> if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) { <del> $this->file = $file; <del> } elseif (!empty($this->plugin)) { <del> $this->path = Plugin::path($this->plugin) . 'Config/Schema'; <del> } <del> } <del> <del>/** <del> * Before callback to be implemented in subclasses <del> * <del> * @param array $event schema object properties <del> * @return boolean Should process continue <del> */ <del> public function before($event = array()) { <del> return true; <del> } <del> <del>/** <del> * After callback to be implemented in subclasses <del> * <del> * @param array $event schema object properties <del> * @return void <del> */ <del> public function after($event = array()) { <del> } <del> <del>/** <del> * Reads database and creates schema tables <del> * <del> * @param array $options schema object properties <del> * @return array Set of name and tables <del> */ <del> public function load($options = array()) { <del> if (is_string($options)) { <del> $options = array('path' => $options); <del> } <del> <del> $this->build($options); <del> extract(get_object_vars($this)); <del> <del> $class = $name . 'Schema'; <del> <del> if (!class_exists($class)) { <del> if (file_exists($path . DS . $file) && is_file($path . DS . $file)) { <del> require_once $path . DS . $file; <del> } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) { <del> require_once $path . DS . 'schema.php'; <del> } <del> } <del> <del> if (class_exists($class)) { <del> $Schema = new $class($options); <del> return $Schema; <del> } <del> return false; <del> } <del> <del>/** <del> * Reads database and creates schema tables <del> * <del> * Options <del> * <del> * - 'connection' - the db connection to use <del> * - 'name' - name of the schema <del> * - 'models' - a list of models to use, or false to ignore models <del> * <del> * @param array $options schema object properties <del> * @return array Array indexed by name and tables <del> */ <del> public function read($options = array()) { <del> extract(array_merge( <del> array( <del> 'connection' => $this->connection, <del> 'name' => $this->name, <del> 'models' => true, <del> ), <del> $options <del> )); <del> $db = ConnectionManager::getDataSource($connection); <del> <del> $tables = array(); <del> $currentTables = (array)$db->listSources(); <del> <del> $prefix = null; <del> if (isset($db->config['prefix'])) { <del> $prefix = $db->config['prefix']; <del> } <del> <del> if (!is_array($models) && $models !== false) { <del> if (isset($this->plugin)) { <del> $models = App::objects($this->plugin . '.Model', null, false); <del> } else { <del> $models = App::objects('Model'); <del> } <del> } <del> <del> if (is_array($models)) { <del> foreach ($models as $model) { <del> $importModel = $model; <del> $plugin = null; <del> if ($model === 'AppModel') { <del> continue; <del> } <del> <del> if (isset($this->plugin)) { <del> if ($model == $this->plugin . 'AppModel') { <del> continue; <del> } <del> $importModel = $model; <del> $plugin = $this->plugin . '.'; <del> } <del> <del> $importModel = App::classname($plugin . $importModel, 'Model'); <del> if (!class_exists($importModel)) { <del> continue; <del> } <del> <del> $vars = get_class_vars($model); <del> if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) { <del> continue; <del> } <del> <del> try { <del> $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection)); <del> } catch (Error\Exception $e) { <del> continue; <del> } <del> <del> if (!is_object($Object) || $Object->useTable === false) { <del> continue; <del> } <del> $db = $Object->getDataSource(); <del> <del> $fulltable = $table = $db->fullTableName($Object, false, false); <del> if ($prefix && strpos($table, $prefix) !== 0) { <del> continue; <del> } <del> if (!in_array($fulltable, $currentTables)) { <del> continue; <del> } <del> <del> $table = $this->_noPrefixTable($prefix, $table); <del> <del> $key = array_search($fulltable, $currentTables); <del> if (empty($tables[$table])) { <del> $tables[$table] = $this->_columns($Object); <del> $tables[$table]['indexes'] = $db->index($Object); <del> $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); <del> unset($currentTables[$key]); <del> } <del> if (empty($Object->hasAndBelongsToMany)) { <del> continue; <del> } <del> foreach ($Object->hasAndBelongsToMany as $assocData) { <del> if (isset($assocData['with'])) { <del> $class = $assocData['with']; <del> } <del> if (!is_object($Object->$class)) { <del> continue; <del> } <del> $withTable = $db->fullTableName($Object->$class, false, false); <del> if ($prefix && strpos($withTable, $prefix) !== 0) { <del> continue; <del> } <del> if (in_array($withTable, $currentTables)) { <del> $key = array_search($withTable, $currentTables); <del> $noPrefixWith = $this->_noPrefixTable($prefix, $withTable); <del> <del> $tables[$noPrefixWith] = $this->_columns($Object->$class); <del> $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class); <del> $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable); <del> unset($currentTables[$key]); <del> } <del> } <del> } <del> } <del> <del> if (!empty($currentTables)) { <del> foreach ($currentTables as $table) { <del> if ($prefix) { <del> if (strpos($table, $prefix) !== 0) { <del> continue; <del> } <del> $table = $this->_noPrefixTable($prefix, $table); <del> } <del> $modelClass = App::classname('Model', 'Model'); <del> $Object = new $modelClass(array( <del> 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection <del> )); <del> <del> $systemTables = array( <del> 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n' <del> ); <del> <del> $fulltable = $db->fullTableName($Object, false, false); <del> <del> if (in_array($table, $systemTables)) { <del> $tables[$Object->table] = $this->_columns($Object); <del> $tables[$Object->table]['indexes'] = $db->index($Object); <del> $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable); <del> } elseif ($models === false) { <del> $tables[$table] = $this->_columns($Object); <del> $tables[$table]['indexes'] = $db->index($Object); <del> $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); <del> } else { <del> $tables['missing'][$table] = $this->_columns($Object); <del> $tables['missing'][$table]['indexes'] = $db->index($Object); <del> $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable); <del> } <del> } <del> } <del> <del> ksort($tables); <del> return compact('name', 'tables'); <del> } <del> <del>/** <del> * Writes schema file from object or options <del> * <del> * @param array|object $object schema object or options array <del> * @param array $options schema object properties to override object <del> * @return mixed false or string written to file <del> */ <del> public function write($object, $options = array()) { <del> if (is_object($object)) { <del> $object = get_object_vars($object); <del> $this->build($object); <del> } <del> <del> if (is_array($object)) { <del> $options = $object; <del> unset($object); <del> } <del> <del> extract(array_merge( <del> get_object_vars($this), $options <del> )); <del> <del> $out = "class {$name}Schema extends Schema {\n\n"; <del> <del> if ($path !== $this->path) { <del> $out .= "\tpublic \$path = '{$path}';\n\n"; <del> } <del> <del> if ($file !== $this->file) { <del> $out .= "\tpublic \$file = '{$file}';\n\n"; <del> } <del> <del> if ($connection !== 'default') { <del> $out .= "\tpublic \$connection = '{$connection}';\n\n"; <del> } <del> <del> $out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n"; <del> <del> if (empty($tables)) { <del> $this->read(); <del> } <del> <del> foreach ($tables as $table => $fields) { <del> if (!is_numeric($table) && $table !== 'missing') { <del> $out .= $this->generateTable($table, $fields); <del> } <del> } <del> $out .= "}\n"; <del> <del> $file = new File($path . DS . $file, true); <del> $content = "<?php \n{$out}"; <del> if ($file->write($content)) { <del> return $content; <del> } <del> return false; <del> } <del> <del>/** <del> * Generate the code for a table. Takes a table name and $fields array <del> * Returns a completed variable declaration to be used in schema classes <del> * <del> * @param string $table Table name you want returned. <del> * @param array $fields Array of field information to generate the table with. <del> * @return string Variable declaration for a schema class <del> */ <del> public function generateTable($table, $fields) { <del> $out = "\tpublic \${$table} = array(\n"; <del> if (is_array($fields)) { <del> $cols = array(); <del> foreach ($fields as $field => $value) { <del> if ($field !== 'indexes' && $field !== 'tableParameters') { <del> if (is_string($value)) { <del> $type = $value; <del> $value = array('type' => $type); <del> } <del> $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', "; <del> unset($value['type']); <del> $col .= implode(', ', $this->_values($value)); <del> } elseif ($field === 'indexes') { <del> $col = "\t\t'indexes' => array(\n\t\t\t"; <del> $props = array(); <del> foreach ((array)$value as $key => $index) { <del> $props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")"; <del> } <del> $col .= implode(",\n\t\t\t", $props) . "\n\t\t"; <del> } elseif ($field === 'tableParameters') { <del> $col = "\t\t'tableParameters' => array("; <del> $props = array(); <del> foreach ((array)$value as $key => $param) { <del> $props[] = "'{$key}' => '$param'"; <del> } <del> $col .= implode(', ', $props); <del> } <del> $col .= ")"; <del> $cols[] = $col; <del> } <del> $out .= implode(",\n", $cols); <del> } <del> $out .= "\n\t);\n\n"; <del> return $out; <del> } <del> <del>/** <del> * Compares two sets of schemas <del> * <del> * @param array|object $old Schema object or array <del> * @param array|object $new Schema object or array <del> * @return array Tables (that are added, dropped, or changed) <del> */ <del> public function compare($old, $new = null) { <del> if (empty($new)) { <del> $new = $this; <del> } <del> if (is_array($new)) { <del> if (isset($new['tables'])) { <del> $new = $new['tables']; <del> } <del> } else { <del> $new = $new->tables; <del> } <del> <del> if (is_array($old)) { <del> if (isset($old['tables'])) { <del> $old = $old['tables']; <del> } <del> } else { <del> $old = $old->tables; <del> } <del> $tables = array(); <del> foreach ($new as $table => $fields) { <del> if ($table === 'missing') { <del> continue; <del> } <del> if (!array_key_exists($table, $old)) { <del> $tables[$table]['create'] = $fields; <del> } else { <del> $diff = $this->_arrayDiffAssoc($fields, $old[$table]); <del> if (!empty($diff)) { <del> $tables[$table]['add'] = $diff; <del> } <del> $diff = $this->_arrayDiffAssoc($old[$table], $fields); <del> if (!empty($diff)) { <del> $tables[$table]['drop'] = $diff; <del> } <del> } <del> <del> foreach ($fields as $field => $value) { <del> if (!empty($old[$table][$field])) { <del> $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]); <del> if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') { <del> $tables[$table]['change'][$field] = $value; <del> } <del> } <del> <del> if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') { <del> $wrapper = array_keys($fields); <del> if ($column = array_search($field, $wrapper)) { <del> if (isset($wrapper[$column - 1])) { <del> $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1]; <del> } <del> } <del> } <del> } <del> <del> if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) { <del> $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']); <del> if ($diff) { <del> if (!isset($tables[$table])) { <del> $tables[$table] = array(); <del> } <del> if (isset($diff['drop'])) { <del> $tables[$table]['drop']['indexes'] = $diff['drop']; <del> } <del> if ($diff && isset($diff['add'])) { <del> $tables[$table]['add']['indexes'] = $diff['add']; <del> } <del> } <del> } <del> if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) { <del> $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']); <del> if ($diff) { <del> $tables[$table]['change']['tableParameters'] = $diff; <del> } <del> } <del> } <del> return $tables; <del> } <del> <del>/** <del> * Extended array_diff_assoc noticing change from/to NULL values <del> * <del> * It behaves almost the same way as array_diff_assoc except for NULL values: if <del> * one of the values is not NULL - change is detected. It is useful in situation <del> * where one value is strval('') ant other is strval(null) - in string comparing <del> * methods this results as EQUAL, while it is not. <del> * <del> * @param array $array1 Base array <del> * @param array $array2 Corresponding array checked for equality <del> * @return array Difference as array with array(keys => values) from input array <del> * where match was not found. <del> */ <del> protected function _arrayDiffAssoc($array1, $array2) { <del> $difference = array(); <del> foreach ($array1 as $key => $value) { <del> if (!array_key_exists($key, $array2)) { <del> $difference[$key] = $value; <del> continue; <del> } <del> $correspondingValue = $array2[$key]; <del> if (is_null($value) !== is_null($correspondingValue)) { <del> $difference[$key] = $value; <del> continue; <del> } <del> if (is_bool($value) !== is_bool($correspondingValue)) { <del> $difference[$key] = $value; <del> continue; <del> } <del> if (is_array($value) && is_array($correspondingValue)) { <del> continue; <del> } <del> if ($value === $correspondingValue) { <del> continue; <del> } <del> $difference[$key] = $value; <del> } <del> return $difference; <del> } <del> <del>/** <del> * Formats Schema columns from Model Object <del> * <del> * @param array $values options keys(type, null, default, key, length, extra) <del> * @return array Formatted values <del> */ <del> protected function _values($values) { <del> $vals = array(); <del> if (is_array($values)) { <del> foreach ($values as $key => $val) { <del> if (is_array($val)) { <del> $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")"; <del> } else { <del> $val = var_export($val, true); <del> if ($val === 'NULL') { <del> $val = 'null'; <del> } <del> if (!is_numeric($key)) { <del> $vals[] = "'{$key}' => {$val}"; <del> } else { <del> $vals[] = "{$val}"; <del> } <del> } <del> } <del> } <del> return $vals; <del> } <del> <del>/** <del> * Formats Schema columns from Model Object <del> * <del> * @param array $Obj model object <del> * @return array Formatted columns <del> */ <del> protected function _columns(&$Obj) { <del> $db = $Obj->getDataSource(); <del> $fields = $Obj->schema(true); <del> <del> $columns = array(); <del> foreach ($fields as $name => $value) { <del> if ($Obj->primaryKey == $name) { <del> $value['key'] = 'primary'; <del> } <del> if (!isset($db->columns[$value['type']])) { <del> trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s for %s.%s does not exist in DBO', $value['type'], $Obj->name, $name), E_USER_NOTICE); <del> continue; <del> } else { <del> $defaultCol = $db->columns[$value['type']]; <del> if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) { <del> unset($value['length']); <del> } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) { <del> unset($value['length']); <del> } <del> unset($value['limit']); <del> } <del> <del> if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) { <del> unset($value['default']); <del> } <del> if (empty($value['length'])) { <del> unset($value['length']); <del> } <del> if (empty($value['key'])) { <del> unset($value['key']); <del> } <del> $columns[$name] = $value; <del> } <del> <del> return $columns; <del> } <del> <del>/** <del> * Compare two schema files table Parameters <del> * <del> * @param array $new New indexes <del> * @param array $old Old indexes <del> * @return mixed False on failure, or an array of parameters to add & drop. <del> */ <del> protected function _compareTableParameters($new, $old) { <del> if (!is_array($new) || !is_array($old)) { <del> return false; <del> } <del> $change = $this->_arrayDiffAssoc($new, $old); <del> return $change; <del> } <del> <del>/** <del> * Compare two schema indexes <del> * <del> * @param array $new New indexes <del> * @param array $old Old indexes <del> * @return mixed false on failure or array of indexes to add and drop <del> */ <del> protected function _compareIndexes($new, $old) { <del> if (!is_array($new) || !is_array($old)) { <del> return false; <del> } <del> <del> $add = $drop = array(); <del> <del> $diff = $this->_arrayDiffAssoc($new, $old); <del> if (!empty($diff)) { <del> $add = $diff; <del> } <del> <del> $diff = $this->_arrayDiffAssoc($old, $new); <del> if (!empty($diff)) { <del> $drop = $diff; <del> } <del> <del> foreach ($new as $name => $value) { <del> if (isset($old[$name])) { <del> $newUnique = isset($value['unique']) ? $value['unique'] : 0; <del> $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0; <del> $newColumn = $value['column']; <del> $oldColumn = $old[$name]['column']; <del> <del> $diff = false; <del> <del> if ($newUnique != $oldUnique) { <del> $diff = true; <del> } elseif (is_array($newColumn) && is_array($oldColumn)) { <del> $diff = ($newColumn !== $oldColumn); <del> } elseif (is_string($newColumn) && is_string($oldColumn)) { <del> $diff = ($newColumn != $oldColumn); <del> } else { <del> $diff = true; <del> } <del> if ($diff) { <del> $drop[$name] = null; <del> $add[$name] = $value; <del> } <del> } <del> } <del> return array_filter(compact('add', 'drop')); <del> } <del> <del>/** <del> * Trim the table prefix from the full table name, and return the prefix-less table <del> * <del> * @param string $prefix Table prefix <del> * @param string $table Full table name <del> * @return string Prefix-less table name <del> */ <del> protected function _noPrefixTable($prefix, $table) { <del> return preg_replace('/^' . preg_quote($prefix) . '/', '', $table); <del> } <del> <del>} <ide><path>lib/Cake/Test/TestCase/Model/SchemaTest.php <del><?php <del>/** <del> * Test for Schema database management <del> * <del> * <del> * PHP 5 <del> * <del> * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html> <del> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <del> * @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests <del> * @package Cake.Test.Case.Model <del> * @since CakePHP(tm) v 1.2.0.5550 <del> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <del> */ <del>namespace Cake\Test\TestCase\Model; <del> <del>use Cake\Core\Plugin; <del>use Cake\Model\Schema; <del>use Cake\TestSuite\Fixture\TestFixture; <del>use Cake\TestSuite\Fixture\TestModel; <del>use Cake\TestSuite\TestCase; <del> <del>/** <del> * Test for Schema database management <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class MyAppSchema extends Schema { <del> <del>/** <del> * name property <del> * <del> * @var string 'MyApp' <del> */ <del> public $name = 'MyApp'; <del> <del>/** <del> * connection property <del> * <del> * @var string 'test' <del> */ <del> public $connection = 'test'; <del> <del>/** <del> * comments property <del> * <del> * @var array <del> */ <del> public $comments = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), <del> 'user_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false, 'length' => 100), <del> 'comment' => array('type' => 'text', 'null' => false, 'default' => null), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> ); <del> <del>/** <del> * posts property <del> * <del> * @var array <del> */ <del> public $posts = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''), <del> 'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'), <del> 'body' => array('type' => 'text', 'null' => true, 'default' => null), <del> 'summary' => array('type' => 'text', 'null' => true), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> ); <del> <del>/** <del> * _foo property <del> * <del> * @var array <del> */ <del> protected $_foo = array('bar'); <del> <del>/** <del> * setup method <del> * <del> * @param mixed $version <del> * @return void <del> */ <del> public function setup($version) { <del> } <del> <del>/** <del> * teardown method <del> * <del> * @param mixed $version <del> * @return void <del> */ <del> public function teardown($version) { <del> } <del> <del>/** <del> * getVar method <del> * <del> * @param string $var Name of var <del> * @return mixed <del> */ <del> public function getVar($var) { <del> if (!isset($this->$var)) { <del> return null; <del> } <del> return $this->$var; <del> } <del> <del>} <del> <del>/** <del> * TestAppSchema class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class TestAppSchema extends Schema { <del> <del>/** <del> * name property <del> * <del> * @var string 'MyApp' <del> */ <del> public $name = 'MyApp'; <del> <del>/** <del> * comments property <del> * <del> * @var array <del> */ <del> public $comments = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0,'key' => 'primary'), <del> 'article_id' => array('type' => 'integer', 'null' => false), <del> 'user_id' => array('type' => 'integer', 'null' => false), <del> 'comment' => array('type' => 'text', 'null' => true, 'default' => null), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> 'tableParameters' => array(), <del> ); <del> <del>/** <del> * posts property <del> * <del> * @var array <del> */ <del> public $posts = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false), <del> 'body' => array('type' => 'text', 'null' => true, 'default' => null), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> 'tableParameters' => array(), <del> ); <del> <del>/** <del> * posts_tags property <del> * <del> * @var array <del> */ <del> public $posts_tags = array( <del> 'post_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), <del> 'tag_id' => array('type' => 'string', 'null' => false, 'key' => 'primary'), <del> 'indexes' => array('posts_tag' => array('column' => array('tag_id', 'post_id'), 'unique' => 1)), <del> 'tableParameters' => array() <del> ); <del> <del>/** <del> * tags property <del> * <del> * @var array <del> */ <del> public $tags = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'tag' => array('type' => 'string', 'null' => false), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> 'tableParameters' => array() <del> ); <del> <del>/** <del> * datatypes property <del> * <del> * @var array <del> */ <del> public $datatypes = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'float_field' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => ''), <del> 'huge_int' => array('type' => 'biginteger'), <del> 'bool' => array('type' => 'boolean', 'null' => false, 'default' => false), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> 'tableParameters' => array() <del> ); <del> <del>/** <del> * setup method <del> * <del> * @param mixed $version <del> * @return void <del> */ <del> public function setup($version) { <del> } <del> <del>/** <del> * teardown method <del> * <del> * @param mixed $version <del> * @return void <del> */ <del> public function teardown($version) { <del> } <del> <del>} <del> <del>/** <del> * SchemaPost class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaPost extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'SchemaPost' <del> */ <del> public $name = 'SchemaPost'; <del> <del>/** <del> * useTable property <del> * <del> * @var string 'posts' <del> */ <del> public $useTable = 'posts'; <del> <del>/** <del> * hasMany property <del> * <del> * @var array <del> */ <del> public $hasMany = array('SchemaComment'); <del> <del>/** <del> * hasAndBelongsToMany property <del> * <del> * @var array <del> */ <del> public $hasAndBelongsToMany = array('SchemaTag'); <del>} <del> <del>/** <del> * SchemaComment class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaComment extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'SchemaComment' <del> */ <del> public $name = 'SchemaComment'; <del> <del>/** <del> * useTable property <del> * <del> * @var string 'comments' <del> */ <del> public $useTable = 'comments'; <del> <del>/** <del> * belongsTo property <del> * <del> * @var array <del> */ <del> public $belongsTo = array('SchemaPost'); <del>} <del> <del>/** <del> * SchemaTag class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaTag extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'SchemaTag' <del> */ <del> public $name = 'SchemaTag'; <del> <del>/** <del> * useTable property <del> * <del> * @var string 'tags' <del> */ <del> public $useTable = 'tags'; <del> <del>/** <del> * hasAndBelongsToMany property <del> * <del> * @var array <del> */ <del> public $hasAndBelongsToMany = array('SchemaPost'); <del>} <del> <del>/** <del> * SchemaDatatype class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaDatatype extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'SchemaDatatype' <del> */ <del> public $name = 'SchemaDatatype'; <del> <del>/** <del> * useTable property <del> * <del> * @var string 'datatypes' <del> */ <del> public $useTable = 'datatypes'; <del>} <del> <del>/** <del> * Testdescribe class <del> * <del> * This class is defined purely to inherit the cacheSources variable otherwise <del> * testSchemaCreateTable will fail if listSources has already been called and <del> * its source cache populated - I.e. if the test is run within a group <del> * <del> * @uses TestModel <del> * @package <del> * @package Cake.Test.Case.Model <del> */ <del>class Testdescribe extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'Testdescribe' <del> */ <del> public $name = 'Testdescribe'; <del>} <del> <del>/** <del> * SchemaCrossDatabase class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaCrossDatabase extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string 'SchemaCrossDatabase' <del> */ <del> public $name = 'SchemaCrossDatabase'; <del> <del>/** <del> * useTable property <del> * <del> * @var string 'posts' <del> */ <del> public $useTable = 'cross_database'; <del> <del>/** <del> * useDbConfig property <del> * <del> * @var string 'test2' <del> */ <del> public $useDbConfig = 'test2'; <del>} <del> <del>/** <del> * SchemaCrossDatabaseFixture class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaCrossDatabaseFixture extends TestFixture { <del> <del>/** <del> * name property <del> * <del> * @var string 'CrossDatabase' <del> */ <del> public $name = 'CrossDatabase'; <del> <del>/** <del> * table property <del> * <del> */ <del> public $table = 'cross_database'; <del> <del>/** <del> * fields property <del> * <del> * @var array <del> */ <del> public $fields = array( <del> 'id' => array('type' => 'integer', 'key' => 'primary'), <del> 'name' => 'string' <del> ); <del> <del>/** <del> * records property <del> * <del> * @var array <del> */ <del> public $records = array( <del> array('id' => 1, 'name' => 'First'), <del> array('id' => 2, 'name' => 'Second'), <del> ); <del>} <del> <del>/** <del> * SchemaPrefixAuthUser class <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaPrefixAuthUser extends TestModel { <del> <del>/** <del> * name property <del> * <del> * @var string <del> */ <del> public $name = 'SchemaPrefixAuthUser'; <del> <del>/** <del> * table prefix <del> * <del> * @var string <del> */ <del> public $tablePrefix = 'auth_'; <del> <del>/** <del> * useTable <del> * <del> * @var string <del> */ <del> public $useTable = 'users'; <del>} <del> <del>/** <del> * SchemaTest <del> * <del> * @package Cake.Test.Case.Model <del> */ <del>class SchemaTest extends TestCase { <del> <del>/** <del> * fixtures property <del> * <del> * @var array <del> */ <del> public $fixtures = array( <del> 'core.post', 'core.tag', 'core.posts_tag', 'core.test_plugin_comment', <del> 'core.datatype', 'core.auth_user', 'core.author', <del> 'core.test_plugin_article', 'core.user', 'core.comment', <del> 'core.prefix_test' <del> ); <del> <del>/** <del> * setUp method <del> * <del> * @return void <del> */ <del> public function setUp() { <del> parent::setUp(); <del> $this->markTestIncomplete('Not runnable until Models are fixed.'); <del> ConnectionManager::getDataSource('test')->cacheSources = false; <del> $this->Schema = new TestAppSchema(); <del> } <del> <del>/** <del> * tearDown method <del> * <del> * @return void <del> */ <del> public function tearDown() { <del> parent::tearDown(); <del> if (file_exists(TMP . 'tests/schema.php')) { <del> unlink(TMP . 'tests/schema.php'); <del> } <del> unset($this->Schema); <del> Plugin::unload(); <del> } <del> <del>/** <del> * testSchemaName method <del> * <del> * @return void <del> */ <del> public function testSchemaName() { <del> $Schema = new Schema(); <del> $this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $Schema->name); <del> <del> Configure::write('App.dir', 'Some.name.with.dots'); <del> $Schema = new Schema(); <del> $this->assertEquals('SomeNameWithDots', $Schema->name); <del> <del> Configure::write('App.dir', 'Some-name-with-dashes'); <del> $Schema = new Schema(); <del> $this->assertEquals('SomeNameWithDashes', $Schema->name); <del> <del> Configure::write('App.dir', 'Some name with spaces'); <del> $Schema = new Schema(); <del> $this->assertEquals('SomeNameWithSpaces', $Schema->name); <del> <del> Configure::write('App.dir', 'Some,name;with&weird=characters'); <del> $Schema = new Schema(); <del> $this->assertEquals('SomeNameWithWeirdCharacters', $Schema->name); <del> <del> Configure::write('App.dir', 'app'); <del> } <del> <del>/** <del> * testSchemaRead method <del> * <del> * @return void <del> */ <del> public function testSchemaRead() { <del> $read = $this->Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaPost', 'SchemaComment', 'SchemaTag', 'SchemaDatatype') <del> )); <del> unset($read['tables']['missing']); <del> <del> $expected = array('comments', 'datatypes', 'posts', 'posts_tags', 'tags'); <del> foreach ($expected as $table) { <del> $this->assertTrue(isset($read['tables'][$table]), 'Missing table ' . $table); <del> } <del> foreach ($this->Schema->tables as $table => $fields) { <del> $this->assertEquals(array_keys($fields), array_keys($read['tables'][$table])); <del> } <del> <del> if (isset($read['tables']['datatypes']['float_field']['length'])) { <del> $this->assertEquals( <del> $read['tables']['datatypes']['float_field']['length'], <del> $this->Schema->tables['datatypes']['float_field']['length'] <del> ); <del> } <del> <del> $this->assertEquals( <del> $read['tables']['datatypes']['float_field']['type'], <del> $this->Schema->tables['datatypes']['float_field']['type'] <del> ); <del> <del> $this->assertEquals( <del> $read['tables']['datatypes']['float_field']['null'], <del> $this->Schema->tables['datatypes']['float_field']['null'] <del> ); <del> <del> $db = ConnectionManager::getDataSource('test'); <del> $config = $db->config; <del> $config['prefix'] = 'schema_test_prefix_'; <del> ConnectionManager::create('schema_prefix', $config); <del> $read = $this->Schema->read(array('connection' => 'schema_prefix', 'models' => false)); <del> $this->assertTrue(empty($read['tables'])); <del> <del> $read = $this->Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaComment', 'SchemaTag', 'SchemaPost') <del> )); <del> $this->assertFalse(isset($read['tables']['missing']['posts_tags']), 'Join table marked as missing'); <del> } <del> <del>/** <del> * testSchemaReadWithAppModel method <del> * <del> * @access public <del> * @return void <del> */ <del> public function testSchemaReadWithAppModel() { <del> $connections = ConnectionManager::enumConnectionObjects(); <del> ConnectionManager::drop('default'); <del> ConnectionManager::create('default', $connections['test']); <del> try { <del> $this->Schema->read(array( <del> 'connection' => 'default', <del> 'name' => 'TestApp', <del> 'models' => array('AppModel') <del> )); <del> } catch(MissingTableException $mte) { <del> ConnectionManager::drop('default'); <del> $this->fail($mte->getMessage()); <del> } <del> ConnectionManager::drop('default'); <del> } <del> <del>/** <del> * testSchemaReadWithOddTablePrefix method <del> * <del> * @return void <del> */ <del> public function testSchemaReadWithOddTablePrefix() { <del> $config = ConnectionManager::getDataSource('test')->config; <del> $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); <del> <del> $SchemaPost = ClassRegistry::init('SchemaPost'); <del> $SchemaPost->tablePrefix = 'po'; <del> $SchemaPost->useTable = 'sts'; <del> $read = $this->Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaPost') <del> )); <del> <del> $this->assertFalse(isset($read['tables']['missing']['posts']), 'Posts table was not read from tablePrefix'); <del> } <del> <del>/** <del> * test read() with tablePrefix properties. <del> * <del> * @return void <del> */ <del> public function testSchemaReadWithTablePrefix() { <del> $config = ConnectionManager::getDataSource('test')->config; <del> $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); <del> <del> $Schema = new Schema(); <del> $read = $Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaPrefixAuthUser') <del> )); <del> unset($read['tables']['missing']); <del> $this->assertTrue(isset($read['tables']['auth_users']), 'auth_users key missing %s'); <del> } <del> <del>/** <del> * test reading schema with config prefix. <del> * <del> * @return void <del> */ <del> public function testSchemaReadWithConfigPrefix() { <del> $this->skipIf($this->db instanceof Sqlite, 'Cannot open 2 connections to Sqlite'); <del> <del> $db = ConnectionManager::getDataSource('test'); <del> $config = $db->config; <del> $this->skipIf(!empty($config['prefix']), 'This test can not be executed with datasource prefix set.'); <del> <del> $config['prefix'] = 'schema_test_prefix_'; <del> ConnectionManager::create('schema_prefix', $config); <del> $read = $this->Schema->read(array('connection' => 'schema_prefix', 'models' => false)); <del> $this->assertTrue(empty($read['tables'])); <del> <del> $config['prefix'] = 'prefix_'; <del> ConnectionManager::create('schema_prefix2', $config); <del> $read = $this->Schema->read(array( <del> 'connection' => 'schema_prefix2', <del> 'name' => 'TestApp', <del> 'models' => false)); <del> $this->assertTrue(isset($read['tables']['prefix_tests'])); <del> } <del> <del>/** <del> * test reading schema from plugins. <del> * <del> * @return void <del> */ <del> public function testSchemaReadWithPlugins() { <del> App::objects('model', null, false); <del> App::build(array( <del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/') <del> )); <del> Plugin::load('TestPlugin'); <del> <del> $Schema = new Schema(); <del> $Schema->plugin = 'TestPlugin'; <del> $read = $Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => true <del> )); <del> unset($read['tables']['missing']); <del> $this->assertTrue(isset($read['tables']['auth_users'])); <del> $this->assertTrue(isset($read['tables']['authors'])); <del> $this->assertTrue(isset($read['tables']['test_plugin_comments'])); <del> $this->assertTrue(isset($read['tables']['posts'])); <del> $this->assertTrue(count($read['tables']) >= 4); <del> <del> App::build(); <del> } <del> <del>/** <del> * test reading schema with tables from another database. <del> * <del> * @return void <del> */ <del> public function testSchemaReadWithCrossDatabase() { <del> $config = ConnectionManager::enumConnectionObjects(); <del> $this->skipIf( <del> !isset($config['test']) || !isset($config['test2']), <del> 'Primary and secondary test databases not configured, ' . <del> 'skipping cross-database join tests. ' . <del> 'To run these tests, you must define $test and $test2 in your database configuration.' <del> ); <del> <del> $db = ConnectionManager::getDataSource('test2'); <del> $fixture = new SchemaCrossDatabaseFixture(); <del> $fixture->create($db); <del> $fixture->insert($db); <del> <del> $read = $this->Schema->read(array( <del> 'connection' => 'test', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaCrossDatabase', 'SchemaPost') <del> )); <del> $this->assertTrue(isset($read['tables']['posts'])); <del> $this->assertFalse(isset($read['tables']['cross_database']), 'Cross database should not appear'); <del> $this->assertFalse(isset($read['tables']['missing']['cross_database']), 'Cross database should not appear'); <del> <del> $read = $this->Schema->read(array( <del> 'connection' => 'test2', <del> 'name' => 'TestApp', <del> 'models' => array('SchemaCrossDatabase', 'SchemaPost') <del> )); <del> $this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear'); <del> $this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear'); <del> $this->assertTrue(isset($read['tables']['cross_database'])); <del> <del> $fixture->drop($db); <del> } <del> <del>/** <del> * test that tables are generated correctly <del> * <del> * @return void <del> */ <del> public function testGenerateTable() { <del> $posts = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false), <del> 'body' => array('type' => 'text', 'null' => true, 'default' => null), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)), <del> ); <del> $result = $this->Schema->generateTable('posts', $posts); <del> $this->assertRegExp('/public \$posts/', $result); <del> <del> $posts = array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false), <del> 'body' => array('type' => 'text', 'null' => true, 'default' => null), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1), <del> 'created' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'updated' => array('type' => 'datetime', 'null' => true, 'default' => null), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true), <del> 'MyFtIndex' => array('column' => array('title', 'body'), 'type' => 'fulltext') <del> ) <del> ); <del> $result = $this->Schema->generateTable('fields', $posts); <del> $this->assertRegExp('/public \$fields/', $result); <del> $this->assertPattern('/\'type\' \=\> \'fulltext\'/', $result); <del> } <del> <del>/** <del> * testSchemaWrite method <del> * <del> * @return void <del> */ <del> public function testSchemaWrite() { <del> $write = $this->Schema->write(array( <del> 'name' => 'MyOtherApp', <del> 'tables' => $this->Schema->tables, <del> 'path' => TMP . 'tests' <del> )); <del> $file = file_get_contents(TMP . 'tests/schema.php'); <del> $this->assertEquals($write, $file); <del> <del> require_once TMP . 'tests/schema.php'; <del> $OtherSchema = new MyOtherAppSchema(); <del> $this->assertEquals($this->Schema->tables, $OtherSchema->tables); <del> } <del> <del>/** <del> * testSchemaComparison method <del> * <del> * @return void <del> */ <del> public function testSchemaComparison() { <del> $New = new MyAppSchema(); <del> $compare = $New->compare($this->Schema); <del> $expected = array( <del> 'comments' => array( <del> 'add' => array( <del> 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'after' => 'id'), <del> 'title' => array('type' => 'string', 'null' => false, 'length' => 100, 'after' => 'user_id'), <del> ), <del> 'drop' => array( <del> 'article_id' => array('type' => 'integer', 'null' => false), <del> 'tableParameters' => array(), <del> ), <del> 'change' => array( <del> 'comment' => array('type' => 'text', 'null' => false, 'default' => null), <del> ) <del> ), <del> 'posts' => array( <del> 'add' => array( <del> 'summary' => array('type' => 'text', 'null' => true, 'after' => 'body'), <del> ), <del> 'drop' => array( <del> 'tableParameters' => array(), <del> ), <del> 'change' => array( <del> 'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''), <del> 'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'), <del> 'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1) <del> ) <del> ), <del> ); <del> $this->assertEquals($expected, $compare); <del> $this->assertNull($New->getVar('comments')); <del> $this->assertEquals(array('bar'), $New->getVar('_foo')); <del> <del> $tables = array( <del> 'missing' => array( <del> 'categories' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), <del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'name' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), <del> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') <del> ) <del> ), <del> 'ratings' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), <del> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null), <del> 'model' => array('type' => 'varchar', 'null' => false, 'default' => null), <del> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null), <del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), <del> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') <del> ) <del> ); <del> $compare = $New->compare($this->Schema, $tables); <del> $expected = array( <del> 'ratings' => array( <del> 'create' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), <del> 'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => null), <del> 'model' => array('type' => 'varchar', 'null' => false, 'default' => null), <del> 'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => null), <del> 'created' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'modified' => array('type' => 'datetime', 'null' => false, 'default' => null), <del> 'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)), <del> 'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM') <del> ) <del> ) <del> ); <del> $this->assertEquals($expected, $compare); <del> } <del> <del>/** <del> * test comparing '' and null and making sure they are different. <del> * <del> * @return void <del> */ <del> public function testCompareEmptyStringAndNull() { <del> $One = new Schema(array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), <del> 'name' => array('type' => 'string', 'null' => false, 'default' => '') <del> ) <del> )); <del> $Two = new Schema(array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'), <del> 'name' => array('type' => 'string', 'null' => false, 'default' => null) <del> ) <del> )); <del> $compare = $One->compare($Two); <del> $expected = array( <del> 'posts' => array( <del> 'change' => array( <del> 'name' => array('type' => 'string', 'null' => false, 'default' => null) <del> ) <del> ) <del> ); <del> $this->assertEquals($expected, $compare); <del> } <del> <del>/** <del> * Test comparing tableParameters and indexes. <del> * <del> * @return void <del> */ <del> public function testTableParametersAndIndexComparison() { <del> $old = array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true) <del> ), <del> 'tableParameters' => array( <del> 'charset' => 'latin1', <del> 'collate' => 'latin1_general_ci' <del> ) <del> ), <del> 'comments' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), <del> 'comment' => array('type' => 'text'), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true), <del> 'post_id' => array('column' => 'post_id'), <del> ), <del> 'tableParameters' => array( <del> 'engine' => 'InnoDB', <del> 'charset' => 'latin1', <del> 'collate' => 'latin1_general_ci' <del> ) <del> ) <del> ); <del> $new = array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => false), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true), <del> 'author_id' => array('column' => 'author_id'), <del> ), <del> 'tableParameters' => array( <del> 'charset' => 'utf8', <del> 'collate' => 'utf8_general_ci', <del> 'engine' => 'MyISAM' <del> ) <del> ), <del> 'comments' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0), <del> 'comment' => array('type' => 'text'), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true), <del> ), <del> 'tableParameters' => array( <del> 'charset' => 'utf8', <del> 'collate' => 'utf8_general_ci' <del> ) <del> ) <del> ); <del> $compare = $this->Schema->compare($old, $new); <del> $expected = array( <del> 'posts' => array( <del> 'add' => array( <del> 'indexes' => array('author_id' => array('column' => 'author_id')), <del> ), <del> 'change' => array( <del> 'tableParameters' => array( <del> 'charset' => 'utf8', <del> 'collate' => 'utf8_general_ci', <del> 'engine' => 'MyISAM' <del> ) <del> ) <del> ), <del> 'comments' => array( <del> 'drop' => array( <del> 'indexes' => array('post_id' => array('column' => 'post_id')), <del> ), <del> 'change' => array( <del> 'tableParameters' => array( <del> 'charset' => 'utf8', <del> 'collate' => 'utf8_general_ci', <del> ) <del> ) <del> ) <del> ); <del> $this->assertEquals($expected, $compare); <del> } <del> <del>/** <del> * Test comparing with field changed from VARCHAR to DATETIME <del> * <del> * @return void <del> */ <del> public function testCompareVarcharToDatetime() { <del> $old = array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'string', 'null' => true, 'length' => 45), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true) <del> ), <del> 'tableParameters' => array( <del> 'charset' => 'latin1', <del> 'collate' => 'latin1_general_ci' <del> ) <del> ), <del> ); <del> $new = array( <del> 'posts' => array( <del> 'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'), <del> 'author_id' => array('type' => 'integer', 'null' => false), <del> 'title' => array('type' => 'datetime', 'null' => false), <del> 'indexes' => array( <del> 'PRIMARY' => array('column' => 'id', 'unique' => true) <del> ), <del> 'tableParameters' => array( <del> 'charset' => 'latin1', <del> 'collate' => 'latin1_general_ci' <del> ) <del> ), <del> ); <del> $compare = $this->Schema->compare($old, $new); <del> $expected = array( <del> 'posts' => array( <del> 'change' => array( <del> 'title' => array( <del> 'type' => 'datetime', <del> 'null' => false, <del> ) <del> ) <del> ), <del> ); <del> $this->assertEquals($expected, $compare, 'Invalid SQL, datetime does not have length'); <del> } <del> <del>/** <del> * testSchemaLoading method <del> * <del> * @return void <del> */ <del> public function testSchemaLoading() { <del> $Other = $this->Schema->load(array('name' => 'MyOtherApp', 'path' => TMP . 'tests')); <del> $this->assertEquals('MyOtherApp', $Other->name); <del> $this->assertEquals($Other->tables, $this->Schema->tables); <del> } <del> <del>/** <del> * test loading schema files inside of plugins. <del> * <del> * @return void <del> */ <del> public function testSchemaLoadingFromPlugin() { <del> App::build(array( <del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/') <del> )); <del> Plugin::load('TestPlugin'); <del> $Other = $this->Schema->load(array('name' => 'TestPluginApp', 'plugin' => 'TestPlugin')); <del> $this->assertEquals('TestPluginApp', $Other->name); <del> $this->assertEquals(array('test_plugin_acos'), array_keys($Other->tables)); <del> <del> App::build(); <del> } <del> <del>/** <del> * testSchemaCreateTable method <del> * <del> * @return void <del> */ <del> public function testSchemaCreateTable() { <del> $db = ConnectionManager::getDataSource('test'); <del> $db->cacheSources = false; <del> <del> $Schema = new Schema(array( <del> 'connection' => 'test', <del> 'testdescribes' => array( <del> 'id' => array('type' => 'integer', 'key' => 'primary'), <del> 'int_null' => array('type' => 'integer', 'null' => true), <del> 'int_not_null' => array('type' => 'integer', 'null' => false), <del> ), <del> )); <del> $sql = $db->createSchema($Schema); <del> <del> $col = $Schema->tables['testdescribes']['int_null']; <del> $col['name'] = 'int_null'; <del> $column = $this->db->buildColumn($col); <del> $this->assertRegExp('/' . preg_quote($column, '/') . '/', $sql); <del> <del> $col = $Schema->tables['testdescribes']['int_not_null']; <del> $col['name'] = 'int_not_null'; <del> $column = $this->db->buildColumn($col); <del> $this->assertRegExp('/' . preg_quote($column, '/') . '/', $sql); <del> } <del>}
2
Ruby
Ruby
allow access default_formula directly
c6e1090c43f769e80c1aa98c2029f1eb466e0da4
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def satisfied_requirements? formula, spec, dependency=nil <ide> satisfied ||= requirement.satisfied? <ide> satisfied ||= requirement.optional? <ide> if !satisfied && requirement.default_formula? <del> default = Formula[requirement.class.default_formula] <add> default = Formula[requirement.default_formula] <ide> satisfied = satisfied_requirements?(default, :stable, formula.full_name) <ide> end <ide> satisfied <ide><path>Library/Homebrew/cmd/uses.rb <ide> def uses <ide> Requirement.prune if ignores.any? { |ignore| req.send(ignore) } && !dependent.build.with?(req) <ide> end <ide> deps.any? { |dep| dep.to_formula.full_name == ff.full_name } || <del> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.class.default_formula) } <add> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } <ide> else <ide> deps = f.deps.reject do |dep| <ide> ignores.any? { |ignore| dep.send(ignore) } <ide> def uses <ide> ignores.any? { |ignore| req.send(ignore) } <ide> end <ide> deps.any? { |dep| dep.to_formula.full_name == ff.full_name } || <del> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.class.default_formula) } <add> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } <ide> end <ide> rescue FormulaUnavailableError <ide> # Silently ignore this case as we don't care about things used in <ide><path>Library/Homebrew/requirement.rb <ide> class Requirement <ide> include Dependable <ide> <del> attr_reader :tags, :name, :cask, :download <add> attr_reader :tags, :name, :cask, :download, :default_formula <ide> alias_method :option_name, :name <ide> <ide> def initialize(tags=[]) <add> @default_formula = self.class.default_formula <ide> @cask ||= self.class.cask <ide> @download ||= self.class.download <ide> tags.each do |tag|
3
Ruby
Ruby
install readme.txt etc. as readme
0ea078e1ae8663b6b3dda18ca4016059acbaf61b
<ide><path>Library/Homebrew/brew.h.rb <ide> def install f <ide> f.prefix.mkpath <ide> f.install <ide> %w[README ChangeLog COPYING LICENSE COPYRIGHT AUTHORS].each do |file| <del> f.prefix.install file if File.file? file <add> FileUtils.mv "#{file}.txt", file rescue nil <add> f.prefix.install file rescue nil <ide> end <ide> end <ide> end
1
Ruby
Ruby
add buildtoolserror and buildflagserror
91e598cf3f88591f2146218eaa2ecc2a3a261e31
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install <ide> end <ide> end <ide> <add> # if the user's flags will prevent bottle only-installations when no <add> # developer tools are available, we need to stop them early on <add> if !MacOS.can_build? <add> bf = ARGV.collect_build_flags <add> <add> raise BuildFlagsError.new(bf) if !bf.empty? <add> end <add> <ide> ARGV.formulae.each do |f| <ide> # head-only without --HEAD is an error <ide> if !ARGV.build_head? && f.stable.nil? && f.devel.nil? <ide> def check_xcode <ide> # when one is no longer required <ide> checks = Checks.new <ide> %w[ <add> check_for_unsupported_osx <add> check_for_bad_install_name_tool <add> check_for_installed_developer_tools <ide> check_xcode_license_approved <ide> check_for_osx_gcc_installer <ide> ].each do |check| <ide> def check_cellar <ide> def perform_preinstall_checks <ide> check_ppc <ide> check_writable_install_location <del> if MacOS::Xcode.installed? <del> check_xcode <del> else <del> opoo "You have not installed Xcode." <del> puts "Bottles may install correctly, but builds will fail!" <del> end <add> check_xcode if MacOS::Xcode.installed? <ide> check_cellar <ide> end <ide> <ide><path>Library/Homebrew/cmd/reinstall.rb <ide> <ide> module Homebrew <ide> def reinstall <add> if !MacOS.can_build? <add> bf = ARGV.collect_build_flags <add> <add> if !bf.empty? <add> raise BuildFlagsError.new(bf) <add> end <add> end <add> <ide> ARGV.resolved_formulae.each { |f| reinstall_formula(f) } <ide> end <ide> <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> <ide> module Homebrew <ide> def upgrade <add> if !MacOS.can_build? <add> bf = ARGV.collect_build_flags <add> <add> if !bf.empty? <add> raise BuildFlagsError.new(bf) <add> end <add> end <add> <ide> Homebrew.perform_preinstall_checks <ide> <ide> if ARGV.named.empty? <ide><path>Library/Homebrew/exceptions.rb <ide> def dump <ide> end <ide> end <ide> <add># raised by FormulaInstaller.check_dependencies_bottled and <add># FormulaInstaller.install if the formula or its dependencies are not bottled <add># and are being installed on a system without necessary build tools <add>class BuildToolsError < RuntimeError <add> def initialize(formulae) <add> if formulae.length > 1 <add> formula_text = "formulae" <add> package_text = "binary packages" <add> else <add> formula_text = "formula" <add> package_text = "a binary package" <add> end <add> <add> if MacOS.version >= "10.10" <add> xcode_text = <<-EOS.undent <add> To continue, you must install Xcode from the App Store, <add> or the CLT by running: <add> xcode-select --install <add> EOS <add> elsif MacOS.version == "10.9" <add> xcode_text = <<-EOS.undent <add> To continue, you must install Xcode from: <add> https://developer.apple.com/downloads/ <add> or the CLT by running: <add> xcode-select --install <add> EOS <add> elsif MacOS.version >= "10.7" <add> xcode_text = <<-EOS.undent <add> To continue, you must install Xcode or the CLT from: <add> https://developer.apple.com/downloads/ <add> EOS <add> else <add> xcode_text = <<-EOS.undent <add> To continue, you must install Xcode from: <add> https://developer.apple.com/downloads/ <add> EOS <add> end <add> <add> super <<-EOS.undent <add> The following #{formula_text}: <add> #{formulae.join(', ')} <add> cannot be installed as a #{package_text} and must be built from source. <add> #{xcode_text} <add> EOS <add> end <add>end <add> <add># raised by Homebrew.install, Homebrew.reinstall, and Homebrew.upgrade <add># if the user passes any flags/environment that would case a bottle-only <add># installation on a system without build tools to fail <add>class BuildFlagsError < RuntimeError <add> def initialize(flags) <add> if flags.length > 1 <add> flag_text = "flags" <add> require_text = "require" <add> else <add> flag_text = "flag" <add> require_text = "requires" <add> end <add> <add> if MacOS.version >= "10.10" <add> xcode_text = <<-EOS.undent <add> or install Xcode from the App Store, or the CLT by running: <add> xcode-select --install <add> EOS <add> elsif MacOS.version == "10.9" <add> xcode_text = <<-EOS.undent <add> or install Xcode from: <add> https://developer.apple.com/downloads/ <add> or the CLT by running: <add> xcode-select --install <add> EOS <add> elsif MacOS.version >= "10.7" <add> xcode_text = <<-EOS.undent <add> or install Xcode or the CLT from: <add> https://developer.apple.com/downloads/ <add> EOS <add> else <add> xcode_text = <<-EOS.undent <add> or install Xcode from: <add> https://developer.apple.com/downloads/ <add> EOS <add> end <add> <add> super <<-EOS.undent <add> The following #{flag_text}: <add> #{flags.join(', ')} <add> #{require_text} building tools, but none are installed. <add> Either remove the #{flag_text} to attempt bottle installation, <add> #{xcode_text} <add> EOS <add> end <add>end <add> <ide> # raised by CompilerSelector if the formula fails with all of <ide> # the compilers available on the user's system <ide> class CompilerSelectionError < RuntimeError <ide><path>Library/Homebrew/extend/ARGV.rb <ide> def env <ide> value "env" <ide> end <ide> <add> # collect any supplied build flags into an array for reporting <add> def collect_build_flags <add> build_flags = [] <add> <add> build_flags << '--HEAD' if build_head? <add> build_flags << '--universal' if build_universal? <add> build_flags << '--32-bit' if build_32_bit? <add> build_flags << '--build-bottle' if build_bottle? <add> build_flags << '--build-from-source' if build_from_source? <add> <add> build_flags <add> end <add> <ide> private <ide> <ide> def spec(default = :stable) <ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> <ide> check_conflicts <ide> <add> if !pour_bottle? && !MacOS.can_build? <add> raise BuildToolsError.new([formula]) <add> end <add> <ide> if !ignore_deps? <ide> deps = compute_dependencies <ide> check_dependencies_bottled(deps) if pour_bottle? <ide><path>Library/Homebrew/os/mac.rb <ide> def otool <ide> end <ide> end <ide> <add> def can_build? <add> Xcode.installed? || CLT.installed? <add> end <add> <ide> def active_developer_dir <ide> @active_developer_dir ||= Utils.popen_read("/usr/bin/xcode-select", "-print-path").strip <ide> end
7
Python
Python
fix style issue in docstring
e41378a2e1962b35df3f8dee90aed848286809b5
<ide><path>keras/engine/topology.py <ide> def load_weights(self, filepath, by_name=False, <ide> where there is a mismatch in the number of weights, <ide> or a mismatch in the shape of the weight <ide> (only valid when `by_name`=True). <del> reshape: Reshape weights to fit the layer when the correct number <del> of values are present but the shape does not match. <add> reshape: Reshape weights to fit the layer when the correct number <add> of weight arrays is present but their shape does not match. <ide> <ide> <ide> # Raises
1
Javascript
Javascript
fix lazy local import of bootstrapping module
b876d72bed76178bffc993d13f95f5060dbe40db
<ide><path>packages/ember-template-compiler/lib/system/initializer.js <ide> import require, { has } from 'require'; <add>import bootstrap from './bootstrap'; <ide> <ide> // Globals mode template compiler <ide> if (has('ember-application') && has('ember-environment') && has('ember-glimmer')) { <ide> if (has('ember-application') && has('ember-environment') && has('ember-glimmer') <ide> let { hasTemplate, setTemplate } = emberGlimmer; <ide> let { environment } = emberEnv; <ide> <del> let bootstrap = function() {}; <del> <ide> Application.initializer({ <ide> name: 'domTemplates', <ide> initialize() { <del> let bootstrapModuleId = 'ember-template-compiler/system/bootstrap'; <ide> let context; <del> if (environment.hasDOM && has(bootstrapModuleId)) { <del> bootstrap = require(bootstrapModuleId).default; <add> if (environment.hasDOM) { <ide> context = document; <ide> } <ide>
1
Ruby
Ruby
push more mutations out of the builder
9da52a5e55cc665a539afb45783f84d9f3607282
<ide><path>activerecord/lib/active_record/associations/builder/association.rb <ide> def initialize(model, name, scope, options) <ide> end <ide> <ide> def build <del> configure_dependency if options[:dependent] <ide> ActiveRecord::Reflection.create(macro, name, scope, options, model) <ide> end <ide> <ide> def validate_options <ide> end <ide> <ide> def define_callbacks(model, reflection) <add> add_before_destroy_callbacks(model, name) if options[:dependent] <ide> Association.extensions.each do |extension| <ide> extension.build model, reflection <ide> end <ide> def #{name}=(value) <ide> CODE <ide> end <ide> <del> def configure_dependency <add> def valid_dependent_options <add> raise NotImplementedError <add> end <add> <add> private <add> <add> def add_before_destroy_callbacks(model, name) <ide> unless valid_dependent_options.include? options[:dependent] <ide> raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{options[:dependent]}" <ide> end <ide> <del> n = name <del> model.before_destroy lambda { |o| o.association(n).handle_dependency } <del> end <del> <del> def valid_dependent_options <del> raise NotImplementedError <add> model.before_destroy lambda { |o| o.association(name).handle_dependency } <ide> end <ide> end <ide> end <ide><path>activerecord/lib/active_record/associations/builder/has_one.rb <ide> def constructable? <ide> !options[:through] <ide> end <ide> <del> def configure_dependency <del> super unless options[:through] <del> end <del> <ide> def valid_dependent_options <ide> [:destroy, :delete, :nullify, :restrict_with_error, :restrict_with_exception] <ide> end <add> <add> private <add> <add> def add_before_destroy_callbacks(model, name) <add> super unless options[:through] <add> end <ide> end <ide> end
2
Text
Text
fix the typo in ps
c2b59b03df364901ce51ee485d60fce7e7aaa955
<ide><path>docs/reference/commandline/port.md <ide> parent = "smn_cli" <ide> You can find out all the ports mapped by not specifying a `PRIVATE_PORT`, or <ide> just a specific mapping: <ide> <del> $ docker ps test <add> $ docker ps <ide> CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES <ide> b650456536c7 busybox:latest top 54 minutes ago Up 54 minutes 0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp test <ide> $ docker port test
1
Javascript
Javascript
remove extraneous `onrespondergrant` argument
49015b0f5bda83794b88b17dd3cbd834fa235b72
<ide><path>Libraries/Text/Text.js <ide> class TouchableText extends React.Component<Props, State> { <ide> touchableHandleActivePressOut: ?() => void; <ide> touchableHandleLongPress: ?(event: PressEvent) => void; <ide> touchableHandlePress: ?(event: PressEvent) => void; <del> touchableHandleResponderGrant: ?( <del> event: PressEvent, <del> dispatchID: string, <del> ) => void; <add> touchableHandleResponderGrant: ?(event: PressEvent) => void; <ide> touchableHandleResponderMove: ?(event: PressEvent) => void; <ide> touchableHandleResponderRelease: ?(event: PressEvent) => void; <ide> touchableHandleResponderTerminate: ?(event: PressEvent) => void; <ide> class TouchableText extends React.Component<Props, State> { <ide> } <ide> return shouldSetResponder; <ide> }, <del> onResponderGrant: (event: PressEvent, dispatchID: string): void => { <del> nullthrows(this.touchableHandleResponderGrant)(event, dispatchID); <add> onResponderGrant: (event: PressEvent): void => { <add> nullthrows(this.touchableHandleResponderGrant)(event); <ide> if (this.props.onResponderGrant != null) { <del> this.props.onResponderGrant.call(this, event, dispatchID); <add> this.props.onResponderGrant.call(this, event); <ide> } <ide> }, <ide> onResponderMove: (event: PressEvent): void => { <ide><path>Libraries/Text/TextProps.js <ide> export type TextProps = $ReadOnly<{| <ide> * See https://reactnative.dev/docs/text.html#onpress <ide> */ <ide> onPress?: ?(event: PressEvent) => mixed, <del> onResponderGrant?: ?(event: PressEvent, dispatchID: string) => void, <add> onResponderGrant?: ?(event: PressEvent) => void, <ide> onResponderMove?: ?(event: PressEvent) => void, <ide> onResponderRelease?: ?(event: PressEvent) => void, <ide> onResponderTerminate?: ?(event: PressEvent) => void,
2
Python
Python
remove unused error object
f1ddac187de7e67923e8ee63192787179f70fa4c
<ide><path>spacy/language.py <ide> def add_pipe( <ide> factory_name, source, name=name <ide> ) <ide> else: <del> if not self.has_factory(factory_name): <del> err = Errors.E002.format( <del> name=factory_name, <del> opts=", ".join(self.factory_names), <del> method="add_pipe", <del> lang=util.get_object_name(self), <del> lang_code=self.lang, <del> ) <ide> pipe_component = self.create_pipe( <ide> factory_name, <ide> name=name,
1
PHP
PHP
add application setter
e6ee45c228b2ebce1b626c6b19fb7d804bdccf06
<ide><path>src/Console/CommandRunner.php <ide> class CommandRunner implements EventDispatcherInterface <ide> */ <ide> public function __construct(ConsoleApplicationInterface $app, $root = 'cake') <ide> { <del> $this->app = $app; <add> $this->setApp($app); <ide> $this->root = $root; <ide> $this->aliases = [ <ide> '--version' => 'version', <ide> '--help' => 'help', <ide> '-h' => 'help', <ide> ]; <del> <del> if ($app instanceof EventDispatcherInterface) { <del> $this->setEventManager($app->getEventManager()); <del> } <ide> } <ide> <ide> /** <ide> public function setAliases(array $aliases) <ide> return $this; <ide> } <ide> <add> /** <add> * Set the application. <add> * <add> * @param \Cake\Core\ConsoleApplicationInterface $app The application to run CLI commands for. <add> * @return $this <add> */ <add> public function setApp(ConsoleApplicationInterface $app) <add> { <add> $this->app = $app; <add> <add> if ($app instanceof EventDispatcherInterface) { <add> $this->setEventManager($app->getEventManager()); <add> } <add> <add> return $this; <add> } <add> <ide> /** <ide> * Run the command contained in $argv. <ide> *
1
Text
Text
update build instructions for windows
0a8f5a0f02f291a1707645c262dac9218c222248
<ide><path>BUILDING.md <ide> $ node -e "console.log('Hello from Node.js ' + process.version)" <ide> Prerequisites: <ide> <ide> * [Python 2.6 or 2.7](https://www.python.org/downloads/) <del>* Visual Studio 2013 / 2015, all editions including the Community edition, or <del>* Visual Studio Express 2013 / 2015 for Desktop <add>* One of: <add> * [Visual C++ Build Tools](http://landinghub.visualstudio.com/visual-cpp-build-tools) <add> * [Visual Studio](https://www.visualstudio.com/) 2013 / 2015, all editions including the Community edition <add> * [Visual Studio](https://www.visualstudio.com/) Express 2013 / 2015 for Desktop <ide> * Basic Unix tools required for some tests, <ide> [Git for Windows](http://git-scm.com/download/win) includes Git Bash <ide> and tools which can be included in the global `PATH`. <ide> To run the tests: <ide> <ide> To test if Node.js was built correctly: <ide> <del>``` <del>$ node -e "console.log('Hello from Node.js ' + process.version)" <add>```text <add>> Release\node -e "console.log('Hello from Node.js', process.version)" <ide> ``` <ide> <ide> ### Android / Android-based devices (e.g., Firefox OS)
1
Mixed
PHP
update events to use new methods
95fe3381e61d1f9dff42388cd9c09bda42f2fe40
<ide><path>src/Controller/Component/AuthComponent.php <ide> public function constructAuthenticate() <ide> } <ide> $config = array_merge($global, (array)$config); <ide> $this->_authenticateObjects[$alias] = new $className($this->_registry, $config); <del> $this->eventManager()->attach($this->_authenticateObjects[$alias]); <add> $this->eventManager()->on($this->_authenticateObjects[$alias]); <ide> } <ide> return $this->_authenticateObjects; <ide> } <ide><path>src/Controller/ComponentRegistry.php <ide> protected function _create($class, $alias, $config) <ide> $instance = new $class($this, $config); <ide> $enable = isset($config['enabled']) ? $config['enabled'] : true; <ide> if ($enable) { <del> $this->eventManager()->attach($instance); <add> $this->eventManager()->on($instance); <ide> } <ide> return $instance; <ide> } <ide><path>src/Controller/Controller.php <ide> public function __construct(Request $request = null, Response $response = null, <ide> <ide> $this->_mergeControllerVars(); <ide> $this->_loadComponents(); <del> $this->eventManager()->attach($this); <add> $this->eventManager()->on($this); <ide> } <ide> <ide> /** <ide><path>src/Controller/ErrorController.php <ide> public function __construct($request = null, $response = null) <ide> } <ide> $eventManager = $this->eventManager(); <ide> if (isset($this->Auth)) { <del> $eventManager->detach($this->Auth); <add> $eventManager->off($this->Auth); <ide> } <ide> if (isset($this->Security)) { <del> $eventManager->detach($this->Security); <add> $eventManager->off($this->Security); <ide> } <ide> $this->viewPath = 'Error'; <ide> } <ide><path>src/Core/ObjectRegistry.php <ide> public function unload($objectName) <ide> } <ide> $object = $this->_loaded[$objectName]; <ide> if (isset($this->_eventManager)) { <del> $this->eventManager()->detach($object); <add> $this->eventManager()->off($object); <ide> } <ide> unset($this->_loaded[$objectName]); <ide> } <ide><path>src/Event/EventManager.php <ide> protected function _detachSubscriber(EventListenerInterface $subscriber, $eventK <ide> if (is_numeric(key($function))) { <ide> foreach ($function as $handler) { <ide> $handler = isset($handler['callable']) ? $handler['callable'] : $handler; <del> $this->detach([$subscriber, $handler], $key); <add> $this->off($key, [$subscriber, $handler]); <ide> } <ide> continue; <ide> } <ide> $function = $function['callable']; <ide> } <del> $this->detach([$subscriber, $function], $key); <add> $this->off($key, [$subscriber, $function]); <ide> } <ide> } <ide> <ide><path>src/Event/README.md <ide> class Orders <ide> } <ide> <ide> $orders = new Orders(); <del>$orders->eventManager()->attach(function ($event) { <add>$orders->eventManager()->on(function ($event) { <ide> // Do something after the order was placed <ide> ... <ide> }, 'Orders.afterPlace'); <ide><path>src/ORM/BehaviorRegistry.php <ide> protected function _create($class, $alias, $config) <ide> $instance = new $class($this->_table, $config); <ide> $enable = isset($config['enabled']) ? $config['enabled'] : true; <ide> if ($enable) { <del> $this->eventManager()->attach($instance); <add> $this->eventManager()->on($instance); <ide> } <ide> $methods = $this->_getMethods($instance, $class, $alias); <ide> $this->_methodMap += $methods['methods']; <ide><path>src/ORM/Table.php <ide> public function __construct(array $config = []) <ide> $this->_associations = $associations ?: new AssociationCollection(); <ide> <ide> $this->initialize($config); <del> $this->_eventManager->attach($this); <add> $this->_eventManager->on($this); <ide> $this->dispatchEvent('Model.initialize'); <ide> } <ide> <ide><path>src/Routing/Dispatcher.php <ide> protected function _invoke(Controller $controller) <ide> public function addFilter(EventListenerInterface $filter) <ide> { <ide> $this->_filters[] = $filter; <del> $this->eventManager()->attach($filter); <add> $this->eventManager()->on($filter); <ide> } <ide> <ide> /** <ide><path>src/TestSuite/IntegrationTestCase.php <ide> protected function _sendRequest($url, $method, $data = []) <ide> $request = $this->_buildRequest($url, $method, $data); <ide> $response = new Response(); <ide> $dispatcher = DispatcherFactory::create(); <del> $dispatcher->eventManager()->attach( <del> [$this, 'controllerSpy'], <add> $dispatcher->eventManager()->on( <ide> 'Dispatcher.beforeDispatch', <del> ['priority' => 999] <add> ['priority' => 999], <add> [$this, 'controllerSpy'] <ide> ); <ide> try { <ide> $dispatcher->dispatch($request, $response); <ide> public function controllerSpy($event) <ide> } <ide> $this->_controller = $event->data['controller']; <ide> $events = $this->_controller->eventManager(); <del> $events->attach(function ($event, $viewFile) { <add> $events->on('View.beforeRender', function ($event, $viewFile) { <ide> $this->_viewName = $viewFile; <del> }, 'View.beforeRender'); <del> $events->attach(function ($event, $viewFile) { <add> }); <add> $events->on('View.beforeLayout', function ($event, $viewFile) { <ide> $this->_layoutName = $viewFile; <del> }, 'View.beforeLayout'); <add> }); <ide> } <ide> <ide> /** <ide><path>src/View/HelperRegistry.php <ide> protected function _create($class, $alias, $settings) <ide> } <ide> $enable = isset($settings['enabled']) ? $settings['enabled'] : true; <ide> if ($enable) { <del> $this->eventManager()->attach($instance); <add> $this->eventManager()->on($instance); <ide> } <ide> return $instance; <ide> } <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> public function testInnerComponentsAreNotEnabled() <ide> $controller->eventManager($mock); <ide> <ide> $mock->expects($this->once()) <del> ->method('attach') <add> ->method('on') <ide> ->with($this->isInstanceOf('TestApp\Controller\Component\AppleComponent')); <ide> <ide> $Collection = new ComponentRegistry($controller);
13
Javascript
Javascript
remove duplicate _metamorphview
b7e6adb90c134593d33268b7c3a1bd15e7d627b4
<ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> import { <ide> removeBeforeObserver <ide> } from "ember-metal/observer"; <ide> <del>import { <del> _Metamorph, <del> _MetamorphView <del>} from "ember-handlebars/views/metamorph_view"; <add>import _MetamorphView from "ember-handlebars/views/metamorph_view"; <add>import { _Metamorph } from "ember-handlebars/views/metamorph_view"; <ide> <ide> var EachView = CollectionView.extend(_Metamorph, { <ide> <ide><path>packages/ember-handlebars/lib/main.js <ide> import { <ide> _HandlebarsBoundView, <ide> SimpleHandlebarsView <ide> } from "ember-handlebars/views/handlebars_bound_view"; <add>import _MetamorphView from "ember-handlebars/views/metamorph_view"; <ide> import { <ide> _SimpleMetamorphView, <del> _MetamorphView, <ide> _Metamorph <ide> } from "ember-handlebars/views/metamorph_view"; <ide> <ide><path>packages/ember-handlebars/lib/views/metamorph_view.js <ide> export var _Metamorph = Mixin.create({ <ide> @uses Ember._Metamorph <ide> @private <ide> */ <del>export var _MetamorphView = View.extend(_Metamorph); <add>export default View.extend(_Metamorph); <ide> <ide> /** <ide> @class _SimpleMetamorphView <ide> export var _MetamorphView = View.extend(_Metamorph); <ide> @private <ide> */ <ide> export var _SimpleMetamorphView = CoreView.extend(_Metamorph); <del>export default View.extend(_Metamorph); <ide><path>packages/ember-routing-handlebars/tests/helpers/outlet_test.js <ide> import EmberRouter from "ember-routing/system/router"; <ide> import HashLocation from "ember-routing/location/hash_location"; <ide> <ide> import EmberHandlebars from "ember-handlebars"; <del>import {_MetamorphView} from "ember-handlebars/views/metamorph_view"; <add>import _MetamorphView from "ember-handlebars/views/metamorph_view"; <ide> import EmberView from "ember-routing/ext/view"; <ide> import EmberContainerView from "ember-views/views/container_view"; <ide> import jQuery from "ember-views/system/jquery";
4
Text
Text
fix links 404/302/303 in docs/community
4863a24451e2df3f2f6b5ba24b8a161bfa95390f
<ide><path>docs/community/3.0-announcement.md <ide> The 3.2 release is planned to introduce an alternative admin-style interface to <ide> You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones). <ide> <ide> [kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3 <del>[sponsors]: https://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors <add>[sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors <ide> [mixins.py]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py <ide> [django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files <ide><path>docs/community/3.1-announcement.md <ide> Note that as a result of this work a number of settings keys and generic view at <ide> <ide> Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. <ide> <del>The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](http://cramer.io/2011/03/08/building-cursors-for-the-disqus-api) on the subject. <add>The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api) on the subject. <ide> <ide> #### Pagination controls in the browsable API. <ide> <ide> Note that the structure of the error responses is still the same. We still have <ide> <ide> We include built-in translations both for standard exception cases, and for serializer validation errors. <ide> <del>The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/projects/p/django-rest-framework/). <add>The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/django-rest-framework-1/django-rest-framework/). <ide> <ide> If you only wish to support a subset of the supported languages, use Django's standard `LANGUAGES` setting: <ide> <ide> We've now moved a number of packages out of the core of REST framework, and into <ide> <ide> We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework. <ide> <del>The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/evonove/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support. <add>The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/jazzband/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support. <ide> <ide> The following packages are now moved out of core and should be separately installed: <ide> <ide> * OAuth - [djangorestframework-oauth](https://jpadilla.github.io/django-rest-framework-oauth/) <del>* XML - [djangorestframework-xml](https://jpadilla.github.io/django-rest-framework-xml) <del>* YAML - [djangorestframework-yaml](https://jpadilla.github.io/django-rest-framework-yaml) <del>* JSONP - [djangorestframework-jsonp](https://jpadilla.github.io/django-rest-framework-jsonp) <add>* XML - [djangorestframework-xml](https://jpadilla.github.io/django-rest-framework-xml/) <add>* YAML - [djangorestframework-yaml](https://jpadilla.github.io/django-rest-framework-yaml/) <add>* JSONP - [djangorestframework-jsonp](https://jpadilla.github.io/django-rest-framework-jsonp/) <ide> <ide> It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do: <ide> <ide><path>docs/community/3.2-announcement.md <ide> We've also fixed a huge number of issues, and made numerous cleanups and improve <ide> <ide> Over the course of the 3.1.x series we've [resolved nearly 600 tickets](https://github.com/encode/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05) on our GitHub issue tracker. This means we're currently running at a rate of **closing around 100 issues or pull requests per month**. <ide> <del>None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](https://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors) and finding out who's hiring. <add>None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors) and finding out who's hiring. <ide> <ide> ## AdminRenderer <ide> <ide><path>docs/community/3.4-announcement.md <ide> Right now we're over 60% of the way towards achieving that. <ide> *Every single sign-up makes a significant impact.* <ide> <ide> <ul class="premium-promo promo"> <del> <li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <del> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <add> <li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <add> <li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <ide> <li><a href="https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li> <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*Many thanks to all our [awesome sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).* <add>*Many thanks to all our [awesome sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).* <ide> <ide> --- <ide> <ide><path>docs/community/3.5-announcement.md <ide> we strongly encourage you to invest in its continued development by <ide> **[signing up for a paid&nbsp;plan][funding]**. <ide> <ide> <ul class="premium-promo promo"> <del> <li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <del> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <add> <li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <add> <li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <ide> <li><a href="https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li> <ide> <li><a href="https://www.machinalis.com/#services" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li> <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](https://www.machinalis.com/#services).* <add>*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](https://www.machinalis.com/#services).* <ide> <ide> --- <ide> <ide><path>docs/community/3.6-announcement.md <ide> we strongly encourage you to invest in its continued development by <ide> **[signing up for a paid&nbsp;plan][funding]**. <ide> <ide> <ul class="premium-promo promo"> <del> <li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <del> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <add> <li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <add> <li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <ide> <li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li> <del> <li><a href="https://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li> <add> <li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li> <ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li> <ide> <li><a href="https://micropyramid.com/django-rest-framework-development-services/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/mp-text-logo.png)">MicroPyramid</a></li> <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).* <add>*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).* <ide> <ide> --- <ide> <ide><path>docs/community/3.7-announcement.md <ide> If you use REST framework commercially and would like to see this work continue, <ide> **[signing up for a paid&nbsp;plan][funding]**. <ide> <ide> <ul class="premium-promo promo"> <del> <li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <del> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <add> <li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <add> <li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <ide> <li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li> <del> <li><a href="https://hello.machinalis.co.uk/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li> <add> <li><a href="https://machinalis.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/Machinalis130.png)">Machinalis</a></li> <ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar.png)">Rollbar</a></li> <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*As well as our release sponsor, we'd like to say thanks in particular our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), and [Rollbar](https://rollbar.com).* <add>*As well as our release sponsor, we'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).* <ide> <ide> --- <ide> <ide><path>docs/community/3.8-announcement.md <ide> If you use REST framework commercially and would like to see this work continue, <ide> **[signing up for a paid&nbsp;plan][funding]**. <ide> <ide> <del>*We'd like to say thanks in particular our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://hello.machinalis.co.uk/), and [Rollbar](https://rollbar.com).* <add>*We'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).* <ide> <ide> --- <ide> <ide><path>docs/community/3.9-announcement.md <ide> If you use REST framework commercially and would like to see this work continue, <ide> <ide> <ide> <ul class="premium-promo promo"> <del> <li><a href="http://jobs.rover.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <del> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <add> <li><a href="https://www.rover.com/careers/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rover_130x130.png)">Rover.com</a></li> <add> <li><a href="https://sentry.io/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li> <ide> <li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li> <ide> <li><a href="https://auklet.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/auklet-new.png)">Auklet</a></li> <ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li> <ide> If you use REST framework commercially and would like to see this work continue, <ide> </ul> <ide> <div style="clear: both; padding-bottom: 20px;"></div> <ide> <del>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](http://jobs.rover.com/), [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Auklet](https://auklet.io/), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).* <add>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Auklet](https://auklet.io/), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).* <ide> <ide> --- <ide> <ide><path>docs/community/funding.md <ide> REST framework continues to be open-source and permissively licensed, but we fir <ide> <ide> ## What funding has enabled so far <ide> <del>* The [3.4](https://www.django-rest-framework.org/topics/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/topics/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. <del>* The [3.6](https://www.django-rest-framework.org/topics/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples. <del>* The [3.7 release](https://www.django-rest-framework.org/topics/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. <del>* The recent [3.8 release](https://www.django-rest-framework.org/topics/3.8-announcement/). <add>* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. <add>* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples. <add>* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. <add>* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/). <ide> * Tom Christie, the creator of Django REST framework, working on the project full-time. <ide> * Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time. <ide> * A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship. <ide> For further enquires please contact <a href=mailto:funding@django-rest-framework <ide> <ide> ## Accountability <ide> <del>In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018) and regularly include financial reports and cost breakdowns. <add>In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns. <ide> <ide> <!-- Begin MailChimp Signup Form --> <ide> <link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css"> <ide><path>docs/community/jobs.md <ide> Looking for a new Django REST Framework related role? On this site we provide a <ide> * [https://www.python.org/jobs/][python-org-jobs] <ide> * [https://djangogigs.com][django-gigs-com] <ide> * [https://djangojobs.net/jobs/][django-jobs-net] <del>* [http://djangojobbers.com][django-jobbers-com] <ide> * [https://www.indeed.com/q-Django-jobs.html][indeed-com] <ide> * [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com] <ide> * [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com] <ide> * [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk] <ide> * [https://remoteok.io/remote-django-jobs][remoteok-io] <ide> * [https://www.remotepython.com/jobs/][remotepython-com] <del>* [https://weworkcontract.com/python-contract-jobs][weworkcontract-com] <ide> <ide> <ide> Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email]. <ide> Wonder how else you can help? One of the best ways you can help Django REST Fram <ide> [python-org-jobs]: https://www.python.org/jobs/ <ide> [django-gigs-com]: https://djangogigs.com <ide> [django-jobs-net]: https://djangojobs.net/jobs/ <del>[django-jobbers-com]: http://djangojobbers.com <ide> [indeed-com]: https://www.indeed.com/q-Django-jobs.html <ide> [stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django <ide> [upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/ <ide> [technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs <ide> [remoteok-io]: https://remoteok.io/remote-django-jobs <ide> [remotepython-com]: https://www.remotepython.com/jobs/ <del>[weworkcontract-com]: https://weworkcontract.com/python-contract-jobs <ide> [drf-funding]: https://fund.django-rest-framework.org/topics/funding/ <ide> [submit-pr]: https://github.com/encode/django-rest-framework <ide> [anna-email]: mailto:anna@django-rest-framework.org <ide><path>docs/community/kickstarter-announcement.md <ide> Our platinum sponsors have each made a hugely substantial contribution to the fu <ide> </ul> <ide> <ide> <ul class="sponsor platinum"> <del><li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li> <del><li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li> <add><li><a href="https://www.divio.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-divio.png);">Divio</a></li> <add><li><a href="https://onlulu.com" rel="nofollow" style="background-image:url(../../img/sponsors/1-lulu.png);">Lulu</a></li> <ide> <li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../../img/sponsors/1-potato.png);">Potato</a></li> <ide> <li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-wiredrive.png);">Wiredrive</a></li> <ide> <li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../../img/sponsors/1-cyan.png);">Cyan</a></li> <ide> Our gold sponsors include companies large and small. Many thanks for their signi <ide> <li><a href="https://www.lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li> <ide> <li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-opbeat.png);">Opbeat</a></li> <ide> <li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-koordinates.png);">Koordinates</a></li> <del><li><a href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li> <del><li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li> <add><li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li> <add><li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li> <ide> <li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-heroku.png);">Heroku</a></li> <ide> <li><a href="https://www.rheinwerk-verlag.de/" rel="nofollow" style="background-image:url(../../img/sponsors/2-rheinwerk_verlag.png);">Rheinwerk Verlag</a></li> <ide> <li><a href="https://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-security_compass.png);">Security Compass</a></li> <ide> <li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../../img/sponsors/2-django.png);">Django Software Foundation</a></li> <ide> <li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../../img/sponsors/2-hipflask.png);">Hipflask</a></li> <ide> <li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../../img/sponsors/2-crate.png);">Crate</a></li> <ide> <li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-cryptico.png);">Cryptico Corp</a></li> <del><li><a href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</a></li> <add><li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-nexthub.png);">NextHub</a></li> <ide> <li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../../img/sponsors/2-compile.png);">Compile</a></li> <del><li><a href="http://wusawork.org" rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</a></li> <add><li><a rel="nofollow" style="background-image:url(../../img/sponsors/2-wusawork.png);">WusaWork</a></li> <ide> <li><a href="http://envisionlinux.org/blog" rel="nofollow">Envision Linux</a></li> <ide> </ul> <ide>
12
Mixed
Javascript
make textencoder/textdecoder global
932be0164fb3ed869ae3ddfff391721d2fd8e1af
<ide><path>.eslintrc.js <ide> module.exports = { <ide> DTRACE_HTTP_SERVER_REQUEST: false, <ide> DTRACE_HTTP_SERVER_RESPONSE: false, <ide> DTRACE_NET_SERVER_CONNECTION: false, <del> DTRACE_NET_STREAM_END: false <add> DTRACE_NET_STREAM_END: false, <add> TextEncoder: false, <add> TextDecoder: false <ide> }, <ide> }; <ide><path>doc/api/errors.md <ide> The stack trace is extended to include the point in time at which the <ide> <a id="ERR_ENCODING_INVALID_ENCODED_DATA"></a> <ide> ### ERR_ENCODING_INVALID_ENCODED_DATA <ide> <del>Data provided to `util.TextDecoder()` API was invalid according to the encoding <add>Data provided to `TextDecoder()` API was invalid according to the encoding <ide> provided. <ide> <ide> <a id="ERR_ENCODING_NOT_SUPPORTED"></a> <ide> ### ERR_ENCODING_NOT_SUPPORTED <ide> <del>Encoding provided to `util.TextDecoder()` API was not one of the <add>Encoding provided to `TextDecoder()` API was not one of the <ide> [WHATWG Supported Encodings][]. <ide> <ide> <a id="ERR_FALSY_VALUE_REJECTION"></a> <ide><path>doc/api/globals.md <ide> added: v0.0.1 <ide> <ide> [`setTimeout`] is described in the [timers][] section. <ide> <add>## TextDecoder <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add><!-- type=global --> <add> <add>The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. <add> <add>## TextEncoder <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add><!-- type=global --> <add> <add>The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. <add> <add> <ide> ## URL <ide> <!-- YAML <ide> added: v10.0.0 <ide> The WHATWG `URLSearchParams` class. See the [`URLSearchParams`][] section. <ide> [`setImmediate`]: timers.html#timers_setimmediate_callback_args <ide> [`setInterval`]: timers.html#timers_setinterval_callback_delay_args <ide> [`setTimeout`]: timers.html#timers_settimeout_callback_delay_args <add>[`TextDecoder`]: util.html#util_class_util_textdecoder <add>[`TextEncoder`]: util.html#util_class_util_textencoder <ide> [`URL`]: url.html#url_class_url <ide> [`URLSearchParams`]: url.html#url_class_urlsearchparams <ide> [buffer section]: buffer.html <ide><path>doc/api/util.md <ide> The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] <ide> is not supported. <ide> <ide> ### new TextDecoder([encoding[, options]]) <add><!-- YAML <add>added: v8.3.0 <add>changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The class is now available on the global object. <add>--> <ide> <ide> * `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance <ide> supports. **Default:** `'utf-8'`. <ide> is not supported. <ide> Creates an new `TextDecoder` instance. The `encoding` may specify one of the <ide> supported encodings or an alias. <ide> <add>The `TextDecoder` class is also available on the global object. <add> <ide> ### textDecoder.decode([input[, options]]) <ide> <ide> * `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or <ide> mark. <ide> ## Class: util.TextEncoder <ide> <!-- YAML <ide> added: v8.3.0 <add>changes: <add> - version: REPLACEME <add> pr-url: REPLACEME <add> description: The class is now available on the global object. <ide> --> <ide> <ide> An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All <ide> const encoder = new TextEncoder(); <ide> const uint8array = encoder.encode('this is some data'); <ide> ``` <ide> <add>The `TextEncoder` class is also available on the global object. <add> <ide> ### textEncoder.encode([input]) <ide> <ide> * `input` {string} The text to encode. **Default:** an empty string. <ide><path>lib/internal/bootstrap/node.js <ide> setupGlobalTimeouts(); <ide> setupGlobalConsole(); <ide> setupGlobalURL(); <add> setupGlobalEncoding(); <ide> } <ide> <ide> if (process.binding('config').experimentalWorker) { <ide> }); <ide> } <ide> <add> function setupGlobalEncoding() { <add> const { TextEncoder, TextDecoder } = NativeModule.require('util'); <add> Object.defineProperties(global, { <add> TextEncoder: { <add> value: TextEncoder, <add> writable: true, <add> configurable: true, <add> enumerable: false <add> }, <add> TextDecoder: { <add> value: TextDecoder, <add> writable: true, <add> configurable: true, <add> enumerable: false <add> } <add> }); <add> } <add> <ide> function setupDOMException() { <ide> // Registers the constructor with C++. <ide> NativeModule.require('internal/domexception'); <ide><path>test/parallel/test-global-encoder.js <add>'use strict'; <add> <add>require('../common'); <add>const { strictEqual } = require('assert'); <add>const util = require('util'); <add> <add>strictEqual(TextDecoder, util.TextDecoder); <add>strictEqual(TextEncoder, util.TextEncoder); <ide><path>test/parallel/test-whatwg-encoding-fatal-streaming.js <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder <del>} = require('util'); <del> <ide> <ide> { <ide> [ <ide><path>test/parallel/test-whatwg-encoding-surrogates-utf8.js <ide> require('../common'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder, <del> TextEncoder <del>} = require('util'); <ide> <ide> const badStrings = [ <ide> { <ide><path>test/parallel/test-whatwg-encoding-textdecoder-fatal.js <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder <del>} = require('util'); <ide> <ide> const bad = [ <ide> { encoding: 'utf-8', input: [0xFF], name: 'invalid code' }, <ide><path>test/parallel/test-whatwg-encoding-textdecoder-ignorebom.js <ide> const common = require('../common'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder <del>} = require('util'); <ide> <ide> const cases = [ <ide> { <ide><path>test/parallel/test-whatwg-encoding-textdecoder-streaming.js <ide> const common = require('../common'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder <del>} = require('util'); <ide> <ide> const string = <ide> '\x00123ABCabc\x80\xFF\u0100\u1000\uFFFD\uD800\uDC00\uDBFF\uDFFF'; <ide><path>test/parallel/test-whatwg-encoding-textdecoder-utf16-surrogates.js <ide> if (!common.hasIntl) <ide> common.skip('missing Intl'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder <del>} = require('util'); <ide> <ide> const bad = [ <ide> { <ide><path>test/parallel/test-whatwg-encoding-textdecoder.js <ide> const common = require('../common'); <ide> <ide> const assert = require('assert'); <del>const { TextDecoder, TextEncoder } = require('util'); <ide> const { customInspectSymbol: inspect } = require('internal/util'); <ide> <ide> const buf = Buffer.from([0xef, 0xbb, 0xbf, 0x74, 0x65, <ide><path>test/parallel/test-whatwg-encoding-textencoder-utf16-surrogates.js <ide> require('../common'); <ide> <ide> const assert = require('assert'); <del>const { <del> TextDecoder, <del> TextEncoder <del>} = require('util'); <ide> <ide> const bad = [ <ide> { <ide><path>test/parallel/test-whatwg-encoding-textencoder.js <ide> const common = require('../common'); <ide> <ide> const assert = require('assert'); <del>const { TextDecoder, TextEncoder } = require('util'); <ide> const { customInspectSymbol: inspect } = require('internal/util'); <ide> <ide> const encoded = Buffer.from([0xef, 0xbb, 0xbf, 0x74, 0x65,
15
Python
Python
add type hints for tf mpnet models
fe5e7cea4ac9c7b0cca8c33b86a24827e8331311
<ide><path>src/transformers/models/mpnet/modeling_tf_mpnet.py <ide> <ide> import math <ide> import warnings <add>from typing import Optional, Tuple, Union <ide> <add>import numpy as np <ide> import tensorflow as tf <ide> <ide> from ...activations_tf import get_tf_activation <ide> ) <ide> from ...modeling_tf_utils import ( <ide> TFMaskedLanguageModelingLoss, <add> TFModelInputType, <ide> TFMultipleChoiceLoss, <ide> TFPreTrainedModel, <ide> TFQuestionAnsweringLoss, <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> training=False, <del> ): <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.array, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> training: bool = False, <add> ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor]]: <ide> outputs = self.mpnet( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> def get_prefix_bias_name(self): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <del> ): <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: bool = False, <add> ) -> Union[TFMaskedLMOutput, Tuple[tf.Tensor]]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <del> ): <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.array, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: bool = False, <add> ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., <ide> def dummy_inputs(self): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <del> ): <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: bool = False, <add> ) -> Union[TFMultipleChoiceModelOutput, Tuple[tf.Tensor]]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]` <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> labels=None, <del> training=False, <del> ): <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.ndarray, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> labels: Optional[tf.Tensor] = None, <add> training: bool = False, <add> ) -> Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]: <ide> r""" <ide> labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> def __init__(self, config, *inputs, **kwargs): <ide> ) <ide> def call( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> position_ids=None, <del> head_mask=None, <del> inputs_embeds=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> start_positions=None, <del> end_positions=None, <del> training=False, <add> input_ids: Optional[TFModelInputType] = None, <add> attention_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> position_ids: Optional[Union[np.array, tf.Tensor]] = None, <add> head_mask: Optional[Union[np.array, tf.Tensor]] = None, <add> inputs_embeds: Optional[tf.Tensor] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> start_positions: Optional[tf.Tensor] = None, <add> end_positions: Optional[tf.Tensor] = None, <add> training: bool = False, <ide> **kwargs, <del> ): <add> ) -> Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]: <ide> r""" <ide> start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*): <ide> Labels for position (index) of the start of the labelled span for computing the token classification loss.
1
Text
Text
change http links to https in support.md
09964826901fb91fd4f722d1b4932b0c458f5439
<ide><path>SUPPORT.md <ide> <ide> If you're looking for support for Atom there are a lot of options, check out: <ide> <del>* User Documentation &mdash; [The Atom Flight Manual](http://flight-manual.atom.io) <add>* User Documentation &mdash; [The Atom Flight Manual](https://flight-manual.atom.io) <ide> * Developer Documentation &mdash; [Atom API Documentation](https://atom.io/docs/api/latest) <ide> * FAQ &mdash; [The Atom FAQ on Discuss](https://discuss.atom.io/c/faq) <ide> * Message Board &mdash; [Discuss, the official Atom and Electron message board](https://discuss.atom.io) <del>* Chat &mdash; [Join the Atom Slack team](http://atom-slack.herokuapp.com/) <add>* Chat &mdash; [Join the Atom Slack team](https://atom-slack.herokuapp.com/) <ide> <ide> On Discuss and in the Atom Slack team, there are a bunch of helpful community members that should be willing to point you in the right direction.
1
Text
Text
add v3.26.0-beta.3 to changelog
891fc1bd25b9736e0d645bda01155d3023f7fab1
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.26.0-beta.3 (March 02, 2021) <add> <add>- [#19412](https://github.com/emberjs/ember.js/pull/19412) [BUGFIX] Updates Glimmer VM to 0.76.0, fix: <add> - `if` helper returns `null` instead of `undefined` <add> - Using `get` helper with key `length` on a string in templates <add> - Value of input not updating if it had previously updated with the same string <add>- [#19416](https://github.com/emberjs/ember.js/pull/19416) [BUGFIX] Update Glimmer VM to 0.77, fix dynamic helpers/modifiers <add> <ide> ### v3.26.0-beta.2 (February 15, 2021) <ide> <ide> - [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] LinkTo with incomplete model failing in rendering tests
1
Text
Text
remove http2 pushstream weight option
a0f7ae6c4110cca75793964dc9dbbf457071dad8
<ide><path>doc/api/http2.md <ide> added: v8.4.0 <ide> Defaults to `false`. <ide> * `parent` {number} Specifies the numeric identifier of a stream the newly <ide> created stream is dependent on. <del> * `weight` {number} Specifies the relative dependency of a stream in relation <del> to other streams with the same `parent`. The value is a number between `1` <del> and `256` (inclusive). <ide> * `callback` {Function} Callback that is called once the push stream has been <ide> initiated. <ide> * Returns: {undefined} <ide> server.on('stream', (stream) => { <ide> }); <ide> ``` <ide> <add>Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass <add>a `weight` value to `http2stream.priority` with the `silent` option set to <add>`true` to enable server-side bandwidth balancing between concurrent streams. <add> <ide> #### http2stream.respond([headers[, options]]) <ide> <!-- YAML <ide> added: v8.4.0
1
Text
Text
add body text and link
2ee112c6b1fc8d00eda69e38a549686cda24ca23
<ide><path>guide/english/tools/calculators/calorie-calculator/index.md <ide> title: Calorie Calculator <ide> --- <ide> ## Calorie Calculator <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/tools/calculators/calorie-calculator/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>A calorie calculator refers to a calculator that estimates the daily caloric requirements of a person given a number of variables, including weight, height, and age. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <del> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>There are a number of equations that can be used in these calculators, and the end calculation and its accuracy may depend on which is used. A few of the most common ones include the Mifflin-St. Jeor equation and the Katch-McArdle formula. <ide> <ide> #### More Information: <del><!-- Please add any articles you think might be helpful to read before writing the article --> <add>* [An online calorie calculator](https://www.calculator.net/calorie-calculator.html) <add> <ide> <ide>
1
Javascript
Javascript
remove dup before create
412fddd0655f66e6b6684d78ea47c41fcb07a314
<ide><path>common/models/user.js <ide> module.exports = function(User) { <ide> return ctx.res.redirect(redirect); <ide> }); <ide> <del> User.beforeRemote('create', function({ req, res }, _, next) { <del> req.body.username = 'fcc' + uuid.v4().slice(0, 8); <del> if (!req.body.email) { <del> return next(); <del> } <del> if (!isEmail(req.body.email)) { <del> return next(new Error('Email format is not valid')); <del> } <del> return User.doesExist(null, req.body.email) <del> .then(exists => { <del> if (!exists) { <del> return next(); <del> } <del> <del> req.flash('error', { <del> msg: dedent` <del> The ${req.body.email} email address is already associated with an account. <del> Try signing in with it here instead. <del> ` <del> }); <del> <del> return res.redirect('/email-signin'); <del> }) <del> .catch(err => { <del> console.error(err); <del> req.flash('error', { <del> msg: 'Oops, something went wrong, please try again later' <del> }); <del> return res.redirect('/email-signin'); <del> }); <del> }); <ide> <ide> User.beforeRemote('login', function(ctx, notUsed, next) { <ide> const { body } = ctx.req;
1
Text
Text
add note about header values encoding
dfc2dc8b6565da78d493c44aa836482dd422aeed
<ide><path>doc/api/http.md <ide> or <ide> request.setHeader('Cookie', ['type=ninja', 'language=javascript']); <ide> ``` <ide> <add>When the value is a string an exception will be thrown if it contains <add>characters outside the `latin1` encoding. <add> <add>If you need to pass UTF-8 characters in the value please encode the value <add>using the [RFC 8187][] standard. <add> <add>```js <add>const filename = 'Rock 🎵.txt'; <add>request.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`); <add>``` <add> <ide> ### `request.setNoDelay([noDelay])` <ide> <ide> <!-- YAML <ide> try { <ide> } <ide> ``` <ide> <add>[RFC 8187]: https://www.rfc-editor.org/rfc/rfc8187.txt <ide> [`'checkContinue'`]: #event-checkcontinue <ide> [`'finish'`]: #event-finish <ide> [`'request'`]: #event-request
1
Javascript
Javascript
improve scroll to top performance
12b228c5d92e5b6ef80f8cfdb0c29fc1845a3044
<ide><path>Libraries/Experimental/VirtualizedList.js <ide> type ItemComponentType = ReactClass<{item: Item, index: number}>; <ide> <ide> /** <ide> * Renders a virtual list of items given a data blob and accessor functions. Items that are outside <del> * the render window are 'virtualized' e.g. unmounted or never rendered in the first place. This <del> * improves performance and saves memory for large data sets, but will reset state on items that <del> * scroll too far out of the render window. <add> * the render window (except for the initial items at the top) are 'virtualized' e.g. unmounted or <add> * never rendered in the first place. This improves performance and saves memory for large data <add> * sets, but will reset state on items that scroll too far out of the render window. <ide> * <ide> * TODO: Note that LayoutAnimation and sticky section headers both have bugs when used with this and <ide> * are therefor not supported, but new Animated impl might work? <ide> type OptionalProps = { <ide> * Set this true while waiting for new data from a refresh. <ide> */ <ide> refreshing?: boolean, <add> removeClippedSubviews?: boolean, <ide> renderScrollComponent: (props: Object) => React.Element<*>, <ide> shouldItemUpdate: ( <ide> props: {item: Item, index: number}, <ide> class VirtualizedList extends React.PureComponent { <ide> maxToRenderPerBatch: 10, <ide> onEndReached: () => {}, <ide> onEndReachedThreshold: 2, // multiples of length <add> removeClippedSubviews: true, <ide> renderScrollComponent: (props: Props) => { <ide> if (props.onRefresh) { <ide> invariant( <ide> class VirtualizedList extends React.PureComponent { <ide> this._updateCellsToRenderBatcher.schedule(); <ide> } <ide> <add> _pushCells(cells, first, last) { <add> const {SeparatorComponent, data, getItem, getItemCount, keyExtractor} = this.props; <add> const end = getItemCount(data) - 1; <add> last = Math.min(end, last); <add> for (let ii = first; ii <= last; ii++) { <add> const item = getItem(data, ii); <add> invariant(item, 'No item for index ' + ii); <add> const key = keyExtractor(item, ii); <add> cells.push( <add> <CellRenderer <add> cellKey={key} <add> index={ii} <add> item={item} <add> key={key} <add> onLayout={this._onCellLayout} <add> parentProps={this.props} <add> /> <add> ); <add> if (SeparatorComponent && ii < end) { <add> cells.push(<SeparatorComponent key={'sep' + ii}/>); <add> } <add> } <add> } <ide> render() { <del> const {FooterComponent, HeaderComponent, SeparatorComponent} = this.props; <del> const {data, disableVirtualization, getItem, horizontal, keyExtractor} = this.props; <add> const {FooterComponent, HeaderComponent} = this.props; <add> const {data, disableVirtualization, horizontal} = this.props; <ide> const cells = []; <ide> if (HeaderComponent) { <ide> cells.push( <ide> class VirtualizedList extends React.PureComponent { <ide> const itemCount = this.props.getItemCount(data); <ide> if (itemCount > 0) { <ide> _usedIndexForKey = false; <add> const lastInitialIndex = this.props.initialNumToRender - 1; <ide> const {first, last} = this.state; <del> if (!disableVirtualization && first > 0) { <del> const firstOffset = this._getFrameMetricsApprox(first).offset - this._headerLength; <add> this._pushCells(cells, 0, lastInitialIndex); <add> if (!disableVirtualization && first > lastInitialIndex) { <add> const initBlock = this._getFrameMetricsApprox(lastInitialIndex); <add> const firstSpace = this._getFrameMetricsApprox(first).offset - <add> (initBlock.offset + initBlock.length); <ide> cells.push( <del> <View key="$lead_spacer" style={{[!horizontal ? 'height' : 'width']: firstOffset}} /> <del> ); <del> } <del> for (let ii = first; ii <= last; ii++) { <del> const item = getItem(data, ii); <del> invariant(item, 'No item for index ' + ii); <del> const key = keyExtractor(item, ii); <del> cells.push( <del> <CellRenderer <del> cellKey={key} <del> index={ii} <del> item={item} <del> key={key} <del> onLayout={this._onCellLayout} <del> parentProps={this.props} <del> /> <add> <View key="$lead_spacer" style={{[!horizontal ? 'height' : 'width']: firstSpace}} /> <ide> ); <del> if (SeparatorComponent && ii < last) { <del> cells.push(<SeparatorComponent key={'sep' + ii}/>); <del> } <ide> } <add> this._pushCells(cells, Math.max(lastInitialIndex + 1, first), last); <ide> if (!this._hasWarned.keys && _usedIndexForKey) { <ide> console.warn( <ide> 'VirtualizedList: missing keys for items, make sure to specify a key property on each ' +
1
Python
Python
kill class in test_basic
a4931ff3a74d9fcd8766bee69a01b62a75a5e131
<ide><path>tests/test_basic.py <ide> import time <ide> import flask <ide> import pickle <del>import unittest <ide> from datetime import datetime <ide> from threading import Thread <del>from tests import emits_module_deprecation_warning <ide> from flask._compat import text_type <ide> from werkzeug.exceptions import BadRequest, NotFound, Forbidden <ide> from werkzeug.http import parse_date <ide> from werkzeug.routing import BuildError <ide> <ide> <del>class TestBasicFunctionality(object): <add>def test_options_work(): <add> app = flask.Flask(__name__) <ide> <del> def test_options_work(self): <del> app = flask.Flask(__name__) <del> @app.route('/', methods=['GET', 'POST']) <del> def index(): <del> return 'Hello World' <del> rv = app.test_client().open('/', method='OPTIONS') <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <del> assert rv.data == b'' <add> @app.route('/', methods=['GET', 'POST']) <add> def index(): <add> return 'Hello World' <add> rv = app.test_client().open('/', method='OPTIONS') <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <add> assert rv.data == b'' <ide> <del> def test_options_on_multiple_rules(self): <del> app = flask.Flask(__name__) <del> @app.route('/', methods=['GET', 'POST']) <del> def index(): <del> return 'Hello World' <del> @app.route('/', methods=['PUT']) <del> def index_put(): <del> return 'Aha!' <del> rv = app.test_client().open('/', method='OPTIONS') <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] <del> <del> def test_options_handling_disabled(self): <del> app = flask.Flask(__name__) <del> def index(): <del> return 'Hello World!' <del> index.provide_automatic_options = False <del> app.route('/')(index) <del> rv = app.test_client().open('/', method='OPTIONS') <del> assert rv.status_code == 405 <ide> <del> app = flask.Flask(__name__) <del> def index2(): <del> return 'Hello World!' <del> index2.provide_automatic_options = True <del> app.route('/', methods=['OPTIONS'])(index2) <del> rv = app.test_client().open('/', method='OPTIONS') <del> assert sorted(rv.allow) == ['OPTIONS'] <del> <del> def test_request_dispatching(self): <del> app = flask.Flask(__name__) <del> @app.route('/') <del> def index(): <del> return flask.request.method <del> @app.route('/more', methods=['GET', 'POST']) <del> def more(): <del> return flask.request.method <add>def test_options_on_multiple_rules(): <add> app = flask.Flask(__name__) <ide> <del> c = app.test_client() <del> assert c.get('/').data == b'GET' <del> rv = c.post('/') <del> assert rv.status_code == 405 <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] <del> rv = c.head('/') <del> assert rv.status_code == 200 <del> assert not rv.data # head truncates <del> assert c.post('/more').data == b'POST' <del> assert c.get('/more').data == b'GET' <del> rv = c.delete('/more') <del> assert rv.status_code == 405 <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <del> <del> def test_disallow_string_for_allowed_methods(self): <del> app = flask.Flask(__name__) <del> with pytest.raises(TypeError): <del> @app.route('/', methods='GET POST') <del> def index(): <del> return "Hey" <add> @app.route('/', methods=['GET', 'POST']) <add> def index(): <add> return 'Hello World' <ide> <del> def test_url_mapping(self): <del> app = flask.Flask(__name__) <del> def index(): <del> return flask.request.method <del> def more(): <del> return flask.request.method <add> @app.route('/', methods=['PUT']) <add> def index_put(): <add> return 'Aha!' <add> rv = app.test_client().open('/', method='OPTIONS') <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] <ide> <del> app.add_url_rule('/', 'index', index) <del> app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) <ide> <del> c = app.test_client() <del> assert c.get('/').data == b'GET' <del> rv = c.post('/') <del> assert rv.status_code == 405 <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] <del> rv = c.head('/') <del> assert rv.status_code == 200 <del> assert not rv.data # head truncates <del> assert c.post('/more').data == b'POST' <del> assert c.get('/more').data == b'GET' <del> rv = c.delete('/more') <del> assert rv.status_code == 405 <del> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <del> <del> def test_werkzeug_routing(self): <del> from werkzeug.routing import Submount, Rule <del> app = flask.Flask(__name__) <del> app.url_map.add(Submount('/foo', [ <del> Rule('/bar', endpoint='bar'), <del> Rule('/', endpoint='index') <del> ])) <del> def bar(): <del> return 'bar' <del> def index(): <del> return 'index' <del> app.view_functions['bar'] = bar <del> app.view_functions['index'] = index <add>def test_options_handling_disabled(): <add> app = flask.Flask(__name__) <ide> <del> c = app.test_client() <del> assert c.get('/foo/').data == b'index' <del> assert c.get('/foo/bar').data == b'bar' <add> def index(): <add> return 'Hello World!' <add> index.provide_automatic_options = False <add> app.route('/')(index) <add> rv = app.test_client().open('/', method='OPTIONS') <add> assert rv.status_code == 405 <ide> <del> def test_endpoint_decorator(self): <del> from werkzeug.routing import Submount, Rule <del> app = flask.Flask(__name__) <del> app.url_map.add(Submount('/foo', [ <del> Rule('/bar', endpoint='bar'), <del> Rule('/', endpoint='index') <del> ])) <add> app = flask.Flask(__name__) <ide> <del> @app.endpoint('bar') <del> def bar(): <del> return 'bar' <add> def index2(): <add> return 'Hello World!' <add> index2.provide_automatic_options = True <add> app.route('/', methods=['OPTIONS'])(index2) <add> rv = app.test_client().open('/', method='OPTIONS') <add> assert sorted(rv.allow) == ['OPTIONS'] <ide> <del> @app.endpoint('index') <del> def index(): <del> return 'index' <ide> <del> c = app.test_client() <del> assert c.get('/foo/').data == b'index' <del> assert c.get('/foo/bar').data == b'bar' <add>def test_request_dispatching(): <add> app = flask.Flask(__name__) <ide> <del> def test_session(self): <del> app = flask.Flask(__name__) <del> app.secret_key = 'testkey' <del> @app.route('/set', methods=['POST']) <del> def set(): <del> flask.session['value'] = flask.request.form['value'] <del> return 'value set' <del> @app.route('/get') <del> def get(): <del> return flask.session['value'] <add> @app.route('/') <add> def index(): <add> return flask.request.method <ide> <del> c = app.test_client() <del> assert c.post('/set', data={'value': '42'}).data == b'value set' <del> assert c.get('/get').data == b'42' <add> @app.route('/more', methods=['GET', 'POST']) <add> def more(): <add> return flask.request.method <ide> <del> def test_session_using_server_name(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SECRET_KEY='foo', <del> SERVER_NAME='example.com' <del> ) <del> @app.route('/') <del> def index(): <del> flask.session['testing'] = 42 <del> return 'Hello World' <del> rv = app.test_client().get('/', 'http://example.com/') <del> assert 'domain=.example.com' in rv.headers['set-cookie'].lower() <del> assert 'httponly' in rv.headers['set-cookie'].lower() <add> c = app.test_client() <add> assert c.get('/').data == b'GET' <add> rv = c.post('/') <add> assert rv.status_code == 405 <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] <add> rv = c.head('/') <add> assert rv.status_code == 200 <add> assert not rv.data # head truncates <add> assert c.post('/more').data == b'POST' <add> assert c.get('/more').data == b'GET' <add> rv = c.delete('/more') <add> assert rv.status_code == 405 <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <ide> <del> def test_session_using_server_name_and_port(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SECRET_KEY='foo', <del> SERVER_NAME='example.com:8080' <del> ) <del> @app.route('/') <del> def index(): <del> flask.session['testing'] = 42 <del> return 'Hello World' <del> rv = app.test_client().get('/', 'http://example.com:8080/') <del> assert 'domain=.example.com' in rv.headers['set-cookie'].lower() <del> assert 'httponly' in rv.headers['set-cookie'].lower() <ide> <del> def test_session_using_server_name_port_and_path(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SECRET_KEY='foo', <del> SERVER_NAME='example.com:8080', <del> APPLICATION_ROOT='/foo' <del> ) <del> @app.route('/') <add>def test_disallow_string_for_allowed_methods(): <add> app = flask.Flask(__name__) <add> with pytest.raises(TypeError): <add> @app.route('/', methods='GET POST') <ide> def index(): <del> flask.session['testing'] = 42 <del> return 'Hello World' <del> rv = app.test_client().get('/', 'http://example.com:8080/foo') <del> assert 'domain=example.com' in rv.headers['set-cookie'].lower() <del> assert 'path=/foo' in rv.headers['set-cookie'].lower() <del> assert 'httponly' in rv.headers['set-cookie'].lower() <del> <del> def test_session_using_application_root(self): <del> class PrefixPathMiddleware(object): <del> def __init__(self, app, prefix): <del> self.app = app <del> self.prefix = prefix <del> def __call__(self, environ, start_response): <del> environ['SCRIPT_NAME'] = self.prefix <del> return self.app(environ, start_response) <add> return "Hey" <add> <add> <add>def test_url_mapping(): <add> app = flask.Flask(__name__) <ide> <del> app = flask.Flask(__name__) <del> app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar') <del> app.config.update( <del> SECRET_KEY='foo', <del> APPLICATION_ROOT='/bar' <del> ) <del> @app.route('/') <del> def index(): <del> flask.session['testing'] = 42 <del> return 'Hello World' <del> rv = app.test_client().get('/', 'http://example.com:8080/') <del> assert 'path=/bar' in rv.headers['set-cookie'].lower() <add> def index(): <add> return flask.request.method <add> <add> def more(): <add> return flask.request.method <add> <add> app.add_url_rule('/', 'index', index) <add> app.add_url_rule('/more', 'more', more, methods=['GET', 'POST']) <add> <add> c = app.test_client() <add> assert c.get('/').data == b'GET' <add> rv = c.post('/') <add> assert rv.status_code == 405 <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS'] <add> rv = c.head('/') <add> assert rv.status_code == 200 <add> assert not rv.data # head truncates <add> assert c.post('/more').data == b'POST' <add> assert c.get('/more').data == b'GET' <add> rv = c.delete('/more') <add> assert rv.status_code == 405 <add> assert sorted(rv.allow) == ['GET', 'HEAD', 'OPTIONS', 'POST'] <add> <add> <add>def test_werkzeug_routing(): <add> from werkzeug.routing import Submount, Rule <add> app = flask.Flask(__name__) <add> app.url_map.add(Submount('/foo', [ <add> Rule('/bar', endpoint='bar'), <add> Rule('/', endpoint='index') <add> ])) <add> <add> def bar(): <add> return 'bar' <add> <add> def index(): <add> return 'index' <add> app.view_functions['bar'] = bar <add> app.view_functions['index'] = index <add> <add> c = app.test_client() <add> assert c.get('/foo/').data == b'index' <add> assert c.get('/foo/bar').data == b'bar' <add> <add> <add>def test_endpoint_decorator(): <add> from werkzeug.routing import Submount, Rule <add> app = flask.Flask(__name__) <add> app.url_map.add(Submount('/foo', [ <add> Rule('/bar', endpoint='bar'), <add> Rule('/', endpoint='index') <add> ])) <add> <add> @app.endpoint('bar') <add> def bar(): <add> return 'bar' <add> <add> @app.endpoint('index') <add> def index(): <add> return 'index' <add> <add> c = app.test_client() <add> assert c.get('/foo/').data == b'index' <add> assert c.get('/foo/bar').data == b'bar' <add> <add> <add>def test_session(): <add> app = flask.Flask(__name__) <add> app.secret_key = 'testkey' <add> <add> @app.route('/set', methods=['POST']) <add> def set(): <add> flask.session['value'] = flask.request.form['value'] <add> return 'value set' <add> <add> @app.route('/get') <add> def get(): <add> return flask.session['value'] <add> <add> c = app.test_client() <add> assert c.post('/set', data={'value': '42'}).data == b'value set' <add> assert c.get('/get').data == b'42' <add> <add> <add>def test_session_using_server_name(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SECRET_KEY='foo', <add> SERVER_NAME='example.com' <add> ) <add> <add> @app.route('/') <add> def index(): <add> flask.session['testing'] = 42 <add> return 'Hello World' <add> rv = app.test_client().get('/', 'http://example.com/') <add> assert 'domain=.example.com' in rv.headers['set-cookie'].lower() <add> assert 'httponly' in rv.headers['set-cookie'].lower() <add> <add> <add>def test_session_using_server_name_and_port(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SECRET_KEY='foo', <add> SERVER_NAME='example.com:8080' <add> ) <add> <add> @app.route('/') <add> def index(): <add> flask.session['testing'] = 42 <add> return 'Hello World' <add> rv = app.test_client().get('/', 'http://example.com:8080/') <add> assert 'domain=.example.com' in rv.headers['set-cookie'].lower() <add> assert 'httponly' in rv.headers['set-cookie'].lower() <add> <add> <add>def test_session_using_server_name_port_and_path(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SECRET_KEY='foo', <add> SERVER_NAME='example.com:8080', <add> APPLICATION_ROOT='/foo' <add> ) <add> <add> @app.route('/') <add> def index(): <add> flask.session['testing'] = 42 <add> return 'Hello World' <add> rv = app.test_client().get('/', 'http://example.com:8080/foo') <add> assert 'domain=example.com' in rv.headers['set-cookie'].lower() <add> assert 'path=/foo' in rv.headers['set-cookie'].lower() <add> assert 'httponly' in rv.headers['set-cookie'].lower() <add> <add> <add>def test_session_using_application_root(): <add> class PrefixPathMiddleware(object): <add> <add> def __init__(self, app, prefix): <add> self.app = app <add> self.prefix = prefix <add> <add> def __call__(self, environ, start_response): <add> environ['SCRIPT_NAME'] = self.prefix <add> return self.app(environ, start_response) <add> <add> app = flask.Flask(__name__) <add> app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar') <add> app.config.update( <add> SECRET_KEY='foo', <add> APPLICATION_ROOT='/bar' <add> ) <add> <add> @app.route('/') <add> def index(): <add> flask.session['testing'] = 42 <add> return 'Hello World' <add> rv = app.test_client().get('/', 'http://example.com:8080/') <add> assert 'path=/bar' in rv.headers['set-cookie'].lower() <add> <add> <add>def test_session_using_session_settings(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SECRET_KEY='foo', <add> SERVER_NAME='www.example.com:8080', <add> APPLICATION_ROOT='/test', <add> SESSION_COOKIE_DOMAIN='.example.com', <add> SESSION_COOKIE_HTTPONLY=False, <add> SESSION_COOKIE_SECURE=True, <add> SESSION_COOKIE_PATH='/' <add> ) <add> <add> @app.route('/') <add> def index(): <add> flask.session['testing'] = 42 <add> return 'Hello World' <add> rv = app.test_client().get('/', 'http://www.example.com:8080/test/') <add> cookie = rv.headers['set-cookie'].lower() <add> assert 'domain=.example.com' in cookie <add> assert 'path=/' in cookie <add> assert 'secure' in cookie <add> assert 'httponly' not in cookie <add> <add> <add>def test_missing_session(): <add> app = flask.Flask(__name__) <add> <add> def expect_exception(f, *args, **kwargs): <add> try: <add> f(*args, **kwargs) <add> except RuntimeError as e: <add> assert e.args and 'session is unavailable' in e.args[0] <add> else: <add> assert False, 'expected exception' <add> with app.test_request_context(): <add> assert flask.session.get('missing_key') is None <add> expect_exception(flask.session.__setitem__, 'foo', 42) <add> expect_exception(flask.session.pop, 'foo') <add> <add> <add>def test_session_expiration(): <add> permanent = True <add> app = flask.Flask(__name__) <add> app.secret_key = 'testkey' <add> <add> @app.route('/') <add> def index(): <add> flask.session['test'] = 42 <add> flask.session.permanent = permanent <add> return '' <add> <add> @app.route('/test') <add> def test(): <add> return text_type(flask.session.permanent) <add> <add> client = app.test_client() <add> rv = client.get('/') <add> assert 'set-cookie' in rv.headers <add> match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie']) <add> expires = parse_date(match.group()) <add> expected = datetime.utcnow() + app.permanent_session_lifetime <add> assert expires.year == expected.year <add> assert expires.month == expected.month <add> assert expires.day == expected.day <add> <add> rv = client.get('/test') <add> assert rv.data == b'True' <add> <add> permanent = False <add> rv = app.test_client().get('/') <add> assert 'set-cookie' in rv.headers <add> match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) <add> assert match is None <add> <add> <add>def test_session_stored_last(): <add> app = flask.Flask(__name__) <add> app.secret_key = 'development-key' <add> app.testing = True <add> <add> @app.after_request <add> def modify_session(response): <add> flask.session['foo'] = 42 <add> return response <add> <add> @app.route('/') <add> def dump_session_contents(): <add> return repr(flask.session.get('foo')) <add> <add> c = app.test_client() <add> assert c.get('/').data == b'None' <add> assert c.get('/').data == b'42' <add> <add> <add>def test_session_special_types(): <add> app = flask.Flask(__name__) <add> app.secret_key = 'development-key' <add> app.testing = True <add> now = datetime.utcnow().replace(microsecond=0) <add> the_uuid = uuid.uuid4() <add> <add> @app.after_request <add> def modify_session(response): <add> flask.session['m'] = flask.Markup('Hello!') <add> flask.session['u'] = the_uuid <add> flask.session['dt'] = now <add> flask.session['b'] = b'\xff' <add> flask.session['t'] = (1, 2, 3) <add> return response <add> <add> @app.route('/') <add> def dump_session_contents(): <add> return pickle.dumps(dict(flask.session)) <add> <add> c = app.test_client() <add> c.get('/') <add> rv = pickle.loads(c.get('/').data) <add> assert rv['m'] == flask.Markup('Hello!') <add> assert type(rv['m']) == flask.Markup <add> assert rv['dt'] == now <add> assert rv['u'] == the_uuid <add> assert rv['b'] == b'\xff' <add> assert type(rv['b']) == bytes <add> assert rv['t'] == (1, 2, 3) <add> <add> <add>def test_session_cookie_setting(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> app.secret_key = 'dev key' <add> is_permanent = True <add> <add> @app.route('/bump') <add> def bump(): <add> rv = flask.session['foo'] = flask.session.get('foo', 0) + 1 <add> flask.session.permanent = is_permanent <add> return str(rv) <add> <add> @app.route('/read') <add> def read(): <add> return str(flask.session.get('foo', 0)) <add> <add> def run_test(expect_header): <add> with app.test_client() as c: <add> assert c.get('/bump').data == b'1' <add> assert c.get('/bump').data == b'2' <add> assert c.get('/bump').data == b'3' <add> <add> rv = c.get('/read') <add> set_cookie = rv.headers.get('set-cookie') <add> assert (set_cookie is not None) == expect_header <add> assert rv.data == b'3' <add> <add> is_permanent = True <add> app.config['SESSION_REFRESH_EACH_REQUEST'] = True <add> run_test(expect_header=True) <add> <add> is_permanent = True <add> app.config['SESSION_REFRESH_EACH_REQUEST'] = False <add> run_test(expect_header=False) <add> <add> is_permanent = False <add> app.config['SESSION_REFRESH_EACH_REQUEST'] = True <add> run_test(expect_header=False) <add> <add> is_permanent = False <add> app.config['SESSION_REFRESH_EACH_REQUEST'] = False <add> run_test(expect_header=False) <add> <add> <add>def test_flashes(): <add> app = flask.Flask(__name__) <add> app.secret_key = 'testkey' <add> <add> with app.test_request_context(): <add> assert not flask.session.modified <add> flask.flash('Zap') <add> flask.session.modified = False <add> flask.flash('Zip') <add> assert flask.session.modified <add> assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] <add> <add> <add>def test_extended_flashing(): <add> # Be sure app.testing=True below, else tests can fail silently. <add> # <add> # Specifically, if app.testing is not set to True, the AssertionErrors <add> # in the view functions will cause a 500 response to the test client <add> # instead of propagating exceptions. <add> <add> app = flask.Flask(__name__) <add> app.secret_key = 'testkey' <add> app.testing = True <add> <add> @app.route('/') <add> def index(): <add> flask.flash(u'Hello World') <add> flask.flash(u'Hello World', 'error') <add> flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning') <add> return '' <add> <add> @app.route('/test/') <add> def test(): <add> messages = flask.get_flashed_messages() <add> assert list(messages) == [ <add> u'Hello World', <add> u'Hello World', <add> flask.Markup(u'<em>Testing</em>') <add> ] <add> return '' <add> <add> @app.route('/test_with_categories/') <add> def test_with_categories(): <add> messages = flask.get_flashed_messages(with_categories=True) <add> assert len(messages) == 3 <add> assert list(messages) == [ <add> ('message', u'Hello World'), <add> ('error', u'Hello World'), <add> ('warning', flask.Markup(u'<em>Testing</em>')) <add> ] <add> return '' <add> <add> @app.route('/test_filter/') <add> def test_filter(): <add> messages = flask.get_flashed_messages( <add> category_filter=['message'], with_categories=True) <add> assert list(messages) == [('message', u'Hello World')] <add> return '' <add> <add> @app.route('/test_filters/') <add> def test_filters(): <add> messages = flask.get_flashed_messages( <add> category_filter=['message', 'warning'], with_categories=True) <add> assert list(messages) == [ <add> ('message', u'Hello World'), <add> ('warning', flask.Markup(u'<em>Testing</em>')) <add> ] <add> return '' <add> <add> @app.route('/test_filters_without_returning_categories/') <add> def test_filters2(): <add> messages = flask.get_flashed_messages( <add> category_filter=['message', 'warning']) <add> assert len(messages) == 2 <add> assert messages[0] == u'Hello World' <add> assert messages[1] == flask.Markup(u'<em>Testing</em>') <add> return '' <add> <add> # Create new test client on each test to clean flashed messages. <add> <add> c = app.test_client() <add> c.get('/') <add> c.get('/test/') <add> <add> c = app.test_client() <add> c.get('/') <add> c.get('/test_with_categories/') <add> <add> c = app.test_client() <add> c.get('/') <add> c.get('/test_filter/') <add> <add> c = app.test_client() <add> c.get('/') <add> c.get('/test_filters/') <add> <add> c = app.test_client() <add> c.get('/') <add> c.get('/test_filters_without_returning_categories/') <add> <add> <add>def test_request_processing(): <add> app = flask.Flask(__name__) <add> evts = [] <add> <add> @app.before_request <add> def before_request(): <add> evts.append('before') <add> <add> @app.after_request <add> def after_request(response): <add> response.data += b'|after' <add> evts.append('after') <add> return response <add> <add> @app.route('/') <add> def index(): <add> assert 'before' in evts <add> assert 'after' not in evts <add> return 'request' <add> assert 'after' not in evts <add> rv = app.test_client().get('/').data <add> assert 'after' in evts <add> assert rv == b'request|after' <add> <add> <add>def test_after_request_processing(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.route('/') <add> def index(): <add> @flask.after_this_request <add> def foo(response): <add> response.headers['X-Foo'] = 'a header' <add> return response <add> return 'Test' <add> c = app.test_client() <add> resp = c.get('/') <add> assert resp.status_code == 200 <add> assert resp.headers['X-Foo'] == 'a header' <add> <add> <add>def test_teardown_request_handler(): <add> called = [] <add> app = flask.Flask(__name__) <add> <add> @app.teardown_request <add> def teardown_request(exc): <add> called.append(True) <add> return "Ignored" <add> <add> @app.route('/') <add> def root(): <add> return "Response" <add> rv = app.test_client().get('/') <add> assert rv.status_code == 200 <add> assert b'Response' in rv.data <add> assert len(called) == 1 <add> <add> <add>def test_teardown_request_handler_debug_mode(): <add> called = [] <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.teardown_request <add> def teardown_request(exc): <add> called.append(True) <add> return "Ignored" <add> <add> @app.route('/') <add> def root(): <add> return "Response" <add> rv = app.test_client().get('/') <add> assert rv.status_code == 200 <add> assert b'Response' in rv.data <add> assert len(called) == 1 <add> <add> <add>def test_teardown_request_handler_error(): <add> called = [] <add> app = flask.Flask(__name__) <add> app.config['LOGGER_HANDLER_POLICY'] = 'never' <add> <add> @app.teardown_request <add> def teardown_request1(exc): <add> assert type(exc) == ZeroDivisionError <add> called.append(True) <add> # This raises a new error and blows away sys.exc_info(), so we can <add> # test that all teardown_requests get passed the same original <add> # exception. <add> try: <add> raise TypeError() <add> except: <add> pass <ide> <del> def test_session_using_session_settings(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SECRET_KEY='foo', <del> SERVER_NAME='www.example.com:8080', <del> APPLICATION_ROOT='/test', <del> SESSION_COOKIE_DOMAIN='.example.com', <del> SESSION_COOKIE_HTTPONLY=False, <del> SESSION_COOKIE_SECURE=True, <del> SESSION_COOKIE_PATH='/' <del> ) <del> @app.route('/') <del> def index(): <del> flask.session['testing'] = 42 <del> return 'Hello World' <del> rv = app.test_client().get('/', 'http://www.example.com:8080/test/') <del> cookie = rv.headers['set-cookie'].lower() <del> assert 'domain=.example.com' in cookie <del> assert 'path=/' in cookie <del> assert 'secure' in cookie <del> assert 'httponly' not in cookie <del> <del> def test_missing_session(self): <del> app = flask.Flask(__name__) <del> def expect_exception(f, *args, **kwargs): <del> try: <del> f(*args, **kwargs) <del> except RuntimeError as e: <del> assert e.args and 'session is unavailable' in e.args[0] <del> else: <del> assert False, 'expected exception' <del> with app.test_request_context(): <del> assert flask.session.get('missing_key') is None <del> expect_exception(flask.session.__setitem__, 'foo', 42) <del> expect_exception(flask.session.pop, 'foo') <add> @app.teardown_request <add> def teardown_request2(exc): <add> assert type(exc) == ZeroDivisionError <add> called.append(True) <add> # This raises a new error and blows away sys.exc_info(), so we can <add> # test that all teardown_requests get passed the same original <add> # exception. <add> try: <add> raise TypeError() <add> except: <add> pass <ide> <del> def test_session_expiration(self): <del> permanent = True <del> app = flask.Flask(__name__) <del> app.secret_key = 'testkey' <del> @app.route('/') <del> def index(): <del> flask.session['test'] = 42 <del> flask.session.permanent = permanent <del> return '' <del> <del> @app.route('/test') <del> def test(): <del> return text_type(flask.session.permanent) <del> <del> client = app.test_client() <del> rv = client.get('/') <del> assert 'set-cookie' in rv.headers <del> match = re.search(r'\bexpires=([^;]+)(?i)', rv.headers['set-cookie']) <del> expires = parse_date(match.group()) <del> expected = datetime.utcnow() + app.permanent_session_lifetime <del> assert expires.year == expected.year <del> assert expires.month == expected.month <del> assert expires.day == expected.day <del> <del> rv = client.get('/test') <del> assert rv.data == b'True' <del> <del> permanent = False <del> rv = app.test_client().get('/') <del> assert 'set-cookie' in rv.headers <del> match = re.search(r'\bexpires=([^;]+)', rv.headers['set-cookie']) <del> assert match is None <del> <del> def test_session_stored_last(self): <del> app = flask.Flask(__name__) <del> app.secret_key = 'development-key' <del> app.testing = True <add> @app.route('/') <add> def fails(): <add> 1 // 0 <add> rv = app.test_client().get('/') <add> assert rv.status_code == 500 <add> assert b'Internal Server Error' in rv.data <add> assert len(called) == 2 <add> <add> <add>def test_before_after_request_order(): <add> called = [] <add> app = flask.Flask(__name__) <add> <add> @app.before_request <add> def before1(): <add> called.append(1) <add> <add> @app.before_request <add> def before2(): <add> called.append(2) <ide> <del> @app.after_request <del> def modify_session(response): <del> flask.session['foo'] = 42 <del> return response <del> @app.route('/') <del> def dump_session_contents(): <del> return repr(flask.session.get('foo')) <add> @app.after_request <add> def after1(response): <add> called.append(4) <add> return response <ide> <del> c = app.test_client() <del> assert c.get('/').data == b'None' <del> assert c.get('/').data == b'42' <add> @app.after_request <add> def after2(response): <add> called.append(3) <add> return response <ide> <del> def test_session_special_types(self): <del> app = flask.Flask(__name__) <del> app.secret_key = 'development-key' <del> app.testing = True <del> now = datetime.utcnow().replace(microsecond=0) <del> the_uuid = uuid.uuid4() <del> <del> @app.after_request <del> def modify_session(response): <del> flask.session['m'] = flask.Markup('Hello!') <del> flask.session['u'] = the_uuid <del> flask.session['dt'] = now <del> flask.session['b'] = b'\xff' <del> flask.session['t'] = (1, 2, 3) <del> return response <add> @app.teardown_request <add> def finish1(exc): <add> called.append(6) <add> <add> @app.teardown_request <add> def finish2(exc): <add> called.append(5) <add> <add> @app.route('/') <add> def index(): <add> return '42' <add> rv = app.test_client().get('/') <add> assert rv.data == b'42' <add> assert called == [1, 2, 3, 4, 5, 6] <ide> <del> @app.route('/') <del> def dump_session_contents(): <del> return pickle.dumps(dict(flask.session)) <ide> <del> c = app.test_client() <del> c.get('/') <del> rv = pickle.loads(c.get('/').data) <del> assert rv['m'] == flask.Markup('Hello!') <del> assert type(rv['m']) == flask.Markup <del> assert rv['dt'] == now <del> assert rv['u'] == the_uuid <del> assert rv['b'] == b'\xff' <del> assert type(rv['b']) == bytes <del> assert rv['t'] == (1, 2, 3) <del> <del> def test_session_cookie_setting(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> app.secret_key = 'dev key' <del> is_permanent = True <del> <del> @app.route('/bump') <del> def bump(): <del> rv = flask.session['foo'] = flask.session.get('foo', 0) + 1 <del> flask.session.permanent = is_permanent <del> return str(rv) <del> <del> @app.route('/read') <del> def read(): <del> return str(flask.session.get('foo', 0)) <del> <del> def run_test(expect_header): <del> with app.test_client() as c: <del> assert c.get('/bump').data == b'1' <del> assert c.get('/bump').data == b'2' <del> assert c.get('/bump').data == b'3' <del> <del> rv = c.get('/read') <del> set_cookie = rv.headers.get('set-cookie') <del> assert (set_cookie is not None) == expect_header <del> assert rv.data == b'3' <del> <del> is_permanent = True <del> app.config['SESSION_REFRESH_EACH_REQUEST'] = True <del> run_test(expect_header=True) <del> <del> is_permanent = True <del> app.config['SESSION_REFRESH_EACH_REQUEST'] = False <del> run_test(expect_header=False) <del> <del> is_permanent = False <del> app.config['SESSION_REFRESH_EACH_REQUEST'] = True <del> run_test(expect_header=False) <del> <del> is_permanent = False <del> app.config['SESSION_REFRESH_EACH_REQUEST'] = False <del> run_test(expect_header=False) <del> <del> def test_flashes(self): <del> app = flask.Flask(__name__) <del> app.secret_key = 'testkey' <add>def test_error_handling(): <add> app = flask.Flask(__name__) <add> app.config['LOGGER_HANDLER_POLICY'] = 'never' <add> <add> @app.errorhandler(404) <add> def not_found(e): <add> return 'not found', 404 <add> <add> @app.errorhandler(500) <add> def internal_server_error(e): <add> return 'internal server error', 500 <ide> <del> with app.test_request_context(): <del> assert not flask.session.modified <del> flask.flash('Zap') <del> flask.session.modified = False <del> flask.flash('Zip') <del> assert flask.session.modified <del> assert list(flask.get_flashed_messages()) == ['Zap', 'Zip'] <del> <del> def test_extended_flashing(self): <del> # Be sure app.testing=True below, else tests can fail silently. <del> # <del> # Specifically, if app.testing is not set to True, the AssertionErrors <del> # in the view functions will cause a 500 response to the test client <del> # instead of propagating exceptions. <add> @app.errorhandler(Forbidden) <add> def forbidden(e): <add> return 'forbidden', 403 <add> <add> @app.route('/') <add> def index(): <add> flask.abort(404) <add> <add> @app.route('/error') <add> def error(): <add> 1 // 0 <add> <add> @app.route('/forbidden') <add> def error2(): <add> flask.abort(403) <add> c = app.test_client() <add> rv = c.get('/') <add> assert rv.status_code == 404 <add> assert rv.data == b'not found' <add> rv = c.get('/error') <add> assert rv.status_code == 500 <add> assert b'internal server error' == rv.data <add> rv = c.get('/forbidden') <add> assert rv.status_code == 403 <add> assert b'forbidden' == rv.data <add> <add> <add>def test_before_request_and_routing_errors(): <add> app = flask.Flask(__name__) <ide> <del> app = flask.Flask(__name__) <del> app.secret_key = 'testkey' <del> app.testing = True <add> @app.before_request <add> def attach_something(): <add> flask.g.something = 'value' <add> <add> @app.errorhandler(404) <add> def return_something(error): <add> return flask.g.something, 404 <add> rv = app.test_client().get('/') <add> assert rv.status_code == 404 <add> assert rv.data == b'value' <add> <add> <add>def test_user_error_handling(): <add> class MyException(Exception): <add> pass <add> <add> app = flask.Flask(__name__) <add> <add> @app.errorhandler(MyException) <add> def handle_my_exception(e): <add> assert isinstance(e, MyException) <add> return '42' <add> <add> @app.route('/') <add> def index(): <add> raise MyException() <add> <add> c = app.test_client() <add> assert c.get('/').data == b'42' <add> <add> <add>def test_http_error_subclass_handling(): <add> class ForbiddenSubclass(Forbidden): <add> pass <add> <add> app = flask.Flask(__name__) <add> <add> @app.errorhandler(ForbiddenSubclass) <add> def handle_forbidden_subclass(e): <add> assert isinstance(e, ForbiddenSubclass) <add> return 'banana' <add> <add> @app.errorhandler(403) <add> def handle_forbidden_subclass(e): <add> assert not isinstance(e, ForbiddenSubclass) <add> assert isinstance(e, Forbidden) <add> return 'apple' <add> <add> @app.route('/1') <add> def index1(): <add> raise ForbiddenSubclass() <add> <add> @app.route('/2') <add> def index2(): <add> flask.abort(403) <ide> <del> @app.route('/') <del> def index(): <del> flask.flash(u'Hello World') <del> flask.flash(u'Hello World', 'error') <del> flask.flash(flask.Markup(u'<em>Testing</em>'), 'warning') <del> return '' <del> <del> @app.route('/test/') <del> def test(): <del> messages = flask.get_flashed_messages() <del> assert list(messages) == [ <del> u'Hello World', <del> u'Hello World', <del> flask.Markup(u'<em>Testing</em>') <del> ] <del> return '' <del> <del> @app.route('/test_with_categories/') <del> def test_with_categories(): <del> messages = flask.get_flashed_messages(with_categories=True) <del> assert len(messages) == 3 <del> assert list(messages) == [ <del> ('message', u'Hello World'), <del> ('error', u'Hello World'), <del> ('warning', flask.Markup(u'<em>Testing</em>')) <del> ] <del> return '' <del> <del> @app.route('/test_filter/') <del> def test_filter(): <del> messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True) <del> assert list(messages) == [('message', u'Hello World')] <del> return '' <del> <del> @app.route('/test_filters/') <del> def test_filters(): <del> messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True) <del> assert list(messages) == [ <del> ('message', u'Hello World'), <del> ('warning', flask.Markup(u'<em>Testing</em>')) <del> ] <del> return '' <del> <del> @app.route('/test_filters_without_returning_categories/') <del> def test_filters2(): <del> messages = flask.get_flashed_messages(category_filter=['message', 'warning']) <del> assert len(messages) == 2 <del> assert messages[0] == u'Hello World' <del> assert messages[1] == flask.Markup(u'<em>Testing</em>') <del> return '' <del> <del> # Create new test client on each test to clean flashed messages. <add> @app.route('/3') <add> def index3(): <add> raise Forbidden() <add> <add> c = app.test_client() <add> assert c.get('/1').data == b'banana' <add> assert c.get('/2').data == b'apple' <add> assert c.get('/3').data == b'apple' <add> <add> <add>def test_trapping_of_bad_request_key_errors(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.route('/fail') <add> def fail(): <add> flask.request.form['missing_key'] <add> c = app.test_client() <add> assert c.get('/fail').status_code == 400 <add> <add> app.config['TRAP_BAD_REQUEST_ERRORS'] = True <add> c = app.test_client() <add> try: <add> c.get('/fail') <add> except KeyError as e: <add> assert isinstance(e, BadRequest) <add> else: <add> assert False, 'Expected exception' <add> <add> <add>def test_trapping_of_all_http_exceptions(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> app.config['TRAP_HTTP_EXCEPTIONS'] = True <ide> <del> c = app.test_client() <del> c.get('/') <del> c.get('/test/') <add> @app.route('/fail') <add> def fail(): <add> flask.abort(404) <ide> <del> c = app.test_client() <del> c.get('/') <del> c.get('/test_with_categories/') <add> c = app.test_client() <add> with pytest.raises(NotFound): <add> c.get('/fail') <ide> <del> c = app.test_client() <del> c.get('/') <del> c.get('/test_filter/') <ide> <del> c = app.test_client() <del> c.get('/') <del> c.get('/test_filters/') <add>def test_enctype_debug_helper(): <add> from flask.debughelpers import DebugFilesKeyError <add> app = flask.Flask(__name__) <add> app.debug = True <ide> <del> c = app.test_client() <del> c.get('/') <del> c.get('/test_filters_without_returning_categories/') <add> @app.route('/fail', methods=['POST']) <add> def index(): <add> return flask.request.files['foo'].filename <ide> <del> def test_request_processing(self): <del> app = flask.Flask(__name__) <del> evts = [] <del> @app.before_request <del> def before_request(): <del> evts.append('before') <del> @app.after_request <del> def after_request(response): <del> response.data += b'|after' <del> evts.append('after') <del> return response <del> @app.route('/') <del> def index(): <del> assert 'before' in evts <del> assert 'after' not in evts <del> return 'request' <del> assert 'after' not in evts <del> rv = app.test_client().get('/').data <del> assert 'after' in evts <del> assert rv == b'request|after' <add> # with statement is important because we leave an exception on the <add> # stack otherwise and we want to ensure that this is not the case <add> # to not negatively affect other tests. <add> with app.test_client() as c: <add> try: <add> c.post('/fail', data={'foo': 'index.txt'}) <add> except DebugFilesKeyError as e: <add> assert 'no file contents were transmitted' in str(e) <add> assert 'This was submitted: "index.txt"' in str(e) <add> else: <add> assert False, 'Expected exception' <ide> <del> def test_after_request_processing(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> @app.route('/') <del> def index(): <del> @flask.after_this_request <del> def foo(response): <del> response.headers['X-Foo'] = 'a header' <del> return response <del> return 'Test' <del> c = app.test_client() <del> resp = c.get('/') <del> assert resp.status_code == 200 <del> assert resp.headers['X-Foo'] == 'a header' <ide> <del> def test_teardown_request_handler(self): <del> called = [] <del> app = flask.Flask(__name__) <del> @app.teardown_request <del> def teardown_request(exc): <del> called.append(True) <del> return "Ignored" <del> @app.route('/') <del> def root(): <del> return "Response" <del> rv = app.test_client().get('/') <add>def test_response_creation(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/unicode') <add> def from_unicode(): <add> return u'Hällo Wörld' <add> <add> @app.route('/string') <add> def from_string(): <add> return u'Hällo Wörld'.encode('utf-8') <add> <add> @app.route('/args') <add> def from_tuple(): <add> return 'Meh', 400, { <add> 'X-Foo': 'Testing', <add> 'Content-Type': 'text/plain; charset=utf-8' <add> } <add> <add> @app.route('/two_args') <add> def from_two_args_tuple(): <add> return 'Hello', { <add> 'X-Foo': 'Test', <add> 'Content-Type': 'text/plain; charset=utf-8' <add> } <add> <add> @app.route('/args_status') <add> def from_status_tuple(): <add> return 'Hi, status!', 400 <add> <add> @app.route('/args_header') <add> def from_response_instance_status_tuple(): <add> return flask.Response('Hello world', 404), { <add> "X-Foo": "Bar", <add> "X-Bar": "Foo" <add> } <add> <add> c = app.test_client() <add> assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8') <add> assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8') <add> rv = c.get('/args') <add> assert rv.data == b'Meh' <add> assert rv.headers['X-Foo'] == 'Testing' <add> assert rv.status_code == 400 <add> assert rv.mimetype == 'text/plain' <add> rv2 = c.get('/two_args') <add> assert rv2.data == b'Hello' <add> assert rv2.headers['X-Foo'] == 'Test' <add> assert rv2.status_code == 200 <add> assert rv2.mimetype == 'text/plain' <add> rv3 = c.get('/args_status') <add> assert rv3.data == b'Hi, status!' <add> assert rv3.status_code == 400 <add> assert rv3.mimetype == 'text/html' <add> rv4 = c.get('/args_header') <add> assert rv4.data == b'Hello world' <add> assert rv4.headers['X-Foo'] == 'Bar' <add> assert rv4.headers['X-Bar'] == 'Foo' <add> assert rv4.status_code == 404 <add> <add> <add>def test_make_response(): <add> app = flask.Flask(__name__) <add> with app.test_request_context(): <add> rv = flask.make_response() <ide> assert rv.status_code == 200 <del> assert b'Response' in rv.data <del> assert len(called) == 1 <add> assert rv.data == b'' <add> assert rv.mimetype == 'text/html' <ide> <del> def test_teardown_request_handler_debug_mode(self): <del> called = [] <del> app = flask.Flask(__name__) <del> app.testing = True <del> @app.teardown_request <del> def teardown_request(exc): <del> called.append(True) <del> return "Ignored" <del> @app.route('/') <del> def root(): <del> return "Response" <del> rv = app.test_client().get('/') <add> rv = flask.make_response('Awesome') <ide> assert rv.status_code == 200 <del> assert b'Response' in rv.data <del> assert len(called) == 1 <add> assert rv.data == b'Awesome' <add> assert rv.mimetype == 'text/html' <ide> <del> def test_teardown_request_handler_error(self): <del> called = [] <del> app = flask.Flask(__name__) <del> app.config['LOGGER_HANDLER_POLICY'] = 'never' <del> @app.teardown_request <del> def teardown_request1(exc): <del> assert type(exc) == ZeroDivisionError <del> called.append(True) <del> # This raises a new error and blows away sys.exc_info(), so we can <del> # test that all teardown_requests get passed the same original <del> # exception. <del> try: <del> raise TypeError() <del> except: <del> pass <del> @app.teardown_request <del> def teardown_request2(exc): <del> assert type(exc) == ZeroDivisionError <del> called.append(True) <del> # This raises a new error and blows away sys.exc_info(), so we can <del> # test that all teardown_requests get passed the same original <del> # exception. <del> try: <del> raise TypeError() <del> except: <del> pass <del> @app.route('/') <del> def fails(): <del> 1 // 0 <del> rv = app.test_client().get('/') <del> assert rv.status_code == 500 <del> assert b'Internal Server Error' in rv.data <del> assert len(called) == 2 <add> rv = flask.make_response('W00t', 404) <add> assert rv.status_code == 404 <add> assert rv.data == b'W00t' <add> assert rv.mimetype == 'text/html' <ide> <del> def test_before_after_request_order(self): <del> called = [] <del> app = flask.Flask(__name__) <del> @app.before_request <del> def before1(): <del> called.append(1) <del> @app.before_request <del> def before2(): <del> called.append(2) <del> @app.after_request <del> def after1(response): <del> called.append(4) <del> return response <del> @app.after_request <del> def after2(response): <del> called.append(3) <del> return response <del> @app.teardown_request <del> def finish1(exc): <del> called.append(6) <del> @app.teardown_request <del> def finish2(exc): <del> called.append(5) <del> @app.route('/') <del> def index(): <del> return '42' <del> rv = app.test_client().get('/') <del> assert rv.data == b'42' <del> assert called == [1, 2, 3, 4, 5, 6] <ide> <del> def test_error_handling(self): <del> app = flask.Flask(__name__) <del> app.config['LOGGER_HANDLER_POLICY'] = 'never' <del> @app.errorhandler(404) <del> def not_found(e): <del> return 'not found', 404 <del> @app.errorhandler(500) <del> def internal_server_error(e): <del> return 'internal server error', 500 <del> @app.errorhandler(Forbidden) <del> def forbidden(e): <del> return 'forbidden', 403 <del> @app.route('/') <del> def index(): <del> flask.abort(404) <del> @app.route('/error') <del> def error(): <del> 1 // 0 <del> @app.route('/forbidden') <del> def error2(): <del> flask.abort(403) <del> c = app.test_client() <del> rv = c.get('/') <add>def test_make_response_with_response_instance(): <add> app = flask.Flask(__name__) <add> with app.test_request_context(): <add> rv = flask.make_response( <add> flask.jsonify({'msg': 'W00t'}), 400) <add> assert rv.status_code == 400 <add> assert rv.data == b'{\n "msg": "W00t"\n}' <add> assert rv.mimetype == 'application/json' <add> <add> rv = flask.make_response( <add> flask.Response(''), 400) <add> assert rv.status_code == 400 <add> assert rv.data == b'' <add> assert rv.mimetype == 'text/html' <add> <add> rv = flask.make_response( <add> flask.Response('', headers={'Content-Type': 'text/html'}), <add> 400, [('X-Foo', 'bar')]) <add> assert rv.status_code == 400 <add> assert rv.headers['Content-Type'] == 'text/html' <add> assert rv.headers['X-Foo'] == 'bar' <add> <add> <add>def test_url_generation(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/hello/<name>', methods=['POST']) <add> def hello(): <add> pass <add> with app.test_request_context(): <add> assert flask.url_for('hello', name='test x') == '/hello/test%20x' <add> assert flask.url_for('hello', name='test x', _external=True) == \ <add> 'http://localhost/hello/test%20x' <add> <add> <add>def test_build_error_handler(): <add> app = flask.Flask(__name__) <add> <add> # Test base case, a URL which results in a BuildError. <add> with app.test_request_context(): <add> pytest.raises(BuildError, flask.url_for, 'spam') <add> <add> # Verify the error is re-raised if not the current exception. <add> try: <add> with app.test_request_context(): <add> flask.url_for('spam') <add> except BuildError as err: <add> error = err <add> try: <add> raise RuntimeError('Test case where BuildError is not current.') <add> except RuntimeError: <add> pytest.raises( <add> BuildError, app.handle_url_build_error, error, 'spam', {}) <add> <add> # Test a custom handler. <add> def handler(error, endpoint, values): <add> # Just a test. <add> return '/test_handler/' <add> app.url_build_error_handlers.append(handler) <add> with app.test_request_context(): <add> assert flask.url_for('spam') == '/test_handler/' <add> <add> <add>def test_custom_converters(): <add> from werkzeug.routing import BaseConverter <add> <add> class ListConverter(BaseConverter): <add> <add> def to_python(self, value): <add> return value.split(',') <add> <add> def to_url(self, value): <add> base_to_url = super(ListConverter, self).to_url <add> return ','.join(base_to_url(x) for x in value) <add> app = flask.Flask(__name__) <add> app.url_map.converters['list'] = ListConverter <add> <add> @app.route('/<list:args>') <add> def index(args): <add> return '|'.join(args) <add> c = app.test_client() <add> assert c.get('/1,2,3').data == b'1|2|3' <add> <add> <add>def test_static_files(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> rv = app.test_client().get('/static/index.html') <add> assert rv.status_code == 200 <add> assert rv.data.strip() == b'<h1>Hello World!</h1>' <add> with app.test_request_context(): <add> assert flask.url_for('static', filename='index.html') == \ <add> '/static/index.html' <add> rv.close() <add> <add> <add>def test_none_response(): <add> app = flask.Flask(__name__) <add> app.testing = True <add> <add> @app.route('/') <add> def test(): <add> return None <add> try: <add> app.test_client().get('/') <add> except ValueError as e: <add> assert str(e) == 'View function did not return a response' <add> pass <add> else: <add> assert "Expected ValueError" <add> <add> <add>def test_request_locals(): <add> assert repr(flask.g) == '<LocalProxy unbound>' <add> assert not flask.g <add> <add> <add>def test_test_app_proper_environ(): <add> app = flask.Flask(__name__) <add> app.config.update( <add> SERVER_NAME='localhost.localdomain:5000' <add> ) <add> <add> @app.route('/') <add> def index(): <add> return 'Foo' <add> <add> @app.route('/', subdomain='foo') <add> def subdomain(): <add> return 'Foo SubDomain' <add> <add> rv = app.test_client().get('/') <add> assert rv.data == b'Foo' <add> <add> rv = app.test_client().get('/', 'http://localhost.localdomain:5000') <add> assert rv.data == b'Foo' <add> <add> rv = app.test_client().get('/', 'https://localhost.localdomain:5000') <add> assert rv.data == b'Foo' <add> <add> app.config.update(SERVER_NAME='localhost.localdomain') <add> rv = app.test_client().get('/', 'https://localhost.localdomain') <add> assert rv.data == b'Foo' <add> <add> try: <add> app.config.update(SERVER_NAME='localhost.localdomain:443') <add> rv = app.test_client().get('/', 'https://localhost.localdomain') <add> # Werkzeug 0.8 <ide> assert rv.status_code == 404 <del> assert rv.data == b'not found' <del> rv = c.get('/error') <del> assert rv.status_code == 500 <del> assert b'internal server error' == rv.data <del> rv = c.get('/forbidden') <del> assert rv.status_code == 403 <del> assert b'forbidden' == rv.data <del> <del> def test_before_request_and_routing_errors(self): <del> app = flask.Flask(__name__) <del> @app.before_request <del> def attach_something(): <del> flask.g.something = 'value' <del> @app.errorhandler(404) <del> def return_something(error): <del> return flask.g.something, 404 <del> rv = app.test_client().get('/') <add> except ValueError as e: <add> # Werkzeug 0.7 <add> assert str(e) == ( <add> "the server name provided " <add> "('localhost.localdomain:443') does not match the " <add> "server name from the WSGI environment ('localhost.localdomain')" <add> ) <add> <add> try: <add> app.config.update(SERVER_NAME='localhost.localdomain') <add> rv = app.test_client().get('/', 'http://foo.localhost') <add> # Werkzeug 0.8 <ide> assert rv.status_code == 404 <del> assert rv.data == b'value' <add> except ValueError as e: <add> # Werkzeug 0.7 <add> assert str(e) == ( <add> "the server name provided " <add> "('localhost.localdomain') does not match the " <add> "server name from the WSGI environment ('foo.localhost')" <add> ) <add> <add> rv = app.test_client().get('/', 'http://foo.localhost.localdomain') <add> assert rv.data == b'Foo SubDomain' <ide> <del> def test_user_error_handling(self): <del> class MyException(Exception): <del> pass <ide> <add>def test_exception_propagation(): <add> def apprunner(configkey): <ide> app = flask.Flask(__name__) <del> @app.errorhandler(MyException) <del> def handle_my_exception(e): <del> assert isinstance(e, MyException) <del> return '42' <add> app.config['LOGGER_HANDLER_POLICY'] = 'never' <add> <ide> @app.route('/') <ide> def index(): <del> raise MyException() <del> <add> 1 // 0 <ide> c = app.test_client() <del> assert c.get('/').data == b'42' <add> if config_key is not None: <add> app.config[config_key] = True <add> try: <add> c.get('/') <add> except Exception: <add> pass <add> else: <add> assert False, 'expected exception' <add> else: <add> assert c.get('/').status_code == 500 <add> <add> # we have to run this test in an isolated thread because if the <add> # debug flag is set to true and an exception happens the context is <add> # not torn down. This causes other tests that run after this fail <add> # when they expect no exception on the stack. <add> for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None: <add> t = Thread(target=apprunner, args=(config_key,)) <add> t.start() <add> t.join() <ide> <del> def test_http_error_subclass_handling(self): <del> class ForbiddenSubclass(Forbidden): <del> pass <ide> <del> app = flask.Flask(__name__) <del> @app.errorhandler(ForbiddenSubclass) <del> def handle_forbidden_subclass(e): <del> assert isinstance(e, ForbiddenSubclass) <del> return 'banana' <del> @app.errorhandler(403) <del> def handle_forbidden_subclass(e): <del> assert not isinstance(e, ForbiddenSubclass) <del> assert isinstance(e, Forbidden) <del> return 'apple' <del> <del> @app.route('/1') <del> def index1(): <del> raise ForbiddenSubclass() <del> @app.route('/2') <del> def index2(): <del> flask.abort(403) <del> @app.route('/3') <del> def index3(): <del> raise Forbidden() <add>def test_max_content_length(): <add> app = flask.Flask(__name__) <add> app.config['MAX_CONTENT_LENGTH'] = 64 <ide> <del> c = app.test_client() <del> assert c.get('/1').data == b'banana' <del> assert c.get('/2').data == b'apple' <del> assert c.get('/3').data == b'apple' <add> @app.before_request <add> def always_first(): <add> flask.request.form['myfile'] <add> assert False <ide> <del> def test_trapping_of_bad_request_key_errors(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> @app.route('/fail') <del> def fail(): <del> flask.request.form['missing_key'] <del> c = app.test_client() <del> assert c.get('/fail').status_code == 400 <add> @app.route('/accept', methods=['POST']) <add> def accept_file(): <add> flask.request.form['myfile'] <add> assert False <ide> <del> app.config['TRAP_BAD_REQUEST_ERRORS'] = True <del> c = app.test_client() <del> try: <del> c.get('/fail') <del> except KeyError as e: <del> assert isinstance(e, BadRequest) <del> else: <del> assert False, 'Expected exception' <add> @app.errorhandler(413) <add> def catcher(error): <add> return '42' <ide> <del> def test_trapping_of_all_http_exceptions(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> app.config['TRAP_HTTP_EXCEPTIONS'] = True <del> @app.route('/fail') <del> def fail(): <del> flask.abort(404) <add> c = app.test_client() <add> rv = c.post('/accept', data={'myfile': 'foo' * 100}) <add> assert rv.data == b'42' <ide> <del> c = app.test_client() <del> try: <del> c.get('/fail') <del> except NotFound as e: <del> pass <del> else: <del> assert False, 'Expected exception' <ide> <del> def test_enctype_debug_helper(self): <del> from flask.debughelpers import DebugFilesKeyError <del> app = flask.Flask(__name__) <del> app.debug = True <del> @app.route('/fail', methods=['POST']) <del> def index(): <del> return flask.request.files['foo'].filename <add>def test_url_processors(): <add> app = flask.Flask(__name__) <ide> <del> # with statement is important because we leave an exception on the <del> # stack otherwise and we want to ensure that this is not the case <del> # to not negatively affect other tests. <del> with app.test_client() as c: <del> try: <del> c.post('/fail', data={'foo': 'index.txt'}) <del> except DebugFilesKeyError as e: <del> assert 'no file contents were transmitted' in str(e) <del> assert 'This was submitted: "index.txt"' in str(e) <del> else: <del> assert False, 'Expected exception' <add> @app.url_defaults <add> def add_language_code(endpoint, values): <add> if flask.g.lang_code is not None and \ <add> app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): <add> values.setdefault('lang_code', flask.g.lang_code) <ide> <del> def test_response_creation(self): <del> app = flask.Flask(__name__) <del> @app.route('/unicode') <del> def from_unicode(): <del> return u'Hällo Wörld' <del> @app.route('/string') <del> def from_string(): <del> return u'Hällo Wörld'.encode('utf-8') <del> @app.route('/args') <del> def from_tuple(): <del> return 'Meh', 400, { <del> 'X-Foo': 'Testing', <del> 'Content-Type': 'text/plain; charset=utf-8' <del> } <del> @app.route('/two_args') <del> def from_two_args_tuple(): <del> return 'Hello', { <del> 'X-Foo': 'Test', <del> 'Content-Type': 'text/plain; charset=utf-8' <del> } <del> @app.route('/args_status') <del> def from_status_tuple(): <del> return 'Hi, status!', 400 <del> @app.route('/args_header') <del> def from_response_instance_status_tuple(): <del> return flask.Response('Hello world', 404), { <del> "X-Foo": "Bar", <del> "X-Bar": "Foo" <del> } <add> @app.url_value_preprocessor <add> def pull_lang_code(endpoint, values): <add> flask.g.lang_code = values.pop('lang_code', None) <ide> <del> c = app.test_client() <del> assert c.get('/unicode').data == u'Hällo Wörld'.encode('utf-8') <del> assert c.get('/string').data == u'Hällo Wörld'.encode('utf-8') <del> rv = c.get('/args') <del> assert rv.data == b'Meh' <del> assert rv.headers['X-Foo'] == 'Testing' <del> assert rv.status_code == 400 <del> assert rv.mimetype == 'text/plain' <del> rv2 = c.get('/two_args') <del> assert rv2.data == b'Hello' <del> assert rv2.headers['X-Foo'] == 'Test' <del> assert rv2.status_code == 200 <del> assert rv2.mimetype == 'text/plain' <del> rv3 = c.get('/args_status') <del> assert rv3.data == b'Hi, status!' <del> assert rv3.status_code == 400 <del> assert rv3.mimetype == 'text/html' <del> rv4 = c.get('/args_header') <del> assert rv4.data == b'Hello world' <del> assert rv4.headers['X-Foo'] == 'Bar' <del> assert rv4.headers['X-Bar'] == 'Foo' <del> assert rv4.status_code == 404 <del> <del> def test_make_response(self): <del> app = flask.Flask(__name__) <del> with app.test_request_context(): <del> rv = flask.make_response() <del> assert rv.status_code == 200 <del> assert rv.data == b'' <del> assert rv.mimetype == 'text/html' <del> <del> rv = flask.make_response('Awesome') <del> assert rv.status_code == 200 <del> assert rv.data == b'Awesome' <del> assert rv.mimetype == 'text/html' <del> <del> rv = flask.make_response('W00t', 404) <del> assert rv.status_code == 404 <del> assert rv.data == b'W00t' <del> assert rv.mimetype == 'text/html' <del> <del> def test_make_response_with_response_instance(self): <del> app = flask.Flask(__name__) <del> with app.test_request_context(): <del> rv = flask.make_response( <del> flask.jsonify({'msg': 'W00t'}), 400) <del> assert rv.status_code == 400 <del> assert rv.data == b'{\n "msg": "W00t"\n}' <del> assert rv.mimetype == 'application/json' <del> <del> rv = flask.make_response( <del> flask.Response(''), 400) <del> assert rv.status_code == 400 <del> assert rv.data == b'' <del> assert rv.mimetype == 'text/html' <del> <del> rv = flask.make_response( <del> flask.Response('', headers={'Content-Type': 'text/html'}), <del> 400, [('X-Foo', 'bar')]) <del> assert rv.status_code == 400 <del> assert rv.headers['Content-Type'] == 'text/html' <del> assert rv.headers['X-Foo'] == 'bar' <del> <del> def test_url_generation(self): <del> app = flask.Flask(__name__) <del> @app.route('/hello/<name>', methods=['POST']) <del> def hello(): <del> pass <del> with app.test_request_context(): <del> assert flask.url_for('hello', name='test x') == '/hello/test%20x' <del> assert flask.url_for('hello', name='test x', _external=True) == \ <del> 'http://localhost/hello/test%20x' <add> @app.route('/<lang_code>/') <add> def index(): <add> return flask.url_for('about') <ide> <del> def test_build_error_handler(self): <del> app = flask.Flask(__name__) <add> @app.route('/<lang_code>/about') <add> def about(): <add> return flask.url_for('something_else') <ide> <del> # Test base case, a URL which results in a BuildError. <del> with app.test_request_context(): <del> pytest.raises(BuildError, flask.url_for, 'spam') <add> @app.route('/foo') <add> def something_else(): <add> return flask.url_for('about', lang_code='en') <ide> <del> # Verify the error is re-raised if not the current exception. <del> try: <del> with app.test_request_context(): <del> flask.url_for('spam') <del> except BuildError as err: <del> error = err <del> try: <del> raise RuntimeError('Test case where BuildError is not current.') <del> except RuntimeError: <del> pytest.raises(BuildError, app.handle_url_build_error, error, 'spam', {}) <del> <del> # Test a custom handler. <del> def handler(error, endpoint, values): <del> # Just a test. <del> return '/test_handler/' <del> app.url_build_error_handlers.append(handler) <del> with app.test_request_context(): <del> assert flask.url_for('spam') == '/test_handler/' <del> <del> def test_custom_converters(self): <del> from werkzeug.routing import BaseConverter <del> class ListConverter(BaseConverter): <del> def to_python(self, value): <del> return value.split(',') <del> def to_url(self, value): <del> base_to_url = super(ListConverter, self).to_url <del> return ','.join(base_to_url(x) for x in value) <del> app = flask.Flask(__name__) <del> app.url_map.converters['list'] = ListConverter <del> @app.route('/<list:args>') <del> def index(args): <del> return '|'.join(args) <del> c = app.test_client() <del> assert c.get('/1,2,3').data == b'1|2|3' <add> c = app.test_client() <ide> <del> def test_static_files(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> rv = app.test_client().get('/static/index.html') <del> assert rv.status_code == 200 <del> assert rv.data.strip() == b'<h1>Hello World!</h1>' <del> with app.test_request_context(): <del> assert flask.url_for('static', filename='index.html') == \ <del> '/static/index.html' <del> rv.close() <add> assert c.get('/de/').data == b'/de/about' <add> assert c.get('/de/about').data == b'/foo' <add> assert c.get('/foo').data == b'/en/about' <ide> <del> def test_none_response(self): <del> app = flask.Flask(__name__) <del> app.testing = True <del> @app.route('/') <del> def test(): <del> return None <del> try: <del> app.test_client().get('/') <del> except ValueError as e: <del> assert str(e) == 'View function did not return a response' <del> pass <del> else: <del> assert "Expected ValueError" <ide> <del> def test_request_locals(self): <del> assert repr(flask.g) == '<LocalProxy unbound>' <del> assert not flask.g <add>def test_inject_blueprint_url_defaults(): <add> app = flask.Flask(__name__) <add> bp = flask.Blueprint('foo.bar.baz', __name__, <add> template_folder='template') <ide> <del> def test_test_app_proper_environ(self): <del> app = flask.Flask(__name__) <del> app.config.update( <del> SERVER_NAME='localhost.localdomain:5000' <del> ) <del> @app.route('/') <del> def index(): <del> return 'Foo' <add> @bp.url_defaults <add> def bp_defaults(endpoint, values): <add> values['page'] = 'login' <ide> <del> @app.route('/', subdomain='foo') <del> def subdomain(): <del> return 'Foo SubDomain' <add> @bp.route('/<page>') <add> def view(page): <add> pass <ide> <del> rv = app.test_client().get('/') <del> assert rv.data == b'Foo' <add> app.register_blueprint(bp) <ide> <del> rv = app.test_client().get('/', 'http://localhost.localdomain:5000') <del> assert rv.data == b'Foo' <add> values = dict() <add> app.inject_url_defaults('foo.bar.baz.view', values) <add> expected = dict(page='login') <add> assert values == expected <ide> <del> rv = app.test_client().get('/', 'https://localhost.localdomain:5000') <del> assert rv.data == b'Foo' <add> with app.test_request_context('/somepage'): <add> url = flask.url_for('foo.bar.baz.view') <add> expected = '/login' <add> assert url == expected <ide> <del> app.config.update(SERVER_NAME='localhost.localdomain') <del> rv = app.test_client().get('/', 'https://localhost.localdomain') <del> assert rv.data == b'Foo' <ide> <del> try: <del> app.config.update(SERVER_NAME='localhost.localdomain:443') <del> rv = app.test_client().get('/', 'https://localhost.localdomain') <del> # Werkzeug 0.8 <del> assert rv.status_code == 404 <del> except ValueError as e: <del> # Werkzeug 0.7 <del> assert str(e) == ( <del> "the server name provided " <del> "('localhost.localdomain:443') does not match the " <del> "server name from the WSGI environment ('localhost.localdomain')" <del> ) <add>def test_nonascii_pathinfo(): <add> app = flask.Flask(__name__) <add> app.testing = True <ide> <del> try: <del> app.config.update(SERVER_NAME='localhost.localdomain') <del> rv = app.test_client().get('/', 'http://foo.localhost') <del> # Werkzeug 0.8 <del> assert rv.status_code == 404 <del> except ValueError as e: <del> # Werkzeug 0.7 <del> assert str(e) == ( <del> "the server name provided " <del> "('localhost.localdomain') does not match the " <del> "server name from the WSGI environment ('foo.localhost')" <del> ) <del> <del> rv = app.test_client().get('/', 'http://foo.localhost.localdomain') <del> assert rv.data == b'Foo SubDomain' <del> <del> def test_exception_propagation(self): <del> def apprunner(configkey): <del> app = flask.Flask(__name__) <del> app.config['LOGGER_HANDLER_POLICY'] = 'never' <del> @app.route('/') <del> def index(): <del> 1 // 0 <del> c = app.test_client() <del> if config_key is not None: <del> app.config[config_key] = True <del> try: <del> c.get('/') <del> except Exception: <del> pass <del> else: <del> assert False, 'expected exception' <del> else: <del> assert c.get('/').status_code == 500 <del> <del> # we have to run this test in an isolated thread because if the <del> # debug flag is set to true and an exception happens the context is <del> # not torn down. This causes other tests that run after this fail <del> # when they expect no exception on the stack. <del> for config_key in 'TESTING', 'PROPAGATE_EXCEPTIONS', 'DEBUG', None: <del> t = Thread(target=apprunner, args=(config_key,)) <del> t.start() <del> t.join() <del> <del> def test_max_content_length(self): <del> app = flask.Flask(__name__) <del> app.config['MAX_CONTENT_LENGTH'] = 64 <del> @app.before_request <del> def always_first(): <del> flask.request.form['myfile'] <del> assert False <del> @app.route('/accept', methods=['POST']) <del> def accept_file(): <del> flask.request.form['myfile'] <del> assert False <del> @app.errorhandler(413) <del> def catcher(error): <del> return '42' <add> @app.route(u'/киртест') <add> def index(): <add> return 'Hello World!' <ide> <del> c = app.test_client() <del> rv = c.post('/accept', data={'myfile': 'foo' * 100}) <del> assert rv.data == b'42' <add> c = app.test_client() <add> rv = c.get(u'/киртест') <add> assert rv.data == b'Hello World!' <ide> <del> def test_url_processors(self): <del> app = flask.Flask(__name__) <ide> <del> @app.url_defaults <del> def add_language_code(endpoint, values): <del> if flask.g.lang_code is not None and \ <del> app.url_map.is_endpoint_expecting(endpoint, 'lang_code'): <del> values.setdefault('lang_code', flask.g.lang_code) <add>def test_debug_mode_complains_after_first_request(): <add> app = flask.Flask(__name__) <add> app.debug = True <ide> <del> @app.url_value_preprocessor <del> def pull_lang_code(endpoint, values): <del> flask.g.lang_code = values.pop('lang_code', None) <add> @app.route('/') <add> def index(): <add> return 'Awesome' <add> assert not app.got_first_request <add> assert app.test_client().get('/').data == b'Awesome' <add> try: <add> @app.route('/foo') <add> def broken(): <add> return 'Meh' <add> except AssertionError as e: <add> assert 'A setup function was called' in str(e) <add> else: <add> assert False, 'Expected exception' <ide> <del> @app.route('/<lang_code>/') <del> def index(): <del> return flask.url_for('about') <add> app.debug = False <ide> <del> @app.route('/<lang_code>/about') <del> def about(): <del> return flask.url_for('something_else') <add> @app.route('/foo') <add> def working(): <add> return 'Meh' <add> assert app.test_client().get('/foo').data == b'Meh' <add> assert app.got_first_request <ide> <del> @app.route('/foo') <del> def something_else(): <del> return flask.url_for('about', lang_code='en') <ide> <del> c = app.test_client() <add>def test_before_first_request_functions(): <add> got = [] <add> app = flask.Flask(__name__) <ide> <del> assert c.get('/de/').data == b'/de/about' <del> assert c.get('/de/about').data == b'/foo' <del> assert c.get('/foo').data == b'/en/about' <add> @app.before_first_request <add> def foo(): <add> got.append(42) <add> c = app.test_client() <add> c.get('/') <add> assert got == [42] <add> c.get('/') <add> assert got == [42] <add> assert app.got_first_request <ide> <del> def test_inject_blueprint_url_defaults(self): <del> app = flask.Flask(__name__) <del> bp = flask.Blueprint('foo.bar.baz', __name__, <del> template_folder='template') <ide> <del> @bp.url_defaults <del> def bp_defaults(endpoint, values): <del> values['page'] = 'login' <del> @bp.route('/<page>') <del> def view(page): pass <add>def test_before_first_request_functions_concurrent(): <add> got = [] <add> app = flask.Flask(__name__) <ide> <del> app.register_blueprint(bp) <add> @app.before_first_request <add> def foo(): <add> time.sleep(0.2) <add> got.append(42) <ide> <del> values = dict() <del> app.inject_url_defaults('foo.bar.baz.view', values) <del> expected = dict(page='login') <del> assert values == expected <add> c = app.test_client() <ide> <del> with app.test_request_context('/somepage'): <del> url = flask.url_for('foo.bar.baz.view') <del> expected = '/login' <del> assert url == expected <add> def get_and_assert(): <add> c.get("/") <add> assert got == [42] <ide> <del> def test_nonascii_pathinfo(self): <del> app = flask.Flask(__name__) <del> app.testing = True <add> t = Thread(target=get_and_assert) <add> t.start() <add> get_and_assert() <add> t.join() <add> assert app.got_first_request <ide> <del> @app.route(u'/киртест') <del> def index(): <del> return 'Hello World!' <ide> <del> c = app.test_client() <del> rv = c.get(u'/киртест') <del> assert rv.data == b'Hello World!' <add>def test_routing_redirect_debugging(): <add> app = flask.Flask(__name__) <add> app.debug = True <ide> <del> def test_debug_mode_complains_after_first_request(self): <del> app = flask.Flask(__name__) <del> app.debug = True <del> @app.route('/') <del> def index(): <del> return 'Awesome' <del> assert not app.got_first_request <del> assert app.test_client().get('/').data == b'Awesome' <add> @app.route('/foo/', methods=['GET', 'POST']) <add> def foo(): <add> return 'success' <add> with app.test_client() as c: <ide> try: <del> @app.route('/foo') <del> def broken(): <del> return 'Meh' <add> c.post('/foo', data={}) <ide> except AssertionError as e: <del> assert 'A setup function was called' in str(e) <add> assert 'http://localhost/foo/' in str(e) <add> assert ('Make sure to directly send ' <add> 'your POST-request to this URL') in str(e) <ide> else: <ide> assert False, 'Expected exception' <ide> <del> app.debug = False <del> @app.route('/foo') <del> def working(): <del> return 'Meh' <del> assert app.test_client().get('/foo').data == b'Meh' <del> assert app.got_first_request <add> rv = c.get('/foo', data={}, follow_redirects=True) <add> assert rv.data == b'success' <ide> <del> def test_before_first_request_functions(self): <del> got = [] <del> app = flask.Flask(__name__) <del> @app.before_first_request <del> def foo(): <del> got.append(42) <del> c = app.test_client() <del> c.get('/') <del> assert got == [42] <del> c.get('/') <del> assert got == [42] <del> assert app.got_first_request <add> app.debug = False <add> with app.test_client() as c: <add> rv = c.post('/foo', data={}, follow_redirects=True) <add> assert rv.data == b'success' <ide> <del> def test_before_first_request_functions_concurrent(self): <del> got = [] <del> app = flask.Flask(__name__) <ide> <del> @app.before_first_request <del> def foo(): <del> time.sleep(0.2) <del> got.append(42) <add>def test_route_decorator_custom_endpoint(): <add> app = flask.Flask(__name__) <add> app.debug = True <ide> <del> c = app.test_client() <del> def get_and_assert(): <del> c.get("/") <del> assert got == [42] <add> @app.route('/foo/') <add> def foo(): <add> return flask.request.endpoint <ide> <del> t = Thread(target=get_and_assert) <del> t.start() <del> get_and_assert() <del> t.join() <del> assert app.got_first_request <add> @app.route('/bar/', endpoint='bar') <add> def for_bar(): <add> return flask.request.endpoint <ide> <del> def test_routing_redirect_debugging(self): <del> app = flask.Flask(__name__) <del> app.debug = True <del> @app.route('/foo/', methods=['GET', 'POST']) <del> def foo(): <del> return 'success' <del> with app.test_client() as c: <del> try: <del> c.post('/foo', data={}) <del> except AssertionError as e: <del> assert 'http://localhost/foo/' in str(e) <del> assert ('Make sure to directly send ' <del> 'your POST-request to this URL') in str(e) <del> else: <del> assert False, 'Expected exception' <add> @app.route('/bar/123', endpoint='123') <add> def for_bar_foo(): <add> return flask.request.endpoint <ide> <del> rv = c.get('/foo', data={}, follow_redirects=True) <del> assert rv.data == b'success' <add> with app.test_request_context(): <add> assert flask.url_for('foo') == '/foo/' <add> assert flask.url_for('bar') == '/bar/' <add> assert flask.url_for('123') == '/bar/123' <ide> <del> app.debug = False <del> with app.test_client() as c: <del> rv = c.post('/foo', data={}, follow_redirects=True) <del> assert rv.data == b'success' <add> c = app.test_client() <add> assert c.get('/foo/').data == b'foo' <add> assert c.get('/bar/').data == b'bar' <add> assert c.get('/bar/123').data == b'123' <ide> <del> def test_route_decorator_custom_endpoint(self): <del> app = flask.Flask(__name__) <del> app.debug = True <ide> <del> @app.route('/foo/') <del> def foo(): <del> return flask.request.endpoint <add>def test_preserve_only_once(): <add> app = flask.Flask(__name__) <add> app.debug = True <ide> <del> @app.route('/bar/', endpoint='bar') <del> def for_bar(): <del> return flask.request.endpoint <add> @app.route('/fail') <add> def fail_func(): <add> 1 // 0 <ide> <del> @app.route('/bar/123', endpoint='123') <del> def for_bar_foo(): <del> return flask.request.endpoint <add> c = app.test_client() <add> for x in range(3): <add> with pytest.raises(ZeroDivisionError): <add> c.get('/fail') <ide> <del> with app.test_request_context(): <del> assert flask.url_for('foo') == '/foo/' <del> assert flask.url_for('bar') == '/bar/' <del> assert flask.url_for('123') == '/bar/123' <add> assert flask._request_ctx_stack.top is not None <add> assert flask._app_ctx_stack.top is not None <add> # implicit appctx disappears too <add> flask._request_ctx_stack.top.pop() <add> assert flask._request_ctx_stack.top is None <add> assert flask._app_ctx_stack.top is None <ide> <del> c = app.test_client() <del> assert c.get('/foo/').data == b'foo' <del> assert c.get('/bar/').data == b'bar' <del> assert c.get('/bar/123').data == b'123' <ide> <del> def test_preserve_only_once(self): <del> app = flask.Flask(__name__) <del> app.debug = True <add>def test_preserve_remembers_exception(): <add> app = flask.Flask(__name__) <add> app.debug = True <add> errors = [] <ide> <del> @app.route('/fail') <del> def fail_func(): <del> 1 // 0 <add> @app.route('/fail') <add> def fail_func(): <add> 1 // 0 <ide> <del> c = app.test_client() <del> for x in range(3): <del> with pytest.raises(ZeroDivisionError): <del> c.get('/fail') <del> <del> assert flask._request_ctx_stack.top is not None <del> assert flask._app_ctx_stack.top is not None <del> # implicit appctx disappears too <del> flask._request_ctx_stack.top.pop() <del> assert flask._request_ctx_stack.top is None <del> assert flask._app_ctx_stack.top is None <del> <del> def test_preserve_remembers_exception(self): <del> app = flask.Flask(__name__) <del> app.debug = True <del> errors = [] <add> @app.route('/success') <add> def success_func(): <add> return 'Okay' <ide> <del> @app.route('/fail') <del> def fail_func(): <del> 1 // 0 <add> @app.teardown_request <add> def teardown_handler(exc): <add> errors.append(exc) <ide> <del> @app.route('/success') <del> def success_func(): <del> return 'Okay' <add> c = app.test_client() <ide> <del> @app.teardown_request <del> def teardown_handler(exc): <del> errors.append(exc) <add> # After this failure we did not yet call the teardown handler <add> with pytest.raises(ZeroDivisionError): <add> c.get('/fail') <add> assert errors == [] <ide> <del> c = app.test_client() <add> # But this request triggers it, and it's an error <add> c.get('/success') <add> assert len(errors) == 2 <add> assert isinstance(errors[0], ZeroDivisionError) <ide> <del> # After this failure we did not yet call the teardown handler <del> with pytest.raises(ZeroDivisionError): <del> c.get('/fail') <del> assert errors == [] <add> # At this point another request does nothing. <add> c.get('/success') <add> assert len(errors) == 3 <add> assert errors[1] is None <ide> <del> # But this request triggers it, and it's an error <del> c.get('/success') <del> assert len(errors) == 2 <del> assert isinstance(errors[0], ZeroDivisionError) <ide> <del> # At this point another request does nothing. <del> c.get('/success') <del> assert len(errors) == 3 <del> assert errors[1] == None <add>def test_get_method_on_g(): <add> app = flask.Flask(__name__) <add> app.testing = True <ide> <del> def test_get_method_on_g(self): <del> app = flask.Flask(__name__) <del> app.testing = True <add> with app.app_context(): <add> assert flask.g.get('x') is None <add> assert flask.g.get('x', 11) == 11 <add> flask.g.x = 42 <add> assert flask.g.get('x') == 42 <add> assert flask.g.x == 42 <ide> <del> with app.app_context(): <del> assert flask.g.get('x') == None <del> assert flask.g.get('x', 11) == 11 <del> flask.g.x = 42 <del> assert flask.g.get('x') == 42 <del> assert flask.g.x == 42 <ide> <del> def test_g_iteration_protocol(self): <del> app = flask.Flask(__name__) <del> app.testing = True <add>def test_g_iteration_protocol(): <add> app = flask.Flask(__name__) <add> app.testing = True <ide> <del> with app.app_context(): <del> flask.g.foo = 23 <del> flask.g.bar = 42 <del> assert 'foo' in flask.g <del> assert 'foos' not in flask.g <del> assert sorted(flask.g) == ['bar', 'foo'] <add> with app.app_context(): <add> flask.g.foo = 23 <add> flask.g.bar = 42 <add> assert 'foo' in flask.g <add> assert 'foos' not in flask.g <add> assert sorted(flask.g) == ['bar', 'foo'] <ide> <ide> <del>class TestSubdomain(object): <add>def test_subdomain_basic_support(): <add> app = flask.Flask(__name__) <add> app.config['SERVER_NAME'] = 'localhost' <ide> <del> def test_basic_support(self): <del> app = flask.Flask(__name__) <del> app.config['SERVER_NAME'] = 'localhost' <del> @app.route('/') <del> def normal_index(): <del> return 'normal index' <del> @app.route('/', subdomain='test') <del> def test_index(): <del> return 'test index' <add> @app.route('/') <add> def normal_index(): <add> return 'normal index' <ide> <del> c = app.test_client() <del> rv = c.get('/', 'http://localhost/') <del> assert rv.data == b'normal index' <add> @app.route('/', subdomain='test') <add> def test_index(): <add> return 'test index' <ide> <del> rv = c.get('/', 'http://test.localhost/') <del> assert rv.data == b'test index' <add> c = app.test_client() <add> rv = c.get('/', 'http://localhost/') <add> assert rv.data == b'normal index' <ide> <del> def test_subdomain_matching(self): <del> app = flask.Flask(__name__) <del> app.config['SERVER_NAME'] = 'localhost' <del> @app.route('/', subdomain='<user>') <del> def index(user): <del> return 'index for %s' % user <add> rv = c.get('/', 'http://test.localhost/') <add> assert rv.data == b'test index' <ide> <del> c = app.test_client() <del> rv = c.get('/', 'http://mitsuhiko.localhost/') <del> assert rv.data == b'index for mitsuhiko' <ide> <del> def test_subdomain_matching_with_ports(self): <del> app = flask.Flask(__name__) <del> app.config['SERVER_NAME'] = 'localhost:3000' <del> @app.route('/', subdomain='<user>') <del> def index(user): <del> return 'index for %s' % user <add>def test_subdomain_matching(): <add> app = flask.Flask(__name__) <add> app.config['SERVER_NAME'] = 'localhost' <ide> <del> c = app.test_client() <del> rv = c.get('/', 'http://mitsuhiko.localhost:3000/') <del> assert rv.data == b'index for mitsuhiko' <add> @app.route('/', subdomain='<user>') <add> def index(user): <add> return 'index for %s' % user <ide> <del> def test_multi_route_rules(self): <del> app = flask.Flask(__name__) <add> c = app.test_client() <add> rv = c.get('/', 'http://mitsuhiko.localhost/') <add> assert rv.data == b'index for mitsuhiko' <ide> <del> @app.route('/') <del> @app.route('/<test>/') <del> def index(test='a'): <del> return test <ide> <del> rv = app.test_client().open('/') <del> assert rv.data == b'a' <del> rv = app.test_client().open('/b/') <del> assert rv.data == b'b' <add>def test_subdomain_matching_with_ports(): <add> app = flask.Flask(__name__) <add> app.config['SERVER_NAME'] = 'localhost:3000' <ide> <del> def test_multi_route_class_views(self): <del> class View(object): <del> def __init__(self, app): <del> app.add_url_rule('/', 'index', self.index) <del> app.add_url_rule('/<test>/', 'index', self.index) <add> @app.route('/', subdomain='<user>') <add> def index(user): <add> return 'index for %s' % user <ide> <del> def index(self, test='a'): <del> return test <add> c = app.test_client() <add> rv = c.get('/', 'http://mitsuhiko.localhost:3000/') <add> assert rv.data == b'index for mitsuhiko' <ide> <del> app = flask.Flask(__name__) <del> _ = View(app) <del> rv = app.test_client().open('/') <del> assert rv.data == b'a' <del> rv = app.test_client().open('/b/') <del> assert rv.data == b'b' <add> <add>def test_multi_route_rules(): <add> app = flask.Flask(__name__) <add> <add> @app.route('/') <add> @app.route('/<test>/') <add> def index(test='a'): <add> return test <add> <add> rv = app.test_client().open('/') <add> assert rv.data == b'a' <add> rv = app.test_client().open('/b/') <add> assert rv.data == b'b' <add> <add> <add>def test_multi_route_class_views(): <add> class View(object): <add> <add> def __init__(self, app): <add> app.add_url_rule('/', 'index', self.index) <add> app.add_url_rule('/<test>/', 'index', self.index) <add> <add> def index(self, test='a'): <add> return test <add> <add> app = flask.Flask(__name__) <add> _ = View(app) <add> rv = app.test_client().open('/') <add> assert rv.data == b'a' <add> rv = app.test_client().open('/b/') <add> assert rv.data == b'b'
1
Ruby
Ruby
fix layout lookup for anonymous controller
b27c29ef4a26755b8de04686241694ce5ee33724
<ide><path>actionpack/lib/abstract_controller/layouts.rb <ide> def _write_layout_method <ide> <<-RUBY <ide> lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super <ide> RUBY <add> else <add> <<-RUBY <add> super <add> RUBY <ide> end <ide> <ide> layout_definition = case _layout <ide><path>actionpack/test/abstract/layouts_test.rb <ide> class ::BadFailLayout < AbstractControllerTests::Layouts::Base <ide> controller.process(:index) <ide> assert_equal "Overwrite Hello index!", controller.response_body <ide> end <add> <add> test "layout for anonymous controller" do <add> klass = Class.new(WithString) do <add> def index <add> render :text => 'index', :layout => true <add> end <add> end <add> <add> controller = klass.new <add> controller.process(:index) <add> assert_equal "With String index", controller.response_body <add> end <ide> end <ide> end <ide> end
2
Javascript
Javascript
add tests for cacheplugin
af00214583da076a07b89f3f94fd54573c2c692f
<ide><path>test/CachePlugin.test.js <add>var should = require("should"); <add>var sinon = require("sinon"); <add>var CachePlugin = require("../lib/CachePlugin"); <add>var applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <add> <add>describe("CachePlugin", function() { <add> var env; <add> <add> beforeEach(function() { <add> env = { <add> compilation: { <add> compiler: {}, <add> warnings: [] <add> } <add> }; <add> }); <add> <add> it("has apply function", function() { <add> (new CachePlugin()).apply.should.be.a.Function(); <add> }); <add> <add> describe('applyMtime', function() { <add> beforeEach(function() { <add> env.plugin = new CachePlugin(); <add> }); <add> <add> it("sets file system accuracy to 1 for granular modification timestamp", function() { <add> env.plugin.applyMtime(1483819067001) <add> env.plugin.FS_ACCURENCY.should.be.exactly(1); <add> }); <add> <add> it("sets file system accuracy to 10 for moderately granular modification timestamp", function() { <add> env.plugin.applyMtime(1483819067004) <add> env.plugin.FS_ACCURENCY.should.be.exactly(10); <add> }); <add> <add> it("sets file system accuracy to 100 for moderately coarse modification timestamp", function() { <add> env.plugin.applyMtime(1483819067040) <add> env.plugin.FS_ACCURENCY.should.be.exactly(100); <add> }); <add> <add> it("sets file system accuracy to 1000 for coarse modification timestamp", function() { <add> env.plugin.applyMtime(1483819067400) <add> env.plugin.FS_ACCURENCY.should.be.exactly(1000); <add> }); <add> }); <add> <add> describe("when applied", function() { <add> describe("for multiple compilers", function() { <add> beforeEach(function() { <add> var plugin = new CachePlugin(); <add> env.compilers = [sinon.spy(), sinon.spy()]; <add> plugin.apply({ <add> compilers: env.compilers <add> }); <add> }); <add> <add> it("calls each compilers apply with the cache plugin context", function() { <add> env.compilers[0].callCount.should.be.exactly(1); <add> env.compilers[0].firstCall.thisValue.should.be.instanceOf(CachePlugin); <add> env.compilers[1].callCount.should.be.exactly(1); <add> env.compilers[1].firstCall.thisValue.should.be.instanceOf(CachePlugin); <add> }); <add> }); <add> <add> describe("for a single compiler", function() { <add> beforeEach(function() { <add> var applyContext = {}; <add> env.eventBindings = applyPluginWithOptions.call(applyContext, CachePlugin, { <add> test: true <add> }); <add> env.plugin = applyContext.plugin; <add> }); <add> <add> it("binds four event handlers", function() { <add> env.eventBindings.length.should.be.exactly(4); <add> }); <add> <add> it("sets the initial cache", function() { <add> env.plugin.cache.test.should.be.true(); <add> }); <add> <add> describe("compilation handler", function() { <add> it("binds to compilation event", function() { <add> env.eventBindings[0].name.should.be.exactly("compilation"); <add> }); <add> <add> describe("when cachable", function() { <add> describe("and not watching", function() { <add> beforeEach(function() { <add> env.eventBindings[0].handler(env.compilation); <add> }); <add> <add> it("sets the compilation cache", function() { <add> env.compilation.cache.should.deepEqual({ <add> test: true <add> }); <add> }); <add> }); <add> <add> describe("and watching", function() { <add> beforeEach(function() { <add> env.eventBindings[1].handler(env.compilation, function() {}); <add> env.eventBindings[0].handler(env.compilation); <add> }); <add> <add> it("does not add a compilation warning is added", function() { <add> env.compilation.warnings.should.be.empty(); <add> }); <add> }); <add> }); <add> <add> describe("when not cachable", function() { <add> beforeEach(function() { <add> env.compilation.notCacheable = true; <add> }); <add> <add> describe("and not watching", function() { <add> beforeEach(function() { <add> env.eventBindings[0].handler(env.compilation); <add> }); <add> <add> it("does not set the cache", function() { <add> should(env.compilation.cache).be.undefined(); <add> }); <add> }); <add> <add> describe("and watching", function() { <add> beforeEach(function() { <add> env.eventBindings[1].handler(env.compilation, function() {}); <add> env.eventBindings[0].handler(env.compilation); <add> }); <add> <add> it("adds a compilation warning", function() { <add> env.compilation.warnings.length.should.be.exactly(1); <add> env.compilation.warnings[0].should.be.Error("CachePlugin - Cache cannot be used because of: true"); <add> }); <add> }); <add> }); <add> }); <add> <add> describe("watch-run handler", function() { <add> beforeEach(function() { <add> env.callback = sinon.spy(); <add> env.eventBindings[1].handler(env.compilation.compiler, env.callback); <add> }); <add> <add> it("binds to watch-run event", function() { <add> env.eventBindings[1].name.should.be.exactly("watch-run"); <add> }); <add> <add> it("sets watching flag", function() { <add> env.plugin.watching.should.be.true(); <add> }); <add> <add> it("calls callback", function() { <add> env.callback.callCount.should.be.exactly(1); <add> }); <add> }); <add> <add> describe("run handler", function() { <add> beforeEach(function() { <add> env.fsStat = sinon.spy(); <add> env.callback = sinon.spy(); <add> env.compilation.compiler.inputFileSystem = { <add> stat: env.fsStat <add> }; <add> }); <add> <add> it("binds to run event", function() { <add> env.eventBindings[2].name.should.be.exactly("run"); <add> }); <add> <add> describe("Has not previously compiled", function() { <add> beforeEach(function() { <add> env.eventBindings[2].handler(env.compilation.compiler, env.callback); <add> }); <add> <add> it("does not get any file stats", function() { <add> env.fsStat.callCount.should.be.exactly(0); <add> }); <add> <add> it("calls the callback", function() { <add> env.callback.callCount.should.be.exactly(1); <add> should(env.callback.firstCall.args[0]).be.undefined(); <add> }); <add> }); <add> <add> describe("Has previously compiled", function() { <add> beforeEach(function() { <add> env.compilation.fileDependencies = ["foo"]; <add> env.compilation.contextDependencies = ["bar"]; <add> env.eventBindings[3].handler(env.compilation, function() {}); <add> env.eventBindings[2].handler(env.compilation.compiler, env.callback); <add> }); <add> <add> it("calls for file stats for file dependencies", function() { <add> env.fsStat.callCount.should.be.exactly(1); <add> env.fsStat.firstCall.args[0].should.be.exactly("foo"); <add> }); <add> <add> describe('file stats callback', function() { <add> beforeEach(function() { <add> env.fsStatCallback = env.fsStat.firstCall.args[1]; <add> }); <add> <add> describe('when error occurs', function() { <add> beforeEach(function() { <add> env.fsStatCallback(new Error('Test Error')); <add> }); <add> <add> it('calls handler callback with error', function() { <add> env.callback.callCount.should.be.exactly(1); <add> env.callback.firstCall.args[0].should.be.Error('Test Error'); <add> }); <add> }); <add> <add> describe('when ENOENT error occurs', function() { <add> beforeEach(function() { <add> env.fsStatCallback({ <add> code: 'ENOENT' <add> }); <add> }); <add> <add> it('calls handler callback without error', function() { <add> env.callback.callCount.should.be.exactly(1); <add> should(env.callback.firstCall.args[0]).be.undefined(); <add> }); <add> }); <add> <add> describe('when stat does not have modified time', function() { <add> beforeEach(function() { <add> sinon.stub(env.plugin, 'applyMtime'); <add> env.fsStatCallback(null, {}); <add> }); <add> <add> afterEach(function() { <add> env.plugin.applyMtime.restore(); <add> }); <add> <add> it('does not update file system accuracy', function() { <add> env.plugin.applyMtime.callCount.should.be.exactly(0); <add> }); <add> <add> it('updates file modified timestamp to infinity', function() { <add> env.compilation.compiler.fileTimestamps.should.deepEqual({ <add> foo: Infinity <add> }); <add> }); <add> <add> it('calls handler callback without error', function() { <add> env.callback.callCount.should.be.exactly(1); <add> should(env.callback.firstCall.args[0]).be.undefined(); <add> }); <add> }); <add> <add> describe('when stat has modified time', function() { <add> beforeEach(function() { <add> sinon.stub(env.plugin, 'applyMtime'); <add> env.fsStatCallback(null, { <add> mtime: 1483819067001 <add> }); <add> }); <add> <add> afterEach(function() { <add> env.plugin.applyMtime.restore(); <add> }); <add> <add> it('does not update file system accuracy', function() { <add> env.plugin.applyMtime.callCount.should.be.exactly(1); <add> }); <add> <add> it('updates file modified timestamp to modified time with accuracy value', function() { <add> env.compilation.compiler.fileTimestamps.should.deepEqual({ <add> foo: 1483819069001 <add> }); <add> }); <add> <add> it('calls handler callback without error', function() { <add> env.callback.callCount.should.be.exactly(1); <add> should(env.callback.firstCall.args[0]).be.undefined(); <add> }); <add> }); <add> }); <add> }); <add> }); <add> <add> describe("after-compile handler", function() { <add> beforeEach(function() { <add> env.compilation.fileDependencies = ["foo"]; <add> env.compilation.contextDependencies = ["bar"]; <add> env.callback = sinon.spy(); <add> env.eventBindings[3].handler(env.compilation, env.callback); <add> }); <add> <add> it("binds to after-compile event", function() { <add> env.eventBindings[3].name.should.be.exactly("after-compile"); <add> }); <add> <add> it("saves copy of compilation file dependecies", function() { <add> env.compilation.compiler.should.deepEqual({ <add> _lastCompilationFileDependencies: ["foo"], <add> _lastCompilationContextDependencies: ["bar"] <add> }); <add> }); <add> <add> it("calls callback", function() { <add> env.callback.callCount.should.be.exactly(1); <add> }); <add> }); <add> }); <add> }); <add>}); <ide><path>test/helpers/applyPluginWithOptions.js <ide> module.exports = function applyPluginWithOptions(Plugin) { <ide> var plugin = new (Function.prototype.bind.apply(Plugin, arguments)); <ide> var pluginEnvironment = new PluginEnvironment(); <ide> plugin.apply(pluginEnvironment.getEnvironmentStub()); <add> <add> var env = (this === global) ? {} : this; <add> env.plugin = plugin; <add> env.pluginEnvironment = pluginEnvironment; <add> <ide> return pluginEnvironment.getEventBindings(); <ide> };
2
Java
Java
use messagesource for @exceptionhandler methods
f2be4e93203d2949a8e46466f92a1715954b85b5
<ide><path>spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java <ide> public class HandlerMethod { <ide> * Create an instance from a bean instance and a method. <ide> */ <ide> public HandlerMethod(Object bean, Method method) { <add> this(bean, method, null); <add> } <add> <add> <add> /** <add> * Variant of {@link #HandlerMethod(Object, Method)} that <add> * also accepts a {@link MessageSource}. <add> */ <add> public HandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { <ide> Assert.notNull(bean, "Bean is required"); <ide> Assert.notNull(method, "Method is required"); <ide> this.bean = bean; <ide> this.beanFactory = null; <del> this.messageSource = null; <add> this.messageSource = messageSource; <ide> this.beanType = ClassUtils.getUserClass(bean); <ide> this.method = method; <ide> this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); <ide><path>spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java <ide> import java.lang.reflect.Method; <ide> import java.util.Arrays; <ide> <add>import org.springframework.context.MessageSource; <ide> import org.springframework.core.CoroutinesUtils; <ide> import org.springframework.core.DefaultParameterNameDiscoverer; <ide> import org.springframework.core.KotlinDetector; <ide> public InvocableHandlerMethod(Object bean, Method method) { <ide> super(bean, method); <ide> } <ide> <add> /** <add> * Variant of {@link #InvocableHandlerMethod(Object, Method)} that <add> * also accepts a {@link MessageSource}. <add> */ <add> public InvocableHandlerMethod(Object bean, Method method, @Nullable MessageSource messageSource) { <add> super(bean, method, messageSource); <add> } <add> <ide> /** <ide> * Construct a new handler method with the given bean instance, method name and parameters. <ide> * @param bean the object bean <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java <ide> protected ServletInvocableHandlerMethod getExceptionHandlerMethod( <ide> } <ide> Method method = resolver.resolveMethod(exception); <ide> if (method != null) { <del> return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method); <add> return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method, this.applicationContext); <ide> } <ide> // For advice applicability check below (involving base packages, assignable types <ide> // and annotation presence), use target class instead of interface-based proxy. <ide> protected ServletInvocableHandlerMethod getExceptionHandlerMethod( <ide> ExceptionHandlerMethodResolver resolver = entry.getValue(); <ide> Method method = resolver.resolveMethod(exception); <ide> if (method != null) { <del> return new ServletInvocableHandlerMethod(advice.resolveBean(), method); <add> return new ServletInvocableHandlerMethod(advice.resolveBean(), method, this.applicationContext); <ide> } <ide> } <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.HttpServletResponse; <ide> <add>import org.springframework.context.MessageSource; <ide> import org.springframework.core.KotlinDetector; <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.ResolvableType; <ide> public class ServletInvocableHandlerMethod extends InvocableHandlerMethod { <ide> @Nullable <ide> private HandlerMethodReturnValueHandlerComposite returnValueHandlers; <ide> <add> /** <add> * Variant of {@link #ServletInvocableHandlerMethod(Object, Method)} that <add> * also accepts a {@link MessageSource}. <add> */ <add> public ServletInvocableHandlerMethod(Object handler, Method method, @Nullable MessageSource messageSource) { <add> super(handler, method, messageSource); <add> } <ide> <ide> /** <ide> * Creates an instance from the given handler and method. <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java <ide> import java.io.IOException; <ide> import java.io.UnsupportedEncodingException; <ide> import java.io.Writer; <add>import java.net.SocketTimeoutException; <ide> import java.util.Collections; <add>import java.util.Locale; <ide> <ide> import org.junit.jupiter.api.BeforeAll; <ide> import org.junit.jupiter.api.BeforeEach; <ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <add>import org.springframework.context.i18n.LocaleContextHolder; <add>import org.springframework.context.support.StaticApplicationContext; <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.annotation.Order; <add>import org.springframework.http.HttpStatus; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.http.server.ServerHttpRequest; <ide> import org.springframework.web.HttpRequestHandler; <ide> import org.springframework.web.bind.annotation.ExceptionHandler; <ide> import org.springframework.web.bind.annotation.ResponseBody; <add>import org.springframework.web.bind.annotation.ResponseStatus; <ide> import org.springframework.web.bind.annotation.RestControllerAdvice; <ide> import org.springframework.web.context.support.WebApplicationObjectSupport; <ide> import org.springframework.web.method.HandlerMethod; <ide> void resolveExceptionWithAssertionErrorAsRootCause() throws Exception { <ide> assertThat(this.response.getContentAsString()).isEqualTo(rootCause.toString()); <ide> } <ide> <add> @Test //gh-27156 <add> void resolveExceptionWithReasonResovledByMessageSource() throws Exception { <add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class); <add> StaticApplicationContext context = new StaticApplicationContext(ctx); <add> Locale locale = Locale.ENGLISH; <add> context.addMessage("gateway.timeout", locale, "Gateway Timeout"); <add> context.refresh(); <add> LocaleContextHolder.setLocale(locale); <add> this.resolver.setApplicationContext(context); <add> this.resolver.afterPropertiesSet(); <add> <add> SocketTimeoutException ex = new SocketTimeoutException(); <add> HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle"); <add> ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex); <add> <add> assertThat(mav).as("Exception was not handled").isNotNull(); <add> assertThat(mav.isEmpty()).isTrue(); <add> assertThat(this.response.getStatus()).isEqualTo(HttpStatus.GATEWAY_TIMEOUT.value()); <add> assertThat(this.response.getErrorMessage()).isEqualTo("Gateway Timeout"); <add> assertThat(this.response.getContentAsString()).isEqualTo(""); <add> } <add> <ide> @Test <ide> void resolveExceptionControllerAdviceHandler() throws Exception { <ide> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class); <ide> public String handleException(Exception ex) { <ide> } <ide> } <ide> <add> @RestControllerAdvice <add> @Order(3) <add> static class ResponseStatusTestExceptionResolver { <add> <add> @ExceptionHandler(SocketTimeoutException.class) <add> @ResponseStatus(code = HttpStatus.GATEWAY_TIMEOUT, reason = "gateway.timeout") <add> public void handleException(SocketTimeoutException ex) { <add> <add> } <add> } <ide> <ide> @Configuration <ide> static class MyConfig { <ide> public TestExceptionResolver testExceptionResolver() { <ide> public AnotherTestExceptionResolver anotherTestExceptionResolver() { <ide> return new AnotherTestExceptionResolver(); <ide> } <add> <add> @Bean <add> public ResponseStatusTestExceptionResolver responseStatusTestExceptionResolver() { <add> return new ResponseStatusTestExceptionResolver(); <add> } <ide> } <ide> <ide>
5
PHP
PHP
modify all() to work with nested input arrays
35b6a0f26d66861bc558f548c9fe076fad369a75
<ide><path>src/Illuminate/Http/Request.php <ide> public function has($key) <ide> */ <ide> public function all() <ide> { <del> return $this->input() + $this->files->all(); <add> return array_merge_recursive($this->input(), $this->files->all()); <ide> } <ide> <ide> /** <ide><path>tests/Http/HttpRequestTest.php <ide> public function testAllInputReturnsInputAndFiles() <ide> } <ide> <ide> <add> public function testAllInputReturnsNestedInputAndFiles() <add> { <add> $file = $this->getMock('Symfony\Component\HttpFoundation\File\UploadedFile', null, array(__FILE__, 'photo.jpg')); <add> $request = Request::create('/?boom=breeze', 'GET', array('foo' => array('bar' => 'baz')), array(), array('foo' => array('photo' => $file))); <add> $this->assertEquals(array('foo' => array('bar' => 'baz', 'photo' => $file), 'boom' => 'breeze'), $request->all()); <add> } <add> <add> <ide> public function testOldMethodCallsSession() <ide> { <ide> $request = Request::create('/', 'GET');
2
Java
Java
fix reactscrollview lints
b0319f3293b553c105b813dd12bff7d55940e60b
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java <ide> import android.graphics.Rect; <ide> import android.graphics.drawable.ColorDrawable; <ide> import android.graphics.drawable.Drawable; <add>import android.support.v4.view.ViewCompat; <ide> import android.util.Log; <ide> import android.view.MotionEvent; <ide> import android.view.View; <ide> public void fling(int velocityY) { <ide> 0, <ide> scrollWindowHeight / 2); <ide> <del> postInvalidateOnAnimation(); <add> ViewCompat.postInvalidateOnAnimation(this); <ide> <ide> // END FB SCROLLVIEW CHANGE <ide> } else { <ide> public void run() { <ide> ReactScrollViewHelper.emitScrollMomentumEndEvent(ReactScrollView.this); <ide> } else { <ide> mDoneFlinging = true; <del> ReactScrollView.this.postOnAnimationDelayed(this, ReactScrollViewHelper.MOMENTUM_DELAY); <add> ViewCompat.postOnAnimationDelayed( <add> ReactScrollView.this, <add> this, <add> ReactScrollViewHelper.MOMENTUM_DELAY); <ide> } <ide> } <ide> }; <del> postOnAnimationDelayed(r, ReactScrollViewHelper.MOMENTUM_DELAY); <add> ViewCompat.postOnAnimationDelayed(this, r, ReactScrollViewHelper.MOMENTUM_DELAY); <ide> } <ide> } <ide>
1
Python
Python
update gyp to r1535
38c52a0575fa92a2413fbefb754bfdc7af144b89
<ide><path>tools/gyp/gyptest.py <ide> def main(argv=None): <ide> os.chdir(opts.chdir) <ide> <ide> if opts.path: <del> os.environ['PATH'] += ':' + ':'.join(opts.path) <add> extra_path = [os.path.abspath(p) for p in opts.path] <add> extra_path = os.pathsep.join(extra_path) <add> os.environ['PATH'] += os.pathsep + extra_path <ide> <ide> if not args: <ide> if not opts.all: <ide><path>tools/gyp/pylib/gyp/MSVSNew.py <ide> def MakeGuid(name, seed='msvs_new'): <ide> #------------------------------------------------------------------------------ <ide> <ide> <del>class MSVSFolder(object): <add>class MSVSSolutionEntry(object): <add> def __cmp__(self, other): <add> # Sort by name then guid (so things are in order on vs2008). <add> return cmp((self.name, self.get_guid()), (other.name, other.get_guid())) <add> <add> <add>class MSVSFolder(MSVSSolutionEntry): <ide> """Folder in a Visual Studio project or solution.""" <ide> <ide> def __init__(self, path, name = None, entries = None, <ide> def __init__(self, path, name = None, entries = None, <ide> self.guid = guid <ide> <ide> # Copy passed lists (or set to empty lists) <del> self.entries = list(entries or []) <add> self.entries = sorted(list(entries or [])) <ide> self.items = list(items or []) <ide> <ide> self.entry_type_guid = ENTRY_TYPE_GUIDS['folder'] <ide> def get_guid(self): <ide> #------------------------------------------------------------------------------ <ide> <ide> <del>class MSVSProject(object): <add>class MSVSProject(MSVSSolutionEntry): <ide> """Visual Studio project.""" <ide> <ide> def __init__(self, path, name = None, dependencies = None, guid = None, <ide> def Write(self, writer=gyp.common.WriteOnDiff): <ide> if isinstance(e, MSVSFolder): <ide> entries_to_check += e.entries <ide> <del> # Sort by name then guid (so things are in order on vs2008). <del> def NameThenGuid(a, b): <del> if a.name < b.name: return -1 <del> if a.name > b.name: return 1 <del> if a.get_guid() < b.get_guid(): return -1 <del> if a.get_guid() > b.get_guid(): return 1 <del> return 0 <del> <del> all_entries = sorted(all_entries, NameThenGuid) <add> all_entries = sorted(all_entries) <ide> <ide> # Open file and print header <ide> f = writer(self.path) <ide><path>tools/gyp/pylib/gyp/MSVSVersion.py <ide> import re <ide> import subprocess <ide> import sys <add>import gyp <ide> <ide> <ide> class VisualStudioVersion(object): <ide> def _CreateVersion(name, path, sdk_based=False): <ide> autodetected if GYP_MSVS_VERSION is not explicitly specified. If a version is <ide> passed in that doesn't match a value in versions python will throw a error. <ide> """ <add> if path: <add> path = os.path.normpath(path) <ide> versions = { <ide> '2012': VisualStudioVersion('2012', <ide> 'Visual Studio 2012', <ide> def _CreateVersion(name, path, sdk_based=False): <ide> return versions[str(name)] <ide> <ide> <add>def _ConvertToCygpath(path): <add> """Convert to cygwin path if we are using cygwin.""" <add> if sys.platform == 'cygwin': <add> p = subprocess.Popen(['cygpath', path], stdout=subprocess.PIPE) <add> path = p.communicate()[0].strip() <add> return path <add> <add> <ide> def _DetectVisualStudioVersions(versions_to_check, force_express): <ide> """Collect the list of installed visual studio versions. <ide> <ide> def _DetectVisualStudioVersions(versions_to_check, force_express): <ide> path = _RegistryGetValue(keys[index], 'InstallDir') <ide> if not path: <ide> continue <add> path = _ConvertToCygpath(path) <ide> # Check for full. <ide> full_path = os.path.join(path, 'devenv.exe') <ide> express_path = os.path.join(path, 'vcexpress.exe') <ide> def _DetectVisualStudioVersions(versions_to_check, force_express): <ide> path = _RegistryGetValue(keys[index], version) <ide> if not path: <ide> continue <add> path = _ConvertToCygpath(path) <ide> versions.append(_CreateVersion(version_to_year[version] + 'e', <ide> os.path.join(path, '..'), sdk_based=True)) <ide> <ide><path>tools/gyp/pylib/gyp/__init__.py <ide> import shlex <ide> import sys <ide> import traceback <add>from gyp.common import GypError <ide> <ide> # Default debug modes for GYP <ide> debug = {} <ide> def FindBuildFiles(): <ide> return build_files <ide> <ide> <del>class GypError(Exception): <del> """Error class representing an error, which is to be presented <del> to the user. The main entry point will catch and display this. <del> """ <del> pass <del> <del> <ide> def Load(build_files, format, default_variables={}, <del> includes=[], depth='.', params=None, check=False, circular_check=True): <add> includes=[], depth='.', params=None, check=False, <add> circular_check=True): <ide> """ <ide> Loads one or more specified build files. <ide> default_variables and includes will be copied before use. <ide> def Load(build_files, format, default_variables={}, <ide> <ide> # Process the input specific to this generator. <ide> result = gyp.input.Load(build_files, default_variables, includes[:], <del> depth, generator_input_info, check, circular_check) <add> depth, generator_input_info, check, circular_check, <add> params['parallel']) <ide> return [generator] + result <ide> <ide> def NameValueListToDict(name_value_list): <ide> def gyp_main(args): <ide> help='do not read options from environment variables') <ide> parser.add_option('--check', dest='check', action='store_true', <ide> help='check format of gyp files') <add> parser.add_option('--parallel', action='store_true', <add> env_name='GYP_PARALLEL', <add> help='Use multiprocessing for speed (experimental)') <ide> parser.add_option('--toplevel-dir', dest='toplevel_dir', action='store', <ide> default=None, metavar='DIR', type='path', <ide> help='directory to use as the root of the source tree') <add> parser.add_option('--build', dest='configs', action='append', <add> help='configuration for build after project generation') <ide> # --no-circular-check disables the check for circular relationships between <ide> # .gyp files. These relationships should not exist, but they've only been <ide> # observed to be harmful with the Xcode generator. Chromium's .gyp files <ide> def gyp_main(args): <ide> if g_o: <ide> options.generator_output = g_o <ide> <add> if not options.parallel and options.use_environment: <add> options.parallel = bool(os.environ.get('GYP_PARALLEL')) <add> <ide> for mode in options.debug: <ide> gyp.debug[mode] = 1 <ide> <ide> def gyp_main(args): <ide> 'cwd': os.getcwd(), <ide> 'build_files_arg': build_files_arg, <ide> 'gyp_binary': sys.argv[0], <del> 'home_dot_gyp': home_dot_gyp} <add> 'home_dot_gyp': home_dot_gyp, <add> 'parallel': options.parallel} <ide> <ide> # Start with the default variables from the command line. <ide> [generator, flat_list, targets, data] = Load(build_files, format, <ide> def gyp_main(args): <ide> # generate targets in the order specified in flat_list. <ide> generator.GenerateOutput(flat_list, targets, data, params) <ide> <add> if options.configs: <add> valid_configs = targets[flat_list[0]]['configurations'].keys() <add> for conf in options.configs: <add> if conf not in valid_configs: <add> raise GypError('Invalid config specified via --build: %s' % conf) <add> generator.PerformBuild(data, options.configs, params) <add> <ide> # Done <ide> return 0 <ide> <ide><path>tools/gyp/pylib/gyp/common.py <ide> def __call__(self, *args): <ide> return result <ide> <ide> <add>class GypError(Exception): <add> """Error class representing an error, which is to be presented <add> to the user. The main entry point will catch and display this. <add> """ <add> pass <add> <add> <ide> def ExceptionAppend(e, msg): <ide> """Append a message to the given exception's message.""" <ide> if not e.args: <ide> def GetFlavor(params): <ide> 'cygwin': 'win', <ide> 'win32': 'win', <ide> 'darwin': 'mac', <del> 'sunos5': 'solaris', <del> 'freebsd7': 'freebsd', <del> 'freebsd8': 'freebsd', <del> 'freebsd9': 'freebsd', <ide> } <del> flavor = flavors.get(sys.platform, 'linux') <del> return params.get('flavor', flavor) <add> <add> if 'flavor' in params: <add> return params['flavor'] <add> if sys.platform in flavors: <add> return flavors[sys.platform] <add> if sys.platform.startswith('sunos'): <add> return 'solaris' <add> if sys.platform.startswith('freebsd'): <add> return 'freebsd' <add> if sys.platform.startswith('dragonfly'): <add> return 'dragonflybsd' <add> <add> return 'linux' <ide> <ide> <ide> def CopyTool(flavor, out_path): <ide><path>tools/gyp/pylib/gyp/common_test.py <ide> <ide> import gyp.common <ide> import unittest <add>import sys <ide> <ide> <ide> class TestTopologicallySorted(unittest.TestCase): <ide> def GetEdge(node): <ide> graph.keys(), GetEdge) <ide> <ide> <add>class TestGetFlavor(unittest.TestCase): <add> """Test that gyp.common.GetFlavor works as intended""" <add> original_platform = '' <add> <add> def setUp(self): <add> self.original_platform = sys.platform <add> <add> def tearDown(self): <add> sys.platform = self.original_platform <add> <add> def assertFlavor(self, expected, argument, param): <add> sys.platform = argument <add> self.assertEqual(expected, gyp.common.GetFlavor(param)) <add> <add> def test_platform_default(self): <add> self.assertFlavor('dragonflybsd', 'dragonfly3', {}) <add> self.assertFlavor('freebsd' , 'freebsd9' , {}) <add> self.assertFlavor('freebsd' , 'freebsd10' , {}) <add> self.assertFlavor('solaris' , 'sunos5' , {}); <add> self.assertFlavor('solaris' , 'sunos' , {}); <add> self.assertFlavor('linux' , 'linux2' , {}); <add> self.assertFlavor('linux' , 'linux3' , {}); <add> <add> def test_param(self): <add> self.assertFlavor('foobar', 'linux2' , {'flavor': 'foobar'}) <add> <add> <ide> if __name__ == '__main__': <ide> unittest.main() <ide><path>tools/gyp/pylib/gyp/generator/android.py <ide> 'RULE_INPUT_PATH': '$(RULE_SOURCES)', <ide> 'RULE_INPUT_EXT': '$(suffix $<)', <ide> 'RULE_INPUT_NAME': '$(notdir $<)', <add> 'CONFIGURATION_NAME': 'NOT_USED_ON_ANDROID', <ide> } <ide> <ide> # Make supports multiple toolsets <ide> generator_supports_multiple_toolsets = True <ide> <ide> <add># Generator-specific gyp specs. <add>generator_additional_non_configuration_keys = [ <add> # Boolean to declare that this target does not want its name mangled. <add> 'android_unmangled_name', <add>] <add>generator_additional_path_sections = [] <add>generator_extra_sources_for_rules = [] <add> <add> <ide> SHARED_FOOTER = """\ <ide> # "gyp_all_modules" is a concatenation of the "gyp_all_modules" targets from <ide> # all the included sub-makefiles. This is just here to clarify. <ide> def Write(self, qualified_target, base_path, output_filename, spec, configs, <ide> extra_outputs = [] <ide> extra_sources = [] <ide> <del> self.android_class = MODULE_CLASSES.get(self.type, 'NONE') <add> self.android_class = MODULE_CLASSES.get(self.type, 'GYP') <ide> self.android_module = self.ComputeAndroidModule(spec) <ide> (self.android_stem, self.android_suffix) = self.ComputeOutputParts(spec) <ide> self.output = self.output_binary = self.ComputeOutput(spec) <ide> def ComputeAndroidModule(self, spec): <ide> distinguish gyp-generated module names. <ide> """ <ide> <add> if int(spec.get('android_unmangled_name', 0)): <add> assert self.type != 'shared_library' or self.target.startswith('lib') <add> return self.target <add> <ide> if self.type == 'shared_library': <ide> # For reasons of convention, the Android build system requires that all <ide> # shared library modules are named 'libfoo' when generating -l flags. <ide> def WriteTarget(self, spec, configs, deps, link_deps, part_of_all): <ide> # Add an alias from the gyp target name to the Android module name. This <ide> # simplifies manual builds of the target, and is required by the test <ide> # framework. <del> self.WriteLn('# Alias gyp target name.') <del> self.WriteLn('.PHONY: %s' % self.target) <del> self.WriteLn('%s: %s' % (self.target, self.android_module)) <del> self.WriteLn('') <add> if self.target != self.android_module: <add> self.WriteLn('# Alias gyp target name.') <add> self.WriteLn('.PHONY: %s' % self.target) <add> self.WriteLn('%s: %s' % (self.target, self.android_module)) <add> self.WriteLn('') <ide> <ide> # Add the command to trigger build of the target type depending <ide> # on the toolset. Ex: BUILD_STATIC_LIBRARY vs. BUILD_HOST_STATIC_LIBRARY <ide> def CalculateMakefilePath(build_file, base_name): <ide> default_configuration = 'Default' <ide> <ide> srcdir = '.' <del> makefile_name = 'GypAndroid.mk' + options.suffix <add> makefile_name = 'GypAndroid' + options.suffix + '.mk' <ide> makefile_path = os.path.join(options.toplevel_dir, makefile_name) <ide> assert not options.generator_output, ( <ide> 'The Android backend does not support options.generator_output.') <ide><path>tools/gyp/pylib/gyp/generator/dump_dependency_json.py <del># Copyright (c) 2011 Google Inc. All rights reserved. <add># Copyright (c) 2012 Google Inc. All rights reserved. <ide> # Use of this source code is governed by a BSD-style license that can be <ide> # found in the LICENSE file. <ide> <ide> import collections <add>import os <ide> import gyp <ide> import gyp.common <add>import gyp.msvs_emulation <ide> import json <ide> import sys <ide> <ide> 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', <ide> 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', <ide> 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', <del> 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX']: <add> 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', <add> 'CONFIGURATION_NAME']: <ide> generator_default_variables[unused] = '' <ide> <ide> <ide> def CalculateVariables(default_variables, params): <ide> default_variables.setdefault(key, val) <ide> default_variables.setdefault('OS', gyp.common.GetFlavor(params)) <ide> <add> flavor = gyp.common.GetFlavor(params) <add> if flavor =='win': <add> # Copy additional generator configuration data from VS, which is shared <add> # by the Windows Ninja generator. <add> import gyp.generator.msvs as msvs_generator <add> generator_additional_non_configuration_keys = getattr(msvs_generator, <add> 'generator_additional_non_configuration_keys', []) <add> generator_additional_path_sections = getattr(msvs_generator, <add> 'generator_additional_path_sections', []) <add> <add> # Set a variable so conditions can be based on msvs_version. <add> msvs_version = gyp.msvs_emulation.GetVSVersion(generator_flags) <add> default_variables['MSVS_VERSION'] = msvs_version.ShortName() <add> <add> # To determine processor word size on Windows, in addition to checking <add> # PROCESSOR_ARCHITECTURE (which reflects the word size of the current <add> # process), it is also necessary to check PROCESSOR_ARCHITEW6432 (which <add> # contains the actual word size of the system when running thru WOW64). <add> if ('64' in os.environ.get('PROCESSOR_ARCHITECTURE', '') or <add> '64' in os.environ.get('PROCESSOR_ARCHITEW6432', '')): <add> default_variables['MSVS_OS_BITS'] = 64 <add> else: <add> default_variables['MSVS_OS_BITS'] = 32 <add> <ide> <ide> def CalculateGeneratorInputInfo(params): <ide> """Calculate the generator specific info that gets fed to input (called by <ide><path>tools/gyp/pylib/gyp/generator/make.py <ide> import os <ide> import re <ide> import sys <add>import subprocess <ide> import gyp <ide> import gyp.common <del>import gyp.system_test <ide> import gyp.xcode_emulation <ide> from gyp.common import GetEnvironFallback <ide> <ide> def ensure_directory_exists(path): <ide> <ide> LINK_COMMANDS_LINUX = """\ <ide> quiet_cmd_alink = AR($(TOOLSET)) $@ <del>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) $(ARFLAGS.$(TOOLSET)) $@ $(filter %.o,$^) <add>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) <add> <add>quiet_cmd_alink_thin = AR($(TOOLSET)) $@ <add>cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) <ide> <ide> # Due to circular dependencies between libraries :(, we wrap the <ide> # special "figure out circular dependencies" flags around the entire <ide> def ensure_directory_exists(path): <ide> <ide> LINK_COMMANDS_MAC = """\ <ide> quiet_cmd_alink = LIBTOOL-STATIC $@ <del>cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool -static -o $@ $(filter %.o,$^) <add>cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) <ide> <ide> quiet_cmd_link = LINK($(TOOLSET)) $@ <ide> cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) <ide> def ensure_directory_exists(path): <ide> <ide> LINK_COMMANDS_ANDROID = """\ <ide> quiet_cmd_alink = AR($(TOOLSET)) $@ <del>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) $(ARFLAGS.$(TOOLSET)) $@ $(filter %.o,$^) <add>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) <add> <add>quiet_cmd_alink_thin = AR($(TOOLSET)) $@ <add>cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) <ide> <ide> # Due to circular dependencies between libraries :(, we wrap the <ide> # special "figure out circular dependencies" flags around the entire <ide> def ensure_directory_exists(path): <ide> LINK.target ?= %(LINK.target)s <ide> LDFLAGS.target ?= $(LDFLAGS) <ide> AR.target ?= $(AR) <del>ARFLAGS.target ?= %(ARFLAGS.target)s <ide> <del># N.B.: the logic of which commands to run should match the computation done <del># in gyp's make.py where ARFLAGS.host etc. is computed. <ide> # TODO(evan): move all cross-compilation logic to gyp-time so we don't need <ide> # to replicate this environment fallback in make as well. <ide> CC.host ?= %(CC.host)s <ide> def ensure_directory_exists(path): <ide> LINK.host ?= %(LINK.host)s <ide> LDFLAGS.host ?= <ide> AR.host ?= %(AR.host)s <del>ARFLAGS.host := %(ARFLAGS.host)s <ide> <ide> # Define a dir function that can handle spaces. <ide> # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions <ide> def Write(self, qualified_target, base_path, output_filename, spec, configs, <ide> else: <ide> self.output = self.output_binary = self.ComputeOutput(spec) <ide> <add> self.is_standalone_static_library = bool( <add> spec.get('standalone_static_library', 0)) <ide> self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', <ide> 'shared_library') <del> if self.type in self._INSTALLABLE_TARGETS: <add> if (self.is_standalone_static_library or <add> self.type in self._INSTALLABLE_TARGETS): <ide> self.alias = os.path.basename(self.output) <ide> install_path = self._InstallableTargetInstallPath() <ide> else: <ide> def WriteActions(self, actions, extra_sources, extra_outputs, <ide> actions) <ide> part_of_all: flag indicating this target is part of 'all' <ide> """ <add> env = self.GetSortedXcodeEnv() <ide> for action in actions: <ide> name = StringToMakefileVariable('%s_%s' % (self.qualified_target, <ide> action['action_name'])) <ide> def WriteActions(self, actions, extra_sources, extra_outputs, <ide> extra_mac_bundle_resources += outputs <ide> <ide> # Write the actual command. <del> command = gyp.common.EncodePOSIXShellList(action['action']) <add> action_commands = action['action'] <add> if self.flavor == 'mac': <add> action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env) <add> for command in action_commands] <add> command = gyp.common.EncodePOSIXShellList(action_commands) <ide> if 'message' in action: <ide> self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) <ide> else: <ide> def WriteActions(self, actions, extra_sources, extra_outputs, <ide> "Spaces in action output filenames not supported (%s)" % output) <ide> <ide> # See the comment in WriteCopies about expanding env vars. <del> env = self.GetSortedXcodeEnv() <ide> outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] <ide> inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] <ide> <ide> def WriteRules(self, rules, extra_sources, extra_outputs, <ide> rules (used to make other pieces dependent on these rules) <ide> part_of_all: flag indicating this target is part of 'all' <ide> """ <add> env = self.GetSortedXcodeEnv() <ide> for rule in rules: <ide> name = StringToMakefileVariable('%s_%s' % (self.qualified_target, <ide> rule['rule_name'])) <ide> def WriteRules(self, rules, extra_sources, extra_outputs, <ide> # amount of pain. <ide> actions += ['@touch --no-create $@'] <ide> <add> # See the comment in WriteCopies about expanding env vars. <add> outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] <add> inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] <add> <ide> outputs = map(self.Absolutify, outputs) <ide> all_outputs += outputs <ide> # Only write the 'obj' and 'builddir' rules for the "primary" output <ide> def WriteRules(self, rules, extra_sources, extra_outputs, <ide> # action, cd_action, and mkdirs get written to a toplevel variable <ide> # called cmd_foo. Toplevel variables can't handle things that change <ide> # per makefile like $(TARGET), so hardcode the target. <add> if self.flavor == 'mac': <add> action = [gyp.xcode_emulation.ExpandEnvVars(command, env) <add> for command in action] <ide> action = gyp.common.EncodePOSIXShellList(action) <ide> action = action.replace('$(TARGET)', self.target) <ide> cd_action = cd_action.replace('$(TARGET)', self.target) <ide> def WriteCopies(self, copies, extra_outputs, part_of_all): <ide> outputs = [] <ide> for copy in copies: <ide> for path in copy['files']: <del> # Absolutify() calls normpath, stripping trailing slashes. <add> # Absolutify() may call normpath, and will strip trailing slashes. <ide> path = Sourceify(self.Absolutify(path)) <ide> filename = os.path.split(path)[1] <ide> output = Sourceify(self.Absolutify(os.path.join(copy['destination'], <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % <ide> self.toolset) <ide> self.WriteList(ldflags, 'LDFLAGS_%s' % configname) <add> if self.flavor == 'mac': <add> self.WriteList(self.xcode_settings.GetLibtoolflags(configname), <add> 'LIBTOOLFLAGS_%s' % configname) <ide> libraries = spec.get('libraries') <ide> if libraries: <ide> # Remove duplicate entries <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> QuoteSpaces(self.output_binary)) <ide> self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) <ide> <add> if self.flavor == 'mac': <add> self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % <add> QuoteSpaces(self.output_binary)) <add> <ide> # Postbuild actions. Like actions, but implicitly depend on the target's <ide> # output. <ide> postbuilds = [] <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> for link_dep in link_deps: <ide> assert ' ' not in link_dep, ( <ide> "Spaces in alink input filenames not supported (%s)" % link_dep) <del> self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, <del> postbuilds=postbuilds) <add> if (self.flavor not in ('mac', 'win') and not <add> self.is_standalone_static_library): <add> self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', <add> part_of_all, postbuilds=postbuilds) <add> else: <add> self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, <add> postbuilds=postbuilds) <ide> elif self.type == 'shared_library': <ide> self.WriteLn('%s: LD_INPUTS := %s' % ( <ide> QuoteSpaces(self.output_binary), <ide> def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, <ide> # 1) They need to install to the build dir or "product" dir. <ide> # 2) They get shortcuts for building (e.g. "make chrome"). <ide> # 3) They are part of "make all". <del> if self.type in self._INSTALLABLE_TARGETS: <add> if (self.type in self._INSTALLABLE_TARGETS or <add> self.is_standalone_static_library): <ide> if self.type == 'shared_library': <ide> file_desc = 'shared library' <add> elif self.type == 'static_library': <add> file_desc = 'static library' <ide> else: <ide> file_desc = 'executable' <ide> install_path = self._InstallableTargetInstallPath() <ide> def Absolutify(self, path): <ide> """Convert a subdirectory-relative path into a base-relative path. <ide> Skips over paths that contain variables.""" <ide> if '$(' in path: <del> # path is no existing file in this case, but calling normpath is still <del> # important for trimming trailing slashes. <del> return os.path.normpath(path) <add> # Don't call normpath in this case, as it might collapse the <add> # path too aggressively if it features '..'. However it's still <add> # important to strip trailing slashes. <add> return path.rstrip('/') <ide> return os.path.normpath(os.path.join(self.path, path)) <ide> <ide> <ide> def WriteAutoRegenerationRule(params, root_makefile, makefile_name, <ide> build_files_args)}) <ide> <ide> <del>def RunSystemTests(flavor): <del> """Run tests against the system to compute default settings for commands. <del> <del> Returns: <del> dictionary of settings matching the block of command-lines used in <del> SHARED_HEADER. E.g. the dictionary will contain a ARFLAGS.target <del> key for the default ARFLAGS for the target ar command. <del> """ <del> # Compute flags used for building static archives. <del> # N.B.: this fallback logic should match the logic in SHARED_HEADER. <del> # See comment there for more details. <del> ar_target = GetEnvironFallback(('AR_target', 'AR'), 'ar') <del> cc_target = GetEnvironFallback(('CC_target', 'CC'), 'cc') <del> arflags_target = 'crs' <del> # ar -T enables thin archives on Linux. OS X's ar supports a -T flag, but it <del> # does something useless (it limits filenames in the archive to 15 chars). <del> if flavor != 'mac' and gyp.system_test.TestArSupportsT(ar_command=ar_target, <del> cc_command=cc_target): <del> arflags_target = 'crsT' <del> <del> ar_host = os.environ.get('AR_host', 'ar') <del> cc_host = os.environ.get('CC_host', 'gcc') <del> arflags_host = 'crs' <del> # It feels redundant to compute this again given that most builds aren't <del> # cross-compiles, but due to quirks of history CC_host defaults to 'gcc' <del> # while CC_target defaults to 'cc', so the commands really are different <del> # even though they're nearly guaranteed to run the same code underneath. <del> if flavor != 'mac' and gyp.system_test.TestArSupportsT(ar_command=ar_host, <del> cc_command=cc_host): <del> arflags_host = 'crsT' <del> <del> return { 'ARFLAGS.target': arflags_target, <del> 'ARFLAGS.host': arflags_host } <add>def PerformBuild(data, configurations, params): <add> options = params['options'] <add> for config in configurations: <add> arguments = ['make'] <add> if options.toplevel_dir and options.toplevel_dir != '.': <add> arguments += '-C', options.toplevel_dir <add> arguments.append('BUILDTYPE=' + config) <add> print 'Building [%s]: %s' % (config, arguments) <add> subprocess.check_call(arguments) <ide> <ide> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> def CalculateMakefilePath(build_file, base_name): <ide> 'flock_index': 2, <ide> 'extra_commands': SHARED_HEADER_SUN_COMMANDS, <ide> }) <del> elif flavor == 'freebsd': <add> elif flavor == 'freebsd' or flavor == 'dragonflybsd': <ide> header_params.update({ <ide> 'flock': 'lockf', <ide> }) <ide> <del> header_params.update(RunSystemTests(flavor)) <ide> header_params.update({ <ide> 'CC.target': GetEnvironFallback(('CC_target', 'CC'), '$(CC)'), <ide> 'AR.target': GetEnvironFallback(('AR_target', 'AR'), '$(AR)'), <ide><path>tools/gyp/pylib/gyp/generator/msvs.py <ide> import gyp.MSVSToolFile as MSVSToolFile <ide> import gyp.MSVSUserFile as MSVSUserFile <ide> import gyp.MSVSVersion as MSVSVersion <add>from gyp.common import GypError <ide> <ide> <ide> # Regular expression for validating Visual Studio GUIDs. If the GUID <ide> def _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config): <ide> # Get the information for this configuration <ide> include_dirs, resource_include_dirs = _GetIncludeDirs(config) <ide> libraries = _GetLibraries(spec) <del> out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec) <add> out_file, vc_tool, _ = _GetOutputFilePathAndTool(spec, msbuild=False) <ide> defines = _GetDefines(config) <ide> defines = [_EscapeCppDefineForMSVS(d) for d in defines] <ide> disabled_warnings = _GetDisabledWarnings(config) <ide> def _GetLibraries(spec): <ide> unique_libraries_list = [] <ide> for entry in reversed(libraries): <ide> library = re.sub('^\-l', '', entry) <add> if not os.path.splitext(library)[1]: <add> library += '.lib' <ide> if library not in found: <ide> found.add(library) <ide> unique_libraries_list.append(library) <ide> unique_libraries_list.reverse() <ide> return unique_libraries_list <ide> <ide> <del>def _GetOutputFilePathAndTool(spec): <add>def _GetOutputFilePathAndTool(spec, msbuild): <ide> """Returns the path and tool to use for this target. <ide> <ide> Figures out the path of the file this spec will create and the name of <ide> def _GetOutputFilePathAndTool(spec): <ide> output_file_props = output_file_map.get(spec['type']) <ide> if output_file_props and int(spec.get('msvs_auto_output_file', 1)): <ide> vc_tool, msbuild_tool, out_dir, suffix = output_file_props <add> if spec.get('standalone_static_library', 0): <add> out_dir = '$(OutDir)' <ide> out_dir = spec.get('product_dir', out_dir) <ide> product_extension = spec.get('product_extension') <ide> if product_extension: <ide> suffix = '.' + product_extension <add> elif msbuild: <add> suffix = '$(TargetExt)' <ide> prefix = spec.get('product_prefix', '') <ide> product_name = spec.get('product_name', '$(ProjectName)') <ide> out_file = ntpath.join(out_dir, prefix + product_name + suffix) <ide> def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): <ide> build_file = gyp.common.BuildFile(qualified_target) <ide> # Create object for this project. <ide> obj = MSVSNew.MSVSProject( <del> _FixPath(proj_path), <add> proj_path, <ide> name=spec['target_name'], <ide> guid=guid, <ide> spec=spec, <ide> def _ShardTargets(target_list, target_dicts): <ide> return (new_target_list, new_target_dicts) <ide> <ide> <add>def PerformBuild(data, configurations, params): <add> options = params['options'] <add> msvs_version = params['msvs_version'] <add> devenv = os.path.join(msvs_version.path, 'Common7', 'IDE', 'devenv.com') <add> <add> for build_file, build_file_dict in data.iteritems(): <add> (build_file_root, build_file_ext) = os.path.splitext(build_file) <add> if build_file_ext != '.gyp': <add> continue <add> sln_path = build_file_root + options.suffix + '.sln' <add> if options.generator_output: <add> sln_path = os.path.join(options.generator_output, sln_path) <add> <add> for config in configurations: <add> arguments = [devenv, sln_path, '/Build', config] <add> print 'Building [%s]: %s' % (config, arguments) <add> rtn = subprocess.check_call(arguments) <add> <add> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> """Generate .sln and .vcproj files. <ide> <ide> def _GetMSBuildAttributes(spec, config, build_file): <ide> config_type = _GetMSVSConfigurationType(spec, build_file) <ide> config_type = _ConvertMSVSConfigurationType(config_type) <ide> msbuild_attributes = config.get('msbuild_configuration_attributes', {}) <del> msbuild_attributes['ConfigurationType'] = config_type <add> msbuild_attributes.setdefault('ConfigurationType', config_type) <ide> output_dir = msbuild_attributes.get('OutputDirectory', <del> '$(SolutionDir)$(Configuration)\\') <del> msbuild_attributes['OutputDirectory'] = _FixPath(output_dir) <add> '$(SolutionDir)$(Configuration)') <add> msbuild_attributes['OutputDirectory'] = _FixPath(output_dir) + '\\' <ide> if 'IntermediateDirectory' not in msbuild_attributes: <del> intermediate = '$(Configuration)\\' <del> msbuild_attributes['IntermediateDirectory'] = _FixPath(intermediate) <add> intermediate = _FixPath('$(Configuration)') + '\\' <add> msbuild_attributes['IntermediateDirectory'] = intermediate <ide> if 'CharacterSet' in msbuild_attributes: <ide> msbuild_attributes['CharacterSet'] = _ConvertMSVSCharacterSet( <ide> msbuild_attributes['CharacterSet']) <ide> def _FinalizeMSBuildSettings(spec, configuration): <ide> msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(msvs_settings) <ide> include_dirs, resource_include_dirs = _GetIncludeDirs(configuration) <ide> libraries = _GetLibraries(spec) <del> out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec) <add> out_file, _, msbuild_tool = _GetOutputFilePathAndTool(spec, msbuild=True) <ide> defines = _GetDefines(configuration) <ide> if converted: <ide> # Visual Studio 2010 has TR1 <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> extension_to_rule_name) <ide> missing_sources = _VerifySourcesExist(sources, project_dir) <ide> <del> for (_, configuration) in configurations.iteritems(): <add> for configuration in configurations.itervalues(): <ide> _FinalizeMSBuildSettings(spec, configuration) <ide> <ide> # Add attributes to root element <ide><path>tools/gyp/pylib/gyp/generator/msvs_test.py <ide> #!/usr/bin/env python <del> <del># Copyright (c) 2011 Google Inc. All rights reserved. <add># Copyright (c) 2012 Google Inc. All rights reserved. <ide> # Use of this source code is governed by a BSD-style license that can be <ide> # found in the LICENSE file. <ide> <ide> def test_GetLibraries(self): <ide> self.assertEqual( <ide> msvs._GetLibraries({'other':'foo', 'libraries': ['a.lib']}), <ide> ['a.lib']) <add> self.assertEqual( <add> msvs._GetLibraries({'libraries': ['-la']}), <add> ['a.lib']) <ide> self.assertEqual( <ide> msvs._GetLibraries({'libraries': ['a.lib', 'b.lib', 'c.lib', '-lb.lib', <ide> '-lb.lib', 'd.lib', 'a.lib']}), <ide><path>tools/gyp/pylib/gyp/generator/ninja.py <ide> <ide> import copy <ide> import hashlib <add>import multiprocessing <ide> import os.path <ide> import re <add>import signal <ide> import subprocess <ide> import sys <ide> import gyp <ide> import gyp.common <ide> import gyp.msvs_emulation <ide> import gyp.MSVSVersion <del>import gyp.system_test <ide> import gyp.xcode_emulation <ide> <ide> from gyp.common import GetEnvironFallback <ide> def WriteCollapsedDependencies(self, name, targets): <ide> self.ninja.newline() <ide> return targets[0] <ide> <del> def WriteSpec(self, spec, config_name, generator_flags): <add> def WriteSpec(self, spec, config_name, generator_flags, <add> case_sensitive_filesystem): <ide> """The main entry point for NinjaWriter: write the build rules for a spec. <ide> <ide> Returns a Target object, which represents the output paths for this spec. <ide> def WriteSpec(self, spec, config_name, generator_flags): <ide> self.toolset = spec['toolset'] <ide> config = spec['configurations'][config_name] <ide> self.target = Target(spec['type']) <add> self.is_standalone_static_library = bool( <add> spec.get('standalone_static_library', 0)) <ide> <ide> self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) <ide> self.xcode_settings = self.msvs_settings = None <ide> def WriteSpec(self, spec, config_name, generator_flags): <ide> if self.flavor == 'win': <ide> self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, <ide> generator_flags) <del> target_platform = self.msvs_settings.GetTargetPlatform(config_name) <del> self.ninja.variable('arch', self.win_env[target_platform]) <add> arch = self.msvs_settings.GetArch(config_name) <add> self.ninja.variable('arch', self.win_env[arch]) <ide> <ide> # Compute predepends for all rules. <ide> # actions_depends is the dependencies this target depends on before running <ide> def WriteSpec(self, spec, config_name, generator_flags): <ide> if sources: <ide> pch = None <ide> if self.flavor == 'win': <add> gyp.msvs_emulation.VerifyMissingSources( <add> sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) <ide> pch = gyp.msvs_emulation.PrecompiledHeader( <ide> self.msvs_settings, config_name, self.GypPathToNinja) <ide> else: <ide> pch = gyp.xcode_emulation.MacPrefixHeader( <ide> self.xcode_settings, self.GypPathToNinja, <ide> lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) <ide> link_deps = self.WriteSources( <del> config_name, config, sources, compile_depends_stamp, pch) <add> config_name, config, sources, compile_depends_stamp, pch, <add> case_sensitive_filesystem, spec) <ide> # Some actions/rules output 'sources' that are already object files. <ide> link_deps += [self.GypPathToNinja(f) <ide> for f in sources if f.endswith(self.obj_ext)] <ide> def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, <ide> outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, <ide> extra_mac_bundle_resources) <ide> if 'copies' in spec: <del> outputs += self.WriteCopies(spec['copies'], prebuild) <add> outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) <ide> <ide> if 'sources' in spec and self.flavor == 'win': <ide> outputs += self.WriteWinIdlFiles(spec, prebuild) <ide> def WriteActions(self, actions, extra_sources, prebuild, <ide> is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(action) <ide> if self.flavor == 'win' else False) <ide> args = action['action'] <del> args = [self.msvs_settings.ConvertVSMacros( <del> arg, self.base_to_build, config=self.config_name) <del> for arg in args] if self.flavor == 'win' else args <del> rule_name = self.WriteNewNinjaRule(name, args, description, <del> is_cygwin, env=env) <add> rule_name, _ = self.WriteNewNinjaRule(name, args, description, <add> is_cygwin, env=env) <ide> <ide> inputs = [self.GypPathToNinja(i, env) for i in action['inputs']] <ide> if int(action.get('process_outputs_as_sources', False)): <ide> def WriteActions(self, actions, extra_sources, prebuild, <ide> <ide> def WriteRules(self, rules, extra_sources, prebuild, <ide> extra_mac_bundle_resources): <add> env = self.GetSortedXcodeEnv() <ide> all_outputs = [] <ide> for rule in rules: <ide> # First write out a rule for the rule action. <ide> def WriteRules(self, rules, extra_sources, prebuild, <ide> ('%s ' + generator_default_variables['RULE_INPUT_PATH']) % name) <ide> is_cygwin = (self.msvs_settings.IsRuleRunUnderCygwin(rule) <ide> if self.flavor == 'win' else False) <del> args = [self.msvs_settings.ConvertVSMacros( <del> arg, self.base_to_build, config=self.config_name) <del> for arg in args] if self.flavor == 'win' else args <del> rule_name = self.WriteNewNinjaRule(name, args, description, is_cygwin) <add> rule_name, args = self.WriteNewNinjaRule( <add> name, args, description, is_cygwin, env=env) <ide> <ide> # TODO: if the command references the outputs directly, we should <ide> # simplify it to just use $out. <ide> def cygwin_munge(path): <ide> else: <ide> assert var == None, repr(var) <ide> <del> inputs = map(self.GypPathToNinja, inputs) <del> outputs = map(self.GypPathToNinja, outputs) <add> inputs = [self.GypPathToNinja(i, env) for i in inputs] <add> outputs = [self.GypPathToNinja(o, env) for o in outputs] <ide> extra_bindings.append(('unique_name', <del> re.sub('[^a-zA-Z0-9_]', '_', outputs[0]))) <add> hashlib.md5(outputs[0]).hexdigest())) <ide> self.ninja.build(outputs, rule_name, self.GypPathToNinja(source), <ide> implicit=inputs, <ide> order_only=prebuild, <ide> def cygwin_munge(path): <ide> <ide> return all_outputs <ide> <del> def WriteCopies(self, copies, prebuild): <add> def WriteCopies(self, copies, prebuild, mac_bundle_depends): <ide> outputs = [] <ide> env = self.GetSortedXcodeEnv() <ide> for copy in copies: <ide> def WriteCopies(self, copies, prebuild): <ide> dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), <ide> env) <ide> outputs += self.ninja.build(dst, 'copy', src, order_only=prebuild) <add> if self.is_mac_bundle: <add> # gyp has mac_bundle_resources to copy things into a bundle's <add> # Resources folder, but there's no built-in way to copy files to other <add> # places in the bundle. Hence, some targets use copies for this. Check <add> # if this file is copied into the current bundle, and if so add it to <add> # the bundle depends so that dependent targets get rebuilt if the copy <add> # input changes. <add> if dst.startswith(self.xcode_settings.GetBundleContentsFolderPath()): <add> mac_bundle_depends.append(dst) <ide> <ide> return outputs <ide> <ide> def WriteMacInfoPlist(self, bundle_depends): <ide> bundle_depends.append(out) <ide> <ide> def WriteSources(self, config_name, config, sources, predepends, <del> precompiled_header): <add> precompiled_header, case_sensitive_filesystem, spec): <ide> """Write build rules to compile all of |sources|.""" <ide> if self.toolset == 'host': <ide> self.ninja.variable('ar', '$ar_host') <ide> def WriteSources(self, config_name, config, sources, predepends, <ide> obj_ext = self.obj_ext <ide> if ext in ('cc', 'cpp', 'cxx'): <ide> command = 'cxx' <del> elif ext == 'c' or (ext in ('s', 'S') and self.flavor != 'win'): <add> elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): <ide> command = 'cc' <add> elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. <add> command = 'cc_s' <ide> elif (self.flavor == 'win' and ext == 'asm' and <del> self.msvs_settings.GetTargetPlatform(config_name) == 'Win32'): <add> self.msvs_settings.GetArch(config_name) == 'x86' and <add> not self.msvs_settings.HasExplicitAsmRules(spec)): <ide> # Asm files only get auto assembled for x86 (not x64). <ide> command = 'asm' <ide> # Add the _asm suffix as msvs is capable of handling .cc and <ide> def WriteSources(self, config_name, config, sources, predepends, <ide> continue <ide> input = self.GypPathToNinja(source) <ide> output = self.GypPathToUniqueOutput(filename + obj_ext) <add> # Ninja's depfile handling gets confused when the case of a filename <add> # changes on a case-insensitive file system. To work around that, always <add> # convert .o filenames to lowercase on such file systems. See <add> # https://github.com/martine/ninja/issues/402 for details. <add> if not case_sensitive_filesystem: <add> output = output.lower() <ide> implicit = precompiled_header.GetObjDependencies([input], [output]) <ide> self.ninja.build(output, command, input, <ide> implicit=[gch for _, _, gch in implicit], <ide> def WriteLink(self, spec, config_name, config, link_deps): <ide> extra_bindings.append(('lib', <ide> gyp.common.EncodePOSIXShellArgument(output))) <ide> if self.flavor == 'win': <del> self.target.import_lib = output + '.lib' <ide> extra_bindings.append(('dll', output)) <del> extra_bindings.append(('implib', self.target.import_lib)) <del> output = [output, self.target.import_lib] <add> if '/NOENTRY' not in ldflags: <add> self.target.import_lib = output + '.lib' <add> extra_bindings.append(('implibflag', <add> '/IMPLIB:%s' % self.target.import_lib)) <add> output = [output, self.target.import_lib] <ide> else: <ide> output = [output, output + '.TOC'] <ide> <ide> def WriteTarget(self, spec, config_name, config, link_deps, compile_deps): <ide> self.target.binary = compile_deps <ide> elif spec['type'] == 'static_library': <ide> self.target.binary = self.ComputeOutput(spec) <del> self.ninja.build(self.target.binary, 'alink', link_deps, <del> order_only=compile_deps, <del> variables=[('postbuilds', self.GetPostbuildCommand( <del> spec, self.target.binary, self.target.binary))]) <add> variables = [] <add> postbuild = self.GetPostbuildCommand( <add> spec, self.target.binary, self.target.binary) <add> if postbuild: <add> variables.append(('postbuilds', postbuild)) <add> if self.xcode_settings: <add> variables.append(('libtool_flags', <add> self.xcode_settings.GetLibtoolflags(config_name))) <add> if (self.flavor not in ('mac', 'win') and not <add> self.is_standalone_static_library): <add> self.ninja.build(self.target.binary, 'alink_thin', link_deps, <add> order_only=compile_deps, variables=variables) <add> else: <add> self.ninja.build(self.target.binary, 'alink', link_deps, <add> order_only=compile_deps, variables=variables) <ide> else: <ide> self.WriteLink(spec, config_name, config, link_deps) <ide> return self.target.binary <ide> def ComputeOutput(self, spec, type=None): <ide> elif self.flavor == 'win' and self.toolset == 'target': <ide> type_in_output_root += ['shared_library'] <ide> <del> if type in type_in_output_root: <add> if type in type_in_output_root or self.is_standalone_static_library: <ide> return filename <ide> elif type == 'shared_library': <ide> libdir = 'lib' <ide> def WriteVariableList(self, var, values): <ide> values = [] <ide> self.ninja.variable(var, ' '.join(values)) <ide> <del> def WriteNewNinjaRule(self, name, args, description, is_cygwin, env={}): <add> def WriteNewNinjaRule(self, name, args, description, is_cygwin, env): <ide> """Write out a new ninja "rule" statement for a given command. <ide> <del> Returns the name of the new rule.""" <add> Returns the name of the new rule, and a copy of |args| with variables <add> expanded.""" <add> <add> if self.flavor == 'win': <add> args = [self.msvs_settings.ConvertVSMacros( <add> arg, self.base_to_build, config=self.config_name) <add> for arg in args] <add> description = self.msvs_settings.ConvertVSMacros( <add> description, config=self.config_name) <add> elif self.flavor == 'mac': <add> # |env| is an empty list on non-mac. <add> args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] <add> description = gyp.xcode_emulation.ExpandEnvVars(description, env) <ide> <ide> # TODO: we shouldn't need to qualify names; we do it because <ide> # currently the ninja rule namespace is global, but it really <ide> def WriteNewNinjaRule(self, name, args, description, is_cygwin, env={}): <ide> rule_name += '.' + name <ide> rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) <ide> <del> args = args[:] <del> <del> if self.flavor == 'win': <del> description = self.msvs_settings.ConvertVSMacros( <del> description, config=self.config_name) <add> # Remove variable references, but not if they refer to the magic rule <add> # variables. This is not quite right, as it also protects these for <add> # actions, not just for rules where they are valid. Good enough. <add> protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] <add> protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' <add> description = re.sub(protect + r'\$', '_', description) <ide> <ide> # gyp dictates that commands are run from the base directory. <ide> # cd into the directory before running, and adjust paths in <ide> def WriteNewNinjaRule(self, name, args, description, is_cygwin, env={}): <ide> else: <ide> env = self.ComputeExportEnvString(env) <ide> command = gyp.common.EncodePOSIXShellList(args) <del> if env: <del> # If an environment is passed in, variables in the command should be <del> # read from it, instead of from ninja's internal variables. <del> command = ninja_syntax.escape(command) <ide> command = 'cd %s; ' % self.build_to_base + env + command <ide> <ide> # GYP rules/actions express being no-ops by not touching their outputs. <ide> def WriteNewNinjaRule(self, name, args, description, is_cygwin, env={}): <ide> rspfile=rspfile, rspfile_content=rspfile_content) <ide> self.ninja.newline() <ide> <del> return rule_name <add> return rule_name, args <ide> <ide> <ide> def CalculateVariables(default_variables, params): <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> flavor = gyp.common.GetFlavor(params) <ide> generator_flags = params.get('generator_flags', {}) <ide> <add> # generator_dir: relative path from pwd to where make puts build files. <add> # Makes migrating from make to ninja easier, ninja doesn't put anything here. <add> generator_dir = os.path.relpath(params['options'].generator_output or '.') <add> <add> # output_dir: relative path from generator_dir to the build directory. <add> output_dir = generator_flags.get('output_dir', 'out') <add> <ide> # build_dir: relative path from source root to our output files. <ide> # e.g. "out/Debug" <del> build_dir = os.path.join(generator_flags.get('output_dir', 'out'), <del> config_name) <add> build_dir = os.path.normpath(os.path.join(generator_dir, <add> output_dir, <add> config_name)) <ide> <ide> toplevel_build = os.path.join(options.toplevel_dir, build_dir) <ide> <ide> master_ninja = ninja_syntax.Writer( <ide> OpenOutput(os.path.join(toplevel_build, 'build.ninja')), <ide> width=120) <add> case_sensitive_filesystem = not os.path.exists( <add> os.path.join(toplevel_build, 'BUILD.NINJA')) <ide> <ide> # Put build-time support tools in out/{config_name}. <ide> gyp.common.CopyTool(flavor, toplevel_build) <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> else: <ide> master_ninja.variable('ld_host', flock + ' linker.lock ' + ld_host) <ide> <del> if flavor == 'mac': <del> master_ninja.variable('mac_tool', os.path.join('.', 'gyp-mac-tool')) <ide> master_ninja.newline() <ide> <ide> if flavor != 'win': <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> command=('$cc -MMD -MF $out.d $defines $includes $cflags $cflags_c ' <ide> '$cflags_pch_c -c $in -o $out'), <ide> depfile='$out.d') <add> master_ninja.rule( <add> 'cc_s', <add> description='CC $out', <add> command=('$cc $defines $includes $cflags $cflags_c ' <add> '$cflags_pch_c -c $in -o $out')) <ide> master_ninja.rule( <ide> 'cxx', <ide> description='CXX $out', <ide> command=('$cxx -MMD -MF $out.d $defines $includes $cflags $cflags_cc ' <ide> '$cflags_pch_cc -c $in -o $out'), <ide> depfile='$out.d') <ide> else: <del> # TODO(scottmg): Requires fork of ninja for dependency and linking <del> # support: https://github.com/sgraham/ninja <ide> # Template for compile commands mostly shared between compiling files <ide> # and generating PCH. In the case of PCH, the "output" is specified by /Fp <ide> # rather than /Fo (for object files), but we still need to specify an /Fo <ide> # when compiling PCH. <del> cc_template = ('ninja-deplist-helper -r . -q -f cl -o $out.dl -e $arch ' <del> '--command ' <add> cc_template = ('ninja -t msvc -r . -o $out -e $arch ' <add> '-- ' <ide> '$cc /nologo /showIncludes /FC ' <ide> '@$out.rsp ' <ide> '$cflags_pch_c /c $in %(outspec)s /Fd$pdbname ') <del> cxx_template = ('ninja-deplist-helper -r . -q -f cl -o $out.dl -e $arch ' <del> '--command ' <add> cxx_template = ('ninja -t msvc -r . -o $out -e $arch ' <add> '-- ' <ide> '$cxx /nologo /showIncludes /FC ' <ide> '@$out.rsp ' <ide> '$cflags_pch_cc /c $in %(outspec)s $pchobj /Fd$pdbname ') <ide> master_ninja.rule( <ide> 'cc', <ide> description='CC $out', <ide> command=cc_template % {'outspec': '/Fo$out'}, <del> depfile='$out.dl', <add> depfile='$out.d', <ide> rspfile='$out.rsp', <ide> rspfile_content='$defines $includes $cflags $cflags_c') <ide> master_ninja.rule( <ide> 'cc_pch', <ide> description='CC PCH $out', <ide> command=cc_template % {'outspec': '/Fp$out /Fo$out.obj'}, <del> depfile='$out.dl', <add> depfile='$out.d', <ide> rspfile='$out.rsp', <ide> rspfile_content='$defines $includes $cflags $cflags_c') <ide> master_ninja.rule( <ide> 'cxx', <ide> description='CXX $out', <ide> command=cxx_template % {'outspec': '/Fo$out'}, <del> depfile='$out.dl', <add> depfile='$out.d', <ide> rspfile='$out.rsp', <ide> rspfile_content='$defines $includes $cflags $cflags_cc') <ide> master_ninja.rule( <ide> 'cxx_pch', <ide> description='CXX PCH $out', <ide> command=cxx_template % {'outspec': '/Fp$out /Fo$out.obj'}, <del> depfile='$out.dl', <add> depfile='$out.d', <ide> rspfile='$out.rsp', <ide> rspfile_content='$defines $includes $cflags $cflags_cc') <ide> master_ninja.rule( <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> master_ninja.rule( <ide> 'alink', <ide> description='AR $out', <add> command='rm -f $out && $ar rcs $out $in') <add> master_ninja.rule( <add> 'alink_thin', <add> description='AR $out', <ide> command='rm -f $out && $ar rcsT $out $in') <ide> <ide> # This allows targets that only need to depend on $lib's API to declare an <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> rspfile_content='$in_newline $libflags') <ide> dlldesc = 'LINK(DLL) $dll' <ide> dllcmd = ('%s gyp-win-tool link-wrapper $arch ' <del> '$ld /nologo /IMPLIB:$implib /DLL /OUT:$dll ' <add> '$ld /nologo $implibflag /DLL /OUT:$dll ' <ide> '/PDB:$dll.pdb @$dll.rsp' % sys.executable) <ide> dllcmd += (' && %s gyp-win-tool manifest-wrapper $arch ' <ide> '$mt -nologo -manifest $manifests -out:$dll.manifest' % <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> 'alink', <ide> description='LIBTOOL-STATIC $out, POSTBUILDS', <ide> command='rm -f $out && ' <del> './gyp-mac-tool filter-libtool libtool -static -o $out $in' <add> './gyp-mac-tool filter-libtool libtool $libtool_flags ' <add> '-static -o $out $in' <ide> '$postbuilds') <ide> <ide> # Record the public interface of $lib in $lib.TOC. See the corresponding <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> master_ninja.rule( <ide> 'mac_tool', <ide> description='MACTOOL $mactool_cmd $in', <del> command='$env $mac_tool $mactool_cmd $in $out') <add> command='$env ./gyp-mac-tool $mactool_cmd $in $out') <ide> master_ninja.rule( <ide> 'package_framework', <ide> description='PACKAGE FRAMEWORK $out, POSTBUILDS', <del> command='$mac_tool package-framework $out $version$postbuilds ' <add> command='./gyp-mac-tool package-framework $out $version$postbuilds ' <ide> '&& touch $out') <ide> if flavor == 'win': <ide> master_ninja.rule( <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> flavor, abs_build_dir=abs_build_dir) <ide> master_ninja.subninja(output_file) <ide> <del> target = writer.WriteSpec(spec, config_name, generator_flags) <add> target = writer.WriteSpec( <add> spec, config_name, generator_flags, case_sensitive_filesystem) <ide> if target: <ide> if name != target.FinalOutput() and spec['toolset'] == 'target': <ide> target_short_names.setdefault(name, []).append(target) <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> if all_outputs: <ide> master_ninja.newline() <ide> master_ninja.build('all', 'phony', list(all_outputs)) <del> master_ninja.default('all') <add> master_ninja.default(generator_flags.get('default_target', 'all')) <ide> <ide> <del>def GenerateOutput(target_list, target_dicts, data, params): <del> if params['options'].generator_output: <del> raise NotImplementedError, "--generator_output not implemented for ninja" <add>def PerformBuild(data, configurations, params): <add> options = params['options'] <add> for config in configurations: <add> builddir = os.path.join(options.toplevel_dir, 'out', config) <add> arguments = ['ninja', '-C', builddir] <add> print 'Building [%s]: %s' % (config, arguments) <add> subprocess.check_call(arguments) <add> <add> <add>def CallGenerateOutputForConfig(arglist): <add> # Ignore the interrupt signal so that the parent process catches it and <add> # kills all multiprocessing children. <add> signal.signal(signal.SIGINT, signal.SIG_IGN) <add> <add> (target_list, target_dicts, data, params, config_name) = arglist <add> GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) <ide> <add> <add>def GenerateOutput(target_list, target_dicts, data, params): <ide> user_config = params.get('generator_flags', {}).get('config', None) <ide> if user_config: <ide> GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> user_config) <ide> else: <ide> config_names = target_dicts[target_list[0]]['configurations'].keys() <del> for config_name in config_names: <del> GenerateOutputForConfig(target_list, target_dicts, data, params, <del> config_name) <add> if params['parallel']: <add> try: <add> pool = multiprocessing.Pool(len(config_names)) <add> arglists = [] <add> for config_name in config_names: <add> arglists.append( <add> (target_list, target_dicts, data, params, config_name)) <add> pool.map(CallGenerateOutputForConfig, arglists) <add> except KeyboardInterrupt, e: <add> pool.terminate() <add> raise e <add> else: <add> for config_name in config_names: <add> GenerateOutputForConfig(target_list, target_dicts, data, params, <add> config_name) <ide><path>tools/gyp/pylib/gyp/generator/scons.py <ide> import os.path <ide> import pprint <ide> import re <add>import subprocess <ide> <ide> <ide> # TODO: remove when we delete the last WriteList() call in this module <ide> def TargetFilename(target, build_file=None, output_suffix=''): <ide> return output_file <ide> <ide> <add>def PerformBuild(data, configurations, params): <add> options = params['options'] <add> <add> # Due to the way we test gyp on the chromium typbots <add> # we need to look for 'scons.py' as well as the more common 'scons' <add> # TODO(sbc): update the trybots to have a more normal install <add> # of scons. <add> scons = 'scons' <add> paths = os.environ['PATH'].split(os.pathsep) <add> for scons_name in ['scons', 'scons.py']: <add> for path in paths: <add> test_scons = os.path.join(path, scons_name) <add> print 'looking for: %s' % test_scons <add> if os.path.exists(test_scons): <add> print "found scons: %s" % scons <add> scons = test_scons <add> break <add> <add> for config in configurations: <add> arguments = [scons, '-C', options.toplevel_dir, '--mode=%s' % config] <add> print "Building [%s]: %s" % (config, arguments) <add> subprocess.check_call(arguments) <add> <add> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> """ <ide> Generates all the output files for the specified targets. <ide><path>tools/gyp/pylib/gyp/generator/xcode.py <ide> def EscapeXCodeArgument(s): <ide> return '"' + s + '"' <ide> <ide> <add> <add>def PerformBuild(data, configurations, params): <add> options = params['options'] <add> <add> for build_file, build_file_dict in data.iteritems(): <add> (build_file_root, build_file_ext) = os.path.splitext(build_file) <add> if build_file_ext != '.gyp': <add> continue <add> xcodeproj_path = build_file_root + options.suffix + '.xcodeproj' <add> if options.generator_output: <add> xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) <add> <add> for config in configurations: <add> arguments = ['xcodebuild', '-project', xcodeproj_path] <add> arguments += ['-configuration', config] <add> print "Building [%s]: %s" % (config, arguments) <add> subprocess.check_call(arguments) <add> <add> <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> options = params['options'] <ide> generator_flags = params.get('generator_flags', {}) <ide><path>tools/gyp/pylib/gyp/input.py <ide> import compiler <ide> import copy <ide> import gyp.common <add>import multiprocessing <ide> import optparse <ide> import os.path <ide> import re <ide> import shlex <add>import signal <ide> import subprocess <ide> import sys <add>import threading <add>import time <add>from gyp.common import GypError <ide> <ide> <ide> # A list of types that are treated as linkable. <ide> def IsPathSection(section): <ide> 'rules', <ide> 'run_as', <ide> 'sources', <add> 'standalone_static_library', <ide> 'suppress_wildcard', <ide> 'target_name', <ide> 'toolset', <ide> def IsPathSection(section): <ide> 'libraries', <ide> 'link_settings', <ide> 'sources', <add> 'standalone_static_library', <ide> 'target_name', <ide> 'type', <ide> ] <ide> def CheckNode(node, keypath): <ide> assert isinstance(c[n], Const) <ide> key = c[n].getChildren()[0] <ide> if key in dict: <del> raise KeyError, "Key '" + key + "' repeated at level " + \ <del> repr(len(keypath) + 1) + " with key path '" + \ <del> '.'.join(keypath) + "'" <add> raise GypError("Key '" + key + "' repeated at level " + <add> repr(len(keypath) + 1) + " with key path '" + <add> '.'.join(keypath) + "'") <ide> kp = list(keypath) # Make a copy of the list for descending this node. <ide> kp.append(key) <ide> dict[key] = CheckNode(c[n + 1], kp) <ide> def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, <ide> if os.path.exists(build_file_path): <ide> build_file_contents = open(build_file_path).read() <ide> else: <del> raise Exception("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) <add> raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) <ide> <ide> build_file_data = None <ide> try: <ide> def ProcessToolsetsInDict(data): <ide> # a build file that contains targets and is expected to provide a targets dict <ide> # that contains the targets... <ide> def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, <del> depth, check): <add> depth, check, load_dependencies): <ide> # If depth is set, predefine the DEPTH variable to be a relative path from <ide> # this build file's directory to the directory identified by depth. <ide> if depth: <ide> def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, <ide> <ide> if build_file_path in data['target_build_files']: <ide> # Already loaded. <del> return <add> return False <ide> data['target_build_files'].add(build_file_path) <ide> <ide> gyp.DebugOutput(gyp.DEBUG_INCLUDES, <ide> def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, <ide> # Set up the included_files key indicating which .gyp files contributed to <ide> # this target dict. <ide> if 'included_files' in build_file_data: <del> raise KeyError, build_file_path + ' must not contain included_files key' <add> raise GypError(build_file_path + ' must not contain included_files key') <ide> <ide> included = GetIncludedBuildFiles(build_file_path, aux_data) <ide> build_file_data['included_files'] = [] <ide> def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, <ide> # Look at each project's target_defaults dict, and merge settings into <ide> # targets. <ide> if 'target_defaults' in build_file_data: <add> if 'targets' not in build_file_data: <add> raise GypError("Unable to find targets in build file %s" % <add> build_file_path) <add> <ide> index = 0 <del> if 'targets' in build_file_data: <del> while index < len(build_file_data['targets']): <del> # This procedure needs to give the impression that target_defaults is <del> # used as defaults, and the individual targets inherit from that. <del> # The individual targets need to be merged into the defaults. Make <del> # a deep copy of the defaults for each target, merge the target dict <del> # as found in the input file into that copy, and then hook up the <del> # copy with the target-specific data merged into it as the replacement <del> # target dict. <del> old_target_dict = build_file_data['targets'][index] <del> new_target_dict = copy.deepcopy(build_file_data['target_defaults']) <del> MergeDicts(new_target_dict, old_target_dict, <del> build_file_path, build_file_path) <del> build_file_data['targets'][index] = new_target_dict <del> index = index + 1 <del> else: <del> raise Exception, \ <del> "Unable to find targets in build file %s" % build_file_path <add> while index < len(build_file_data['targets']): <add> # This procedure needs to give the impression that target_defaults is <add> # used as defaults, and the individual targets inherit from that. <add> # The individual targets need to be merged into the defaults. Make <add> # a deep copy of the defaults for each target, merge the target dict <add> # as found in the input file into that copy, and then hook up the <add> # copy with the target-specific data merged into it as the replacement <add> # target dict. <add> old_target_dict = build_file_data['targets'][index] <add> new_target_dict = copy.deepcopy(build_file_data['target_defaults']) <add> MergeDicts(new_target_dict, old_target_dict, <add> build_file_path, build_file_path) <add> build_file_data['targets'][index] = new_target_dict <add> index += 1 <ide> <ide> # No longer needed. <ide> del build_file_data['target_defaults'] <ide> def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, <ide> # in other words, you can't put a "dependencies" section inside a "post" <ide> # conditional within a target. <ide> <add> dependencies = [] <ide> if 'targets' in build_file_data: <ide> for target_dict in build_file_data['targets']: <ide> if 'dependencies' not in target_dict: <ide> continue <ide> for dependency in target_dict['dependencies']: <del> other_build_file = \ <del> gyp.common.ResolveTarget(build_file_path, dependency, None)[0] <del> try: <del> LoadTargetBuildFile(other_build_file, data, aux_data, variables, <del> includes, depth, check) <del> except Exception, e: <del> gyp.common.ExceptionAppend( <del> e, 'while loading dependencies of %s' % build_file_path) <del> raise <add> dependencies.append( <add> gyp.common.ResolveTarget(build_file_path, dependency, None)[0]) <add> <add> if load_dependencies: <add> for dependency in dependencies: <add> try: <add> LoadTargetBuildFile(dependency, data, aux_data, variables, <add> includes, depth, check, load_dependencies) <add> except Exception, e: <add> gyp.common.ExceptionAppend( <add> e, 'while loading dependencies of %s' % build_file_path) <add> raise <add> else: <add> return (build_file_path, dependencies) <add> <add> <add>def CallLoadTargetBuildFile(global_flags, <add> build_file_path, data, <add> aux_data, variables, <add> includes, depth, check): <add> """Wrapper around LoadTargetBuildFile for parallel processing. <add> <add> This wrapper is used when LoadTargetBuildFile is executed in <add> a worker process. <add> """ <add> <add> try: <add> signal.signal(signal.SIGINT, signal.SIG_IGN) <add> <add> # Apply globals so that the worker process behaves the same. <add> for key, value in global_flags.iteritems(): <add> globals()[key] = value <add> <add> # Save the keys so we can return data that changed. <add> data_keys = set(data) <add> aux_data_keys = set(aux_data) <add> <add> result = LoadTargetBuildFile(build_file_path, data, <add> aux_data, variables, <add> includes, depth, check, False) <add> if not result: <add> return result <add> <add> (build_file_path, dependencies) = result <add> <add> data_out = {} <add> for key in data: <add> if key == 'target_build_files': <add> continue <add> if key not in data_keys: <add> data_out[key] = data[key] <add> aux_data_out = {} <add> for key in aux_data: <add> if key not in aux_data_keys: <add> aux_data_out[key] = aux_data[key] <add> <add> # This gets serialized and sent back to the main process via a pipe. <add> # It's handled in LoadTargetBuildFileCallback. <add> return (build_file_path, <add> data_out, <add> aux_data_out, <add> dependencies) <add> except Exception, e: <add> print "Exception: ", e <add> return None <add> <add> <add>class ParallelProcessingError(Exception): <add> pass <add> <add> <add>class ParallelState(object): <add> """Class to keep track of state when processing input files in parallel. <add> <add> If build files are loaded in parallel, use this to keep track of <add> state during farming out and processing parallel jobs. It's stored <add> in a global so that the callback function can have access to it. <add> """ <add> <add> def __init__(self): <add> # The multiprocessing pool. <add> self.pool = None <add> # The condition variable used to protect this object and notify <add> # the main loop when there might be more data to process. <add> self.condition = None <add> # The "data" dict that was passed to LoadTargetBuildFileParallel <add> self.data = None <add> # The "aux_data" dict that was passed to LoadTargetBuildFileParallel <add> self.aux_data = None <add> # The number of parallel calls outstanding; decremented when a response <add> # was received. <add> self.pending = 0 <add> # The set of all build files that have been scheduled, so we don't <add> # schedule the same one twice. <add> self.scheduled = set() <add> # A list of dependency build file paths that haven't been scheduled yet. <add> self.dependencies = [] <add> # Flag to indicate if there was an error in a child process. <add> self.error = False <ide> <del> return data <add> def LoadTargetBuildFileCallback(self, result): <add> """Handle the results of running LoadTargetBuildFile in another process. <add> """ <add> self.condition.acquire() <add> if not result: <add> self.error = True <add> self.condition.notify() <add> self.condition.release() <add> return <add> (build_file_path0, data0, aux_data0, dependencies0) = result <add> self.data['target_build_files'].add(build_file_path0) <add> for key in data0: <add> self.data[key] = data0[key] <add> for key in aux_data0: <add> self.aux_data[key] = aux_data0[key] <add> for new_dependency in dependencies0: <add> if new_dependency not in self.scheduled: <add> self.scheduled.add(new_dependency) <add> self.dependencies.append(new_dependency) <add> self.pending -= 1 <add> self.condition.notify() <add> self.condition.release() <add> <add> <add>def LoadTargetBuildFileParallel(build_file_path, data, aux_data, <add> variables, includes, depth, check): <add> parallel_state = ParallelState() <add> parallel_state.condition = threading.Condition() <add> parallel_state.dependencies = [build_file_path] <add> parallel_state.scheduled = set([build_file_path]) <add> parallel_state.pending = 0 <add> parallel_state.data = data <add> parallel_state.aux_data = aux_data <add> <add> try: <add> parallel_state.condition.acquire() <add> while parallel_state.dependencies or parallel_state.pending: <add> if parallel_state.error: <add> break <add> if not parallel_state.dependencies: <add> parallel_state.condition.wait() <add> continue <add> <add> dependency = parallel_state.dependencies.pop() <add> <add> parallel_state.pending += 1 <add> data_in = {} <add> data_in['target_build_files'] = data['target_build_files'] <add> aux_data_in = {} <add> global_flags = { <add> 'path_sections': globals()['path_sections'], <add> 'non_configuration_keys': globals()['non_configuration_keys'], <add> 'absolute_build_file_paths': globals()['absolute_build_file_paths'], <add> 'multiple_toolsets': globals()['multiple_toolsets']} <add> <add> if not parallel_state.pool: <add> parallel_state.pool = multiprocessing.Pool(8) <add> parallel_state.pool.apply_async( <add> CallLoadTargetBuildFile, <add> args = (global_flags, dependency, <add> data_in, aux_data_in, <add> variables, includes, depth, check), <add> callback = parallel_state.LoadTargetBuildFileCallback) <add> except KeyboardInterrupt, e: <add> parallel_state.pool.terminate() <add> raise e <add> <add> parallel_state.condition.release() <add> if parallel_state.error: <add> sys.exit() <ide> <ide> <ide> # Look for the bracket that matches the first bracket seen in a <ide> def ExpandVariables(input, phase, variables, build_file): <ide> os.chdir(oldwd) <ide> assert replacement != None <ide> elif command_string: <del> raise Exception("Unknown command string '%s' in '%s'." % <del> (command_string, contents)) <add> raise GypError("Unknown command string '%s' in '%s'." % <add> (command_string, contents)) <ide> else: <ide> # Fix up command with platform specific workarounds. <ide> contents = FixupPlatformCommand(contents) <ide> def ExpandVariables(input, phase, variables, build_file): <ide> sys.stderr.write(p_stderr) <ide> # Simulate check_call behavior, since check_call only exists <ide> # in python 2.5 and later. <del> raise Exception("Call to '%s' returned exit status %d." % <del> (contents, p.returncode)) <add> raise GypError("Call to '%s' returned exit status %d." % <add> (contents, p.returncode)) <ide> replacement = p_stdout.rstrip() <ide> <ide> cached_command_results[cache_key] = replacement <ide> def ExpandVariables(input, phase, variables, build_file): <ide> # ], <ide> replacement = [] <ide> else: <del> raise KeyError, 'Undefined variable ' + contents + \ <del> ' in ' + build_file <add> raise GypError('Undefined variable ' + contents + <add> ' in ' + build_file) <ide> else: <ide> replacement = variables[contents] <ide> <ide> if isinstance(replacement, list): <ide> for item in replacement: <ide> if (not contents[-1] == '/' and <ide> not isinstance(item, str) and not isinstance(item, int)): <del> raise TypeError, 'Variable ' + contents + \ <del> ' must expand to a string or list of strings; ' + \ <del> 'list contains a ' + \ <del> item.__class__.__name__ <add> raise GypError('Variable ' + contents + <add> ' must expand to a string or list of strings; ' + <add> 'list contains a ' + <add> item.__class__.__name__) <ide> # Run through the list and handle variable expansions in it. Since <ide> # the list is guaranteed not to contain dicts, this won't do anything <ide> # with conditions sections. <ide> ProcessVariablesAndConditionsInList(replacement, phase, variables, <ide> build_file) <ide> elif not isinstance(replacement, str) and \ <ide> not isinstance(replacement, int): <del> raise TypeError, 'Variable ' + contents + \ <del> ' must expand to a string or list of strings; ' + \ <del> 'found a ' + replacement.__class__.__name__ <add> raise GypError('Variable ' + contents + <add> ' must expand to a string or list of strings; ' + <add> 'found a ' + replacement.__class__.__name__) <ide> <ide> if expand_to_list: <ide> # Expanding in list context. It's guaranteed that there's only one <ide> def ProcessConditionsInDict(the_dict, phase, variables, build_file): <ide> <ide> for condition in conditions_list: <ide> if not isinstance(condition, list): <del> raise TypeError, conditions_key + ' must be a list' <add> raise GypError(conditions_key + ' must be a list') <ide> if len(condition) != 2 and len(condition) != 3: <ide> # It's possible that condition[0] won't work in which case this <ide> # attempt will raise its own IndexError. That's probably fine. <del> raise IndexError, conditions_key + ' ' + condition[0] + \ <del> ' must be length 2 or 3, not ' + str(len(condition)) <add> raise GypError(conditions_key + ' ' + condition[0] + <add> ' must be length 2 or 3, not ' + str(len(condition))) <ide> <ide> [cond_expr, true_dict] = condition[0:2] <ide> false_dict = None <ide> def BuildTargetsDict(data): <ide> target['target_name'], <ide> target['toolset']) <ide> if target_name in targets: <del> raise KeyError, 'Duplicate target definitions for ' + target_name <add> raise GypError('Duplicate target definitions for ' + target_name) <ide> targets[target_name] = target <ide> <ide> return targets <ide> def QualifyDependencies(targets): <ide> # appears in the "dependencies" list. <ide> if dependency_key != 'dependencies' and \ <ide> dependency not in target_dict['dependencies']: <del> raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \ <del> ' of ' + target + ', but not in dependencies' <add> raise GypError('Found ' + dependency + ' in ' + dependency_key + <add> ' of ' + target + ', but not in dependencies') <ide> <ide> <ide> def ExpandWildcardDependencies(targets, data): <ide> def ExpandWildcardDependencies(targets, data): <ide> if dependency_build_file == target_build_file: <ide> # It's an error for a target to depend on all other targets in <ide> # the same file, because a target cannot depend on itself. <del> raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \ <del> target + ' referring to same build file' <add> raise GypError('Found wildcard in ' + dependency_key + ' of ' + <add> target + ' referring to same build file') <ide> <ide> # Take the wildcard out and adjust the index so that the next <ide> # dependency in the list will be processed the next time through the <ide> class DependencyGraphNode(object): <ide> dependents: List of DependencyGraphNodes that depend on this one. <ide> """ <ide> <del> class CircularException(Exception): <add> class CircularException(GypError): <ide> pass <ide> <ide> def __init__(self, ref): <ide> def LinkDependencies(self, targets, dependencies=None, initial=True): <ide> # but that's presently the easiest way to access the target dicts so that <ide> # this function can find target types. <ide> <del> if not 'target_name' in targets[self.ref]: <del> raise Exception("Missing 'target_name' field in target.") <add> if 'target_name' not in targets[self.ref]: <add> raise GypError("Missing 'target_name' field in target.") <ide> <del> try: <del> target_type = targets[self.ref]['type'] <del> except KeyError, e: <del> raise Exception("Missing 'type' field in target %s" % <del> targets[self.ref]['target_name']) <add> if 'type' not in targets[self.ref]: <add> raise GypError("Missing 'type' field in target %s" % <add> targets[self.ref]['target_name']) <add> <add> target_type = targets[self.ref]['type'] <ide> <ide> is_linkable = target_type in linkable_types <ide> <ide> def BuildDependencyList(targets): <ide> # access. <ide> dependency_nodes = {} <ide> for target, spec in targets.iteritems(): <del> if not target in dependency_nodes: <add> if target not in dependency_nodes: <ide> dependency_nodes[target] = DependencyGraphNode(target) <ide> <ide> # Set up the dependency links. Targets that have no dependencies are treated <ide> def BuildDependencyList(targets): <ide> for target, spec in targets.iteritems(): <ide> target_node = dependency_nodes[target] <ide> target_build_file = gyp.common.BuildFile(target) <del> if not 'dependencies' in spec or len(spec['dependencies']) == 0: <add> dependencies = spec.get('dependencies') <add> if not dependencies: <ide> target_node.dependencies = [root_node] <ide> root_node.dependents.append(target_node) <ide> else: <del> dependencies = spec['dependencies'] <del> for index in xrange(0, len(dependencies)): <del> try: <del> dependency = dependencies[index] <del> dependency_node = dependency_nodes[dependency] <del> target_node.dependencies.append(dependency_node) <del> dependency_node.dependents.append(target_node) <del> except KeyError, e: <del> gyp.common.ExceptionAppend(e, <del> 'while trying to load target %s' % target) <del> raise <add> for dependency in dependencies: <add> dependency_node = dependency_nodes.get(dependency) <add> if not dependency_node: <add> raise GypError("Dependency '%s' not found while " <add> "trying to load target %s" % (dependency, target)) <add> target_node.dependencies.append(dependency_node) <add> dependency_node.dependents.append(target_node) <ide> <ide> flat_list = root_node.FlattenToList() <ide> <ide> # If there's anything left unvisited, there must be a circular dependency <ide> # (cycle). If you need to figure out what's wrong, look for elements of <ide> # targets that are not in flat_list. <ide> if len(flat_list) != len(targets): <del> raise DependencyGraphNode.CircularException, \ <del> 'Some targets not reachable, cycle in dependency graph detected: ' + \ <del> ' '.join(set(flat_list) ^ set(targets)) <add> raise DependencyGraphNode.CircularException( <add> 'Some targets not reachable, cycle in dependency graph detected: ' + <add> ' '.join(set(flat_list) ^ set(targets))) <ide> <ide> return [dependency_nodes, flat_list] <ide> <ide> def VerifyNoGYPFileCircularDependencies(targets): <ide> for dependency in target_dependencies: <ide> try: <ide> dependency_build_file = gyp.common.BuildFile(dependency) <del> if dependency_build_file == build_file: <del> # A .gyp file is allowed to refer back to itself. <del> continue <del> dependency_node = dependency_nodes[dependency_build_file] <del> if dependency_node not in build_file_node.dependencies: <del> build_file_node.dependencies.append(dependency_node) <del> dependency_node.dependents.append(build_file_node) <del> except KeyError, e: <add> except GypError, e: <ide> gyp.common.ExceptionAppend( <ide> e, 'while computing dependencies of .gyp file %s' % build_file) <ide> raise <ide> <add> if dependency_build_file == build_file: <add> # A .gyp file is allowed to refer back to itself. <add> continue <add> dependency_node = dependency_nodes.get(dependency_build_file) <add> if not dependency_node: <add> raise GypError("Dependancy '%s' not found" % dependency_build_file) <add> if dependency_node not in build_file_node.dependencies: <add> build_file_node.dependencies.append(dependency_node) <add> dependency_node.dependents.append(build_file_node) <add> <add> <ide> # Files that have no dependencies are treated as dependent on root_node. <ide> root_node = DependencyGraphNode(None) <ide> for build_file_node in dependency_nodes.itervalues(): <ide> def DoDependentSettings(key, flat_list, targets, dependency_nodes): <ide> elif key == 'link_settings': <ide> dependencies = dependency_nodes[target].LinkDependencies(targets) <ide> else: <del> raise KeyError, "DoDependentSettings doesn't know how to determine " + \ <del> 'dependencies for ' + key <add> raise GypError("DoDependentSettings doesn't know how to determine " <add> 'dependencies for ' + key) <ide> <ide> for dependency in dependencies: <ide> dependency_dict = targets[dependency] <ide> def MergeDicts(to, fro, to_file, fro_file): <ide> # and prepend are the only policies that can coexist. <ide> for list_incompatible in lists_incompatible: <ide> if list_incompatible in fro: <del> raise KeyError, 'Incompatible list policies ' + k + ' and ' + \ <del> list_incompatible <add> raise GypError('Incompatible list policies ' + k + ' and ' + <add> list_incompatible) <ide> <ide> if list_base in to: <ide> if ext == '?': <ide> def SetUpConfigurations(target, target_dict): <ide> configuration_dict = target_dict['configurations'][configuration] <ide> for key in configuration_dict.keys(): <ide> if key in invalid_configuration_keys: <del> raise KeyError, ('%s not allowed in the %s configuration, found in ' <del> 'target %s' % (key, configuration, target)) <add> raise GypError('%s not allowed in the %s configuration, found in ' <add> 'target %s' % (key, configuration, target)) <ide> <ide> <ide> <ide> def ProcessListFiltersInDict(name, the_dict): <ide> # to be created. <ide> excluded_key = list_key + '_excluded' <ide> if excluded_key in the_dict: <del> raise KeyError, \ <del> name + ' key ' + excluded_key + ' must not be present prior ' + \ <del> ' to applying exclusion/regex filters for ' + list_key <add> raise GypError(name + ' key ' + excluded_key + <add> ' must not be present prior ' <add> ' to applying exclusion/regex filters for ' + list_key) <ide> <ide> excluded_list = [] <ide> <ide> def ValidateTargetType(target, target_dict): <ide> 'none') <ide> target_type = target_dict.get('type', None) <ide> if target_type not in VALID_TARGET_TYPES: <del> raise Exception("Target %s has an invalid target type '%s'. " <del> "Must be one of %s." % <del> (target, target_type, '/'.join(VALID_TARGET_TYPES))) <add> raise GypError("Target %s has an invalid target type '%s'. " <add> "Must be one of %s." % <add> (target, target_type, '/'.join(VALID_TARGET_TYPES))) <add> if (target_dict.get('standalone_static_library', 0) and <add> not target_type == 'static_library'): <add> raise GypError('Target %s has type %s but standalone_static_library flag is' <add> ' only valid for static_library type.' % (target, <add> target_type)) <ide> <ide> <ide> def ValidateSourcesInTarget(target, target_dict, build_file): <ide> def ValidateSourcesInTarget(target, target_dict, build_file): <ide> error += ' %s: %s\n' % (basename, ' '.join(files)) <ide> <ide> if error: <del> print ('static library %s has several files with the same basename:\n' % <del> target + error + 'Some build systems, e.g. MSVC08, ' <del> 'cannot handle that.') <del> raise KeyError, 'Duplicate basenames in sources section, see list above' <add> print('static library %s has several files with the same basename:\n' % <add> target + error + 'Some build systems, e.g. MSVC08, ' <add> 'cannot handle that.') <add> raise GypError('Duplicate basenames in sources section, see list above') <ide> <ide> <ide> def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): <ide> def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): <ide> # Make sure that there's no conflict among rule names and extensions. <ide> rule_name = rule['rule_name'] <ide> if rule_name in rule_names: <del> raise KeyError, 'rule %s exists in duplicate, target %s' % \ <del> (rule_name, target) <add> raise GypError('rule %s exists in duplicate, target %s' % <add> (rule_name, target)) <ide> rule_names[rule_name] = rule <ide> <ide> rule_extension = rule['extension'] <ide> if rule_extension in rule_extensions: <del> raise KeyError, ('extension %s associated with multiple rules, ' + <del> 'target %s rules %s and %s') % \ <del> (rule_extension, target, <del> rule_extensions[rule_extension]['rule_name'], <del> rule_name) <add> raise GypError(('extension %s associated with multiple rules, ' + <add> 'target %s rules %s and %s') % <add> (rule_extension, target, <add> rule_extensions[rule_extension]['rule_name'], <add> rule_name)) <ide> rule_extensions[rule_extension] = rule <ide> <ide> # Make sure rule_sources isn't already there. It's going to be <ide> # created below if needed. <ide> if 'rule_sources' in rule: <del> raise KeyError, \ <del> 'rule_sources must not exist in input, target %s rule %s' % \ <del> (target, rule_name) <add> raise GypError( <add> 'rule_sources must not exist in input, target %s rule %s' % <add> (target, rule_name)) <ide> extension = rule['extension'] <ide> <ide> rule_sources = [] <ide> def ValidateRunAsInTarget(target, target_dict, build_file): <ide> if not run_as: <ide> return <ide> if not isinstance(run_as, dict): <del> raise Exception("The 'run_as' in target %s from file %s should be a " <del> "dictionary." % <del> (target_name, build_file)) <add> raise GypError("The 'run_as' in target %s from file %s should be a " <add> "dictionary." % <add> (target_name, build_file)) <ide> action = run_as.get('action') <ide> if not action: <del> raise Exception("The 'run_as' in target %s from file %s must have an " <del> "'action' section." % <del> (target_name, build_file)) <add> raise GypError("The 'run_as' in target %s from file %s must have an " <add> "'action' section." % <add> (target_name, build_file)) <ide> if not isinstance(action, list): <del> raise Exception("The 'action' for 'run_as' in target %s from file %s " <del> "must be a list." % <del> (target_name, build_file)) <add> raise GypError("The 'action' for 'run_as' in target %s from file %s " <add> "must be a list." % <add> (target_name, build_file)) <ide> working_directory = run_as.get('working_directory') <ide> if working_directory and not isinstance(working_directory, str): <del> raise Exception("The 'working_directory' for 'run_as' in target %s " <del> "in file %s should be a string." % <del> (target_name, build_file)) <add> raise GypError("The 'working_directory' for 'run_as' in target %s " <add> "in file %s should be a string." % <add> (target_name, build_file)) <ide> environment = run_as.get('environment') <ide> if environment and not isinstance(environment, dict): <del> raise Exception("The 'environment' for 'run_as' in target %s " <del> "in file %s should be a dictionary." % <del> (target_name, build_file)) <add> raise GypError("The 'environment' for 'run_as' in target %s " <add> "in file %s should be a dictionary." % <add> (target_name, build_file)) <ide> <ide> <ide> def ValidateActionsInTarget(target, target_dict, build_file): <ide> def ValidateActionsInTarget(target, target_dict, build_file): <ide> for action in actions: <ide> action_name = action.get('action_name') <ide> if not action_name: <del> raise Exception("Anonymous action in target %s. " <del> "An action must have an 'action_name' field." % <del> target_name) <add> raise GypError("Anonymous action in target %s. " <add> "An action must have an 'action_name' field." % <add> target_name) <ide> inputs = action.get('inputs', None) <ide> if inputs is None: <del> raise Exception('Action in target %s has no inputs.' % target_name) <add> raise GypError('Action in target %s has no inputs.' % target_name) <ide> action_command = action.get('action') <ide> if action_command and not action_command[0]: <del> raise Exception("Empty action as command in target %s." % target_name) <add> raise GypError("Empty action as command in target %s." % target_name) <ide> <ide> <ide> def TurnIntIntoStrInDict(the_dict): <ide> def VerifyNoCollidingTargets(targets): <ide> key = subdir + ':' + name <ide> if key in used: <ide> # Complain if this target is already used. <del> raise Exception('Duplicate target name "%s" in directory "%s" used both ' <del> 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) <add> raise GypError('Duplicate target name "%s" in directory "%s" used both ' <add> 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) <ide> used[key] = gyp <ide> <ide> <ide> def Load(build_files, variables, includes, depth, generator_input_info, check, <del> circular_check): <add> circular_check, parallel): <ide> # Set up path_sections and non_configuration_keys with the default data plus <ide> # the generator-specifc data. <ide> global path_sections <ide> def Load(build_files, variables, includes, depth, generator_input_info, check, <ide> # used as keys to the data dict and for references between input files. <ide> build_file = os.path.normpath(build_file) <ide> try: <del> LoadTargetBuildFile(build_file, data, aux_data, variables, includes, <del> depth, check) <add> if parallel: <add> print >>sys.stderr, 'Using parallel processing (experimental).' <add> LoadTargetBuildFileParallel(build_file, data, aux_data, <add> variables, includes, depth, check) <add> else: <add> LoadTargetBuildFile(build_file, data, aux_data, <add> variables, includes, depth, check, True) <ide> except Exception, e: <ide> gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) <ide> raise <ide><path>tools/gyp/pylib/gyp/mac_tool.py <ide> def ExecFilterLibtool(self, *cmd_list): <ide> """Calls libtool and filters out 'libtool: file: foo.o has no symbols'.""" <ide> libtool_re = re.compile(r'^libtool: file: .* has no symbols$') <ide> libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE) <del> for line in libtoolout.stderr: <add> _, err = libtoolout.communicate() <add> for line in err.splitlines(): <ide> if not libtool_re.match(line): <del> sys.stderr.write(line) <add> print >>sys.stderr, line <ide> return libtoolout.returncode <ide> <ide> def ExecPackageFramework(self, framework, version): <ide><path>tools/gyp/pylib/gyp/msvs_emulation.py <ide> def __init__(self, spec, generator_flags): <ide> ('msvs_disabled_warnings', list), <ide> ('msvs_precompiled_header', str), <ide> ('msvs_precompiled_source', str), <add> ('msvs_configuration_platform', str), <ide> ('msvs_target_platform', str), <ide> ] <ide> configs = spec['configurations'] <ide> def __init__(self, spec, generator_flags): <ide> def GetVSMacroEnv(self, base_to_build=None, config=None): <ide> """Get a dict of variables mapping internal VS macro names to their gyp <ide> equivalents.""" <del> target_platform = self.GetTargetPlatform(config) <del> target_platform = {'x86': 'Win32'}.get(target_platform, target_platform) <add> target_platform = 'Win32' if self.GetArch(config) == 'x86' else 'x64' <ide> replacements = { <ide> '$(VSInstallDir)': self.vs_version.Path(), <ide> '$(VCInstallDir)': os.path.join(self.vs_version.Path(), 'VC') + '\\', <ide> def __call__(self, name, map=None, prefix='', default=None): <ide> return self.parent._GetAndMunge(self.field, self.base_path + [name], <ide> default=default, prefix=prefix, append=self.append, map=map) <ide> <del> def GetTargetPlatform(self, config): <del> target_platform = self.msvs_target_platform.get(config, '') <del> if not target_platform: <del> target_platform = 'Win32' <del> return {'Win32': 'x86'}.get(target_platform, target_platform) <del> <del> def _RealConfig(self, config): <del> target_platform = self.GetTargetPlatform(config) <del> if target_platform == 'x64' and not config.endswith('_x64'): <add> def GetArch(self, config): <add> """Get architecture based on msvs_configuration_platform and <add> msvs_target_platform. Returns either 'x86' or 'x64'.""" <add> configuration_platform = self.msvs_configuration_platform.get(config, '') <add> platform = self.msvs_target_platform.get(config, '') <add> if not platform: # If no specific override, use the configuration's. <add> platform = configuration_platform <add> # Map from platform to architecture. <add> return {'Win32': 'x86', 'x64': 'x64'}.get(platform, 'x86') <add> <add> def _TargetConfig(self, config): <add> """Returns the target-specific configuration.""" <add> # There's two levels of architecture/platform specification in VS. The <add> # first level is globally for the configuration (this is what we consider <add> # "the" config at the gyp level, which will be something like 'Debug' or <add> # 'Release_x64'), and a second target-specific configuration, which is an <add> # override for the global one. |config| is remapped here to take into <add> # account the local target-specific overrides to the global configuration. <add> arch = self.GetArch(config) <add> if arch == 'x64' and not config.endswith('_x64'): <ide> config += '_x64' <add> if arch == 'x86' and config.endswith('_x64'): <add> config = config.rsplit('_', 1)[0] <ide> return config <ide> <ide> def _Setting(self, path, config, <ide> default=None, prefix='', append=None, map=None): <ide> """_GetAndMunge for msvs_settings.""" <del> config = self._RealConfig(config) <ide> return self._GetAndMunge( <ide> self.msvs_settings[config], path, default, prefix, append, map) <ide> <ide> def _ConfigAttrib(self, path, config, <ide> default=None, prefix='', append=None, map=None): <ide> """_GetAndMunge for msvs_configuration_attributes.""" <del> config = self._RealConfig(config) <ide> return self._GetAndMunge( <ide> self.msvs_configuration_attributes[config], <ide> path, default, prefix, append, map) <ide> <ide> def AdjustIncludeDirs(self, include_dirs, config): <ide> """Updates include_dirs to expand VS specific paths, and adds the system <ide> include dirs used for platform SDK and similar.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> includes = include_dirs + self.msvs_system_include_dirs[config] <ide> includes.extend(self._Setting( <ide> ('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[])) <ide> def AdjustIncludeDirs(self, include_dirs, config): <ide> def GetComputedDefines(self, config): <ide> """Returns the set of defines that are injected to the defines list based <ide> on other VS settings.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> defines = [] <ide> if self._ConfigAttrib(['CharacterSet'], config) == '1': <ide> defines.extend(('_UNICODE', 'UNICODE')) <ide> def GetComputedDefines(self, config): <ide> def GetOutputName(self, config, expand_special): <ide> """Gets the explicitly overridden output name for a target or returns None <ide> if it's not overridden.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> type = self.spec['type'] <ide> root = 'VCLibrarianTool' if type == 'static_library' else 'VCLinkerTool' <ide> # TODO(scottmg): Handle OutputDirectory without OutputFile. <ide> def GetOutputName(self, config, expand_special): <ide> output_file, config=config)) <ide> return output_file <ide> <add> def GetPDBName(self, config, expand_special): <add> """Gets the explicitly overridden pdb name for a target or returns None <add> if it's not overridden.""" <add> config = self._TargetConfig(config) <add> output_file = self._Setting(('VCLinkerTool', 'ProgramDatabaseFile'), config) <add> if output_file: <add> output_file = expand_special(self.ConvertVSMacros( <add> output_file, config=config)) <add> return output_file <add> <ide> def GetCflags(self, config): <ide> """Returns the flags that need to be added to .c and .cc compilations.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> cflags = [] <ide> cflags.extend(['/wd' + w for w in self.msvs_disabled_warnings[config]]) <ide> cl = self._GetWrapper(self, self.msvs_settings[config], <ide> def GetCflags(self, config): <ide> cl('RuntimeLibrary', <ide> map={'0': 'T', '1': 'Td', '2': 'D', '3': 'Dd'}, prefix='/M') <ide> cl('ExceptionHandling', map={'1': 'sc','2': 'a'}, prefix='/EH') <add> cl('EnablePREfast', map={'true': '/analyze'}) <ide> cl('AdditionalOptions', prefix='') <ide> # ninja handles parallelism by itself, don't have the compiler do it too. <ide> cflags = filter(lambda x: not x.startswith('/MP'), cflags) <ide> def GetCflags(self, config): <ide> def GetPrecompiledHeader(self, config, gyp_to_build_path): <ide> """Returns an object that handles the generation of precompiled header <ide> build steps.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> return _PchHelper(self, config, gyp_to_build_path) <ide> <ide> def _GetPchFlags(self, config, extension): <ide> """Get the flags to be added to the cflags for precompiled header support. <ide> """ <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> # The PCH is only built once by a particular source file. Usage of PCH must <ide> # only be for the same language (i.e. C vs. C++), so only include the pch <ide> # flags when the language matches. <ide> def _GetPchFlags(self, config, extension): <ide> <ide> def GetCflagsC(self, config): <ide> """Returns the flags that need to be added to .c compilations.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> return self._GetPchFlags(config, '.c') <ide> <ide> def GetCflagsCC(self, config): <ide> """Returns the flags that need to be added to .cc compilations.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> return ['/TP'] + self._GetPchFlags(config, '.cc') <ide> <ide> def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): <ide> """Get and normalize the list of paths in AdditionalLibraryDirectories <ide> setting.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> libpaths = self._Setting((root, 'AdditionalLibraryDirectories'), <ide> config, default=[]) <ide> libpaths = [os.path.normpath( <ide> def _GetAdditionalLibraryDirectories(self, root, config, gyp_to_build_path): <ide> <ide> def GetLibFlags(self, config, gyp_to_build_path): <ide> """Returns the flags that need to be added to lib commands.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> libflags = [] <ide> lib = self._GetWrapper(self, self.msvs_settings[config], <ide> 'VCLibrarianTool', append=libflags) <ide> def GetLdflags(self, config, gyp_to_build_path, expand_special, <ide> manifest_base_name, is_executable): <ide> """Returns the flags that need to be added to link commands, and the <ide> manifest files.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> ldflags = [] <ide> ld = self._GetWrapper(self, self.msvs_settings[config], <ide> 'VCLinkerTool', append=ldflags) <ide> def GetLdflags(self, config, gyp_to_build_path, expand_special, <ide> out = self.GetOutputName(config, expand_special) <ide> if out: <ide> ldflags.append('/OUT:' + out) <add> pdb = self.GetPDBName(config, expand_special) <add> if pdb: <add> ldflags.append('/PDB:' + pdb) <ide> ld('AdditionalOptions', prefix='') <ide> ld('SubSystem', map={'1': 'CONSOLE', '2': 'WINDOWS'}, prefix='/SUBSYSTEM:') <ide> ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL') <ide> def GetLdflags(self, config, gyp_to_build_path, expand_special, <ide> ld('IgnoreDefaultLibraryNames', prefix='/NODEFAULTLIB:') <ide> ld('ResourceOnlyDLL', map={'true': '/NOENTRY'}) <ide> ld('EntryPointSymbol', prefix='/ENTRY:') <add> ld('Profile', map={ 'true': '/PROFILE'}) <ide> # TODO(scottmg): This should sort of be somewhere else (not really a flag). <ide> ld('AdditionalDependencies', prefix='') <ide> # TODO(scottmg): These too. <ide> def _GetAdditionalManifestFiles(self, config, gyp_to_build_path): <ide> def IsUseLibraryDependencyInputs(self, config): <ide> """Returns whether the target should be linked via Use Library Dependency <ide> Inputs (using component .objs of a given .lib).""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> uldi = self._Setting(('VCLinkerTool', 'UseLibraryDependencyInputs'), config) <ide> return uldi == 'true' <ide> <ide> def GetRcflags(self, config, gyp_to_ninja_path): <ide> """Returns the flags that need to be added to invocations of the resource <ide> compiler.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> rcflags = [] <ide> rc = self._GetWrapper(self, self.msvs_settings[config], <ide> 'VCResourceCompilerTool', append=rcflags) <ide> def IsRuleRunUnderCygwin(self, rule): <ide> return int(rule.get('msvs_cygwin_shell', <ide> self.spec.get('msvs_cygwin_shell', 1))) != 0 <ide> <del> def HasExplicitIdlRules(self, spec): <del> """Determine if there's an explicit rule for idl files. When there isn't we <del> need to generate implicit rules to build MIDL .idl files.""" <add> def _HasExplicitRuleForExtension(self, spec, extension): <add> """Determine if there's an explicit rule for a particular extension.""" <ide> for rule in spec.get('rules', []): <del> if rule['extension'] == 'idl' and int(rule.get('msvs_external_rule', 0)): <add> if rule['extension'] == extension: <ide> return True <ide> return False <ide> <add> def HasExplicitIdlRules(self, spec): <add> """Determine if there's an explicit rule for idl files. When there isn't we <add> need to generate implicit rules to build MIDL .idl files.""" <add> return self._HasExplicitRuleForExtension(spec, 'idl') <add> <add> def HasExplicitAsmRules(self, spec): <add> """Determine if there's an explicit rule for asm files. When there isn't we <add> need to generate implicit rules to assemble .asm files.""" <add> return self._HasExplicitRuleForExtension(spec, 'asm') <add> <ide> def GetIdlBuildData(self, source, config): <ide> """Determine the implicit outputs for an idl file. Returns output <ide> directory, outputs, and variables and flags that are required.""" <del> config = self._RealConfig(config) <add> config = self._TargetConfig(config) <ide> midl_get = self._GetWrapper(self, self.msvs_settings[config], 'VCMIDLTool') <ide> def midl(name, default=None): <ide> return self.ConvertVSMacros(midl_get(name, default=default), <ide> def GenerateEnvironmentFiles(toplevel_build_dir, generator_flags, open_out): <ide> f = open_out(os.path.join(toplevel_build_dir, 'environment.' + arch), 'wb') <ide> f.write(env_block) <ide> f.close() <add> <add>def VerifyMissingSources(sources, build_dir, generator_flags, gyp_to_ninja): <add> """Emulate behavior of msvs_error_on_missing_sources present in the msvs <add> generator: Check that all regular source files, i.e. not created at run time, <add> exist on disk. Missing files cause needless recompilation when building via <add> VS, and we want this check to match for people/bots that build using ninja, <add> so they're not surprised when the VS build fails.""" <add> if int(generator_flags.get('msvs_error_on_missing_sources', 0)): <add> no_specials = filter(lambda x: '$' not in x, sources) <add> relative = [os.path.join(build_dir, gyp_to_ninja(s)) for s in no_specials] <add> missing = filter(lambda x: not os.path.exists(x), relative) <add> if missing: <add> # They'll look like out\Release\..\..\stuff\things.cc, so normalize the <add> # path for a slightly less crazy looking output. <add> cleaned_up = [os.path.normpath(x) for x in missing] <add> raise Exception('Missing input files:\n%s' % '\n'.join(cleaned_up)) <ide><path>tools/gyp/pylib/gyp/ninja_syntax.py <ide> import textwrap <ide> import re <ide> <del>def escape_spaces(word): <del> return word.replace('$ ','$$ ').replace(' ','$ ') <add>def escape_path(word): <add> return word.replace('$ ','$$ ').replace(' ','$ ').replace(':', '$:') <ide> <ide> class Writer(object): <ide> def __init__(self, output, width=78): <ide> def variable(self, key, value, indent=0): <ide> self._line('%s = %s' % (key, value), indent) <ide> <ide> def rule(self, name, command, description=None, depfile=None, <del> generator=False, restat=False, rspfile=None, <del> rspfile_content=None): <add> generator=False, restat=False, rspfile=None, rspfile_content=None): <ide> self._line('rule %s' % name) <ide> self.variable('command', command, indent=1) <ide> if description: <ide> def build(self, outputs, rule, inputs=None, implicit=None, order_only=None, <ide> variables=None): <ide> outputs = self._as_list(outputs) <ide> all_inputs = self._as_list(inputs)[:] <del> out_outputs = list(map(escape_spaces, outputs)) <del> all_inputs = list(map(escape_spaces, all_inputs)) <add> out_outputs = list(map(escape_path, outputs)) <add> all_inputs = list(map(escape_path, all_inputs)) <ide> <ide> if implicit: <del> implicit = map(escape_spaces, self._as_list(implicit)) <add> implicit = map(escape_path, self._as_list(implicit)) <ide> all_inputs.append('|') <ide> all_inputs.extend(implicit) <ide> if order_only: <del> order_only = map(escape_spaces, self._as_list(order_only)) <add> order_only = map(escape_path, self._as_list(order_only)) <ide> all_inputs.append('||') <ide> all_inputs.extend(order_only) <ide> <ide><path>tools/gyp/pylib/gyp/system_test.py <del>#!/usr/bin/env python <del> <del># Copyright (c) 2011 Google Inc. All rights reserved. <del># Use of this source code is governed by a BSD-style license that can be <del># found in the LICENSE file. <del> <del>import os <del>import tempfile <del>import shutil <del>import subprocess <del> <del> <del>def TestCommands(commands, files={}, env={}): <del> """Run commands in a temporary directory, returning true if they all succeed. <del> Return false on failures or if any commands produce output. <del> <del> Arguments: <del> commands: an array of shell-interpretable commands, e.g. ['ls -l', 'pwd'] <del> each will be expanded with Python %-expansion using env first. <del> files: a dictionary mapping filename to contents; <del> files will be created in the temporary directory before running <del> the command. <del> env: a dictionary of strings to expand commands with. <del> """ <del> tempdir = tempfile.mkdtemp() <del> try: <del> for name, contents in files.items(): <del> f = open(os.path.join(tempdir, name), 'wb') <del> f.write(contents) <del> f.close() <del> for command in commands: <del> proc = subprocess.Popen(command % env, shell=True, <del> stdout=subprocess.PIPE, <del> stderr=subprocess.STDOUT, <del> cwd=tempdir) <del> output = proc.communicate()[0] <del> if proc.returncode != 0 or output: <del> return False <del> return True <del> finally: <del> shutil.rmtree(tempdir) <del> return False <del> <del> <del>def TestArSupportsT(ar_command='ar', cc_command='cc'): <del> """Test whether 'ar' supports the 'T' flag.""" <del> return TestCommands(['%(cc)s -c test.c', <del> '%(ar)s crsT test.a test.o', <del> '%(cc)s test.a'], <del> files={'test.c': 'int main(){}'}, <del> env={'ar': ar_command, 'cc': cc_command}) <del> <del> <del>def main(): <del> # Run the various test functions and print the results. <del> def RunTest(description, function, **kwargs): <del> print "Testing " + description + ':', <del> if function(**kwargs): <del> print 'ok' <del> else: <del> print 'fail' <del> RunTest("ar 'T' flag", TestArSupportsT) <del> RunTest("ar 'T' flag with ccache", TestArSupportsT, cc_command='ccache cc') <del> return 0 <del> <del> <del>if __name__ == '__main__': <del> sys.exit(main()) <ide><path>tools/gyp/pylib/gyp/win_tool.py <ide> These functions are executed via gyp-win-tool when using the ninja generator. <ide> """ <ide> <add>from ctypes import windll, wintypes <ide> import os <ide> import shutil <ide> import subprocess <ide> import sys <del>import win32con <del>import win32file <del>import pywintypes <add> <add>BASE_DIR = os.path.dirname(os.path.abspath(__file__)) <ide> <ide> <ide> def main(args): <ide> def main(args): <ide> <ide> <ide> class LinkLock(object): <del> """A flock-style lock to limit the number of concurrent links to one. Based on <del> http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ <add> """A flock-style lock to limit the number of concurrent links to one. <add> <add> Uses a session-local mutex based on the file's directory. <ide> """ <ide> def __enter__(self): <del> self.file = open('LinkLock', 'w+') <del> self.file_handle = win32file._get_osfhandle(self.file.fileno()) <del> win32file.LockFileEx(self.file_handle, win32con.LOCKFILE_EXCLUSIVE_LOCK, <del> 0, -0x10000, pywintypes.OVERLAPPED()) <add> name = 'Local\\%s' % BASE_DIR.replace('\\', '_').replace(':', '_') <add> self.mutex = windll.kernel32.CreateMutexW( <add> wintypes.c_int(0), <add> wintypes.c_int(0), <add> wintypes.create_unicode_buffer(name)) <add> assert self.mutex <add> result = windll.kernel32.WaitForSingleObject( <add> self.mutex, wintypes.c_int(0xFFFFFFFF)) <add> # 0x80 means another process was killed without releasing the mutex, but <add> # that this process has been given ownership. This is fine for our <add> # purposes. <add> assert result in (0, 0x80), ( <add> "%s, %s" % (result, windll.kernel32.GetLastError())) <ide> <ide> def __exit__(self, type, value, traceback): <del> win32file.UnlockFileEx( <del> self.file_handle, 0, -0x10000, pywintypes.OVERLAPPED()) <del> self.file.close() <add> windll.kernel32.ReleaseMutex(self.mutex) <add> windll.kernel32.CloseHandle(self.mutex) <ide> <ide> <ide> class WinTool(object): <ide> def ExecRcWrapper(self, arch, *args): <ide> print line <ide> return popen.returncode <ide> <del> def ExecClWrapper(self, arch, depname, *args): <del> """Runs cl.exe and filters output through ninja-deplist-helper to get <del> dependendency information which is stored in |depname|.""" <del> env = self._GetEnv(arch) <del> args = ' '.join(args) + \ <del> '| ninja-deplist-helper -r . -q -f cl -o ' + depname + '"' <del> popen = subprocess.Popen(args, shell=True, env=env) <del> popen.wait() <del> return popen.returncode <del> <ide> def ExecActionWrapper(self, arch, rspfile, *dir): <ide> """Runs an action command line from a response file using the environment <ide> for |arch|. If |dir| is supplied, use that as the working directory.""" <ide><path>tools/gyp/pylib/gyp/xcode_emulation.py <ide> def GetLdflags(self, configname, product_dir, gyp_to_build_path): <ide> self.configname = None <ide> return ldflags <ide> <add> def GetLibtoolflags(self, configname): <add> """Returns flags that need to be passed to the static linker. <add> <add> Args: <add> configname: The name of the configuration to get ld flags for. <add> """ <add> self.configname = configname <add> libtoolflags = [] <add> <add> for libtoolflag in self._Settings().get('OTHER_LDFLAGS', []): <add> libtoolflags.append(libtoolflag) <add> # TODO(thakis): ARCHS? <add> <add> self.configname = None <add> return libtoolflags <add> <ide> def GetPerTargetSettings(self): <ide> """Gets a list of all the per-target settings. This will only fetch keys <ide> whose values are the same across all configurations.""" <ide> def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration, <ide> 'TARGET_BUILD_DIR' : built_products_dir, <ide> 'TEMP_DIR' : '${TMPDIR}', <ide> } <add> if xcode_settings.GetPerTargetSetting('SDKROOT'): <add> env['SDKROOT'] = xcode_settings._SdkPath() <add> else: <add> env['SDKROOT'] = '' <add> <ide> if spec['type'] in ( <ide> 'executable', 'static_library', 'shared_library', 'loadable_module'): <ide> env['EXECUTABLE_NAME'] = xcode_settings.GetExecutableName() <ide><path>tools/gyp/pylib/gyp/xcodeproj_file.py <ide> class XCObject(object): <ide> but in some cases an object's parent may wish to push a <ide> hashable value into its child, and it can do so by appending <ide> to _hashables. <del> Attribues: <add> Attributes: <ide> id: The object's identifier, a 24-character uppercase hexadecimal string. <ide> Usually, objects being created should not set id until the entire <ide> project file structure is built. At that point, UpdateIDs() should <ide> def Hashables(self): <ide> <ide> return hashables <ide> <del> def ComputeIDs(self, recursive=True, overwrite=True, hash=None): <add> def HashablesForChild(self): <add> return None <add> <add> def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None): <ide> """Set "id" properties deterministically. <ide> <ide> An object's "id" property is set based on a hash of its class type and <ide> def _HashUpdate(hash, data): <ide> hash.update(struct.pack('>i', len(data))) <ide> hash.update(data) <ide> <del> if hash is None: <del> hash = _new_sha1() <add> if seed_hash is None: <add> seed_hash = _new_sha1() <add> <add> hash = seed_hash.copy() <ide> <ide> hashables = self.Hashables() <ide> assert len(hashables) > 0 <ide> for hashable in hashables: <ide> _HashUpdate(hash, hashable) <ide> <ide> if recursive: <add> hashables_for_child = self.HashablesForChild() <add> if hashables_for_child is None: <add> child_hash = hash <add> else: <add> assert len(hashables_for_child) > 0 <add> child_hash = seed_hash.copy() <add> for hashable in hashables_for_child: <add> _HashUpdate(child_hash, hashable) <add> <ide> for child in self.Children(): <del> child.ComputeIDs(recursive, overwrite, hash.copy()) <add> child.ComputeIDs(recursive, overwrite, child_hash) <ide> <ide> if overwrite or self.id is None: <ide> # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is <ide> def __init__(self, properties=None, id=None, parent=None): <ide> for child in self._properties.get('children', []): <ide> self._AddChildToDicts(child) <ide> <add> def Hashables(self): <add> # super <add> hashables = XCHierarchicalElement.Hashables(self) <add> <add> # It is not sufficient to just rely on name and parent to build a unique <add> # hashable : a node could have two child PBXGroup sharing a common name. <add> # To add entropy the hashable is enhanced with the names of all its <add> # children. <add> for child in self._properties.get('children', []): <add> child_name = child.Name() <add> if child_name != None: <add> hashables.append(child_name) <add> <add> return hashables <add> <add> def HashablesForChild(self): <add> # To avoid a circular reference the hashables used to compute a child id do <add> # not include the child names. <add> return XCHierarchicalElement.Hashables(self) <add> <ide> def _AddChildToDicts(self, child): <ide> # Sets up this PBXGroup object's dicts to reference the child properly. <ide> child_path = child.PathFromSourceTreeAndPath() <ide> def __init__(self, properties=None, id=None, parent=None): <ide> # TODO(mark): This is the replacement for a replacement for a quick hack. <ide> # It is no longer incredibly sucky, but this list needs to be extended. <ide> extension_map = { <del> 'a': 'archive.ar', <del> 'app': 'wrapper.application', <del> 'bdic': 'file', <del> 'bundle': 'wrapper.cfbundle', <del> 'c': 'sourcecode.c.c', <del> 'cc': 'sourcecode.cpp.cpp', <del> 'cpp': 'sourcecode.cpp.cpp', <del> 'css': 'text.css', <del> 'cxx': 'sourcecode.cpp.cpp', <del> 'dylib': 'compiled.mach-o.dylib', <del> 'framework': 'wrapper.framework', <del> 'h': 'sourcecode.c.h', <del> 'hxx': 'sourcecode.cpp.h', <del> 'icns': 'image.icns', <del> 'java': 'sourcecode.java', <del> 'js': 'sourcecode.javascript', <del> 'm': 'sourcecode.c.objc', <del> 'mm': 'sourcecode.cpp.objcpp', <del> 'nib': 'wrapper.nib', <del> 'o': 'compiled.mach-o.objfile', <del> 'pdf': 'image.pdf', <del> 'pl': 'text.script.perl', <del> 'plist': 'text.plist.xml', <del> 'pm': 'text.script.perl', <del> 'png': 'image.png', <del> 'py': 'text.script.python', <del> 'r': 'sourcecode.rez', <del> 'rez': 'sourcecode.rez', <del> 's': 'sourcecode.asm', <del> 'strings': 'text.plist.strings', <del> 'ttf': 'file', <del> 'xcconfig': 'text.xcconfig', <del> 'xib': 'file.xib', <del> 'y': 'sourcecode.yacc', <add> 'a': 'archive.ar', <add> 'app': 'wrapper.application', <add> 'bdic': 'file', <add> 'bundle': 'wrapper.cfbundle', <add> 'c': 'sourcecode.c.c', <add> 'cc': 'sourcecode.cpp.cpp', <add> 'cpp': 'sourcecode.cpp.cpp', <add> 'css': 'text.css', <add> 'cxx': 'sourcecode.cpp.cpp', <add> 'dylib': 'compiled.mach-o.dylib', <add> 'framework': 'wrapper.framework', <add> 'h': 'sourcecode.c.h', <add> 'hxx': 'sourcecode.cpp.h', <add> 'icns': 'image.icns', <add> 'java': 'sourcecode.java', <add> 'js': 'sourcecode.javascript', <add> 'm': 'sourcecode.c.objc', <add> 'mm': 'sourcecode.cpp.objcpp', <add> 'nib': 'wrapper.nib', <add> 'o': 'compiled.mach-o.objfile', <add> 'pdf': 'image.pdf', <add> 'pl': 'text.script.perl', <add> 'plist': 'text.plist.xml', <add> 'pm': 'text.script.perl', <add> 'png': 'image.png', <add> 'py': 'text.script.python', <add> 'r': 'sourcecode.rez', <add> 'rez': 'sourcecode.rez', <add> 's': 'sourcecode.asm', <add> 'strings': 'text.plist.strings', <add> 'ttf': 'file', <add> 'xcconfig': 'text.xcconfig', <add> 'xcdatamodel': 'wrapper.xcdatamodel', <add> 'xib': 'file.xib', <add> 'y': 'sourcecode.yacc', <ide> } <ide> <ide> if is_dir:
22
Javascript
Javascript
normalize process.argv before user code execution
69714ab1c44f45f7949484ab7f4574f3ad9894ce
<ide><path>lib/internal/main/check_syntax.js <ide> const { <ide> stripShebang, stripBOM <ide> } = require('internal/modules/cjs/helpers'); <ide> <del>// TODO(joyeecheung): not every one of these are necessary <del>prepareMainThreadExecution(); <del>markBootstrapComplete(); <ide> <ide> if (process.argv[1] && process.argv[1] !== '-') { <ide> // Expand process.argv[1] into a full path. <ide> if (process.argv[1] && process.argv[1] !== '-') { <ide> const fs = require('fs'); <ide> const source = fs.readFileSync(filename, 'utf-8'); <ide> <add> // TODO(joyeecheung): not every one of these are necessary <add> prepareMainThreadExecution(); <add> markBootstrapComplete(); <add> <ide> checkScriptSyntax(source, filename); <ide> } else { <add> // TODO(joyeecheung): not every one of these are necessary <add> prepareMainThreadExecution(); <add> markBootstrapComplete(); <add> <ide> readStdin((code) => { <ide> checkScriptSyntax(code, '[stdin]'); <ide> }); <ide><path>lib/internal/main/run_main_module.js <ide> const { <ide> prepareMainThreadExecution <ide> } = require('internal/bootstrap/pre_execution'); <ide> <del>prepareMainThreadExecution(); <del> <ide> // Expand process.argv[1] into a full path. <ide> const path = require('path'); <ide> process.argv[1] = path.resolve(process.argv[1]); <ide> <add>prepareMainThreadExecution(); <add> <ide> const CJSModule = require('internal/modules/cjs/loader'); <ide> <ide> markBootstrapComplete(); <ide><path>test/parallel/test-preload-print-process-argv.js <add>'use strict'; <add> <add>// This tests that process.argv is the same in the preloaded module <add>// and the user module. <add> <add>const common = require('../common'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>const assert = require('assert'); <add>const { spawnSync } = require('child_process'); <add>const fs = require('fs'); <add> <add>if (!common.isMainThread) { <add> common.skip('Cannot chdir to the tmp directory in workers'); <add>} <add> <add>tmpdir.refresh(); <add> <add>process.chdir(tmpdir.path); <add>fs.writeFileSync( <add> 'preload.js', <add> 'console.log(JSON.stringify(process.argv));', <add> 'utf-8'); <add> <add>fs.writeFileSync( <add> 'main.js', <add> 'console.log(JSON.stringify(process.argv));', <add> 'utf-8'); <add> <add>const child = spawnSync(process.execPath, ['-r', './preload.js', 'main.js']); <add> <add>if (child.status !== 0) { <add> console.log(child.stderr.toString()); <add> assert.strictEqual(child.status, 0); <add>} <add> <add>const lines = child.stdout.toString().trim().split('\n'); <add>assert.deepStrictEqual(JSON.parse(lines[0]), JSON.parse(lines[1]));
3
Ruby
Ruby
correct safe_system doc link
8eb176f50bb0eee4671c1a24f1f5701a77742eba
<ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(url) <ide> end <ide> end <ide> <del># Raised by {#safe_system} in `utils.rb`. <add># Raised by {Kernel#safe_system} in `utils.rb`. <ide> class ErrorDuringExecution < RuntimeError <ide> attr_reader :cmd, :status, :output <ide>
1
PHP
PHP
replace strlen() with is_null()
8ccc8f4ed5cde0bca666def9acdd8aa31eecdd6e
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function isDirty($attribute = null) <ide> { <ide> $dirtyAttributes = $this->getDirty(); <ide> <del> if (strlen($attribute) > 0) return array_key_exists($attribute, $dirtyAttributes); <add> if ( ! is_null($attribute)) return array_key_exists($attribute, $dirtyAttributes); <ide> <ide> return count($dirtyAttributes) > 0; <ide> }
1
Java
Java
polish propertysource and environment javadoc
0756a6abfed06ed4590341c5c9b10b41ad633e25
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/Configuration.java <ide> * <h3>Using the {@code Environment} API</h3> <ide> * Externalized values may be looked up by injecting the Spring <ide> * {@link org.springframework.core.env.Environment Environment} into a <del> * {@code @Configuration} class: <add> * {@code @Configuration} class using the {@code @Autowired} or the {@code @Inject} <add> * annotation: <ide> * <pre class="code"> <ide> * &#064;Configuration <ide> * public class AppConfig { <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/PropertySource.java <ide> * } <ide> * }</pre> <ide> * <del> * Notice that the {@code Environment} object is @{@link Autowired} into the <del> * configuration class and then used when populating the {@code TestBean} <del> * object. Given the configuration above, a call to {@code testBean.getName()} will <del> * return "myTestBean". <add> * Notice that the {@code Environment} object is @{@link <add> * org.springframework.beans.factory.annotation.Autowired Autowired} into the <add> * configuration class and then used when populating the {@code TestBean} object. Given <add> * the configuration above, a call to {@code testBean.getName()} will return "myTestBean". <ide> * <ide> * <h3>A note on property overriding with @PropertySource</h3> <ide> * In cases where a given property key exists in more than one {@code .properties} <ide> * if the {@code @Configuration} classes above were registered via component-scanning, <ide> * the ordering is difficult to predict. In such cases - and if overriding is important - <ide> * it is recommended that the user fall back to using the programmatic PropertySource API. <del> * See {@link org.springframework.core.env.ConfigurableEnvironment ConfigurableEnvironment} and <del> * {@link org.springframework.core.env.MutablePropertySources MutablePropertySources} Javadoc <del> * for details. <del> <add> * See {@link org.springframework.core.env.ConfigurableEnvironment ConfigurableEnvironment} <add> * and * {@link org.springframework.core.env.MutablePropertySources MutablePropertySources} <add> * Javadoc for details. <ide> * <ide> * @author Chris Beams <ide> * @since 3.1 <add> * @see Configuration <add> * @see org.springframework.core.env.PropertySource <add> * @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources() <add> * @see org.springframework.core.env.MutablePropertySources <ide> */ <ide> @Target(ElementType.TYPE) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Documented <ide> public @interface PropertySource { <ide> <ide> /** <del> * Indicate the name of this PropertySource. If omitted, a name <add> * Indicate the name of this property source. If omitted, a name <ide> * will be generated based on the description of the underlying <ide> * resource. <ide> * @see org.springframework.core.env.PropertySource#getName() <ide><path>org.springframework.core/src/main/java/org/springframework/core/env/PropertySource.java <ide> * Abstract base class representing a source of key/value property pairs. The underlying <ide> * {@linkplain #getSource() source object} may be of any type {@code T} that encapsulates <ide> * properties. Examples include {@link java.util.Properties} objects, {@link java.util.Map} <del> * objects, {@code ServletContext} and {@code ServletConfig} objects (for access to init parameters). <del> * Explore the {@code PropertySource} type hierarchy to see provided implementations. <add> * objects, {@code ServletContext} and {@code ServletConfig} objects (for access to init <add> * parameters). Explore the {@code PropertySource} type hierarchy to see provided <add> * implementations. <ide> * <del> * <p>{@code PropertySource} objects are not typically used in isolation, but rather through a <del> * {@link PropertySources} object, which aggregates property sources and in conjunction with <del> * a {@link PropertyResolver} implementation that can perform precedence-based searches across <del> * the set of {@code PropertySources}. <add> * <p>{@code PropertySource} objects are not typically used in isolation, but rather <add> * through a {@link PropertySources} object, which aggregates property sources and in <add> * conjunction with a {@link PropertyResolver} implementation that can perform <add> * precedence-based searches across the set of {@code PropertySources}. <ide> * <del> * <p>{@code PropertySource} identity is determined not based on the content of encapsulated <del> * properties, but rather based on the {@link #getName() name} of the {@code PropertySource} <del> * alone. This is useful for manipulating {@code PropertySource} objects when in collection <del> * contexts. See operations in {@link MutablePropertySources} as well as the <del> * {@link #named(String)} and {@link #toString()} methods for details. <add> * <p>{@code PropertySource} identity is determined not based on the content of <add> * encapsulated properties, but rather based on the {@link #getName() name} of the <add> * {@code PropertySource} alone. This is useful for manipulating {@code PropertySource} <add> * objects when in collection contexts. See operations in {@link MutablePropertySources} <add> * as well as the {@link #named(String)} and {@link #toString()} methods for details. <add> * <add> * <p>Note that when working with @{@link <add> * org.springframework.context.annotation.Configuration Configuration} classes that <add> * the @{@link org.springframework.context.annotation.PropertySource PropertySource} <add> * annotation provides a convenient and declarative way of adding property sources to the <add> * enclosing {@code Environment}. <ide> * <ide> * @author Chris Beams <ide> * @since 3.1 <ide> * @see PropertySources <ide> * @see PropertyResolver <ide> * @see PropertySourcesPropertyResolver <ide> * @see MutablePropertySources <add> * @see org.springframework.context.annotation.PropertySource <ide> */ <ide> public abstract class PropertySource<T> { <ide> <ide><path>org.springframework.core/src/main/java/org/springframework/core/env/StandardEnvironment.java <ide> * {@link org.springframework.context.support.AbstractApplicationContext#refresh() <ide> * refresh()} method is called. This ensures that all PropertySources are available during <ide> * the container bootstrap process, including use by <del> * {@link org.springframework.context.support.PropertySourcesPlaceholderConfigurer <add> * {@linkplain org.springframework.context.support.PropertySourcesPlaceholderConfigurer <ide> * property placeholder configurers}. <ide> * <ide> * @author Chris Beams <ide> public class StandardEnvironment extends AbstractEnvironment { <ide> * </ul> <ide> * <p>Properties present in {@value #SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME} will <ide> * take precedence over those in {@value #SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME}. <add> * @see AbstractEnvironment#customizePropertySources(MutablePropertySources) <ide> * @see #getSystemProperties() <ide> * @see #getSystemEnvironment() <ide> */ <ide><path>org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/context/StandardPortletEnvironment.java <ide> public class StandardPortletEnvironment extends StandardEnvironment { <ide> * initialized} once the actual {@link PortletConfig}, {@link PortletContext}, and <ide> * {@link ServletContext} objects are available. <ide> * @see StandardEnvironment#customizePropertySources <add> * @see org.springframework.core.env.AbstractEnvironment#customizePropertySources <ide> * @see PortletConfigPropertySource <ide> * @see PortletContextPropertySource <ide> * @see AbstractRefreshablePortletApplicationContext#initPropertySources <ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/StandardServletEnvironment.java <ide> public class StandardServletEnvironment extends StandardEnvironment { <ide> * servlet property sources, but higher than system properties and environment <ide> * variables. <ide> * @see StandardEnvironment#customizePropertySources <add> * @see org.springframework.core.env.AbstractEnvironment#customizePropertySources <ide> * @see ServletConfigPropertySource <ide> * @see ServletContextPropertySource <ide> * @see org.springframework.jndi.JndiPropertySource
6
Text
Text
fix 1.13.0 changelog typo
e99e694502b2763b01bc09d5d7c818d9d8ffc991
<ide><path>CHANGELOG.md <ide> be found. <ide> - Pin images by digest for `docker service create` and `update` [#28173](https://github.com/docker/docker/pull/28173) <ide> - Add short (`-f`) flag for `docker node rm --force` and `docker swarm leave --force` [#28196](https://github.com/docker/docker/pull/28196) <ide> + Don't repull image if pinned by digest [#28265](https://github.com/docker/docker/pull/28265) <del>+ swarm-mode support for indows [#27838](https://github.com/docker/docker/pull/27838) <add>+ swarm-mode support for Windows [#27838](https://github.com/docker/docker/pull/27838) <ide> <ide> ### Volume <ide>
1
Text
Text
add example for zlib.creategzip()
57ed7c33b1e142c8df9b57f0907055774e8b46c4
<ide><path>doc/api/zlib.md <ide> const fs = require('fs'); <ide> const inp = fs.createReadStream('input.txt'); <ide> const out = fs.createWriteStream('input.txt.gz'); <ide> <del>inp.pipe(gzip).pipe(out); <add>inp.pipe(gzip) <add> .on('error', () => { <add> // handle error <add> }) <add> .pipe(out) <add> .on('error', () => { <add> // handle error <add> }); <ide> ``` <ide> <ide> It is also possible to compress or decompress data in a single step: <ide> added: v0.5.8 <ide> * `options` {zlib options} <ide> <ide> Creates and returns a new [`Gzip`][] object. <add>See [example][zlib.createGzip example]. <ide> <ide> ## zlib.createInflate([options]) <ide> <!-- YAML <ide> Decompress a chunk of data with [`Unzip`][]. <ide> [RFC 7932]: https://www.rfc-editor.org/rfc/rfc7932.txt <ide> [pool size]: cli.html#cli_uv_threadpool_size_size <ide> [zlib documentation]: https://zlib.net/manual.html#Constants <add>[zlib.createGzip example]: #zlib_zlib
1
Text
Text
apply suggestions from code review
bf873783d20bfe170d442157c08d615c42fa80af
<ide><path>docs/New-Maintainer-Checklist.md <ide> changes (e.g. version updates), triaging, fixing and debugging user-reported <ide> issues, or reviewing user pull requests. You should also be making contributions <ide> to Homebrew at least once per quarter. <ide> <del>You will should watch or regularly check Homebrew/brew and/or <add>You should watch or regularly check Homebrew/brew and/or <ide> Homebrew/homebrew-core. Let us know which (or both) so we can grant you commit <ide> access appropriately. <ide> <ide> If they are interested in doing system administration work or Homebrew/brew rele <ide> - Invite them to the [`homebrew-ops` private operations mailing list](https://lists.sfconservancy.org/mailman/admin/homebrew-ops/members/add). <ide> - Invite them to the [`homebrew` private 1Password](https://homebrew.1password.com/people). <ide> <del>If they are elected to of the Homebrew's [Software Freedom Conservancy](https://sfconservancy.org) Project Leadership Committee: <add>If they are elected to the Homebrew's [Software Freedom Conservancy](https://sfconservancy.org) Project Leadership Committee: <ide> <ide> - Email their name, email and employer to homebrew@sfconservancy.org <ide> - Make them [owners on the Homebrew GitHub organisation](https://github.com/orgs/Homebrew/people) <ide><path>docs/Releases.md <ide> Homebrew release: <ide> branch you can create a new Git tag. Ideally this should be signed with your <ide> GPG key. This can then be pushed to GitHub. <ide> 3. Use `brew release-notes --markdown $PREVIOUS_TAG` to generate the release <del> notes for the release. [Create a new release on GitHub](https://github.com/Homebrew/brew/releases) <add> notes for the release. [Create a new release on GitHub](https://github.com/Homebrew/brew/releases/new) <ide> based on the new tag. <ide> <ide> If this is a major or minor release (e.g. X.0.0 or X.Y.0) then there are a few more steps:
2
Text
Text
add changes for v1.5.10
c6842b5a65b49aedb35d5b2dd8e430169a5a455d
<ide><path>CHANGELOG.md <add><a name="1.5.10"></a> <add># 1.5.10 asynchronous-synchronization (2016-12-15) <add> <add> <add>## Bug Fixes <add>- **$compile:** <add> - don't throw tplrt error when there is whitespace around a top-level comment <add> ([12752f](https://github.com/angular/angular.js/commit/12752f66ac425ab38a5ee574a4bfbf3516adc42c) <add> [#15108](https://github.com/angular/angular.js/issues/15108)) <add> - clean up `@`-binding observers when re-assigning bindings <add> ([f3cb6e](https://github.com/angular/angular.js/commit/f3cb6e309aa1f676e5951ac745fa886d3581c2f4) <add> [#15268](https://github.com/angular/angular.js/issues/15268)) <add> - set attribute value even if `ngAttr*` contains no interpolation <add> ([229799](https://github.com/angular/angular.js/commit/22979904fb754c59e9f6ee5d8763e3b8de0e18c2) <add> [#15133](https://github.com/angular/angular.js/issues/15133)) <add> - `bindToController` should work without `controllerAs` <add> ([944989](https://github.com/angular/angular.js/commit/9449893763a4fd95ee8ff78b53c6966a874ec9ae) <add> [#15088](https://github.com/angular/angular.js/issues/15088)) <add> - do not overwrite values set in `$onInit()` for `<`-bound literals <add> ([07e1ba](https://github.com/angular/angular.js/commit/07e1ba365fb5e8a049be732bd7b62f71e0aa1672) <add> [#15118](https://github.com/angular/angular.js/issues/15118)) <add> - avoid calling `$onChanges()` twice for `NaN` initial values <add> ([0cf5be](https://github.com/angular/angular.js/commit/0cf5be52642f7e9d81a708b3005042eac6492572)) <add>- **$location:** prevent infinite digest with IDN urls in Edge <add> ([4bf892](https://github.com/angular/angular.js/commit/4bf89218130d434771089fdfe643490b8d2ee259) <add> [#15217](https://github.com/angular/angular.js/issues/15217)) <add>- **$rootScope:** correctly handle adding/removing watchers during `$digest` <add> ([a9708d](https://github.com/angular/angular.js/commit/a9708de84b50f06eacda33834d5bbdfc97c97f37) <add> [#15422](https://github.com/angular/angular.js/issues/15422)) <add>- **$sce:** fix `adjustMatcher` to replace multiple `*` and `**` <add> ([78eecb](https://github.com/angular/angular.js/commit/78eecb43dbb0500358d333aea8955bd0646a7790)) <add>- **jqLite:** silently ignore `after()` if element has no parent <add> ([77ed85](https://github.com/angular/angular.js/commit/77ed85bcd3be057a5a79231565ac7accc6d644c6) <add> [#15331](https://github.com/angular/angular.js/issues/15331)) <add>- **input[radio]:** use non-strict comparison for checkedness <add> ([593a50](https://github.com/angular/angular.js/commit/593a5034841b3b7661d3bcbdd06b7a9d0876fd34)) <add>- **select, ngOptions:** <add> - let `ngValue` take precedence over option text with multiple interpolations <add> ([5b7ec8](https://github.com/angular/angular.js/commit/5b7ec8c84e88ee08aacaf9404853eda0016093f5) <add> [#15413](https://github.com/angular/angular.js/issues/15413)) <add> - don't add comment nodes as empty options <add> ([1d29c9](https://github.com/angular/angular.js/commit/1d29c91c3429de96e4103533752700d1266741be) <add> [#15454](https://github.com/angular/angular.js/issues/15454)) <add>- **ngClassOdd/Even:** add/remove the correct classes when expression/`$index` change simultaneously <add> ([e3d020](https://github.com/angular/angular.js/commit/e3d02070ab8a02c818dcc5114db6fba9d3f385d6)) <add>- **$resource:** allow params in `hostname` (except for IPv6 addresses) <add> ([7f45b5](https://github.com/angular/angular.js/commit/7f45b5fee79e2cb87d65bdd015d455304cec1ee4) <add> [#14542](https://github.com/angular/angular.js/issues/14542)) <add>- **$sanitize:** reduce stack height in IE <= 11 <add> ([862dc2](https://github.com/angular/angular.js/commit/862dc2532f8126a4a71fd3d957884ba6f11f591c) <add> [#14928](https://github.com/angular/angular.js/issues/14928)) <add>- **ngMock/$controller:** respect `$compileProvider.preAssignBindingsEnabled()` <add> ([75c83f](https://github.com/angular/angular.js/commit/75c83ff3195931859a099f7a95bf81d32abf2eb3)) <add> <add> <add>## New Features <add>- **bootstrap:** do not bootstrap from unknown schemes with a different origin <add> ([bdeb33](https://github.com/angular/angular.js/commit/bdeb3392a8719131ab2b993f2a881c43a2860f92) <add> [#15428](https://github.com/angular/angular.js/issues/15428)) <add>- **$anchorScroll:** convert numeric hash targets to string <add> ([a52640](https://github.com/angular/angular.js/commit/a5264090b66ad0cf9a93de84bb7b307868c0edef) <add> [#14680](https://github.com/angular/angular.js/issues/14680)) <add>- **$compile:** <add> - add `preAssignBindingsEnabled` option <add> ([f86576](https://github.com/angular/angular.js/commit/f86576def44005f180a66e3aa12d6cc73c1ac72c)) <add> - throw error when directive name or factory function is invalid <add> ([5c9399](https://github.com/angular/angular.js/commit/5c9399d18ae5cd79e6cf6fc4377d66df00f6fcc7) <add> [#15056](https://github.com/angular/angular.js/issues/15056)) <add>- **$controller:** throw when requested controller is not registered <add> ([9ae793](https://github.com/angular/angular.js/commit/9ae793d8a69afe84370b601e07fc375fc18a576a) <add> [#14980](https://github.com/angular/angular.js/issues/14980)) <add>- **$location:** add support for selectively rewriting links based on attribute <add> ([a4a222](https://github.com/angular/angular.js/commit/a4a22266f127d3b9a6818e6f4754f048e253f693)) <add>- **$resource:** pass `status`/`statusText` to success callbacks <add> ([a8da25](https://github.com/angular/angular.js/commit/a8da25c74d2c1f6265f0fafd95bf72c981d9d678) <add> [#8341](https://github.com/angular/angular.js/issues/8841) <add> [#8841](https://github.com/angular/angular.js/issues/8841)) <add>- **ngSwitch:** allow multiple case matches via optional attribute `ngSwitchWhenSeparator` <add> ([0e1651](https://github.com/angular/angular.js/commit/0e1651bfd28ba73ebd0e4943d85af48c4506e02c) <add> [#3410](https://github.com/angular/angular.js/issues/3410) <add> [#3516](https://github.com/angular/angular.js/issues/3516)) <add> <add> <add>## Performance Improvements <add>- **all:** don't trigger digests after enter/leave of structural directives <add> ([c57779](https://github.com/angular/angular.js/commit/c57779d8725493c5853dceda0105dafd5c0e3a7c) <add> [#15322](https://github.com/angular/angular.js/issues/15322)) <add>- **$compile:** validate `directive.restrict` property on directive init <add> ([31d464](https://github.com/angular/angular.js/commit/31d464feef38b1cc950da6c8dccd0f194ebfc68b)) <add>- **ngOptions:** avoid calls to `element.value` <add> ([e269ad](https://github.com/angular/angular.js/commit/e269ad1244bc50fee9218f7c18fab3e9ab063aab)) <add>- **jqLite:** move bind/unbind definitions out of the loop <add> ([7717b9](https://github.com/angular/angular.js/commit/7717b96e950a5916a5f12fd611c73d3b06a8d717)) <add> <add> <ide> <a name="1.6.0"></a> <ide> # 1.6.0 rainbow-tsunami (2016-12-08) <ide>
1
PHP
PHP
add doc blocks for validator methods
ca89846ff7060252f5f5bb4af8226a7610235aea
<ide><path>src/Validation/Validator.php <ide> public function allowEmpty($field, $when = true) <ide> * method called will take precedence. <ide> * <ide> * @param string $field the name of the field <del> * @param string $message The validation message to show if the field is not <add> * @param string $message The message to show if the field is not <ide> * @param bool|string|callable $when Indicates when the field is not allowed <ide> * to be empty. Valid values are true (always), 'create', 'update'. If a <ide> * callable is passed then the field will allowed be empty only when <ide> public function notEmpty($field, $message = null, $when = false) <ide> return $this; <ide> } <ide> <add> /** <add> * Add a notBlank rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::notBlank() <add> */ <ide> public function notBlank($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function notBlank($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an alphanumeric rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::alphaNumeric() <add> */ <ide> public function alphaNumeric($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function alphaNumeric($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an rule that ensures a string length is within a range. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $range The inclusive minimum and maximum length you want permitted. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::alphaNumeric() <add> */ <ide> public function lengthBetween($field, array $range, $message = null, $when = null) <ide> { <ide> if (count($range) !== 2) { <ide> public function lengthBetween($field, array $range, $message = null, $when = nul <ide> ]); <ide> } <ide> <add> /** <add> * Add a credit card rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $type The type of cards you want to allow. Defaults to 'all'. <add> * You can also supply an array of accepted card types. e.g `['mastercard', 'visa', 'amex']` <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::cc() <add> */ <ide> public function creditCard($field, $type = 'all', $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function creditCard($field, $type = 'all', $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a greater than comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be greater than. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function greaterThan($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function greaterThan($field, $value, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a greater than or equal to comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be greater than or equal to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function greaterThanOrEqual($field, $value, $message = null, $when = null <ide> ]); <ide> } <ide> <add> /** <add> * Add a less than comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be less than. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function lessThan($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function lessThan($field, $value, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a less than or equal comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be less than or equal to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function lessThanOrEqual($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function lessThanOrEqual($field, $value, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a equal to comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be equal to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function equals($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function equals($field, $value, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a not equal to comparison rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int|float $value The value user data must be not be equal to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::comparison() <add> */ <ide> public function notEquals($field, $value, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function notEquals($field, $value, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a rule to compare two fields to each other. <add> * <add> * If both fields have the exact same value the rule will pass. <add> * <add> * @param mixed $field The field you want to apply the rule to. <add> * @param mixed $secondField The field you want to compare against. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::compareWith() <add> */ <ide> public function sameAs($field, $secondField, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function sameAs($field, $secondField, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a rule to check if a field contains non alpha numeric characters. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int $limit The minimum number of non-alphanumeric fields required. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::containsNonAlphaNumeric() <add> */ <ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function containsNonAlphaNumeric($field, $limit = 1, $message = null, $wh <ide> ]); <ide> } <ide> <add> /** <add> * Add a date format validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $format A list of accepted date formats. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::date() <add> */ <ide> public function date($field, $formats = ['ymd'], $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function date($field, $formats = ['ymd'], $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a date time format validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $format A list of accepted date formats. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::datetime() <add> */ <ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function dateTime($field, $formats = ['ymd'], $message = null, $when = nu <ide> ]); <ide> } <ide> <add> /** <add> * Add a time format validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $format A list of accepted date formats. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::time() <add> */ <ide> public function time($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function time($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a boolean validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::boolean() <add> */ <ide> public function boolean($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function boolean($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a decimal validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int $places The number of decimal places to require. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::decimal() <add> */ <ide> public function decimal($field, $places = null, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function decimal($field, $places = null, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an email validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param bool $checkMX Whether or not to check the MX records. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::email() <add> */ <ide> public function email($field, $checkMX = false, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function email($field, $checkMX = false, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an IP validation rule to a field. <add> * <add> * This rule will accept both IPv4 and IPv6 addresses. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::ip() <add> */ <ide> public function ip($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function ip($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an IPv4 validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::ip() <add> */ <ide> public function ipv4($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function ipv4($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add an IPv6 validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::ip() <add> */ <ide> public function ipv6($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function ipv6($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a string length validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int $min The minimum length required. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::minLength() <add> */ <ide> public function minLength($field, $min, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function minLength($field, $min, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a string length validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param int $max The maximum length allowed. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::maxLength() <add> */ <ide> public function maxLength($field, $max, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function maxLength($field, $max, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a numeric value validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::numeric() <add> */ <ide> public function numeric($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function numeric($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a natural number validation rule to a field. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::naturalNumber() <add> */ <ide> public function naturalNumber($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function naturalNumber($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field is a non negative integer. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::naturalNumber() <add> */ <ide> public function nonNegativeInteger($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function nonNegativeInteger($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field is within a numeric range <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $range The inclusive upper and lower bounds of the valid range. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::range() <add> */ <ide> public function range($field, array $range, $message = null, $when = null) <ide> { <ide> if (count($range) !== 2) { <ide> public function range($field, array $range, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field is a URL. <add> * <add> * This validator does not require a protocol. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::url() <add> */ <ide> public function url($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function url($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field is a URL. <add> * <add> * This validator requires the URL to have a protocol. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::url() <add> */ <ide> public function urlWithProtocol($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function urlWithProtocol($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field value is within a whitelist. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $list The list of valid options. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::inList() <add> */ <ide> public function inList($field, array $list, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function inList($field, array $list, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field is a UUID <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::uuid() <add> */ <ide> public function uuid($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function uuid($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field is an uploaded file <add> * <add> * For options see Cake\Validation\Validation::uploadedFile() <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param array $options An array of options. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::uploadedFile() <add> */ <ide> public function uploadedFile($field, array $options, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function uploadedFile($field, array $options, $message = null, $when = nu <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field is a lat/long tuple. <add> * <add> * e.g. `<lat>, <lng>` <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::uuid() <add> */ <ide> public function latLong($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function latLong($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field is a latitude. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::latitude() <add> */ <ide> public function latitude($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function latitude($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure the field is a longitude. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::longitude() <add> */ <ide> public function longitude($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function longitude($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field contains only ascii bytes <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::ascii() <add> */ <ide> public function ascii($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function ascii($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field contains only BMP utf8 bytes <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::utf8() <add> */ <ide> public function utf8($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide> public function utf8($field, $message = null, $when = null) <ide> ]); <ide> } <ide> <del> public function utf8Strict($field, $message = null, $when = null) <add> /** <add> * Add a validation rule to ensure a field contains only utf8 bytes. <add> * <add> * This rule will accept 3 and 4 byte UTF8 sequences, which are necessary for emoji. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::utf8() <add> */ <add> public function utf8Extended($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <del> return $this->add($field, 'utf8Strict', $extra + [ <add> return $this->add($field, 'utf8Extended', $extra + [ <ide> 'rule' => ['utf8', ['extended' => true]] <ide> ]); <ide> } <ide> <add> /** <add> * Add a validation rule to ensure a field is an integer value. <add> * <add> * @param string $field The field you want to apply the rule to. <add> * @param string $message The error message when the rule fails. <add> * @param string|callable $when Either 'create' or 'update' or a callable that returns <add> * true when the valdiation rule should be applied. <add> * @see Cake\Validation\Validation::isInteger() <add> */ <ide> public function integer($field, $message = null, $when = null) <ide> { <ide> $extra = array_filter(['on' => $when, 'message' => $message]); <ide><path>tests/TestCase/Validation/ValidatorTest.php <ide> public function testUtf8() <ide> $this->assertProxyMethod($validator, 'utf8', null, [['extended' => false]]); <ide> $this->assertEmpty($validator->errors(['username' => 'ü'])); <ide> <del> $this->assertProxyMethod($validator, 'utf8Strict', null, [['extended' => true]], 'utf8'); <add> $this->assertProxyMethod($validator, 'utf8Extended', null, [['extended' => true]], 'utf8'); <ide> $this->assertEmpty($validator->errors(['username' => 'ü'])); <ide> } <ide>
2
Ruby
Ruby
restore previous style
88a69b3de20e0faa12f8dee2c2298617d76b55ec
<ide><path>Library/Homebrew/build.rb <ide> def install <ide> ENV.keg_only_deps = keg_only_deps <ide> ENV.deps = formula_deps <ide> ENV.run_time_deps = run_time_deps <del> ENV.setup_build_environment(formula: formula, cc: args.cc, build_bottle: args.build_bottle?, <del> bottle_arch: args.bottle_arch, debug_symbols: args.debug_symbols?) <add> ENV.setup_build_environment( <add> formula: formula, <add> cc: args.cc, <add> build_bottle: args.build_bottle?, <add> bottle_arch: args.bottle_arch, <add> debug_symbols: args.debug_symbols?, <add> ) <ide> reqs.each do |req| <ide> req.modify_build_environment( <ide> env: args.env, cc: args.cc, build_bottle: args.build_bottle?, bottle_arch: args.bottle_arch, <ide> ) <ide> end <ide> deps.each(&:modify_build_environment) <ide> else <del> ENV.setup_build_environment(formula: formula, cc: args.cc, build_bottle: args.build_bottle?, <del> bottle_arch: args.bottle_arch, debug_symbols: args.debug_symbols?) <add> ENV.setup_build_environment( <add> formula: formula, <add> cc: args.cc, <add> build_bottle: args.build_bottle?, <add> bottle_arch: args.bottle_arch, <add> debug_symbols: args.debug_symbols?, <add> ) <ide> reqs.each do |req| <ide> req.modify_build_environment( <ide> env: args.env, cc: args.cc, build_bottle: args.build_bottle?, bottle_arch: args.bottle_arch,
1
PHP
PHP
status command
c5d02773392041b28dec8855aeee85246b8d7d17
<ide><path>src/Illuminate/Database/Console/Migrations/StatusCommand.php <ide> public function handle() <ide> } <ide> <ide> $ran = $this->migrator->getRepository()->getRan(); <add> $migrationsBatches = $this->migrator->getRepository()->getMigrationsBatches(); <ide> <del> if (count($migrations = $this->getStatusFor($ran)) > 0) { <del> $this->table(['Ran?', 'Migration'], $migrations); <add> if (count($migrations = $this->getStatusFor($ran, $migrationsBatches)) > 0) { <add> $this->table(['Ran?', 'Migration', 'Batch'], $migrations); <ide> } else { <ide> $this->error('No migrations found'); <ide> } <ide> public function handle() <ide> * Get the status for the given ran migrations. <ide> * <ide> * @param array $ran <add> * @param array $migrationsBatches <ide> * @return \Illuminate\Support\Collection <ide> */ <del> protected function getStatusFor(array $ran) <add> protected function getStatusFor(array $ran, array $migrationsBatches) <ide> { <ide> return Collection::make($this->getAllMigrationFiles()) <del> ->map(function ($migration) use ($ran) { <add> ->map(function ($migration) use ($ran, $migrationsBatches) { <ide> $migrationName = $this->migrator->getMigrationName($migration); <ide> <ide> return in_array($migrationName, $ran) <del> ? ['<info>Y</info>', $migrationName] <add> ? ['<info>Y</info>', $migrationName, $migrationsBatches[$migrationName]] <ide> : ['<fg=red>N</fg=red>', $migrationName]; <ide> }); <ide> } <ide><path>src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php <ide> public function getRan() <ide> ->pluck('migration')->all(); <ide> } <ide> <add> /** <add> * Get the ran migrations with batch numbers. <add> * <add> * @return array <add> */ <add> public function getMigrationsBatches() <add> { <add> return $this->table() <add> ->orderBy('batch', 'asc') <add> ->orderBy('migration', 'asc') <add> ->pluck('batch', 'migration')->all(); <add> } <add> <ide> /** <ide> * Get list of migrations. <ide> * <ide><path>src/Illuminate/Database/Migrations/MigrationRepositoryInterface.php <ide> interface MigrationRepositoryInterface <ide> */ <ide> public function getRan(); <ide> <add> /** <add> * Get the ran migrations with batch numbers for a given package. <add> * <add> * @return array <add> */ <add> public function getMigrationsBatches(); <add> <ide> /** <ide> * Get list of migrations. <ide> *
3
Text
Text
fix broken link to commonjs.
25f8a6c92773967d20641c6c239f31c1b01dd459
<ide><path>docs/introduction/Installation.md <ide> This assumes you are using [npm](https://www.npmjs.com/) as your package manager <ide> <ide> If you're not, you can [access these files on unpkg](https://unpkg.com/redux/), download them, or point your package manager to them. <ide> <del>Most commonly, people consume Redux as a collection of [CommonJS](http://webpack.github.io/docs/commonjs.html) modules. These modules are what you get when you import `redux` in a [Webpack](https://webpack.js.org/), [Browserify](http://browserify.org/), or a Node environment. If you like to live on the edge and use [Rollup](https://rollupjs.org), we support that as well. <add>Most commonly, people consume Redux as a collection of [CommonJS](http://www.commonjs.org/) modules. These modules are what you get when you import `redux` in a [Webpack](https://webpack.js.org/), [Browserify](http://browserify.org/), or a Node environment. If you like to live on the edge and use [Rollup](https://rollupjs.org), we support that as well. <ide> <ide> If you don't use a module bundler, it's also fine. The `redux` npm package includes precompiled production and development [UMD](https://github.com/umdjs/umd) builds in the [`dist` folder](https://unpkg.com/redux/dist/). They can be used directly without a bundler and are thus compatible with many popular JavaScript module loaders and environments. For example, you can drop a UMD build as a [`<script>` tag](https://unpkg.com/redux/dist/redux.js) on the page, or [tell Bower to install it](https://github.com/reduxjs/redux/pull/1181#issuecomment-167361975). The UMD builds make Redux available as a `window.Redux` global variable. <ide>
1
Javascript
Javascript
fix peer deps for use-sync-external-store
e39b2c8998a458a772b9284d0fb9f6a5ccdda914
<ide><path>scripts/rollup/build-all-release-channels.js <ide> function buildForChannel(channel, nodeTotal, nodeIndex) { <ide> <ide> function processStable(buildDir) { <ide> if (fs.existsSync(buildDir + '/node_modules')) { <add> // Identical to `oss-stable` but with real, semver versions. This is what <add> // will get published to @latest. <add> spawnSync('cp', [ <add> '-r', <add> buildDir + '/node_modules', <add> buildDir + '/oss-stable-semver', <add> ]); <add> <ide> const defaultVersionIfNotFound = '0.0.0' + '-' + sha + '-' + dateString; <ide> const versionsMap = new Map(); <ide> for (const moduleName in stablePackages) { <ide> function processStable(buildDir) { <ide> ); <ide> fs.renameSync(buildDir + '/node_modules', buildDir + '/oss-stable'); <ide> <del> // Identical to `oss-stable` but with real, semver versions. This is what <del> // will get published to @latest. <del> spawnSync('cp', [ <del> '-r', <del> buildDir + '/oss-stable', <del> buildDir + '/oss-stable-semver', <del> ]); <add> // Now do the semver ones <ide> const semverVersionsMap = new Map(); <ide> for (const moduleName in stablePackages) { <ide> const version = stablePackages[moduleName];
1
PHP
PHP
check type of token
bdb839222d85de0c0f1f68263d61e358f0ec813c
<ide><path>app/Http/Middleware/VerifyCsrfToken.php <ide> public function handle($request, Closure $next) <ide> */ <ide> protected function tokensMatch($request) <ide> { <del> return $request->session()->token() == $request->input('_token'); <add> return $request->session()->token() === $request->input('_token'); <ide> } <ide> <ide> /**
1
Python
Python
fix error in oldnumeric.empty
9b0c090eaa73c7646dbc163cf2ff85a59e2109dc
<ide><path>numpy/oldnumeric/functions.py <ide> def identity(n,typecode='l', dtype=None): <ide> <ide> def empty(shape, typecode='l', dtype=None): <ide> dtype = convtypecode(typecode, dtype) <del> return mu.empty(shape, dtype, order) <add> return mu.empty(shape, dtype) <ide> <ide> def array(sequence, typecode=None, copy=1, savespace=0, dtype=None): <ide> dtype = convtypecode2(typecode, dtype)
1
Javascript
Javascript
remove unused function argument
b161440cd3c846734c7355340483b03d5db3ba00
<ide><path>lib/internal/webstreams/readablestream.js <ide> function readableStreamPipeTo( <ide> <ide> function watchClosed(stream, promise, action) { <ide> if (stream[kState].state === 'closed') <del> action(stream[kState].storedError); <add> action(); <ide> else <ide> PromisePrototypeThen(promise, action, () => {}); <ide> }
1
PHP
PHP
remove unused directories
c673b815f7cbed1ed746332df9eaf5a036c3dc1c
<ide><path>src/Console/Command/Task/PluginTask.php <ide> public function bake($plugin) { <ide> if (strtolower($looksGood) === 'y') { <ide> $Folder = new Folder($this->path . $plugin); <ide> $directories = [ <del> $classBase . DS . 'Config' . DS . 'Schema', <add> $classBase . DS . 'Config', <ide> $classBase . DS . 'Model' . DS . 'Behavior', <ide> $classBase . DS . 'Model' . DS . 'Table', <ide> $classBase . DS . 'Model' . DS . 'Entity', <ide> $classBase . DS . 'Console' . DS . 'Command' . DS . 'Task', <ide> $classBase . DS . 'Controller' . DS . 'Component', <del> $classBase . DS . 'Lib', <ide> $classBase . DS . 'View' . DS . 'Helper', <ide> $classBase . DS . 'Template', <ide> 'tests' . DS . 'TestCase' . DS . 'Controller' . DS . 'Component',
1
Go
Go
create file containing pid
fb0b375be70e79eaa8349143dceef048db6e0e19
<ide><path>docker/docker.go <ide> package main <ide> <ide> import ( <ide> "flag" <add> "fmt" <ide> "github.com/dotcloud/docker" <ide> "github.com/dotcloud/docker/rcli" <ide> "github.com/dotcloud/docker/term" <ide> "io" <ide> "log" <ide> "os" <add> "os/signal" <add> "syscall" <ide> ) <ide> <ide> var GIT_COMMIT string <ide> func main() { <ide> flDaemon := flag.Bool("d", false, "Daemon mode") <ide> flDebug := flag.Bool("D", false, "Debug mode") <ide> bridgeName := flag.String("b", "", "Attach containers to a pre-existing network bridge") <add> pidfile := flag.String("p", "/var/run/docker.pid", "File containing process PID") <ide> flag.Parse() <ide> if *bridgeName != "" { <ide> docker.NetworkBridgeIface = *bridgeName <ide> func main() { <ide> flag.Usage() <ide> return <ide> } <del> if err := daemon(); err != nil { <add> if err := daemon(*pidfile); err != nil { <ide> log.Fatal(err) <ide> } <ide> } else { <ide> func main() { <ide> } <ide> } <ide> <del>func daemon() error { <add>func createPidFile(pidfile string) error { <add> if _, err := os.Stat(pidfile); err == nil { <add> return fmt.Errorf("pid file found, ensure docker is not running or delete %s", pidfile) <add> } <add> <add> file, err := os.Create(pidfile) <add> if err != nil { <add> return err <add> } <add> <add> defer file.Close() <add> <add> _, err = fmt.Fprintf(file, "%d", os.Getpid()) <add> return err <add>} <add> <add>func removePidFile(pidfile string) { <add> if err := os.Remove(pidfile); err != nil { <add> log.Printf("Error removing %s: %s", pidfile, err) <add> } <add>} <add> <add>func daemon(pidfile string) error { <add> if err := createPidFile(pidfile); err != nil { <add> log.Fatal(err) <add> } <add> defer removePidFile(pidfile) <add> <add> c := make(chan os.Signal, 1) <add> signal.Notify(c, os.Interrupt, os.Kill, os.Signal(syscall.SIGTERM)) <add> go func() { <add> sig := <-c <add> log.Printf("Received signal '%v', exiting\n", sig) <add> removePidFile(pidfile) <add> os.Exit(0) <add> }() <add> <ide> service, err := docker.NewServer() <ide> if err != nil { <ide> return err
1
Javascript
Javascript
remove trailing tabs
32e803c5bc821a34d6d225659f7a4b4a24053e07
<ide><path>build/tasks/build.js <ide> module.exports = function( grunt ) { <ide> // Ignore jQuery's return statement (the only necessary one) <ide> if ( name !== "jquery" ) { <ide> contents = contents <del> .replace( /return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1" ); <add> .replace( /\s*return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1" ); <ide> } <ide> <ide> // Remove define wrappers, closure ends, and empty declarations <del> // Unless it's the proper AMD define <ide> contents = contents <ide> .replace( /define\([^{]*?{/, "" ) <ide> .replace( rdefineEnd, "" );
1
Ruby
Ruby
support aliases to expires_in for cache stores
fd8c36707f64776ce0f48379816083401ffe40fc
<ide><path>activesupport/lib/active_support/cache.rb <ide> module Cache <ide> <ide> # These options mean something to all cache implementations. Individual cache <ide> # implementations may support additional options. <del> UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl, :coder, :skip_nil] <add> UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :expire_in, :expired_in, :race_condition_ttl, :coder, :skip_nil] <add> <add> # Mapping of canonical option names to aliases that a store will recognize. <add> OPTION_ALIASES = { <add> expires_in: [:expire_in, :expired_in] <add> }.freeze <ide> <ide> module Strategy <ide> autoload :LocalCache, "active_support/cache/strategy/local_cache" <ide> def ensure_connection_pool_added! <ide> # except for <tt>:namespace</tt> which can be used to set the global <ide> # namespace for the cache. <ide> def initialize(options = nil) <del> @options = options ? options.dup : {} <add> @options = options ? normalize_options(options) : {} <ide> @coder = @options.delete(:coder) { self.class::DEFAULT_CODER } || NullCoder <ide> end <ide> <ide> def mute <ide> # All caches support auto-expiring content after a specified number of <ide> # seconds. This value can be specified as an option to the constructor <ide> # (in which case all entries will be affected), or it can be supplied to <del> # the +fetch+ or +write+ method to effect just one entry. <add> # the +fetch+ or +write+ method to affect just one entry. <add> # <tt>:expire_in</tt> and <tt>:expired_in</tt> are aliases for <add> # <tt>:expires_in</tt>. <ide> # <ide> # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes) <ide> # cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry <ide> def delete_multi_entries(entries, **options) <ide> # Merges the default options with ones specific to a method call. <ide> def merged_options(call_options) <ide> if call_options <add> call_options = normalize_options(call_options) <ide> if options.empty? <ide> call_options <ide> else <ide> def merged_options(call_options) <ide> end <ide> end <ide> <add> # Normalize aliased options to their canonical form <add> def normalize_options(options) <add> options = options.dup <add> OPTION_ALIASES.each do |canonical_name, aliases| <add> alias_key = aliases.detect { |key| options.key?(key) } <add> options[canonical_name] ||= options[alias_key] if alias_key <add> options.except!(*aliases) <add> end <add> options <add> end <add> <ide> # Expands and namespaces the cache key. May be overridden by <ide> # cache stores to do additional normalization. <ide> def normalize_key(key, options = nil) <ide><path>activesupport/test/cache/behaviors/cache_store_behavior.rb <ide> def test_expires_in <ide> end <ide> end <ide> <add> def test_expire_in_is_alias_for_expires_in <add> time = Time.local(2008, 4, 24) <add> <add> Time.stub(:now, time) do <add> @cache.write("foo", "bar", expire_in: 20) <add> assert_equal "bar", @cache.read("foo") <add> end <add> <add> Time.stub(:now, time + 10) do <add> assert_equal "bar", @cache.read("foo") <add> end <add> <add> Time.stub(:now, time + 21) do <add> assert_nil @cache.read("foo") <add> end <add> end <add> <add> def test_expired_in_is_alias_for_expires_in <add> time = Time.local(2008, 4, 24) <add> <add> Time.stub(:now, time) do <add> @cache.write("foo", "bar", expired_in: 20) <add> assert_equal "bar", @cache.read("foo") <add> end <add> <add> Time.stub(:now, time + 10) do <add> assert_equal "bar", @cache.read("foo") <add> end <add> <add> Time.stub(:now, time + 21) do <add> assert_nil @cache.read("foo") <add> end <add> end <add> <ide> def test_race_condition_protection_skipped_if_not_defined <ide> @cache.write("foo", "bar") <ide> time = @cache.send(:read_entry, @cache.send(:normalize_key, "foo", {}), **{}).expires_at
2
Javascript
Javascript
remove bower.json lint target
285cfbfccc4c61d50ee8e0fe6e23695dc663e166
<ide><path>Gruntfile.js <ide> module.exports = function( grunt ) { <ide> jsonlint: { <ide> pkg: { <ide> src: [ "package.json" ] <del> }, <del> <del> bower: { <del> src: [ "bower.json" ] <ide> } <ide> }, <ide> jshint: {
1
Javascript
Javascript
add stencil properties to material
5059d33b6fd73d6af9840aec93b4bdf0104d9db9
<ide><path>src/loaders/Loader.js <ide> THREE.Loader.prototype = { <ide> break; <ide> case 'depthTest': <ide> case 'depthWrite': <add> case 'stencilTest': <add> case 'stencilWrite': <ide> case 'colorWrite': <ide> case 'opacity': <ide> case 'reflectivity': <ide><path>src/loaders/MaterialLoader.js <ide> THREE.MaterialLoader.prototype = { <ide> if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest; <ide> if ( json.depthTest !== undefined ) material.depthTest = json.depthTest; <ide> if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite; <add> if ( json.stencilTest !== undefined ) material.stencilTest = json.stencilTest; <add> if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite; <ide> if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite; <ide> if ( json.wireframe !== undefined ) material.wireframe = json.wireframe; <ide> if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth; <ide><path>src/materials/Material.js <ide> THREE.Material = function () { <ide> this.depthTest = true; <ide> this.depthWrite = true; <ide> <add> this.stencilTest = false; <add> this.stencilWrite = false; <add> <ide> this.colorWrite = true; <ide> <ide> this.precision = null; // override the renderer's default precision for this material <ide> THREE.Material.prototype = { <ide> this.depthTest = source.depthTest; <ide> this.depthWrite = source.depthWrite; <ide> <add> this.stencilTest = source.stencilTest; <add> this.stencilWrite = source.stencilWrite; <add> <ide> this.colorWrite = source.colorWrite; <ide> <ide> this.precision = source.precision; <ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> <ide> } <ide> <del> // Ensure depth buffer writing is enabled so it can be cleared on next render <add> // Ensure buffer writing is enabled so they can be cleared on next render <ide> <ide> state.setDepthTest( true ); <ide> state.setDepthWrite( true ); <add> state.setStencilTest( true ); <add> state.setStencilWrite( true ); <ide> state.setColorWrite( true ); <ide> <ide> // _gl.finish(); <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> state.setDepthFunc( material.depthFunc ); <ide> state.setDepthTest( material.depthTest ); <ide> state.setDepthWrite( material.depthWrite ); <add> state.setStencilTest( material.stencilTest ); <add> state.setStencilWrite( material.stencilWrite ); <ide> state.setColorWrite( material.colorWrite ); <ide> state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits ); <ide> <ide><path>src/renderers/webgl/WebGLState.js <ide> THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { <ide> currentBlending = null; <ide> <ide> currentDepthWrite = null; <add> currentStencilWrite = null; <ide> currentColorWrite = null; <ide> <ide> currentFlipSided = null;
5
Ruby
Ruby
fix the build
84c20e27b6ecf48b17b707403175a44a528c57d6
<ide><path>railties/test/generators/plugin_generator_test.rb <ide> def test_generation_runs_bundle_install_with_full_and_mountable <ide> end <ide> assert_match(/run bundle install/, result) <ide> assert_match(/Using bukkits \(?0\.0\.1\)?/, result) <del> assert_match(/Your bundle is complete/, result) <add> assert_match(/Bundle complete!/, result) <ide> assert_equal 1, result.scan("Your bundle is complete").size <ide> end <ide>
1
Javascript
Javascript
treat enotconn at shutdown as success
1447a79dc435578bffba32ead9b2ffa0425fc30a
<ide><path>lib/net.js <ide> const { <ide> const assert = require('internal/assert'); <ide> const { <ide> UV_EADDRINUSE, <del> UV_EINVAL <add> UV_EINVAL, <add> UV_ENOTCONN <ide> } = internalBinding('uv'); <ide> <ide> const { Buffer } = require('buffer'); <ide> Socket.prototype._final = function(cb) { <ide> req.callback = cb; <ide> const err = this._handle.shutdown(req); <ide> <del> if (err === 1) // synchronous finish <add> if (err === 1 || err === UV_ENOTCONN) // synchronous finish <ide> return afterShutdown.call(req, 0); <ide> else if (err !== 0) <ide> return this.destroy(errnoException(err, 'shutdown'));
1
Go
Go
add some additional tests
2030daf2ee4ea8fbded8889a24ccf947e6a71d81
<ide><path>daemon/info_unix.go <ide> func getBackingFs(v *types.Info) string { <ide> // <ide> // tini version 0.18.0 - git.fec3683 <ide> func parseInitVersion(v string) (version string, commit string, err error) { <del> parts := strings.Split(strings.TrimSpace(v), " - ") <add> parts := strings.Split(v, " - ") <ide> <ide> if len(parts) >= 2 { <del> gitParts := strings.Split(parts[1], ".") <add> gitParts := strings.Split(strings.TrimSpace(parts[1]), ".") <ide> if len(gitParts) == 2 && gitParts[0] == "git" { <ide> commit = gitParts[1] <ide> } <ide> } <add> parts[0] = strings.TrimSpace(parts[0]) <ide> if strings.HasPrefix(parts[0], "tini version ") { <ide> version = strings.TrimPrefix(parts[0], "tini version ") <ide> } <ide><path>daemon/info_unix_test.go <ide> func TestParseInitVersion(t *testing.T) { <ide> }, { <ide> output: "tini version 0.13.2", <ide> version: "0.13.2", <add> }, { <add> output: "tini version 0.13.2 - ", <add> version: "0.13.2", <add> }, { <add> output: " - git.949e6fa", <add> commit: "949e6fa", <ide> }, { <ide> output: "tini version0.13.2", <ide> invalid: true, <add> }, { <add> output: "version 0.13.0", <add> invalid: true, <ide> }, { <ide> output: "", <ide> invalid: true, <add> }, { <add> output: " - ", <add> invalid: true, <ide> }, { <ide> output: "hello world", <ide> invalid: true, <ide> }, <ide> } <ide> <ide> for _, test := range tests { <del> version, commit, err := parseInitVersion(test.output) <del> if test.invalid { <del> assert.Check(t, is.ErrorContains(err, "")) <del> } else { <del> assert.Check(t, err) <del> } <del> assert.Equal(t, test.version, version) <del> assert.Equal(t, test.commit, commit) <add> test := test <add> t.Run(test.output, func(t *testing.T) { <add> version, commit, err := parseInitVersion(test.output) <add> if test.invalid { <add> assert.Check(t, is.ErrorContains(err, "")) <add> } else { <add> assert.Check(t, err) <add> } <add> assert.Equal(t, test.version, version) <add> assert.Equal(t, test.commit, commit) <add> }) <ide> } <ide> } <ide>
2
Ruby
Ruby
enable identitymap when generating new apps
375aaa9db1bb808f9126e3a057c80fca0c631ba6
<ide><path>railties/lib/rails/generators/rails/app/templates/config/application.rb <ide> class Application < Rails::Application <ide> <ide> # Configure sensitive parameters which will be filtered from the log file. <ide> config.filter_parameters += [:password] <add> <add><% unless options[:skip_active_record] -%> <add> # Enable IdentityMap for Active Record, to disable set to false or remove the line below. <add> config.active_record.identity_map = true <add><% end -%> <ide> end <ide> end <ide><path>railties/test/isolation/abstract_unit.rb <ide> def add_to_config(str) <ide> end <ide> end <ide> <add> def remove_from_config(str) <add> application_file = "#{app_path}/config/application.rb" <add> environment = File.read(application_file) <add> lines = File.readlines(application_file) <add> if environment =~ /(\n\s*end\s*end\s*)\Z/ <add> File.open(application_file, 'w') do |f| <add> lines.each {|line| f.puts(line) unless line =~ /#{str}/ } <add> end <add> end <add> end <add> <ide> def app_file(path, contents) <ide> FileUtils.mkdir_p File.dirname("#{app_path}/#{path}") <ide> File.open("#{app_path}/#{path}", 'w') do |f| <ide> def use_frameworks(arr) <ide> :activemodel, <ide> :activerecord, <ide> :activeresource] - arr <add> remove_from_config "config.active_record" if to_remove.include? :activerecord <ide> $:.reject! {|path| path =~ %r'/(#{to_remove.join('|')})/' } <ide> end <ide>
2
PHP
PHP
add method for setting middleware to the resource
398e3f2e8ccd3414e9e3ebc2a733ff1cda0ea375
<ide><path>src/Illuminate/Routing/PendingResourceRegistration.php <ide> public function parameter($previous, $new) <ide> <ide> return $this; <ide> } <add> <add> /** <add> * Set a middleware to the resource. <add> * <add> * @param mixed $middleware <add> * @return \Illuminate\Routing\PendingResourceRegistration <add> */ <add> public function middleware($middleware) <add> { <add> $this->options['middleware'] = $middleware; <add> <add> return $this; <add> } <ide> } <ide><path>tests/Routing/RouteRegistrarTest.php <ide> public function testCanOverrideParametersOnRegisteredResource() <ide> $this->assertContains('topic', $this->router->getRoutes()->getByName('posts.show')->uri); <ide> } <ide> <add> public function testCanSetMiddlewareOnRegisteredResource() <add> { <add> $this->router->resource('users', 'Illuminate\Tests\Routing\RouteRegistrarControllerStub') <add> ->middleware('Illuminate\Tests\Routing\RouteRegistrarMiddlewareStub'); <add> <add> $this->seeMiddleware('Illuminate\Tests\Routing\RouteRegistrarMiddlewareStub'); <add> } <add> <ide> public function testCanSetRouteName() <ide> { <ide> $this->router->as('users.index')->get('users', function () { <ide> public function destroy() <ide> return 'deleted'; <ide> } <ide> } <add> <add>class RouteRegistrarMiddlewareStub <add>{ <add> <add>}
2
Javascript
Javascript
read renderer id from operations
e050529c7d54af391330c991817c614ee6ef66dd
<ide><path>src/backend/agent.js <ide> const debug = (methodName, ...args) => { <ide> } <ide> }; <ide> <del>type OperationsParams = {| <del> operations: Uint32Array, <del> rendererID: number, <del>|}; <del> <ide> type InspectSelectParams = {| <ide> id: number, <ide> rendererID: number, <ide> export default class Agent extends EventEmitter { <ide> } <ide> }; <ide> <del> onHookOperations = ({ operations, rendererID }: OperationsParams) => { <add> onHookOperations = (operations: Uint32Array) => { <ide> if (__DEBUG__) { <ide> debug('onHookOperations', operations); <ide> } <ide> export default class Agent extends EventEmitter { <ide> this._bridge.send('operations', operations); <ide> <ide> if (this._persistedSelection !== null) { <add> const rendererID = operations[0]; <ide> if (this._persistedSelection.rendererID === rendererID) { <ide> // Check if we can select a deeper match for the persisted selection. <ide> const renderer = this._rendererInterfaces[rendererID]; <ide><path>src/backend/renderer.js <ide> export function attach( <ide> pendingOperationsQueue.push(ops); <ide> } else { <ide> // If we've already connected to the frontend, just pass the operations through. <del> hook.emit('operations', { <del> operations: ops, <del> rendererID, <del> }); <add> hook.emit('operations', ops); <ide> } <ide> <ide> pendingOperations.length = 0; <ide> export function attach( <ide> // We may have already queued up some operations before the frontend connected <ide> // If so, let the frontend know about them. <ide> localPendingOperationsQueue.forEach(ops => { <del> hook.emit('operations', { <del> operations: ops, <del> rendererID, <del> }); <add> hook.emit('operations', ops); <ide> }); <ide> } else { <ide> // Before the traversals, remember to start tracking
2
Text
Text
amend viewset docs to warn of potential problem
9b468fba60def77144949628211aac95c6316c70
<ide><path>docs/api-guide/viewsets.md <ide> Note that you can use any of the standard attributes or method overrides provide <ide> def get_queryset(self): <ide> return self.request.user.accounts.all() <ide> <add>Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you you will have to specify the `base_name` kwarg as part of your [router registration][routers]. <add> <ide> Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. <ide> <ide> ## ReadOnlyModelViewSet <ide> To create a base viewset class that provides `create`, `list` and `retrieve` ope <ide> By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. <ide> <ide> [cite]: http://guides.rubyonrails.org/routing.html <add>[routers]: routers.md
1
Javascript
Javascript
fix tdt -> tet in locale comment
e693b284cc51c18a9e476955dddc146dc9f1fc80
<ide><path>src/locale/tet.js <ide> //! moment.js locale configuration <del>//! locale : Tetun Dili (East Timor) [tdt] <add>//! locale : Tetun Dili (East Timor) [tet] <ide> //! author : Joshua Brooks : https://github.com/joshbrooks <ide> //! author : Onorio De J. Afonso : https://github.com/marobo <ide>
1
Javascript
Javascript
check document.documentmode once
d6b59e3d264198a42c205c3cebc0b561e0ca9bec
<ide><path>packages/react-dom/src/__tests__/ReactServerRenderingHydration.js <ide> describe('ReactDOMServerHydration', () => { <ide> <ide> it('should not warn when the style property differs on whitespace or order in IE', () => { <ide> document.documentMode = 11; <add> jest.resetModules(); <add> React = require('react'); <add> ReactDOM = require('react-dom'); <add> ReactDOMServer = require('react-dom/server'); <ide> try { <ide> const element = document.createElement('div'); <ide> <ide><path>packages/react-dom/src/client/ReactDOMComponent.js <ide> let warnForTextDifference; <ide> let warnForPropDifference; <ide> let warnForExtraAttributes; <ide> let warnForInvalidEventListener; <add>let canDiffStyleForHydrationWarning; <ide> <ide> let normalizeMarkupForTextOrAttribute; <ide> let normalizeHTML; <ide> if (__DEV__) { <ide> validateUnknownProperties(type, props, /* canUseEventSystem */ true); <ide> }; <ide> <add> // IE 11 parses & normalizes the style attribute as opposed to other <add> // browsers. It adds spaces and sorts the properties in some <add> // non-alphabetical order. Handling that would require sorting CSS <add> // properties in the client & server versions or applying <add> // `expectedStyle` to a temporary DOM node to read its `style` attribute <add> // normalized. Since it only affects IE, we're skipping style warnings <add> // in that browser completely in favor of doing all that work. <add> // See https://github.com/facebook/react/issues/11807 <add> canDiffStyleForHydrationWarning = !document.documentMode; <add> <ide> // HTML parsing normalizes CR and CRLF to LF. <ide> // It also can turn \u0000 into \uFFFD inside attributes. <ide> // https://www.w3.org/TR/html5/single-page.html#preprocessing-the-input-stream <ide> export function diffHydratedProperties( <ide> // $FlowFixMe - Should be inferred as not undefined. <ide> extraAttributeNames.delete(propKey); <ide> <del> // IE 11 parses & normalizes the style attribute as opposed to other <del> // browsers. It adds spaces and sorts the properties in some <del> // non-alphabetical order. Handling that would require sorting CSS <del> // properties in the client & server versions or applying <del> // `expectedStyle` to a temporary DOM node to read its `style` attribute <del> // normalized. Since it only affects IE, we're skipping style warnings <del> // in that browser completely in favor of doing all that work. <del> // See https://github.com/facebook/react/issues/11807 <del> if (!document.documentMode) { <add> if (canDiffStyleForHydrationWarning) { <ide> const expectedStyle = CSSPropertyOperations.createDangerousStringForStyles( <ide> nextProp, <ide> );
2
Javascript
Javascript
use static injection for reacterrorutils
46b3c3e4ae0d52565f7ed2344036a22016781ca0
<ide><path>packages/react-dom/src/client/ReactDOMFB.js <ide> <ide> import * as ReactFiberTreeReflection from 'react-reconciler/reflection'; <ide> import * as ReactInstanceMap from 'shared/ReactInstanceMap'; <del>import ReactErrorUtils from 'shared/ReactErrorUtils'; <ide> import {addUserTimingListener} from 'shared/ReactFeatureFlags'; <ide> <ide> import ReactDOM from './ReactDOM'; <ide> Object.assign( <ide> { <ide> // These are real internal dependencies that are trickier to remove: <ide> ReactBrowserEventEmitter, <del> ReactErrorUtils, <ide> ReactFiberTreeReflection, <ide> ReactDOMComponentTree, <ide> ReactInstanceMap, <ide><path>packages/shared/ReactErrorUtils.js <ide> */ <ide> <ide> import invariant from 'fbjs/lib/invariant'; <add>import invokeGuardedCallback from './invokeGuardedCallback'; <ide> <ide> const ReactErrorUtils = { <ide> // Used by Fiber to simulate a try-catch. <ide> const ReactErrorUtils = { <ide> _rethrowError: (null: mixed), <ide> _hasRethrowError: (false: boolean), <ide> <del> injection: { <del> injectErrorUtils(injectedErrorUtils: Object) { <del> invariant( <del> typeof injectedErrorUtils.invokeGuardedCallback === 'function', <del> 'Injected invokeGuardedCallback() must be a function.', <del> ); <del> invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; <del> }, <del> }, <del> <ide> /** <ide> * Call a function while guarding against errors that happens within it. <ide> * Returns an error if it throws, otherwise null. <ide> const ReactErrorUtils = { <ide> }, <ide> }; <ide> <del>let invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) { <del> ReactErrorUtils._hasCaughtError = false; <del> ReactErrorUtils._caughtError = null; <del> const funcArgs = Array.prototype.slice.call(arguments, 3); <del> try { <del> func.apply(context, funcArgs); <del> } catch (error) { <del> ReactErrorUtils._caughtError = error; <del> ReactErrorUtils._hasCaughtError = true; <del> } <del>}; <del> <del>if (__DEV__) { <del> // In DEV mode, we swap out invokeGuardedCallback for a special version <del> // that plays more nicely with the browser's DevTools. The idea is to preserve <del> // "Pause on exceptions" behavior. Because React wraps all user-provided <del> // functions in invokeGuardedCallback, and the production version of <del> // invokeGuardedCallback uses a try-catch, all user exceptions are treated <del> // like caught exceptions, and the DevTools won't pause unless the developer <del> // takes the extra step of enabling pause on caught exceptions. This is <del> // untintuitive, though, because even though React has caught the error, from <del> // the developer's perspective, the error is uncaught. <del> // <del> // To preserve the expected "Pause on exceptions" behavior, we don't use a <del> // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake <del> // DOM node, and call the user-provided callback from inside an event handler <del> // for that fake event. If the callback throws, the error is "captured" using <del> // a global event handler. But because the error happens in a different <del> // event loop context, it does not interrupt the normal program flow. <del> // Effectively, this gives us try-catch behavior without actually using <del> // try-catch. Neat! <del> <del> // Check that the browser supports the APIs we need to implement our special <del> // DEV version of invokeGuardedCallback <del> if ( <del> typeof window !== 'undefined' && <del> typeof window.dispatchEvent === 'function' && <del> typeof document !== 'undefined' && <del> typeof document.createEvent === 'function' <del> ) { <del> const fakeNode = document.createElement('react'); <del> <del> const invokeGuardedCallbackDev = function( <del> name, <del> func, <del> context, <del> a, <del> b, <del> c, <del> d, <del> e, <del> f, <del> ) { <del> // If document doesn't exist we know for sure we will crash in this method <del> // when we call document.createEvent(). However this can cause confusing <del> // errors: https://github.com/facebookincubator/create-react-app/issues/3482 <del> // So we preemptively throw with a better message instead. <del> invariant( <del> typeof document !== 'undefined', <del> 'The `document` global was defined when React was initialized, but is not ' + <del> 'defined anymore. This can happen in a test environment if a component ' + <del> 'schedules an update from an asynchronous callback, but the test has already ' + <del> 'finished running. To solve this, you can either unmount the component at ' + <del> 'the end of your test (and ensure that any asynchronous operations get ' + <del> 'canceled in `componentWillUnmount`), or you can change the test itself ' + <del> 'to be asynchronous.', <del> ); <del> const evt = document.createEvent('Event'); <del> <del> // Keeps track of whether the user-provided callback threw an error. We <del> // set this to true at the beginning, then set it to false right after <del> // calling the function. If the function errors, `didError` will never be <del> // set to false. This strategy works even if the browser is flaky and <del> // fails to call our global error handler, because it doesn't rely on <del> // the error event at all. <del> let didError = true; <del> <del> // Create an event handler for our fake event. We will synchronously <del> // dispatch our fake event using `dispatchEvent`. Inside the handler, we <del> // call the user-provided callback. <del> const funcArgs = Array.prototype.slice.call(arguments, 3); <del> function callCallback() { <del> // We immediately remove the callback from event listeners so that <del> // nested `invokeGuardedCallback` calls do not clash. Otherwise, a <del> // nested call would trigger the fake event handlers of any call higher <del> // in the stack. <del> fakeNode.removeEventListener(evtType, callCallback, false); <del> func.apply(context, funcArgs); <del> didError = false; <del> } <del> <del> // Create a global error event handler. We use this to capture the value <del> // that was thrown. It's possible that this error handler will fire more <del> // than once; for example, if non-React code also calls `dispatchEvent` <del> // and a handler for that event throws. We should be resilient to most of <del> // those cases. Even if our error event handler fires more than once, the <del> // last error event is always used. If the callback actually does error, <del> // we know that the last error event is the correct one, because it's not <del> // possible for anything else to have happened in between our callback <del> // erroring and the code that follows the `dispatchEvent` call below. If <del> // the callback doesn't error, but the error event was fired, we know to <del> // ignore it because `didError` will be false, as described above. <del> let error; <del> // Use this to track whether the error event is ever called. <del> let didSetError = false; <del> let isCrossOriginError = false; <del> <del> function onError(event) { <del> error = event.error; <del> didSetError = true; <del> if (error === null && event.colno === 0 && event.lineno === 0) { <del> isCrossOriginError = true; <del> } <del> } <del> <del> // Create a fake event type. <del> const evtType = `react-${name ? name : 'invokeguardedcallback'}`; <del> <del> // Attach our event handlers <del> window.addEventListener('error', onError); <del> fakeNode.addEventListener(evtType, callCallback, false); <del> <del> // Synchronously dispatch our fake event. If the user-provided function <del> // errors, it will trigger our global error handler. <del> evt.initEvent(evtType, false, false); <del> fakeNode.dispatchEvent(evt); <del> <del> if (didError) { <del> if (!didSetError) { <del> // The callback errored, but the error event never fired. <del> error = new Error( <del> 'An error was thrown inside one of your components, but React ' + <del> "doesn't know what it was. This is likely due to browser " + <del> 'flakiness. React does its best to preserve the "Pause on ' + <del> 'exceptions" behavior of the DevTools, which requires some ' + <del> "DEV-mode only tricks. It's possible that these don't work in " + <del> 'your browser. Try triggering the error in production mode, ' + <del> 'or switching to a modern browser. If you suspect that this is ' + <del> 'actually an issue with React, please file an issue.', <del> ); <del> } else if (isCrossOriginError) { <del> error = new Error( <del> "A cross-origin error was thrown. React doesn't have access to " + <del> 'the actual error object in development. ' + <del> 'See https://fb.me/react-crossorigin-error for more information.', <del> ); <del> } <del> ReactErrorUtils._hasCaughtError = true; <del> ReactErrorUtils._caughtError = error; <del> } else { <del> ReactErrorUtils._hasCaughtError = false; <del> ReactErrorUtils._caughtError = null; <del> } <del> <del> // Remove our event listeners <del> window.removeEventListener('error', onError); <del> }; <del> <del> invokeGuardedCallback = invokeGuardedCallbackDev; <del> } <del>} <del> <ide> let rethrowCaughtError = function() { <ide> if (ReactErrorUtils._hasRethrowError) { <ide> const error = ReactErrorUtils._rethrowError; <ide><path>packages/shared/__tests__/ReactErrorUtils-test.internal.js <ide> describe('ReactErrorUtils', () => { <ide> <ide> it(`can be shimmed`, () => { <ide> const ops = []; <del> // Override the original invokeGuardedCallback <del> ReactErrorUtils.injection.injectErrorUtils({ <del> invokeGuardedCallback(name, func, context, a) { <del> ops.push(a); <del> try { <del> func.call(context, a); <del> } catch (error) { <del> this._hasCaughtError = true; <del> this._caughtError = error; <del> } <del> }, <del> }); <del> <del> var err = new Error('foo'); <del> var callback = function() { <del> throw err; <del> }; <del> ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError( <del> 'foo', <del> callback, <del> null, <del> 'somearg', <add> jest.resetModules(); <add> jest.mock( <add> 'shared/invokeGuardedCallback', <add> () => <add> function invokeGuardedCallback(name, func, context, a) { <add> ops.push(a); <add> try { <add> func.call(context, a); <add> } catch (error) { <add> this._hasCaughtError = true; <add> this._caughtError = error; <add> } <add> }, <ide> ); <del> expect(() => ReactErrorUtils.rethrowCaughtError()).toThrow(err); <del> expect(ops).toEqual(['somearg']); <add> ReactErrorUtils = require('shared/ReactErrorUtils').default; <add> <add> try { <add> var err = new Error('foo'); <add> var callback = function() { <add> throw err; <add> }; <add> ReactErrorUtils.invokeGuardedCallbackAndCatchFirstError( <add> 'foo', <add> callback, <add> null, <add> 'somearg', <add> ); <add> expect(() => ReactErrorUtils.rethrowCaughtError()).toThrow(err); <add> expect(ops).toEqual(['somearg']); <add> } finally { <add> jest.unmock('shared/invokeGuardedCallback'); <add> } <ide> }); <ide> }); <ide><path>packages/shared/forks/invokeGuardedCallback.www.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> */ <add> <add>import invariant from 'fbjs/lib/invariant'; <add> <add>const invokeGuardedCallback = require('ReactFbErrorUtils') <add> .invokeGuardedCallback; <add>invariant( <add> typeof invokeGuardedCallback === 'function', <add> 'Expected ReactFbErrorUtils.invokeGuardedCallback to be a function.', <add>); <add> <add>export default invokeGuardedCallback; <ide><path>packages/shared/invokeGuardedCallback.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> */ <add> <add>import invariant from 'fbjs/lib/invariant'; <add> <add>let invokeGuardedCallback = function<A, B, C, D, E, F, Context>( <add> name: string | null, <add> func: (a: A, b: B, c: C, d: D, e: E, f: F) => void, <add> context: Context, <add> a: A, <add> b: B, <add> c: C, <add> d: D, <add> e: E, <add> f: F, <add>) { <add> this._hasCaughtError = false; <add> this._caughtError = null; <add> const funcArgs = Array.prototype.slice.call(arguments, 3); <add> try { <add> func.apply(context, funcArgs); <add> } catch (error) { <add> this._caughtError = error; <add> this._hasCaughtError = true; <add> } <add>}; <add> <add>if (__DEV__) { <add> // In DEV mode, we swap out invokeGuardedCallback for a special version <add> // that plays more nicely with the browser's DevTools. The idea is to preserve <add> // "Pause on exceptions" behavior. Because React wraps all user-provided <add> // functions in invokeGuardedCallback, and the production version of <add> // invokeGuardedCallback uses a try-catch, all user exceptions are treated <add> // like caught exceptions, and the DevTools won't pause unless the developer <add> // takes the extra step of enabling pause on caught exceptions. This is <add> // untintuitive, though, because even though React has caught the error, from <add> // the developer's perspective, the error is uncaught. <add> // <add> // To preserve the expected "Pause on exceptions" behavior, we don't use a <add> // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake <add> // DOM node, and call the user-provided callback from inside an event handler <add> // for that fake event. If the callback throws, the error is "captured" using <add> // a global event handler. But because the error happens in a different <add> // event loop context, it does not interrupt the normal program flow. <add> // Effectively, this gives us try-catch behavior without actually using <add> // try-catch. Neat! <add> <add> // Check that the browser supports the APIs we need to implement our special <add> // DEV version of invokeGuardedCallback <add> if ( <add> typeof window !== 'undefined' && <add> typeof window.dispatchEvent === 'function' && <add> typeof document !== 'undefined' && <add> typeof document.createEvent === 'function' <add> ) { <add> const fakeNode = document.createElement('react'); <add> <add> const invokeGuardedCallbackDev = function<A, B, C, D, E, F, Context>( <add> name: string | null, <add> func: (a: A, b: B, c: C, d: D, e: E, f: F) => void, <add> context: Context, <add> a: A, <add> b: B, <add> c: C, <add> d: D, <add> e: E, <add> f: F, <add> ) { <add> // If document doesn't exist we know for sure we will crash in this method <add> // when we call document.createEvent(). However this can cause confusing <add> // errors: https://github.com/facebookincubator/create-react-app/issues/3482 <add> // So we preemptively throw with a better message instead. <add> invariant( <add> typeof document !== 'undefined', <add> 'The `document` global was defined when React was initialized, but is not ' + <add> 'defined anymore. This can happen in a test environment if a component ' + <add> 'schedules an update from an asynchronous callback, but the test has already ' + <add> 'finished running. To solve this, you can either unmount the component at ' + <add> 'the end of your test (and ensure that any asynchronous operations get ' + <add> 'canceled in `componentWillUnmount`), or you can change the test itself ' + <add> 'to be asynchronous.', <add> ); <add> const evt = document.createEvent('Event'); <add> <add> // Keeps track of whether the user-provided callback threw an error. We <add> // set this to true at the beginning, then set it to false right after <add> // calling the function. If the function errors, `didError` will never be <add> // set to false. This strategy works even if the browser is flaky and <add> // fails to call our global error handler, because it doesn't rely on <add> // the error event at all. <add> let didError = true; <add> <add> // Create an event handler for our fake event. We will synchronously <add> // dispatch our fake event using `dispatchEvent`. Inside the handler, we <add> // call the user-provided callback. <add> const funcArgs = Array.prototype.slice.call(arguments, 3); <add> function callCallback() { <add> // We immediately remove the callback from event listeners so that <add> // nested `invokeGuardedCallback` calls do not clash. Otherwise, a <add> // nested call would trigger the fake event handlers of any call higher <add> // in the stack. <add> fakeNode.removeEventListener(evtType, callCallback, false); <add> func.apply(context, funcArgs); <add> didError = false; <add> } <add> <add> // Create a global error event handler. We use this to capture the value <add> // that was thrown. It's possible that this error handler will fire more <add> // than once; for example, if non-React code also calls `dispatchEvent` <add> // and a handler for that event throws. We should be resilient to most of <add> // those cases. Even if our error event handler fires more than once, the <add> // last error event is always used. If the callback actually does error, <add> // we know that the last error event is the correct one, because it's not <add> // possible for anything else to have happened in between our callback <add> // erroring and the code that follows the `dispatchEvent` call below. If <add> // the callback doesn't error, but the error event was fired, we know to <add> // ignore it because `didError` will be false, as described above. <add> let error; <add> // Use this to track whether the error event is ever called. <add> let didSetError = false; <add> let isCrossOriginError = false; <add> <add> function onError(event) { <add> error = event.error; <add> didSetError = true; <add> if (error === null && event.colno === 0 && event.lineno === 0) { <add> isCrossOriginError = true; <add> } <add> } <add> <add> // Create a fake event type. <add> const evtType = `react-${name ? name : 'invokeguardedcallback'}`; <add> <add> // Attach our event handlers <add> window.addEventListener('error', onError); <add> fakeNode.addEventListener(evtType, callCallback, false); <add> <add> // Synchronously dispatch our fake event. If the user-provided function <add> // errors, it will trigger our global error handler. <add> evt.initEvent(evtType, false, false); <add> fakeNode.dispatchEvent(evt); <add> <add> if (didError) { <add> if (!didSetError) { <add> // The callback errored, but the error event never fired. <add> error = new Error( <add> 'An error was thrown inside one of your components, but React ' + <add> "doesn't know what it was. This is likely due to browser " + <add> 'flakiness. React does its best to preserve the "Pause on ' + <add> 'exceptions" behavior of the DevTools, which requires some ' + <add> "DEV-mode only tricks. It's possible that these don't work in " + <add> 'your browser. Try triggering the error in production mode, ' + <add> 'or switching to a modern browser. If you suspect that this is ' + <add> 'actually an issue with React, please file an issue.', <add> ); <add> } else if (isCrossOriginError) { <add> error = new Error( <add> "A cross-origin error was thrown. React doesn't have access to " + <add> 'the actual error object in development. ' + <add> 'See https://fb.me/react-crossorigin-error for more information.', <add> ); <add> } <add> this._hasCaughtError = true; <add> this._caughtError = error; <add> } else { <add> this._hasCaughtError = false; <add> this._caughtError = null; <add> } <add> <add> // Remove our event listeners <add> window.removeEventListener('error', onError); <add> }; <add> <add> invokeGuardedCallback = invokeGuardedCallbackDev; <add> } <add>} <add> <add>export default invokeGuardedCallback; <ide><path>scripts/rollup/forks.js <ide> const forks = Object.freeze({ <ide> } <ide> }, <ide> <del> // Different behavior for caught errors. <add> // Different wrapping/reporting for caught errors. <add> 'shared/invokeGuardedCallback': (bundleType, entry) => { <add> switch (bundleType) { <add> case FB_DEV: <add> case FB_PROD: <add> return 'shared/forks/invokeGuardedCallback.www.js'; <add> default: <add> return null; <add> } <add> }, <add> <add> // Different dialogs for caught errors. <ide> 'react-reconciler/src/ReactFiberErrorDialog': (bundleType, entry) => { <ide> switch (bundleType) { <ide> case FB_DEV:
6
PHP
PHP
reset mailer when exceptions are thrown
e1164a7acc208c62b1411bd67f56024a6b94b20b
<ide><path>src/Mailer/Mailer.php <ide> public function set($key, $value = null) <ide> */ <ide> public function send($action, $args = [], $headers = []) <ide> { <del> if (!method_exists($this, $action)) { <del> throw new MissingActionException([ <del> 'mailer' => $this->getName() . 'Mailer', <del> 'action' => $action, <del> ]); <del> } <add> try { <add> if (!method_exists($this, $action)) { <add> throw new MissingActionException([ <add> 'mailer' => $this->getName() . 'Mailer', <add> 'action' => $action, <add> ]); <add> } <ide> <del> $this->_email->setHeaders($headers); <del> if (!$this->_email->viewBuilder()->template()) { <del> $this->_email->viewBuilder()->template($action); <del> } <add> $this->_email->setHeaders($headers); <add> if (!$this->_email->viewBuilder()->template()) { <add> $this->_email->viewBuilder()->template($action); <add> } <ide> <del> call_user_func_array([$this, $action], $args); <add> call_user_func_array([$this, $action], $args); <ide> <del> $result = $this->_email->send(); <del> $this->reset(); <add> $result = $this->_email->send(); <add> } finally { <add> $this->reset(); <add> } <ide> <ide> return $result; <ide> }
1
Text
Text
factorialize a number - portuguese
907b93eaeaf799d9976e64446e9d8d34de55a7f6
<ide><path>curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number.portuguese.md <ide> factorialize(5); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>function factorialize(num) { <add> return num <= 1 ? 1 : num * factorialize(num - 1); <add>} <add> <add>factorialize(5); <ide> ``` <ide> </section>
1
PHP
PHP
fix some docblocks
bdef94e517368568a896b5a03ad87eee394adccd
<ide><path>src/Illuminate/Database/Query/JoinClause.php <ide> public function __construct($type, $table) <ide> * <ide> * on `contacts`.`user_id` = `users`.`id` and `contacts`.`info_id` = `info`.`id` <ide> * <del> * @param string $first <add> * @param string|\Closure $first <ide> * @param string|null $operator <ide> * @param string|null $second <ide> * @param string $boolean <ide> public function on($first, $operator = null, $second = null, $boolean = 'and', $ <ide> /** <ide> * Add an "or on" clause to the join. <ide> * <del> * @param string $first <add> * @param string|\Closure $first <ide> * @param string|null $operator <ide> * @param string|null $second <ide> * @return \Illuminate\Database\Query\JoinClause <ide> public function orOn($first, $operator = null, $second = null) <ide> /** <ide> * Add an "on where" clause to the join. <ide> * <del> * @param string $first <add> * @param string|\Closure $first <ide> * @param string|null $operator <ide> * @param string|null $second <ide> * @param string $boolean <ide> public function where($first, $operator = null, $second = null, $boolean = 'and' <ide> /** <ide> * Add an "or on where" clause to the join. <ide> * <del> * @param string $first <add> * @param string|\Closure $first <ide> * @param string|null $operator <ide> * @param string|null $second <ide> * @return \Illuminate\Database\Query\JoinClause <ide> public function orWhereNotIn($column, array $values) <ide> */ <ide> public function nest(Closure $callback, $boolean = 'and') <ide> { <del> $join = new self($this->type, $this->table); <add> $join = new static($this->type, $this->table); <ide> <ide> $callback($join); <ide> <del> if ($clausesCount = count($join->clauses)) { <add> if (count($join->clauses)) { <ide> $nested = true; <ide> <ide> $this->clauses[] = compact('nested', 'join', 'boolean');
1
Javascript
Javascript
check invalid argument error for option
f8f96017e82abe4e965251b2f6072bdb6bea9d51
<ide><path>test/parallel/test-whatwg-encoding-textdecoder.js <ide> testDecodeSample( <ide> ] <ide> ); <ide> <add>{ <add> common.expectsError( <add> () => new TextDecoder('utf-8', 1), <add> { <add> code: 'ERR_INVALID_ARG_TYPE', <add> type: TypeError <add> } <add> ); <add>} <add> <ide> // From: https://github.com/w3c/web-platform-tests/blob/master/encoding/api-invalid-label.html <ide> [ <ide> 'utf-8',
1
Javascript
Javascript
increase coverage for timers
e21e12944c11f9d30e154d735f35b1f528cd7dc2
<ide><path>test/parallel/test-timers-clear-null-does-not-throw-error.js <add>'use strict'; <add>require('../common'); <add>const assert = require('assert'); <add> <add>// This test makes sure clearing timers with <add>// 'null' or no input does not throw error <add> <add>assert.doesNotThrow(() => clearInterval(null)); <add> <add>assert.doesNotThrow(() => clearInterval()); <add> <add>assert.doesNotThrow(() => clearTimeout(null)); <add> <add>assert.doesNotThrow(() => clearTimeout()); <add> <add>assert.doesNotThrow(() => clearImmediate(null)); <add> <add>assert.doesNotThrow(() => clearImmediate());
1
Javascript
Javascript
use npm for e2e tests
33fb428a07d04fb70356d507ed411a0e96432a19
<ide><path>local-cli/server/util/attachHMRServer.js <ide> function attachHMRServer({httpServer, path, packagerServer}) { <ide> <ide> client.ws.on('close', () => disconnect()); <ide> }) <del> .done(); <add> .catch(err => { <add> throw err; <add> }); <ide> }); <ide> } <ide> <ide><path>scripts/run-ci-e2e-tests.js <ide> try { <ide> if (tryExecNTimes( <ide> () => { <ide> exec('sleep 10s'); <del> return exec(`react-native init EndToEndTest --version ${PACKAGE}`).code; <add> return exec(`react-native init EndToEndTest --version ${PACKAGE} --npm`).code; <ide> }, <ide> numberOfRetries, <ide> () => rm('-rf', 'EndToEndTest'))) {
2
Ruby
Ruby
add some more tests
1af531dcf7b8d9ee4237ea5fd392b43875309954
<ide><path>lib/action_cable/channel/periodic_timers.rb <ide> module ActionCable <ide> module Channel <ide> module PeriodicTimers <ide> extend ActiveSupport::Concern <del> <add> <ide> included do <ide> class_attribute :periodic_timers, instance_reader: false <ide> self.periodic_timers = [] <add><path>test/channel/base_test.rb <del><path>test/channel_test.rb <ide> require 'test_helper' <add>require 'stubs/test_connection' <ide> <del>class ChannelTest < ActiveSupport::TestCase <add>class ActionCable::Channel::BaseTest < ActiveSupport::TestCase <ide> Room = Struct.new(:id) <del> User = Struct.new(:name) <del> <del> class TestConnection <del> attr_reader :identifiers, :logger, :current_user, :transmissions <del> <del> def initialize(user) <del> @identifiers = [ :current_user ] <del> <del> @current_user = user <del> @logger = Logger.new(StringIO.new) <del> @transmissions = [] <del> end <del> <del> def transmit(data) <del> @transmissions << data <del> end <del> <del> def last_transmission <del> @transmissions.last <del> end <del> end <ide> <ide> class ChatChannel < ActionCable::Channel::Base <ide> attr_reader :room, :last_action <ide><path>test/channel/periodic_timers_test.rb <add>require 'test_helper' <add>require 'stubs/test_connection' <add> <add>class ActionCable::Channel::PeriodicTimersTest < ActiveSupport::TestCase <add> Room = Struct.new(:id) <add> <add> class ChatChannel < ActionCable::Channel::Base <add> periodically -> { ping }, every: 5 <add> periodically :send_updates, every: 1 <add> <add> private <add> def ping <add> end <add> end <add> <add> setup do <add> @connection = TestConnection.new <add> end <add> <add> test "periodic timers definition" do <add> timers = ChatChannel.periodic_timers <add> <add> assert_equal 2, timers.size <add> <add> first_timer = timers[0] <add> assert_kind_of Proc, first_timer[0] <add> assert_equal 5, first_timer[1][:every] <add> <add> second_timer = timers[1] <add> assert_equal :send_updates, second_timer[0] <add> assert_equal 1, second_timer[1][:every] <add> end <add> <add> test "timer start and stop" do <add> EventMachine::PeriodicTimer.expects(:new).times(2).returns(true) <add> channel = ChatChannel.new @connection, "{id: 1}", { id: 1 } <add> <add> channel.expects(:stop_periodic_timers).once <add> channel.unsubscribe_from_channel <add> end <add>end <ide><path>test/channel/stream_test.rb <add>require 'test_helper' <add>require 'stubs/test_connection' <add> <add>class ActionCable::Channel::StreamTest < ActiveSupport::TestCase <add> Room = Struct.new(:id) <add> <add> class ChatChannel < ActionCable::Channel::Base <add> def subscribed <add> @room = Room.new params[:id] <add> stream_from "test_room_#{@room.id}" <add> end <add> end <add> <add> setup do <add> @connection = TestConnection.new <add> end <add> <add> test "streaming start and stop" do <add> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe) } <add> channel = ChatChannel.new @connection, "{id: 1}", { id: 1 } <add> <add> @connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe_proc) } <add> channel.unsubscribe_from_channel <add> end <add>end <ide><path>test/connection/base_test.rb <add>require 'test_helper' <add>require 'stubs/test_server' <add> <add>class ActionCable::Connection::BaseTest < ActiveSupport::TestCase <add> setup do <add> @server = TestServer.new <add> <add> env = Rack::MockRequest.env_for "/test", 'HTTP_CONNECTION' => 'upgrade', 'HTTP_UPGRADE' => 'websocket' <add> @connection = ActionCable::Connection::Base.new(@server, env) <add> end <add> <add> test "making a connection with invalid headers" do <add> connection = ActionCable::Connection::Base.new(@server, Rack::MockRequest.env_for("/test")) <add> response = connection.process <add> assert_equal 404, response[0] <add> end <add>end <ide><path>test/stubs/test_connection.rb <add>require 'stubs/user' <add> <add>class TestConnection <add> attr_reader :identifiers, :logger, :current_user, :transmissions <add> <add> def initialize(user = User.new("lifo")) <add> @identifiers = [ :current_user ] <add> <add> @current_user = user <add> @logger = ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new) <add> @transmissions = [] <add> end <add> <add> def transmit(data) <add> @transmissions << data <add> end <add> <add> def last_transmission <add> @transmissions.last <add> end <add> <add> # Disable async in tests <add> def send_async(method, *arguments) <add> send method, *arguments <add> end <add>end <ide><path>test/stubs/test_server.rb <add>require 'ostruct' <add> <add>class TestServer <add> attr_reader :logger, :config <add> <add> def initialize <add> @logger = ActiveSupport::TaggedLogging.new ActiveSupport::Logger.new(StringIO.new) <add> @config = OpenStruct.new(log_tags: []) <add> end <add>end <ide><path>test/stubs/user.rb <add>class User <add> attr_reader :name <add> <add> def initialize(name) <add> @name = name <add> end <add>end <ide><path>test/test_helper.rb <ide> gem 'minitest' <ide> require "minitest/autorun" <ide> <del>require 'mocha/mini_test' <del> <ide> Bundler.setup <ide> Bundler.require :default, :test <ide> <ide> require 'puma' <add>require 'mocha/mini_test' <ide> <ide> require 'action_cable' <ide> ActiveSupport.test_order = :sorted
9
Python
Python
fix inner dimensions for 3b/11b models
33e72b08d54bf5edd192492af7549b581563ecc2
<ide><path>transformers/modeling_t5.py <ide> import torch.nn.functional as F <ide> from torch.nn import CrossEntropyLoss, MSELoss <ide> <del>from .modeling_utils import PreTrainedModel <add>from .modeling_utils import PreTrainedModel, prune_linear_layer <ide> from .configuration_t5 import T5Config <ide> from .file_utils import add_start_docstrings, DUMMY_INPUTS, DUMMY_MASK <ide> <ide> def __init__(self, config, has_relative_attention_bias=False): <ide> <ide> self.output_attentions = config.output_attentions <ide> self.relative_attention_num_buckets = config.relative_attention_num_buckets <del> self.dim = config.d_model <add> self.d_model = config.d_model <ide> self.d_kv = config.d_kv <ide> self.n_heads = config.num_heads <ide> self.dropout = config.dropout_rate <del> assert self.dim % self.n_heads == 0 <del> assert self.dim // self.n_heads == self.d_kv <add> self.inner_dim = self.n_heads * self.d_kv <ide> <ide> # Mesh TensorFlow initialization to avoid scaling before softmax <del> self.q = nn.Linear(self.dim, self.dim, bias=False) <del> self.k = nn.Linear(self.dim, self.dim, bias=False) <del> self.v = nn.Linear(self.dim, self.dim, bias=False) <del> self.o = nn.Linear(self.dim, self.dim, bias=False) <add> self.q = nn.Linear(self.d_model, self.inner_dim, bias=False) <add> self.k = nn.Linear(self.d_model, self.inner_dim, bias=False) <add> self.v = nn.Linear(self.d_model, self.inner_dim, bias=False) <add> self.o = nn.Linear(self.inner_dim, self.d_model, bias=False) <ide> <ide> if self.has_relative_attention_bias: <ide> self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads) <ide> self.pruned_heads = set() <ide> <ide> def prune_heads(self, heads): <del> attention_head_size = self.dim // self.n_heads <ide> if len(heads) == 0: <ide> return <del> mask = torch.ones(self.n_heads, attention_head_size) <add> mask = torch.ones(self.n_heads, self.d_kv) <ide> heads = set(heads) - self.pruned_heads <ide> for head in heads: <ide> head -= sum(1 if h < head else 0 for h in self.pruned_heads) <ide> def prune_heads(self, heads): <ide> self.o = prune_linear_layer(self.o, index, dim=1) <ide> # Update hyper params <ide> self.n_heads = self.n_heads - len(heads) <del> self.dim = attention_head_size * self.n_heads <add> self.inner_dim = self.d_kv * self.n_heads <ide> self.pruned_heads = self.pruned_heads.union(heads) <ide> <ide> @staticmethod <ide> def forward(self, input, mask=None, kv=None, position_bias=None, cache=None, hea <ide> klen = qlen if cache is None else cache['slen'] + qlen <ide> else: <ide> klen = kv.size(1) <del> # assert dim == self.dim, 'Dimensions do not match: %s input vs %s configured' % (dim, self.dim) <del> n_heads = self.n_heads <del> dim_per_head = self.dim // n_heads <ide> <ide> def shape(x): <ide> """ projection """ <del> return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2) <add> return x.view(bs, -1, self.n_heads, self.d_kv).transpose(1, 2) <ide> <ide> def unshape(x): <ide> """ compute context """ <del> return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head) <add> return x.transpose(1, 2).contiguous().view(bs, -1, self.inner_dim) <ide> <ide> q = shape(self.q(input)) # (bs, n_heads, qlen, dim_per_head) <ide> if kv is None: <ide><path>transformers/modeling_tf_t5.py <ide> def __init__(self, config, has_relative_attention_bias=False, **kwargs): <ide> <ide> self.output_attentions = config.output_attentions <ide> self.relative_attention_num_buckets = config.relative_attention_num_buckets <del> self.dim = config.d_model <add> self.d_model = config.d_model <ide> self.d_kv = config.d_kv <ide> self.n_heads = config.num_heads <del> assert self.dim % self.n_heads == 0 <del> assert self.dim // self.n_heads == self.d_kv <add> self.inner_dim = self.n_heads * self.d_kv <ide> <ide> # Mesh TensorFlow initialization to avoid scaling before softmax <del> self.q = tf.keras.layers.Dense(self.dim, use_bias=False, name='q') <del> self.k = tf.keras.layers.Dense(self.dim, use_bias=False, name='k') <del> self.v = tf.keras.layers.Dense(self.dim, use_bias=False, name='v') <del> self.o = tf.keras.layers.Dense(self.dim, use_bias=False, name='o') <add> self.q = tf.keras.layers.Dense(self.inner_dim, use_bias=False, name='q') <add> self.k = tf.keras.layers.Dense(self.inner_dim, use_bias=False, name='k') <add> self.v = tf.keras.layers.Dense(self.inner_dim, use_bias=False, name='v') <add> self.o = tf.keras.layers.Dense(self.d_model, use_bias=False, name='o') <ide> self.dropout = tf.keras.layers.Dropout(config.dropout_rate) <ide> <ide> if self.has_relative_attention_bias: <ide> def call(self, input, mask=None, kv=None, position_bias=None, cache=None, head_m <ide> klen = qlen if cache is None else cache['slen'] + qlen <ide> else: <ide> klen = shape_list(kv)[1] <del> # assert dim == self.dim, 'Dimensions do not match: %s input vs %s configured' % (dim, self.dim) <del> n_heads = self.n_heads <del> dim_per_head = self.dim // n_heads <ide> <ide> def shape(x): <ide> """ projection """ <del> return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3)) <add> return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, self.d_kv)), perm=(0, 2, 1, 3)) <ide> <ide> def unshape(x): <ide> """ compute context """ <del> return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head)) <add> return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.inner_dim)) <ide> <ide> q = shape(self.q(input)) # (bs, n_heads, qlen, dim_per_head) <ide> if kv is None:
2
Mixed
Ruby
move advisory lock to it's own connection
1ee4a8812fcaf2de48e5ab65d7f707c391fce31d
<ide><path>activerecord/CHANGELOG.md <add>* Store advisory locks on their own named connection. <add> <add> Previously advisory locks were taken out against a connection when a migration started. This works fine in single database applications but doesn't work well when migrations need to open new connections which results in the lock getting dropped. <add> <add> In order to fix this we are storing the advisory lock on a new connection with the connection specification name `AdisoryLockBase`. The caveat is that we need to maintain at least 2 connections to a database while migrations are running in order to do this. <add> <add> *Eileen M. Uchitelle*, *John Crepezzi* <add> <ide> * Allow schema cache path to be defined in the database configuration file. <ide> <ide> For example: <ide> * Deprecate `#default_hash` and it's alias `#[]` on database configurations <ide> <ide> Applications should use `configs_for`. `#default_hash` and `#[]` will be removed in 6.2. <del> <del> *Eileen M. Uchitelle*, *John Crepezzi* <add>======= <ide> <ide> * Add scale support to `ActiveRecord::Validations::NumericalityValidator`. <ide> <ide><path>activerecord/lib/active_record.rb <ide> module ActiveRecord <ide> extend ActiveSupport::Autoload <ide> <add> autoload :AdvisoryLockBase <ide> autoload :Base <ide> autoload :Callbacks <ide> autoload :Core <ide><path>activerecord/lib/active_record/advisory_lock_base.rb <add># frozen_string_literal: true <add> <add>module ActiveRecord <add> # This class is used to create a connection that we can use for advisory <add> # locks. This will take out a "global" lock that can't be accidentally <add> # removed if a new connection is established during a migration. <add> class AdvisoryLockBase < ActiveRecord::Base # :nodoc: <add> self.abstract_class = true <add> <add> self.connection_specification_name = "AdvisoryLockBase" <add> <add> class << self <add> def _internal? <add> true <add> end <add> end <add> end <add>end <ide><path>activerecord/lib/active_record/migration.rb <ide> def use_advisory_lock? <ide> <ide> def with_advisory_lock <ide> lock_id = generate_migrator_advisory_lock_id <del> connection = Base.connection <add> AdvisoryLockBase.establish_connection(ActiveRecord::Base.connection_db_config) unless AdvisoryLockBase.connected? <add> connection = AdvisoryLockBase.connection <ide> got_lock = connection.get_advisory_lock(lock_id) <ide> raise ConcurrentMigrationError unless got_lock <ide> load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock <ide><path>activerecord/test/cases/migration_test.rb <ide> def migrate(x) <ide> "without an advisory lock, the Migrator should not make any changes, but it did." <ide> end <ide> <add> def test_with_advisory_lock_doesnt_release_closed_connections <add> migration = Class.new(ActiveRecord::Migration::Current).new <add> migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) <add> <add> silence_stream($stderr) do <add> migrator.send(:with_advisory_lock) do <add> ActiveRecord::Base.establish_connection :arunit <add> end <add> end <add> end <add> <ide> def test_with_advisory_lock_raises_the_right_error_when_it_fails_to_release_lock <ide> migration = Class.new(ActiveRecord::Migration::Current).new <ide> migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) <ide> def test_with_advisory_lock_raises_the_right_error_when_it_fails_to_release_lock <ide> e = assert_raises(ActiveRecord::ConcurrentMigrationError) do <ide> silence_stream($stderr) do <ide> migrator.send(:with_advisory_lock) do <del> ActiveRecord::Base.connection.release_advisory_lock(lock_id) <add> ActiveRecord::AdvisoryLockBase.connection.release_advisory_lock(lock_id) <ide> end <ide> end <ide> end
5
Java
Java
bind implementation of parallel
06f5d836a04ad238042da14928635ee09392d316
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import rx.operators.OperationOnErrorResumeNextViaObservable; <ide> import rx.operators.OperationOnErrorReturn; <ide> import rx.operators.OperationOnExceptionResumeNextViaObservable; <del>import rx.operators.OperationParallel; <add>import rx.operators.OperatorParallel; <ide> import rx.operators.OperationParallelMerge; <ide> import rx.operators.OperationRepeat; <ide> import rx.operators.OperationReplay; <ide> public final Observable<T> onExceptionResumeNext(final Observable<? extends T> r <ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#parallel">RxJava Wiki: parallel()</a> <ide> */ <ide> public final <R> Observable<R> parallel(Func1<Observable<T>, Observable<R>> f) { <del> return OperationParallel.parallel(this, f); <add> return bind(new OperatorParallel<T, R>(f, Schedulers.computation())); <ide> } <ide> <ide> /** <ide> public final <R> Observable<R> parallel(Func1<Observable<T>, Observable<R>> f) { <ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Observable-Utility-Operators#parallel">RxJava Wiki: parallel()</a> <ide> */ <ide> public final <R> Observable<R> parallel(final Func1<Observable<T>, Observable<R>> f, final Scheduler s) { <del> return OperationParallel.parallel(this, f, s); <add> return bind(new OperatorParallel<T, R>(f, s)); <ide> } <ide> <ide> /** <ide><path>rxjava-core/src/main/java/rx/operators/OperationParallel.java <del>/** <del> * Copyright 2014 Netflix, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package rx.operators; <del> <del>import java.util.concurrent.atomic.AtomicInteger; <del> <del>import rx.Observable; <del>import rx.Scheduler; <del>import rx.observables.GroupedObservable; <del>import rx.schedulers.Schedulers; <del>import rx.util.functions.Func0; <del>import rx.util.functions.Func1; <del> <del>/** <del> * Identifies unit of work that can be executed in parallel on a given Scheduler. <del> */ <del>public final class OperationParallel<T> { <del> <del> public static <T, R> Observable<R> parallel(Observable<T> source, Func1<Observable<T>, Observable<R>> f) { <del> return parallel(source, f, Schedulers.threadPoolForComputation()); <del> } <del> <del> public static <T, R> Observable<R> parallel(final Observable<T> source, final Func1<Observable<T>, Observable<R>> f, final Scheduler s) { <del> return Observable.defer(new Func0<Observable<R>>() { <del> <del> @Override <del> public Observable<R> call() { <del> final AtomicInteger i = new AtomicInteger(0); <del> return source.groupBy(new Func1<T, Integer>() { <del> <del> @Override <del> public Integer call(T t) { <del> return i.incrementAndGet() % s.degreeOfParallelism(); <del> } <del> <del> }).mergeMap(new Func1<GroupedObservable<Integer, T>, Observable<R>>() { <del> <del> @Override <del> public Observable<R> call(GroupedObservable<Integer, T> group) { <del> return f.call(group.observeOn(s)); <del> } <del> }); <del> } <del> }); <del> } <del>} <ide><path>rxjava-core/src/main/java/rx/operators/OperatorParallel.java <add>/** <add> * Copyright 2014 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package rx.operators; <add> <add>import rx.Observable; <add>import rx.Operator; <add>import rx.Scheduler; <add>import rx.observables.GroupedObservable; <add>import rx.util.functions.Func1; <add> <add>/** <add> * Identifies unit of work that can be executed in parallel on a given Scheduler. <add> */ <add>public final class OperatorParallel<T, R> implements Func1<Operator<? super R>, Operator<? super T>> { <add> <add> private final Scheduler scheduler; <add> private final Func1<Observable<T>, Observable<R>> f; <add> <add> public OperatorParallel(Func1<Observable<T>, Observable<R>> f, Scheduler scheduler) { <add> this.scheduler = scheduler; <add> this.f = f; <add> } <add> <add> @Override <add> public Operator<? super T> call(Operator<? super R> op) { <add> <add> Func1<Operator<? super GroupedObservable<Integer, T>>, Operator<? super T>> groupBy = new OperatorGroupBy<Integer, T>(new Func1<T, Integer>() { <add> <add> int i = 0; <add> <add> @Override <add> public Integer call(T t) { <add> return i++ % scheduler.degreeOfParallelism(); <add> } <add> <add> }); <add> <add> Func1<Operator<? super Observable<R>>, Operator<? super GroupedObservable<Integer, T>>> map = new OperatorMap<GroupedObservable<Integer, T>, Observable<R>>(new Func1<GroupedObservable<Integer, T>, Observable<R>>() { <add> <add> @Override <add> public Observable<R> call(GroupedObservable<Integer, T> g) { <add> return f.call(g.observeOn(scheduler)); <add> } <add> }); <add> <add> // bind together operators <add> return groupBy.call(map.call(new OperatorMerge().call(op))); <add> } <add>} <add><path>rxjava-core/src/test/java/rx/operators/OperatorParallelTest.java <del><path>rxjava-core/src/test/java/rx/operators/OperationParallelTest.java <ide> import rx.util.functions.Action1; <ide> import rx.util.functions.Func1; <ide> <del>public class OperationParallelTest { <add>public class OperatorParallelTest { <ide> <ide> @Test <ide> public void testParallel() {
4
PHP
PHP
add more test variations
5403d02c8f479855eeaaeb39935c0effc1b412bb
<ide><path>tests/Http/HttpRequestTest.php <ide> public function testFilledAnyMethod() <ide> $this->assertTrue($request->filledAny(['name'])); <ide> $this->assertTrue($request->filledAny('name')); <ide> <add> $this->assertFalse($request->filledAny(['age'])); <add> $this->assertFalse($request->filledAny('age')); <add> <add> $this->assertFalse($request->filledAny(['foo'])); <add> $this->assertFalse($request->filledAny('foo')); <add> <ide> $this->assertTrue($request->filledAny(['age', 'name'])); <ide> $this->assertTrue($request->filledAny('age', 'name')); <ide> <ide> public function testFilledAnyMethod() <ide> <ide> $this->assertFalse($request->filledAny('age', 'city')); <ide> $this->assertFalse($request->filledAny('age', 'city')); <add> <add> $this->assertFalse($request->filledAny('foo', 'bar')); <add> $this->assertFalse($request->filledAny('foo', 'bar')); <ide> } <ide> <ide> public function testInputMethod()
1
Javascript
Javascript
remove iife in sigcont handler
223ba43434ef4faad6d199d2e620ece30c278fa9
<ide><path>lib/readline.js <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> if (this.listenerCount('SIGTSTP') > 0) { <ide> this.emit('SIGTSTP'); <ide> } else { <del> process.once('SIGCONT', (function continueProcess(self) { <del> return function() { <del> // Don't raise events if stream has already been abandoned. <del> if (!self.paused) { <del> // Stream must be paused and resumed after SIGCONT to catch <del> // SIGINT, SIGTSTP, and EOF. <del> self.pause(); <del> self.emit('SIGCONT'); <del> } <del> // Explicitly re-enable "raw mode" and move the cursor to <del> // the correct position. <del> // See https://github.com/joyent/node/issues/3295. <del> self._setRawMode(true); <del> self._refreshLine(); <del> }; <del> })(this)); <add> process.once('SIGCONT', () => { <add> // Don't raise events if stream has already been abandoned. <add> if (!this.paused) { <add> // Stream must be paused and resumed after SIGCONT to catch <add> // SIGINT, SIGTSTP, and EOF. <add> this.pause(); <add> this.emit('SIGCONT'); <add> } <add> // Explicitly re-enable "raw mode" and move the cursor to <add> // the correct position. <add> // See https://github.com/joyent/node/issues/3295. <add> this._setRawMode(true); <add> this._refreshLine(); <add> }); <ide> this._setRawMode(false); <ide> process.kill(process.pid, 'SIGTSTP'); <ide> }
1
Javascript
Javascript
fix mistaken typings
11b6713d73c08a4e777a3a85922c76d34de66ed8
<ide><path>lib/Stats.js <ide> class Stats { <ide> } <ide> <ide> /** <del> * @returns {boolean} true if the compilation encountered an error <add> * @returns {boolean} true if the compilation had a warning <ide> */ <ide> hasWarnings() { <ide> return ( <ide> class Stats { <ide> } <ide> <ide> /** <del> * @returns {boolean} true if the compilation had a warning <add> * @returns {boolean} true if the compilation encountered an error <ide> */ <ide> hasErrors() { <ide> return (
1
Ruby
Ruby
test #maximum and #minimum with empty enumerable
5df979dd351b432b151101eb221a3b4dd549625c
<ide><path>activesupport/test/core_ext/enumerable_test.rb <ide> def test_minimum <ide> assert_equal 5, payments.minimum(:price) <ide> end <ide> <add> def test_minimum_with_empty_enumerable <add> payments = GenericEnumerable.new([]) <add> assert_nil payments.minimum(:price) <add> end <add> <ide> def test_maximum <ide> payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ]) <ide> assert_equal 15, payments.maximum(:price) <ide> end <ide> <add> def test_maximum_with_empty_enumerable <add> payments = GenericEnumerable.new([]) <add> assert_nil payments.maximum(:price) <add> end <add> <ide> def test_sums <ide> enum = GenericEnumerable.new([5, 15, 10]) <ide> assert_equal 30, enum.sum
1
Javascript
Javascript
fix addeventlister detection for ie9
e99974004480d968d3fe37ee57540e72bbc96098
<ide><path>src/jqLite.js <ide> var jqCache = {}, <ide> jqName = 'ng-' + new Date().getTime(), <ide> jqId = 1, <del> addEventListenerFn = (window.document.attachEvent ? <del> function(element, type, fn) {element.attachEvent('on' + type, fn);} : <del> function(element, type, fn) {element.addEventListener(type, fn, false);}), <del> removeEventListenerFn = (window.document.detachEvent ? <del> function(element, type, fn) {element.detachEvent('on' + type, fn); } : <del> function(element, type, fn) { element.removeEventListener(type, fn, false); }); <add> addEventListenerFn = (window.document.addEventListener ? <add> function(element, type, fn) {element.addEventListener(type, fn, false);} : <add> function(element, type, fn) {element.attachEvent('on' + type, fn);}), <add> removeEventListenerFn = (window.document.removeEventListener ? <add> function(element, type, fn) {element.removeEventListener(type, fn, false); } : <add> function(element, type, fn) {element.detachEvent('on' + type, fn); }); <ide> <ide> function jqNextId() { return (jqId++); } <ide>
1
Javascript
Javascript
tolerate empty domains. fixes #115
a0fa7a00e5f949adbeb8c2790ae2fbb330ad617f
<ide><path>d3.js <ide> d3.interpolators = [ <ide> function(a, b) { return (typeof b === "number") && d3.interpolateNumber(+a, b); } <ide> ]; <ide> function d3_uninterpolateNumber(a, b) { <del> b = 1 / (b - (a = +a)); <add> b = b - (a = +a) ? 1 / (b - a) : 0; <ide> return function(x) { return (x - a) * b; }; <ide> } <ide> <ide> function d3_uninterpolateClamp(a, b) { <del> b = 1 / (b - (a = +a)); <add> b = b - (a = +a) ? 1 / (b - a) : 0; <ide> return function(x) { return Math.max(0, Math.min(1, (x - a) * b)); }; <ide> } <ide> d3.rgb = function(r, g, b) { <ide><path>d3.min.js <del>(function(){function cF(){return"circle"}function cE(){return 64}function cD(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(cC<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();cC=!e.f&&!e.e,d.remove()}cC?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function cB(a){return function(){var b=a.apply(this,arguments),c=b[0],d=b[1]+bN;return[c*Math.cos(d),c*Math.sin(d)]}}function cA(a){return[a.x,a.y]}function cz(a){return a.endAngle}function cy(a){return a.startAngle}function cx(a){return a.radius}function cw(a){return a.target}function cv(a){return a.source}function cu(a){return function(b,c){return a[c][1]}}function ct(a){return function(b,c){return a[c][0]}}function cs(a){function i(f){if(f.length<1)return null;var i=bU(this,f,b,d),j=bU(this,f,b===c?ct(i):c,d===e?cu(i):e);return"M"+g(a(j),h)+"L"+g(a(i.reverse()),h)+"Z"}var b=bV,c=bV,d=0,e=bW,f="linear",g=bX[f],h=.7;i.x=function(a){if(!arguments.length)return c;b=c=a;return i},i.x0=function(a){if(!arguments.length)return b;b=a;return i},i.x1=function(a){if(!arguments.length)return c;c=a;return i},i.y=function(a){if(!arguments.length)return e;d=e=a;return i},i.y0=function(a){if(!arguments.length)return d;d=a;return i},i.y1=function(a){if(!arguments.length)return e;e=a;return i},i.interpolate=function(a){if(!arguments.length)return f;g=bX[f=a];return i},i.tension=function(a){if(!arguments.length)return h;h=a;return i};return i}function cr(a){var b,c=-1,d=a.length,e,f;while(++c<d)b=a[c],e=b[0],f=b[1]+bN,b[0]=e*Math.cos(f),b[1]=e*Math.sin(f);return a}function cq(a){return a.length<3?bY(a):a[0]+cc(a,cp(a))}function cp(a){var b=[],c,d,e,f,g=co(a),h=-1,i=a.length-1;while(++h<i)c=cn(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function co(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=cn(e,f);while(++b<c)d[b]=g+(g=cn(e=f,f=a[b+1]));d[b]=g;return d}function cn(a,b){return(b[1]-a[1])/(b[0]-a[0])}function cm(a,b,c){a.push("C",ci(cj,b),",",ci(cj,c),",",ci(ck,b),",",ci(ck,c),",",ci(cl,b),",",ci(cl,c))}function ci(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function ch(a,b){var c=a.length-1,d=a[0][0],e=a[0][1],f=a[c][0]-d,g=a[c][1]-e,h=-1,i,j;while(++h<=c)i=a[h],j=h/c,i[0]=b*i[0]+(1-b)*(d+j*f),i[1]=b*i[1]+(1-b)*(e+j*g);return ce(a)}function cg(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[ci(cl,g),",",ci(cl,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),cm(b,g,h);return b.join("")}function cf(a){if(a.length<4)return bY(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(ci(cl,f)+","+ci(cl,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),cm(b,f,g);return b.join("")}function ce(a){if(a.length<3)return bY(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),cm(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cm(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cm(b,h,i);return b.join("")}function cd(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function cc(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bY(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function cb(a,b,c){return a.length<3?bY(a):a[0]+cc(a,cd(a,b))}function ca(a,b){return a.length<3?bY(a):a[0]+cc((a.push(a[0]),a),cd([a[a.length-2]].concat(a,[a[1]]),b))}function b_(a,b){return a.length<4?bY(a):a[1]+cc(a.slice(1,a.length-1),cd(a,b))}function b$(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bZ(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bY(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bW(a){return a[1]}function bV(a){return a[0]}function bU(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bT(a){function g(d){return d.length<1?null:"M"+e(a(bU(this,d,b,c)),f)}var b=bV,c=bW,d="linear",e=bX[d],f=.7;g.x=function(a){if(!arguments.length)return b;b=a;return g},g.y=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bX[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g}function bS(a){return a.endAngle}function bR(a){return a.startAngle}function bQ(a){return a.outerRadius}function bP(a){return a.innerRadius}function bM(a,b,c){function g(){d=c.length/(b-a),e=c.length-1;return f}function f(b){return c[Math.max(0,Math.min(e,Math.floor(d*(b-a))))]}var d,e;f.domain=function(c){if(!arguments.length)return[a,b];a=+c[0],b=+c[c.length-1];return g()},f.range=function(a){if(!arguments.length)return c;c=a;return g()},f.copy=function(){return bM(a,b,c)};return g()}function bL(a,b){function e(a){return isNaN(a=+a)?NaN:b[d3.bisect(c,a)]}function d(){var d=0,f=a.length,g=b.length;c=[];while(++d<g)c[d-1]=d3.quantile(a,d/g);return e}var c;e.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending);return d()},e.range=function(a){if(!arguments.length)return b;b=a;return d()},e.quantiles=function(){return c},e.copy=function(){return bL(a,b)};return d()}function bG(a,b,c){function f(c){return d[((a[c]||(a[c]=++b))-1)%d.length]}var d,e;f.domain=function(d){if(!arguments.length)return d3.keys(a);a={},b=0;var e=-1,g=d.length,h;while(++e<g)a[h=d[e]]||(a[h]=++b);return f[c.t](c.x,c.p)},f.range=function(a){if(!arguments.length)return d;d=a,e=0,c={t:"range",x:a};return f},f.rangePoints=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=(i-h)/(b-1+g);d=b<2?[(h+i)/2]:d3.range(h+j*g/2,i+j/2,j),e=0,c={t:"rangePoints",x:a,p:g};return f},f.rangeBands=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=(i-h)/(b+g);d=d3.range(h+j*g,i,j),e=j*(1-g),c={t:"rangeBands",x:a,p:g};return f},f.rangeRoundBands=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=Math.floor((i-h)/(b+g)),k=i-h-(b-g)*j;d=d3.range(h+Math.round(k/2),i,j),e=Math.round(j*(1-g)),c={t:"rangeRoundBands",x:a,p:g};return f},f.rangeBand=function(){return e},f.copy=function(){var d={},e;for(e in a)d[e]=a[e];return bG(d,b,c)};return f[c.t](c.x,c.p)}function bF(a){return function(b){return b<0?-Math.pow(-b,a):Math.pow(b,a)}}function bE(a,b){function e(b){return a(c(b))}var c=bF(b),d=bF(1/b);e.invert=function(b){return d(a.invert(b))},e.domain=function(b){if(!arguments.length)return a.domain().map(d);a.domain(b.map(c));return e},e.ticks=function(a){return bw(e.domain(),a)},e.tickFormat=function(a){return bx(e.domain(),a)},e.nice=function(){return e.domain(bq(e.domain(),bu))},e.exponent=function(a){if(!arguments.length)return b;var f=e.domain();c=bF(b=a),d=bF(1/b);return e.domain(f)},e.copy=function(){return bE(a.copy(),b)};return bt(e,a)}function bD(a){return a.toPrecision(1)}function bC(a){return-Math.log(-a)/Math.LN10}function bB(a){return Math.log(a)/Math.LN10}function bA(a,b){function d(c){return a(b(c))}var c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=e[0]<0?bC:bB,c=b.pow,a.domain(e.map(b));return d},d.nice=function(){a.domain(bq(a.domain(),br));return d},d.ticks=function(){var d=bp(a.domain()),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bC){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return bD},d.copy=function(){return bA(a.copy(),b)};return bt(d,a)}function bz(a,b,c,d){var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(b){var c=d3.bisect(a,b,1,a.length-1)-1;return f[c](e[c](b))}}function by(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bx(a,b){return d3.format(",."+Math.max(0,-Math.floor(Math.log(bv(a,b)[2])/Math.LN10+.01))+"f")}function bw(a,b){return d3.range.apply(d3,bv(a,b))}function bv(a,b){var c=bp(a),d=c[1]-c[0],e=Math.pow(10,Math.floor(Math.log(d/b)/Math.LN10)),f=b/d*e;f<=.15?e*=10:f<=.35?e*=5:f<=.75&&(e*=2),c[0]=Math.ceil(c[0]/e)*e,c[1]=Math.floor(c[1]/e)*e+e*.5,c[2]=e;return c}function bu(a){a=Math.pow(10,Math.round(Math.log(a)/Math.LN10)-1);return{floor:function(b){return Math.floor(b/a)*a},ceil:function(b){return Math.ceil(b/a)*a}}}function bt(a,b){a.range=d3.rebind(a,b.range),a.rangeRound=d3.rebind(a,b.rangeRound),a.interpolate=d3.rebind(a,b.interpolate),a.clamp=d3.rebind(a,b.clamp);return a}function bs(a,b,c,d){function h(a){return e(a)}function g(){var g=a.length==2?by:bz,i=d?G:F;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(b){return bw(a,b)},h.tickFormat=function(b){return bx(a,b)},h.nice=function(){bq(a,bu);return g()},h.copy=function(){return bs(a,b,c,d)};return g()}function br(){return Math}function bq(a,b){var c=0,d=a.length-1,e=a[c],f=a[d],g;f<e&&(g=c,c=d,d=g,g=e,e=f,f=g),b=b(f-e),a[c]=b.floor(e),a[d]=b.ceil(f);return a}function bp(a){var b=a[0],c=a[a.length-1];return b<c?[b,c]:[c,b]}function bo(){}function bm(){var a=null,b=bi,c=Infinity;while(b)b.flush?b=a?a.next=b.next:bi=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bl(){var a,b=Date.now(),c=bi;while(c)a=b-c.then,a>=c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bm()-b;d>24?(isFinite(d)&&(clearTimeout(bk),bk=setTimeout(bl,d)),bj=0):(bj=1,bn(bl))}function bh(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];g&&a.call(g=g.node,g.__data__,e,b)}return this}function bc(a){return typeof a=="function"?function(b,c,d){var e=a.call(this,b,c)+"";return d!=e&&d3.interpolate(d,e)}:(a=a+"",function(b,c,d){return d!=a&&d3.interpolate(d,a)})}function bb(a,b){e(a,bd);var c={},d=d3.dispatch("start","end"),f=bg;a.id=b,a.tween=function(b,d){if(arguments.length<2)return c[b];d==null?delete c[b]:c[b]=d;return a},a.ease=function(b){if(!arguments.length)return f;f=typeof b=="function"?b:d3.ease.apply(d3,arguments);return a},a.each=function(b,c){if(arguments.length<2)return bh.call(a,b);d[b].add(c);return a},d3.timer(function(e){a.each(function(g,h,i){function p(a){if(n.active!==b)return!0;var c=Math.min(1,(a-l)/m),e=f(c),i=j.length;while(--i>=0)j[i].call(k,e);if(c===1){n.active=0,n.owner===b&&delete k.__transition__,bf=b,d.end.dispatch.call(k,g,h),bf=0;return!0}}function o(a){if(n.active<=b){n.active=b,d.start.dispatch.call(k,g,h);for(var e in c)(e=c[e].call(k,g,h))&&j.push(e);l-=a,d3.timer(p)}return!0}var j=[],k=this,l=a[i][h].delay-e,m=a[i][h].duration,n=k.__transition__;n?n.owner<b&&(n.owner=b):n=k.__transition__={active:0,owner:b},l<=0?o(0):d3.timer(o,l)});return!0});return a}function ba(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function $(a){e(a,_);return a}function Z(a){return{__data__:a}}function Y(a){return function(b){return U(a,b)}}function X(a){return function(b){return T(a,b)}}function S(a){e(a,V);return a}function R(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);return a<60?d+(e-d)*a/60:a<180?e:a<240?d+(e-d)*(240-a)/60:d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return H(g(a+120),g(a),g(a-120))}function Q(a,b,c){this.h=a,this.s=b,this.l=c}function P(a,b,c){return new Q(a,b,c)}function M(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function L(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return P(g,h,i)}function K(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(M(h[0]),M(h[1]),M(h[2]))}}if(i=N[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function J(a){return a<16?"0"+a.toString(16):a.toString(16)}function I(a,b,c){this.r=a,this.g=b,this.b=c}function H(a,b,c){return new I(a,b,c)}function G(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function F(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function E(a){return a in D||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function B(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function A(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function z(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function y(a){return 1-Math.sqrt(1-a*a)}function x(a){return Math.pow(2,10*(a-1))}function w(a){return 1-Math.cos(a*Math.PI/2)}function v(a){return function(b){return Math.pow(b,a)}}function u(a){return a}function t(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function s(a){return function(b){return 1-a(1-b)}}function n(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function m(a){return a+""}function j(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function h(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function g(a){return a==null}function f(a){return a.length}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.29.7"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}var e=[].__proto__?function(a,b){a.__proto__=b}:function(a,b){for(var c in b)a[c]=b[c]};d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:a>=b?0:NaN},d3.descending=function(a,b){return b<a?-1:b>a?1:b>=a?0:NaN},d3.min=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&e>f&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&e>f&&(e=f)}return e},d3.max=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&f>e&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&f>e&&(e=f)}return e},d3.sum=function(a,b){var c=0,d=a.length,e,f=-1;if(arguments.length===1)while(++f<d)isNaN(e=+a[f])||(c+=e);else while(++f<d)isNaN(e=+b.call(a,a[f],f))||(c+=e);return c},d3.quantile=function(a,b){var c=(a.length-1)*b+1,d=Math.floor(c),e=a[d-1],f=c-d;return f?e+f*(a[d]-e):e},d3.zip=function(){if(!(e=arguments.length))return[];for(var a=-1,b=d3.min(arguments,f),c=Array(b);++a<b;)for(var d=-1,e,g=c[a]=Array(e);++d<e;)g[d]=arguments[d][a];return c},d3.bisectLeft=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;a[e]<b?c=e+1:d=e}return c},d3.bisect=d3.bisectRight=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;b<a[e]?d=e:c=e+1}return c},d3.first=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])>0&&(e=f);return e},d3.last=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])<=0&&(e=f);return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],e,f=-1,h=a.length;arguments.length<2&&(b=g);while(++f<h)b.call(d,e=a[f],f)?d=[]:(d.length||c.push(d),d.push(e));return c},d3.range=function(a,b,c){arguments.length<3&&(c=1,arguments.length<2&&(b=a,a=0));if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(i,"\\$&")};var i=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;d3.round=function(a,b){return b?Math.round(a*Math.pow(10,b))*Math.pow(10,-b):Math.round(a)},d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=j(c);return b},d3.format=function(a){var b=k.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9],j=!1,o=!1;h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4)));switch(i){case"n":g=!0,i="g";break;case"%":j=!0,i="f";break;case"p":j=!0,i="r";break;case"d":o=!0,h="0"}i=l[i]||m;return function(a){var b=j?a*100:+a,k=b<0&&(b=-b)?"−":d;if(o&&b%1)return"";a=i(b,h);if(e){var l=a.length+k.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=n(a)),a=k+a}else{g&&(a=n(a)),a=k+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}j&&(a+="%");return a}};var k=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l={g:function(a,b){return a.toPrecision(b)},e:function(a,b){return a.toExponential(b)},f:function(a,b){return a.toFixed(b)},r:function(a,b){var c=1+Math.floor(1e-15+Math.log(a)/Math.LN10);return d3.round(a,b-c).toFixed(Math.max(0,Math.min(20,b-c)))}},o=v(2),p=v(3),q={linear:function(){return u},poly:v,quad:function(){return o},cubic:function(){return p},sin:function(){return w},exp:function(){return x},circle:function(){return y},elastic:z,back:A,bounce:function(){return B}},r={"in":function(a){return a},out:s,"in-out":t,"out-in":function(a){return t(s(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return r[d](q[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){var c=d3.interpolators.length,d;while(--c>=0&&!(d=d3.interpolators[c](a,b)));return d},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;C.lastIndex=0;for(d=0;c=C.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=C.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=C.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;return h.length===1?h[0]==null?i[0].x:function(){return b}:function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return R(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=E(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var C=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,D={background:1,fill:1,stroke:1};d3.interpolators=[d3.interpolateObject,function(a,b){return b instanceof Array&&d3.interpolateArray(a,b)},function(a,b){return typeof b=="string"&&d3.interpolateString(String(a),b)},function(a,b){return(typeof b=="string"?b in N||/^(#|rgb\(|hsl\()/.test(b):b instanceof I||b instanceof Q)&&d3.interpolateRgb(String(a),b)},function(a,b){return typeof b=="number"&&d3.interpolateNumber(+a,b)}],d3.rgb=function(a,b,c){return arguments.length===1?K(""+a,H,R):H(~~a,~~b,~~c)},I.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return H(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return H(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},I.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return H(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},I.prototype.hsl=function(){return L(this.r,this.g,this.b)},I.prototype.toString=function(){return"#"+J(this.r)+J(this.g)+J(this.b)};var N={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var O in N)N[O]=K(N[O],H,R);d3.hsl=function(a,b,c){return arguments.length===1?K(""+a,L,P):P(+a,+b,+c)},Q.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return P(this.h,this.s,this.l/a)},Q.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return P(this.h,this.s,a*this.l)},Q.prototype.rgb=function(){return R(this.h,this.s,this.l)},Q.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"},d3.select=function(a){return typeof a=="string"?W.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?W.selectAll(b):S([a(b)])};var T=function(a,b){return b.querySelector(a)},U=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(T=function(a,b){return Sizzle(a,b)[0]},U=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var V=[],W=S([[document]]);W[0].parentNode=document.documentElement,d3.selection=function(){return W},d3.selection.prototype=V,V.select=function(a){var b=[],c,d,e,f;typeof a!="function"&&(a=X(a));for(var g=-1,h=this.length;++g<h;){b.push(c=[]),c.parentNode=(e=this[g]).parentNode;for(var i=-1,j=e.length;++i<j;)(f=e[i])?(c.push(d=a(f)),d&&"__data__"in f&&(d.__data__=f.__data__)):c.push(null)}return S(b)},V.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h])b.push(c=a(d)),c.parentNode=d;return S(b)},V.attr=function(a,b){function i(){var c=b.apply(this,arguments);c==null?this.removeAttributeNS(a.space,a.local):this.setAttributeNS(a.space,a.local,c)}function h(){var c=b.apply(this,arguments);c==null?this.removeAttribute(a):this.setAttribute(a,c)}function g(){this.setAttributeNS(a.space,a.local,b)}function f(){this.setAttribute(a,b)}function e(){this.removeAttributeNS(a.space,a.local)}function d(){this.removeAttribute(a)}a=d3.ns.qualify(a);if(arguments.length<2){var c=this.node();return a.local?c.getAttributeNS(a.space,a.local):c.getAttribute(a)}return this.each(b==null?a.local?e:d:typeof b=="function"?a.local?i:h:a.local?g:f)},V.classed=function(a,b){function i(){(b.apply(this,arguments)?f:g).call(this)}function g(){if(b=this.classList)return b.remove(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;e=h(e.replace(c," ")),d?b.baseVal=e:this.className=e}function f(){if(b=this.classList)return b.add(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;c.lastIndex=0,c.test(e)||(e=h(e+" "+a),d?b.baseVal=e:this.className=e)}var c=new RegExp("(^|\\s+)"+d3.requote(a)+"(\\s+|$)","g");if(arguments.length<2){var d=this.node();if(e=d.classList)return e.contains(a);var e=d.className;c.lastIndex=0;return c.test(e.baseVal!=null?e.baseVal:e)}return this.each(typeof b=="function"?i:b?f:g)},V.style=function(a,b,c){function f(){var d=b.apply(this,arguments);d==null?this.style.removeProperty(a):this.style.setProperty(a,d,c)}function e(){this.style.setProperty(a,b,c)}function d(){this.style.removeProperty(a)}arguments.length<3&&(c="");return arguments.length<2?window.getComputedStyle(this.node(),null).getPropertyValue(a):this.each(b==null?d:typeof b=="function"?f:e)},V.property=function(a,b){function e(){var c=b.apply(this,arguments);c==null?delete this[a]:this[a]=c}function d(){this[a]=b}function c(){delete this[a]}return arguments.length<2?this.node()[a]:this.each(b==null?c:typeof b=="function"?e:d)},V.text=function(a){return arguments.length<1?this.node().textContent:this.each(typeof a=="function"?function(){this.textContent=a.apply(this,arguments)}:function(){this.textContent=a})},V.html=function(a){return arguments.length<1?this.node().innerHTML:this.each(typeof a=="function"?function(){this.innerHTML=a.apply(this,arguments)}:function(){this.innerHTML=a})},V.append=function(a){function c(b){return b.appendChild(document.createElementNS(a.space,a.local))}function b(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return this.select(a.local?c:b)},V.insert=function(a,b){function d(c){return c.insertBefore(document.createElementNS(a.space,a.local),T(b,c))}function c(c){return c.insertBefore(document.createElement(a),T(b,c))}a=d3.ns.qualify(a);return this.select(a.local?d:c)},V.remove=function(){return this.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},V.data=function(a,b){function f(a,f){var g,h=a.length,i=f.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(b){var q={},r=[],s,t=f.length;for(g=-1;++g<h;)s=b.call(o=a[g],o.__data__,g),s in q?n[t++]=o:q[s]=o,r.push(s);for(g=-1;++g<i;)o=q[s=b.call(f,p=f[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null),delete q[s];for(g=-1;++g<h;)r[g]in q&&(n[g]=a[g])}else{for(g=-1;++g<j;)o=a[g],p=f[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null) <del>:(m[g]=Z(p),l[g]=n[g]=null);for(;g<i;++g)m[g]=Z(f[g]),l[g]=n[g]=null;for(;g<k;++g)n[g]=a[g],m[g]=l[g]=null}m.update=l,m.parentNode=l.parentNode=n.parentNode=a.parentNode,c.push(m),d.push(l),e.push(n)}var c=[],d=[],e=[],g=-1,h=this.length,i;if(typeof a=="function")while(++g<h)f(i=this[g],a.call(i,i.parentNode.__data__,g));else while(++g<h)f(i=this[g],a);var j=S(d);j.enter=function(){return $(c)},j.exit=function(){return S(e)};return j};var _=[];_.append=V.append,_.insert=V.insert,_.empty=V.empty,_.select=function(a){var b=[],c,d,e,f,g;for(var h=-1,i=this.length;++h<i;){e=(f=this[h]).update,b.push(c=[]),c.parentNode=f.parentNode;for(var j=-1,k=f.length;++j<k;)(g=f[j])?(c.push(e[j]=d=a(f.parentNode)),d.__data__=g.__data__):c.push(null)}return S(b)},V.filter=function(a){var b=[],c,d,e;for(var f=0,g=this.length;f<g;f++){b.push(c=[]),c.parentNode=(d=this[f]).parentNode;for(var h=0,i=d.length;h<i;h++)(e=d[h])&&a.call(e,e.__data__,h)&&c.push(e)}return S(b)},V.map=function(a){return this.each(function(){this.__data__=a.apply(this,arguments)})},V.sort=function(a){a=ba.apply(this,arguments);for(var b=0,c=this.length;b<c;b++)for(var d=this[b].sort(a),e=1,f=d.length,g=d[0];e<f;e++){var h=d[e];h&&(g&&g.parentNode.insertBefore(h,g.nextSibling),g=h)}return this},V.on=function(a,b,c){arguments.length<3&&(c=!1);var d=a.indexOf("."),e=d===-1?a:a.substring(0,d),f="__on"+a;return this.each(function(a,d){function h(a){var c=d3.event;d3.event=a;try{b.call(this,g.__data__,d)}finally{d3.event=c}}this[f]&&this.removeEventListener(e,this[f],c),b&&this.addEventListener(e,this[f]=h,c);var g=this})},V.each=function(a){for(var b=-1,c=this.length;++b<c;)for(var d=this[b],e=-1,f=d.length;++e<f;){var g=d[e];g&&a.call(g,g.__data__,e,b)}return this},V.call=function(a){a.apply(this,(arguments[0]=this,arguments));return this},V.empty=function(){return!this.node()},V.node=function(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];if(g)return g}return null},V.transition=function(){var a=[],b,c;for(var d=-1,e=this.length;++d<e;){a.push(b=[]);for(var f=this[d],g=-1,h=f.length;++g<h;)b.push((c=f[g])?{node:c,delay:0,duration:250}:null)}return bb(a,bf||++be)};var bd=[],be=0,bf=0,bg=d3.ease("cubic-in-out");bd.call=V.call,d3.transition=function(){return W.transition()},d3.transition.prototype=bd,bd.select=function(a){var b=[],c,d,e;typeof a!="function"&&(a=X(a));for(var f=-1,g=this.length;++f<g;){b.push(c=[]);for(var h=this[f],i=-1,j=h.length;++i<j;)(e=h[i])&&(d=a(e.node))?("__data__"in e.node&&(d.__data__=e.node.__data__),c.push({node:d,delay:e.delay,duration:e.duration})):c.push(null)}return bb(b,this.id).ease(this.ease())},bd.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h]){b.push(c=a(d.node));for(var j=-1,k=c.length;++j<k;)c[j]={node:c[j],delay:d.delay,duration:d.duration}}return bb(b,this.id).ease(this.ease())},bd.attr=function(a,b){return this.attrTween(a,bc(b))},bd.attrTween=function(a,b){function d(c,d){var e=b.call(this,c,d,this.getAttributeNS(a.space,a.local));return e&&function(b){this.setAttributeNS(a.space,a.local,e(b))}}function c(c,d){var e=b.call(this,c,d,this.getAttribute(a));return e&&function(b){this.setAttribute(a,e(b))}}a=d3.ns.qualify(a);return this.tween("attr."+a,a.local?d:c)},bd.style=function(a,b,c){arguments.length<3&&(c=null);return this.styleTween(a,bc(b),c)},bd.styleTween=function(a,b,c){arguments.length<3&&(c=null);return this.tween("style."+a,function(d,e){var f=b.call(this,d,e,window.getComputedStyle(this,null).getPropertyValue(a));return f&&function(b){this.style.setProperty(a,f(b),c)}})},bd.text=function(a){return this.tween("text",function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a})},bd.remove=function(){return this.each("end",function(){var a;!this.__transition__&&(a=this.parentNode)&&a.removeChild(this)})},bd.delay=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].delay=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].delay=a}))},bd.duration=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].duration=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].duration=a}))};var bi=null,bj,bk;d3.timer=function(a,b){var c=Date.now(),d=!1,e,f=bi;if(arguments.length<2)b=0;else if(!isFinite(b))return;while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(bi={callback:a,then:c,delay:b,next:bi}),bj||(bk=clearTimeout(bk),bj=1,bn(bl))},d3.timer.flush=function(){var a,b=Date.now(),c=bi;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bm()};var bn=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){return bs([0,1],[0,1],d3.interpolate,!1)},d3.scale.log=function(){return bA(d3.scale.linear(),bB)},bB.pow=function(a){return Math.pow(10,a)},bC.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){return bE(d3.scale.linear(),1)},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){return bG({},0,{t:"range",x:[]})},d3.scale.category10=function(){return d3.scale.ordinal().range(bH)},d3.scale.category20=function(){return d3.scale.ordinal().range(bI)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bJ)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bK)};var bH=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bI=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bJ=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bK=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){return bL([],[])},d3.scale.quantize=function(){return bM(0,1,[0,1])},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bN,h=d.apply(this,arguments)+bN,i=(h<g&&(i=g,g=h,h=i),h-g),j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bO?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bP,b=bQ,c=bR,d=bS;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bN;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bN=-Math.PI/2,bO=2*Math.PI-1e-6;d3.svg.line=function(){return bT(Object)};var bX={linear:bY,"step-before":bZ,"step-after":b$,basis:ce,"basis-open":cf,"basis-closed":cg,bundle:ch,cardinal:cb,"cardinal-open":b_,"cardinal-closed":ca,monotone:cq},cj=[0,2/3,1/3,0],ck=[0,1/3,2/3,0],cl=[0,1/6,2/3,1/6];d3.svg.line.radial=function(){var a=bT(cr);a.radius=a.x,delete a.x,a.angle=a.y,delete a.y;return a},d3.svg.area=function(){return cs(Object)},d3.svg.area.radial=function(){var a=cs(cr);a.radius=a.x,delete a.x,a.innerRadius=a.x0,delete a.x0,a.outerRadius=a.x1,delete a.x1,a.angle=a.y,delete a.y,a.startAngle=a.y0,delete a.y0,a.endAngle=a.y1,delete a.y1;return a},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bN,k=e.call(a,h,g)+bN;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=cv,b=cw,c=cx,d=bR,e=bS;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=cv,b=cw,c=cA;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.diagonal.radial=function(){var a=d3.svg.diagonal(),b=cA,c=a.projection;a.projection=function(a){return arguments.length?c(cB(b=a)):b};return a},d3.svg.mouse=function(a){return cD(a,d3.event)};var cC=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(b){var c=d3.event.touches;return c?a(c).map(function(a){var c=cD(b,a);c.identifier=a.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cG[a.call(this,c,d)]||cG.circle)(b.call(this,c,d))}var a=cF,b=cE;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c};var cG={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cI)),c=b*cI;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cH),c=b*cH/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cH),c=b*cH/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}};d3.svg.symbolTypes=d3.keys(cG);var cH=Math.sqrt(3),cI=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <add>(function(){function cF(){return"circle"}function cE(){return 64}function cD(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(cC<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();cC=!e.f&&!e.e,d.remove()}cC?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function cB(a){return function(){var b=a.apply(this,arguments),c=b[0],d=b[1]+bN;return[c*Math.cos(d),c*Math.sin(d)]}}function cA(a){return[a.x,a.y]}function cz(a){return a.endAngle}function cy(a){return a.startAngle}function cx(a){return a.radius}function cw(a){return a.target}function cv(a){return a.source}function cu(a){return function(b,c){return a[c][1]}}function ct(a){return function(b,c){return a[c][0]}}function cs(a){function i(f){if(f.length<1)return null;var i=bU(this,f,b,d),j=bU(this,f,b===c?ct(i):c,d===e?cu(i):e);return"M"+g(a(j),h)+"L"+g(a(i.reverse()),h)+"Z"}var b=bV,c=bV,d=0,e=bW,f="linear",g=bX[f],h=.7;i.x=function(a){if(!arguments.length)return c;b=c=a;return i},i.x0=function(a){if(!arguments.length)return b;b=a;return i},i.x1=function(a){if(!arguments.length)return c;c=a;return i},i.y=function(a){if(!arguments.length)return e;d=e=a;return i},i.y0=function(a){if(!arguments.length)return d;d=a;return i},i.y1=function(a){if(!arguments.length)return e;e=a;return i},i.interpolate=function(a){if(!arguments.length)return f;g=bX[f=a];return i},i.tension=function(a){if(!arguments.length)return h;h=a;return i};return i}function cr(a){var b,c=-1,d=a.length,e,f;while(++c<d)b=a[c],e=b[0],f=b[1]+bN,b[0]=e*Math.cos(f),b[1]=e*Math.sin(f);return a}function cq(a){return a.length<3?bY(a):a[0]+cc(a,cp(a))}function cp(a){var b=[],c,d,e,f,g=co(a),h=-1,i=a.length-1;while(++h<i)c=cn(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function co(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=cn(e,f);while(++b<c)d[b]=g+(g=cn(e=f,f=a[b+1]));d[b]=g;return d}function cn(a,b){return(b[1]-a[1])/(b[0]-a[0])}function cm(a,b,c){a.push("C",ci(cj,b),",",ci(cj,c),",",ci(ck,b),",",ci(ck,c),",",ci(cl,b),",",ci(cl,c))}function ci(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function ch(a,b){var c=a.length-1,d=a[0][0],e=a[0][1],f=a[c][0]-d,g=a[c][1]-e,h=-1,i,j;while(++h<=c)i=a[h],j=h/c,i[0]=b*i[0]+(1-b)*(d+j*f),i[1]=b*i[1]+(1-b)*(e+j*g);return ce(a)}function cg(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[ci(cl,g),",",ci(cl,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),cm(b,g,h);return b.join("")}function cf(a){if(a.length<4)return bY(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(ci(cl,f)+","+ci(cl,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),cm(b,f,g);return b.join("")}function ce(a){if(a.length<3)return bY(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),cm(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cm(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),cm(b,h,i);return b.join("")}function cd(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function cc(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bY(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function cb(a,b,c){return a.length<3?bY(a):a[0]+cc(a,cd(a,b))}function ca(a,b){return a.length<3?bY(a):a[0]+cc((a.push(a[0]),a),cd([a[a.length-2]].concat(a,[a[1]]),b))}function b_(a,b){return a.length<4?bY(a):a[1]+cc(a.slice(1,a.length-1),cd(a,b))}function b$(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bZ(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bY(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bW(a){return a[1]}function bV(a){return a[0]}function bU(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bT(a){function g(d){return d.length<1?null:"M"+e(a(bU(this,d,b,c)),f)}var b=bV,c=bW,d="linear",e=bX[d],f=.7;g.x=function(a){if(!arguments.length)return b;b=a;return g},g.y=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bX[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g}function bS(a){return a.endAngle}function bR(a){return a.startAngle}function bQ(a){return a.outerRadius}function bP(a){return a.innerRadius}function bM(a,b,c){function g(){d=c.length/(b-a),e=c.length-1;return f}function f(b){return c[Math.max(0,Math.min(e,Math.floor(d*(b-a))))]}var d,e;f.domain=function(c){if(!arguments.length)return[a,b];a=+c[0],b=+c[c.length-1];return g()},f.range=function(a){if(!arguments.length)return c;c=a;return g()},f.copy=function(){return bM(a,b,c)};return g()}function bL(a,b){function e(a){return isNaN(a=+a)?NaN:b[d3.bisect(c,a)]}function d(){var d=0,f=a.length,g=b.length;c=[];while(++d<g)c[d-1]=d3.quantile(a,d/g);return e}var c;e.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending);return d()},e.range=function(a){if(!arguments.length)return b;b=a;return d()},e.quantiles=function(){return c},e.copy=function(){return bL(a,b)};return d()}function bG(a,b,c){function f(c){return d[((a[c]||(a[c]=++b))-1)%d.length]}var d,e;f.domain=function(d){if(!arguments.length)return d3.keys(a);a={},b=0;var e=-1,g=d.length,h;while(++e<g)a[h=d[e]]||(a[h]=++b);return f[c.t](c.x,c.p)},f.range=function(a){if(!arguments.length)return d;d=a,e=0,c={t:"range",x:a};return f},f.rangePoints=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=(i-h)/(b-1+g);d=b<2?[(h+i)/2]:d3.range(h+j*g/2,i+j/2,j),e=0,c={t:"rangePoints",x:a,p:g};return f},f.rangeBands=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=(i-h)/(b+g);d=d3.range(h+j*g,i,j),e=j*(1-g),c={t:"rangeBands",x:a,p:g};return f},f.rangeRoundBands=function(a,g){arguments.length<2&&(g=0);var h=a[0],i=a[1],j=Math.floor((i-h)/(b+g)),k=i-h-(b-g)*j;d=d3.range(h+Math.round(k/2),i,j),e=Math.round(j*(1-g)),c={t:"rangeRoundBands",x:a,p:g};return f},f.rangeBand=function(){return e},f.copy=function(){var d={},e;for(e in a)d[e]=a[e];return bG(d,b,c)};return f[c.t](c.x,c.p)}function bF(a){return function(b){return b<0?-Math.pow(-b,a):Math.pow(b,a)}}function bE(a,b){function e(b){return a(c(b))}var c=bF(b),d=bF(1/b);e.invert=function(b){return d(a.invert(b))},e.domain=function(b){if(!arguments.length)return a.domain().map(d);a.domain(b.map(c));return e},e.ticks=function(a){return bw(e.domain(),a)},e.tickFormat=function(a){return bx(e.domain(),a)},e.nice=function(){return e.domain(bq(e.domain(),bu))},e.exponent=function(a){if(!arguments.length)return b;var f=e.domain();c=bF(b=a),d=bF(1/b);return e.domain(f)},e.copy=function(){return bE(a.copy(),b)};return bt(e,a)}function bD(a){return a.toPrecision(1)}function bC(a){return-Math.log(-a)/Math.LN10}function bB(a){return Math.log(a)/Math.LN10}function bA(a,b){function d(c){return a(b(c))}var c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=e[0]<0?bC:bB,c=b.pow,a.domain(e.map(b));return d},d.nice=function(){a.domain(bq(a.domain(),br));return d},d.ticks=function(){var d=bp(a.domain()),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bC){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return bD},d.copy=function(){return bA(a.copy(),b)};return bt(d,a)}function bz(a,b,c,d){var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(b){var c=d3.bisect(a,b,1,a.length-1)-1;return f[c](e[c](b))}}function by(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bx(a,b){return d3.format(",."+Math.max(0,-Math.floor(Math.log(bv(a,b)[2])/Math.LN10+.01))+"f")}function bw(a,b){return d3.range.apply(d3,bv(a,b))}function bv(a,b){var c=bp(a),d=c[1]-c[0],e=Math.pow(10,Math.floor(Math.log(d/b)/Math.LN10)),f=b/d*e;f<=.15?e*=10:f<=.35?e*=5:f<=.75&&(e*=2),c[0]=Math.ceil(c[0]/e)*e,c[1]=Math.floor(c[1]/e)*e+e*.5,c[2]=e;return c}function bu(a){a=Math.pow(10,Math.round(Math.log(a)/Math.LN10)-1);return{floor:function(b){return Math.floor(b/a)*a},ceil:function(b){return Math.ceil(b/a)*a}}}function bt(a,b){a.range=d3.rebind(a,b.range),a.rangeRound=d3.rebind(a,b.rangeRound),a.interpolate=d3.rebind(a,b.interpolate),a.clamp=d3.rebind(a,b.clamp);return a}function bs(a,b,c,d){function h(a){return e(a)}function g(){var g=a.length==2?by:bz,i=d?G:F;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(b){return bw(a,b)},h.tickFormat=function(b){return bx(a,b)},h.nice=function(){bq(a,bu);return g()},h.copy=function(){return bs(a,b,c,d)};return g()}function br(){return Math}function bq(a,b){var c=0,d=a.length-1,e=a[c],f=a[d],g;f<e&&(g=c,c=d,d=g,g=e,e=f,f=g),b=b(f-e),a[c]=b.floor(e),a[d]=b.ceil(f);return a}function bp(a){var b=a[0],c=a[a.length-1];return b<c?[b,c]:[c,b]}function bo(){}function bm(){var a=null,b=bi,c=Infinity;while(b)b.flush?b=a?a.next=b.next:bi=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bl(){var a,b=Date.now(),c=bi;while(c)a=b-c.then,a>=c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bm()-b;d>24?(isFinite(d)&&(clearTimeout(bk),bk=setTimeout(bl,d)),bj=0):(bj=1,bn(bl))}function bh(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];g&&a.call(g=g.node,g.__data__,e,b)}return this}function bc(a){return typeof a=="function"?function(b,c,d){var e=a.call(this,b,c)+"";return d!=e&&d3.interpolate(d,e)}:(a=a+"",function(b,c,d){return d!=a&&d3.interpolate(d,a)})}function bb(a,b){e(a,bd);var c={},d=d3.dispatch("start","end"),f=bg;a.id=b,a.tween=function(b,d){if(arguments.length<2)return c[b];d==null?delete c[b]:c[b]=d;return a},a.ease=function(b){if(!arguments.length)return f;f=typeof b=="function"?b:d3.ease.apply(d3,arguments);return a},a.each=function(b,c){if(arguments.length<2)return bh.call(a,b);d[b].add(c);return a},d3.timer(function(e){a.each(function(g,h,i){function p(a){if(n.active!==b)return!0;var c=Math.min(1,(a-l)/m),e=f(c),i=j.length;while(--i>=0)j[i].call(k,e);if(c===1){n.active=0,n.owner===b&&delete k.__transition__,bf=b,d.end.dispatch.call(k,g,h),bf=0;return!0}}function o(a){if(n.active<=b){n.active=b,d.start.dispatch.call(k,g,h);for(var e in c)(e=c[e].call(k,g,h))&&j.push(e);l-=a,d3.timer(p)}return!0}var j=[],k=this,l=a[i][h].delay-e,m=a[i][h].duration,n=k.__transition__;n?n.owner<b&&(n.owner=b):n=k.__transition__={active:0,owner:b},l<=0?o(0):d3.timer(o,l)});return!0});return a}function ba(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function $(a){e(a,_);return a}function Z(a){return{__data__:a}}function Y(a){return function(b){return U(a,b)}}function X(a){return function(b){return T(a,b)}}function S(a){e(a,V);return a}function R(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);return a<60?d+(e-d)*a/60:a<180?e:a<240?d+(e-d)*(240-a)/60:d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return H(g(a+120),g(a),g(a-120))}function Q(a,b,c){this.h=a,this.s=b,this.l=c}function P(a,b,c){return new Q(a,b,c)}function M(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function L(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return P(g,h,i)}function K(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(M(h[0]),M(h[1]),M(h[2]))}}if(i=N[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function J(a){return a<16?"0"+a.toString(16):a.toString(16)}function I(a,b,c){this.r=a,this.g=b,this.b=c}function H(a,b,c){return new I(a,b,c)}function G(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function F(a,b){b=b-(a=+a)?1/(b-a):0;return function(c){return(c-a)*b}}function E(a){return a in D||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function B(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function A(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function z(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function y(a){return 1-Math.sqrt(1-a*a)}function x(a){return Math.pow(2,10*(a-1))}function w(a){return 1-Math.cos(a*Math.PI/2)}function v(a){return function(b){return Math.pow(b,a)}}function u(a){return a}function t(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function s(a){return function(b){return 1-a(1-b)}}function n(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function m(a){return a+""}function j(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function h(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function g(a){return a==null}function f(a){return a.length}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.29.7"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}var e=[].__proto__?function(a,b){a.__proto__=b}:function(a,b){for(var c in b)a[c]=b[c]};d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:a>=b?0:NaN},d3.descending=function(a,b){return b<a?-1:b>a?1:b>=a?0:NaN},d3.min=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&e>f&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&e>f&&(e=f)}return e},d3.max=function(a,b){var c=-1,d=a.length,e,f;if(arguments.length===1){while(++c<d&&((e=a[c])==null||e!=e))e=undefined;while(++c<d)(f=a[c])!=null&&f>e&&(e=f)}else{while(++c<d&&((e=b.call(a,a[c],c))==null||e!=e))e=undefined;while(++c<d)(f=b.call(a,a[c],c))!=null&&f>e&&(e=f)}return e},d3.sum=function(a,b){var c=0,d=a.length,e,f=-1;if(arguments.length===1)while(++f<d)isNaN(e=+a[f])||(c+=e);else while(++f<d)isNaN(e=+b.call(a,a[f],f))||(c+=e);return c},d3.quantile=function(a,b){var c=(a.length-1)*b+1,d=Math.floor(c),e=a[d-1],f=c-d;return f?e+f*(a[d]-e):e},d3.zip=function(){if(!(e=arguments.length))return[];for(var a=-1,b=d3.min(arguments,f),c=Array(b);++a<b;)for(var d=-1,e,g=c[a]=Array(e);++d<e;)g[d]=arguments[d][a];return c},d3.bisectLeft=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;a[e]<b?c=e+1:d=e}return c},d3.bisect=d3.bisectRight=function(a,b,c,d){arguments.length<3&&(c=0),arguments.length<4&&(d=a.length);while(c<d){var e=c+d>>1;b<a[e]?d=e:c=e+1}return c},d3.first=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])>0&&(e=f);return e},d3.last=function(a,b){var c=0,d=a.length,e=a[0],f;arguments.length===1&&(b=d3.ascending);while(++c<d)b.call(a,e,f=a[c])<=0&&(e=f);return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],e,f=-1,h=a.length;arguments.length<2&&(b=g);while(++f<h)b.call(d,e=a[f],f)?d=[]:(d.length||c.push(d),d.push(e));return c},d3.range=function(a,b,c){arguments.length<3&&(c=1,arguments.length<2&&(b=a,a=0));if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(i,"\\$&")};var i=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;d3.round=function(a,b){return b?Math.round(a*Math.pow(10,b))*Math.pow(10,-b):Math.round(a)},d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=j(c);return b},d3.format=function(a){var b=k.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9],j=!1,o=!1;h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4)));switch(i){case"n":g=!0,i="g";break;case"%":j=!0,i="f";break;case"p":j=!0,i="r";break;case"d":o=!0,h="0"}i=l[i]||m;return function(a){var b=j?a*100:+a,k=b<0&&(b=-b)?"−":d;if(o&&b%1)return"";a=i(b,h);if(e){var l=a.length+k.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=n(a)),a=k+a}else{g&&(a=n(a)),a=k+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}j&&(a+="%");return a}};var k=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l={g:function(a,b){return a.toPrecision(b)},e:function(a,b){return a.toExponential(b)},f:function(a,b){return a.toFixed(b)},r:function(a,b){var c=1+Math.floor(1e-15+Math.log(a)/Math.LN10);return d3.round(a,b-c).toFixed(Math.max(0,Math.min(20,b-c)))}},o=v(2),p=v(3),q={linear:function(){return u},poly:v,quad:function(){return o},cubic:function(){return p},sin:function(){return w},exp:function(){return x},circle:function(){return y},elastic:z,back:A,bounce:function(){return B}},r={"in":function(a){return a},out:s,"in-out":t,"out-in":function(a){return t(s(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return r[d](q[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){var c=d3.interpolators.length,d;while(--c>=0&&!(d=d3.interpolators[c](a,b)));return d},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;C.lastIndex=0;for(d=0;c=C.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=C.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=C.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;return h.length===1?h[0]==null?i[0].x:function(){return b}:function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return R(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=E(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var C=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,D={background:1,fill:1,stroke:1};d3.interpolators=[d3.interpolateObject,function(a,b){return b instanceof Array&&d3.interpolateArray(a,b)},function(a,b){return typeof b=="string"&&d3.interpolateString(String(a),b)},function(a,b){return(typeof b=="string"?b in N||/^(#|rgb\(|hsl\()/.test(b):b instanceof I||b instanceof Q)&&d3.interpolateRgb(String(a),b)},function(a,b){return typeof b=="number"&&d3.interpolateNumber(+a,b)}],d3.rgb=function(a,b,c){return arguments.length===1?K(""+a,H,R):H(~~a,~~b,~~c)},I.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return H(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return H(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},I.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return H(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},I.prototype.hsl=function(){return L(this.r,this.g,this.b)},I.prototype.toString=function(){return"#"+J(this.r)+J(this.g)+J(this.b)};var N={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var O in N)N[O]=K(N[O],H,R);d3.hsl=function(a,b,c){return arguments.length===1?K(""+a,L,P):P(+a,+b,+c)},Q.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return P(this.h,this.s,this.l/a)},Q.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return P(this.h,this.s,a*this.l)},Q.prototype.rgb=function(){return R(this.h,this.s,this.l)},Q.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"},d3.select=function(a){return typeof a=="string"?W.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?W.selectAll(b):S([a(b)])};var T=function(a,b){return b.querySelector(a)},U=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(T=function(a,b){return Sizzle(a,b)[0]},U=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var V=[],W=S([[document]]);W[0].parentNode=document.documentElement,d3.selection=function(){return W},d3.selection.prototype=V,V.select=function(a){var b=[],c,d,e,f;typeof a!="function"&&(a=X(a));for(var g=-1,h=this.length;++g<h;){b.push(c=[]),c.parentNode=(e=this[g]).parentNode;for(var i=-1,j=e.length;++i<j;)(f=e[i])?(c.push(d=a(f)),d&&"__data__"in f&&(d.__data__=f.__data__)):c.push(null)}return S(b)},V.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h])b.push(c=a(d)),c.parentNode=d;return S(b)},V.attr=function(a,b){function i(){var c=b.apply(this,arguments);c==null?this.removeAttributeNS(a.space,a.local):this.setAttributeNS(a.space,a.local,c)}function h(){var c=b.apply(this,arguments);c==null?this.removeAttribute(a):this.setAttribute(a,c)}function g(){this.setAttributeNS(a.space,a.local,b)}function f(){this.setAttribute(a,b)}function e(){this.removeAttributeNS(a.space,a.local)}function d(){this.removeAttribute(a)}a=d3.ns.qualify(a);if(arguments.length<2){var c=this.node();return a.local?c.getAttributeNS(a.space,a.local):c.getAttribute(a)}return this.each(b==null?a.local?e:d:typeof b=="function"?a.local?i:h:a.local?g:f)},V.classed=function(a,b){function i(){(b.apply(this,arguments)?f:g).call(this)}function g(){if(b=this.classList)return b.remove(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;e=h(e.replace(c," ")),d?b.baseVal=e:this.className=e}function f(){if(b=this.classList)return b.add(a);var b=this.className,d=b.baseVal!=null,e=d?b.baseVal:b;c.lastIndex=0,c.test(e)||(e=h(e+" "+a),d?b.baseVal=e:this.className=e)}var c=new RegExp("(^|\\s+)"+d3.requote(a)+"(\\s+|$)","g");if(arguments.length<2){var d=this.node();if(e=d.classList)return e.contains(a);var e=d.className;c.lastIndex=0;return c.test(e.baseVal!=null?e.baseVal:e)}return this.each(typeof b=="function"?i:b?f:g)},V.style=function(a,b,c){function f(){var d=b.apply(this,arguments);d==null?this.style.removeProperty(a):this.style.setProperty(a,d,c)}function e(){this.style.setProperty(a,b,c)}function d(){this.style.removeProperty(a)}arguments.length<3&&(c="");return arguments.length<2?window.getComputedStyle(this.node(),null).getPropertyValue(a):this.each(b==null?d:typeof b=="function"?f:e)},V.property=function(a,b){function e(){var c=b.apply(this,arguments);c==null?delete this[a]:this[a]=c}function d(){this[a]=b}function c(){delete this[a]}return arguments.length<2?this.node()[a]:this.each(b==null?c:typeof b=="function"?e:d)},V.text=function(a){return arguments.length<1?this.node().textContent:this.each(typeof a=="function"?function(){this.textContent=a.apply(this,arguments)}:function(){this.textContent=a})},V.html=function(a){return arguments.length<1?this.node().innerHTML:this.each(typeof a=="function"?function(){this.innerHTML=a.apply(this,arguments)}:function(){this.innerHTML=a})},V.append=function(a){function c(b){return b.appendChild(document.createElementNS(a.space,a.local))}function b(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return this.select(a.local?c:b)},V.insert=function(a,b){function d(c){return c.insertBefore(document.createElementNS(a.space,a.local),T(b,c))}function c(c){return c.insertBefore(document.createElement(a),T(b,c))}a=d3.ns.qualify(a);return this.select(a.local?d:c)},V.remove=function(){return this.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},V.data=function(a,b){function f(a,f){var g,h=a.length,i=f.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(b){var q={},r=[],s,t=f.length;for(g=-1;++g<h;)s=b.call(o=a[g],o.__data__,g),s in q?n[t++]=o:q[s]=o,r.push(s);for(g=-1;++g<i;)o=q[s=b.call(f,p=f[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null),delete q[s];for(g=-1;++g<h;)r[g]in q&&(n[g]=a[g])}else{for(g=-1;++g<j;)o=a[g],p=f[g],o?(o.__data__=p,l[g]=o,m[g <add>]=n[g]=null):(m[g]=Z(p),l[g]=n[g]=null);for(;g<i;++g)m[g]=Z(f[g]),l[g]=n[g]=null;for(;g<k;++g)n[g]=a[g],m[g]=l[g]=null}m.update=l,m.parentNode=l.parentNode=n.parentNode=a.parentNode,c.push(m),d.push(l),e.push(n)}var c=[],d=[],e=[],g=-1,h=this.length,i;if(typeof a=="function")while(++g<h)f(i=this[g],a.call(i,i.parentNode.__data__,g));else while(++g<h)f(i=this[g],a);var j=S(d);j.enter=function(){return $(c)},j.exit=function(){return S(e)};return j};var _=[];_.append=V.append,_.insert=V.insert,_.empty=V.empty,_.select=function(a){var b=[],c,d,e,f,g;for(var h=-1,i=this.length;++h<i;){e=(f=this[h]).update,b.push(c=[]),c.parentNode=f.parentNode;for(var j=-1,k=f.length;++j<k;)(g=f[j])?(c.push(e[j]=d=a(f.parentNode)),d.__data__=g.__data__):c.push(null)}return S(b)},V.filter=function(a){var b=[],c,d,e;for(var f=0,g=this.length;f<g;f++){b.push(c=[]),c.parentNode=(d=this[f]).parentNode;for(var h=0,i=d.length;h<i;h++)(e=d[h])&&a.call(e,e.__data__,h)&&c.push(e)}return S(b)},V.map=function(a){return this.each(function(){this.__data__=a.apply(this,arguments)})},V.sort=function(a){a=ba.apply(this,arguments);for(var b=0,c=this.length;b<c;b++)for(var d=this[b].sort(a),e=1,f=d.length,g=d[0];e<f;e++){var h=d[e];h&&(g&&g.parentNode.insertBefore(h,g.nextSibling),g=h)}return this},V.on=function(a,b,c){arguments.length<3&&(c=!1);var d=a.indexOf("."),e=d===-1?a:a.substring(0,d),f="__on"+a;return this.each(function(a,d){function h(a){var c=d3.event;d3.event=a;try{b.call(this,g.__data__,d)}finally{d3.event=c}}this[f]&&this.removeEventListener(e,this[f],c),b&&this.addEventListener(e,this[f]=h,c);var g=this})},V.each=function(a){for(var b=-1,c=this.length;++b<c;)for(var d=this[b],e=-1,f=d.length;++e<f;){var g=d[e];g&&a.call(g,g.__data__,e,b)}return this},V.call=function(a){a.apply(this,(arguments[0]=this,arguments));return this},V.empty=function(){return!this.node()},V.node=function(a){for(var b=0,c=this.length;b<c;b++)for(var d=this[b],e=0,f=d.length;e<f;e++){var g=d[e];if(g)return g}return null},V.transition=function(){var a=[],b,c;for(var d=-1,e=this.length;++d<e;){a.push(b=[]);for(var f=this[d],g=-1,h=f.length;++g<h;)b.push((c=f[g])?{node:c,delay:0,duration:250}:null)}return bb(a,bf||++be)};var bd=[],be=0,bf=0,bg=d3.ease("cubic-in-out");bd.call=V.call,d3.transition=function(){return W.transition()},d3.transition.prototype=bd,bd.select=function(a){var b=[],c,d,e;typeof a!="function"&&(a=X(a));for(var f=-1,g=this.length;++f<g;){b.push(c=[]);for(var h=this[f],i=-1,j=h.length;++i<j;)(e=h[i])&&(d=a(e.node))?("__data__"in e.node&&(d.__data__=e.node.__data__),c.push({node:d,delay:e.delay,duration:e.duration})):c.push(null)}return bb(b,this.id).ease(this.ease())},bd.selectAll=function(a){var b=[],c,d;typeof a!="function"&&(a=Y(a));for(var e=-1,f=this.length;++e<f;)for(var g=this[e],h=-1,i=g.length;++h<i;)if(d=g[h]){b.push(c=a(d.node));for(var j=-1,k=c.length;++j<k;)c[j]={node:c[j],delay:d.delay,duration:d.duration}}return bb(b,this.id).ease(this.ease())},bd.attr=function(a,b){return this.attrTween(a,bc(b))},bd.attrTween=function(a,b){function d(c,d){var e=b.call(this,c,d,this.getAttributeNS(a.space,a.local));return e&&function(b){this.setAttributeNS(a.space,a.local,e(b))}}function c(c,d){var e=b.call(this,c,d,this.getAttribute(a));return e&&function(b){this.setAttribute(a,e(b))}}a=d3.ns.qualify(a);return this.tween("attr."+a,a.local?d:c)},bd.style=function(a,b,c){arguments.length<3&&(c=null);return this.styleTween(a,bc(b),c)},bd.styleTween=function(a,b,c){arguments.length<3&&(c=null);return this.tween("style."+a,function(d,e){var f=b.call(this,d,e,window.getComputedStyle(this,null).getPropertyValue(a));return f&&function(b){this.style.setProperty(a,f(b),c)}})},bd.text=function(a){return this.tween("text",function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a})},bd.remove=function(){return this.each("end",function(){var a;!this.__transition__&&(a=this.parentNode)&&a.removeChild(this)})},bd.delay=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].delay=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].delay=a}))},bd.duration=function(a){var b=this;return b.each(typeof a=="function"?function(c,d,e){b[e][d].duration=+a.apply(this,arguments)}:(a=+a,function(c,d,e){b[e][d].duration=a}))};var bi=null,bj,bk;d3.timer=function(a,b){var c=Date.now(),d=!1,e,f=bi;if(arguments.length<2)b=0;else if(!isFinite(b))return;while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(bi={callback:a,then:c,delay:b,next:bi}),bj||(bk=clearTimeout(bk),bj=1,bn(bl))},d3.timer.flush=function(){var a,b=Date.now(),c=bi;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bm()};var bn=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){return bs([0,1],[0,1],d3.interpolate,!1)},d3.scale.log=function(){return bA(d3.scale.linear(),bB)},bB.pow=function(a){return Math.pow(10,a)},bC.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){return bE(d3.scale.linear(),1)},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){return bG({},0,{t:"range",x:[]})},d3.scale.category10=function(){return d3.scale.ordinal().range(bH)},d3.scale.category20=function(){return d3.scale.ordinal().range(bI)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bJ)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bK)};var bH=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bI=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bJ=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bK=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){return bL([],[])},d3.scale.quantize=function(){return bM(0,1,[0,1])},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bN,h=d.apply(this,arguments)+bN,i=(h<g&&(i=g,g=h,h=i),h-g),j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bO?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bP,b=bQ,c=bR,d=bS;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bN;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bN=-Math.PI/2,bO=2*Math.PI-1e-6;d3.svg.line=function(){return bT(Object)};var bX={linear:bY,"step-before":bZ,"step-after":b$,basis:ce,"basis-open":cf,"basis-closed":cg,bundle:ch,cardinal:cb,"cardinal-open":b_,"cardinal-closed":ca,monotone:cq},cj=[0,2/3,1/3,0],ck=[0,1/3,2/3,0],cl=[0,1/6,2/3,1/6];d3.svg.line.radial=function(){var a=bT(cr);a.radius=a.x,delete a.x,a.angle=a.y,delete a.y;return a},d3.svg.area=function(){return cs(Object)},d3.svg.area.radial=function(){var a=cs(cr);a.radius=a.x,delete a.x,a.innerRadius=a.x0,delete a.x0,a.outerRadius=a.x1,delete a.x1,a.angle=a.y,delete a.y,a.startAngle=a.y0,delete a.y0,a.endAngle=a.y1,delete a.y1;return a},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bN,k=e.call(a,h,g)+bN;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=cv,b=cw,c=cx,d=bR,e=bS;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=cv,b=cw,c=cA;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.diagonal.radial=function(){var a=d3.svg.diagonal(),b=cA,c=a.projection;a.projection=function(a){return arguments.length?c(cB(b=a)):b};return a},d3.svg.mouse=function(a){return cD(a,d3.event)};var cC=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(b){var c=d3.event.touches;return c?a(c).map(function(a){var c=cD(b,a);c.identifier=a.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cG[a.call(this,c,d)]||cG.circle)(b.call(this,c,d))}var a=cF,b=cE;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c};var cG={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cI)),c=b*cI;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cH),c=b*cH/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cH),c=b*cH/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}};d3.svg.symbolTypes=d3.keys(cG);var cH=Math.sqrt(3),cI=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <ide><path>src/core/uninterpolate.js <ide> function d3_uninterpolateNumber(a, b) { <del> b = 1 / (b - (a = +a)); <add> b = b - (a = +a) ? 1 / (b - a) : 0; <ide> return function(x) { return (x - a) * b; }; <ide> } <ide> <ide> function d3_uninterpolateClamp(a, b) { <del> b = 1 / (b - (a = +a)); <add> b = b - (a = +a) ? 1 / (b - a) : 0; <ide> return function(x) { return Math.max(0, Math.min(1, (x - a) * b)); }; <ide> } <ide><path>test/scale/linear-test.js <ide> suite.addBatch({ <ide> assert.equal(x(-5), "rgb(255,128,128)"); <ide> assert.equal(x(50), "rgb(128,192,128)"); <ide> assert.equal(x(75), "rgb(64,160,64)"); <add> }, <add> "an empty domain maps to the range start": function(linear) { <add> var x = linear().domain([0, 0]).range(["red", "green"]); <add> assert.equal(x(0), "rgb(255,0,0)"); <add> assert.equal(x(-1), "rgb(255,0,0)"); <add> assert.equal(x(1), "rgb(255,0,0)"); <ide> } <ide> }, <ide>
4
Python
Python
add extra resources to kubernetespod
2744a3f3cc1402fb7bff7b962745be4dae920a5a
<ide><path>libcloud/container/drivers/kubernetes.py <ide> from libcloud.compute.base import NodeImage <ide> from libcloud.compute.base import NodeLocation <ide> <del>from libcloud.utils import misc <add>from libcloud.utils.misc import to_k8s_memory_size_str_from_n_bytes <add>from libcloud.utils.misc import to_n_bytes_from_k8s_memory_size_str <ide> <ide> __all__ = ["KubernetesContainerDriver"] <ide> <ide> <ide> ROOT_URL = "/api/" <ide> <ide> <add>def sum_resources(self, *resource_dicts): <add> total_cpu = 0 <add> total_memory = 0 <add> for rd in resource_dicts: <add> cpu = rd.get("cpu", "0") <add> is_in_milli_format = "m" in cpu <add> if is_in_milli_format: <add> total_cpu += int(cpu.strip("m")) <add> else: <add> total_cpu += int(cpu) * 1000 <add> total_memory += to_n_bytes_from_k8s_memory_size_str(rd.get("memory", "0K")) <add> return { <add> "cpu": f"{total_cpu}m", <add> "memory": to_k8s_memory_size_str_from_n_bytes(total_memory), <add> } <add> <add> <ide> class KubernetesPod(object): <ide> def __init__( <ide> self, <ide> def __init__( <ide> ip_addresses, <ide> created_at, <ide> node_name, <add> extra, <ide> ): <ide> """ <ide> A Kubernetes pod <ide> def __init__( <ide> self.ip_addresses = ip_addresses <ide> self.created_at = created_at <ide> self.node_name = node_name <add> self.extra = extra <ide> <ide> <ide> class KubernetesContainerDriver(KubernetesDriverMixin, ContainerDriver): <ide> def _to_pod(self, data): <ide> """ <ide> container_statuses = data["status"].get("containerStatuses", {}) <ide> containers = [] <add> extra = {"resources": {}} <ide> # response contains the status of the containers in a separate field <ide> for container in data["spec"]["containers"]: <ide> if container_statuses: <ide> def _to_pod(self, data): <ide> )[0] <ide> else: <ide> spec = container_statuses <del> containers.append(self._to_container(container, spec, data)) <add> container_obj = self._to_container(container, spec, data) <add> # Calculate new resources <add> resources = extra["resources"] <add> container_resources = container_obj.extra.get("resources", {}) <add> resources["limits"] = sum_resources( <add> resources.get("limits", {}), container_resources.get("limits", {}) <add> ) <add> extra["resources"]["requests"] = sum_resources( <add> resources.get("requests", {}), container_resources.get("requests", {}) <add> ) <add> containers.append(container_obj) <ide> ip_addresses = [ip_dict["ip"] for ip_dict in data["status"].get("podIPs", [])] <ide> created_at = datetime.datetime.strptime( <ide> data["metadata"]["creationTimestamp"], "%Y-%m-%dT%H:%M:%SZ" <ide> def _to_pod(self, data): <ide> containers=containers, <ide> created_at=created_at, <ide> node_name=data["spec"].get("nodeName"), <add> extra=extra, <ide> ) <ide> <ide> def _to_container(self, data, container_status, pod_data):
1
PHP
PHP
write tests for token guard
ec4f6ae66e7792e3703d82b47eefb96fced0890e
<ide><path>tests/Auth/AuthTokenGuardTest.php <add><?php <add> <add>use Illuminate\Http\Request; <add>use Illuminate\Auth\TokenGuard; <add>use Illuminate\Contracts\Auth\UserProvider; <add> <add>class AuthTokenGuardTest extends PHPUnit_Framework_TestCase <add>{ <add> public function tearDown() <add> { <add> Mockery::close(); <add> } <add> <add> public function testUserCanBeRetrievedByQueryStringVariable() <add> { <add> $provider = Mockery::mock(UserProvider::class); <add> $user = new AuthTokenGuardTestUser; <add> $user->id = 1; <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn($user); <add> $request = Request::create('/', 'GET', ['api_token' => 'foo']); <add> <add> $guard = new TokenGuard($provider, $request); <add> <add> $user = $guard->user(); <add> <add> $this->assertEquals(1, $user->id); <add> $this->assertTrue($guard->check()); <add> $this->assertFalse($guard->guest()); <add> $this->assertEquals(1, $guard->id()); <add> } <add> <add> public function testUserCanBeRetrievedByAuthHeaders() <add> { <add> $provider = Mockery::mock(UserProvider::class); <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn((object) ['id' => 1]); <add> $request = Request::create('/', 'GET', [], [], [], ['PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'foo']); <add> <add> $guard = new TokenGuard($provider, $request); <add> <add> $user = $guard->user(); <add> <add> $this->assertEquals(1, $user->id); <add> } <add> <add> public function testUserCanBeRetrievedByBearerToken() <add> { <add> $provider = Mockery::mock(UserProvider::class); <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn((object) ['id' => 1]); <add> $request = Request::create('/', 'GET', [], [], [], ['HTTP_AUTHORIZATION' => 'Bearer foo']); <add> <add> $guard = new TokenGuard($provider, $request); <add> <add> $user = $guard->user(); <add> <add> $this->assertEquals(1, $user->id); <add> } <add> <add> public function testValidateCanDetermineIfCredentialsAreValid() <add> { <add> $provider = Mockery::mock(UserProvider::class); <add> $user = new AuthTokenGuardTestUser; <add> $user->id = 1; <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn($user); <add> $request = Request::create('/', 'GET', ['api_token' => 'foo']); <add> <add> $guard = new TokenGuard($provider, $request); <add> <add> $this->assertTrue($guard->validate(['api_token' => 'foo'])); <add> } <add> <add> public function testValidateCanDetermineIfCredentialsAreInvalid() <add> { <add> $provider = Mockery::mock(UserProvider::class); <add> $user = new AuthTokenGuardTestUser; <add> $user->id = 1; <add> $provider->shouldReceive('retrieveByCredentials')->once()->with(['api_token' => 'foo'])->andReturn(null); <add> $request = Request::create('/', 'GET', ['api_token' => 'foo']); <add> <add> $guard = new TokenGuard($provider, $request); <add> <add> $this->assertFalse($guard->validate(['api_token' => 'foo'])); <add> } <add>} <add> <add>class AuthTokenGuardTestUser <add>{ <add> public $id; <add> public function getAuthIdentifier() <add> { <add> return $this->id; <add> } <add>}
1
PHP
PHP
check length in env function
7e446b5056013af842e4fa6f26c45e762eedc997
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function env($key, $default = null) <ide> return; <ide> } <ide> <del> if (Str::startsWith($value, '"') && Str::endsWith($value, '"')) { <add> if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { <ide> return substr($value, 1, -1); <ide> } <ide>
1
Text
Text
add v3.17.0-beta.4 to changelog
b14380eb0200ea194cc4fa80211f78cc2806fce1
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.17.0-beta.4 (February 10, 2020) <add> <add>- [#18727](https://github.com/emberjs/ember.js/pull/18727) [BUGFIX] Avoid breaking {{-in-element}} usage <add>- [#18728](https://github.com/emberjs/ember.js/pull/18728) [BUGFIX] Fix `{{#-in-element}}` double-clearing issue <add>- [#18729](https://github.com/emberjs/ember.js/pull/18729) [BUGFIX] Remove deprecation for instantiation of new singleton instances (e.g. a service) during teardown (originally added in 3.16.1 by [#18717](https://github.com/emberjs/ember.js/pull/18717)). <add> <ide> ### v3.17.0-beta.3 (February 3, 2020) <ide> <ide> - [#18703](https://github.com/emberjs/ember.js/pull/18703) [BUGFIX] Correctly links ArrayProxy tags to `arrangedContent`
1
Ruby
Ruby
add class level `run` to rails command
f8d2a14e251b9985db11475a0cf8b1350efbf8f1
<ide><path>railties/lib/rails/commands/command.rb <ide> def initialize(argv = []) <ide> @options = {} <ide> end <ide> <del> def run(task_name) <del> command_name = self.class.command_name_for(task_name) <add> def self.run(task_name, argv) <add> command_name = command_name_for(task_name) <ide> <add> if command = command_for(command_name) <add> command.new(argv).run(command_name) <add> true # Indicate command was found and run. <add> end <add> end <add> <add> def run(command_name) <ide> parse_options_for(command_name) <ide> @option_parser.parse! @argv <ide> <del> if command = command_for(command_name) <del> command.public_send(command_name) <del> else <del> puts @option_parser <del> end <add> public_send(command_name) <ide> end <ide> <ide> def self.options_for(command_name, &options_to_parse) <ide> def self.set_banner(command_name, banner) <ide> options_for(command_name) { |opts, _| opts.banner = banner } <ide> end <ide> <del> def exists?(task_name) # :nodoc: <del> command_name = self.class.command_name_for(task_name) <del> !command_for(command_name).nil? <del> end <del> <ide> private <ide> @@commands = [] <ide> @@command_options = {} <ide> def self.command_name_for(task_name) <ide> task_name.gsub(':', '_').to_sym <ide> end <ide> <del> def command_for(command_name) <del> klass = @@commands.find do |command| <add> def self.command_for(command_name) <add> @@commands.find do |command| <ide> command.public_instance_methods.include?(command_name) <ide> end <del> <del> if klass <del> klass.new(@argv) <del> end <ide> end <ide> end <ide> end <ide><path>railties/lib/rails/commands/commands_tasks.rb <ide> class CommandsTasks # :nodoc: <ide> <ide> def initialize(argv) <ide> @argv = argv <del> @rails_command = Rails::Commands::Command.new(argv) <ide> end <ide> <ide> def run_command!(command) <ide> command = parse_command(command) <ide> <del> if @rails_command.exists?(command) <del> @rails_command.run(command) <del> elsif COMMAND_WHITELIST.include?(command) <add> run_with_command = Rails::Commands::Command.run(command, argv) <add> <add> if !run_with_command && COMMAND_WHITELIST.include?(command) <ide> send(command) <ide> else <ide> write_error_message(command)
2
Javascript
Javascript
fix bad type specification in animated
3ff4ee961c490baff2a230fdf6ee6417ae811edd
<ide><path>Libraries/Animated/src/AnimatedImplementation.js <ide> class AnimatedValueXY extends AnimatedWithChildren { <ide> }; <ide> } <ide> <del> stopAnimation(callback?: ?() => number): void { <add> stopAnimation(callback?: (value: {x: number, y: number}) => void): void { <ide> this.x.stopAnimation(); <ide> this.y.stopAnimation(); <ide> callback && callback(this.__getValue());
1
Text
Text
add meta tag in the header of html
87ecb0ba1fb0e8359e94a206953b32ad46687b35
<ide><path>docs/docs/02-displaying-data.ja-JP.md <ide> UIについて、最も基本的なことは、いくつかのデータを表示 <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script> <ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <ide><path>docs/docs/02-displaying-data.ko-KR.md <ide> UI를 가지고 할 수 있는 가장 기초적인 것은 데이터를 표시하 <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script> <ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <ide><path>docs/docs/02-displaying-data.md <ide> Let's look at a really simple example. Create a `hello-react.html` file with the <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script> <ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <ide><path>docs/docs/02-displaying-data.zh-CN.md <ide> next: jsx-in-depth-zh-CN.html <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://fb.me/react-{{site.react_version}}.js"></script> <ide> <script src="https://fb.me/JSXTransformer-{{site.react_version}}.js"></script> <ide> React 组件非常简单。你可以认为它们就是简单的函数,接受 ` <ide> <ide> 我们得出解决这个问题最好的方案是通过 JavaScript 直接生成模板,这样你就可以用一个真正语言的所有表达能力去构建用户界面。为了使这变得更简单,我们做了一个非常简单、**可选**类似 HTML 语法 ,通过函数调用即可生成模板的编译器,称为 JSX。 <ide> <del>**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写: <add>**JSX 让你可以用 HTML 语法去写 JavaScript 函数调用** 为了在 React 生成一个链接,通过纯 JavaScript 你可以这么写: <ide> <ide> `React.createElement('a', {href: 'https://facebook.github.io/react/'}, 'Hello React!')`。 <ide> <ide><path>docs/docs/getting-started.ja-JP.md <ide> React でのハッキングを始めるにあたり、一番簡単なものと <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <script src="build/JSXTransformer.js"></script> <ide> React.render( <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <!-- JSXTransformer は必要ありません! --> <ide><path>docs/docs/getting-started.ko-KR.md <ide> React를 시작하는 가장 빠른 방법은 다음의 Hello World JSFiddle 예 <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <script src="build/JSXTransformer.js"></script> <ide> React.render( <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <!-- JSXTransformer는 이제 불필요합니다! --> <ide><path>docs/docs/getting-started.md <ide> In the root directory of the starter kit, create a `helloworld.html` with the fo <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <script src="build/JSXTransformer.js"></script> <ide> Update your HTML file as below: <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <!-- No need for JSXTransformer! --> <ide> If you want to use React with [browserify](http://browserify.org/), [webpack](ht <ide> <ide> ## Next Steps <ide> <del>Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the starter kit's `examples` directory to learn more. <add>Check out [the tutorial](/react/docs/tutorial.html) and the other examples in the starter kit's `examples` directory to learn more. <ide> <ide> We also have a wiki where the community contributes with [workflows, UI-components, routing, data management etc.](https://github.com/facebook/react/wiki/Complementary-Tools) <ide> <ide><path>docs/docs/getting-started.zh-CN.md <ide> redirect_from: "docs/index-zh-CN.html" <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <script src="build/JSXTransformer.js"></script> <ide> React.render( <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React!</title> <ide> <script src="build/react.js"></script> <ide> <!-- 不需要 JSXTransformer! --> <ide><path>docs/docs/tutorial.ja-JP.md <ide> next: thinking-in-react-ja-JP.html <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script> <ide> Markdown はインラインでテキストをフォーマットする簡単な <ide> ```html{7} <ide> <!-- index.html --> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script> <ide><path>docs/docs/tutorial.ko-KR.md <ide> next: thinking-in-react-ko-KR.html <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script> <ide> Markdown은 텍스트를 포맷팅하는 간단한 방식입니다. 예를 들 <ide> ```html{7} <ide> <!-- index.html --> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script> <ide><path>docs/docs/tutorial.md <ide> For this tutorial, we'll use prebuilt JavaScript files on a CDN. Open up your fa <ide> <!DOCTYPE html> <ide> <html> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script> <ide> First, add the third-party library **marked** to your application. This is a Jav <ide> ```html{7} <ide> <!-- index.html --> <ide> <head> <add> <meta charset="UTF-8" /> <ide> <title>Hello React</title> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/react.js"></script> <ide> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/{{site.react_version}}/JSXTransformer.js"></script>
11
PHP
PHP
remove inline assignment
dcadfcbcab97c99ca3fe7f58fe39fa4f29682455
<ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function queryAssociation(Model $model, &$linkModel, $type, $association, <ide> unset($stack['_joined']); <ide> } <ide> <del> if (!$query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external)) { <add> $query = $this->generateAssociationQuery($model, $linkModel, $type, $association, $assocData, $queryData, $external); <add> if (empty($query)) { <ide> return; <ide> } <ide>
1
Ruby
Ruby
avoid another call to `scope`
3c8775349c5ecbdbf98e1815b2d65d2955196564
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def root(path, options={}) <ide> <ide> if @scope.resources? <ide> with_scope_level(:root) do <del> scope(parent_resource.path) do <add> path_scope(parent_resource.path) do <ide> super(options) <ide> end <ide> end
1
Ruby
Ruby
use flat_map when building ar order
5e6bee112a7d590cbc51934b768f9632814726ce
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def order(*args) <ide> # Like #order, but modifies relation in place. <ide> def order!(*args) <ide> args.flatten! <del> <ide> validate_order_args args <ide> <ide> references = args.reject { |arg| Arel::Node === arg } <ide> def reorder(*args) <ide> # Like #reorder, but modifies relation in place. <ide> def reorder!(*args) <ide> args.flatten! <del> <ide> validate_order_args args <ide> <ide> self.reordering_value = true <ide> def build_select(arel, selects) <ide> def reverse_sql_order(order_query) <ide> order_query = ["#{quoted_table_name}.#{quoted_primary_key} ASC"] if order_query.empty? <ide> <del> order_query.map do |o| <add> order_query.flat_map do |o| <ide> case o <ide> when Arel::Nodes::Ordering <ide> o.reverse <ide> def reverse_sql_order(order_query) <ide> else <ide> o <ide> end <del> end.flatten <add> end <ide> end <ide> <ide> def array_of_strings?(o) <ide> def build_order(arel) <ide> orders = order_values <ide> orders = reverse_sql_order(orders) if reverse_order_value <ide> <del> orders = orders.uniq.reject(&:blank?).map do |order| <add> orders = orders.uniq.reject(&:blank?).flat_map do |order| <ide> case order <ide> when Symbol <ide> table[order].asc <ide> def build_order(arel) <ide> else <ide> order <ide> end <del> end.flatten <add> end <ide> <ide> arel.order(*orders) unless orders.empty? <ide> end
1
Mixed
Javascript
move createcipher to runtime deprecation
933d8eb689bb4bc412e71c0069bf9b7b24de4f9d
<ide><path>doc/api/deprecations.md <ide> Type: End-of-Life <ide> <a id="DEP0106"></a> <ide> ### DEP0106: crypto.createCipher and crypto.createDecipher <ide> <del>Type: Documentation-only <add>Type: Runtime <ide> <ide> Using [`crypto.createCipher()`][] and [`crypto.createDecipher()`][] should be <ide> avoided as they use a weak key derivation function (MD5 with no salt) and static <ide><path>lib/crypto.js <ide> function createVerify(algorithm, options) { <ide> module.exports = exports = { <ide> // Methods <ide> _toBuf: toBuf, <del> createCipher, <ide> createCipheriv, <del> createDecipher, <ide> createDecipheriv, <ide> createDiffieHellman, <ide> createDiffieHellmanGroup, <ide> function getFipsForced() { <ide> } <ide> <ide> Object.defineProperties(exports, { <add> createCipher: { <add> enumerable: false, <add> value: deprecate(createCipher, <add> 'crypto.createCipher is deprecated.', 'DEP0106') <add> }, <add> createDecipher: { <add> enumerable: false, <add> value: deprecate(createDecipher, <add> 'crypto.createDecipher is deprecated.', 'DEP0106') <add> }, <ide> // crypto.fips is deprecated. DEP0093. Use crypto.getFips()/crypto.setFips() <ide> fips: { <ide> get: !fipsMode ? getFipsDisabled : <ide><path>test/parallel/test-crypto-authenticated.js <ide> const expectedWarnings = common.hasFipsCrypto ? <ide> ['Use Cipheriv for counter mode of aes-256-ccm', common.noWarnCode] <ide> ]; <ide> <del>const expectedDeprecationWarnings = ['crypto.DEFAULT_ENCODING is deprecated.', <del> 'DEP0091']; <add>const expectedDeprecationWarnings = [ <add> ['crypto.DEFAULT_ENCODING is deprecated.', 'DEP0091'], <add> ['crypto.createCipher is deprecated.', 'DEP0106'] <add>]; <ide> <ide> common.expectWarning({ <ide> Warning: expectedWarnings, <ide><path>test/parallel/test-crypto-cipher-decipher.js <ide> if (common.hasFipsCrypto) <ide> const crypto = require('crypto'); <ide> const assert = require('assert'); <ide> <add>common.expectWarning({ <add> Warning: [ <add> ['Use Cipheriv for counter mode of aes-256-gcm', common.noWarnCode] <add> ], <add> DeprecationWarning: [ <add> ['crypto.createCipher is deprecated.', 'DEP0106'] <add> ] <add>}); <add> <ide> function testCipher1(key) { <ide> // Test encryption and decryption <ide> const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; <ide> testCipher2(Buffer.from('0123456789abcdef')); <ide> const aadbuf = Buffer.from('aadbuf'); <ide> const data = Buffer.from('test-crypto-cipher-decipher'); <ide> <del> common.expectWarning('Warning', <del> 'Use Cipheriv for counter mode of aes-256-gcm', <del> common.noWarnCode); <del> <ide> const cipher = crypto.createCipher('aes-256-gcm', key); <ide> cipher.setAAD(aadbuf); <ide> cipher.setAutoPadding(); <ide><path>test/parallel/test-process-emit-warning-from-native.js <ide> const crypto = require('crypto'); <ide> const key = '0123456789'; <ide> <ide> { <del> common.expectWarning('Warning', <del> 'Use Cipheriv for counter mode of aes-256-gcm', <del> common.noWarnCode); <add> common.expectWarning({ <add> DeprecationWarning: [ <add> ['crypto.createCipher is deprecated.', 'DEP0106'] <add> ], <add> Warning: [ <add> ['Use Cipheriv for counter mode of aes-256-gcm', common.noWarnCode] <add> ] <add> }); <ide> <ide> // Emits regular warning expected by expectWarning() <ide> crypto.createCipher('aes-256-gcm', key);
5
Text
Text
add colons for consistent styling
3831de8a05727d5db9e444208738e709bb9a9af7
<ide><path>CONTRIBUTING.md <ide> Before you submit your pull request consider the following guidelines: <ide> that relates to your submission. You don't want to duplicate effort. <ide> * Please sign our [Contributor License Agreement (CLA)](#cla) before sending pull <ide> requests. We cannot accept code without this. <del>* Make your changes in a new git branch <add>* Make your changes in a new git branch: <ide> <ide> ```shell <ide> git checkout -b my-fix-branch master <ide> Before you submit your pull request consider the following guidelines: <ide> ``` <ide> Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. <ide> <del>* Build your changes locally to ensure all the tests pass <add>* Build your changes locally to ensure all the tests pass: <ide> <ide> ```shell <ide> grunt test <ide> Before you submit your pull request consider the following guidelines: <ide> ``` <ide> <ide> * In GitHub, send a pull request to `angular:master`. <del>* If we suggest changes then <add>* If we suggest changes then: <ide> * Make the required updates. <ide> * Re-run the Angular test suite to ensure tests are still passing. <ide> * Rebase your branch and force push to your GitHub repository (this will update your Pull Request):
1
Javascript
Javascript
add locale for kannada
8b638ee23bd58121f2b7d5fee052e87ae5423364
<ide><path>src/locale/kn.js <add>//! moment.js locale configuration <add>//! locale : Kannada [kn] <add>//! author : Rajeev Naik : https://github.com/rajeevnaikte <add> <add>import moment from '../moment'; <add> <add>var symbolMap = { <add> '1': '೧', <add> '2': '೨', <add> '3': '೩', <add> '4': '೪', <add> '5': '೫', <add> '6': '೬', <add> '7': '೭', <add> '8': '೮', <add> '9': '೯', <add> '0': '೦' <add>}, <add>numberMap = { <add> '೧': '1', <add> '೨': '2', <add> '೩': '3', <add> '೪': '4', <add> '೫': '5', <add> '೬': '6', <add> '೭': '7', <add> '೮': '8', <add> '೯': '9', <add> '೦': '0' <add>}; <add> <add>export default moment.defineLocale('kn', { <add> months : 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'), <add> monthsShort : 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬ_ಅಕ್ಟೋಬ_ನವೆಂಬ_ಡಿಸೆಂಬ'.split('_'), <add> monthsParseExact: true, <add> weekdays : 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'), <add> weekdaysShort : 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), <add> weekdaysMin : 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), <add> longDateFormat : { <add> LT : 'A h:mm', <add> LTS : 'A h:mm:ss', <add> L : 'DD/MM/YYYY', <add> LL : 'D MMMM YYYY', <add> LLL : 'D MMMM YYYY, A h:mm', <add> LLLL : 'dddd, D MMMM YYYY, A h:mm' <add> }, <add> calendar : { <add> sameDay : '[ಇಂದು] LT', <add> nextDay : '[ನಾಳೆ] LT', <add> nextWeek : 'dddd, LT', <add> lastDay : '[ನಿನ್ನೆ] LT', <add> lastWeek : '[ಕೊನೆಯ] dddd, LT', <add> sameElse : 'L' <add> }, <add> relativeTime : { <add> future : '%s ನಂತರ', <add> past : '%s ಹಿಂದೆ', <add> s : 'ಕೆಲವು ಕ್ಷಣಗಳು', <add> m : 'ಒಂದು ನಿಮಿಷ', <add> mm : '%d ನಿಮಿಷ', <add> h : 'ಒಂದು ಗಂಟೆ', <add> hh : '%d ಗಂಟೆ', <add> d : 'ಒಂದು ದಿನ', <add> dd : '%d ದಿನ', <add> M : 'ಒಂದು ತಿಂಗಳು', <add> MM : '%d ತಿಂಗಳು', <add> y : 'ಒಂದು ವರ್ಷ', <add> yy : '%d ವರ್ಷ' <add> }, <add> preparse: function (string) { <add> return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) { <add> return numberMap[match]; <add> }); <add> }, <add> postformat: function (string) { <add> return string.replace(/\d/g, function (match) { <add> return symbolMap[match]; <add> }); <add> }, <add> meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, <add> meridiemHour : function (hour, meridiem) { <add> if (hour === 12) { <add> hour = 0; <add> } <add> if (meridiem === 'ರಾತ್ರಿ') { <add> return hour < 4 ? hour : hour + 12; <add> } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') { <add> return hour; <add> } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') { <add> return hour >= 10 ? hour : hour + 12; <add> } else if (meridiem === 'ಸಂಜೆ') { <add> return hour + 12; <add> } <add> }, <add> meridiem : function (hour, minute, isLower) { <add> if (hour < 4) { <add> return 'ರಾತ್ರಿ'; <add> } else if (hour < 10) { <add> return 'ಬೆಳಿಗ್ಗೆ'; <add> } else if (hour < 17) { <add> return 'ಮಧ್ಯಾಹ್ನ'; <add> } else if (hour < 20) { <add> return 'ಸಂಜೆ'; <add> } else { <add> return 'ರಾತ್ರಿ'; <add> } <add> }, <add> ordinalParse: /\d{1,2}(ನೇ)/, <add> ordinal : function (number) { <add> return number + 'ನೇ'; <add> }, <add> week : { <add> dow : 0, // Sunday is the first day of the week. <add> doy : 6 // The week that contains Jan 1st is the first week of the year. <add> } <add>}); <ide><path>src/test/locale/kn.js <add>import {localeModule, test} from '../qunit'; <add>import moment from '../../moment'; <add>localeModule('kn'); <add> <add>test('parse', function (assert) { <add> var tests = 'ಜನವರಿ ಜನ_ಫೆಬ್ರವರಿ ಫೆಬ್ರ_ಮಾರ್ಚ್ ಮಾರ್ಚ್_ಏಪ್ರಿಲ್ ಏಪ್ರಿಲ್_ಮೇ ಮೇ_ಜೂನ್ ಜೂನ್_ಜುಲೈ ಜುಲೈ_ಆಗಸ್ಟ್ ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್ ಸೆಪ್ಟೆಂಬ_ಅಕ್ಟೋಬರ್ ಅಕ್ಟೋಬ_ನವೆಂಬರ್ ನವೆಂಬ_ಡಿಸೆಂಬರ್ ಡಿಸೆಂಬ'.split('_'), i; <add> function equalTest(input, mmm, i) { <add> assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <add> } <add> for (i = 0; i < 12; i++) { <add> tests[i] = tests[i].split(' '); <add> equalTest(tests[i][0], 'MMM', i); <add> equalTest(tests[i][1], 'MMM', i); <add> equalTest(tests[i][0], 'MMMM', i); <add> equalTest(tests[i][1], 'MMMM', i); <add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); <add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); <add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); <add> } <add>}); <add> <add>test('format', function (assert) { <add> var a = [ <add> ['dddd, Do MMMM YYYY, a h:mm:ss', 'ಭಾನುವಾರ, ೧೪ನೇ ಫೆಬ್ರವರಿ ೨೦೧೦, ಮಧ್ಯಾಹ್ನ ೩:೨೫:೫೦'], <add> ['ddd, a h ಗಂಟೆ', 'ಭಾನು, ಮಧ್ಯಾಹ್ನ ೩ ಗಂಟೆ'], <add> ['M Mo MM MMMM MMM', '೨ ೨ನೇ ೦೨ ಫೆಬ್ರವರಿ ಫೆಬ್ರ'], <add> ['YYYY YY', '೨೦೧೦ ೧೦'], <add> ['D Do DD', '೧೪ ೧೪ನೇ ೧೪'], <add> ['d do dddd ddd dd', '೦ ೦ನೇ ಭಾನುವಾರ ಭಾನು ಭಾ'], <add> ['DDD DDDo DDDD', '೪೫ ೪೫ನೇ ೦೪೫'], <add> ['w wo ww', '೮ ೮ನೇ ೦೮'], <add> ['h hh', '೩ ೦೩'], <add> ['H HH', '೧೫ ೧೫'], <add> ['m mm', '೨೫ ೨೫'], <add> ['s ss', '೫೦ ೫೦'], <add> ['a A', 'ಮಧ್ಯಾಹ್ನ ಮಧ್ಯಾಹ್ನ'], <add> ['LTS', 'ಮಧ್ಯಾಹ್ನ ೩:೨೫:೫೦'], <add> ['L', '೧೪/೦೨/೨೦೧೦'], <add> ['LL', '೧೪ ಫೆಬ್ರವರಿ ೨೦೧೦'], <add> ['LLL', '೧೪ ಫೆಬ್ರವರಿ ೨೦೧೦, ಮಧ್ಯಾಹ್ನ ೩:೨೫'], <add> ['LLLL', 'ಭಾನುವಾರ, ೧೪ ಫೆಬ್ರವರಿ ೨೦೧೦, ಮಧ್ಯಾಹ್ನ ೩:೨೫'], <add> ['l', '೧೪/೨/೨೦೧೦'], <add> ['ll', '೧೪ ಫೆಬ್ರ ೨೦೧೦'], <add> ['lll', '೧೪ ಫೆಬ್ರ ೨೦೧೦, ಮಧ್ಯಾಹ್ನ ೩:೨೫'], <add> ['llll', 'ಭಾನು, ೧೪ ಫೆಬ್ರ ೨೦೧೦, ಮಧ್ಯಾಹ್ನ ೩:೨೫'] <add> ], <add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <add> i; <add> for (i = 0; i < a.length; i++) { <add> assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); <add> } <add>}); <add> <add>test('format ordinal', function (assert) { <add> assert.equal(moment([2011, 0, 1]).format('DDDo'), '೧ನೇ', '೧ನೇ'); <add> assert.equal(moment([2011, 0, 2]).format('DDDo'), '೨ನೇ', '೨ನೇ'); <add> assert.equal(moment([2011, 0, 3]).format('DDDo'), '೩ನೇ', '೩ನೇ'); <add> assert.equal(moment([2011, 0, 4]).format('DDDo'), '೪ನೇ', '೪ನೇ'); <add> assert.equal(moment([2011, 0, 5]).format('DDDo'), '೫ನೇ', '೫ನೇ'); <add> assert.equal(moment([2011, 0, 6]).format('DDDo'), '೬ನೇ', '೬ನೇ'); <add> assert.equal(moment([2011, 0, 7]).format('DDDo'), '೭ನೇ', '೭ನೇ'); <add> assert.equal(moment([2011, 0, 8]).format('DDDo'), '೮ನೇ', '೮ನೇ'); <add> assert.equal(moment([2011, 0, 9]).format('DDDo'), '೯ನೇ', '೯ನೇ'); <add> assert.equal(moment([2011, 0, 10]).format('DDDo'), '೧೦ನೇ', '೧೦ನೇ'); <add> <add> assert.equal(moment([2011, 0, 11]).format('DDDo'), '೧೧ನೇ', '೧೧ನೇ'); <add> assert.equal(moment([2011, 0, 12]).format('DDDo'), '೧೨ನೇ', '೧೨ನೇ'); <add> assert.equal(moment([2011, 0, 13]).format('DDDo'), '೧೩ನೇ', '೧೩ನೇ'); <add> assert.equal(moment([2011, 0, 14]).format('DDDo'), '೧೪ನೇ', '೧೪ನೇ'); <add> assert.equal(moment([2011, 0, 15]).format('DDDo'), '೧೫ನೇ', '೧೫ನೇ'); <add> assert.equal(moment([2011, 0, 16]).format('DDDo'), '೧೬ನೇ', '೧೬ನೇ'); <add> assert.equal(moment([2011, 0, 17]).format('DDDo'), '೧೭ನೇ', '೧೭ನೇ'); <add> assert.equal(moment([2011, 0, 18]).format('DDDo'), '೧೮ನೇ', '೧೮ನೇ'); <add> assert.equal(moment([2011, 0, 19]).format('DDDo'), '೧೯ನೇ', '೧೯ನೇ'); <add> assert.equal(moment([2011, 0, 20]).format('DDDo'), '೨೦ನೇ', '೨೦ನೇ'); <add> <add> assert.equal(moment([2011, 0, 21]).format('DDDo'), '೨೧ನೇ', '೨೧ನೇ'); <add> assert.equal(moment([2011, 0, 22]).format('DDDo'), '೨೨ನೇ', '೨೨ನೇ'); <add> assert.equal(moment([2011, 0, 23]).format('DDDo'), '೨೩ನೇ', '೨೩ನೇ'); <add> assert.equal(moment([2011, 0, 24]).format('DDDo'), '೨೪ನೇ', '೨೪ನೇ'); <add> assert.equal(moment([2011, 0, 25]).format('DDDo'), '೨೫ನೇ', '೨೫ನೇ'); <add> assert.equal(moment([2011, 0, 26]).format('DDDo'), '೨೬ನೇ', '೨೬ನೇ'); <add> assert.equal(moment([2011, 0, 27]).format('DDDo'), '೨೭ನೇ', '೨೭ನೇ'); <add> assert.equal(moment([2011, 0, 28]).format('DDDo'), '೨೮ನೇ', '೨೮ನೇ'); <add> assert.equal(moment([2011, 0, 29]).format('DDDo'), '೨೯ನೇ', '೨೯ನೇ'); <add> assert.equal(moment([2011, 0, 30]).format('DDDo'), '೩೦ನೇ', '೩೦ನೇ'); <add> <add> assert.equal(moment([2011, 0, 31]).format('DDDo'), '೩೧ನೇ', '೩೧ನೇ'); <add>}); <add> <add>test('format month', function (assert) { <add> var expected = 'ಜನವರಿ ಜನ_ಫೆಬ್ರವರಿ ಫೆಬ್ರ_ಮಾರ್ಚ್ ಮಾರ್ಚ್_ಏಪ್ರಿಲ್ ಏಪ್ರಿಲ್_ಮೇ ಮೇ_ಜೂನ್ ಜೂನ್_ಜುಲೈ ಜುಲೈ_ಆಗಸ್ಟ್ ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್ ಸೆಪ್ಟೆಂಬ_ಅಕ್ಟೋಬರ್ ಅಕ್ಟೋಬ_ನವೆಂಬರ್ ನವೆಂಬ_ಡಿಸೆಂಬರ್ ಡಿಸೆಂಬ'.split('_'), i; <add> for (i = 0; i < expected.length; i++) { <add> assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <add> } <add>}); <add> <add>test('format week', function (assert) { <add> var expected = 'ಭಾನುವಾರ ಭಾನು ಭಾ_ಸೋಮವಾರ ಸೋಮ ಸೋ_ಮಂಗಳವಾರ ಮಂಗಳ ಮಂ_ಬುಧವಾರ ಬುಧ ಬು_ಗುರುವಾರ ಗುರು ಗು_ಶುಕ್ರವಾರ ಶುಕ್ರ ಶು_ಶನಿವಾರ ಶನಿ ಶ'.split('_'), i; <add> for (i = 0; i < expected.length; i++) { <add> assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <add> } <add>}); <add> <add>test('from', function (assert) { <add> var start = moment([2007, 1, 28]); <add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ಕೆಲವು ಕ್ಷಣಗಳು', '44 seconds = a few seconds'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ಒಂದು ನಿಮಿಷ', '45 seconds = a minute'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ಒಂದು ನಿಮಿಷ', '89 seconds = a minute'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '೨ ನಿಮಿಷ', '90 seconds = 2 minutes'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '೪೪ ನಿಮಿಷ', '44 minutes = 44 minutes'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ಒಂದು ಗಂಟೆ', '45 minutes = an hour'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ಒಂದು ಗಂಟೆ', '89 minutes = an hour'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '೨ ಗಂಟೆ', '90 minutes = 2 hours'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '೫ ಗಂಟೆ', '5 hours = 5 hours'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '೨೧ ಗಂಟೆ', '21 hours = 21 hours'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ಒಂದು ದಿನ', '22 hours = a day'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ಒಂದು ದಿನ', '35 hours = a day'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '೨ ದಿನ', '36 hours = 2 days'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ಒಂದು ದಿನ', '1 day = a day'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '೫ ದಿನ', '5 days = 5 days'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '೨೫ ದಿನ', '25 days = 25 days'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ಒಂದು ತಿಂಗಳು', '26 days = a month'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ಒಂದು ತಿಂಗಳು', '30 days = a month'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ಒಂದು ತಿಂಗಳು', '43 days = a month'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '೨ ತಿಂಗಳು', '46 days = 2 months'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '೨ ತಿಂಗಳು', '75 days = 2 months'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '೩ ತಿಂಗಳು', '76 days = 3 months'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ಒಂದು ತಿಂಗಳು', '1 month = a month'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '೫ ತಿಂಗಳು', '5 months = 5 months'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ಒಂದು ವರ್ಷ', '345 days = a year'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '೨ ವರ್ಷ', '548 days = 2 years'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ಒಂದು ವರ್ಷ', '1 year = a year'); <add> assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '೫ ವರ್ಷ', '5 years = 5 years'); <add>}); <add> <add>test('suffix', function (assert) { <add> assert.equal(moment(30000).from(0), 'ಕೆಲವು ಕ್ಷಣಗಳು ನಂತರ', 'prefix'); <add> assert.equal(moment(0).from(30000), 'ಕೆಲವು ಕ್ಷಣಗಳು ಹಿಂದೆ', 'suffix'); <add>}); <add> <add>test('now from now', function (assert) { <add> assert.equal(moment().fromNow(), 'ಕೆಲವು ಕ್ಷಣಗಳು ಹಿಂದೆ', 'now from now should display as in the past'); <add>}); <add> <add>test('fromNow', function (assert) { <add> assert.equal(moment().add({s: 30}).fromNow(), 'ಕೆಲವು ಕ್ಷಣಗಳು ನಂತರ', 'ಕೆಲವು ಕ್ಷಣಗಳು ನಂತರ'); <add> assert.equal(moment().add({d: 5}).fromNow(), '೫ ದಿನ ನಂತರ', '೫ ದಿನ ನಂತರ'); <add>}); <add> <add>test('calendar day', function (assert) { <add> var a = moment().hours(12).minutes(0).seconds(0); <add> <add> assert.equal(moment(a).calendar(), 'ಇಂದು ಮಧ್ಯಾಹ್ನ ೧೨:೦೦', 'today at the same time'); <add> assert.equal(moment(a).add({m: 25}).calendar(), 'ಇಂದು ಮಧ್ಯಾಹ್ನ ೧೨:೨೫', 'Now plus 25 min'); <add> assert.equal(moment(a).add({h: 3}).calendar(), 'ಇಂದು ಮಧ್ಯಾಹ್ನ ೩:೦೦', 'Now plus 3 hours'); <add> assert.equal(moment(a).add({d: 1}).calendar(), 'ನಾಳೆ ಮಧ್ಯಾಹ್ನ ೧೨:೦೦', 'tomorrow at the same time'); <add> assert.equal(moment(a).subtract({h: 1}).calendar(), 'ಇಂದು ಮಧ್ಯಾಹ್ನ ೧೧:೦೦', 'Now minus 1 hour'); <add> assert.equal(moment(a).subtract({d: 1}).calendar(), 'ನಿನ್ನೆ ಮಧ್ಯಾಹ್ನ ೧೨:೦೦', 'yesterday at the same time'); <add>}); <add> <add>test('calendar next week', function (assert) { <add> var i, m; <add> for (i = 2; i < 7; i++) { <add> m = moment().add({d: i}); <add> assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); <add> } <add>}); <add> <add>test('calendar last week', function (assert) { <add> var i, m; <add> <add> for (i = 2; i < 7; i++) { <add> m = moment().subtract({d: i}); <add> assert.equal(m.calendar(), m.format('[ಕೊನೆಯ] dddd[,] LT'), 'Today - ' + i + ' days current time'); <add> m.hours(0).minutes(0).seconds(0).milliseconds(0); <add> assert.equal(m.calendar(), m.format('[ಕೊನೆಯ] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); <add> m.hours(23).minutes(59).seconds(59).milliseconds(999); <add> assert.equal(m.calendar(), m.format('[ಕೊನೆಯ] dddd[,] LT'), 'Today - ' + i + ' days end of day'); <add> } <add>}); <add> <add>test('calendar all else', function (assert) { <add> var weeksAgo = moment().subtract({w: 1}), <add> weeksFromNow = moment().add({w: 1}); <add> <add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); <add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); <add> <add> weeksAgo = moment().subtract({w: 2}); <add> weeksFromNow = moment().add({w: 2}); <add> <add> assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); <add> assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); <add>}); <add> <add>test('meridiem', function (assert) { <add> assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), 'ರಾತ್ರಿ', 'before dawn'); <add> assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), 'ಬೆಳಿಗ್ಗೆ', 'morning'); <add> assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), 'ಮಧ್ಯಾಹ್ನ', 'during day'); <add> assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), 'ಸಂಜೆ', 'evening'); <add> assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), 'ಸಂಜೆ', 'late evening'); <add> assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), 'ರಾತ್ರಿ', 'night'); <add> <add> assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), 'ರಾತ್ರಿ', 'before dawn'); <add> assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), 'ಬೆಳಿಗ್ಗೆ', 'morning'); <add> assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), 'ಮಧ್ಯಾಹ್ನ', ' during day'); <add> assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), 'ಸಂಜೆ', 'evening'); <add> assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), 'ಸಂಜೆ', 'late evening'); <add> assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), 'ರಾತ್ರಿ', 'night'); <add>}); <add> <add>test('weeks year starting sunday formatted', function (assert) { <add> assert.equal(moment([2012, 0, 1]).format('w ww wo'), '೧ ೦೧ ೧ನೇ', 'Jan 1 2012 should be week 1'); <add> assert.equal(moment([2012, 0, 7]).format('w ww wo'), '೧ ೦೧ ೧ನೇ', 'Jan 7 2012 should be week 1'); <add> assert.equal(moment([2012, 0, 8]).format('w ww wo'), '೨ ೦೨ ೨ನೇ', 'Jan 8 2012 should be week 2'); <add> assert.equal(moment([2012, 0, 14]).format('w ww wo'), '೨ ೦೨ ೨ನೇ', 'Jan 14 2012 should be week 2'); <add> assert.equal(moment([2012, 0, 15]).format('w ww wo'), '೩ ೦೩ ೩ನೇ', 'Jan 15 2012 should be week 3'); <add>}); <add>
2
Javascript
Javascript
use structuredclone instead of v8
dda7a21b07aa3f6b21b163fcebf7c118f819e8fb
<ide><path>lib/internal/webstreams/readablestream.js <ide> const { <ide> kEnumerableProperty, <ide> } = require('internal/util'); <ide> <del>const { <del> serialize, <del> deserialize, <del>} = require('v8'); <del> <ide> const { <ide> validateBuffer, <ide> validateObject, <ide> const { <ide> kIsReadable, <ide> } = require('internal/streams/utils'); <ide> <add>const { <add> structuredClone, <add>} = require('internal/structured_clone'); <add> <ide> const { <ide> ArrayBufferViewGetBuffer, <ide> ArrayBufferViewGetByteLength, <ide> function readableStreamDefaultTee(stream, cloneForBranch2) { <ide> const value1 = value; <ide> let value2 = value; <ide> if (!canceled2 && cloneForBranch2) { <del> // Structured Clone <del> value2 = deserialize(serialize(value2)); <add> value2 = structuredClone(value2); <ide> } <ide> if (!canceled1) { <ide> readableStreamDefaultControllerEnqueue(
1
Javascript
Javascript
support multiple pages directories for linting
527cb97b56cf5be39a5076c4811cb1c91f8824d4
<ide><path>packages/eslint-plugin-next/lib/rules/no-html-link-for-pages.js <ide> const path = require('path') <ide> const fs = require('fs') <ide> const { <del> getUrlFromPagesDirectory, <add> getUrlFromPagesDirectories, <ide> normalizeURL, <ide> execOnce, <ide> } = require('../utils/url') <ide> const pagesDirWarning = execOnce((pagesDirs) => { <ide> ) <ide> }) <ide> <add>// Cache for fs.existsSync lookup. <add>// Prevent multiple blocking IO requests that have already been calculated. <add>const fsExistsSyncCache = {} <add> <ide> module.exports = { <ide> meta: { <ide> docs: { <ide> module.exports = { <ide> recommended: true, <ide> }, <ide> fixable: null, // or "code" or "whitespace" <del> schema: ['pagesDirectory'], <add> schema: [ <add> { <add> oneOf: [ <add> { <add> type: 'string', <add> }, <add> { <add> type: 'array', <add> uniqueItems: true, <add> items: { <add> type: 'string', <add> }, <add> }, <add> ], <add> }, <add> ], <ide> }, <ide> <ide> create: function (context) { <ide> const [customPagesDirectory] = context.options <ide> const pagesDirs = customPagesDirectory <del> ? [customPagesDirectory] <add> ? [customPagesDirectory].flat() <ide> : [ <ide> path.join(context.getCwd(), 'pages'), <ide> path.join(context.getCwd(), 'src', 'pages'), <ide> ] <del> const pagesDir = pagesDirs.find((dir) => fs.existsSync(dir)) <del> if (!pagesDir) { <add> const foundPagesDirs = pagesDirs.filter((dir) => { <add> if (fsExistsSyncCache[dir] === undefined) { <add> fsExistsSyncCache[dir] = fs.existsSync(dir) <add> } <add> return fsExistsSyncCache[dir] <add> }) <add> if (foundPagesDirs.length === 0) { <ide> pagesDirWarning(pagesDirs) <ide> return {} <ide> } <ide> <del> const urls = getUrlFromPagesDirectory('/', pagesDir) <add> const urls = getUrlFromPagesDirectories('/', foundPagesDirs) <ide> return { <ide> JSXOpeningElement(node) { <ide> if (node.name.name !== 'a') { <ide><path>packages/eslint-plugin-next/lib/utils/url.js <ide> const fs = require('fs') <ide> const path = require('path') <ide> <add>// Cache for fs.lstatSync lookup. <add>// Prevent multiple blocking IO requests that have already been calculated. <add>const fsLstatSyncCache = {} <add>const fsLstatSync = (source) => { <add> fsLstatSyncCache[source] = fsLstatSyncCache[source] || fs.lstatSync(source) <add> return fsLstatSyncCache[source] <add>} <add> <ide> /** <ide> * Checks if the source is a directory. <ide> * @param {string} source <ide> */ <ide> function isDirectory(source) { <del> return fs.lstatSync(source).isDirectory() <add> return fsLstatSync(source).isDirectory() <ide> } <ide> <ide> /** <ide> * Checks if the source is a directory. <ide> * @param {string} source <ide> */ <ide> function isSymlink(source) { <del> return fs.lstatSync(source).isSymbolicLink() <add> return fsLstatSync(source).isSymbolicLink() <ide> } <ide> <ide> /** <ide> * Gets the possible URLs from a directory. <ide> * @param {string} urlprefix <del> * @param {string} directory <add> * @param {string[]} directories <ide> */ <del>function getUrlFromPagesDirectory(urlPrefix, directory) { <del> return parseUrlForPages(urlPrefix, directory).map( <del> // Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly. <del> (url) => new RegExp(`^${normalizeURL(url)}$`) <del> ) <add>function getUrlFromPagesDirectories(urlPrefix, directories) { <add> return Array.from( <add> // De-duplicate similar pages across multiple directories. <add> new Set( <add> directories <add> .map((directory) => parseUrlForPages(urlPrefix, directory)) <add> .flat() <add> .map( <add> // Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly. <add> (url) => `^${normalizeURL(url)}$` <add> ) <add> ) <add> ).map((urlReg) => new RegExp(urlReg)) <ide> } <ide> <add>// Cache for fs.readdirSync lookup. <add>// Prevent multiple blocking IO requests that have already been calculated. <add>const fsReadDirSyncCache = {} <add> <ide> /** <ide> * Recursively parse directory for page URLs. <ide> * @param {string} urlprefix <ide> * @param {string} directory <ide> */ <ide> function parseUrlForPages(urlprefix, directory) { <del> const files = fs.readdirSync(directory) <add> fsReadDirSyncCache[directory] = <add> fsReadDirSyncCache[directory] || fs.readdirSync(directory) <ide> const res = [] <del> files.forEach((fname) => { <add> fsReadDirSyncCache[directory].forEach((fname) => { <ide> if (/(\.(j|t)sx?)$/.test(fname)) { <ide> fname = fname.replace(/\[.*\]/g, '.*') <ide> if (/^index(\.(j|t)sx?)$/.test(fname)) { <ide> function execOnce(fn) { <ide> } <ide> <ide> module.exports = { <del> getUrlFromPagesDirectory, <add> getUrlFromPagesDirectories, <ide> normalizeURL, <ide> execOnce, <ide> } <ide><path>test/eslint-plugin-next/no-html-link-for-pages.unit.test.js <ide> const linterConfig = { <ide> }, <ide> }, <ide> } <add>const linterConfigWithMultipleDirectories = { <add> ...linterConfig, <add> rules: { <add> 'no-html-link-for-pages': [ <add> 2, <add> [ <add> path.join(__dirname, 'custom-pages'), <add> path.join(__dirname, 'custom-pages/list'), <add> ], <add> ], <add> }, <add>} <ide> <ide> linter.defineRules({ <ide> 'no-html-link-for-pages': rule, <ide> describe('no-html-link-for-pages', function () { <ide> assert.deepEqual(report, []) <ide> }) <ide> <add> it('valid link element with multiple directories', function () { <add> const report = linter.verify( <add> validCode, <add> linterConfigWithMultipleDirectories, <add> { <add> filename: 'foo.js', <add> } <add> ) <add> assert.deepEqual(report, []) <add> }) <add> <ide> it('valid anchor element', function () { <ide> const report = linter.verify(validAnchorCode, linterConfig, { <ide> filename: 'foo.js',
3
PHP
PHP
set translations to use the cake domain
8a77a31620cec8c1338e54876cc2760682811f2f
<ide><path>lib/Cake/View/Helper/FormHelper.php <ide> public function radio($fieldName, $options = array(), $attributes = array()) { <ide> <ide> $showEmpty = $this->_extractOption('empty', $attributes); <ide> if ($showEmpty) { <del> $showEmpty = ($showEmpty === true) ? __('empty') : $showEmpty; <add> $showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty; <ide> $options = array('' => $showEmpty) + $options; <ide> } <ide> unset($attributes['empty']); <ide><path>lib/Cake/View/Helper/HtmlHelper.php <ide> protected function _prepareCrumbs($startText) { <ide> 'text' => $startText <ide> ); <ide> } <del> $startText += array('url' => '/', 'text' => __('Home')); <add> $startText += array('url' => '/', 'text' => __d('cake', 'Home')); <ide> list($url, $text) = array($startText['url'], $startText['text']); <ide> unset($startText['url'], $startText['text']); <ide> array_unshift($crumbs, array($text, $url, $startText));
2
Ruby
Ruby
clarify homebrew_github_api_token in gist-logs err
2a1b936f7697f355f76603ef1984ccbdf4abea9e
<ide><path>Library/Homebrew/cmd/gist-logs.rb <ide> def gistify_logs(f) <ide> puts <<~EOS <ide> You can create a new personal access token: <ide> #{GitHub::ALL_SCOPES_URL} <del> and then set the new HOMEBREW_GITHUB_API_TOKEN as the authentication method. <add> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> <ide> EOS <ide> login! <ide><path>Library/Homebrew/utils/github.rb <ide> def initialize(reset, github_message) <ide> GitHub API Error: #{github_message} <ide> Try again in #{pretty_ratelimit_reset(reset)}, or create a personal access token: <ide> #{ALL_SCOPES_URL} <del> and then set the token as: export HOMEBREW_GITHUB_API_TOKEN="your_new_token" <add> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> EOS <ide> end <ide> <ide> def initialize(github_message) <ide> printf "protocol=https\\nhost=github.com\\n" | git credential-osxkeychain erase <ide> Or create a personal access token: <ide> #{ALL_SCOPES_URL} <del> and then set the token as: export HOMEBREW_GITHUB_API_TOKEN="your_new_token" <add> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> EOS <ide> end <ide> super message <ide> def api_credentials_error_message(response_headers, needed_scopes) <ide> Scopes they need: #{needed_human_scopes} <ide> Scopes they have: #{credentials_scopes} <ide> Create a personal access token: #{ALL_SCOPES_URL} <del> and then set HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <add> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> EOS <ide> when :environment <ide> onoe <<~EOS <ide> Your HOMEBREW_GITHUB_API_TOKEN does not have sufficient scope! <ide> Scopes they need: #{needed_human_scopes} <ide> Scopes it has: #{credentials_scopes} <ide> Create a new personal access token: #{ALL_SCOPES_URL} <del> and then set the new HOMEBREW_GITHUB_API_TOKEN as the authentication method instead. <add> #{Utils::Shell.set_variable_in_profile("HOMEBREW_GITHUB_API_TOKEN", "your_token_here")} <ide> EOS <ide> end <ide> end
2
Ruby
Ruby
restore previous state when interrupted
4c55082e7c0bcf0c6bb2b1401286fda466ad3248
<ide><path>Library/Homebrew/cmd/update.rb <ide> def pull! <ide> # the refspec ensures that 'origin/master' gets updated <ide> args << "refs/heads/master:refs/remotes/origin/master" <ide> <del> safe_system "git", *args <add> reset_on_interrupt { safe_system "git", *args } <ide> <ide> @current_revision = read_current_revision <ide> end <ide> <add> def reset_on_interrupt <add> ignore_interrupts { yield } <add> ensure <add> if $?.signaled? && $?.termsig == 2 # SIGINT <add> safe_system "git", "reset", "--hard", @initial_revision <add> end <add> end <add> <ide> # Matches raw git diff format (see `man git-diff-tree`) <ide> DIFFTREE_RX = /^:[0-7]{6} [0-7]{6} [0-9a-fA-F]{40} [0-9a-fA-F]{40} ([ACDMR])\d{0,3}\t(.+?)(?:\t(.+))?$/ <ide>
1