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 |
|---|---|---|---|---|---|
Text | Text | fix line length and output examples | 7491653511f256fc40641c68a6338540ab75cc7f | <ide><path>src/I18n/README.md
<ide> should you wish to create them manually instead of using the conventions this li
<ide> ```php
<ide> use Cake\I18n\I18n;
<ide>
<del>I18n::locale('de_DE');
<add>I18n::locale('en_US');
<ide> ```
<ide>
<ide> ### Translating a message
<ide> echo Number::format(100100100);
<ide>
<ide> ```php
<ide> echo Number::currency(123456.7890, 'EUR');
<del>// outputs €100,100,100.00
<add>// outputs €123,456.79
<ide> ```
<ide>
<ide> ## Documentation
<ide>
<del>Please make sure you check the [official I18n documentation](http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html)
<add>Please make sure you check the [official I18n
<add>documentation](http://book.cakephp.org/3.0/en/core-libraries/internationalization-and-localization.html)
<ide>
<del>The [documentation for the Time class](http://book.cakephp.org/3.0/en/core-libraries/time.html) contains instruction on how configure and output
<del>time strings for selected locales.
<add>The [documentation for the Time
<add>class](http://book.cakephp.org/3.0/en/core-libraries/time.html) contains
<add>instruction on how configure and output time strings for selected locales.
<ide>
<del>The [documentation for the Number class](http://book.cakephp.org/3.0/en/core-libraries/number.html) shows how to use the `Number` class for
<del>displaying numbers in specific locales.
<add>The [documentation for the Number
<add>class](http://book.cakephp.org/3.0/en/core-libraries/number.html) shows how to
<add>use the `Number` class for displaying numbers in specific locales. | 1 |
Text | Text | fix sentence 😳 | fc1175b28dd1fe3751dc483b8fceb45d976e4fb2 | <ide><path>docs/focus/2018-05-07.md
<ide> - Clear the branch name after a successful checkout [atom/github#1438](https://github.com/atom/github/pull/1438)
<ide> - Improve readability of console git diagnostic messages [atom/github#1439](https://github.com/atom/github/pull/1439)
<ide> - Teletype
<del> - Shipped [Teletype 0.13.2](https://github.com/atom/teletype/releases/tag/v0.13.2) to fix an issue that Fixed an issue that would sometimes occur when closing the WebRTC connection ([atom/teletype#368](https://github.com/atom/teletype/issues/368))
<add> - Shipped [Teletype 0.13.2](https://github.com/atom/teletype/releases/tag/v0.13.2) to fix an issue that would sometimes occur when closing the WebRTC connection ([atom/teletype#368](https://github.com/atom/teletype/issues/368))
<ide> - Reactor Duty
<ide>
<ide> ## Focus for week ahead | 1 |
Ruby | Ruby | fix docs of `assert_no_emails` [ci skip] | ff090977c1e7f7e0382be6f62910af03788d2eeb | <ide><path>actionmailer/lib/action_mailer/test_helper.rb
<ide> def assert_emails(number, &block)
<ide> #
<ide> # Note: This assertion is simply a shortcut for:
<ide> #
<del> # assert_emails 0
<add> # assert_emails 0, &block
<ide> def assert_no_emails(&block)
<ide> assert_emails 0, &block
<ide> end | 1 |
Javascript | Javascript | improve size output readability | 62d87e20b15374c6292468ca775c2b504421f9eb | <ide><path>lib/Stats.js
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> newline();
<ide> }
<ide> }
<add> function formatSize(size) {
<add> if(size <= 0) return "0 bytes";
<add>
<add> var abbreviations = ["bytes", "kB", "MB", "GB"];
<add> var index = Math.floor(Math.log(size) / Math.log(1000));
<add>
<add> return +(size / Math.pow(1000, index))
<add> .toPrecision(3) + ' ' + abbreviations[index];
<add> }
<ide>
<ide> if(obj.hash) {
<ide> normal("Hash: ");
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> obj.assets.forEach(function(asset) {
<ide> t.push([
<ide> asset.name,
<del> asset.size,
<add> formatSize(asset.size),
<ide> asset.chunks.join(", "),
<ide> asset.emitted ? "[emitted]" : "",
<ide> asset.chunkNames.join(", ")
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> }
<ide> function processModuleAttributes(module) {
<ide> normal(" ");
<del> normal(module.size);
<add> normal(formatSize(module.size));
<ide> if(module.chunks) {
<ide> module.chunks.forEach(function(chunk) {
<ide> normal(" {");
<ide> Stats.jsonToString = function jsonToString(obj, useColors) {
<ide> normal(")");
<ide> }
<ide> normal(" ");
<del> normal(chunk.size);
<add> normal(formatSize(chunk.size));
<ide> chunk.parents.forEach(function(id) {
<ide> normal(" {");
<ide> yellow(id); | 1 |
Javascript | Javascript | move text measurement into font | 4a7fe7cb5d9a35b0bc67aaade6dfa476890b9caa | <ide><path>fonts.js
<ide> var kMaxWaitForFontFace = 1000;
<ide> */
<ide>
<ide> var Fonts = (function Fonts() {
<del> var kScalePrecision = 40;
<ide> var fonts = [];
<del>
<del> if (!isWorker) {
<del> var ctx = document.createElement('canvas').getContext('2d');
<del> ctx.scale(1 / kScalePrecision, 1);
<del> }
<del>
<ide> var fontCount = 0;
<ide>
<ide> function FontInfo(name, data, properties) {
<ide> var Fonts = (function Fonts() {
<ide> }
<ide>
<ide> var current;
<del> var measureCache;
<ide>
<ide> return {
<ide> registerFont: function fonts_registerFont(fontName, data, properties) {
<ide> var Fonts = (function Fonts() {
<ide> },
<ide> lookupById: function fonts_lookupById(id) {
<ide> return fonts[id];
<del> },
<del> setActive: function fonts_setActive(fontName, fontObj, size) {
<del> // |current| can be null is fontName is a built-in font
<del> // (e.g. "sans-serif")
<del> if (fontObj && (current = fonts[fontObj.id])) {
<del> var sizes = current.sizes;
<del> if (!(measureCache = sizes[size]))
<del> measureCache = sizes[size] = Object.create(null);
<del> } else {
<del> measureCache = null
<del> }
<del>
<del> ctx.font = (size * kScalePrecision) + 'px "' + fontName + '"';
<del> },
<del> measureText: function fonts_measureText(text) {
<del> var width;
<del> if (measureCache && (width = measureCache[text]))
<del> return width;
<del> width = ctx.measureText(text).width / kScalePrecision;
<del> if (measureCache)
<del> measureCache[text] = width;
<del> return width;
<ide> }
<ide> };
<ide> })();
<ide> function getUnicodeRangeFor(value) {
<ide> return -1;
<ide> }
<ide>
<add>var MeasureText = {
<add> currentCache: null,
<add> currentFont: null,
<add> currentSize: 0,
<add> ctx: null,
<add> sizes: Object.create(null)
<add>};
<add>
<ide> /**
<ide> * 'Font' is the class the outside world should use, it encapsulate all the font
<ide> * decoding logics whatever type it is (assuming the font type is supported).
<ide> function getUnicodeRangeFor(value) {
<ide> * type1Font.bind();
<ide> */
<ide> var Font = (function() {
<add> var kScalePrecision = 40;
<add>
<ide> var constructor = function font_constructor(name, file, properties) {
<ide> this.name = name;
<ide> this.textMatrix = properties.textMatrix || IDENTITY_MATRIX;
<ide> var Font = (function() {
<ide> return rule;
<ide> },
<ide>
<del> charsToUnicode: function fonts_chars2Unicode(chars) {
<add> charsToUnicode: function fonts_charsToUnicode(chars) {
<ide> var charsCache = this.charsCache;
<ide>
<ide> // if we translated this string before, just grab it from the cache
<ide> var Font = (function() {
<ide>
<ide> // Enter the translated string into the cache
<ide> return charsCache[chars] = str;
<add> },
<add>
<add> measureText: function fonts_measureText(text, size) {
<add> if (MeasureText.currentFont != this ||
<add> MeasureText.currentSize != size) {
<add> var ctx = MeasureText.ctx;
<add> if (!ctx) {
<add> ctx = MeasureText.ctx = document.createElement('canvas').getContext('2d');
<add> ctx.scale(1 / kScalePrecision, 1);
<add> }
<add> ctx.font = (size * kScalePrecision) + 'px "' + this.loadedName + '"';
<add> MeasureText.currentFont = this;
<add> MeasureText.currentSize = size;
<add> var cache = MeasureText.sizes[size];
<add> if (!cache)
<add> cache = MeasureText.sizes[size] = Object.create(null);
<add> MeasureText.currentCache = cache;
<add> }
<add>
<add> var key = size + "$" + text;
<add> var width = MeasureText.currentCache[key];
<add> if (width)
<add> return width;
<add> var ctx = MeasureText.ctx;
<add> width = ctx.measureText(text).width / kScalePrecision;
<add> return MeasureText.currentCache[key] = width;
<ide> }
<ide> };
<ide>
<ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> this.ctx.$setFont(fontName, size);
<ide> } else {
<ide> this.ctx.font = size + 'px "' + fontName + '"';
<del> Fonts.setActive(fontName, fontObj, size);
<ide> }
<ide> },
<ide> setTextRenderingMode: function(mode) {
<ide> var CanvasGraphics = (function() {
<ide> ctx.$showText(current.y, text);
<ide> } else {
<ide> ctx.translate(current.x, -1 * current.y);
<del> var font = this.current.font;
<del> if (font) {
<del> ctx.transform.apply(ctx, font.textMatrix);
<del> text = font.charsToUnicode(text);
<del> }
<add> var font = current.font;
<add> ctx.transform.apply(ctx, font.textMatrix);
<add> text = font.charsToUnicode(text);
<ide> ctx.fillText(text, 0, 0);
<del> current.x += Fonts.measureText(text);
<add> current.x += font.measureText(text, current.fontSize);
<ide> }
<ide>
<del> this.ctx.restore();
<add> ctx.restore();
<ide> },
<ide> showSpacedText: function(arr) {
<ide> for (var i = 0; i < arr.length; ++i) { | 2 |
PHP | PHP | move htmlattributestrait methods into basicwiget | 403ebbe9cc154c334ba86266bba882d39f579a69 | <ide><path>src/View/Widget/BasicWidget.php
<ide> */
<ide> namespace Cake\View\Widget;
<ide>
<add>use Cake\Database\Schema\TableSchema;
<ide> use Cake\View\Form\ContextInterface;
<ide> use Cake\View\StringTemplate;
<ide>
<ide> */
<ide> class BasicWidget implements WidgetInterface
<ide> {
<del> use HtmlAttributesTrait;
<del>
<ide> /**
<ide> * StringTemplate instance.
<ide> *
<ide> protected function mergeDefaults(array $data, ContextInterface $context): array
<ide> return $data;
<ide> }
<ide>
<add> /**
<add> * Set value for "required" attribute if applicable.
<add> *
<add> * @param array $data Data array
<add> * @param \Cake\View\Form\ContextInterface $context Context instance.
<add> * @param string $fieldName Field name.
<add> * @return array Updated data array.
<add> */
<add> protected function setRequired(array $data, ContextInterface $context, string $fieldName): array
<add> {
<add> if (
<add> empty($data['disabled'])
<add> && (
<add> (isset($data['type'])
<add> && $data['type'] !== 'hidden'
<add> )
<add> || !isset($data['type'])
<add> )
<add> && $context->isRequired($fieldName)
<add> ) {
<add> $data['required'] = true;
<add> }
<add>
<add> return $data;
<add> }
<add>
<add> /**
<add> * Set value for "maxlength" attribute if applicable.
<add> *
<add> * @param array $data Data array
<add> * @param \Cake\View\Form\ContextInterface $context Context instance.
<add> * @param string $fieldName Field name.
<add> * @return array Updated data array.
<add> */
<add> protected function setMaxLength(array $data, ContextInterface $context, string $fieldName): array
<add> {
<add> $maxLength = $context->getMaxLength($fieldName);
<add> if ($maxLength !== null) {
<add> $data['maxlength'] = min($maxLength, 100000);
<add> }
<add>
<add> return $data;
<add> }
<add>
<add> /**
<add> * Set value for "step" attribute if applicable.
<add> *
<add> * @param array $data Data array
<add> * @param \Cake\View\Form\ContextInterface $context Context instance.
<add> * @param string $fieldName Field name.
<add> * @return array Updated data array.
<add> */
<add> protected function setStep(array $data, ContextInterface $context, string $fieldName): array
<add> {
<add> $dbType = $context->type($fieldName);
<add> $fieldDef = $context->attributes($fieldName);
<add>
<add> $fractionalTypes = [
<add> TableSchema::TYPE_DATETIME_FRACTIONAL,
<add> TableSchema::TYPE_TIMESTAMP_FRACTIONAL,
<add> ];
<add>
<add> if ($data['type'] === 'number') {
<add> if ($dbType === 'decimal' && isset($fieldDef['precision'])) {
<add> $decimalPlaces = $fieldDef['precision'];
<add> $data['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
<add> } elseif ($dbType === 'float') {
<add> $data['step'] = 'any';
<add> }
<add> } elseif (in_array($dbType, $fractionalTypes, true)) {
<add> $data['step'] = '0.001';
<add> }
<add>
<add> return $data;
<add> }
<add>
<ide> /**
<ide> * @inheritDoc
<ide> */
<ide><path>src/View/Widget/HtmlAttributesTrait.php
<del><?php
<del>declare(strict_types=1);
<del>
<del>/**
<del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<del> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
<del> * @link https://cakephp.org CakePHP(tm) Project
<del> * @since 4.0.0
<del> * @license https://opensource.org/licenses/mit-license.php MIT License
<del> */
<del>namespace Cake\View\Widget;
<del>
<del>use Cake\Database\Schema\TableSchema;
<del>use Cake\View\Form\ContextInterface;
<del>
<del>/**
<del> * Trait with helper methods to set default HTML attributes for widgets.
<del> *
<del> * @internal
<del> */
<del>trait HtmlAttributesTrait
<del>{
<del> /**
<del> * Set value for "required" attribute if applicable.
<del> *
<del> * @param array $data Data array
<del> * @param \Cake\View\Form\ContextInterface $context Context instance.
<del> * @param string $fieldName Field name.
<del> * @return array Updated data array.
<del> */
<del> protected function setRequired(array $data, ContextInterface $context, string $fieldName): array
<del> {
<del> if (
<del> empty($data['disabled'])
<del> && (
<del> (isset($data['type'])
<del> && $data['type'] !== 'hidden'
<del> )
<del> || !isset($data['type'])
<del> )
<del> && $context->isRequired($fieldName)
<del> ) {
<del> $data['required'] = true;
<del> }
<del>
<del> return $data;
<del> }
<del>
<del> /**
<del> * Set value for "maxlength" attribute if applicable.
<del> *
<del> * @param array $data Data array
<del> * @param \Cake\View\Form\ContextInterface $context Context instance.
<del> * @param string $fieldName Field name.
<del> * @return array Updated data array.
<del> */
<del> protected function setMaxLength(array $data, ContextInterface $context, string $fieldName): array
<del> {
<del> $maxLength = $context->getMaxLength($fieldName);
<del> if ($maxLength !== null) {
<del> $data['maxlength'] = min($maxLength, 100000);
<del> }
<del>
<del> return $data;
<del> }
<del>
<del> /**
<del> * Set value for "step" attribute if applicable.
<del> *
<del> * @param array $data Data array
<del> * @param \Cake\View\Form\ContextInterface $context Context instance.
<del> * @param string $fieldName Field name.
<del> * @return array Updated data array.
<del> */
<del> protected function setStep(array $data, ContextInterface $context, string $fieldName): array
<del> {
<del> $dbType = $context->type($fieldName);
<del> $fieldDef = $context->attributes($fieldName);
<del>
<del> $fractionalTypes = [
<del> TableSchema::TYPE_DATETIME_FRACTIONAL,
<del> TableSchema::TYPE_TIMESTAMP_FRACTIONAL,
<del> ];
<del>
<del> if ($data['type'] === 'number') {
<del> if ($dbType === 'decimal' && isset($fieldDef['precision'])) {
<del> $decimalPlaces = $fieldDef['precision'];
<del> $data['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
<del> } elseif ($dbType === 'float') {
<del> $data['step'] = 'any';
<del> }
<del> } elseif (in_array($dbType, $fractionalTypes, true)) {
<del> $data['step'] = '0.001';
<del> }
<del>
<del> return $data;
<del> }
<del>} | 2 |
Python | Python | fix word embeddings example | ce406b773b9f36be5718a4369ad07fea4f9ebdba | <ide><path>examples/lstm_seq2seq.py
<ide> latent_dim = 256 # Latent dimensionality of the encoding space.
<ide> num_samples = 10000 # Number of samples to train on.
<ide> # Path to the data txt file on disk.
<del>data_path = '/Users/fchollet/Downloads/fra-eng/fra.txt'
<add>data_path = 'fra-eng/fra.txt'
<ide>
<ide> # Vectorize the data.
<ide> input_texts = []
<ide><path>examples/pretrained_word_embeddings.py
<ide> from keras.preprocessing.text import Tokenizer
<ide> from keras.preprocessing.sequence import pad_sequences
<ide> from keras.utils import to_categorical
<del>from keras.layers import Dense, Input, Flatten
<add>from keras.layers import Dense, Input, GlobalMaxPooling1D
<ide> from keras.layers import Conv1D, MaxPooling1D, Embedding
<ide> from keras.models import Model
<ide>
<ide>
<ide> BASE_DIR = ''
<del>GLOVE_DIR = BASE_DIR + '/glove.6B/'
<del>TEXT_DATA_DIR = BASE_DIR + '/20_newsgroup/'
<add>GLOVE_DIR = os.path.join(BASE_DIR, 'glove.6B')
<add>TEXT_DATA_DIR = os.path.join(BASE_DIR, '20_newsgroup')
<ide> MAX_SEQUENCE_LENGTH = 1000
<ide> MAX_NB_WORDS = 20000
<ide> EMBEDDING_DIM = 100
<ide>
<ide> # prepare embedding matrix
<ide> num_words = min(MAX_NB_WORDS, len(word_index))
<del>embedding_matrix = np.zeros((num_words + 1, EMBEDDING_DIM))
<add>embedding_matrix = np.zeros((num_words, EMBEDDING_DIM))
<ide> for word, i in word_index.items():
<ide> if i >= MAX_NB_WORDS:
<ide> continue
<ide> x = Conv1D(128, 5, activation='relu')(x)
<ide> x = MaxPooling1D(5)(x)
<ide> x = Conv1D(128, 5, activation='relu')(x)
<del>x = MaxPooling1D(35)(x)
<del>x = Flatten()(x)
<add>x = GlobalMaxPooling1D()(x)
<ide> x = Dense(128, activation='relu')(x)
<ide> preds = Dense(len(labels_index), activation='softmax')(x)
<ide> | 2 |
Python | Python | fix documentation for percentile and quantile | a52aae6793fbcea04148ca41456a3fe24b26efee | <ide><path>numpy/lib/function_base.py
<ide> def percentile(a,
<ide>
<ide> Notes
<ide> -----
<del> Given a vector ``V`` of length ``N``, the q-th percentile of ``V`` is
<add> Given a vector ``V`` of length ``n``, the q-th percentile of ``V`` is
<ide> the value ``q/100`` of the way from the minimum to the maximum in a
<ide> sorted copy of ``V``. The values and distances of the two nearest
<ide> neighbors as well as the `method` parameter will determine the
<ide> def percentile(a,
<ide> same as the minimum if ``q=0`` and the same as the maximum if
<ide> ``q=100``.
<ide>
<del> This optional `method` parameter specifies the method to use when the
<del> desired quantile lies between two data points ``i < j``.
<del> If ``g`` is the fractional part of the index surrounded by ``i`` and
<del> alpha and beta are correction constants modifying i and j.
<del>
<del> Below, 'q' is the quantile value, 'n' is the sample size and
<del> alpha and beta are constants.
<del> The following formula gives an interpolation "i + g" of where the quantile
<del> would be in the sorted sample.
<del> With 'i' being the floor and 'g' the fractional part of the result.
<add> The optional `method` parameter specifies the method to use when the
<add> desired percentile lies between two indexes ``i`` and ``j = i + 1``.
<add> In that case, we first determine ``i + g``, a virtual index that lies
<add> between ``i`` and ``j``, where ``i`` is the floor and ``g`` is the
<add> fractional part of the index. The final result is, then, an interpolation
<add> of ``a[i]`` and ``a[j]`` based on ``g``. During the computation of ``g``,
<add> ``i`` and ``j`` are modified using correction constants ``alpha`` and
<add> ``beta`` whose choices depend on the ``method`` used. Finally, note that
<add> since Python uses 0-based indexing, the code subtracts another 1 from the
<add> index internally.
<add>
<add> The following formula determines the virtual index ``i + g``, the location
<add> of the percentile in the sorted sample:
<ide>
<ide> .. math::
<del> i + g = q * ( n - alpha - beta + 1 ) + alpha
<add> i + g = (q / 100) * ( n - alpha - beta + 1 ) + alpha
<ide>
<ide> The different methods then work as follows
<ide>
<ide> def quantile(a,
<ide>
<ide> Notes
<ide> -----
<del> Given a vector ``V`` of length ``N``, the q-th quantile of ``V`` is the
<del> value ``q`` of the way from the minimum to the maximum in a sorted copy of
<del> ``V``. The values and distances of the two nearest neighbors as well as the
<del> `method` parameter will determine the quantile if the normalized
<del> ranking does not match the location of ``q`` exactly. This function is the
<del> same as the median if ``q=0.5``, the same as the minimum if ``q=0.0`` and
<del> the same as the maximum if ``q=1.0``.
<add> Given a vector ``V`` of length ``n``, the q-th quantile of ``V`` is
<add> the value ``q`` of the way from the minimum to the maximum in a
<add> sorted copy of ``V``. The values and distances of the two nearest
<add> neighbors as well as the `method` parameter will determine the
<add> quantile if the normalized ranking does not match the location of
<add> ``q`` exactly. This function is the same as the median if ``q=0.5``, the
<add> same as the minimum if ``q=0.0`` and the same as the maximum if
<add> ``q=1.0``.
<ide>
<ide> The optional `method` parameter specifies the method to use when the
<del> desired quantile lies between two data points ``i < j``.
<del> If ``g`` is the fractional part of the index surrounded by ``i`` and ``j``,
<del> and alpha and beta are correction constants modifying i and j:
<add> desired quantile lies between two indexes ``i`` and ``j = i + 1``.
<add> In that case, we first determine ``i + g``, a virtual index that lies
<add> between ``i`` and ``j``, where ``i`` is the floor and ``g`` is the
<add> fractional part of the index. The final result is, then, an interpolation
<add> of ``a[i]`` and ``a[j]`` based on ``g``. During the computation of ``g``,
<add> ``i`` and ``j`` are modified using correction constants ``alpha`` and
<add> ``beta`` whose choices depend on the ``method`` used. Finally, note that
<add> since Python uses 0-based indexing, the code subtracts another 1 from the
<add> index internally.
<add>
<add> The following formula determines the virtual index ``i + g``, the location
<add> of the quantile in the sorted sample:
<ide>
<ide> .. math::
<ide> i + g = q * ( n - alpha - beta + 1 ) + alpha | 1 |
Ruby | Ruby | add cask reinstall command | a4e092a1c49bf7a81244a1f04ef1e115176754cc | <ide><path>Library/Homebrew/cask/lib/hbc/cli.rb
<ide> require "hbc/cli/info"
<ide> require "hbc/cli/install"
<ide> require "hbc/cli/list"
<add>require "hbc/cli/reinstall"
<ide> require "hbc/cli/search"
<ide> require "hbc/cli/style"
<ide> require "hbc/cli/uninstall"
<ide><path>Library/Homebrew/cask/lib/hbc/cli/reinstall.rb
<add>module Hbc
<add> class CLI
<add> class Reinstall < Install
<add> def self.install_casks(cask_tokens, force, skip_cask_deps, require_sha)
<add> count = 0
<add> cask_tokens.each do |cask_token|
<add> begin
<add> cask = Hbc.load(cask_token)
<add>
<add> if cask.installed?
<add> # use copy of cask for uninstallation to avoid 'No such file or directory' bug
<add> installed_cask = cask;
<add> latest_installed_version = installed_cask.timestamped_versions.last
<add>
<add> unless latest_installed_version.nil?
<add> latest_installed_cask_file = installed_cask.metadata_master_container_path
<add> .join(latest_installed_version.join(File::Separator),
<add> "Casks", "#{cask_token}.rb")
<add>
<add> # use the same cask file that was used for installation, if possible
<add> installed_cask = Hbc.load(latest_installed_cask_file) if latest_installed_cask_file.exist?
<add> end
<add>
<add> # Always force uninstallation, ignore method parameter
<add> Installer.new(installed_cask, force: true).uninstall
<add> end
<add>
<add> Installer.new(cask,
<add> force: force,
<add> skip_cask_deps: skip_cask_deps,
<add> require_sha: require_sha).install
<add> count += 1
<add> rescue CaskUnavailableError => e
<add> warn_unavailable_with_suggestion cask_token, e
<add> rescue CaskNoShasumError => e
<add> opoo e.message
<add> count += 1
<add> end
<add> end
<add> count.zero? ? nil : count == cask_tokens.length
<add> end
<add>
<add> def self.help
<add> "reinstalls the given Cask"
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/cask/test/cask/cli/reinstall_test.rb
<add>require "test_helper"
<add>
<add>describe Hbc::CLI::Reinstall do
<add> it "allows reinstalling a Cask" do
<add> Hbc::CLI::Install.run("local-transmission")
<add> Hbc.load("local-transmission").must_be :installed?
<add> Hbc::CLI::Reinstall.run("local-transmission")
<add> Hbc.load("local-transmission").must_be :installed?
<add> end
<add>
<add> it "allows reinstalling a non installed Cask" do
<add> Hbc::CLI::Uninstall.run("local-transmission")
<add> Hbc.load("local-transmission").wont_be :installed?
<add> Hbc::CLI::Reinstall.run("local-transmission")
<add> Hbc.load("local-transmission").must_be :installed?
<add> end
<add>end | 3 |
Go | Go | use pivot_root instead of chroot for chrootarchive | 85988b33d299697f410a3a92db5d537fdbee955b | <ide><path>pkg/chrootarchive/archive_unix.go
<ide> import (
<ide> "io/ioutil"
<ide> "os"
<ide> "runtime"
<del> "syscall"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/reexec"
<ide> )
<ide>
<del>func chroot(path string) error {
<del> if err := syscall.Chroot(path); err != nil {
<del> return err
<del> }
<del> return syscall.Chdir("/")
<del>}
<del>
<ide> // untar is the entry-point for docker-untar on re-exec. This is not used on
<ide> // Windows as it does not support chroot, hence no point sandboxing through
<ide> // chroot and rexec.
<ide><path>pkg/chrootarchive/chroot_linux.go
<add>package chrootarchive
<add>
<add>import (
<add> "fmt"
<add> "io/ioutil"
<add> "os"
<add> "path/filepath"
<add> "syscall"
<add>)
<add>
<add>// chroot on linux uses pivot_root instead of chroot
<add>// pivot_root takes a new root and an old root.
<add>// Old root must be a sub-dir of new root, it is where the current rootfs will reside after the call to pivot_root.
<add>// New root is where the new rootfs is set to.
<add>// Old root is removed after the call to pivot_root so it is no longer available under the new root.
<add>// This is similar to how libcontainer sets up a container's rootfs
<add>func chroot(path string) (err error) {
<add> // Create new mount namespace so mounts don't leak
<add> if err := syscall.Unshare(syscall.CLONE_NEWNS); err != nil {
<add> return fmt.Errorf("Error creating mount namespace before pivot: %v", err)
<add> }
<add> // path must be a different fs for pivot_root, so bind-mount to itself to ensure this
<add> if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
<add> return fmt.Errorf("Error mounting pivot dir before pivot: %v", err)
<add> }
<add>
<add> // setup oldRoot for pivot_root
<add> pivotDir, err := ioutil.TempDir(path, ".pivot_root")
<add> if err != nil {
<add> return fmt.Errorf("Error setting up pivot dir: %v", err)
<add> }
<add>
<add> var mounted bool
<add> defer func() {
<add> if mounted {
<add> // make sure pivotDir is not mounted before we try to remove it
<add> if errCleanup := syscall.Unmount(pivotDir, syscall.MNT_DETACH); errCleanup != nil {
<add> if err == nil {
<add> err = errCleanup
<add> }
<add> return
<add> }
<add> }
<add>
<add> errCleanup := os.Remove(pivotDir)
<add> if errCleanup != nil {
<add> errCleanup = fmt.Errorf("Error cleaning up after pivot: %v", errCleanup)
<add> if err == nil {
<add> err = errCleanup
<add> }
<add> }
<add> }()
<add>
<add> if err := syscall.PivotRoot(path, pivotDir); err != nil {
<add> // If pivot fails, fall back to the normal chroot
<add> return realChroot(path)
<add> }
<add> mounted = true
<add>
<add> // This is the new path for where the old root (prior to the pivot) has been moved to
<add> // This dir contains the rootfs of the caller, which we need to remove so it is not visible during extraction
<add> pivotDir = filepath.Join("/", filepath.Base(pivotDir))
<add>
<add> if err := syscall.Chdir("/"); err != nil {
<add> return fmt.Errorf("Error changing to new root: %v", err)
<add> }
<add>
<add> // Make the pivotDir (where the old root lives) private so it can be unmounted without propagating to the host
<add> if err := syscall.Mount("", pivotDir, "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
<add> return fmt.Errorf("Error making old root private after pivot: %v", err)
<add> }
<add>
<add> // Now unmount the old root so it's no longer visible from the new root
<add> if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil {
<add> return fmt.Errorf("Error while unmounting old root after pivot: %v", err)
<add> }
<add> mounted = false
<add>
<add> return nil
<add>}
<add>
<add>func realChroot(path string) error {
<add> if err := syscall.Chroot(path); err != nil {
<add> return fmt.Errorf("Error after fallback to chroot: %v", err)
<add> }
<add> if err := syscall.Chdir("/"); err != nil {
<add> return fmt.Errorf("Error chaning to new root after chroot: %v", err)
<add> }
<add> return nil
<add>}
<ide><path>pkg/chrootarchive/chroot_unix.go
<add>// +build !windows,!linux
<add>
<add>package chrootarchive
<add>
<add>import "syscall"
<add>
<add>func chroot(path string) error {
<add> if err := syscall.Chroot(path); err != nil {
<add> return err
<add> }
<add> return syscall.Chdir("/")
<add>} | 3 |
Python | Python | remove unused method | af7eeb6d260a240c3ce4c21d267aac2f1409a649 | <ide><path>glances/outputs/glances_bottle.py
<ide> def _favicon(self):
<ide> # Return the static file
<ide> return static_file('favicon.ico', root=self.STATIC_PATH)
<ide>
<del> def enable_cors(self):
<del> """Enable CORS"""
<del> response.headers['Access-Control-Allow-Origin'] = '*'
<del> response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
<del> response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
<del>
<ide> def _api_plugins(self):
<ide> """
<ide> Glances API RESTFul implementation | 1 |
Javascript | Javascript | fix semicolons and vars | fb99f542060d3959d273634c90889788861b5c05 | <ide><path>src/ng/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> ngModelCtrl = ngModelCtrl_;
<ide> nullOption = nullOption_;
<ide> unknownOption = unknownOption_;
<del> }
<add> };
<ide>
<ide>
<ide> self.addOption = function(value) {
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> $element.prepend(unknownOption);
<ide> $element.val(unknownVal);
<ide> unknownOption.prop('selected', true); // needed for IE
<del> }
<add> };
<ide>
<ide>
<ide> self.hasOption = function(value) {
<ide> return optionsMap.hasOwnProperty(value);
<del> }
<add> };
<ide>
<ide> $scope.$on('$destroy', function() {
<ide> // disable unknown option so that we don't do work when the whole select is being destroyed
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> var optionGroup,
<ide> collection = valuesFn(scope) || [],
<ide> locals = {},
<del> key, value, optionElement, index, groupIndex, length, groupLength;
<add> key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
<ide>
<ide> if (multiple) {
<ide> value = [];
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> key = optionElement.val();
<ide> if (keyName) locals[keyName] = key;
<ide> if (trackFn) {
<del> for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
<add> for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
<ide> locals[valueName] = collection[trackIndex];
<ide> if (trackFn(scope, locals) == key) break;
<ide> }
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> value = null;
<ide> } else {
<ide> if (trackFn) {
<del> for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) {
<add> for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
<ide> locals[valueName] = collection[trackIndex];
<ide> if (trackFn(scope, locals) == key) {
<ide> value = valueFn(scope, locals);
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> optionGroupNames.push(optionGroupName);
<ide> }
<ide> if (multiple) {
<del> selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined;
<add> selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) !== undefined;
<ide> } else {
<ide> if (trackFn) {
<ide> var modelCast = {};
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> }
<ide> }
<ide> }
<del> }
<add> };
<ide> }];
<ide>
<ide> var optionDirective = ['$interpolate', function($interpolate) {
<ide> var optionDirective = ['$interpolate', function($interpolate) {
<ide> });
<ide> };
<ide> }
<del> }
<add> };
<ide> }]; | 1 |
Javascript | Javascript | pass svg attributes through | 232a47ad0493fa2664f3205986dbc73ac5061bff | <ide><path>src/renderers/dom/client/__tests__/ReactDOMSVG-test.js
<ide> describe('ReactDOMSVG', function() {
<ide> ReactDOMServer = require('ReactDOMServer');
<ide> });
<ide>
<add> it('creates initial markup for known hyphenated attributes', function() {
<add> var markup = ReactDOMServer.renderToString(
<add> <svg clip-path="url(#starlet)" />
<add> );
<add> expect(markup).toContain('clip-path="url(#starlet)"');
<add> });
<add>
<add> it('creates initial markup for camel case attributes', function() {
<add> var markup = ReactDOMServer.renderToString(
<add> <svg viewBox="0 0 100 100" />
<add> );
<add> expect(markup).toContain('viewBox="0 0 100 100"');
<add> });
<add>
<add> it('deprecates camel casing of hyphenated attributes', function() {
<add> spyOn(console, 'error');
<add> var markup = ReactDOMServer.renderToString(
<add> <svg clipPath="url(#starlet)" />
<add> );
<add> expect(markup).toContain('clip-path="url(#starlet)"');
<add> expect(console.error.argsForCall.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toContain('clipPath');
<add> expect(console.error.argsForCall[0][0]).toContain('clip-path');
<add> });
<add>
<add> it('creates initial markup for unknown hyphenated attributes', function() {
<add> var markup = ReactDOMServer.renderToString(
<add> <svg the-word="the-bird" />
<add> );
<add> expect(markup).toContain('the-word="the-bird"');
<add> });
<add>
<add> it('creates initial markup for unknown camel case attributes', function() {
<add> var markup = ReactDOMServer.renderToString(
<add> <svg theWord="theBird" />
<add> );
<add> expect(markup).toContain('theWord="theBird"');
<add> });
<add>
<ide> it('creates initial namespaced markup', function() {
<ide> var markup = ReactDOMServer.renderToString(
<ide> <svg>
<ide><path>src/renderers/dom/shared/DOMPropertyOperations.js
<ide> function shouldIgnoreValue(propertyInfo, value) {
<ide> (propertyInfo.hasOverloadedBooleanValue && value === false);
<ide> }
<ide>
<add>if (__DEV__) {
<add> var reactProps = {
<add> children: true,
<add> dangerouslySetInnerHTML: true,
<add> key: true,
<add> ref: true,
<add> };
<add> var warnedSVGProperties = {};
<add>
<add> var warnDeprecatedSVGProperty = function(name, attributeName) {
<add> if (reactProps.hasOwnProperty(name) && reactProps[name] ||
<add> warnedSVGProperties.hasOwnProperty(name) && warnedSVGProperties[name]) {
<add> return;
<add> }
<add>
<add> warnedSVGProperties[name] = true;
<add> warning(
<add> false,
<add> 'SVG property %s is deprecated. Use the original attribute name ' +
<add> '%s for SVG tags instead.',
<add> name,
<add> attributeName
<add> );
<add> };
<add>}
<add>
<ide> /**
<ide> * Operations for dealing with DOM properties.
<ide> */
<ide> var DOMPropertyOperations = {
<ide> return name + '=' + quoteAttributeValueForBrowser(value);
<ide> },
<ide>
<add> /**
<add> * Creates markup for an SVG property.
<add> *
<add> * @param {string} name
<add> * @param {*} value
<add> * @return {string} Markup string, or empty string if the property was invalid.
<add> */
<add> createMarkupForSVGAttribute: function(name, value) {
<add> if (!isAttributeNameSafe(name) || value == null) {
<add> return '';
<add> }
<add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
<add> DOMProperty.properties[name] : null;
<add> if (propertyInfo) {
<add> var { attributeName, attributeNamespace } = propertyInfo;
<add> if (__DEV__) {
<add> if (!attributeNamespace && name !== attributeName) {
<add> warnDeprecatedSVGProperty(name, attributeName);
<add> }
<add> }
<add> return attributeName + '=' + quoteAttributeValueForBrowser(value);
<add> }
<add> return name + '=' + quoteAttributeValueForBrowser(value);
<add> },
<add>
<ide> /**
<ide> * Sets the value for a property on a node.
<ide> *
<ide> var DOMPropertyOperations = {
<ide> }
<ide> },
<ide>
<add> setValueForSVGAttribute: function(node, name, value) {
<add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
<add> DOMProperty.properties[name] : null;
<add> if (propertyInfo) {
<add> if (__DEV__) {
<add> var { attributeName, attributeNamespace } = propertyInfo;
<add> if (!attributeNamespace && name !== attributeName) {
<add> warnDeprecatedSVGProperty(name, attributeName);
<add> }
<add> }
<add> DOMPropertyOperations.setValueForProperty(node, name, value);
<add> } else {
<add> DOMPropertyOperations.setValueForAttribute(node, name, value);
<add> }
<add> },
<add>
<ide> /**
<ide> * Deletes the value for a property on a node.
<ide> *
<ide> var DOMPropertyOperations = {
<ide> }
<ide> },
<ide>
<add> deleteValueForSVGAttribute: function(node, name) {
<add> var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ?
<add> DOMProperty.properties[name] : null;
<add> if (propertyInfo) {
<add> DOMPropertyOperations.deleteValueForProperty(node, name);
<add> } else {
<add> node.removeAttribute(name);
<add> }
<add> },
<add>
<ide> };
<ide>
<ide> ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> ReactDOMComponent.Mixin = {
<ide> if (propKey !== CHILDREN) {
<ide> markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
<ide> }
<add> } else if (this._namespaceURI === DOMNamespaces.svg) {
<add> markup = DOMPropertyOperations.createMarkupForSVGAttribute(propKey, propValue);
<ide> } else {
<ide> markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
<ide> }
<ide> ReactDOMComponent.Mixin = {
<ide> DOMProperty.properties[propKey] ||
<ide> DOMProperty.isCustomAttribute(propKey)) {
<ide> DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey);
<add> } else if (this._namespaceURI === DOMNamespaces.svg) {
<add> DOMPropertyOperations.deleteValueForSVGAttribute(
<add> getNode(this),
<add> propKey
<add> );
<ide> }
<ide> }
<ide> for (propKey in nextProps) {
<ide> ReactDOMComponent.Mixin = {
<ide> propKey,
<ide> nextProp
<ide> );
<add> } else if (this._namespaceURI === DOMNamespaces.svg) {
<add> DOMPropertyOperations.setValueForSVGAttribute(
<add> getNode(this),
<add> propKey,
<add> nextProp
<add> );
<ide> } else if (
<ide> DOMProperty.properties[propKey] ||
<ide> DOMProperty.isCustomAttribute(propKey)) {
<ide><path>src/renderers/dom/shared/SVGDOMPropertyConfig.js
<ide> var NS = {
<ide> var SVGDOMPropertyConfig = {
<ide> Properties: {
<ide> clipPath: MUST_USE_ATTRIBUTE,
<del> cx: MUST_USE_ATTRIBUTE,
<del> cy: MUST_USE_ATTRIBUTE,
<del> d: MUST_USE_ATTRIBUTE,
<del> dx: MUST_USE_ATTRIBUTE,
<del> dy: MUST_USE_ATTRIBUTE,
<del> fill: MUST_USE_ATTRIBUTE,
<ide> fillOpacity: MUST_USE_ATTRIBUTE,
<ide> fontFamily: MUST_USE_ATTRIBUTE,
<ide> fontSize: MUST_USE_ATTRIBUTE,
<del> fx: MUST_USE_ATTRIBUTE,
<del> fy: MUST_USE_ATTRIBUTE,
<del> gradientTransform: MUST_USE_ATTRIBUTE,
<del> gradientUnits: MUST_USE_ATTRIBUTE,
<ide> markerEnd: MUST_USE_ATTRIBUTE,
<ide> markerMid: MUST_USE_ATTRIBUTE,
<ide> markerStart: MUST_USE_ATTRIBUTE,
<del> offset: MUST_USE_ATTRIBUTE,
<del> opacity: MUST_USE_ATTRIBUTE,
<del> patternContentUnits: MUST_USE_ATTRIBUTE,
<del> patternUnits: MUST_USE_ATTRIBUTE,
<del> points: MUST_USE_ATTRIBUTE,
<del> preserveAspectRatio: MUST_USE_ATTRIBUTE,
<del> r: MUST_USE_ATTRIBUTE,
<del> rx: MUST_USE_ATTRIBUTE,
<del> ry: MUST_USE_ATTRIBUTE,
<del> spreadMethod: MUST_USE_ATTRIBUTE,
<ide> stopColor: MUST_USE_ATTRIBUTE,
<ide> stopOpacity: MUST_USE_ATTRIBUTE,
<del> stroke: MUST_USE_ATTRIBUTE,
<ide> strokeDasharray: MUST_USE_ATTRIBUTE,
<ide> strokeLinecap: MUST_USE_ATTRIBUTE,
<ide> strokeOpacity: MUST_USE_ATTRIBUTE,
<ide> strokeWidth: MUST_USE_ATTRIBUTE,
<ide> textAnchor: MUST_USE_ATTRIBUTE,
<del> transform: MUST_USE_ATTRIBUTE,
<del> version: MUST_USE_ATTRIBUTE,
<del> viewBox: MUST_USE_ATTRIBUTE,
<del> x1: MUST_USE_ATTRIBUTE,
<del> x2: MUST_USE_ATTRIBUTE,
<del> x: MUST_USE_ATTRIBUTE,
<ide> xlinkActuate: MUST_USE_ATTRIBUTE,
<ide> xlinkArcrole: MUST_USE_ATTRIBUTE,
<ide> xlinkHref: MUST_USE_ATTRIBUTE,
<ide> var SVGDOMPropertyConfig = {
<ide> xmlBase: MUST_USE_ATTRIBUTE,
<ide> xmlLang: MUST_USE_ATTRIBUTE,
<ide> xmlSpace: MUST_USE_ATTRIBUTE,
<del> y1: MUST_USE_ATTRIBUTE,
<del> y2: MUST_USE_ATTRIBUTE,
<del> y: MUST_USE_ATTRIBUTE,
<ide> },
<ide> DOMAttributeNamespaces: {
<ide> xlinkActuate: NS.xlink,
<ide> var SVGDOMPropertyConfig = {
<ide> fillOpacity: 'fill-opacity',
<ide> fontFamily: 'font-family',
<ide> fontSize: 'font-size',
<del> gradientTransform: 'gradientTransform',
<del> gradientUnits: 'gradientUnits',
<ide> markerEnd: 'marker-end',
<ide> markerMid: 'marker-mid',
<ide> markerStart: 'marker-start',
<del> patternContentUnits: 'patternContentUnits',
<del> patternUnits: 'patternUnits',
<del> preserveAspectRatio: 'preserveAspectRatio',
<del> spreadMethod: 'spreadMethod',
<ide> stopColor: 'stop-color',
<ide> stopOpacity: 'stop-opacity',
<ide> strokeDasharray: 'stroke-dasharray',
<ide> strokeLinecap: 'stroke-linecap',
<ide> strokeOpacity: 'stroke-opacity',
<ide> strokeWidth: 'stroke-width',
<ide> textAnchor: 'text-anchor',
<del> viewBox: 'viewBox',
<ide> xlinkActuate: 'xlink:actuate',
<ide> xlinkArcrole: 'xlink:arcrole',
<ide> xlinkHref: 'xlink:href',
<ide><path>src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> expect(container.firstChild.hasAttribute('height')).toBe(false);
<ide> });
<ide>
<add> it('should remove known SVG camel case attributes', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<svg viewBox="0 0 100 100" />, container);
<add>
<add> expect(container.firstChild.hasAttribute('viewBox')).toBe(true);
<add> ReactDOM.render(<svg />, container);
<add> expect(container.firstChild.hasAttribute('viewBox')).toBe(false);
<add> });
<add>
<add> it('should remove known SVG hyphenated attributes', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<svg clip-path="0 0 100 100" />, container);
<add>
<add> expect(container.firstChild.hasAttribute('clip-path')).toBe(true);
<add> ReactDOM.render(<svg />, container);
<add> expect(container.firstChild.hasAttribute('clip-path')).toBe(false);
<add> });
<add>
<add> it('should remove arbitrary SVG hyphenated attributes', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<svg the-word="the-bird" />, container);
<add>
<add> expect(container.firstChild.hasAttribute('the-word')).toBe(true);
<add> ReactDOM.render(<svg />, container);
<add> expect(container.firstChild.hasAttribute('the-word')).toBe(false);
<add> });
<add>
<add> it('should remove arbitrary SVG camel case attributes', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(<svg theWord="theBird" />, container);
<add>
<add> expect(container.firstChild.hasAttribute('theWord')).toBe(true);
<add> ReactDOM.render(<svg />, container);
<add> expect(container.firstChild.hasAttribute('theWord')).toBe(false);
<add> });
<add>
<add> it('should remove SVG attributes that should have been hyphenated', function() {
<add> spyOn(console, 'error');
<add> var container = document.createElement('div');
<add> ReactDOM.render(<svg clipPath="0 0 100 100" />, container);
<add> expect(console.error.argsForCall.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toContain('clipPath');
<add> expect(console.error.argsForCall[0][0]).toContain('clip-path');
<add>
<add> expect(container.firstChild.hasAttribute('clip-path')).toBe(true);
<add> ReactDOM.render(<svg />, container);
<add> expect(container.firstChild.hasAttribute('clip-path')).toBe(false);
<add> });
<add>
<add> it('should remove namespaced SVG attributes', function() {
<add> var container = document.createElement('div');
<add> ReactDOM.render(
<add> <svg>
<add> <image xlinkHref="http://i.imgur.com/w7GCRPb.png" />
<add> </svg>,
<add> container
<add> );
<add>
<add> expect(container.firstChild.firstChild.hasAttributeNS(
<add> 'http://www.w3.org/1999/xlink',
<add> 'href'
<add> )).toBe(true);
<add> ReactDOM.render(<svg><image /></svg>, container);
<add> expect(container.firstChild.firstChild.hasAttributeNS(
<add> 'http://www.w3.org/1999/xlink',
<add> 'href'
<add> )).toBe(false);
<add> });
<add>
<ide> it('should remove properties', function() {
<ide> var container = document.createElement('div');
<ide> ReactDOM.render(<div className="monkey" />, container);
<ide> describe('ReactDOMComponent', function() {
<ide> expect(container.childNodes[0].getAttribute('myattr')).toBe('myval');
<ide> });
<ide>
<add> it('should update known hyphenated attributes for SVG tags', function() {
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = React.createElement('svg', {}, null);
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = <svg clip-path="url(#starlet)" />;
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.childNodes[0].getAttribute('clip-path')).toBe(
<add> 'url(#starlet)'
<add> );
<add> });
<add>
<add> it('should update camel case attributes for SVG tags', function() {
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = React.createElement('svg', {}, null);
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = <svg viewBox="0 0 100 100" />;
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.childNodes[0].getAttribute('viewBox')).toBe(
<add> '0 0 100 100'
<add> );
<add> });
<add>
<add> it('should warn camel casing hyphenated attributes for SVG tags', function() {
<add> spyOn(console, 'error');
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = React.createElement('svg', {}, null);
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = <svg clipPath="url(#starlet)" />;
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.childNodes[0].getAttribute('clip-path')).toBe(
<add> 'url(#starlet)'
<add> );
<add> expect(console.error.argsForCall.length).toBe(1);
<add> expect(console.error.argsForCall[0][0]).toContain('clipPath');
<add> expect(console.error.argsForCall[0][0]).toContain('clip-path');
<add> });
<add>
<add> it('should update arbitrary hyphenated attributes for SVG tags', function() {
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = React.createElement('svg', {}, null);
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = <svg the-word="the-bird" />;
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.childNodes[0].getAttribute('the-word')).toBe('the-bird');
<add> });
<add>
<add> it('should update arbitrary camel case attributes for SVG tags', function() {
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = React.createElement('svg', {}, null);
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = <svg theWord="theBird" />;
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.childNodes[0].getAttribute('theWord')).toBe('theBird');
<add> });
<add>
<add> it('should update namespaced SVG attributes', function() {
<add> var container = document.createElement('div');
<add>
<add> var beforeUpdate = (
<add> <svg>
<add> <image xlinkHref="http://i.imgur.com/w7GCRPb.png" />
<add> </svg>
<add> );
<add> ReactDOM.render(beforeUpdate, container);
<add>
<add> var afterUpdate = (
<add> <svg>
<add> <image xlinkHref="http://i.imgur.com/JvqCM2p.png" />
<add> </svg>
<add> );
<add> ReactDOM.render(afterUpdate, container);
<add>
<add> expect(container.firstChild.firstChild.getAttributeNS(
<add> 'http://www.w3.org/1999/xlink',
<add> 'href'
<add> )).toBe('http://i.imgur.com/JvqCM2p.png');
<add> });
<add>
<ide> it('should clear all the styles when removing `style`', function() {
<ide> var styles = {display: 'none', color: 'red'};
<ide> var container = document.createElement('div'); | 5 |
Python | Python | remove unused 'staticviews' | afdda88b13bb168d91cee267799a7e8d9bf26366 | <ide><path>djangorestframework/utils/staticviews.py
<del>from django.contrib.auth.views import *
<del>from django.conf import settings
<del>from django.http import HttpResponse
<del>from django.shortcuts import render_to_response
<del>from django.template import RequestContext
<del>import base64
<del>
<del>
<del># BLERGH
<del># Replicate django.contrib.auth.views.login simply so we don't have get users to update TEMPLATE_CONTEXT_PROCESSORS
<del># to add ADMIN_MEDIA_PREFIX to the RequestContext. I don't like this but really really want users to not have to
<del># be making settings changes in order to accomodate django-rest-framework
<del>@csrf_protect
<del>@never_cache
<del>def api_login(request, template_name='djangorestframework/login.html',
<del> redirect_field_name=REDIRECT_FIELD_NAME,
<del> authentication_form=AuthenticationForm):
<del> """Displays the login form and handles the login action."""
<del>
<del> redirect_to = request.REQUEST.get(redirect_field_name, '')
<del>
<del> if request.method == "POST":
<del> form = authentication_form(data=request.POST)
<del> if form.is_valid():
<del> # Light security check -- make sure redirect_to isn't garbage.
<del> if not redirect_to or ' ' in redirect_to:
<del> redirect_to = settings.LOGIN_REDIRECT_URL
<del>
<del> # Heavier security check -- redirects to http://example.com should
<del> # not be allowed, but things like /view/?param=http://example.com
<del> # should be allowed. This regex checks if there is a '//' *before* a
<del> # question mark.
<del> elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
<del> redirect_to = settings.LOGIN_REDIRECT_URL
<del>
<del> # Okay, security checks complete. Log the user in.
<del> auth_login(request, form.get_user())
<del>
<del> if request.session.test_cookie_worked():
<del> request.session.delete_test_cookie()
<del>
<del> return HttpResponseRedirect(redirect_to)
<del>
<del> else:
<del> form = authentication_form(request)
<del>
<del> request.session.set_test_cookie()
<del>
<del> #current_site = get_current_site(request)
<del>
<del> return render_to_response(template_name, {
<del> 'form': form,
<del> redirect_field_name: redirect_to,
<del> #'site': current_site,
<del> #'site_name': current_site.name,
<del> }, context_instance=RequestContext(request))
<del>
<del>
<del>def api_logout(request, next_page=None, template_name='djangorestframework/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
<del> return logout(request, next_page, template_name, redirect_field_name) | 1 |
PHP | PHP | get theme from viewbuilder if available | 1678abe95ed42e298b24074dd68dffa0165583d2 | <ide><path>src/View/CellTrait.php
<ide> protected function _createCell($className, $action, $plugin, $options)
<ide> return $instance;
<ide> }
<ide>
<add> if (method_exists($this, 'viewBuilder')) {
<add> $builder->theme($this->viewBuilder()->theme());
<add> }
<add>
<ide> if (isset($this->viewClass)) {
<ide> $builder->className($this->viewClass);
<ide> $instance->viewClass = $this->viewClass; | 1 |
PHP | PHP | remove unneeded property | 9f80a2adde929b653a2bf9430e9d3b696b3f2629 | <ide><path>src/Illuminate/Notifications/Events/BroadcastNotificationCreated.php
<ide> class BroadcastNotificationCreated implements ShouldBroadcast
<ide> */
<ide> public $notification;
<ide>
<del> /**
<del> * The queue connection.
<del> *
<del> * @var string
<del> */
<del> public $connection;
<del>
<ide> /**
<ide> * The notification data.
<ide> * | 1 |
Ruby | Ruby | add method tests | c8016f6c0af91ed5a105ea82911259a7bff03666 | <ide><path>Library/Homebrew/test/cli/named_args_spec.rb
<add># frozen_string_literal: true
<add>
<add>require "cli/named_args"
<add>
<add>describe Homebrew::CLI::NamedArgs do
<add> let(:foo) do
<add> formula "foo" do
<add> url "https://brew.sh"
<add> version "1.0"
<add> end
<add> end
<add>
<add> let(:foo_keg) do
<add> path = (HOMEBREW_CELLAR/"foo/1.0").resolved_path
<add> mkdir_p path
<add> Keg.new(path)
<add> end
<add>
<add> let(:bar) do
<add> formula "bar" do
<add> url "https://brew.sh"
<add> version "1.0"
<add> end
<add> end
<add>
<add> let(:bar_keg) do
<add> path = (HOMEBREW_CELLAR/"bar/1.0").resolved_path
<add> mkdir_p path
<add> Keg.new(path)
<add> end
<add>
<add> let(:baz) do
<add> Cask::CaskLoader.load(+<<~RUBY)
<add> cask "baz" do
<add> version "1.0"
<add> end
<add> RUBY
<add> end
<add>
<add> describe "#to_formulae" do
<add> it "returns formulae" do
<add> allow(Formulary).to receive(:loader_for).and_call_original
<add> stub_formula_loader foo
<add> stub_formula_loader bar
<add>
<add> expect(described_class.new("foo", "bar").to_formulae).to eq [foo, bar]
<add> end
<add> end
<add>
<add> describe "#to_formulae_and_casks" do
<add> it "returns formulae and casks" do
<add> allow(Formulary).to receive(:loader_for).and_call_original
<add> stub_formula_loader foo
<add> stub_cask_loader baz
<add>
<add> expect(described_class.new("foo", "baz").to_formulae_and_casks).to eq [foo, baz]
<add> end
<add> end
<add>
<add> describe "#to_resolved_formulae" do
<add> it "returns resolved formulae" do
<add> allow(Formulary).to receive(:resolve).and_return(foo, bar)
<add>
<add> expect(described_class.new("foo", "bar").to_resolved_formulae).to eq [foo, bar]
<add> end
<add> end
<add>
<add> describe "#to_resolved_formulae_to_casks" do
<add> it "returns resolved formulae, as well as casks" do
<add> allow(Formulary).to receive(:resolve).and_call_original
<add> allow(Formulary).to receive(:resolve).with("foo", any_args).and_return foo
<add> stub_cask_loader baz
<add>
<add> resolved_formulae, casks = described_class.new("foo", "baz").to_resolved_formulae_to_casks
<add>
<add> expect(resolved_formulae).to eq [foo]
<add> expect(casks).to eq [baz]
<add> end
<add> end
<add>
<add> describe "#to_casks" do
<add> it "returns casks" do
<add> stub_cask_loader baz
<add>
<add> expect(described_class.new("baz").to_casks).to eq [baz]
<add> end
<add> end
<add>
<add> describe "#to_kegs" do
<add> it "returns kegs" do
<add> named_args = described_class.new("foo", "bar")
<add> allow(named_args).to receive(:resolve_keg).with("foo").and_return foo_keg
<add> allow(named_args).to receive(:resolve_keg).with("bar").and_return bar_keg
<add>
<add> expect(named_args.to_kegs).to eq [foo_keg, bar_keg]
<add> end
<add> end
<add>
<add> describe "#to_kegs_to_casks" do
<add> it "returns kegs, as well as casks" do
<add> named_args = described_class.new("foo", "baz")
<add> allow(named_args).to receive(:resolve_keg).and_call_original
<add> allow(named_args).to receive(:resolve_keg).with("foo").and_return foo_keg
<add> stub_cask_loader baz
<add>
<add> kegs, casks = named_args.to_kegs_to_casks
<add>
<add> expect(kegs).to eq [foo_keg]
<add> expect(casks).to eq [baz]
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/spec_helper.rb
<ide> require_relative "../global"
<ide>
<ide> require "test/support/no_seed_progress_formatter"
<add>require "test/support/helper/cask"
<ide> require "test/support/helper/fixtures"
<ide> require "test/support/helper/formula"
<ide> require "test/support/helper/mktmpdir"
<ide>
<ide> config.include(RuboCop::RSpec::ExpectOffense)
<ide>
<add> config.include(Test::Helper::Cask)
<ide> config.include(Test::Helper::Fixtures)
<ide> config.include(Test::Helper::Formula)
<ide> config.include(Test::Helper::MkTmpDir)
<ide><path>Library/Homebrew/test/support/helper/cask.rb
<add># frozen_string_literal: true
<add>
<add>require "cask/cask_loader"
<add>
<add>module Test
<add> module Helper
<add> module Cask
<add> def stub_cask_loader(cask, ref = cask.token)
<add> loader = ::Cask::CaskLoader::FromInstanceLoader.new cask
<add> allow(::Cask::CaskLoader).to receive(:for).with(ref).and_return(loader)
<add> end
<add> end
<add> end
<add>end | 3 |
Javascript | Javascript | allow mutiple donations with warning | bcf99422638d486b3b9d4a3344abb7a62ebebc92 | <ide><path>client/src/pages/donate.js
<ide> import PropTypes from 'prop-types';
<ide> import { bindActionCreators } from 'redux';
<ide> import { connect } from 'react-redux';
<ide> import { createSelector } from 'reselect';
<del>import { Grid, Row, Col } from '@freecodecamp/react-bootstrap';
<add>import { Grid, Row, Col, Alert } from '@freecodecamp/react-bootstrap';
<ide>
<ide> import { stripePublicKey } from '../../config/env.json';
<ide> import { Spacer, Loader } from '../components/helpers';
<ide> export class DonatePage extends Component {
<ide> </Col>
<ide> </Row>
<ide> <Row>
<del> {isDonating ? (
<del> <Col md={6} mdOffset={3}>
<add> <Fragment>
<add> <Col md={6}>
<add> <Row>
<add> <Col sm={10} smOffset={1} xs={12}>
<add> {isDonating ? (
<add> <Alert>
<add> <p>
<add> Thank you for being a supporter of freeCodeCamp. You
<add> currently have a recurring donation.
<add> </p>
<add> <br />
<add> <p>
<add> If you would like to make additional donations, those
<add> will help our nonprofit and our mission, too.
<add> </p>
<add> </Alert>
<add> ) : null}
<add> </Col>
<add> </Row>
<add> <DonateForm
<add> enableDonationSettingsPage={this.enableDonationSettingsPage}
<add> handleProcessing={this.handleProcessing}
<add> stripe={stripe}
<add> />
<add> </Col>
<add> <Col md={6}>
<ide> <DonateText />
<ide> </Col>
<del> ) : (
<del> <Fragment>
<del> <Col md={6}>
<del> <DonateForm
<del> enableDonationSettingsPage={this.enableDonationSettingsPage}
<del> handleProcessing={this.handleProcessing}
<del> stripe={stripe}
<del> />
<del> </Col>
<del> <Col md={6}>
<del> <DonateText />
<del> </Col>
<del> </Fragment>
<del> )}
<add> </Fragment>
<ide> </Row>
<ide> <Spacer />
<ide> </Grid> | 1 |
PHP | PHP | handle negative numbers in redis correctly | 056e99e1718a3fbd1401f3135e2439b66706267a | <ide><path>src/Cache/Engine/RedisEngine.php
<ide> public function read($key)
<ide> $key = $this->_key($key);
<ide>
<ide> $value = $this->_Redis->get($key);
<del> if (ctype_digit($value)) {
<del> $value = (int)$value;
<add> if (preg_match('/^[-]?\d+$/', $value)) {
<add> return (int)$value;
<ide> }
<ide> if ($value !== false && is_string($value)) {
<del> $value = unserialize($value);
<add> return unserialize($value);
<ide> }
<ide> return $value;
<ide> }
<ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php
<ide> public function testMultiDatabaseOperations()
<ide> Cache::drop('redisdb1');
<ide> }
<ide>
<add> /**
<add> * test write numbers method
<add> *
<add> * @return void
<add> */
<add> public function testWriteNumbers()
<add> {
<add> $result = Cache::write('test-counter', 1, 'redis');
<add> $this->assertSame(1, Cache::read('test-counter', 'redis'));
<add>
<add> $result = Cache::write('test-counter', 0, 'redis');
<add> $this->assertSame(0, Cache::read('test-counter', 'redis'));
<add>
<add> $result = Cache::write('test-counter', -1, 'redis');
<add> $this->assertSame(-1, Cache::read('test-counter', 'redis'));
<add> }
<add>
<ide> /**
<ide> * testReadAndWriteCache method
<ide> * | 2 |
Ruby | Ruby | remove more mutations from the `build` method | 8ea64bd0fce854a4bb85bf67c983d30358c8cd39 | <ide><path>activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb
<ide> def valid_options
<ide> super + [:join_table, :association_foreign_key]
<ide> end
<ide>
<del> def build
<del> reflection = super
<del> define_destroy_hook
<del> reflection
<del> end
<del>
<del> def define_destroy_hook
<add> def define_callbacks(model, reflection)
<add> super
<ide> name = self.name
<ide> model.send(:include, Module.new {
<ide> class_eval <<-RUBY, __FILE__, __LINE__ + 1 | 1 |
Java | Java | fix regression with binding and validation | 6fb31903536c0a41dd4fbe153c81494ccfd4d405 | <ide><path>spring-beans/src/main/java/org/springframework/beans/AbstractPropertyAccessor.java
<ide> import java.lang.reflect.Array;
<ide> import java.lang.reflect.InvocationTargetException;
<ide> import java.lang.reflect.UndeclaredThrowableException;
<add>import java.security.PrivilegedActionException;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> else if (propValue instanceof Map) {
<ide> }
<ide> else {
<ide> if (isExtractOldValueForEditor() && ph.isReadable()) {
<del> oldValue = ph.getValue();
<add> try {
<add> oldValue = ph.getValue();
<add> }
<add> catch (Exception ex) {
<add> if (ex instanceof PrivilegedActionException) {
<add> ex = ((PrivilegedActionException) ex).getException();
<add> }
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Could not read previous value of property '" +
<add> this.nestedPath + propertyName + "'", ex);
<add> }
<add> }
<ide> }
<ide> valueToApply = convertForProperty(
<ide> propertyName, oldValue, originalValue, ph.toTypeDescriptor());
<ide><path>spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java
<ide> public void setterDoestNotCallGetter() {
<ide> assertTrue("Set name to tom", target.getName().equals("tom"));
<ide> }
<ide>
<add> @Test
<add> public void getterSilentlyFailWithOldValueExtraction() {
<add> GetterBean target = new GetterBean();
<add> BeanWrapper accessor = createAccessor(target);
<add> accessor.setExtractOldValueForEditor(true); // This will call the getter
<add> accessor.setPropertyValue("name", "tom");
<add> assertTrue("Set name to tom", target.getName().equals("tom"));
<add> }
<add>
<ide> @Test
<ide> public void setValidAndInvalidPropertyValuesShouldContainExceptionDetails() {
<ide> TestBean target = new TestBean(); | 2 |
Text | Text | fix broken internal link in process.md | 828f0c838e81096b9debd6e7f55e54b556eb7ef8 | <ide><path>doc/api/process.md
<ide> cases:
<ide> [Readable]: stream.html
<ide> [Child Process]: child_process.html
<ide> [Cluster]: cluster.html
<del>[`process.exitCode`]: #processexitcode-1
<add>[`process.exitCode`]: #process_process_exitcode
<ide> [LTS]: https://github.com/nodejs/LTS/ | 1 |
Javascript | Javascript | build chunks on seal (fixes prefetching bug) | 0870e00113e228275db72536d88e462078d8351f | <ide><path>lib/Compilation.js
<ide> function Compilation(compiler) {
<ide> this.bail = options && options.bail;
<ide> this.profile = options && options.profile;
<ide> this.entries = [];
<add> this.preparedChunks = [];
<ide> this.chunks = [];
<ide> this.namedChunks = {};
<ide> this.modules = [];
<ide> Compilation.prototype.addEntry = function process(context, entry, name, callback
<ide> if(err) return callback(err);
<ide>
<ide> if(module) {
<del> var chunk = this.addChunk(name);
<del> chunk.id = 0;
<del> chunk.entry = true;
<del> chunk.addModule(module);
<del> module.addChunk(chunk);
<del> this.processDependenciesBlockForChunk(module, chunk);
<add> this.preparedChunks.push({
<add> name: name,
<add> module: module
<add> });
<ide> }
<ide> return callback();
<ide> }.bind(this));
<ide> };
<ide>
<del>
<ide> Compilation.prototype.prefetch = function process(context, dependency, callback) {
<ide> this._addModuleChain(context, dependency, function(module) {
<ide>
<ide> Compilation.prototype.prefetch = function process(context, dependency, callback)
<ide>
<ide> Compilation.prototype.seal = function seal(callback) {
<ide> this.applyPlugins("seal");
<add> this.preparedChunks.forEach(function(preparedChunk) {
<add> var module = preparedChunk.module;
<add> var chunk = this.addChunk(preparedChunk.name);
<add> chunk.id = 0;
<add> chunk.entry = true;
<add> chunk.addModule(module);
<add> module.addChunk(chunk);
<add> this.processDependenciesBlockForChunk(module, chunk);
<add> }, this);
<ide> this.applyPlugins("optimize");
<ide> this.applyPlugins("optimize-modules", this.modules);
<ide> this.applyPlugins("after-optimize-modules", this.modules); | 1 |
Javascript | Javascript | move function def out of loop | c785918cbd245cc8ecf9a38e373b121c4e68a55b | <ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> childTranscludeFn = nodeLinkFn.transclude;
<ide> if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
<ide> nodeLinkFn(childLinkFn, childScope, node, $rootElement,
<del> (function(transcludeFn) {
<del> return function(cloneFn) {
<del> var transcludeScope = scope.$new();
<del> transcludeScope.$$transcluded = true;
<del>
<del> return transcludeFn(transcludeScope, cloneFn).
<del> on('$destroy', bind(transcludeScope, transcludeScope.$destroy));
<del> };
<del> })(childTranscludeFn || transcludeFn)
<add> createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
<ide> );
<ide> } else {
<ide> nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
<ide> function $CompileProvider($provide) {
<ide> }
<ide> }
<ide>
<add> function createBoundTranscludeFn(scope, transcludeFn) {
<add> return function boundTranscludeFn(cloneFn) {
<add> var transcludedScope = scope.$new(),
<add> clone;
<add> transcludedScope.$$transcluded = true;
<add> clone = transcludeFn(transcludedScope, cloneFn);
<add> clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
<add> return clone;
<add> };
<add> }
<ide>
<ide> /**
<ide> * Looks for directives on the given node and adds them to the directive collection which is | 1 |
Java | Java | remove validation of ordering | 1d0d90c0e595490b0944a7eaf11e6e317c998267 | <ide><path>rxjava-core/src/test/java/rx/schedulers/AbstractSchedulerTests.java
<ide> public String call(String s) {
<ide> List<String> strings = m.toList().toBlockingObservable().last();
<ide>
<ide> assertEquals(4, strings.size());
<del> assertEquals("names=>a-1", strings.get(0));
<del> assertEquals("names=>b-1", strings.get(1));
<del> assertEquals("names=>a-2", strings.get(2));
<del> assertEquals("names=>b-2", strings.get(3));
<add> // because flatMap does a merge there is no guarantee of order
<add> assertTrue(strings.contains("names=>a-1"));
<add> assertTrue(strings.contains("names=>a-2"));
<add> assertTrue(strings.contains("names=>b-1"));
<add> assertTrue(strings.contains("names=>b-2"));
<ide> }
<ide>
<ide> @SuppressWarnings("rawtypes") | 1 |
Mixed | Python | fix charset issues | f19e0d544fdcd318c2bde2057d91777beda78915 | <ide><path>docs/api-guide/renderers.md
<ide> If your API includes views that can serve both regular webpages and API response
<ide>
<ide> ## JSONRenderer
<ide>
<del>Renders the request data into `JSON` enforcing ASCII encoding
<add>Renders the request data into `JSON`, using ASCII encoding.
<ide>
<ide> The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
<ide>
<ide> **.media_type**: `application/json`
<ide>
<ide> **.format**: `'.json'`
<ide>
<add>**.charset**: `iso-8859-1`
<add>
<ide> ## UnicodeJSONRenderer
<ide>
<del>Same as `JSONRenderer` but doesn't enforce ASCII encoding
<add>Renders the request data into `JSON`, using utf-8 encoding.
<add>
<add>The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
<add>
<add>**.media_type**: `application/json`
<add>
<add>**.format**: `'.json'`
<add>
<add>**.charset**: `utf-8`
<ide>
<ide> ## JSONPRenderer
<ide>
<ide> The javascript callback function must be set by the client including a `callback
<ide>
<ide> **.format**: `'.jsonp'`
<ide>
<add>**.charset**: `iso-8859-1`
<add>
<ide> ## YAMLRenderer
<ide>
<ide> Renders the request data into `YAML`.
<ide> Requires the `pyyaml` package to be installed.
<ide>
<ide> **.format**: `'.yaml'`
<ide>
<add>**.charset**: `utf-8`
<add>
<ide> ## XMLRenderer
<ide>
<ide> Renders REST framework's default style of `XML` response content.
<ide> If you are considering using `XML` for your API, you may want to consider implem
<ide>
<ide> **.format**: `'.xml'`
<ide>
<add>**.charset**: `utf-8`
<add>
<ide> ## TemplateHTMLRenderer
<ide>
<ide> Renders data to HTML, using Django's standard template rendering.
<ide> If you're building websites that use `TemplateHTMLRenderer` along with other ren
<ide>
<ide> **.format**: `'.html'`
<ide>
<add>**.charset**: `utf-8`
<add>
<ide> See also: `StaticHTMLRenderer`
<ide>
<ide> ## StaticHTMLRenderer
<ide> You can use `TemplateHTMLRenderer` either to return regular HTML pages using RES
<ide>
<ide> **.format**: `'.html'`
<ide>
<add>**.charset**: `utf-8`
<add>
<ide> See also: `TemplateHTMLRenderer`
<ide>
<ide> ## BrowsableAPIRenderer
<ide> Renders data into HTML for the Browsable API. This renderer will determine whic
<ide>
<ide> **.format**: `'.api'`
<ide>
<add>**.charset**: `utf-8`
<add>
<ide> ---
<ide>
<ide> # Custom renderers
<ide>
<ide> To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
<ide>
<add>The method should return a bytestring, which wil be used as the body of the HTTP response.
<add>
<ide> The arguments passed to the `.render()` method are:
<ide>
<ide> ### `data`
<ide> The following is an example plaintext renderer that will return a response with
<ide> from rest_framework import renderers
<ide>
<ide>
<del> class PlainText(renderers.BaseRenderer):
<add> class PlainTextRenderer(renderers.BaseRenderer):
<ide> media_type = 'text/plain'
<ide> format = 'txt'
<ide>
<ide> def render(self, data, media_type=None, renderer_context=None):
<del> if isinstance(data, basestring):
<del> return data
<del> return smart_unicode(data)
<add> return data.encode(self.charset)
<add>
<add>## Setting the character set
<add>
<add>By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer.
<add>
<add> class PlainTextRenderer(renderers.BaseRenderer):
<add> media_type = 'text/plain'
<add> format = 'txt'
<add> charset = 'iso-8859-1'
<add>
<add> def render(self, data, media_type=None, renderer_context=None):
<add> return data.encode(self.charset)
<add>
<add>If the renderer returns a raw bytestring, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string.
<add>
<add> class JPEGRenderer(renderers.BaseRenderer):
<add> media_type = 'image/jpeg'
<add> format = 'jpg'
<add> charset = None
<add>
<add> def render(self, data, media_type=None, renderer_context=None):
<add> return data
<ide>
<ide> ---
<ide>
<ide> Templates will render with a `RequestContext` which includes the `status_code` a
<ide>
<ide> The following third party packages are also available.
<ide>
<del>## MessagePack
<add>### MessagePack
<ide>
<ide> [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
<ide>
<del>## CSV
<add>### CSV
<ide>
<ide> Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
<ide>
<ide><path>rest_framework/renderers.py
<ide> from __future__ import unicode_literals
<ide>
<ide> import copy
<del>import string
<ide> import json
<ide> from django import forms
<ide> from django.http.multipartparser import parse_header
<ide> class BaseRenderer(object):
<ide>
<ide> media_type = None
<ide> format = None
<del> charset = None
<add> charset = 'utf-8'
<ide>
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> raise NotImplemented('Renderer class requires .render() to be implemented')
<ide> class JSONRenderer(BaseRenderer):
<ide> format = 'json'
<ide> encoder_class = encoders.JSONEncoder
<ide> ensure_ascii = True
<add> charset = 'iso-8859-1'
<ide>
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> """
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> except (ValueError, TypeError):
<ide> indent = None
<ide>
<del> return json.dumps(data, cls=self.encoder_class, indent=indent, ensure_ascii=self.ensure_ascii)
<add> ret = json.dumps(data, cls=self.encoder_class,
<add> indent=indent, ensure_ascii=self.ensure_ascii)
<add>
<add> if not self.ensure_ascii:
<add> return bytes(ret.encode(self.charset))
<add> return ret
<ide>
<ide>
<ide> class UnicodeJSONRenderer(JSONRenderer):
<ide> def get_content(self, renderer, data,
<ide> renderer_context['indent'] = 4
<ide> content = renderer.render(data, accepted_media_type, renderer_context)
<ide>
<del> if not all(char in string.printable for char in content):
<add> if renderer.charset is None:
<ide> return '[%d bytes of binary content]' % len(content)
<ide>
<ide> return content
<ide><path>rest_framework/response.py
<ide> def rendered_content(self):
<ide> else:
<ide> content_type = media_type
<ide> self['Content-Type'] = content_type
<del> return renderer.render(self.data, media_type, context)
<add>
<add> ret = renderer.render(self.data, media_type, context)
<add> if isinstance(ret, six.text_type):
<add> return bytes(ret.encode(self.charset))
<add> return ret
<ide>
<ide> @property
<ide> def status_text(self):
<ide><path>rest_framework/tests/renderers.py
<ide> # -*- coding: utf-8 -*-
<add>from __future__ import unicode_literals
<add>
<ide> from decimal import Decimal
<ide> from django.core.cache import cache
<ide> from django.test import TestCase
<ide> class RendererEndToEndTests(TestCase):
<ide> def test_default_renderer_serializes_content(self):
<ide> """If the Accept header is not set the default renderer should serialize the response."""
<ide> resp = self.client.get('/')
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_head_method_serializes_no_content(self):
<ide> """No response must be included in HEAD requests."""
<ide> resp = self.client.head('/')
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, six.b(''))
<ide>
<ide> def test_default_renderer_serializes_content_on_accept_any(self):
<ide> """If the Accept header is set to */* the default renderer should serialize the response."""
<ide> resp = self.client.get('/', HTTP_ACCEPT='*/*')
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_default_case(self):
<ide> """If the Accept header is set the specified renderer should serialize the response.
<ide> (In this case we check that works for the default renderer)"""
<ide> resp = self.client.get('/', HTTP_ACCEPT=RendererA.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_non_default_case(self):
<ide> """If the Accept header is set the specified renderer should serialize the response.
<ide> (In this case we check that works for a non-default renderer)"""
<ide> resp = self.client.get('/', HTTP_ACCEPT=RendererB.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_accept_query(self):
<ide> RendererB.media_type
<ide> )
<ide> resp = self.client.get('/' + param)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_format_query(self):
<ide> RendererB.format
<ide> )
<ide> resp = self.client.get('/' + param)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_format_kwargs(self):
<ide> """If a 'format' keyword arg is specified, the renderer with the matching
<ide> format attribute should serialize the response."""
<ide> resp = self.client.get('/something.formatb')
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_is_used_on_format_query_with_matching_accept(self):
<ide> )
<ide> resp = self.client.get('/' + param,
<ide> HTTP_ACCEPT=RendererB.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_proper_encoding(self):
<ide> obj = {'countries': ['United Kingdom', 'France', 'España']}
<ide> renderer = UnicodeJSONRenderer()
<ide> content = renderer.render(obj, 'application/json')
<del> self.assertEqual(content, '{"countries": ["United Kingdom", "France", "España"]}')
<add> self.assertEqual(content, '{"countries": ["United Kingdom", "France", "España"]}'.encode('utf-8'))
<ide>
<ide>
<ide> class JSONPRendererTests(TestCase):
<ide> def test_without_callback_with_json_renderer(self):
<ide> resp = self.client.get('/jsonp/jsonrenderer',
<ide> HTTP_ACCEPT='application/javascript')
<ide> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript')
<add> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=iso-8859-1')
<ide> self.assertEqual(resp.content,
<ide> ('callback(%s);' % _flat_repr).encode('ascii'))
<ide>
<ide> def test_without_callback_without_json_renderer(self):
<ide> resp = self.client.get('/jsonp/nojsonrenderer',
<ide> HTTP_ACCEPT='application/javascript')
<ide> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript')
<add> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=iso-8859-1')
<ide> self.assertEqual(resp.content,
<ide> ('callback(%s);' % _flat_repr).encode('ascii'))
<ide>
<ide> def test_with_callback(self):
<ide> resp = self.client.get('/jsonp/nojsonrenderer?callback=' + callback_func,
<ide> HTTP_ACCEPT='application/javascript')
<ide> self.assertEqual(resp.status_code, status.HTTP_200_OK)
<del> self.assertEqual(resp['Content-Type'], 'application/javascript')
<add> self.assertEqual(resp['Content-Type'], 'application/javascript; charset=iso-8859-1')
<ide> self.assertEqual(resp.content,
<ide> ('%s(%s);' % (callback_func, _flat_repr)).encode('ascii'))
<ide>
<ide><path>rest_framework/tests/response.py
<ide> class RendererIntegrationTests(TestCase):
<ide> def test_default_renderer_serializes_content(self):
<ide> """If the Accept header is not set the default renderer should serialize the response."""
<ide> resp = self.client.get('/')
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_head_method_serializes_no_content(self):
<ide> """No response must be included in HEAD requests."""
<ide> resp = self.client.head('/')
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, six.b(''))
<ide>
<ide> def test_default_renderer_serializes_content_on_accept_any(self):
<ide> """If the Accept header is set to */* the default renderer should serialize the response."""
<ide> resp = self.client.get('/', HTTP_ACCEPT='*/*')
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_default_case(self):
<ide> """If the Accept header is set the specified renderer should serialize the response.
<ide> (In this case we check that works for the default renderer)"""
<ide> resp = self.client.get('/', HTTP_ACCEPT=RendererA.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererA.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererA.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_non_default_case(self):
<ide> """If the Accept header is set the specified renderer should serialize the response.
<ide> (In this case we check that works for a non-default renderer)"""
<ide> resp = self.client.get('/', HTTP_ACCEPT=RendererB.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_accept_query(self):
<ide> RendererB.media_type
<ide> )
<ide> resp = self.client.get('/' + param)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_format_query(self):
<ide> """If a 'format' query is specified, the renderer with the matching
<ide> format attribute should serialize the response."""
<ide> resp = self.client.get('/?format=%s' % RendererB.format)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_serializes_content_on_format_kwargs(self):
<ide> """If a 'format' keyword arg is specified, the renderer with the matching
<ide> format attribute should serialize the response."""
<ide> resp = self.client.get('/something.formatb')
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_specified_renderer_is_used_on_format_query_with_matching_accept(self):
<ide> the renderer with the matching format attribute should serialize the response."""
<ide> resp = self.client.get('/?format=%s' % RendererB.format,
<ide> HTTP_ACCEPT=RendererB.media_type)
<del> self.assertEqual(resp['Content-Type'], RendererB.media_type)
<add> self.assertEqual(resp['Content-Type'], RendererB.media_type + '; charset=utf-8')
<ide> self.assertEqual(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT))
<ide> self.assertEqual(resp.status_code, DUMMYSTATUS)
<ide>
<ide> def test_does_not_append_charset_by_default(self):
<ide> """
<ide> headers = {"HTTP_ACCEPT": RendererA.media_type}
<ide> resp = self.client.get('/', **headers)
<del> self.assertEqual(RendererA.media_type, resp['Content-Type'])
<add> expected = "{0}; charset={1}".format(RendererA.media_type, 'utf-8')
<add> self.assertEqual(expected, resp['Content-Type'])
<ide>
<ide> def test_if_there_is_charset_specified_on_renderer_it_gets_appended(self):
<ide> """ | 5 |
Python | Python | solve some encoding issue | b016d508f014721823d836486a419482c47e3fd4 | <ide><path>glances/folder_list.py
<ide>
<ide> import os
<ide>
<del>from glances.compat import range
<add>from glances.compat import range, nativestr
<ide> from glances.logger import logger
<ide>
<ide> # Use the built-in version of scandir/walk if possible, otherwise
<ide> def __set_folder_list(self, section):
<ide> value['path'] = self.config.get_value(section, key + 'path')
<ide> if value['path'] is None:
<ide> continue
<add> else:
<add> value['path'] = nativestr(value['path'])
<ide>
<ide> # Optional conf keys
<ide> for i in ['careful', 'warning', 'critical']:
<ide><path>glances/plugins/glances_docker.py
<ide> import threading
<ide> import time
<ide>
<del>from glances.compat import iterkeys, itervalues
<add>from glances.compat import iterkeys, itervalues, nativestr
<ide> from glances.logger import logger
<ide> from glances.timer import getTimeSinceLastUpdate
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide> def update(self):
<ide> # The key is the container name and not the Id
<ide> container_stats['key'] = self.get_key()
<ide> # Export name (first name in the Names list, without the /)
<del> container_stats['name'] = container.name
<add> container_stats['name'] = nativestr(container.name)
<ide> # Export global Names (used by the WebUI)
<del> container_stats['Names'] = [container.name]
<add> container_stats['Names'] = [ nativestr(container.name)]
<ide> # Container Id
<ide> container_stats['Id'] = container.id
<ide> # Container Image | 2 |
Python | Python | fix wrong tokenizer checkpoint name in flax marian | 6df29ba5e6d98d4cb661d00b569fd6f61e7286b0 | <ide><path>src/transformers/models/marian/modeling_flax_marian.py
<ide> def encode(
<ide> ```python
<ide> >>> from transformers import MarianTokenizer, FlaxMarianMTModel
<ide>
<del> >>> tokenizer = MarianTokenizer.from_pretrained("facebook/marian-large-cnn")
<add> >>> tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
<ide> >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
<ide>
<ide> >>> text = "My friends are cool but they eat too many carbs."
<ide> def decode(
<ide> >>> import jax.numpy as jnp
<ide> >>> from transformers import MarianTokenizer, FlaxMarianMTModel
<ide>
<del> >>> tokenizer = MarianTokenizer.from_pretrained("facebook/marian-large-cnn")
<add> >>> tokenizer = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
<ide> >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
<ide>
<ide> >>> text = "My friends are cool but they eat too many carbs." | 1 |
Ruby | Ruby | use the cached arel table | f6e7e11ad28555860bb8a1bb362fa091f48cc81a | <ide><path>activerecord/lib/active_record/associations/join_dependency/join_base.rb
<ide> def aliased_prefix
<ide> end
<ide>
<ide> def table
<del> Arel::Table.new(table_name, arel_engine)
<add> base_klass.arel_table
<ide> end
<ide>
<ide> def aliased_table_name
<ide><path>activerecord/lib/active_record/associations/join_dependency/join_part.rb
<ide> class JoinPart # :nodoc:
<ide> # association.
<ide> attr_reader :base_klass, :children
<ide>
<del> delegate :table_name, :column_names, :primary_key, :arel_engine, :to => :base_klass
<add> delegate :table_name, :column_names, :primary_key, :to => :base_klass
<ide>
<ide> def initialize(base_klass, parent)
<ide> @base_klass = base_klass | 2 |
Javascript | Javascript | ignore children with clashing keys | 216fcdeb42cd4d783a89f618ed989010c10506fc | <ide><path>src/utils/ReactChildren.js
<ide>
<ide> var PooledClass = require('PooledClass');
<ide>
<del>var invariant = require('invariant');
<ide> var traverseAllChildren = require('traverseAllChildren');
<add>var warning = require('warning');
<ide>
<ide> var twoArgumentPooler = PooledClass.twoArgumentPooler;
<ide> var threeArgumentPooler = PooledClass.threeArgumentPooler;
<ide> PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
<ide> function mapSingleChildIntoContext(traverseContext, child, name, i) {
<ide> var mapBookKeeping = traverseContext;
<ide> var mapResult = mapBookKeeping.mapResult;
<del> var mappedChild =
<del> mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
<del> // We found a component instance
<del> invariant(
<del> !mapResult.hasOwnProperty(name),
<add>
<add> var keyUnique = !mapResult.hasOwnProperty(name);
<add> warning(
<add> keyUnique,
<ide> 'ReactChildren.map(...): Encountered two children with the same key, ' +
<del> '`%s`. Children keys must be unique.',
<add> '`%s`. Child keys must be unique; when two children share a key, only ' +
<add> 'the first child will be used.',
<ide> name
<ide> );
<del> mapResult[name] = mappedChild;
<add>
<add> if (keyUnique) {
<add> var mappedChild =
<add> mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
<add> mapResult[name] = mappedChild;
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>src/utils/__tests__/ReactChildren-test.js
<ide> describe('ReactChildren', function() {
<ide> }).not.toThrow();
<ide> });
<ide>
<del> it('should throw if key provided is a dupe with explicit key', function() {
<add> it('should warn if key provided is a dupe with explicit key', function() {
<ide> var zero = <div key="something"/>;
<del> var one = <div key="something" />;
<add> var one = <span key="something" />;
<ide>
<del> var mapFn = function() {return null;};
<add> var mapFn = function(component) { return component; };
<ide> var instance = (
<ide> <div>{zero}{one}</div>
<ide> );
<ide>
<del> expect(function() {
<del> ReactChildren.map(instance.props.children, mapFn);
<del> }).toThrow();
<add> spyOn(console, 'warn');
<add> var mapped = ReactChildren.map(instance.props.children, mapFn);
<add>
<add> expect(console.warn.calls.length).toEqual(1);
<add> expect(mapped).toEqual({'.$something': zero});
<ide> });
<ide> });
<ide><path>src/utils/flattenChildren.js
<ide>
<ide> "use strict";
<ide>
<del>var invariant = require('invariant');
<ide> var traverseAllChildren = require('traverseAllChildren');
<add>var warning = require('warning');
<ide>
<ide> /**
<ide> * @param {function} traverseContext Context passed through traversal.
<ide> var traverseAllChildren = require('traverseAllChildren');
<ide> function flattenSingleChildIntoContext(traverseContext, child, name) {
<ide> // We found a component instance.
<ide> var result = traverseContext;
<del> invariant(
<del> !result.hasOwnProperty(name),
<del> 'flattenChildren(...): Encountered two children with the same key, `%s`. ' +
<del> 'Children keys must be unique.',
<add> var keyUnique = !result.hasOwnProperty(name);
<add> warning(
<add> keyUnique,
<add> 'flattenChildren(...): Encountered two children with the same key, ' +
<add> '`%s`. Child keys must be unique; when two children share a key, only ' +
<add> 'the first child will be used.',
<ide> name
<ide> );
<del> if (child != null) {
<add> if (keyUnique && child != null) {
<ide> result[name] = child;
<ide> }
<ide> } | 3 |
Go | Go | remove unnecessary diff tests | 038f3add5191240058c7a4154556553c5493ea44 | <ide><path>integration/container/diff_test.go
<ide> import (
<ide> "github.com/docker/docker/integration/internal/request"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/gotestyourself/gotestyourself/poll"
<del> "github.com/gotestyourself/gotestyourself/skip"
<ide> "github.com/stretchr/testify/assert"
<ide> "github.com/stretchr/testify/require"
<ide> )
<ide>
<del>// ensure that an added file shows up in docker diff
<del>func TestDiffFilenameShownInOutput(t *testing.T) {
<add>func TestDiff(t *testing.T) {
<ide> defer setupTest(t)()
<ide> client := request.NewAPIClient(t)
<ide> ctx := context.Background()
<ide> func TestDiffFilenameShownInOutput(t *testing.T) {
<ide> // it will take a few seconds to exit. Also there's no way in Windows to
<ide> // differentiate between an Add or a Modify, and all files are under
<ide> // a "Files/" prefix.
<del> lookingFor := containertypes.ContainerChangeResponseItem{Kind: archive.ChangeAdd, Path: "/foo/bar"}
<add> expected := []containertypes.ContainerChangeResponseItem{
<add> {Kind: archive.ChangeAdd, Path: "/foo"},
<add> {Kind: archive.ChangeAdd, Path: "/foo/bar"},
<add> }
<ide> if testEnv.OSType == "windows" {
<ide> poll.WaitOn(t, container.IsInState(ctx, client, cID, "exited"), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(60*time.Second))
<del> lookingFor = containertypes.ContainerChangeResponseItem{Kind: archive.ChangeModify, Path: "Files/foo/bar"}
<del> }
<del>
<del> items, err := client.ContainerDiff(ctx, cID)
<del> require.NoError(t, err)
<del> assert.Contains(t, items, lookingFor)
<del>}
<del>
<del>// test to ensure GH #3840 doesn't occur any more
<del>func TestDiffEnsureInitLayerFilesAreIgnored(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux")
<del>
<del> defer setupTest(t)()
<del> client := request.NewAPIClient(t)
<del> ctx := context.Background()
<del>
<del> // this is a list of files which shouldn't show up in `docker diff`
<del> initLayerFiles := []string{"/etc/resolv.conf", "/etc/hostname", "/etc/hosts", "/.dockerenv"}
<del> containerCount := 5
<del>
<del> // we might not run into this problem from the first run, so start a few containers
<del> for i := 0; i < containerCount; i++ {
<del> cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", `echo foo > /root/bar`))
<del>
<del> items, err := client.ContainerDiff(ctx, cID)
<del> require.NoError(t, err)
<del> for _, item := range items {
<del> assert.NotContains(t, initLayerFiles, item.Path)
<add> expected = []containertypes.ContainerChangeResponseItem{
<add> {Kind: archive.ChangeModify, Path: "Files/foo"},
<add> {Kind: archive.ChangeModify, Path: "Files/foo/bar"},
<ide> }
<ide> }
<del>}
<del>
<del>func TestDiffEnsureDefaultDevs(t *testing.T) {
<del> skip.If(t, testEnv.DaemonInfo.OSType != "linux")
<del>
<del> defer setupTest(t)()
<del> client := request.NewAPIClient(t)
<del> ctx := context.Background()
<del>
<del> cID := container.Run(t, ctx, client, container.WithCmd("sleep", "0"))
<ide>
<ide> items, err := client.ContainerDiff(ctx, cID)
<ide> require.NoError(t, err)
<del>
<del> expected := []containertypes.ContainerChangeResponseItem{
<del> {Kind: archive.ChangeModify, Path: "/dev"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/full"}, // busybox
<del> {Kind: archive.ChangeModify, Path: "/dev/ptmx"}, // libcontainer
<del> {Kind: archive.ChangeAdd, Path: "/dev/mqueue"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/kmsg"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/fd"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/ptmx"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/null"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/random"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/stdout"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/stderr"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/tty1"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/stdin"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/tty"},
<del> {Kind: archive.ChangeAdd, Path: "/dev/urandom"},
<del> }
<del>
<del> for _, item := range items {
<del> assert.Contains(t, expected, item)
<del> }
<add> assert.Equal(t, expected, items)
<ide> } | 1 |
Ruby | Ruby | make bottle implementation more generic | 7da459874fa289d3ebe8b82693e85893499a3148 | <ide><path>Library/Homebrew/bottles.rb
<ide> require 'extend/ARGV'
<ide> require 'bottle_version'
<ide>
<del>def bottle_filename f, options={}
<add>def bottle_filename options={}
<ide> options = { :tag => bottle_tag }.merge(options)
<del> name = f.name.downcase
<del> version = PkgVersion.new(f.stable.version, f.revision)
<del> options[:revision] ||= f.bottle.revision.to_i if f.bottle
<del> "#{name}-#{version}#{bottle_native_suffix(options)}"
<add> "#{options[:name]}-#{options[:version]}#{bottle_native_suffix(options)}"
<ide> end
<ide>
<ide> def install_bottle? f, options={:warn=>false}
<ide> return true if f.local_bottle_path
<ide> return true if ARGV.force_bottle?
<ide> return false unless f.pour_bottle?
<ide> return false unless f.default_build?
<del> return false unless bottle_current?(f)
<add> return false unless f.bottle
<add>
<ide> if f.bottle.cellar != :any && f.bottle.cellar != HOMEBREW_CELLAR.to_s
<ide> if options[:warn]
<ide> opoo "Building source; cellar of #{f}'s bottle is #{f.bottle.cellar}"
<ide> def built_as_bottle? f
<ide> tab.built_as_bottle
<ide> end
<ide>
<del>def bottle_current? f
<del> f.bottle and f.bottle.url and not f.bottle.checksum.empty?
<del>end
<del>
<ide> def bottle_file_outdated? f, file
<ide> filename = file.basename.to_s
<ide> return nil unless f and f.bottle and f.bottle.url \
<ide> def bottle_regex
<ide> Pathname::BOTTLE_EXTNAME_RX
<ide> end
<ide>
<del>def bottle_url f, tag=bottle_tag
<del> "#{f.bottle.root_url}/#{bottle_filename(f, :tag => tag)}"
<add>def bottle_url(root_url, filename_options={})
<add> "#{root_url}/#{bottle_filename(filename_options)}"
<ide> end
<ide>
<ide> def bottle_tag
<ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide> extend BuildEnvironmentDSL
<ide>
<ide> attr_reader :name, :path, :homepage, :build
<del> attr_reader :stable, :bottle, :devel, :head, :active_spec
<add> attr_reader :stable, :devel, :head, :active_spec
<ide> attr_reader :pkg_version, :revision
<ide>
<ide> # The current working directory during builds and tests.
<ide> def initialize name='__UNKNOWN__', path=self.class.path(name)
<ide> set_spec :stable
<ide> set_spec :devel
<ide> set_spec :head
<del> set_spec :bottle do |bottle|
<del> # Ensure the bottle URL is set. If it does not have a checksum,
<del> # then a bottle is not available for the current platform.
<del> # TODO: push this down into Bottle; we can pass the formula instance
<del> # into a validation method on the bottle instance.
<del> unless bottle.checksum.nil? || bottle.checksum.empty?
<del> @bottle = bottle
<del> bottle.url ||= bottle_url(self, bottle.current_tag)
<del> bottle.version = PkgVersion.new(stable.version, revision)
<del> end
<del> end
<ide>
<ide> @active_spec = determine_active_spec
<ide> validate_attributes :url, :name, :version
<ide> @build = determine_build_options
<del>
<del> # TODO: @pkg_version is already set for bottles, since constructing it
<del> # requires passing in the active_spec version. This should be fixed by
<del> # making the bottle an attribute of SoftwareSpec rather than a separate
<del> # spec itself.
<del> if active_spec == bottle
<del> @pkg_version = bottle.version
<del> else
<del> @pkg_version = PkgVersion.new(version, revision)
<del> end
<add> @pkg_version = PkgVersion.new(version, revision)
<ide>
<ide> @pin = FormulaPin.new(self)
<ide>
<ide> def initialize name='__UNKNOWN__', path=self.class.path(name)
<ide>
<ide> def set_spec(name)
<ide> spec = self.class.send(name)
<del> if block_given? && yield(spec) || spec.url
<add> if spec.url
<ide> spec.owner = self
<ide> instance_variable_set("@#{name}", spec)
<ide> end
<ide> end
<ide>
<del> def select_bottle?
<del> !ARGV.build_bottle? && install_bottle?(self)
<del> end
<del>
<ide> def determine_active_spec
<ide> case
<ide> when head && ARGV.build_head? then head # --HEAD
<ide> when devel && ARGV.build_devel? then devel # --devel
<del> when bottle && select_bottle? then bottle # bottle available
<ide> when stable then stable
<ide> when devel && stable.nil? then devel # devel-only
<ide> when head && stable.nil? then head # head-only
<ide> def determine_build_options
<ide> build
<ide> end
<ide>
<add> def bottle
<add> Bottle.new(self, active_spec.bottle_specification) if active_spec.bottled?
<add> end
<add>
<ide> def url; active_spec.url; end
<ide> def version; active_spec.version; end
<ide> def mirrors; active_spec.mirrors; end
<ide> class << self
<ide> attr_rw :homepage, :plist_startup, :plist_manual, :revision
<ide>
<ide> def specs
<del> @specs ||= [stable, devel, head, bottle].freeze
<add> @specs ||= [stable, devel, head].freeze
<ide> end
<ide>
<ide> def url val, specs={}
<ide> def #{cksum}(val)
<ide> EOS
<ide> end
<ide>
<add> def bottle *, &block
<add> stable.bottle(&block)
<add> end
<add>
<ide> def build
<ide> stable.build
<ide> end
<ide> def stable &block
<ide> @stable.instance_eval(&block)
<ide> end
<ide>
<del> def bottle *, &block
<del> @bottle ||= Bottle.new
<del> return @bottle unless block_given?
<del> @bottle.instance_eval(&block)
<del> @bottle.version = @stable.version
<del> end
<del>
<ide> def devel &block
<ide> @devel ||= SoftwareSpec.new
<ide> return @devel unless block_given?
<ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide> attr_reader :name
<ide> attr_reader :build, :resources, :owner
<ide> attr_reader :dependency_collector
<add> attr_reader :bottle_specification
<ide>
<ide> def_delegators :@resource, :stage, :fetch, :verify_download_integrity
<ide> def_delegators :@resource, :cached_download, :clear_cache
<ide> def initialize
<ide> @resources = {}
<ide> @build = BuildOptions.new(ARGV.options_only)
<ide> @dependency_collector = DependencyCollector.new
<add> @bottle_specification = BottleSpecification.new
<ide> end
<ide>
<ide> def owner= owner
<ide> def url val=nil, specs={}
<ide> dependency_collector.add(@resource)
<ide> end
<ide>
<add> def bottled?
<add> bottle_specification.fully_specified?
<add> end
<add>
<add> def bottle &block
<add> bottle_specification.instance_eval(&block)
<add> end
<add>
<ide> def resource? name
<ide> resources.has_key?(name)
<ide> end
<ide> def verify_download_integrity fn
<ide> end
<ide> end
<ide>
<del>class Bottle < SoftwareSpec
<del> attr_rw :root_url, :prefix, :cellar, :revision
<del> attr_accessor :current_tag
<add>class Bottle
<add> extend Forwardable
<add>
<add> attr_reader :resource, :prefix, :cellar, :revision
<add>
<add> def_delegators :resource, :url, :fetch, :verify_download_integrity
<add> def_delegators :resource, :downloader, :cached_download, :clear_cache
<ide>
<del> def_delegators :@resource, :version=, :url=
<add> def initialize(f, spec)
<add> @resource = Resource.new
<add> @resource.owner = f
<add> @resource.url = bottle_url(
<add> spec.root_url,
<add> :name => f.name,
<add> :version => f.pkg_version,
<add> :revision => spec.revision,
<add> :tag => spec.current_tag
<add> )
<add> @resource.version = f.pkg_version
<add> @resource.checksum = spec.checksum
<add> @prefix = spec.prefix
<add> @cellar = spec.cellar
<add> @revision = spec.revision
<add> end
<add>end
<add>
<add>class BottleSpecification
<add> attr_rw :root_url, :prefix, :cellar, :revision
<add> attr_reader :current_tag, :checksum
<ide>
<ide> def initialize
<del> super
<ide> @revision = 0
<ide> @prefix = '/usr/local'
<ide> @cellar = '/usr/local/Cellar'
<ide> @root_url = 'https://downloads.sf.net/project/machomebrew/Bottles'
<ide> end
<ide>
<add> def fully_specified?
<add> checksum && !checksum.empty?
<add> end
<add>
<ide> # Checksum methods in the DSL's bottle block optionally take
<ide> # a Hash, which indicates the platform the checksum applies on.
<ide> Checksum::TYPES.each do |cksum|
<ide> def #{cksum}(val=nil)
<ide> end
<ide>
<ide> cksum, current_tag = @#{cksum}.fetch_bottle_for(bottle_tag)
<del> @resource.checksum = cksum if cksum
<add> @checksum = cksum if cksum
<ide> @current_tag = current_tag if cksum
<ide> end
<ide> EOS
<ide><path>Library/Homebrew/test/test_formula.rb
<ide> def initialize(name="spec_test_ball", path=nil)
<ide> assert_equal f.stable, f.active_spec
<ide>
<ide> assert_instance_of SoftwareSpec, f.stable
<del> assert_instance_of Bottle, f.bottle
<ide> assert_instance_of SoftwareSpec, f.devel
<ide> assert_instance_of HeadSoftwareSpec, f.head
<ide> end
<ide> def initialize(*args)
<ide> def test_class_specs_are_always_initialized
<ide> f = formula { url 'foo-1.0' }
<ide>
<del> %w{stable devel head bottle}.each do |spec|
<add> %w{stable devel head}.each do |spec|
<ide> assert_kind_of SoftwareSpec, f.class.send(spec)
<ide> end
<ide> end
<ide>
<ide> def test_incomplete_instance_specs_are_not_accessible
<ide> f = formula { url 'foo-1.0' }
<ide>
<del> %w{devel head bottle}.each { |spec| assert_nil f.send(spec) }
<add> %w{devel head}.each { |spec| assert_nil f.send(spec) }
<ide> end
<ide>
<ide> def test_honors_attributes_declared_before_specs
<ide> def test_honors_attributes_declared_before_specs
<ide> devel { url 'foo-1.1' }
<ide> end
<ide>
<del> %w{stable devel head bottle}.each do |spec|
<add> %w{stable devel head}.each do |spec|
<ide> assert_equal 'foo', f.class.send(spec).deps.first.name
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_formula_spec_selection.rb
<ide> def test_selects_devel_when_requested
<ide> assert_spec_selected :devel
<ide> end
<ide>
<del> def test_selects_bottle_when_available
<del> formula do
<del> def install_bottle?(*); true; end
<del>
<del> url 'foo-1.0'
<del> bottle { sha1 TEST_SHA1 => bottle_tag }
<del> end
<del>
<del> assert_spec_selected :bottle
<del> end
<del>
<ide> def test_selects_stable_by_default
<ide> formula do
<ide> url 'foo-1.0'
<ide> def test_incomplete_devel_not_set
<ide> assert_spec_unset :devel
<ide> assert_spec_selected :stable
<ide> end
<del>
<del> def test_incomplete_bottle_not_set
<del> formula do
<del> url 'foo-1.0'
<del> bottle { sha1 TEST_SHA1 => :some_nonexistent_thing }
<del> end
<del>
<del> assert_spec_unset :bottle
<del> assert_spec_selected :stable
<del> end
<ide> end
<ide><path>Library/Homebrew/test/test_software_spec.rb
<ide> def test_verify_download_integrity
<ide> end
<ide> end
<ide>
<del>class BottleTests < Test::Unit::TestCase
<add>class BottleSpecificationTests < Test::Unit::TestCase
<ide> def setup
<del> @spec = Bottle.new
<add> @spec = BottleSpecification.new
<ide> end
<ide>
<ide> def test_checksum_setters | 6 |
Python | Python | apply basestring fixer | 68338eed3ae91c9846142e088c16b63635e58178 | <ide><path>numpy/compat/py3k.py
<ide>
<ide> __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar',
<ide> 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested',
<del> 'asstr', 'open_latin1', 'long']
<add> 'asstr', 'open_latin1', 'long', 'basestring']
<ide>
<ide> import sys
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> import io
<add>
<ide> long = int
<ide> integer_types = (int,)
<add> basestring = str
<ide> bytes = bytes
<ide> unicode = str
<ide>
<ide> def open_latin1(filename, mode='r'):
<ide> bytes = str
<ide> unicode = unicode
<ide> long = long
<add> basestring = basestring
<ide> integer_types = (int, long)
<ide> asbytes = str
<ide> asstr = str
<ide><path>numpy/core/memmap.py
<ide>
<ide> import numpy as np
<ide> from .numeric import uint8, ndarray, dtype
<del>from numpy.compat import long
<add>from numpy.compat import long, basestring
<ide>
<ide> dtypedescr = dtype
<ide> valid_filemodes = ["r", "c", "r+", "w+"]
<ide><path>numpy/core/numeric.py
<ide>
<ide> import sys
<ide> import warnings
<add>import collections
<ide> from . import multiarray
<ide> from . import umath
<ide> from .umath import *
<ide> from . import numerictypes
<ide> from .numerictypes import *
<del>import collections
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> import pickle
<add> basestring = str
<ide> else:
<ide> import cPickle as pickle
<ide>
<ide><path>numpy/distutils/extension.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>__revision__ = "$Id: extension.py,v 1.1 2005/04/09 19:29:34 pearu Exp $"
<del>
<add>import sys
<add>import re
<ide> from distutils.extension import Extension as old_Extension
<ide>
<del>import re
<add>if sys.version_info[0] >= 3:
<add> basestring = str
<add>
<add>
<ide> cxx_ext_re = re.compile(r'.*[.](cpp|cxx|cc)\Z',re.I).match
<ide> fortran_pyf_ext_re = re.compile(r'.*[.](f90|f95|f77|for|ftn|f|pyf)\Z',re.I).match
<ide>
<ide><path>numpy/lib/_iotools.py
<ide> import sys
<ide> import numpy as np
<ide> import numpy.core.numeric as nx
<add>from numpy.compat import asbytes, bytes, asbytes_nested, long, basestring
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> from builtins import bool, int, float, complex, object, unicode, str
<ide> else:
<ide> from __builtin__ import bool, int, float, complex, object, unicode, str
<ide>
<del>from numpy.compat import asbytes, bytes, asbytes_nested, long
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> def _bytes_to_complex(s):
<ide><path>numpy/lib/format.py
<ide> import numpy
<ide> import sys
<ide> from numpy.lib.utils import safe_eval
<del>from numpy.compat import asbytes, isfileobj, long
<add>from numpy.compat import asbytes, isfileobj, long, basestring
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> import pickle
<ide><path>numpy/lib/npyio.py
<ide> _is_string_like, has_nested_fields, flatten_dtype, \
<ide> easy_dtype, _bytes_to_name
<ide>
<del>from numpy.compat import asbytes, asstr, asbytes_nested, bytes
<add>from numpy.compat import asbytes, asstr, asbytes_nested, bytes, basestring
<ide> from io import BytesIO
<ide>
<ide> if sys.version_info[0] >= 3:
<ide><path>numpy/lib/recfunctions.py
<ide> from numpy.ma import MaskedArray
<ide> from numpy.ma.mrecords import MaskedRecords
<ide> from numpy.lib._iotools import _is_string_like
<add>from numpy.compat import basestring
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> izip = zip
<ide><path>numpy/ma/core.py
<ide> from numpy import ndarray, amax, amin, iscomplexobj, bool_
<ide> from numpy import array as narray
<ide> from numpy.lib.function_base import angle
<del>from numpy.compat import getargspec, formatargspec, long
<add>from numpy.compat import getargspec, formatargspec, long, basestring
<ide> from numpy import expand_dims as n_expand_dims
<ide>
<ide> if sys.version_info[0] >= 3:
<ide><path>numpy/ma/mrecords.py
<ide> __author__ = "Pierre GF Gerard-Marchant"
<ide>
<ide> import sys
<add>import warnings
<ide>
<ide> import numpy as np
<del>from numpy import bool_, dtype, \
<del> ndarray, recarray, array as narray
<ide> import numpy.core.numerictypes as ntypes
<del>from numpy.core.records import fromarrays as recfromarrays, \
<del> fromrecords as recfromrecords
<add>from numpy.compat import basestring
<add>from numpy import (
<add> bool_, dtype, ndarray, recarray, array as narray
<add> )
<add>from numpy.core.records import (
<add> fromarrays as recfromarrays, fromrecords as recfromrecords
<add> )
<ide>
<ide> _byteorderconv = np.core.records._byteorderconv
<ide> _typestr = ntypes._typestr
<ide>
<ide> _check_fill_value = ma.core._check_fill_value
<ide>
<del>import warnings
<ide>
<ide> __all__ = ['MaskedRecords', 'mrecarray',
<ide> 'fromarrays', 'fromrecords', 'fromtextfile', 'addfield',
<ide><path>numpy/testing/nosetester.py
<ide> import sys
<ide> import warnings
<ide> import numpy.testing.utils
<add>from numpy.compat import basestring
<ide>
<ide> def get_package_name(filepath):
<ide> """
<ide><path>tools/py3tool.py
<ide> # available fixers, with fixers not currently skipped commented out.
<ide> FIXES_TO_SKIP = [
<ide> 'apply',
<del># 'basestring',
<add> 'basestring',
<ide> 'buffer',
<ide> 'callable',
<ide> 'dict', | 12 |
PHP | PHP | add types to core package | 7570b54a3dd56948b0a279c6024d215c10cb742a | <ide><path>src/Core/BasePlugin.php
<ide> public function initialize()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function getName()
<add> public function getName(): string
<ide> {
<ide> if ($this->name) {
<ide> return $this->name;
<ide> public function getName()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function getPath()
<add> public function getPath(): string
<ide> {
<ide> if ($this->path) {
<ide> return $this->path;
<ide> public function getPath()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function getConfigPath()
<add> public function getConfigPath(): string
<ide> {
<ide> if ($this->configPath) {
<ide> return $this->configPath;
<ide> public function getConfigPath()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function getClassPath()
<add> public function getClassPath(): string
<ide> {
<ide> if ($this->classPath) {
<ide> return $this->classPath;
<ide> public function getClassPath()
<ide> /**
<ide> * {@inheritdoc}
<ide> */
<del> public function enable($hook)
<add> public function enable(string $hook): PluginInterface
<ide> {
<ide> $this->checkHook($hook);
<ide> $this->{"{$hook}Enabled}"} = true;
<ide> public function enable($hook)
<ide> /**
<ide> * {@inheritdoc}
<ide> */
<del> public function disable($hook)
<add> public function disable(string $hook): PluginInterface
<ide> {
<ide> $this->checkHook($hook);
<ide> $this->{"{$hook}Enabled"} = false;
<ide> public function disable($hook)
<ide> /**
<ide> * {@inheritdoc}
<ide> */
<del> public function isEnabled($hook)
<add> public function isEnabled(string $hook): bool
<ide> {
<ide> $this->checkHook($hook);
<ide>
<ide> public function isEnabled($hook)
<ide> * @throws \InvalidArgumentException on invalid hooks
<ide> * @return void
<ide> */
<del> protected function checkHook($hook)
<add> protected function checkHook(string $hook): void
<ide> {
<ide> if (!in_array($hook, static::VALID_HOOKS)) {
<ide> throw new InvalidArgumentException(
<ide><path>src/Core/ConventionsTrait.php
<ide> trait ConventionsTrait
<ide> * @param string $name Model class name
<ide> * @return string Singular model key
<ide> */
<del> protected function _fixtureName($name)
<add> protected function _fixtureName(string $name): string
<ide> {
<ide> return Inflector::underscore($name);
<ide> }
<ide> protected function _fixtureName($name)
<ide> * @param string $name Name
<ide> * @return string Camelized and plural model name
<ide> */
<del> protected function _entityName($name)
<add> protected function _entityName(string $name): string
<ide> {
<ide> return Inflector::singularize(Inflector::camelize($name));
<ide> }
<ide> protected function _entityName($name)
<ide> * @param string $name Model class name
<ide> * @return string Singular model key
<ide> */
<del> protected function _modelKey($name)
<add> protected function _modelKey(string $name): string
<ide> {
<ide> list(, $name) = pluginSplit($name);
<ide>
<ide> protected function _modelKey($name)
<ide> * @param string $key Foreign key
<ide> * @return string Model name
<ide> */
<del> protected function _modelNameFromKey($key)
<add> protected function _modelNameFromKey(string $key): string
<ide> {
<ide> $key = str_replace('_id', '', $key);
<ide>
<ide> protected function _modelNameFromKey($key)
<ide> * @param string $name Name to use
<ide> * @return string Variable name
<ide> */
<del> protected function _singularName($name)
<add> protected function _singularName(string $name): string
<ide> {
<ide> return Inflector::variable(Inflector::singularize($name));
<ide> }
<ide> protected function _singularName($name)
<ide> * @param string $name Name to use
<ide> * @return string Plural name for views
<ide> */
<del> protected function _variableName($name)
<add> protected function _variableName(string $name): string
<ide> {
<ide> return Inflector::variable($name);
<ide> }
<ide> protected function _variableName($name)
<ide> * @param string $name Controller name
<ide> * @return string Singular human name
<ide> */
<del> protected function _singularHumanName($name)
<add> protected function _singularHumanName(string $name): string
<ide> {
<ide> return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
<ide> }
<ide> protected function _singularHumanName($name)
<ide> * @param string $name name
<ide> * @return string Camelized name
<ide> */
<del> protected function _camelize($name)
<add> protected function _camelize(string $name): string
<ide> {
<ide> return Inflector::camelize($name);
<ide> }
<ide> protected function _camelize($name)
<ide> * @param string $name Controller name
<ide> * @return string Plural human name
<ide> */
<del> protected function _pluralHumanName($name)
<add> protected function _pluralHumanName(string $name): string
<ide> {
<ide> return Inflector::humanize(Inflector::underscore($name));
<ide> }
<ide> protected function _pluralHumanName($name)
<ide> * @param string $pluginName Name of the plugin you want ie. DebugKit
<ide> * @return string path path to the correct plugin.
<ide> */
<del> protected function _pluginPath($pluginName)
<add> protected function _pluginPath(string $pluginName): string
<ide> {
<ide> if (Plugin::isLoaded($pluginName)) {
<ide> return Plugin::path($pluginName);
<ide> protected function _pluginPath($pluginName)
<ide> * @param string $pluginName Plugin name
<ide> * @return string Plugin's namespace
<ide> */
<del> protected function _pluginNamespace($pluginName)
<add> protected function _pluginNamespace(string $pluginName): string
<ide> {
<ide> return str_replace('/', '\\', $pluginName);
<ide> }
<ide><path>src/Core/HttpApplicationInterface.php
<ide> public function middleware($middleware);
<ide> * @param callable $next The next middleware
<ide> * @return \Psr\Http\Message\ResponseInterface
<ide> */
<del> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next);
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next): ResponseInterface;
<ide> }
<ide><path>src/Core/InstanceConfigTrait.php
<ide> protected function _configWrite($key, $value, $merge = false)
<ide> * @return void
<ide> * @throws \Cake\Core\Exception\Exception if attempting to clobber existing config
<ide> */
<del> protected function _configDelete($key)
<add> protected function _configDelete(string $key): void
<ide> {
<ide> if (strpos($key, '.') === false) {
<ide> unset($this->_config[$key]);
<ide><path>src/Core/ObjectRegistry.php
<ide> abstract class ObjectRegistry implements Countable, IteratorAggregate
<ide> * @return mixed
<ide> * @throws \Exception If the class cannot be found.
<ide> */
<del> public function load($objectName, $config = [])
<add> public function load($objectName, array $config = [])
<ide> {
<ide> if (is_array($config) && isset($config['className'])) {
<ide> $name = $objectName;
<ide> public function load($objectName, $config = [])
<ide> * @return void
<ide> * @throws \RuntimeException When a duplicate is found.
<ide> */
<del> protected function _checkDuplicate($name, $config)
<add> protected function _checkDuplicate(string $name, config $config): void
<ide> {
<ide> /** @var \Cake\Core\InstanceConfigTrait $existing */
<ide> $existing = $this->_loaded[$name];
<ide> abstract protected function _create($class, $alias, $config);
<ide> *
<ide> * @return array List of object names.
<ide> */
<del> public function loaded()
<add> public function loaded(): array
<ide> {
<ide> return array_keys($this->_loaded);
<ide> }
<ide> public function loaded()
<ide> * @param string $name The object name to check for.
<ide> * @return bool True is object is loaded else false.
<ide> */
<del> public function has($name)
<add> public function has(string $name): bool
<ide> {
<ide> return isset($this->_loaded[$name]);
<ide> }
<ide> public function has($name)
<ide> * @param string $name Name of object.
<ide> * @return object|null Object instance if loaded else null.
<ide> */
<del> public function get($name)
<add> public function get(string $name)
<ide> {
<ide> if (isset($this->_loaded[$name])) {
<ide> return $this->_loaded[$name];
<ide> public function get($name)
<ide> * @param string $name Name of property to read
<ide> * @return mixed
<ide> */
<del> public function __get($name)
<add> public function __get(string $name)
<ide> {
<ide> return $this->get($name);
<ide> }
<ide> public function __get($name)
<ide> * @param string $name Name of object being checked.
<ide> * @return bool
<ide> */
<del> public function __isset($name)
<add> public function __isset(string $name)
<ide> {
<ide> return isset($this->_loaded[$name]);
<ide> }
<ide> public function __isset($name)
<ide> * @param mixed $object Object to set.
<ide> * @return void
<ide> */
<del> public function __set($name, $object)
<add> public function __set(string $name, $object)
<ide> {
<ide> $this->set($name, $object);
<ide> }
<ide> public function __set($name, $object)
<ide> * @param string $name Name of a property to unset.
<ide> * @return void
<ide> */
<del> public function __unset($name)
<add> public function __unset(string $name)
<ide> {
<ide> $this->unload($name);
<ide> }
<ide> public function __unset($name)
<ide> * @param array $objects Array of child objects to normalize.
<ide> * @return array Array of normalized objects.
<ide> */
<del> public function normalizeArray($objects)
<add> public function normalizeArray(array $objects): array
<ide> {
<ide> $normal = [];
<ide> foreach ($objects as $i => $objectName) {
<ide> public function reset()
<ide> * @param object $object instance to store in the registry
<ide> * @return $this
<ide> */
<del> public function set($objectName, $object)
<add> public function set(string $objectName, $object)
<ide> {
<ide> list(, $name) = pluginSplit($objectName);
<ide>
<ide> public function set($objectName, $object)
<ide> * @param string $objectName The name of the object to remove from the registry.
<ide> * @return $this
<ide> */
<del> public function unload($objectName)
<add> public function unload(string $objectName)
<ide> {
<ide> if (empty($this->_loaded[$objectName])) {
<ide> list($plugin, $objectName) = pluginSplit($objectName);
<ide> public function getIterator()
<ide> *
<ide> * @return int
<ide> */
<del> public function count()
<add> public function count(): int
<ide> {
<ide> return count($this->_loaded);
<ide> }
<ide> public function count()
<ide> *
<ide> * @return array
<ide> */
<del> public function __debugInfo()
<add> public function __debugInfo(): array
<ide> {
<ide> $properties = get_object_vars($this);
<ide> if (isset($properties['_loaded'])) {
<ide><path>src/Core/PluginApplicationInterface.php
<ide> interface PluginApplicationInterface extends EventDispatcherInterface
<ide> * @param array $config The configuration data for the plugin if using a string for $name
<ide> * @return $this
<ide> */
<del> public function addPlugin($name, array $config = []);
<add> public function addPlugin($name, array $config = []): self;
<ide>
<ide> /**
<ide> * Run bootstrap logic for loaded plugins.
<ide> *
<ide> * @return void
<ide> */
<del> public function pluginBootstrap();
<add> public function pluginBootstrap(): void;
<ide>
<ide> /**
<ide> * Run routes hooks for loaded plugins
<ide><path>src/Core/PluginCollection.php
<ide> public function __construct(array $plugins = [])
<ide> * @internal
<ide> * @return void
<ide> */
<del> protected function loadConfig()
<add> protected function loadConfig(): void
<ide> {
<ide> if (Configure::check('plugins')) {
<ide> return;
<ide> protected function loadConfig()
<ide> * @throws Cake\Core\Exception\MissingPluginException when a plugin path cannot be resolved.
<ide> * @internal
<ide> */
<del> public function findPath($name)
<add> public function findPath(string $name): string
<ide> {
<ide> $this->loadConfig();
<ide>
<ide> public function findPath($name)
<ide> * @param \Cake\Core\PluginInterface $plugin The plugin to load.
<ide> * @return $this
<ide> */
<del> public function add(PluginInterface $plugin)
<add> public function add(PluginInterface $plugin): self
<ide> {
<ide> $name = $plugin->getName();
<ide> $this->plugins[$name] = $plugin;
<ide> public function add(PluginInterface $plugin)
<ide> * @param string $name The named plugin.
<ide> * @return $this
<ide> */
<del> public function remove($name)
<add> public function remove(string $name): self
<ide> {
<ide> unset($this->plugins[$name]);
<ide> $this->names = array_keys($this->plugins);
<ide> public function remove($name)
<ide> * @param string $name The named plugin.
<ide> * @return bool
<ide> */
<del> public function has($name)
<add> public function has(string $name): bool
<ide> {
<ide> return isset($this->plugins[$name]);
<ide> }
<ide> public function has($name)
<ide> * @return \Cake\Core\PluginInterface The plugin.
<ide> * @throws \Cake\Core\Exception\MissingPluginException when unknown plugins are fetched.
<ide> */
<del> public function get($name)
<add> public function get(string $name): PluginInterface
<ide> {
<ide> if (!$this->has($name)) {
<ide> throw new MissingPluginException(['plugin' => $name]);
<ide> public function next()
<ide> *
<ide> * @return string
<ide> */
<del> public function key()
<add> public function key(): string
<ide> {
<ide> return $this->names[$this->position];
<ide> }
<ide> public function current()
<ide> *
<ide> * @return void
<ide> */
<del> public function rewind()
<add> public function rewind(): void
<ide> {
<ide> $this->position = 0;
<ide> }
<ide> public function rewind()
<ide> *
<ide> * @return bool
<ide> */
<del> public function valid()
<add> public function valid(): bool
<ide> {
<ide> return $this->position < count($this->plugins);
<ide> }
<ide> public function valid()
<ide> *
<ide> * @return int
<ide> */
<del> public function count()
<add> public function count(): int
<ide> {
<ide> return count($this->plugins);
<ide> }
<ide> public function count()
<ide> * @return \Generator A generator containing matching plugins.
<ide> * @throws \InvalidArgumentException on invalid hooks
<ide> */
<del> public function with($hook)
<add> public function with(string $hook)
<ide> {
<ide> if (!in_array($hook, PluginInterface::VALID_HOOKS)) {
<ide> throw new InvalidArgumentException("The `{$hook}` hook is not a known plugin hook.");
<ide><path>src/Core/PluginInterface.php
<ide> interface PluginInterface
<ide> *
<ide> * @return string
<ide> */
<del> public function getName();
<add> public function getName(): string;
<ide>
<ide> /**
<ide> * Get the filesystem path to this plugin
<ide> *
<ide> * @return string
<ide> */
<del> public function getPath();
<add> public function getPath(): string;
<ide>
<ide> /**
<ide> * Get the filesystem path to configuration for this plugin
<ide> *
<ide> * @return string
<ide> */
<del> public function getConfigPath();
<add> public function getConfigPath(): string;
<ide>
<ide> /**
<ide> * Get the filesystem path to configuration for this plugin
<ide> *
<ide> * @return string
<ide> */
<del> public function getClassPath();
<add> public function getClassPath(): string;
<ide>
<ide> /**
<ide> * Load all the application configuration and bootstrap logic.
<ide> public function routes($routes);
<ide> * @param string $hook The hook to disable
<ide> * @return $this
<ide> */
<del> public function disable($hook);
<add> public function disable(string $hook): self;
<ide>
<ide> /**
<ide> * Enables the named hook
<ide> *
<ide> * @param string $hook The hook to disable
<ide> * @return $this
<ide> */
<del> public function enable($hook);
<add> public function enable(string $hook): self;
<ide>
<ide> /**
<ide> * Check if the named hook is enabled
<ide> *
<ide> * @param string $hook The hook to check
<ide> * @return bool
<ide> */
<del> public function isEnabled($hook);
<add> public function isEnabled(string $hook): bool;
<ide> }
<ide><path>src/Core/StaticConfigTrait.php
<ide> trait StaticConfigTrait
<ide> * @throws \LogicException When trying to store an invalid structured config array.
<ide> * @return void
<ide> */
<del> public static function setConfig($key, $config = null)
<add> public static function setConfig($key, ?array $config = null): void
<ide> {
<ide> if ($config === null) {
<ide> if (!is_array($key)) {
<ide> public static function setConfig($key, $config = null)
<ide> * @param string $key The name of the configuration.
<ide> * @return array|null Array of configuration data.
<ide> */
<del> public static function getConfig($key)
<add> public static function getConfig(string $key): ?array
<ide> {
<ide> return isset(static::$_config[$key]) ? static::$_config[$key] : null;
<ide> }
<ide> public static function getConfig($key)
<ide> * @param string $config An existing configuration you wish to remove.
<ide> * @return bool Success of the removal, returns false when the config does not exist.
<ide> */
<del> public static function drop($config)
<add> public static function drop(string $config): bool
<ide> {
<ide> if (!isset(static::$_config[$config])) {
<ide> return false;
<ide> public static function drop($config)
<ide> *
<ide> * @return array Array of configurations.
<ide> */
<del> public static function configured()
<add> public static function configured(): array
<ide> {
<ide> return array_keys(static::$_config);
<ide> }
<ide> public static function configured()
<ide> * @return array The configuration array to be stored after parsing the DSN
<ide> * @throws \InvalidArgumentException If not passed a string, or passed an invalid string
<ide> */
<del> public static function parseDsn($dsn)
<add> public static function parseDsn(string $dsn): array
<ide> {
<ide> if (empty($dsn)) {
<ide> return [];
<ide> public static function parseDsn($dsn)
<ide> * @param array $map Additions/edits to the class map to apply.
<ide> * @return void
<ide> */
<del> public static function setDsnClassMap(array $map)
<add> public static function setDsnClassMap(array $map): void
<ide> {
<ide> static::$_dsnClassMap = $map + static::$_dsnClassMap;
<ide> }
<ide> public static function setDsnClassMap(array $map)
<ide> *
<ide> * @return array
<ide> */
<del> public static function getDsnClassMap()
<add> public static function getDsnClassMap(): array
<ide> {
<ide> return static::$_dsnClassMap;
<ide> }
<ide><path>src/Core/functions.php
<ide> * @return mixed Wrapped text.
<ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#h
<ide> */
<del> function h($text, $double = true, $charset = null)
<add> function h($text, bool $double = true, ?string $charset = null)
<ide> {
<ide> if (is_string($text)) {
<ide> //optimize for strings
<ide> function h($text, $double = true, $charset = null)
<ide> * @return array Array with 2 indexes. 0 => plugin name, 1 => class name.
<ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pluginSplit
<ide> */
<del> function pluginSplit($name, $dotAppend = false, $plugin = null)
<add> function pluginSplit(string $name, bool $dotAppend = false, ?string $plugin = null): array
<ide> {
<ide> if (strpos($name, '.') !== false) {
<ide> $parts = explode('.', $name, 2);
<ide> function pluginSplit($name, $dotAppend = false, $plugin = null)
<ide> * @param string $class The full class name, ie `Cake\Core\App`.
<ide> * @return array Array with 2 indexes. 0 => namespace, 1 => classname.
<ide> */
<del> function namespaceSplit($class)
<add> function namespaceSplit(string $class): array
<ide> {
<ide> $pos = strrpos($class, '\\');
<ide> if ($pos === false) {
<ide> function pj($var)
<ide> * @return string|bool|null Environment variable setting.
<ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#env
<ide> */
<del> function env($key, $default = null)
<add> function env(string $key, ?string $default = null)
<ide> {
<ide> if ($key === 'HTTPS') {
<ide> if (isset($_SERVER['HTTPS'])) {
<ide> function env($key, $default = null)
<ide> * @param string $message The warning message.
<ide> * @return void
<ide> */
<del> function triggerWarning($message)
<add> function triggerWarning(string $message): void
<ide> {
<ide> $stackFrame = 1;
<ide> $trace = debug_backtrace();
<ide> function triggerWarning($message)
<ide> * as that should point to application/plugin code.
<ide> * @return void
<ide> */
<del> function deprecationWarning($message, $stackFrame = 1)
<add> function deprecationWarning(string $message, int $stackFrame = 1): void
<ide> {
<ide> if (!(error_reporting() & E_USER_DEPRECATED)) {
<ide> return;
<ide> function deprecationWarning($message, $stackFrame = 1)
<ide> * @param mixed $var Variable to check
<ide> * @return string Returns the class name or variable type
<ide> */
<del> function getTypeName($var)
<add> function getTypeName($var): string
<ide> {
<ide> return is_object($var) ? get_class($var) : gettype($var);
<ide> }
<ide><path>src/Http/BaseApplication.php
<ide> public function pluginMiddleware($middleware)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function addPlugin($name, array $config = [])
<add> public function addPlugin(string $name, array $config = []): PluginApplicationInterface
<ide> {
<ide> if (is_string($name)) {
<ide> $plugin = $this->makePlugin($name, $config);
<ide> public function bootstrap()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function pluginBootstrap()
<add> public function pluginBootstrap(): void
<ide> {
<ide> foreach ($this->plugins->with('bootstrap') as $plugin) {
<ide> $plugin->bootstrap($this);
<ide> public function pluginConsole($commands)
<ide> * @param callable $next The next middleware
<ide> * @return \Psr\Http\Message\ResponseInterface
<ide> */
<del> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next): ResponseInterface
<ide> {
<ide> return $this->getDispatcher()->dispatch($request, $response);
<ide> }
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public function testSimpleParseDsn()
<ide> */
<ide> public function testParseBadType()
<ide> {
<del> $this->expectException(\InvalidArgumentException::class);
<add> $this->expectException(\TypeError::class);
<ide> $className = get_class($this->subject);
<ide> $className::parseDsn(['url' => 'http://:80']);
<ide> } | 12 |
Text | Text | add hardware flaws as a way to attack | 0df20f3e7981bdb8a062ad78df566d566d27f13c | <ide><path>guide/english/security/cyberattacks/index.md
<ide> In 2017, a Ukrainian government website was infected with malware that erases vi
<ide>
<ide> One of the biggest cyberattacks to date is the Yahoo hack, this affected all 3 billion user accounts. The hack was dangerous, as it exposed users names,
<ide> email addresses, telephone numbers, DOB, encrypted passwords and unencrypted security questions. This attack proves that no matter how big a company is,
<del>no one can be 100% that their data is secure.
<add>no one can be 100% that their data is secure. There are also hardware hacks, i.e. holes in hardware that people with malicious intent can abuse. Some recent examples of this are the widely known Meltdown and Spectre incidents which accidentally allowed websites access to memory that they shouldn't have access to.
<ide>
<ide> ## Common Types of Cyberattacks
<ide> * Malware | 1 |
Javascript | Javascript | add gulp task to generate refs | 8be4db1c34cfadd9d7da8c35b2d1a0af1cbe61f9 | <ide><path>gulpfile.js
<ide> function createTestSource(testsName) {
<ide> return source;
<ide> }
<ide>
<add>function makeRef(done, noPrompts) {
<add> console.log();
<add> console.log('### Creating reference images');
<add>
<add> var PDF_BROWSERS = process.env['PDF_BROWSERS'] ||
<add> 'resources/browser_manifests/browser_manifest.json';
<add>
<add> if (!checkFile('test/' + PDF_BROWSERS)) {
<add> console.log('Browser manifest file test/' + PDF_BROWSERS +
<add> ' does not exist.');
<add> console.log('Copy and adjust the example in ' +
<add> 'test/resources/browser_manifests.');
<add> done(new Error('Missing manifest file'));
<add> return;
<add> }
<add>
<add> var args = ['test.js', '--masterMode'];
<add> if (noPrompts) {
<add> args.push('--noPrompts');
<add> }
<add> args.push('--browserManifestFile=' + PDF_BROWSERS);
<add> var testProcess = spawn('node', args, {cwd: TEST_DIR, stdio: 'inherit'});
<add> testProcess.on('close', function (code) {
<add> done();
<add> });
<add>}
<add>
<ide> gulp.task('default', function() {
<ide> console.log('Available tasks:');
<ide> var tasks = Object.keys(gulp.tasks);
<ide> gulp.task('fonttest', function () {
<ide> return createTestSource('font');
<ide> });
<ide>
<del>gulp.task('botmakeref', function (done) {
<del> console.log();
<del> console.log('### Creating reference images');
<del>
<del> var PDF_BROWSERS = process.env['PDF_BROWSERS'] ||
<del> 'resources/browser_manifests/browser_manifest.json';
<del>
<del> if (!checkFile('test/' + PDF_BROWSERS)) {
<del> console.log('Browser manifest file test/' + PDF_BROWSERS +
<del> ' does not exist.');
<del> console.log('Copy and adjust the example in ' +
<del> 'test/resources/browser_manifests.');
<del> done(new Error('Missing manifest file'));
<del> return;
<del> }
<add>gulp.task('makeref', function (done) {
<add> makeRef(done);
<add>});
<ide>
<del> var args = ['test.js', '--masterMode', '--noPrompts',
<del> '--browserManifestFile=' + PDF_BROWSERS];
<del> var testProcess = spawn('node', args, {cwd: TEST_DIR, stdio: 'inherit'});
<del> testProcess.on('close', function (code) {
<del> done();
<del> });
<add>gulp.task('botmakeref', function (done) {
<add> makeRef(done, true);
<ide> });
<ide>
<ide> gulp.task('baseline', function (done) { | 1 |
Javascript | Javascript | address more of max's comments | 7ce5b000e448552bb4ba9556c8f38ccfef127162 | <ide><path>src/atom-environment.js
<ide> class AtomEnvironment {
<ide> this.config.resetUserSettings(userSettings)
<ide>
<ide> if (projectSettings != null && projectSettings.config != null) {
<add> console.log(projectSettings)
<ide> this.project.replace(projectSettings)
<ide> }
<ide>
<ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide> this.safeMode = options.safeMode
<ide> this.socketPath = options.socketPath
<ide> this.logFile = options.logFile
<del> this.projectSettings = options.projectSettings
<ide> this.userDataDir = options.userDataDir
<ide> this._killProcess = options.killProcess || process.kill.bind(process)
<ide> if (options.test || options.benchmark || options.benchmarkTest) this.socketPath = null
<ide><path>src/main-process/atom-window.js
<ide> class AtomWindow extends EventEmitter {
<ide> if (this.shouldHideTitleBar()) options.frame = false
<ide> this.browserWindow = new BrowserWindow(options)
<ide>
<del> if (this.atomApplication.projectSettings != null) {
<del> this.projectSettings = this.atomApplication.projectSettings
<del> }
<add> Object.defineProperty(this.browserWindow, 'loadSettingsJSON', {
<add> get: () => JSON.stringify(Object.assign({
<add> userSettings: this.atomApplication.configFile.get(),
<add> projectSettings: this.projectSettings
<add> }, this.loadSettings))
<add> })
<ide>
<del> this.loadDataOverProcessBoundary()
<ide> this.handleEvents()
<ide>
<ide> this.loadSettings = Object.assign({}, settings)
<ide> class AtomWindow extends EventEmitter {
<ide> return paths.every(p => this.containsPath(p))
<ide> }
<ide>
<del> loadDataOverProcessBoundary () {
<del> Object.defineProperty(this.browserWindow, 'loadSettingsJSON', {
<del> get: () => JSON.stringify(Object.assign({
<del> userSettings: this.atomApplication.configFile.get(),
<del> projectSettings: this.projectSettings
<del> }, this.loadSettings)),
<del> configurable: true
<del> })
<del> }
<del>
<ide> containsPath (pathToCheck) {
<ide> if (!pathToCheck) return false
<ide> let stat
<ide><path>src/main-process/parse-command-line.js
<ide> module.exports = function parseCommandLine (processArgs) {
<ide> 'When in test mode, waits until the specified time (in minutes) and kills the process (exit code: 130).'
<ide> )
<ide> options.alias('v', 'version').boolean('v').describe('v', 'Print the version information.')
<del> options.alias('p', 'atomproject').describe('p', 'Start atom with an atomproject file.')
<add> options.alias('p', 'project').describe('p', 'Start atom with an atomproject file.')
<ide> options.alias('w', 'wait').boolean('w').describe('w', 'Wait for window to be closed before returning.')
<ide> options.alias('a', 'add').boolean('a').describe('add', 'Open path as a new project in last used window.')
<ide> options.string('socket-path')
<ide> module.exports = function parseCommandLine (processArgs) {
<ide> const benchmark = args['benchmark']
<ide> const benchmarkTest = args['benchmark-test']
<ide> const test = args['test']
<del> const atomProject = args['atomproject']
<add> const atomProject = args['project']
<ide> const mainProcess = args['main-process']
<ide> const timeout = args['timeout']
<ide> const newWindow = args['new-window']
<ide> module.exports = function parseCommandLine (processArgs) {
<ide> const config = contents.config
<ide> const originPath = atomProject
<ide> const paths = contents.paths.map((curPath) =>
<del> relativizeToAtomProject(curPath, atomProject, executedFrom)
<del> )
<add> relativizeToAtomProject(curPath, path.dirname(path.join(executedFrom, atomProject))
<add> ))
<add> console.log(paths)
<ide> pathsToOpen.push(path.dirname(atomProject))
<ide> projectSettings = { originPath, paths, config }
<ide> }
<ide> module.exports = function parseCommandLine (processArgs) {
<ide> }
<ide>
<ide> const readProjectSettingsSync = (filepath, executedFrom) => {
<del> if (!hasAtomProjectFormat(path.basename(filepath))) {
<del> throw new Error('File must match format: *.atomproject.{json, cson}')
<del> }
<ide> try {
<ide> const readPath = path.isAbsolute(filepath) ? filepath : path.join(executedFrom, filepath)
<ide> const contents = CSON.readFileSync(readPath)
<ide> const readProjectSettingsSync = (filepath, executedFrom) => {
<ide> }
<ide> }
<ide>
<del>const hasAtomProjectFormat = (atomProject) => {
<del> const projectFileFormat = /.*\.atomproject\.(json|cson)/
<del> return projectFileFormat.test(atomProject)
<del>}
<del>
<del>const relativizeToAtomProject = (curPath, atomProject, executedFrom) => {
<del> const projectPath = path.isAbsolute(atomProject) ? atomProject : path.join(executedFrom, atomProject)
<del> return path.join(path.dirname(projectPath), curPath)
<add>const relativizeToAtomProject = (curPath, atomProject) => {
<add> return path.isAbsolute(curPath) ? curPath : path.join(atomProject, curPath)
<ide> }
<ide>
<ide> const normalizeDriveLetterName = (filePath) => { | 4 |
Ruby | Ruby | avoid range object creation | d3f8765482133df14d355f1763d3df1c883d2689 | <ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> def view_assigns
<ide> hash = {}
<ide> variables = instance_variable_names
<ide> variables -= protected_instance_variables if respond_to?(:protected_instance_variables)
<del> variables.each { |name| hash[name.to_s[1..-1]] = instance_variable_get(name) }
<add> variables.each { |name| hash[name.to_s[1, name.length]] = instance_variable_get(name) }
<ide> hash
<ide> end
<ide> | 1 |
Ruby | Ruby | ask the filename object for the prefix | 49a97c280a35fe07bce036467da85ace0c006fa7 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_file_outdated? f, file
<ide> bottle_ext && bottle_url_ext && bottle_ext != bottle_url_ext
<ide> end
<ide>
<del>def bottle_suffix revision
<del> revision = revision > 0 ? ".#{revision}" : ""
<del> ".bottle#{revision}.tar.gz"
<del>end
<del>
<ide> def bottle_native_regex
<ide> /(\.#{bottle_tag}\.bottle\.(\d+\.)?tar\.gz)$/o
<ide> end
<ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def bottle_formula f
<ide> puts output
<ide>
<ide> if ARGV.include? '--rb'
<del> bottle_base = filename.to_s.gsub(bottle_suffix(bottle_revision), '')
<del> File.open "#{bottle_base}.bottle.rb", 'w' do |file|
<del> file.write output
<del> end
<add> File.open("#{filename.prefix}.bottle.rb", "w") { |file| file.write(output) }
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/software_spec.rb
<ide> def initialize(name, version, tag, revision)
<ide> end
<ide>
<ide> def to_s
<del> "#{name}-#{version}.#{tag}#{bottle_suffix(revision)}"
<add> prefix + suffix
<ide> end
<ide> alias_method :to_str, :to_s
<add>
<add> def prefix
<add> "#{name}-#{version}.#{tag}"
<add> end
<add>
<add> def suffix
<add> s = revision > 0 ? ".#{revision}" : ""
<add> ".bottle#{s}.tar.gz"
<add> end
<ide> end
<ide>
<ide> extend Forwardable
<ide><path>Library/Homebrew/test/test_bottle_filename.rb
<ide> def fn(revision)
<ide> Bottle::Filename.new("foo", "1.0", :tag, revision)
<ide> end
<ide>
<add> def test_prefix_suffix
<add> assert_equal "foo-1.0.tag", fn(0).prefix
<add> assert_equal ".bottle.tar.gz", fn(0).suffix
<add> assert_equal ".bottle.1.tar.gz", fn(1).suffix
<add> end
<add>
<ide> def test_to_str
<ide> expected = "foo-1.0.tag.bottle.tar.gz"
<ide> assert_equal expected, fn(0).to_s | 4 |
Javascript | Javascript | remove usage of deprecated @flow weak in xplat | 6a039d7be36cbf29d6efa3b4b9557f4f19f878a4 | <ide><path>packages/rn-tester/js/examples/PanResponder/PanResponderExample.js
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<ide> * @format
<del> * @flow weak
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide> class PanResponderExample extends React.Component<Props, State> {
<ide> }}
<ide> style={[
<ide> styles.circle,
<add> // $FlowFixMe[incompatible-type]
<ide> {
<ide> translateX: this.state.left,
<ide> translateY: this.state.top, | 1 |
Javascript | Javascript | add a hint to a very common appregistry error | a6adc501e8902ce87b31917ea1d5299058c9aa7e | <ide><path>Libraries/ReactNative/AppRegistry.js
<ide> const AppRegistry = {
<ide> BugReporting.addSource('AppRegistry.runApplication' + runCount++, () => msg);
<ide> invariant(
<ide> runnables[appKey] && runnables[appKey].run,
<del> 'Application ' + appKey + ' has not been registered. This ' +
<del> 'is either due to a require() error during initialization ' +
<del> 'or failure to call AppRegistry.registerComponent.'
<add> 'Application ' + appKey + ' has not been registered.\n\n' +
<add> 'Hint: This error often happens when you\'re running the packager ' +
<add> '(local dev server) from a wrong folder. For example you have ' +
<add> 'multiple apps and the packager is still running for the app you ' +
<add> 'were working on before.\nIf this is the case, simply kill the old ' +
<add> 'packager instance (e.g. close the packager terminal window) ' +
<add> 'and start the packager in the correct app folder (e.g. cd into app ' +
<add> 'folder and run \'npm start\').\n\n' +
<add> 'This error can also happen due to a require() error during ' +
<add> 'initialization or failure to call AppRegistry.registerComponent.\n\n'
<ide> );
<ide> runnables[appKey].run(appParameters);
<ide> }, | 1 |
Ruby | Ruby | add protobuf to whitelist | 486a557cf527761d9b5a0cf54674f4d562c7bfcb | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> open-mpi
<ide> openssl@1.1
<ide> pcre
<add> protobuf
<ide> wolfssl
<ide> xz
<ide> ].include?(@formula_name) | 1 |
Ruby | Ruby | improve tokenization of version strings | 28acfbba51ea1e4e67365e5c9fa666d0c5ca9db5 | <ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_version_comparisons
<ide> assert_operator version('0.1'), :==, version('0.1.0')
<ide> assert_operator version('0.1'), :<, version('0.2')
<ide> assert_operator version('1.2.3'), :>, version('1.2.2')
<del> assert_operator version('1.2.3-p34'), :>, version('1.2.3-p33')
<ide> assert_operator version('1.2.4'), :<, version('1.2.4.1')
<add> end
<add>
<add> def test_patchlevel
<add> assert_operator version('1.2.3-p34'), :>, version('1.2.3-p33')
<add> assert_operator version('1.2.3-p33'), :<, version('1.2.3-p34')
<add> end
<add>
<add> def test_HEAD
<ide> assert_operator version('HEAD'), :>, version('1.2.3')
<ide> assert_operator version('1.2.3'), :<, version('HEAD')
<add> end
<add>
<add> def test_alpha_beta_rc
<ide> assert_operator version('3.2.0b4'), :<, version('3.2.0')
<ide> assert_operator version('1.0beta6'), :<, version('1.0b7')
<ide> assert_operator version('1.0b6'), :<, version('1.0beta7')
<ide> assert_operator version('1.1alpha4'), :<, version('1.1beta2')
<ide> assert_operator version('1.1beta2'), :<, version('1.1rc1')
<ide> assert_operator version('1.0.0beta7'), :<, version('1.0.0')
<ide> assert_operator version('3.2.1'), :>, version('3.2beta4')
<del> assert_nil version('1.0') <=> 'foo'
<ide> end
<ide>
<del> def test_version_queries
<del> assert Version.new("1.1alpha1").alpha?
<del> assert Version.new("1.0beta2").beta?
<del> assert Version.new("1.0rc-1").rc?
<add> def test_comparing_unevenly_padded_versions
<add> assert_operator version('2.1.0-p194'), :<, version('2.1-p195')
<add> assert_operator version('2.1-p195'), :>, version('2.1.0-p194')
<add> assert_operator version('2.1-p194'), :<, version('2.1.0-p195')
<add> assert_operator version('2.1.0-p195'), :>, version('2.1-p194')
<add> assert_operator version('2-p194'), :<, version('2.1-p195')
<add> end
<add>
<add> def test_comparison_returns_nil_for_non_version
<add> assert_nil version('1.0') <=> 'foo'
<ide> end
<ide>
<ide> def test_compare_patchlevel_to_non_patchlevel
<ide><path>Library/Homebrew/version.rb
<del>class VersionElement
<add>class Version
<ide> include Comparable
<ide>
<del> def initialize elem
<del> elem = elem.to_s.downcase
<del> @elem = case elem
<del> when /\d+/ then elem.to_i
<del> when 'a', 'alpha' then 'alpha'
<del> when 'b', 'beta' then 'beta'
<del> else elem
<del> end
<add> class Token
<add> include Comparable
<add>
<add> attr_reader :value
<add>
<add> def initialize(value)
<add> @value = value
<add> end
<add>
<add> def inspect
<add> "#<#{self.class} #{value.inspect}>"
<add> end
<ide> end
<ide>
<del> ZERO = VersionElement.new(0)
<add> class NullToken < Token
<add> def initialize(value=nil)
<add> super
<add> end
<ide>
<del> def <=>(other)
<del> return unless other.is_a? VersionElement
<del> return -1 if string? and other.numeric?
<del> return 1 if numeric? and other.string?
<del> return elem <=> other.elem
<add> def <=>(other)
<add> case other
<add> when NumericToken
<add> other.value == 0 ? 0 : -1
<add> when AlphaToken, BetaToken, RCToken
<add> 1
<add> else
<add> -1
<add> end
<add> end
<add>
<add> def inspect
<add> "#<#{self.class}>"
<add> end
<ide> end
<ide>
<del> def to_s
<del> @elem.to_s
<add> NULL_TOKEN = NullToken.new
<add>
<add> class StringToken < Token
<add> PATTERN = /[a-z]+[0-9]+/i
<add>
<add> def initialize(value)
<add> @value = value.to_s
<add> end
<add>
<add> def <=>(other)
<add> case other
<add> when StringToken
<add> value <=> other.value
<add> when NumericToken, NullToken
<add> -Integer(other <=> self)
<add> end
<add> end
<ide> end
<ide>
<del> protected
<add> class NumericToken < Token
<add> PATTERN = /[0-9]+/i
<ide>
<del> attr_reader :elem
<add> def initialize(value)
<add> @value = value.to_i
<add> end
<ide>
<del> def string?
<del> elem.is_a? String
<add> def <=>(other)
<add> case other
<add> when NumericToken
<add> value <=> other.value
<add> when StringToken
<add> 1
<add> when NullToken
<add> -Integer(other <=> self)
<add> end
<add> end
<ide> end
<ide>
<del> def numeric?
<del> elem.is_a? Numeric
<add> class CompositeToken < StringToken
<add> def rev
<add> value[/([0-9]+)/, 1]
<add> end
<ide> end
<del>end
<ide>
<del>class Version
<del> include Comparable
<add> class AlphaToken < CompositeToken
<add> PATTERN = /a(?:lpha)?[0-9]+/i
<ide>
<del> def initialize val, detected=false
<del> @version = val.to_s
<del> @detected_from_url = detected
<add> def <=>(other)
<add> case other
<add> when AlphaToken
<add> rev <=> other.rev
<add> else
<add> super
<add> end
<add> end
<ide> end
<ide>
<del> def detected_from_url?
<del> @detected_from_url
<add> class BetaToken < CompositeToken
<add> PATTERN = /b(?:eta)?[0-9]+/i
<add>
<add> def <=>(other)
<add> case other
<add> when BetaToken
<add> rev <=> other.rev
<add> when AlphaToken
<add> 1
<add> when RCToken, PatchToken
<add> -1
<add> else
<add> super
<add> end
<add> end
<ide> end
<ide>
<del> def head?
<del> @version == 'HEAD'
<add> class RCToken < CompositeToken
<add> PATTERN = /rc[0-9]+/i
<add>
<add> def <=>(other)
<add> case other
<add> when RCToken
<add> rev <=> other.rev
<add> when AlphaToken, BetaToken
<add> 1
<add> when PatchToken
<add> -1
<add> else
<add> super
<add> end
<add> end
<ide> end
<ide>
<del> def devel?
<del> alpha? or beta? or rc?
<add> class PatchToken < CompositeToken
<add> PATTERN = /p[0-9]+/i
<add>
<add> def <=>(other)
<add> case other
<add> when PatchToken
<add> rev <=> other.rev
<add> when AlphaToken, BetaToken, RCToken
<add> 1
<add> else
<add> super
<add> end
<add> end
<ide> end
<ide>
<del> def alpha?
<del> to_a.any? { |e| e.to_s == 'alpha' }
<add> def initialize(val, detected=false)
<add> @version = val.to_s
<add> @detected_from_url = detected
<ide> end
<ide>
<del> def beta?
<del> to_a.any? { |e| e.to_s == 'beta' }
<add> def detected_from_url?
<add> @detected_from_url
<ide> end
<ide>
<del> def rc?
<del> to_a.any? { |e| e.to_s == 'rc' }
<add> def head?
<add> @version == 'HEAD'
<ide> end
<ide>
<ide> def <=>(other)
<del> # Return nil if objects aren't comparable
<del> return unless other.is_a? Version
<del> # Versions are equal if both are HEAD
<del> return 0 if head? and other.head?
<del> # HEAD is greater than any numerical version
<del> return 1 if head? and not other.head?
<del> return -1 if not head? and other.head?
<del>
<del> stuple, otuple = to_a, other.to_a
<del> slen, olen = stuple.length, otuple.length
<add> return unless Version === other
<add> return 0 if head? && other.head?
<add> return 1 if head? && !other.head?
<add> return -1 if !head? && other.head?
<ide>
<del> max = [slen, olen].max
<del>
<del> stuple.fill(VersionElement::ZERO, slen, max - slen)
<del> otuple.fill(VersionElement::ZERO, olen, max - olen)
<del>
<del> stuple <=> otuple
<add> max = [tokens.length, other.tokens.length].max
<add> pad_to(max) <=> other.pad_to(max)
<ide> end
<ide>
<ide> def to_s
<ide> def to_s
<ide>
<ide> protected
<ide>
<del> def to_a
<del> @array ||= @version.scan(/\d+|[a-zA-Z]+/).map! { |e| VersionElement.new(e) }
<add> def pad_to(length)
<add> nums, rest = tokens.partition { |t| NumericToken === t }
<add> nums.concat([NULL_TOKEN]*(length - tokens.length)).concat(rest)
<add> end
<add>
<add> def tokens
<add> @tokens ||= tokenize
<add> end
<add> alias_method :to_a, :tokens
<add>
<add> def tokenize
<add> @version.scan(
<add> Regexp.union(
<add> AlphaToken::PATTERN,
<add> BetaToken::PATTERN,
<add> RCToken::PATTERN,
<add> PatchToken::PATTERN,
<add> NumericToken::PATTERN,
<add> StringToken::PATTERN
<add> )
<add> ).map! do |token|
<add> case token
<add> when /\A#{AlphaToken::PATTERN}\z/o then AlphaToken
<add> when /\A#{BetaToken::PATTERN}\z/o then BetaToken
<add> when /\A#{RCToken::PATTERN}\z/o then RCToken
<add> when /\A#{PatchToken::PATTERN}\z/o then PatchToken
<add> when /\A#{NumericToken::PATTERN}\z/o then NumericToken
<add> when /\A#{StringToken::PATTERN}\z/o then StringToken
<add> end.new(token)
<add> end
<ide> end
<ide>
<ide> def self.parse spec | 2 |
Ruby | Ruby | remove deprecate #calculate calls | 759d302db851754a73ec4c74e951f8a5faf2bee1 | <ide><path>activerecord/test/cases/associations/eager_test.rb
<ide> def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditi
<ide> end
<ide>
<ide> def test_count_eager_with_has_many_and_limit_and_high_offset
<del> posts = Post.count(:all, :include => [ :author, :comments ], :limit => 2, :offset => 10, :conditions => { 'authors.name' => 'David' })
<add> posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
<ide> assert_equal 0, posts
<ide> end
<ide>
<ide> def test_eager_with_has_many_and_limit_with_no_results
<del> posts = Post.find(:all, :include => [ :author, :comments ], :limit => 2, :conditions => "posts.title = 'magic forest'")
<add> posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").find(:all)
<ide> assert_equal 0, posts.size
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
<ide> def test_dynamic_find_should_respect_association_include
<ide> assert Category.find(1).posts_with_authors_sorted_by_author_id.find_by_title('Welcome to the weblog')
<ide> end
<ide>
<del> def test_counting_on_habtm_association_and_not_array
<del> david = Developer.find(1)
<del> # Extra parameter just to make sure we aren't falling back to
<del> # Array#count in Ruby >=1.8.7, which would raise an ArgumentError
<del> assert_nothing_raised { david.projects.count(:all, :conditions => '1=1') }
<del> end
<del>
<ide> def test_count
<ide> david = Developer.find(1)
<ide> assert_equal 2, david.projects.count
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_counting
<ide> assert_equal 2, Firm.find(:first, :order => "id").plain_clients.count
<ide> end
<ide>
<del> def test_counting_with_empty_hash_conditions
<del> assert_equal 2, Firm.find(:first, :order => "id").plain_clients.count(:conditions => {})
<del> end
<del>
<del> def test_counting_with_single_conditions
<del> assert_equal 1, Firm.find(:first, :order => "id").plain_clients.count(:conditions => ['name=?', "Microsoft"])
<del> end
<del>
<ide> def test_counting_with_single_hash
<del> assert_equal 1, Firm.find(:first, :order => "id").plain_clients.count(:conditions => {:name => "Microsoft"})
<add> assert_equal 1, Firm.find(:first, :order => "id").plain_clients.where(:name => "Microsoft").count
<ide> end
<ide>
<ide> def test_counting_with_column_name_and_hash
<ide><path>activerecord/test/cases/associations/has_many_through_associations_test.rb
<ide> def test_dynamic_find_should_respect_association_include
<ide> end
<ide>
<ide> def test_count_with_include_should_alias_join_table
<del> assert_equal 2, people(:michael).posts.count(:include => :readers)
<add> assert_equal 2, people(:michael).posts.includes(:readers).count
<ide> end
<ide>
<ide> def test_inner_join_with_quoted_table_name
<ide><path>activerecord/test/cases/associations/inner_join_association_test.rb
<ide> def test_find_with_implicit_inner_joins_does_not_set_associations
<ide>
<ide> def test_count_honors_implicit_inner_joins
<ide> real_count = Author.scoped.to_a.sum{|a| a.posts.count }
<del> assert_equal real_count, Author.count(:joins => :posts), "plain inner join count should match the number of referenced posts records"
<add> assert_equal real_count, Author.joins(:posts).count, "plain inner join count should match the number of referenced posts records"
<ide> end
<ide>
<ide> def test_calculate_honors_implicit_inner_joins
<ide> real_count = Author.scoped.to_a.sum{|a| a.posts.count }
<del> assert_equal real_count, Author.calculate(:count, 'authors.id', :joins => :posts), "plain inner join count should match the number of referenced posts records"
<add> assert_equal real_count, Author.joins(:posts).calculate(:count, 'authors.id'), "plain inner join count should match the number of referenced posts records"
<ide> end
<ide>
<ide> def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
<ide> real_count = Author.scoped.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
<del> authors_with_welcoming_post_titles = Author.calculate(:count, 'authors.id', :joins => :posts, :distinct => true, :conditions => "posts.title like 'Welcome%'")
<add> authors_with_welcoming_post_titles = Author.scoped(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
<ide> assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/join_model_test.rb
<ide> def test_has_many_uniq_through_count
<ide> assert !authors(:mary).unique_categorized_posts.loaded?
<ide> assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
<ide> assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
<del> assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
<add> assert_queries(1) { assert_equal 0, author.unique_categorized_posts.where(title: nil).count(:title) }
<ide> assert !authors(:mary).unique_categorized_posts.loaded?
<ide> end
<ide>
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_sequence_name_with_abstract_class
<ide> def test_count_with_join
<ide> res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
<ide>
<del> res2 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'", :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
<add> res2 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
<ide> assert_equal res, res2
<ide>
<ide> res3 = nil
<ide> assert_nothing_raised do
<del> res3 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'",
<del> :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
<add> res3 = Post.where("posts.#{QUOTED_TYPE} = 'Post'").joins("LEFT JOIN comments ON posts.id=comments.post_id").count
<ide> end
<ide> assert_equal res, res3
<ide>
<ide> res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
<ide> res5 = nil
<ide> assert_nothing_raised do
<del> res5 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
<del> :joins => "p, comments co",
<del> :select => "p.id")
<add> res5 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count
<ide> end
<ide>
<ide> assert_equal res4, res5
<ide>
<ide> res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
<ide> res7 = nil
<ide> assert_nothing_raised do
<del> res7 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
<del> :joins => "p, comments co",
<del> :select => "p.id",
<del> :distinct => true)
<add> res7 = Post.where("p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id").joins("p, comments co").select("p.id").count(distinct: true)
<ide> end
<ide> assert_equal res6, res7
<ide> end
<ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_should_get_minimum_of_field
<ide> end
<ide>
<ide> def test_should_group_by_field
<del> c = Account.sum(:credit_limit, :group => :firm_id)
<add> c = Account.group(:firm_id).sum(:credit_limit)
<ide> [1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
<ide> end
<ide>
<ide> def test_should_group_by_multiple_fields
<del> c = Account.count(:all, :group => ['firm_id', :credit_limit])
<add> c = Account.group('firm_id', :credit_limit).count(:all)
<ide> [ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
<ide> end
<ide>
<ide> def test_should_group_by_multiple_fields_having_functions
<ide> end
<ide>
<ide> def test_should_group_by_summed_field
<del> c = Account.sum(:credit_limit, :group => :firm_id)
<add> c = Account.group(:firm_id).sum(:credit_limit)
<ide> assert_equal 50, c[1]
<ide> assert_equal 105, c[6]
<ide> assert_equal 60, c[2]
<ide> end
<ide>
<ide> def test_should_order_by_grouped_field
<del> c = Account.sum(:credit_limit, :group => :firm_id, :order => "firm_id")
<add> c = Account.scoped(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
<ide> assert_equal [1, 2, 6, 9], c.keys.compact
<ide> end
<ide>
<ide> def test_should_order_by_calculation
<del> c = Account.sum(:credit_limit, :group => :firm_id, :order => "sum_credit_limit desc, firm_id")
<add> c = Account.scoped(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
<ide> assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
<ide> assert_equal [6, 2, 9, 1], c.keys.compact
<ide> end
<ide>
<ide> def test_should_limit_calculation
<del> c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
<del> :group => :firm_id, :order => "firm_id", :limit => 2)
<add> c = Account.scoped(:where => "firm_id IS NOT NULL",
<add> :group => :firm_id, :order => "firm_id", :limit => 2).sum(:credit_limit)
<ide> assert_equal [1, 2], c.keys.compact
<ide> end
<ide>
<ide> def test_should_limit_calculation_with_offset
<del> c = Account.sum(:credit_limit, :conditions => "firm_id IS NOT NULL",
<del> :group => :firm_id, :order => "firm_id", :limit => 2, :offset => 1)
<add> c = Account.scoped(:where => "firm_id IS NOT NULL", :group => :firm_id,
<add> :order => "firm_id", :limit => 2, :offset => 1).sum(:credit_limit)
<ide> assert_equal [2, 6], c.keys.compact
<ide> end
<ide>
<ide> def test_no_limit_no_offset
<ide> end
<ide>
<ide> def test_should_group_by_summed_field_having_condition
<del> c = Account.sum(:credit_limit, :group => :firm_id,
<del> :having => 'sum(credit_limit) > 50')
<del> assert_nil c[1]
<del> assert_equal 105, c[6]
<del> assert_equal 60, c[2]
<del> end
<del>
<del> def test_should_group_by_summed_field_having_sanitized_condition
<del> c = Account.sum(:credit_limit, :group => :firm_id,
<del> :having => ['sum(credit_limit) > ?', 50])
<add> c = Account.scoped(:group => :firm_id,
<add> :having => 'sum(credit_limit) > 50').sum(:credit_limit)
<ide> assert_nil c[1]
<ide> assert_equal 105, c[6]
<ide> assert_equal 60, c[2]
<ide> def test_should_group_by_summed_field_having_condition_from_select
<ide> end
<ide>
<ide> def test_should_group_by_summed_association
<del> c = Account.sum(:credit_limit, :group => :firm)
<add> c = Account.group(:firm).sum(:credit_limit)
<ide> assert_equal 50, c[companies(:first_firm)]
<ide> assert_equal 105, c[companies(:rails_core)]
<ide> assert_equal 60, c[companies(:first_client)]
<ide> end
<ide>
<ide> def test_should_sum_field_with_conditions
<del> assert_equal 105, Account.sum(:credit_limit, :conditions => 'firm_id = 6')
<add> assert_equal 105, Account.where('firm_id = 6').sum(:credit_limit)
<ide> end
<ide>
<ide> def test_should_return_zero_if_sum_conditions_return_nothing
<del> assert_equal 0, Account.sum(:credit_limit, :conditions => '1 = 2')
<del> assert_equal 0, companies(:rails_core).companies.sum(:id, :conditions => '1 = 2')
<add> assert_equal 0, Account.where('1 = 2').sum(:credit_limit)
<add> assert_equal 0, companies(:rails_core).companies.where('1 = 2').sum(:id)
<ide> end
<ide>
<ide> def test_sum_should_return_valid_values_for_decimals
<ide> def test_sum_should_return_valid_values_for_decimals
<ide> end
<ide>
<ide> def test_should_group_by_summed_field_with_conditions
<del> c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
<del> :group => :firm_id)
<add> c = Account.scoped(:where => 'firm_id > 1',
<add> :group => :firm_id).sum(:credit_limit)
<ide> assert_nil c[1]
<ide> assert_equal 105, c[6]
<ide> assert_equal 60, c[2]
<ide> end
<ide>
<ide> def test_should_group_by_summed_field_with_conditions_and_having
<del> c = Account.sum(:credit_limit, :conditions => 'firm_id > 1',
<del> :group => :firm_id,
<del> :having => 'sum(credit_limit) > 60')
<add> c = Account.scoped(:where => 'firm_id > 1',
<add> :group => :firm_id,
<add> :having => 'sum(credit_limit) > 60').sum(:credit_limit)
<ide> assert_nil c[1]
<ide> assert_equal 105, c[6]
<ide> assert_nil c[2]
<ide> end
<ide>
<ide> def test_should_group_by_fields_with_table_alias
<del> c = Account.sum(:credit_limit, :group => 'accounts.firm_id')
<add> c = Account.group('accounts.firm_id').sum(:credit_limit)
<ide> assert_equal 50, c[1]
<ide> assert_equal 105, c[6]
<ide> assert_equal 60, c[2]
<ide> def test_should_calculate_with_invalid_field
<ide> end
<ide>
<ide> def test_should_calculate_grouped_with_invalid_field
<del> c = Account.count(:all, :group => 'accounts.firm_id')
<add> c = Account.group('accounts.firm_id').count(:all)
<ide> assert_equal 1, c[1]
<ide> assert_equal 2, c[6]
<ide> assert_equal 1, c[2]
<ide> end
<ide>
<ide> def test_should_calculate_grouped_association_with_invalid_field
<del> c = Account.count(:all, :group => :firm)
<add> c = Account.group(:firm).count(:all)
<ide> assert_equal 1, c[companies(:first_firm)]
<ide> assert_equal 2, c[companies(:rails_core)]
<ide> assert_equal 1, c[companies(:first_client)]
<ide> def test_should_group_by_association_with_non_numeric_foreign_key
<ide> column.expects(:type_cast).with("ABC").returns("ABC")
<ide> Account.expects(:columns).at_least_once.returns([column])
<ide>
<del> c = Account.count(:all, :group => :firm)
<add> c = Account.group(:firm).count(:all)
<ide> first_key = c.keys.first
<ide> assert_equal Firm, first_key.class
<ide> assert_equal 1, c[first_key]
<ide> end
<ide>
<ide> def test_should_calculate_grouped_association_with_foreign_key_option
<ide> Account.belongs_to :another_firm, :class_name => 'Firm', :foreign_key => 'firm_id'
<del> c = Account.count(:all, :group => :another_firm)
<add> c = Account.group(:another_firm).count(:all)
<ide> assert_equal 1, c[companies(:first_firm)]
<ide> assert_equal 2, c[companies(:rails_core)]
<ide> assert_equal 1, c[companies(:first_client)]
<ide> end
<ide>
<del> def test_should_not_modify_options_when_using_includes
<del> options = {:conditions => 'companies.id > 1', :include => :firm}
<del> options_copy = options.dup
<del>
<del> Account.references(:companies).count(:all, options)
<del> assert_equal options_copy, options
<del> end
<del>
<ide> def test_should_calculate_grouped_by_function
<del> c = Company.count(:all, :group => "UPPER(#{QUOTED_TYPE})")
<add> c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
<ide> assert_equal 2, c[nil]
<ide> assert_equal 1, c['DEPENDENTFIRM']
<ide> assert_equal 4, c['CLIENT']
<ide> assert_equal 2, c['FIRM']
<ide> end
<ide>
<ide> def test_should_calculate_grouped_by_function_with_table_alias
<del> c = Company.count(:all, :group => "UPPER(companies.#{QUOTED_TYPE})")
<add> c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
<ide> assert_equal 2, c[nil]
<ide> assert_equal 1, c['DEPENDENTFIRM']
<ide> assert_equal 4, c['CLIENT']
<ide> def test_should_sum_scoped_field_with_from
<ide> end
<ide>
<ide> def test_should_sum_scoped_field_with_conditions
<del> assert_equal 8, companies(:rails_core).companies.sum(:id, :conditions => 'id > 7')
<add> assert_equal 8, companies(:rails_core).companies.where('id > 7').sum(:id)
<ide> end
<ide>
<ide> def test_should_group_by_scoped_field
<del> c = companies(:rails_core).companies.sum(:id, :group => :name)
<add> c = companies(:rails_core).companies.group(:name).sum(:id)
<ide> assert_equal 7, c['Leetsoft']
<ide> assert_equal 8, c['Jadedpixel']
<ide> end
<ide>
<ide> def test_should_group_by_summed_field_through_association_and_having
<del> c = companies(:rails_core).companies.sum(:id, :group => :name,
<del> :having => 'sum(id) > 7')
<add> c = companies(:rails_core).companies.group(:name).having('sum(id) > 7').sum(:id)
<ide> assert_nil c['Leetsoft']
<ide> assert_equal 8, c['Jadedpixel']
<ide> end
<ide>
<ide> def test_should_count_selected_field_with_include
<del> assert_equal 6, Account.count(:distinct => true, :include => :firm)
<del> assert_equal 4, Account.count(:distinct => true, :include => :firm, :select => :credit_limit)
<add> assert_equal 6, Account.includes(:firm).count(:distinct => true)
<add> assert_equal 4, Account.includes(:firm).select(:credit_limit).count(:distinct => true)
<ide> end
<ide>
<ide> def test_should_not_perform_joined_include_by_default
<ide> def test_should_count_scoped_select_with_options
<ide> Account.last.update_column('credit_limit', 49)
<ide> Account.first.update_column('credit_limit', 51)
<ide>
<del> assert_equal 1, Account.scoped(:select => "credit_limit").count(:conditions => ['credit_limit >= 50'])
<add> assert_equal 1, Account.scoped(:select => "credit_limit").where('credit_limit >= 50').count
<ide> end
<ide>
<ide> def test_should_count_manual_select_with_include
<del> assert_equal 6, Account.count(:select => "DISTINCT accounts.id", :include => :firm)
<add> assert_equal 6, Account.scoped(:select => "DISTINCT accounts.id", :includes => :firm).count
<ide> end
<ide>
<ide> def test_count_with_column_parameter
<ide> assert_equal 5, Account.count(:firm_id)
<ide> end
<ide>
<ide> def test_count_with_column_and_options_parameter
<del> assert_equal 2, Account.count(:firm_id, :conditions => "credit_limit = 50 AND firm_id IS NOT NULL")
<add> assert_equal 2, Account.where("credit_limit = 50 AND firm_id IS NOT NULL").count(:firm_id)
<ide> end
<ide>
<ide> def test_should_count_field_in_joined_table
<del> assert_equal 5, Account.count('companies.id', :joins => :firm)
<del> assert_equal 4, Account.count('companies.id', :joins => :firm, :distinct => true)
<add> assert_equal 5, Account.joins(:firm).count('companies.id')
<add> assert_equal 4, Account.joins(:firm).count('companies.id', :distinct => true)
<ide> end
<ide>
<ide> def test_should_count_field_in_joined_table_with_group_by
<del> c = Account.count('companies.id', :group => 'accounts.firm_id', :joins => :firm)
<add> c = Account.scoped(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
<ide>
<ide> [1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
<ide> end
<ide> def test_should_sum_expression
<ide> end
<ide>
<ide> def test_count_with_from_option
<del> assert_equal Company.count(:all), Company.count(:all, :from => 'companies')
<del> assert_equal Account.count(:all, :conditions => "credit_limit = 50"),
<del> Account.count(:all, :from => 'accounts', :conditions => "credit_limit = 50")
<del> assert_equal Company.count(:type, :conditions => {:type => "Firm"}),
<del> Company.count(:type, :conditions => {:type => "Firm"}, :from => 'companies')
<add> assert_equal Company.count(:all), Company.from('companies').count(:all)
<add> assert_equal Account.where("credit_limit = 50").count(:all),
<add> Account.from('accounts').where("credit_limit = 50").count(:all)
<add> assert_equal Company.where(:type => "Firm").count(:type),
<add> Company.where(:type => "Firm").from('companies').count(:type)
<ide> end
<ide>
<ide> def test_sum_with_from_option
<del> assert_equal Account.sum(:credit_limit), Account.sum(:credit_limit, :from => 'accounts')
<del> assert_equal Account.sum(:credit_limit, :conditions => "credit_limit > 50"),
<del> Account.sum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
<add> assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit)
<add> assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
<add> Account.where("credit_limit > 50").from('accounts').sum(:credit_limit)
<ide> end
<ide>
<ide> def test_sum_array_compatibility
<ide> assert_equal Account.sum(:credit_limit), Account.sum(&:credit_limit)
<ide> end
<ide>
<ide> def test_average_with_from_option
<del> assert_equal Account.average(:credit_limit), Account.average(:credit_limit, :from => 'accounts')
<del> assert_equal Account.average(:credit_limit, :conditions => "credit_limit > 50"),
<del> Account.average(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
<add> assert_equal Account.average(:credit_limit), Account.from('accounts').average(:credit_limit)
<add> assert_equal Account.where("credit_limit > 50").average(:credit_limit),
<add> Account.where("credit_limit > 50").from('accounts').average(:credit_limit)
<ide> end
<ide>
<ide> def test_minimum_with_from_option
<del> assert_equal Account.minimum(:credit_limit), Account.minimum(:credit_limit, :from => 'accounts')
<del> assert_equal Account.minimum(:credit_limit, :conditions => "credit_limit > 50"),
<del> Account.minimum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
<add> assert_equal Account.minimum(:credit_limit), Account.from('accounts').minimum(:credit_limit)
<add> assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
<add> Account.where("credit_limit > 50").from('accounts').minimum(:credit_limit)
<ide> end
<ide>
<ide> def test_maximum_with_from_option
<del> assert_equal Account.maximum(:credit_limit), Account.maximum(:credit_limit, :from => 'accounts')
<del> assert_equal Account.maximum(:credit_limit, :conditions => "credit_limit > 50"),
<del> Account.maximum(:credit_limit, :from => 'accounts', :conditions => "credit_limit > 50")
<add> assert_equal Account.maximum(:credit_limit), Account.from('accounts').maximum(:credit_limit)
<add> assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
<add> Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
<ide> end
<ide>
<ide> def test_from_option_with_specified_index
<ide> if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
<del> assert_equal Edge.count(:all), Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)')
<del> assert_equal Edge.count(:all, :conditions => 'sink_id < 5'),
<del> Edge.count(:all, :from => 'edges USE INDEX(unique_edge_index)', :conditions => 'sink_id < 5')
<add> assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
<add> assert_equal Edge.where('sink_id < 5').count(:all),
<add> Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
<ide> end
<ide> end
<ide>
<ide> def test_from_option_with_table_different_than_class
<del> assert_equal Account.count(:all), Company.count(:all, :from => 'accounts')
<add> assert_equal Account.count(:all), Company.from('accounts').count(:all)
<ide> end
<ide>
<ide> def test_distinct_is_honored_when_used_with_count_operation_after_group
<ide><path>activerecord/test/cases/deprecated_finder_test.rb
<del>require "cases/helper"
<del>require 'models/entrant'
<del>
<del>class DeprecatedFinderTest < ActiveRecord::TestCase
<del> fixtures :entrants
<del>
<del> def test_deprecated_find_all_was_removed
<del> assert_raise(NoMethodError) { Entrant.find_all }
<del> end
<del>
<del> def test_deprecated_find_first_was_removed
<del> assert_raise(NoMethodError) { Entrant.find_first }
<del> end
<del>
<del> def test_deprecated_find_on_conditions_was_removed
<del> assert_raise(NoMethodError) { Entrant.find_on_conditions }
<del> end
<del>
<del> def test_count
<del> assert_equal(0, Entrant.count(:conditions => "id > 3"))
<del> assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
<del> assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
<del> end
<del>
<del> def test_count_by_sql
<del> assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
<del> assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
<del> assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
<del> end
<del>end
<ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_string_sanitation
<ide> assert_equal "'something; select table'", ActiveRecord::Base.sanitize("something; select table")
<ide> end
<ide>
<del> def test_count
<del> assert_equal(0, Entrant.count(:conditions => "id > 3"))
<del> assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
<del> assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
<del> end
<del>
<ide> def test_count_by_sql
<ide> assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
<ide> assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
<ide><path>activerecord/test/cases/named_scope_test.rb
<ide> def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specifie
<ide> assert !Topic.find(:all, :conditions => {:approved => true}).empty?
<ide>
<ide> assert_equal Topic.find(:all, :conditions => {:approved => true}), Topic.approved
<del> assert_equal Topic.count(:conditions => {:approved => true}), Topic.approved.count
<add> assert_equal Topic.where(:approved => true).count, Topic.approved.count
<ide> end
<ide>
<ide> def test_scopes_with_string_name_can_be_composed | 11 |
Python | Python | move comment outside of try/except | 8922a6e025d53d5aaccba02b76dbef5a43afe768 | <ide><path>numpy/polynomial/_polybase.py
<ide> def _generate_string(self, term_method):
<ide> out += " "
<ide> power = str(i + 1)
<ide> # Polynomial coefficient
<add> # The coefficient array can be an object array with elements that
<add> # will raise a TypeError with >= 0 (e.g. strings or Python
<add> # complex). In this case, represent the coeficient as-is.
<ide> try:
<ide> if coef >= 0:
<ide> next_term = f"+ {coef}"
<ide> else:
<ide> next_term = f"- {-coef}"
<del> # The coefficient array can be an object array with elements that
<del> # will raise a TypeError with >= 0 (e.g. strings or Python
<del> # complex). In this case, represent the coeficient as-is.
<ide> except TypeError:
<ide> next_term = f"+ {coef}"
<ide> # Polynomial term | 1 |
Python | Python | fix typo in cli.py | e3c853e60401bccf1564bee19dda7a3b41602ff9 | <ide><path>flask/cli.py
<ide> def shell_command():
<ide> namespace of this shell according to it's configuration.
<ide>
<ide> This is useful for executing small snippets of management code
<del> without having to manually configuring the application.
<add> without having to manually configure the application.
<ide> """
<ide> import code
<ide> from flask.globals import _app_ctx_stack | 1 |
Javascript | Javascript | add test for no-primitive-constructors rule | 7d5cc2eee3aec0ec3871c56cee9ba7cc8744fcd8 | <ide><path>eslint-rules/__tests__/no-primitive-constructors-test.js
<add>/**
<add> * Copyright 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @emails react-core
<add> */
<add>
<add>'use strict';
<add>
<add>var rule = require('../no-primitive-constructors');
<add>var RuleTester = require('eslint').RuleTester;
<add>var ruleTester = new RuleTester();
<add>
<add>ruleTester.run('eslint-rules/no-primitive-constructors', rule, {
<add> valid: [
<add> '!!obj',
<add> "'' + obj",
<add> '+string',
<add> ],
<add> invalid: [
<add> {
<add> code: 'Boolean(obj)',
<add> errors: [
<add> {
<add> message: 'Do not use the Boolean constructor. To cast a value to a boolean, use double negation: !!value',
<add> },
<add> ],
<add> },
<add> {
<add> code: 'String(obj)',
<add> errors: [
<add> {
<add> message: 'Do not use the String constructor. To cast a value to a string, concat it with the empty string (unless it\'s a symbol, which has different semantics): \'\' + value',
<add> },
<add> ],
<add> },
<add> {
<add> code: 'Number(string)',
<add> errors: [
<add> {
<add> message: 'Do not use the Number constructor. To cast a value to a number, use the plus operator: +value',
<add> },
<add> ],
<add> },
<add> ],
<add>});
<ide><path>eslint-rules/no-primitive-constructors.js
<ide> module.exports = function(context) {
<ide> node,
<ide> name,
<ide> 'To cast a value to a string, concat it with the empty string ' +
<del> '(unless it\'s a symbol, which have different semantics): ' +
<add> '(unless it\'s a symbol, which has different semantics): ' +
<ide> '\'\' + value'
<ide> );
<ide> break; | 2 |
Javascript | Javascript | improve code coverage for streams/duplexify | 0185464352353e87cd79f27347003e35b781d031 | <ide><path>test/parallel/test-stream-duplex-from.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const { Duplex, Readable, Writable, pipeline } = require('stream');
<add>const { Blob } = require('buffer');
<ide>
<ide> {
<ide> const d = Duplex.from({
<ide> const { Duplex, Readable, Writable, pipeline } = require('stream');
<ide> common.mustCall(() => {}),
<ide> );
<ide> }
<add>
<add>// Ensure that isDuplexNodeStream was called
<add>{
<add> const duplex = new Duplex();
<add> assert.strictEqual(Duplex.from(duplex), duplex);
<add>}
<add>
<add>// Ensure that Duplex.from works for blobs
<add>{
<add> const blob = new Blob(['blob']);
<add> const expecteByteLength = blob.size;
<add> const duplex = Duplex.from(blob);
<add> duplex.on('data', common.mustCall((arrayBuffer) => {
<add> assert.strictEqual(arrayBuffer.byteLength, expecteByteLength);
<add> }));
<add>}
<add>
<add>// Ensure that given a promise rejection it emits an error
<add>{
<add> const myErrorMessage = 'myCustomError';
<add> Duplex.from(Promise.reject(myErrorMessage))
<add> .on('error', common.mustCall((error) => {
<add> assert.strictEqual(error, myErrorMessage);
<add> }));
<add>}
<add>
<add>// Ensure that given a promise rejection on an async function it emits an error
<add>{
<add> const myErrorMessage = 'myCustomError';
<add> async function asyncFn() {
<add> return Promise.reject(myErrorMessage);
<add> }
<add>
<add> Duplex.from(asyncFn)
<add> .on('error', common.mustCall((error) => {
<add> assert.strictEqual(error, myErrorMessage);
<add> }));
<add>}
<add>
<add>// Ensure that Duplex.from throws an Invalid return value when function is void
<add>{
<add> assert.throws(() => Duplex.from(() => {}), {
<add> code: 'ERR_INVALID_RETURN_VALUE',
<add> });
<add>}
<add>
<add>// Ensure data if a sub object has a readable stream it's duplexified
<add>{
<add> const msg = Buffer.from('hello');
<add> const duplex = Duplex.from({
<add> readable: Readable({
<add> read() {
<add> this.push(msg);
<add> this.push(null);
<add> }
<add> })
<add> }).on('data', common.mustCall((data) => {
<add> assert.strictEqual(data, msg);
<add> }));
<add>
<add> assert.strictEqual(duplex.writable, false);
<add>}
<add>
<add>// Ensure data if a sub object has a writable stream it's duplexified
<add>{
<add> const msg = Buffer.from('hello');
<add> const duplex = Duplex.from({
<add> writable: Writable({
<add> write: common.mustCall((data) => {
<add> assert.strictEqual(data, msg);
<add> })
<add> })
<add> });
<add>
<add> duplex.write(msg);
<add> assert.strictEqual(duplex.readable, false);
<add>}
<add>
<add>// Ensure data if a sub object has a writable and readable stream it's duplexified
<add>{
<add> const msg = Buffer.from('hello');
<add>
<add> const duplex = Duplex.from({
<add> readable: Readable({
<add> read() {
<add> this.push(msg);
<add> this.push(null);
<add> }
<add> }),
<add> writable: Writable({
<add> write: common.mustCall((data) => {
<add> assert.strictEqual(data, msg);
<add> })
<add> })
<add> });
<add>
<add> duplex.pipe(duplex)
<add> .on('data', common.mustCall((data) => {
<add> assert.strictEqual(data, msg);
<add> assert.strictEqual(duplex.readable, true);
<add> assert.strictEqual(duplex.writable, true);
<add> }))
<add> .on('end', common.mustCall());
<add>}
<add>
<add>// Ensure that given readable stream that throws an error it calls destroy
<add>{
<add> const myErrorMessage = 'error!';
<add> const duplex = Duplex.from(Readable({
<add> read() {
<add> throw new Error(myErrorMessage);
<add> }
<add> }));
<add> duplex.on('error', common.mustCall((msg) => {
<add> assert.strictEqual(msg.message, myErrorMessage);
<add> }));
<add>}
<add>
<add>// Ensure that given writable stream that throws an error it calls destroy
<add>{
<add> const myErrorMessage = 'error!';
<add> const duplex = Duplex.from(Writable({
<add> write(chunk, enc, cb) {
<add> cb(myErrorMessage);
<add> }
<add> }));
<add>
<add> duplex.on('error', common.mustCall((msg) => {
<add> assert.strictEqual(msg, myErrorMessage);
<add> }));
<add>
<add> duplex.write('test');
<add>} | 1 |
Text | Text | clarify instructions for catphotoapp step 6 | 85a110e2642eee73f94b450ddf5ddff9c13854db | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc23991f86c76b9248c6eb8.md
<ide> dashedName: step-6
<ide>
<ide> # --description--
<ide>
<del>In the previous step, you nested the `h2` element, comment, and `p` element within the `main` element. Indenting nested elements two more spaces than their parent element improves readability:
<add>In the previous step, you put the `h2`, comment, and `p` elements inside the `main` element. This is called *nesting*. Nested elements should be placed two spaces further to the right of the element they are nested in. This spacing is called indentation and it is used to make HTML easier to read.
<ide>
<del>```html
<del><ul>
<del> <li> This `li` element indented </li>
<del> <li> This `li` element is also indented </li>
<del></ul>
<del>```
<del>
<del>Add two more spaces in front of the `h2`, comment, and `p` elements so your HTML is more readable.
<add>The `h2` element and the comment are indented two spaces more than the `main` element in the code below. Use the space bar on your keyboard to add two more spaces in front of the `p` element so that it is indented properly as well.
<ide>
<ide> # --hints--
<ide>
<ide> assert(code.toLowerCase().match(/-->\n\s{6}<p>/));
<ide> <h1>CatPhotoApp</h1>
<ide> --fcc-editable-region--
<ide> <main>
<del> <h2>Cat Photos</h2>
<del> <!-- TODO: Add link to cat photos -->
<add> <h2>Cat Photos</h2>
<add> <!-- TODO: Add link to cat photos -->
<ide> <p>Click here to view more cat photos.</p>
<ide> </main>
<ide> --fcc-editable-region-- | 1 |
Text | Text | improve security doc | e704dd31e79114a2156c4fdda3247a181ad6435d | <ide><path>docs/sources/articles/security.md
<ide> page_keywords: Docker, Docker documentation, security
<ide>
<ide> # Docker Security
<ide>
<del>> *Adapted from* [Containers & Docker: How Secure are
<del>> They?](http://blog.docker.com/2013/08/containers-docker-how-secure-are-they/)
<del>
<ide> There are three major areas to consider when reviewing Docker security:
<ide>
<del> - the intrinsic security of containers, as implemented by kernel
<add> - the intrinsic security of the kernel and its support for
<ide> namespaces and cgroups;
<ide> - the attack surface of the Docker daemon itself;
<add> - loopholes in the container configuration profile, either by default,
<add> or when customized by users.
<ide> - the "hardening" security features of the kernel and how they
<ide> interact with containers.
<ide>
<ide> ## Kernel Namespaces
<ide>
<del>Docker containers are very similar to LXC containers, and they come with
<del>the similar security features. When you start a container with `docker
<add>Docker containers are very similar to LXC containers, and they have
<add>similar security features. When you start a container with `docker
<ide> run`, behind the scenes Docker creates a set of namespaces and control
<ide> groups for the container.
<ide>
<ide> less affect, processes running in another container, or in the host
<ide> system.
<ide>
<ide> **Each container also gets its own network stack**, meaning that a
<del>container doesn't get a privileged access to the sockets or interfaces
<add>container doesn't get privileged access to the sockets or interfaces
<ide> of another container. Of course, if the host system is setup
<ide> accordingly, containers can interact with each other through their
<ide> respective network interfaces — just like they can interact with
<ide> in 2005, so both the design and the implementation are pretty mature.
<ide>
<ide> ## Control Groups
<ide>
<del>Control Groups are the other key component of Linux Containers. They
<del>implement resource accounting and limiting. They provide a lot of very
<del>useful metrics, but they also help to ensure that each container gets
<add>Control Groups are another key component of Linux Containers. They
<add>implement resource accounting and limiting. They provide many
<add>useful metrics, but they also help ensure that each container gets
<ide> its fair share of memory, CPU, disk I/O; and, more importantly, that a
<ide> single container cannot bring the system down by exhausting one of those
<ide> resources.
<ide> the Docker host and a guest container; and it allows you to do so
<ide> without limiting the access rights of the container. This means that you
<ide> can start a container where the `/host` directory will be the `/` directory
<ide> on your host; and the container will be able to alter your host filesystem
<del>without any restriction. This sounds crazy? Well, you have to know that
<del>**all virtualization systems allowing filesystem resource sharing behave the
<del>same way**. Nothing prevents you from sharing your root filesystem (or
<del>even your root block device) with a virtual machine.
<add>without any restriction. This is similar to how virtualization systems
<add>allow filesystem resource sharing. Nothing prevents you from sharing your
<add>root filesystem (or even your root block device) with a virtual machine.
<ide>
<ide> This has a strong security implication: for example, if you instrument Docker
<ide> from a web server to provision containers through an API, you should be
<ide> trusted network or VPN; or protected with e.g., `stunnel` and client SSL
<ide> certificates. You can also secure them with [HTTPS and
<ide> certificates](/articles/https/).
<ide>
<del>Recent improvements in Linux namespaces will soon allow to run
<del>full-featured containers without root privileges, thanks to the new user
<del>namespace. This is covered in detail [here](
<del>http://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/).
<del>Moreover, this will solve the problem caused by sharing filesystems
<del>between host and guest, since the user namespace allows users within
<del>containers (including the root user) to be mapped to other users in the
<del>host system.
<del>
<del>The end goal for Docker is therefore to implement two additional
<del>security improvements:
<del>
<del> - map the root user of a container to a non-root user of the Docker
<del> host, to mitigate the effects of a container-to-host privilege
<del> escalation;
<del> - allow the Docker daemon to run without root privileges, and delegate
<del> operations requiring those privileges to well-audited sub-processes,
<del> each with its own (very limited) scope: virtual network setup,
<del> filesystem management, etc.
<add>The daemon is also potentially vulnerable to other inputs, such as image
<add>loading from either disk with 'docker load', or from the network with
<add>'docker pull'. This has been a focus of improvement in the community,
<add>especially for 'pull' security. While these overlap, it should be noted
<add>that 'docker load' is a mechanism for backup and restore and is not
<add>currently considered a secure mechanism for loading images. As of
<add>Docker 1.3.2, images are now extracted in a chrooted subprocess on
<add>Linux/Unix platforms, being the first-step in a wider effort toward
<add>privilege separation.
<add>
<add>Eventually, it is expected that the Docker daemon will run restricted
<add>privileges, delegating operations well-audited sub-processes,
<add>each with its own (very limited) scope of Linux capabilities,
<add>virtual network setup, filesystem management, etc. That is, most likely,
<add>pieces of the Docker engine itself will run inside of containers.
<ide>
<ide> Finally, if you run Docker on a server, it is recommended to run
<ide> exclusively Docker in the server, and move all other services within
<ide> existing monitoring/supervision processes (e.g., NRPE, collectd, etc).
<ide>
<ide> ## Linux Kernel Capabilities
<ide>
<del>By default, Docker starts containers with a very restricted set of
<add>By default, Docker starts containers with a restricted set of
<ide> capabilities. What does that mean?
<ide>
<ide> Capabilities turn the binary "root/non-root" dichotomy into a
<ide> tools (e.g., to handle DHCP, WPA, or VPNs), and much more. A container is
<ide> very different, because almost all of those tasks are handled by the
<ide> infrastructure around the container:
<ide>
<del> - SSH access will typically be managed by a single server running in
<add> - SSH access will typically be managed by a single server running on
<ide> the Docker host;
<ide> - `cron`, when necessary, should run as a user
<ide> process, dedicated and tailored for the app that needs its
<ide> a whitelist instead of a blacklist approach. You can see a full list of
<ide> available capabilities in [Linux
<ide> manpages](http://man7.org/linux/man-pages/man7/capabilities.7.html).
<ide>
<del>Of course, you can always enable extra capabilities if you really need
<del>them (for instance, if you want to use a FUSE-based filesystem), but by
<del>default, Docker containers use only a
<del>[whitelist](https://github.com/docker/docker/blob/master/daemon/execdriver/native/template/default_template.go)
<del>of kernel capabilities by default.
<add>One primary risk with running Docker containers is that the default set
<add>of capabilities and mounts given to a container may provide incomplete
<add>isolation, either independently, or when used in combination with
<add>kernel vulnerabilities.
<add>
<add>Docker supports the addition and removal of capabilities, allowing use
<add>of a non-default profile. This may make Docker more secure through
<add>capability removal, or less secure through the addition of capabilities.
<add>The best practice for users would be to remove all capabilities except
<add>those explicitly required for their processes.
<ide>
<ide> ## Other Kernel Security Features
<ide>
<ide> harden a Docker host. Here are a few examples.
<ide> checks, both at compile-time and run-time; it will also defeat many
<ide> exploits, thanks to techniques like address randomization. It doesn't
<ide> require Docker-specific configuration, since those security features
<del> apply system-wide, independently of containers.
<add> apply system-wide, independent of containers.
<ide> - If your distribution comes with security model templates for
<ide> Docker containers, you can use them out of the box. For instance, we
<ide> ship a template that works with AppArmor and Red Hat comes with SELinux
<ide> with e.g., special network topologies or shared filesystems, you can
<ide> expect to see tools to harden existing Docker containers without
<ide> affecting Docker's core.
<ide>
<add>Recent improvements in Linux namespaces will soon allow to run
<add>full-featured containers without root privileges, thanks to the new user
<add>namespace. This is covered in detail [here](
<add>http://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/).
<add>Moreover, this will solve the problem caused by sharing filesystems
<add>between host and guest, since the user namespace allows users within
<add>containers (including the root user) to be mapped to other users in the
<add>host system.
<add>
<add>Today, Docker does not directly support user namespaces, but they
<add>may still be utilized by Docker containers on supported kernels,
<add>by directly using the clone syscall, or utilizing the 'unshare'
<add>utility. Using this, some users may find it possible to drop
<add>more capabilities from their process as user namespaces provide
<add>an artifical capabilities set. Likewise, however, this artifical
<add>capabilities set may require use of 'capsh' to restrict the
<add>user-namespace capabilities set when using 'unshare'.
<add>
<add>Eventually, it is expected that Docker will direct, native support
<add>for user-namespaces, simplifying the process of hardening containers.
<add>
<ide> ## Conclusions
<ide>
<ide> Docker containers are, by default, quite secure; especially if you take
<ide> You can add an extra layer of safety by enabling Apparmor, SELinux,
<ide> GRSEC, or your favorite hardening solution.
<ide>
<ide> Last but not least, if you see interesting security features in other
<del>containerization systems, you will be able to implement them as well
<del>with Docker, since everything is provided by the kernel anyway.
<add>containerization systems, these are simply kernels features that may
<add>be implemented in Docker as well. We welcome users to submit issues,
<add>pull requests, and communicate via the mailing list.
<ide>
<del>For more context and especially for comparisons with VMs and other
<del>container systems, please also see the [original blog post](
<add>References:
<add>* [Docker Containers: How Secure Are They? (2013)](
<ide> http://blog.docker.com/2013/08/containers-docker-how-secure-are-they/).
<add>* [On the Security of Containers (2014)](https://medium.com/@ewindisch/on-the-security-of-containers-2c60ffe25a9e). | 1 |
PHP | PHP | add 'deprecated' docblock to 'defer' property | e5bf6463cf3debfed29efe879a7a4ff3455cc1f9 | <ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> abstract class ServiceProvider
<ide> /**
<ide> * Indicates if loading of the provider is deferred.
<ide> *
<add> * @deprecated 5.8 Implement the \Illuminate\Contracts\Support\Deferred interface instead.
<add> *
<ide> * @var bool
<ide> */
<ide> protected $defer = false; | 1 |
Go | Go | fix cancellation context issue | 2567dd9afc070428082aa1bec14ee037337dd5c4 | <ide><path>builder/builder-next/builder.go
<ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.
<ide> b.jobs[buildID] = newBuildJob()
<ide> }
<ide> j := b.jobs[buildID]
<del> ctx, cancel := context.WithCancel(ctx)
<add> var cancel func()
<add> ctx, cancel = context.WithCancel(ctx)
<ide> j.cancel = cancel
<ide> b.mu.Unlock()
<ide> | 1 |
Javascript | Javascript | refactor the code in test-util-debug.js | 8839d504cca2f404ff50842e9451a1a8a0ff28a0 | <ide><path>test/sequential/test-util-debug.js
<ide> function parent() {
<ide> }
<ide>
<ide> function test(environ, shouldWrite) {
<del> var expectErr = '';
<add> let expectErr = '';
<ide> if (shouldWrite) {
<ide> expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' +
<ide> 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n';
<ide> }
<del> var expectOut = 'ok\n';
<add> const expectOut = 'ok\n';
<ide>
<ide> const spawn = require('child_process').spawn;
<del> var child = spawn(process.execPath, [__filename, 'child'], {
<add> const child = spawn(process.execPath, [__filename, 'child'], {
<ide> env: Object.assign(process.env, { NODE_DEBUG: environ })
<ide> });
<ide>
<ide> expectErr = expectErr.split('%PID%').join(child.pid);
<ide>
<del> var err = '';
<add> let err = '';
<ide> child.stderr.setEncoding('utf8');
<del> child.stderr.on('data', function(c) {
<add> child.stderr.on('data', (c) => {
<ide> err += c;
<ide> });
<ide>
<del> var out = '';
<add> let out = '';
<ide> child.stdout.setEncoding('utf8');
<del> child.stdout.on('data', function(c) {
<add> child.stdout.on('data', (c) => {
<ide> out += c;
<ide> });
<ide>
<del> child.on('close', common.mustCall(function(c) {
<add> child.on('close', common.mustCall((c) => {
<ide> assert(!c);
<del> assert.equal(err, expectErr);
<del> assert.equal(out, expectOut);
<del> console.log('ok %j %j', environ, shouldWrite);
<add> assert.strictEqual(err, expectErr);
<add> assert.strictEqual(out, expectOut);
<ide> }));
<ide> }
<ide>
<ide>
<ide> function child() {
<ide> const util = require('util');
<del> var debug = util.debuglog('tud');
<add> const debug = util.debuglog('tud');
<ide> debug('this', { is: 'a' }, /debugging/);
<ide> debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' });
<ide> console.log('ok'); | 1 |
PHP | PHP | fix sqs id returns | be6bcb19bcf90177cc5049419a1d2fbfe24bc5f5 | <ide><path>src/Illuminate/Queue/SqsQueue.php
<ide> public function push($job, $data = '', $queue = null)
<ide>
<ide> $response = $this->sqs->sendMessage(array('QueueUrl' => $this->getQueue($queue), 'MessageBody' => $payload));
<ide>
<del> return $response->MessageId;
<add> return $response->get('MessageId');
<ide> }
<ide>
<ide> /**
<ide> public function later($delay, $job, $data = '', $queue = null)
<ide>
<ide> 'QueueUrl' => $this->getQueue($queue), 'MessageBody' => $payload, 'DelaySeconds' => $delay,
<ide>
<del> ))->MessageId;
<add> ))->get('MessageId');
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | remove hack from bigquery dts hook | fedab9d64a58f1b5d3c88fe7a67f1f4021db8d26 | <ide><path>airflow/providers/google/cloud/hooks/bigquery_dts.py
<ide> def _disable_auto_scheduling(config: Union[dict, TransferConfig]) -> TransferCon
<ide> schedule_options["disable_auto_scheduling"] = True
<ide> else:
<ide> new_config["schedule_options"] = {"disable_auto_scheduling": True}
<del> # HACK: TransferConfig.to_dict returns invalid representation
<del> # See: https://github.com/googleapis/python-bigquery-datatransfer/issues/90
<del> if isinstance(new_config.get('user_id'), str):
<del> new_config['user_id'] = int(new_config['user_id'])
<add>
<ide> return TransferConfig(**new_config)
<ide>
<ide> def get_conn(self) -> DataTransferServiceClient:
<ide><path>setup.py
<ide> def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version
<ide> 'pandas-gbq',
<ide> pandas_requirement,
<ide> 'sqlalchemy-bigquery>=1.2.1',
<add> # A transient dependency of google-cloud-bigquery-datatransfer, but we
<add> # further constrain it since older versions are buggy.
<add> 'proto-plus>=1.19.6',
<ide> ]
<ide> grpc = [
<ide> # Google has very clear rules on what dependencies should be used. All the limits below | 2 |
Javascript | Javascript | remove framestopop from bridge | a483f802fddfd927f2baa0d95e2b4094d452cddd | <ide><path>Libraries/BatchedBridge/MessageQueue.js
<ide> class MessageQueue {
<ide> );
<ide> }
<ide> this.processCallbacks(moduleID, methodID, params, onFail, onSucc);
<del> try {
<del> return global.nativeCallSyncHook(moduleID, methodID, params);
<del> } catch (e) {
<del> if (
<del> typeof e === 'object' &&
<del> e != null &&
<del> typeof e.framesToPop === 'undefined' &&
<del> /^Exception in HostFunction: /.test(e.message)
<del> ) {
<del> e.framesToPop = 2;
<del> }
<del> throw e;
<del> }
<add> return global.nativeCallSyncHook(moduleID, methodID, params);
<ide> }
<ide>
<ide> processCallbacks(
<ide><path>Libraries/BatchedBridge/NativeModules.js
<ide> function loadModule(name: string, moduleID: number): ?Object {
<ide> function genMethod(moduleID: number, methodID: number, type: MethodType) {
<ide> let fn = null;
<ide> if (type === 'promise') {
<del> fn = function(...args: Array<any>) {
<add> fn = function promiseMethodWrapper(...args: Array<any>) {
<ide> // In case we reject, capture a useful stack trace here.
<ide> const enqueueingFrameError: ExtendedError = new Error();
<del> enqueueingFrameError.framesToPop = 1;
<ide> return new Promise((resolve, reject) => {
<ide> BatchedBridge.enqueueNativeCall(
<ide> moduleID,
<ide> function genMethod(moduleID: number, methodID: number, type: MethodType) {
<ide> });
<ide> };
<ide> } else {
<del> fn = function(...args: Array<any>) {
<add> fn = function nonPromiseMethodWrapper(...args: Array<any>) {
<ide> const lastArg = args.length > 0 ? args[args.length - 1] : null;
<ide> const secondLastArg = args.length > 1 ? args[args.length - 2] : null;
<ide> const hasSuccessCallback = typeof lastArg === 'function';
<ide><path>Libraries/BatchedBridge/__tests__/NativeModules-test.js
<ide> describe('MessageQueue', function() {
<ide> }).toThrow();
<ide> await expect(promise1).rejects.toBeInstanceOf(Error);
<ide> await expect(promise1).rejects.toMatchObject({message: 'firstFailure'});
<del> // Check that we get a useful stack trace from failures.
<del> const error = await promise1.catch(x => x);
<del> expect(getLineFromFrame(parseErrorStack(error)[0])).toContain(
<del> 'NativeModules.RemoteModule1.promiseReturningMethod(',
<del> );
<ide>
<ide> // Handle the second remote invocation by signaling success.
<ide> BatchedBridge.__invokeCallback(secondSuccCBID, ['secondSucc']);
<ide> describe('MessageQueue', function() {
<ide> });
<ide> });
<ide>
<del> it('throwing a "native" exception gets framesToPop = 2', function() {
<del> global.nativeCallSyncHook = () => {
<del> throw new Error('Exception in HostFunction: foo');
<del> };
<del> let error;
<del> try {
<del> NativeModules.RemoteModule1.syncMethod('paloAlto', 'menloPark');
<del> } catch (e) {
<del> error = e;
<del> }
<del> // We can't test this behaviour with `getLineFromFrame` because our mock
<del> // function adds an extra frame, so check `framesToPop` directly instead.
<del> expect(error.framesToPop).toBe(2);
<del> });
<del>
<del> it('throwing a "native" exception preserves framesToPop if set', function() {
<del> global.nativeCallSyncHook = () => {
<del> const e = new Error('Exception in HostFunction: foo');
<del> e.framesToPop = 42;
<del> throw e;
<del> };
<del> let error;
<del> try {
<del> NativeModules.RemoteModule1.syncMethod('paloAlto', 'menloPark');
<del> } catch (e) {
<del> error = e;
<del> }
<del> expect(error.framesToPop).toBe(42);
<del> });
<del>
<ide> it('returning a value', function() {
<ide> global.nativeCallSyncHook = jest.fn(() => {
<ide> return 'secondSucc';
<ide> describe('MessageQueue', function() {
<ide> });
<ide> });
<ide> });
<del>
<del>const linesByFile = new Map();
<del>
<del>function getLineFromFrame({lineNumber /* 1-based */, file}) {
<del> if (file == null) {
<del> return null;
<del> }
<del> const cleanedFile = cleanFileName(file);
<del> const lines =
<del> linesByFile.get(cleanedFile) ||
<del> fs.readFileSync(cleanedFile, 'utf8').split('\n');
<del> if (!linesByFile.has(cleanedFile)) {
<del> linesByFile.set(cleanedFile, lines);
<del> }
<del> return (lines[lineNumber - 1] || '').trim();
<del>}
<del>
<del>// Works around a parseErrorStack bug involving `new X` stack frames.
<del>function cleanFileName(file) {
<del> return file.replace(/^.+? \((?=\/)/, '');
<del>} | 3 |
Text | Text | add advantages and disadvantages of array | 493f8daa875751caa5213e05d3e9f3f428a080ad | <ide><path>guide/english/java/arrays/index.md
<ide> Output:
<ide> [ 0 | 1 | 2 | 3 | 4 ]
<ide> ```
<ide>
<add>**Advantages of Arrays**
<add>- **Code Optimization**: It makes the code optimized, we can retrieve or sort the data efficiently.
<add>+ **Random access**: We can get any data located at an index position.
<add>
<add>**Disadvantages of Arrays**
<add>- **Size Limit**: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.
<add>
<ide> #### More Information:
<ide> * Source: [Java Arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) | 1 |
Ruby | Ruby | squelch an unused variable warning | db3a6e6a7fc80e85afe239abf5d01aa30685c1c1 | <ide><path>activerecord/test/cases/counter_cache_test.rb
<ide> class ::SpecialReply < ::Reply
<ide>
<ide> test "update other counters on parent destroy" do
<ide> david, joanna = dog_lovers(:david, :joanna)
<add> joanna = joanna # squelch a warning
<ide>
<ide> assert_difference 'joanna.reload.dogs_count', -1 do
<ide> david.destroy | 1 |
PHP | PHP | add constants for abstract schema types | 50ddb7579de6ea1cd5c0dc2aa867da232a2b0601 | <ide><path>src/Database/Schema/MysqlSchema.php
<ide> */
<ide> namespace Cake\Database\Schema;
<ide>
<add>use Cake\Database\Schema\TableSchema;
<ide> use Cake\Database\Exception;
<ide>
<ide> /**
<ide> protected function _convertColumn($column)
<ide> return ['type' => $col, 'length' => null];
<ide> }
<ide> if (($col === 'tinyint' && $length === 1) || $col === 'boolean') {
<del> return ['type' => 'boolean', 'length' => null];
<add> return ['type' => TableSchema::TYPE_BOOLEAN, 'length' => null];
<ide> }
<ide>
<ide> $unsigned = (isset($matches[3]) && strtolower($matches[3]) === 'unsigned');
<ide> if (strpos($col, 'bigint') !== false || $col === 'bigint') {
<del> return ['type' => 'biginteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_BIGINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if ($col === 'tinyint') {
<del> return ['type' => 'tinyinteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_TINYINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if ($col === 'smallint') {
<del> return ['type' => 'smallinteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_SMALLINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if (in_array($col, ['int', 'integer', 'mediumint'])) {
<del> return ['type' => 'integer', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_INTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if ($col === 'char' && $length === 36) {
<del> return ['type' => 'uuid', 'length' => null];
<add> return ['type' => TableSchema::TYPE_UUID, 'length' => null];
<ide> }
<ide> if ($col === 'char') {
<del> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<add> return ['type' => TableSchema::TYPE_STRING, 'fixed' => true, 'length' => $length];
<ide> }
<ide> if (strpos($col, 'char') !== false) {
<del> return ['type' => 'string', 'length' => $length];
<add> return ['type' => TableSchema::TYPE_STRING, 'length' => $length];
<ide> }
<ide> if (strpos($col, 'text') !== false) {
<ide> $lengthName = substr($col, 0, -4);
<ide> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<ide>
<del> return ['type' => 'text', 'length' => $length];
<add> return ['type' => TableSchema::TYPE_TEXT, 'length' => $length];
<ide> }
<ide> if (strpos($col, 'blob') !== false || $col === 'binary') {
<ide> $lengthName = substr($col, 0, -4);
<ide> $length = isset(Table::$columnLengths[$lengthName]) ? Table::$columnLengths[$lengthName] : null;
<ide>
<del> return ['type' => 'binary', 'length' => $length];
<add> return ['type' => TableSchema::TYPE_BINARY, 'length' => $length];
<ide> }
<ide> if (strpos($col, 'float') !== false || strpos($col, 'double') !== false) {
<ide> return [
<del> 'type' => 'float',
<add> 'type' => TableSchema::TYPE_FLOAT,
<ide> 'length' => $length,
<ide> 'precision' => $precision,
<ide> 'unsigned' => $unsigned
<ide> ];
<ide> }
<ide> if (strpos($col, 'decimal') !== false) {
<ide> return [
<del> 'type' => 'decimal',
<add> 'type' => TableSchema::TYPE_DECIMAL,
<ide> 'length' => $length,
<ide> 'precision' => $precision,
<ide> 'unsigned' => $unsigned
<ide> ];
<ide> }
<ide>
<ide> if (strpos($col, 'json') !== false) {
<del> return ['type' => 'json', 'length' => null];
<add> return ['type' => TableSchema::TYPE_JSON, 'length' => null];
<ide> }
<ide>
<del> return ['type' => 'string', 'length' => null];
<add> return ['type' => TableSchema::TYPE_STRING, 'length' => null];
<ide> }
<ide>
<ide> /**
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $nativeJson = $this->_driver->supportsNativeJson();
<ide>
<ide> $typeMap = [
<del> 'tinyinteger' => ' TINYINT',
<del> 'smallinteger' => ' SMALLINT',
<del> 'integer' => ' INTEGER',
<del> 'biginteger' => ' BIGINT',
<del> 'boolean' => ' BOOLEAN',
<del> 'float' => ' FLOAT',
<del> 'decimal' => ' DECIMAL',
<del> 'date' => ' DATE',
<del> 'time' => ' TIME',
<del> 'datetime' => ' DATETIME',
<del> 'timestamp' => ' TIMESTAMP',
<del> 'uuid' => ' CHAR(36)',
<del> 'json' => $nativeJson ? ' JSON' : ' LONGTEXT'
<add> TableSchema::TYPE_TINYINTEGER => ' TINYINT',
<add> TableSchema::TYPE_SMALLINTEGER => ' SMALLINT',
<add> TableSchema::TYPE_INTEGER => ' INTEGER',
<add> TableSchema::TYPE_BIGINTEGER => ' BIGINT',
<add> TableSchema::TYPE_BOOLEAN => ' BOOLEAN',
<add> TableSchema::TYPE_FLOAT => ' FLOAT',
<add> TableSchema::TYPE_DECIMAL => ' DECIMAL',
<add> TableSchema::TYPE_DATE => ' DATE',
<add> TableSchema::TYPE_TIME => ' TIME',
<add> TableSchema::TYPE_DATETIME => ' DATETIME',
<add> TableSchema::TYPE_TIMESTAMP => ' TIMESTAMP',
<add> TableSchema::TYPE_UUID => ' CHAR(36)',
<add> TableSchema::TYPE_JSON => $nativeJson ? ' JSON' : ' LONGTEXT'
<ide> ];
<ide> $specialMap = [
<ide> 'string' => true,
<ide> public function columnSql(TableSchema $schema, $name)
<ide> break;
<ide> }
<ide> }
<del> $hasLength = ['integer', 'smallinteger', 'tinyinteger', 'string'];
<add> $hasLength = [
<add> TableSchema::TYPE_INTEGER,
<add> TableSchema::TYPE_SMALLINTEGER,
<add> TableSchema::TYPE_TINYINTEGER,
<add> TableSchema::TYPE_STRING
<add> ];
<ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide>
<del> $hasPrecision = ['float', 'decimal'];
<add> $hasPrecision = [TableSchema::TYPE_FLOAT, TableSchema::TYPE_DECIMAL];
<ide> if (in_array($data['type'], $hasPrecision, true) &&
<ide> (isset($data['length']) || isset($data['precision']))
<ide> ) {
<ide> $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
<ide> }
<ide>
<del> $hasUnsigned = ['float', 'decimal', 'tinyinteger', 'smallinteger', 'integer', 'biginteger'];
<add> $hasUnsigned = [
<add> TableSchema::TYPE_TINYINTEGER,
<add> TableSchema::TYPE_SMALLINTEGER,
<add> TableSchema::TYPE_INTEGER,
<add> TableSchema::TYPE_BIGINTEGER,
<add> TableSchema::TYPE_FLOAT,
<add> TableSchema::TYPE_DECIMAL
<add> ];
<ide> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<ide> $out .= ' UNSIGNED';
<ide> }
<ide>
<del> $hasCollate = ['text', 'string'];
<add> $hasCollate = [
<add> TableSchema::TYPE_TEXT,
<add> TableSchema::TYPE_STRING,
<add> ];
<ide> if (in_array($data['type'], $hasCollate, true) && isset($data['collate']) && $data['collate'] !== '') {
<ide> $out .= ' COLLATE ' . $data['collate'];
<ide> }
<ide> public function columnSql(TableSchema $schema, $name)
<ide> [$name] == (array)$schema->primaryKey() &&
<ide> !$schema->hasAutoincrement()
<ide> );
<del> if (in_array($data['type'], ['integer', 'biginteger']) &&
<add> if (in_array($data['type'], [TableSchema::TYPE_INTEGER, TableSchema::TYPE_BIGINTEGER]) &&
<ide> ($data['autoIncrement'] === true || $addAutoIncrement)
<ide> ) {
<ide> $out .= ' AUTO_INCREMENT';
<ide> }
<del> if (isset($data['null']) && $data['null'] === true && $data['type'] === 'timestamp') {
<add> if (isset($data['null']) && $data['null'] === true && $data['type'] === TableSchema::TYPE_TIMESTAMP) {
<ide> $out .= ' NULL';
<ide> unset($data['default']);
<ide> }
<ide> if (isset($data['default']) &&
<del> in_array($data['type'], ['timestamp', 'datetime']) &&
<add> in_array($data['type'], [TableSchema::TYPE_TIMESTAMP, TableSchema::TYPE_DATETIME]) &&
<ide> strtolower($data['default']) === 'current_timestamp'
<ide> ) {
<ide> $out .= ' DEFAULT CURRENT_TIMESTAMP';
<ide><path>src/Database/Schema/TableSchema.php
<ide> class TableSchema
<ide> */
<ide> const INDEX_FULLTEXT = 'fulltext';
<ide>
<add> /**
<add> * Binary column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_BINARY = 'binary';
<add>
<add> /**
<add> * Date column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_DATE = 'date';
<add>
<add> /**
<add> * Datetime column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_DATETIME = 'datetime';
<add>
<add> /**
<add> * Time column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_TIME = 'time';
<add>
<add> /**
<add> * Timestamp column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_TIMESTAMP = 'timestamp';
<add>
<add> /**
<add> * json column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_JSON = 'json';
<add>
<add> /**
<add> * String column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_STRING = 'string';
<add>
<add> /**
<add> * Text column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_TEXT = 'text';
<add>
<add> /**
<add> * Tiny Integer column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_TINYINTEGER = 'tinyinteger';
<add>
<add> /**
<add> * Small Integer column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_SMALLINTEGER = 'smallinteger';
<add>
<add> /**
<add> * Integer column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_INTEGER = 'integer';
<add>
<add> /**
<add> * Big Integer column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_BIGINTEGER = 'biginteger';
<add>
<add> /**
<add> * Float column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_FLOAT = 'float';
<add>
<add> /**
<add> * Decimal column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_DECIMAL = 'decimal';
<add>
<add> /**
<add> * Boolean column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_BOOLEAN = 'boolean';
<add>
<add> /**
<add> * UUID column type
<add> *
<add> * @var string
<add> */
<add> const TYPE_UUID = 'uuid';
<add>
<ide> /**
<ide> * Foreign key cascade action
<ide> * | 2 |
PHP | PHP | add dispatcherfilter settings | 4639d3597ce3cb44712ea8cf9c2447a79dc9be13 | <ide><path>app/Config/bootstrap.php
<ide> *
<ide> * Configure::write('Dispatcher.filters', array(
<ide> * 'MyCacheFilter', // will use MyCacheFilter class from the Routing/Filter package in your app.
<add> * 'MyCacheFilter' => array('prefix' => 'my_cache_'), // will use MyCacheFilter class from the Routing/Filter package in your app with settings array.
<ide> * 'MyPlugin.MyFilter', // will use MyFilter class from the Routing/Filter package in MyPlugin plugin.
<del> * array('callable' => $aFunction, 'on' => 'before', 'priority' => 9), // A valid PHP callback type to be called on beforeDispatch
<add> * array('callable' => $aFunction, 'on' => 'before', 'priority' => 9), // A valid PHP callback type to be called on beforeDispatch
<ide> * array('callable' => $anotherMethod, 'on' => 'after'), // A valid PHP callback type to be called on afterDispatch
<ide> *
<ide> * ));
<ide><path>lib/Cake/Routing/Dispatcher.php
<ide> protected function _attachFilters($manager) {
<ide> return;
<ide> }
<ide>
<del> foreach ($filters as $filter) {
<add> foreach ($filters as $index => $filter) {
<add> $settings = array();
<add> if (is_array($filter) && !is_int($index)) {
<add> $settings = $filter;
<add> $filter = $index;
<add> }
<ide> if (is_string($filter)) {
<ide> $filter = array('callable' => $filter);
<ide> }
<ide> protected function _attachFilters($manager) {
<ide> if (!class_exists($callable)) {
<ide> throw new MissingDispatcherFilterException($callable);
<ide> }
<del> $manager->attach(new $callable);
<add> $manager->attach(new $callable($settings));
<ide> } else {
<ide> $on = strtolower($filter['on']);
<ide> $options = array();
<ide><path>lib/Cake/Routing/DispatcherFilter.php
<ide> abstract class DispatcherFilter implements CakeEventListener {
<ide> */
<ide> public $priority = 10;
<ide>
<add>/**
<add> * Settings for this filter
<add> *
<add> * @var array
<add> */
<add> public $settings = array();
<add>
<add>/**
<add> * Constructor.
<add> *
<add> * @param string $setting Configuration settings for the filter.
<add> */
<add> public function __construct($settings = array()) {
<add> $this->settings = Hash::merge($this->settings, $settings);
<add> }
<add>
<ide> /**
<ide> * Returns the list of events this filter listens to.
<ide> * Dispatcher notifies 2 different events `Dispatcher.before` and `Dispatcher.after`.
<ide><path>lib/Cake/Test/Case/Routing/DispatcherTest.php
<ide> */
<ide>
<ide> App::uses('Dispatcher', 'Routing');
<add>App::uses('DispatcherFilter', 'Routing');
<ide>
<ide> if (!class_exists('AppController', false)) {
<ide> require_once CAKE . 'Test' . DS . 'test_app' . DS . 'Controller' . DS . 'AppController.php';
<ide> public function index() {
<ide>
<ide> }
<ide>
<add>/**
<add> * TestFilterDispatcher class
<add> *
<add> * @package Cake.Test.Case.Routing
<add> */
<add>class TestFilterDispatcher extends DispatcherFilter {
<add>
<add> public $priority = 10;
<add>
<add>/**
<add> * TestFilterDispatcher::beforeDispatch()
<add> *
<add> * @param mixed $event
<add> * @return CakeResponse|boolean
<add> */
<add> public function beforeDispatch(CakeEvent $event) {
<add> $event->stopPropagation();
<add> $response = $event->data['request'];
<add> $response->addParams(array('settings' => $this->settings));
<add> return null;
<add> }
<add>
<add>/**
<add> * TestFilterDispatcher::afterDispatch()
<add> *
<add> * @param mixed $event
<add> * @return mixed boolean to stop the event dispatching or null to continue
<add> */
<add> public function afterDispatch(CakeEvent $event) {
<add> }
<add>
<add>}
<add>
<ide> /**
<ide> * DispatcherTest class
<ide> *
<ide> public function testDispatcherFilterSubscriber() {
<ide> $this->assertNull($dispatcher->controller);
<ide> }
<ide>
<add>/**
<add> * Tests that it is possible to attach filter with config classes to the dispatch cycle
<add> *
<add> * @return void
<add> */
<add> public function testDispatcherFilterSettings() {
<add> Configure::write('Dispatcher.filters', array(
<add> 'TestFilterDispatcher' => array('service' => 'google.com')
<add> ));
<add> $Dispatcher = new Dispatcher();
<add> $url = new CakeRequest('some_pages/index');
<add> $response = $this->getMock('CakeResponse');
<add> $Dispatcher->dispatch($url, $response, array('return' => 1));
<add> $settings = $url->param('settings');
<add> $this->assertEquals($settings, array('service' => 'google.com'));
<add> }
<add>
<ide> /**
<ide> * Tests that attaching an inexistent class as filter will throw an exception
<ide> *
<ide> protected function _cachePath($here) {
<ide> }
<ide> return $filename;
<ide> }
<del>}
<add>}
<ide>\ No newline at end of file | 4 |
Python | Python | use deprecated decorator in testing ufunclike.log2 | fcc0b79de4ae35548dbc711c9273ecd875764ccd | <ide><path>numpy/lib/tests/test_ufunclike.py
<ide> from numpy.testing import *
<ide> import numpy.core as nx
<ide> import numpy.lib.ufunclike as ufl
<del>import warnings
<add>from numpy.testing.decorators import deprecated
<ide>
<ide> class TestUfunclike(TestCase):
<ide>
<ide> def test_isneginf(self):
<ide> assert_equal(res, tgt)
<ide> assert_equal(out, tgt)
<ide>
<add> @deprecated()
<ide> def test_log2(self):
<ide> a = nx.array([4.5, 2.3, 6.5])
<ide> out = nx.zeros(a.shape, float)
<ide> tgt = nx.array([2.169925, 1.20163386, 2.70043972])
<del> try:
<del> warnings.filterwarnings("ignore",category=DeprecationWarning)
<del> res = ufl.log2(a)
<del> assert_almost_equal(res, tgt)
<del> res = ufl.log2(a, out)
<del> assert_almost_equal(res, tgt)
<del> assert_almost_equal(out, tgt)
<del> except DeprecationWarning:
<del> pass
<add> res = ufl.log2(a)
<add> assert_almost_equal(res, tgt)
<add> res = ufl.log2(a, out)
<add> assert_almost_equal(res, tgt)
<add> assert_almost_equal(out, tgt)
<ide>
<ide> def test_fix(self):
<ide> a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
<ide><path>numpy/lib/ufunclike.py
<ide> __all__ = ['fix', 'isneginf', 'isposinf']
<ide>
<ide> import numpy.core.numeric as nx
<del>import warnings
<ide>
<ide> def fix(x, y=None):
<ide> """
<ide> def isneginf(x, y=None):
<ide> nx.logical_and(nx.isinf(x), nx.signbit(x), y)
<ide> return y
<ide>
<add>
<ide> _log2 = nx.log(2)
<ide> def log2(x, y=None):
<ide> """
<ide> def log2(x, y=None):
<ide> array([ NaN, 1., 2.])
<ide>
<ide> """
<add> import warnings
<ide> msg = "numpy.lib.log2 is deprecated, use np.log2 instead."
<ide> warnings.warn(msg, DeprecationWarning)
<ide> | 2 |
PHP | PHP | extract mergevars into a trait | 35641cdc70a65aaeccc64da493bbe2d18c769683 | <ide><path>lib/Cake/Test/TestCase/Utility/MergeVariablesTraitTest.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v 3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>namespace Cake\Test\TestCase\Utility;
<add>
<add>use Cake\TestSuite\TestCase;
<add>use Cake\Utility\MergeVariablesTrait;
<add>
<add>class Base {
<add> use MergeVariablesTrait;
<add>
<add> public $listProperty = ['One'];
<add>
<add> public $assocProperty = ['Red'];
<add>
<add> public function mergeVars($properties) {
<add> return $this->_mergeVars($properties);
<add> }
<add>
<add>}
<add>
<add>class Child extends Base {
<add>
<add> public $listProperty = ['Two', 'Three'];
<add>
<add> public $assocProperty = [
<add> 'Green' => ['lime'],
<add> 'Orange'
<add> ];
<add>
<add>}
<add>
<add>class Grandchild extends Child {
<add>
<add> public $listProperty = ['Four', 'Five'];
<add>
<add> public $assocProperty = [
<add> 'Green' => ['apple'],
<add> 'Yellow' => ['banana']
<add> ];
<add>}
<add>
<add>/**
<add> * MergeVariablesTrait test case
<add> *
<add> * @package Cake.Test.TestCase.Utility
<add> */
<add>class MergeVariablesTraitTest extends TestCase {
<add>
<add>/**
<add> * Test merging vars as a list.
<add> *
<add> * @return void
<add> */
<add> public function testMergeVarsAsList() {
<add> $object = new Grandchild();
<add> $object->mergeVars(['listProperty' => false]);
<add>
<add> $expected = ['One', 'Two', 'Three', 'Four', 'Five'];
<add> $this->assertSame($expected, $object->listProperty);
<add> }
<add>
<add>/**
<add> * Test merging vars as an assoc list.
<add> *
<add> * @return void
<add> */
<add> public function testMergeVarsAsAssoc() {
<add> $object = new Grandchild();
<add> $object->mergeVars(['assocProperty' => true]);
<add> $expected = [
<add> 'Red' => null,
<add> 'Orange' => null,
<add> 'Green' => ['lime', 'apple'],
<add> 'Yellow' => ['banana'],
<add> ];
<add> $this->assertEquals($expected, $object->assocProperty);
<add> }
<add>}
<ide><path>lib/Cake/Utility/MergeVariablesTrait.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v 3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>namespace Cake\Utility;
<add>
<add>use Cake\Utility\Hash;
<add>
<add>/**
<add> * Provides features for merging object properties recursively with
<add> * parent classes.
<add> *
<add> * @package Cake.Utility
<add> */
<add>trait MergeVariablesTrait {
<add>
<add>/**
<add> * Merge the list of $properties with all parent classes of the current class.
<add> *
<add> * @param array $properties An array of properties and the merge strategy for them.
<add> * @return void
<add> */
<add> protected function _mergeVars($properties) {
<add> $class = get_class($this);
<add> $parents = [];
<add> while (true) {
<add> $parent = get_parent_class($class);
<add> if (!$parent) {
<add> break;
<add> }
<add> $parents[] = $parent;
<add> $class = $parent;
<add> }
<add> foreach ($properties as $property => $strategy) {
<add> if (!property_exists($this, $property)) {
<add> continue;
<add> }
<add> $thisValue = $this->{$property};
<add> if ($thisValue === null || $thisValue === false) {
<add> continue;
<add> }
<add> $this->_mergeProperty($property, $parents, $strategy);
<add> }
<add> }
<add>
<add>/**
<add> * Merge a single property with the values declared in all parent classes.
<add> *
<add> * @param string $property The name of the property being merged.
<add> * @param array $parentClasses An array of classes you want to merge with.
<add> * @param bool $asAssoc Set true for merging as assoc, false for list.
<add> * @return void
<add> */
<add> protected function _mergeProperty($property, $parentClasses, $asAssoc) {
<add> $thisValue = $this->{$property};
<add> if ($asAssoc) {
<add> $thisValue = Hash::normalize($thisValue);
<add> }
<add> foreach ($parentClasses as $class) {
<add> $parentProperties = get_class_vars($class);
<add> if (!isset($parentProperties[$property])) {
<add> continue;
<add> }
<add> $parentProperty = $parentProperties[$property];
<add> if ($asAssoc) {
<add> $parentProperty = Hash::normalize($parentProperty);
<add> }
<add> $thisValue = Hash::merge($parentProperty, $thisValue);
<add> }
<add> $this->{$property} = $thisValue;
<add> }
<add>
<add>} | 2 |
PHP | PHP | fix cs errors | f3cabe98c07e1ff7bd2f712f2bee5f5a4beebd69 | <ide><path>tests/TestCase/Http/ServerRequestFactoryTest.php
<ide> public function testFromGlobalsWithFilesAsObjectsDefault()
<ide> 'error' => 0,
<ide> 'name' => 'file.txt',
<ide> 'type' => 'text/plain',
<del> 'size' => 1234
<add> 'size' => 1234,
<ide> ],
<ide> ];
<ide> $this->assertEquals($expected, $request->getData());
<ide> public function testFromGlobalsWithFilesAsObjectsDisabled()
<ide> 'error' => 0,
<ide> 'name' => 'file.txt',
<ide> 'type' => 'text/plain',
<del> 'size' => 1234
<add> 'size' => 1234,
<ide> ],
<ide> ];
<ide> $this->assertEquals($expected, $request->getData());
<ide><path>tests/TestCase/Http/ServerRequestTest.php
<ide> public function testFilesWithInvalidStructure()
<ide> 'files' => [
<ide> [
<ide> 'invalid' => [
<del> 'data'
<del> ]
<del> ]
<add> 'data',
<add> ],
<add> ],
<ide> ],
<ide> ]);
<ide> }
<ide> public function testFilesAsObjectsInRequestData()
<ide> 'flat' => ['existing'],
<ide> 'nested' => [
<ide> 'name' => 'nested',
<del> 'file' => ['existing']
<add> 'file' => ['existing'],
<ide> ],
<ide> 'deep' => [
<ide> 0 => [
<ide> 'name' => 'deep 1',
<del> 'file' => ['existing']
<add> 'file' => ['existing'],
<ide> ],
<ide> 1 => [
<ide> 'name' => 'deep 2',
<ide> public function testFilesAsObjectsInRequestData()
<ide> 0,
<ide> 'nested.txt',
<ide> 'text/plain'
<del> )
<add> ),
<ide> ],
<ide> 'deep' => [
<ide> 0 => [
<ide> public function testFilesAsObjectsInRequestData()
<ide> 0,
<ide> 'deep-1.txt',
<ide> 'text/plain'
<del> )
<add> ),
<ide> ],
<ide> 1 => [
<ide> 'name' => 'deep 2',
<ide> public function testFilesAsObjectsInRequestData()
<ide> 0,
<ide> 'deep-2.txt',
<ide> 'text/plain'
<del> )
<add> ),
<ide> ],
<ide> ],
<ide> 0 => new UploadedFile(
<ide> public function testFilesAsObjectsInRequestData()
<ide> 0,
<ide> 'numeric-nested.txt',
<ide> 'text/plain'
<del> )
<add> ),
<ide> ],
<ide> ];
<ide>
<ide> $request = new ServerRequest([
<ide> 'files' => $files,
<ide> 'post' => $post,
<del> 'mergeFilesAsObjects' => true
<add> 'mergeFilesAsObjects' => true,
<ide> ]);
<ide>
<ide> $this->assertEquals($expected, $request->getData()); | 2 |
Javascript | Javascript | adjust indentation for impending lint change | 8cccdd96f597a62ff1ef1c695211707cad1cddb8 | <ide><path>lib/net.js
<ide> Socket.prototype.connect = function() {
<ide> if (pipe) {
<ide> if (typeof path !== 'string') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'options.path',
<del> 'string',
<del> path);
<add> 'options.path',
<add> 'string',
<add> path);
<ide> }
<ide> internalConnect(this, path);
<ide> } else {
<ide><path>lib/repl.js
<ide> REPLServer.prototype.defineCommand = function(keyword, cmd) {
<ide> cmd = { action: cmd };
<ide> } else if (typeof cmd.action !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'action', 'function', cmd.action);
<add> 'action',
<add> 'function',
<add> cmd.action);
<ide> }
<ide> this.commands[keyword] = cmd;
<ide> }; | 2 |
Python | Python | acknowledge ignore'd tasks when acks_late | 903a960a3538cead258cc2ac4135ec94ffe55311 | <ide><path>celery/worker/job.py
<ide> def _log_error(self, einfo):
<ide> description = 'ignored'
<ide> severity = logging.INFO
<ide> exc_info = None
<add> self.acknowledge()
<ide> else:
<ide> format = self.internal_error_msg
<ide> description = 'INTERNAL ERROR' | 1 |
Python | Python | add warnning info | 603b470a3d855c5187564701c475cfef5826c224 | <ide><path>examples/single_model_scripts/utils_multiple_choice.py
<ide> def _truncate_seq_pair(tokens_a, tokens_b, max_length):
<ide> if len(tokens_a) > len(tokens_b):
<ide> tokens_a.pop()
<ide> else:
<del> logger.info('Attention! you are removing from question + options. Try to use a bigger max seq length!')
<add> logger.info('Attention! you are removing from token_b (swag task is ok). '
<add> 'If you are training ARC and RACE (you are poping question + options), '
<add> 'you need to try to use a bigger max seq length!')
<ide> tokens_b.pop()
<ide>
<ide> | 1 |
Ruby | Ruby | return the result based on current active_spec | 5aa6b5c5faa605d3dfd39ce86803c3d967093d06 | <ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide> # @see #active_spec
<ide> attr_reader :active_spec_sym
<ide>
<del> # The {PkgVersion} for this formula with version and {#revision} information.
<del> attr_reader :pkg_version
<del>
<ide> # Used for creating new Homebrew versions of software without new upstream
<ide> # versions.
<ide> # @see .revision
<ide> def initialize(name, path, spec)
<ide> :stable
<ide> end
<ide> validate_attributes!
<del> @pkg_version = PkgVersion.new(version, revision)
<ide> @build = active_spec.build
<ide> @pin = FormulaPin.new(self)
<ide> end
<ide> def version
<ide> active_spec.version
<ide> end
<ide>
<add> # The {PkgVersion} for this formula with {version} and {#revision} information.
<add> def pkg_version
<add> PkgVersion.new(version, revision)
<add> end
<add>
<ide> # A named Resource for the currently active {SoftwareSpec}.
<ide> def resource(name)
<ide> active_spec.resource(name) | 1 |
Javascript | Javascript | add more information to activity events | 90db4f3c6d0710b0da1827125390c032fcc48fb5 | <ide><path>packager/react-packager/src/Bundler/index.js
<ide> class Bundler {
<ide> null,
<ide> {
<ide> telemetric: true,
<add> entryPoint: entryFile,
<ide> },
<ide> );
<ide> const modulesByName = Object.create(null);
<ide><path>packager/react-packager/src/Server/index.js
<ide> class Server {
<ide> return;
<ide> }
<ide>
<add> const options = this._getOptionsFromUrl(req.url);
<ide> const startReqEventId = Activity.startEvent(
<ide> 'Requesting bundle',
<ide> {
<ide> url: req.url,
<ide> },
<ide> {
<ide> telemetric: true,
<add> entryPoint: options.entryFile,
<add> details: req.url,
<ide> },
<ide> );
<del> const options = this._getOptionsFromUrl(req.url);
<ide> debug('Getting bundle for request');
<ide> const building = this._useCachedOrUpdateOrCreateBundle(options);
<ide> building.then( | 2 |
Java | Java | update copyright dates | 1c10cdd1e87f133c082771587a730bbf2255a920 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 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><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/VersionResourceResolver.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 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><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 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><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/XhrStreamingTransportHandler.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 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. | 5 |
Javascript | Javascript | add missing bracket | 97e72d58649e80196c1eef79d4e73ded3ed65893 | <ide><path>src/core.js
<ide> function getPdf(arg, callback) {
<ide> calledErrorBack = true;
<ide> params.error();
<ide> }
<add> }
<ide> }
<ide>
<ide> xhr.onreadystatechange = function getPdfOnreadystatechange(e) { | 1 |
Python | Python | update nb tag_map | 16cb19e960d614ddfcf04e35350f5c2fe4b6ba71 | <ide><path>spacy/lang/nb/tag_map.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<del>from ...symbols import POS, PUNCT, ADJ, CONJ, SCONJ, SYM, NUM, DET, ADV, ADP, X
<add>from ...symbols import POS, PUNCT, ADJ, CONJ, CCONJ, SCONJ, SYM, NUM, DET, ADV, ADP, X
<ide> from ...symbols import VERB, NOUN, PROPN, PART, INTJ, PRON, AUX
<ide>
<ide>
<del># Tags are a combination of POS and morphological features from a yet
<del># unpublished dataset developed by Schibsted, Nasjonalbiblioteket and LTG. The
<add># Tags are a combination of POS and morphological features from a
<add># https://github.com/ltgoslo/norne developed by Schibsted, Nasjonalbiblioteket and LTG. The
<ide> # data format is .conllu and follows the Universal Dependencies annotation.
<ide> # (There are some annotation differences compared to this dataset:
<ide> # https://github.com/UniversalDependencies/UD_Norwegian-Bokmaal
<ide> "VERB__VerbForm=Part": {"morph": "VerbForm=Part", POS: VERB},
<ide> "VERB___": {"morph": "_", POS: VERB},
<ide> "X___": {"morph": "_", POS: X},
<add> 'CCONJ___': {"morph": "_", POS: CCONJ},
<add> "ADJ__Abbr=Yes": {"morph": "Abbr=Yes", POS: ADJ},
<add> "ADJ__Abbr=Yes|Degree=Pos": {"morph": "Abbr=Yes|Degree=Pos", POS: ADJ},
<add> "ADJ__Case=Gen|Definite=Def|Number=Sing|VerbForm=Part": {"morph": "Case=Gen|Definite=Def|Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__Definite=Def|Number=Sing|VerbForm=Part": {"morph": "Definite=Def|Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__Definite=Ind|Gender=Masc|Number=Sing|VerbForm=Part": {"morph": "Definite=Ind|Gender=Masc|Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__Definite=Ind|Gender=Neut|Number=Sing|VerbForm=Part": {"morph": "Definite=Ind|Gender=Neut|Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__Definite=Ind|Number=Sing|VerbForm=Part": {"morph": "Definite=Ind|Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__Number=Sing|VerbForm=Part": {"morph": "Number=Sing|VerbForm=Part", POS: ADJ},
<add> "ADJ__VerbForm=Part": {"morph": "VerbForm=Part", POS: ADJ},
<add> "ADP__Abbr=Yes": {"morph": "Abbr=Yes", POS: ADP},
<add> "ADV__Abbr=Yes": {"morph": "Abbr=Yes", POS: ADV},
<add> "DET__Case=Gen|Gender=Masc|Number=Sing|PronType=Art": {"morph": "Case=Gen|Gender=Masc|Number=Sing|PronType=Art", POS: DET},
<add> "DET__Case=Gen|Number=Plur|PronType=Tot": {"morph": "Case=Gen|Number=Plur|PronType=Tot", POS: DET},
<add> "DET__Definite=Def|PronType=Prs": {"morph": "Definite=Def|PronType=Prs", POS: DET},
<add> "DET__Definite=Ind|Gender=Fem|Number=Sing|PronType=Prs": {"morph": "Definite=Ind|Gender=Fem|Number=Sing|PronType=Prs", POS: DET},
<add> "DET__Definite=Ind|Gender=Masc|Number=Sing|PronType=Prs": {"morph": "Definite=Ind|Gender=Masc|Number=Sing|PronType=Prs", POS: DET},
<add> "DET__Definite=Ind|Gender=Neut|Number=Sing|PronType=Prs": {"morph": "Definite=Ind|Gender=Neut|Number=Sing|PronType=Prs", POS: DET},
<add> "DET__Gender=Fem|Number=Sing|PronType=Art": {"morph": "Gender=Fem|Number=Sing|PronType=Art", POS: DET},
<add> "DET__Gender=Fem|Number=Sing|PronType=Ind": {"morph": "Gender=Fem|Number=Sing|PronType=Ind", POS: DET},
<add> "DET__Gender=Fem|Number=Sing|PronType=Prs": {"morph": "Gender=Fem|Number=Sing|PronType=Prs", POS: DET},
<add> "DET__Gender=Fem|Number=Sing|PronType=Tot": {"morph": "Gender=Fem|Number=Sing|PronType=Tot", POS: DET},
<add> "DET__Gender=Masc|Number=Sing|Polarity=Neg|PronType=Neg": {"morph": "Gender=Masc|Number=Sing|Polarity=Neg|PronType=Neg", POS: DET},
<add> "DET__Gender=Masc|Number=Sing|PronType=Art": {"morph": "Gender=Masc|Number=Sing|PronType=Art", POS: DET},
<add> "DET__Gender=Masc|Number=Sing|PronType=Ind": {"morph": "Gender=Masc|Number=Sing|PronType=Ind", POS: DET},
<add> "DET__Gender=Masc|Number=Sing|PronType=Tot": {"morph": "Gender=Masc|Number=Sing|PronType=Tot", POS: DET},
<add> "DET__Gender=Neut|Number=Sing|Polarity=Neg|PronType=Neg": {"morph": "Gender=Neut|Number=Sing|Polarity=Neg|PronType=Neg", POS: DET},
<add> "DET__Gender=Neut|Number=Sing|PronType=Art": {"morph": "Gender=Neut|Number=Sing|PronType=Art", POS: DET},
<add> "DET__Gender=Neut|Number=Sing|PronType=Dem,Ind": {"morph": "Gender=Neut|Number=Sing|PronType=Dem,Ind", POS: DET},
<add> "DET__Gender=Neut|Number=Sing|PronType=Ind": {"morph": "Gender=Neut|Number=Sing|PronType=Ind", POS: DET},
<add> "DET__Gender=Neut|Number=Sing|PronType=Tot": {"morph": "Gender=Neut|Number=Sing|PronType=Tot", POS: DET},
<add> "DET__Number=Plur|Polarity=Neg|PronType=Neg": {"morph": "Number=Plur|Polarity=Neg|PronType=Neg", POS: DET},
<add> "DET__Number=Plur|PronType=Art": {"morph": "Number=Plur|PronType=Art", POS: DET},
<add> "DET__Number=Plur|PronType=Ind": {"morph": "Number=Plur|PronType=Ind", POS: DET},
<add> "DET__Number=Plur|PronType=Prs": {"morph": "Number=Plur|PronType=Prs", POS: DET},
<add> "DET__Number=Plur|PronType=Tot": {"morph": "Number=Plur|PronType=Tot", POS: DET},
<add> "DET__PronType=Ind": {"morph": "PronType=Ind", POS: DET},
<add> "DET__PronType=Prs": {"morph": "PronType=Prs", POS: DET},
<add> "NOUN__Abbr=Yes": {"morph": "Abbr=Yes", POS: NOUN},
<add> "NOUN__Abbr=Yes|Case=Gen": {"morph": "Abbr=Yes|Case=Gen", POS: NOUN},
<add> "NOUN__Abbr=Yes|Definite=Def,Ind|Gender=Masc|Number=Plur,Sing": {"morph": "Abbr=Yes|Definite=Def,Ind|Gender=Masc|Number=Plur,Sing", POS: NOUN},
<add> "NOUN__Abbr=Yes|Definite=Def,Ind|Gender=Masc|Number=Sing": {"morph": "Abbr=Yes|Definite=Def,Ind|Gender=Masc|Number=Sing", POS: NOUN},
<add> "NOUN__Abbr=Yes|Definite=Def,Ind|Gender=Neut|Number=Plur,Sing": {"morph": "Abbr=Yes|Definite=Def,Ind|Gender=Neut|Number=Plur,Sing", POS: NOUN},
<add> "NOUN__Abbr=Yes|Gender=Masc": {"morph": "Abbr=Yes|Gender=Masc", POS: NOUN},
<add> "NUM__Case=Gen|Number=Plur|NumType=Card": {"morph": "Case=Gen|Number=Plur|NumType=Card", POS: NUM},
<add> "NUM__Definite=Def|Number=Sing|NumType=Card": {"morph": "Definite=Def|Number=Sing|NumType=Card", POS: NUM},
<add> "NUM__Definite=Def|NumType=Card": {"morph": "Definite=Def|NumType=Card", POS: NUM},
<add> "NUM__Gender=Fem|Number=Sing|NumType=Card": {"morph": "Gender=Fem|Number=Sing|NumType=Card", POS: NUM},
<add> "NUM__Gender=Masc|Number=Sing|NumType=Card": {"morph": "Gender=Masc|Number=Sing|NumType=Card", POS: NUM},
<add> "NUM__Gender=Neut|Number=Sing|NumType=Card": {"morph": "Gender=Neut|Number=Sing|NumType=Card", POS: NUM},
<add> "NUM__Number=Plur|NumType=Card": {"morph": "Number=Plur|NumType=Card", POS: NUM},
<add> "NUM__Number=Sing|NumType=Card": {"morph": "Number=Sing|NumType=Card", POS: NUM},
<add> "NUM__NumType=Card": {"morph": "NumType=Card", POS: NUM},
<add> "PART__Polarity=Neg": {"morph": "Polarity=Neg", POS: PART},
<add> "PRON__Animacy=Hum|Case=Acc|Gender=Fem|Number=Sing|Person=3|PronType=Prs": { "morph": "Animacy=Hum|Case=Acc|Gender=Fem|Number=Sing|Person=3|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Acc|Gender=Masc|Number=Sing|Person=3|PronType=Prs": { "morph": "Animacy=Hum|Case=Acc|Gender=Masc|Number=Sing|Person=3|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Acc|Number=Plur|Person=1|PronType=Prs": {"morph": "Animacy=Hum|Case=Acc|Number=Plur|Person=1|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Acc|Number=Plur|Person=2|PronType=Prs": {"morph": "Animacy=Hum|Case=Acc|Number=Plur|Person=2|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Acc|Number=Sing|Person=1|PronType=Prs": {"morph": "Animacy=Hum|Case=Acc|Number=Sing|Person=1|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Acc|Number=Sing|Person=2|PronType=Prs": {"morph": "Animacy=Hum|Case=Acc|Number=Sing|Person=2|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Gen,Nom|Number=Sing|PronType=Art,Prs": {"morph": "Animacy=Hum|Case=Gen,Nom|Number=Sing|PronType=Art,Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Gen|Number=Sing|PronType=Art,Prs": {"morph": "Animacy=Hum|Case=Gen|Number=Sing|PronType=Art,Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Gender=Fem|Number=Sing|Person=3|PronType=Prs": { "morph": "Animacy=Hum|Case=Nom|Gender=Fem|Number=Sing|Person=3|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Gender=Masc|Number=Sing|Person=3|PronType=Prs": { "morph": "Animacy=Hum|Case=Nom|Gender=Masc|Number=Sing|Person=3|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Number=Plur|Person=1|PronType=Prs": {"morph": "Animacy=Hum|Case=Nom|Number=Plur|Person=1|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Number=Plur|Person=2|PronType=Prs": {"morph": "Animacy=Hum|Case=Nom|Number=Plur|Person=2|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Number=Sing|Person=1|PronType=Prs": {"morph": "Animacy=Hum|Case=Nom|Number=Sing|Person=1|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Number=Sing|Person=2|PronType=Prs": {"morph": "Animacy=Hum|Case=Nom|Number=Sing|Person=2|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Case=Nom|Number=Sing|PronType=Prs": {"morph": "Animacy=Hum|Case=Nom|Number=Sing|PronType=Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Number=Plur|PronType=Rcp": {"morph": "Animacy=Hum|Number=Plur|PronType=Rcp", POS: PRON},
<add> "PRON__Animacy=Hum|Number=Sing|PronType=Art,Prs": {"morph": "Animacy=Hum|Number=Sing|PronType=Art,Prs", POS: PRON},
<add> "PRON__Animacy=Hum|Poss=Yes|PronType=Int": {"morph": "Animacy=Hum|Poss=Yes|PronType=Int", POS: PRON},
<add> "PRON__Animacy=Hum|PronType=Int": {"morph": "Animacy=Hum|PronType=Int", POS: PRON},
<add> "PRON__Case=Acc|PronType=Prs|Reflex=Yes": {"morph": "Case=Acc|PronType=Prs|Reflex=Yes", POS: PRON},
<add> "PRON__Gender=Fem,Masc|Number=Sing|Person=3|Polarity=Neg|PronType=Neg,Prs": { "morph": "Gender=Fem,Masc|Number=Sing|Person=3|Polarity=Neg|PronType=Neg,Prs", POS: PRON},
<add> "PRON__Gender=Fem,Masc|Number=Sing|Person=3|PronType=Ind,Prs": {"morph": "Gender=Fem,Masc|Number=Sing|Person=3|PronType=Ind,Prs", POS: PRON},
<add> "PRON__Gender=Fem,Masc|Number=Sing|Person=3|PronType=Prs,Tot": {"morph": "Gender=Fem,Masc|Number=Sing|Person=3|PronType=Prs,Tot", POS: PRON},
<add> "PRON__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"morph": "Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs", POS: PRON},
<add> "PRON__Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs": {"morph": "Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs", POS: PRON},
<add> "PRON__Gender=Neut|Number=Sing|Person=3|PronType=Ind,Prs": {"morph": "Gender=Neut|Number=Sing|Person=3|PronType=Ind,Prs", POS: PRON},
<add> "PRON__Gender=Neut|Number=Sing|Poss=Yes|PronType=Prs": {"morph": "Gender=Neut|Number=Sing|Poss=Yes|PronType=Prs", POS: PRON},
<add> "PRON__Number=Plur|Person=3|Polarity=Neg|PronType=Neg,Prs": {"morph": "Number=Plur|Person=3|Polarity=Neg|PronType=Neg,Prs", POS: PRON},
<add> "PRON__Number=Plur|Person=3|PronType=Ind,Prs": {"morph": "Number=Plur|Person=3|PronType=Ind,Prs", POS: PRON},
<add> "PRON__Number=Plur|Person=3|PronType=Prs,Tot": {"morph": "Number=Plur|Person=3|PronType=Prs,Tot", POS: PRON},
<add> "PRON__Number=Plur|Poss=Yes|PronType=Prs": {"morph": "Number=Plur|Poss=Yes|PronType=Prs", POS: PRON},
<add> "PRON__Number=Plur|Poss=Yes|PronType=Rcp": {"morph": "Number=Plur|Poss=Yes|PronType=Rcp", POS: PRON},
<add> "PRON__Number=Sing|Polarity=Neg|PronType=Neg": {"morph": "Number=Sing|Polarity=Neg|PronType=Neg", POS: PRON},
<add> "PRON__PronType=Prs": {"morph": "PronType=Prs", POS: PRON},
<add> "PRON__PronType=Rel": {"morph": "PronType=Rel", POS: PRON},
<add> "PROPN__Abbr=Yes": {"morph": "Abbr=Yes", POS: PROPN},
<add> "PROPN__Abbr=Yes|Case=Gen": {"morph": "Abbr=Yes|Case=Gen", POS: PROPN},
<add> "VERB__Abbr=Yes|Mood=Ind|Tense=Pres|VerbForm=Fin": {"morph": "Abbr=Yes|Mood=Ind|Tense=Pres|VerbForm=Fin", POS: VERB},
<add> "VERB__Definite=Ind|Number=Sing|VerbForm=Part": {"morph": "Definite=Ind|Number=Sing|VerbForm=Part", POS: VERB},
<ide> } | 1 |
Javascript | Javascript | name anonymous functions for debugging purposes | 2d03f93fedd5c1a6ea98954d2451375b3683c933 | <ide><path>test/driver.js
<ide> function load() {
<ide>
<ide> var r = new XMLHttpRequest();
<ide> r.open('GET', manifestFile, false);
<del> r.onreadystatechange = function(e) {
<add> r.onreadystatechange = function loadOnreadystatechange(e) {
<ide> if (r.readyState == 4) {
<ide> log('done\n');
<ide> manifest = JSON.parse(r.responseText);
<ide> function nextTask() {
<ide> var r = new XMLHttpRequest();
<ide> r.open('GET', task.file);
<ide> r.mozResponseType = r.responseType = 'arraybuffer';
<del> r.onreadystatechange = function() {
<add> r.onreadystatechange = function nextTaskOnreadystatechange() {
<ide> var failure;
<ide> if (r.readyState == 4) {
<ide> var data = r.mozResponseArrayBuffer || r.mozResponse ||
<ide> function isLastPage(task) {
<ide> return (task.pageNum > task.pdfDoc.numPages);
<ide> }
<ide>
<add>function canvasToDataURL() {
<add> return canvas.toDataURL('image/png');
<add>}
<add>
<ide> function nextPage(task, loadError) {
<ide> var failure = loadError || '';
<ide>
<ide> if (!task.pdfDoc) {
<del> sendTaskResult(canvas.toDataURL('image/png'), task, failure);
<add> sendTaskResult(canvasToDataURL(), task, failure);
<ide> log('done' + (failure ? ' (failed !: ' + failure + ')' : '') + '\n');
<ide> ++currentTaskIdx;
<ide> nextTask();
<ide> function nextPage(task, loadError) {
<ide>
<ide> page.startRendering(
<ide> ctx,
<del> function(e) {
<add> function nextPageStartRendering(e) {
<ide> snapshotCurrentPage(task, (!failure && e) ?
<ide> ('render : ' + e) : failure);
<ide> }
<ide> function nextPage(task, loadError) {
<ide> function snapshotCurrentPage(task, failure) {
<ide> log('done, snapshotting... ');
<ide>
<del> sendTaskResult(canvas.toDataURL('image/png'), task, failure);
<add> sendTaskResult(canvasToDataURL(), task, failure);
<ide> log('done' + (failure ? ' (failed !: ' + failure + ')' : '') + '\n');
<ide>
<ide> // Set up the next request
<ide> var backoff = (inFlightRequests > 0) ? inFlightRequests * 10 : 0;
<ide> setTimeout(
<del> function() {
<add> function snapshotCurrentPageSetTimeout() {
<ide> ++task.pageNum;
<ide> nextPage(task);
<ide> },
<ide> function sendTaskResult(snapshot, task, failure) {
<ide> // (The POST URI is ignored atm.)
<ide> r.open('POST', '/submit_task_results', true);
<ide> r.setRequestHeader('Content-Type', 'application/json');
<del> r.onreadystatechange = function(e) {
<add> r.onreadystatechange = function sendTaskResultOnreadystatechange(e) {
<ide> if (r.readyState == 4) {
<ide> inFlightRequests--;
<ide> } | 1 |
Ruby | Ruby | simplify non-plist return | 4c67a8ce27394d05f7436907d7f0afb8f1845189 | <ide><path>Library/Homebrew/extend/os/mac/caveats.rb
<ide> class Caveats
<ide>
<ide> def plist_caveats
<ide> s = []
<del> if !f.plist && !f.service? && !keg&.plist_installed?
<del> caveat = "#{s.join("\n")}\n" if s.present?
<del> return caveat
<del> end
<add> return if !f.plist && !f.service? && !keg&.plist_installed?
<ide>
<ide> plist_domain = f.plist_path.basename(".plist")
<ide> | 1 |
Javascript | Javascript | extract dommanip to a separate file | ee6e874075ba1fcd8f9e62cd1ee5c04f6518b6d6 | <ide><path>src/manipulation.js
<ide> import jQuery from "./core.js";
<ide> import isAttached from "./core/isAttached.js";
<del>import flat from "./var/flat.js";
<ide> import isIE from "./var/isIE.js";
<ide> import push from "./var/push.js";
<ide> import access from "./core/access.js";
<ide> import rtagName from "./manipulation/var/rtagName.js";
<del>import rscriptType from "./manipulation/var/rscriptType.js";
<ide> import wrapMap from "./manipulation/wrapMap.js";
<ide> import getAll from "./manipulation/getAll.js";
<add>import domManip from "./manipulation/domManip.js";
<ide> import setGlobalEval from "./manipulation/setGlobalEval.js";
<del>import buildFragment from "./manipulation/buildFragment.js";
<ide> import dataPriv from "./data/var/dataPriv.js";
<ide> import dataUser from "./data/var/dataUser.js";
<ide> import acceptData from "./data/var/acceptData.js";
<del>import DOMEval from "./core/DOMEval.js";
<ide> import nodeName from "./core/nodeName.js";
<ide>
<ide> import "./core/init.js";
<ide> function manipulationTarget( elem, content ) {
<ide> return elem;
<ide> }
<ide>
<del>// Replace/restore the type attribute of script elements for safe DOM manipulation
<del>function disableScript( elem ) {
<del> elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
<del> return elem;
<del>}
<del>function restoreScript( elem ) {
<del> if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
<del> elem.type = elem.type.slice( 5 );
<del> } else {
<del> elem.removeAttribute( "type" );
<del> }
<del>
<del> return elem;
<del>}
<del>
<ide> function cloneCopyEvent( src, dest ) {
<ide> var i, l, type, pdataOld, udataOld, udataCur, events;
<ide>
<ide> function cloneCopyEvent( src, dest ) {
<ide> }
<ide> }
<ide>
<del>function domManip( collection, args, callback, ignored ) {
<del>
<del> // Flatten any nested arrays
<del> args = flat( args );
<del>
<del> var fragment, first, scripts, hasScripts, node, doc,
<del> i = 0,
<del> l = collection.length,
<del> iNoClone = l - 1,
<del> value = args[ 0 ],
<del> valueIsFunction = typeof value === "function";
<del>
<del> if ( valueIsFunction ) {
<del> return collection.each( function( index ) {
<del> var self = collection.eq( index );
<del> args[ 0 ] = value.call( this, index, self.html() );
<del> domManip( self, args, callback, ignored );
<del> } );
<del> }
<del>
<del> if ( l ) {
<del> fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
<del> first = fragment.firstChild;
<del>
<del> if ( fragment.childNodes.length === 1 ) {
<del> fragment = first;
<del> }
<del>
<del> // Require either new content or an interest in ignored elements to invoke the callback
<del> if ( first || ignored ) {
<del> scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
<del> hasScripts = scripts.length;
<del>
<del> // Use the original fragment for the last item
<del> // instead of the first because it can end up
<del> // being emptied incorrectly in certain situations (trac-8070).
<del> for ( ; i < l; i++ ) {
<del> node = fragment;
<del>
<del> if ( i !== iNoClone ) {
<del> node = jQuery.clone( node, true, true );
<del>
<del> // Keep references to cloned scripts for later restoration
<del> if ( hasScripts ) {
<del> jQuery.merge( scripts, getAll( node, "script" ) );
<del> }
<del> }
<del>
<del> callback.call( collection[ i ], node, i );
<del> }
<del>
<del> if ( hasScripts ) {
<del> doc = scripts[ scripts.length - 1 ].ownerDocument;
<del>
<del> // Reenable scripts
<del> jQuery.map( scripts, restoreScript );
<del>
<del> // Evaluate executable scripts on first document insertion
<del> for ( i = 0; i < hasScripts; i++ ) {
<del> node = scripts[ i ];
<del> if ( rscriptType.test( node.type || "" ) &&
<del> !dataPriv.access( node, "globalEval" ) &&
<del> jQuery.contains( doc, node ) ) {
<del>
<del> if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) {
<del>
<del> // Optional AJAX dependency, but won't run scripts if not present
<del> if ( jQuery._evalUrl && !node.noModule ) {
<del> jQuery._evalUrl( node.src, {
<del> nonce: node.nonce,
<del> crossOrigin: node.crossOrigin
<del> }, doc );
<del> }
<del> } else {
<del> DOMEval( node.textContent, node, doc );
<del> }
<del> }
<del> }
<del> }
<del> }
<del> }
<del>
<del> return collection;
<del>}
<del>
<ide> function remove( elem, selector, keepData ) {
<ide> var node,
<ide> nodes = selector ? jQuery.filter( selector, elem ) : elem,
<ide><path>src/manipulation/domManip.js
<add>import jQuery from "../core.js";
<add>import flat from "../var/flat.js";
<add>import rscriptType from "./var/rscriptType.js";
<add>import getAll from "./getAll.js";
<add>import buildFragment from "./buildFragment.js";
<add>import dataPriv from "../data/var/dataPriv.js";
<add>import DOMEval from "../core/DOMEval.js";
<add>
<add>// Replace/restore the type attribute of script elements for safe DOM manipulation
<add>function disableScript( elem ) {
<add> elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
<add> return elem;
<add>}
<add>function restoreScript( elem ) {
<add> if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
<add> elem.type = elem.type.slice( 5 );
<add> } else {
<add> elem.removeAttribute( "type" );
<add> }
<add>
<add> return elem;
<add>}
<add>
<add>function domManip( collection, args, callback, ignored ) {
<add>
<add> // Flatten any nested arrays
<add> args = flat( args );
<add>
<add> var fragment, first, scripts, hasScripts, node, doc,
<add> i = 0,
<add> l = collection.length,
<add> iNoClone = l - 1,
<add> value = args[ 0 ],
<add> valueIsFunction = typeof value === "function";
<add>
<add> if ( valueIsFunction ) {
<add> return collection.each( function( index ) {
<add> var self = collection.eq( index );
<add> args[ 0 ] = value.call( this, index, self.html() );
<add> domManip( self, args, callback, ignored );
<add> } );
<add> }
<add>
<add> if ( l ) {
<add> fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
<add> first = fragment.firstChild;
<add>
<add> if ( fragment.childNodes.length === 1 ) {
<add> fragment = first;
<add> }
<add>
<add> // Require either new content or an interest in ignored elements to invoke the callback
<add> if ( first || ignored ) {
<add> scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
<add> hasScripts = scripts.length;
<add>
<add> // Use the original fragment for the last item
<add> // instead of the first because it can end up
<add> // being emptied incorrectly in certain situations (trac-8070).
<add> for ( ; i < l; i++ ) {
<add> node = fragment;
<add>
<add> if ( i !== iNoClone ) {
<add> node = jQuery.clone( node, true, true );
<add>
<add> // Keep references to cloned scripts for later restoration
<add> if ( hasScripts ) {
<add> jQuery.merge( scripts, getAll( node, "script" ) );
<add> }
<add> }
<add>
<add> callback.call( collection[ i ], node, i );
<add> }
<add>
<add> if ( hasScripts ) {
<add> doc = scripts[ scripts.length - 1 ].ownerDocument;
<add>
<add> // Reenable scripts
<add> jQuery.map( scripts, restoreScript );
<add>
<add> // Evaluate executable scripts on first document insertion
<add> for ( i = 0; i < hasScripts; i++ ) {
<add> node = scripts[ i ];
<add> if ( rscriptType.test( node.type || "" ) &&
<add> !dataPriv.access( node, "globalEval" ) &&
<add> jQuery.contains( doc, node ) ) {
<add>
<add> if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) {
<add>
<add> // Optional AJAX dependency, but won't run scripts if not present
<add> if ( jQuery._evalUrl && !node.noModule ) {
<add> jQuery._evalUrl( node.src, {
<add> nonce: node.nonce,
<add> crossOrigin: node.crossOrigin
<add> }, doc );
<add> }
<add> } else {
<add> DOMEval( node.textContent, node, doc );
<add> }
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> return collection;
<add>}
<add>
<add>export default domManip;
<ide><path>test/unit/ajax.js
<ide> if ( typeof window.ArrayBuffer === "undefined" || typeof new XMLHttpRequest().re
<ide> } );
<ide> } );
<ide>
<del>//----------- jQuery.domManip()
<add>//----------- domManip()
<ide>
<del> QUnit.test( "trac-11264 - jQuery.domManip() - no side effect because of ajaxSetup or global events", function( assert ) {
<add> QUnit.test( "trac-11264 - domManip() - no side effect because of ajaxSetup or global events", function( assert ) {
<ide> assert.expect( 1 );
<ide>
<ide> jQuery.ajaxSetup( {
<ide> if ( typeof window.ArrayBuffer === "undefined" || typeof new XMLHttpRequest().re
<ide> );
<ide>
<ide> QUnit.test(
<del> "trac-11402 - jQuery.domManip() - script in comments are properly evaluated",
<add> "trac-11402 - domManip() - script in comments are properly evaluated",
<ide> function( assert ) {
<ide> assert.expect( 2 );
<ide> jQuery( "#qunit-fixture" ).load( baseURL + "cleanScript.html", assert.async() ); | 3 |
Javascript | Javascript | allow usage of a string path with {{bind}} helper | 65800fe09483bed3fc8adadd0678ee343f05a3e5 | <ide><path>packages/ember-htmlbars/lib/helpers/binding.js
<ide> function bindHelper(params, hash, options, env) {
<ide>
<ide> var property = params[0];
<ide>
<add> if (options.types[0] === 'string') {
<add> property = this.getStream(property);
<add> }
<add>
<ide> if (options.render) {
<ide> options.helperName = 'bind';
<ide> Ember.deprecate("The block form of bind, {{#bind foo}}{{/bind}}, has been deprecated and will be removed.");
<ide> bind.call(this, property, hash, options, env, false, exists);
<ide> } else {
<del> simpleBind.call(this, params, hash, options, env);
<add> simpleBind.call(this, [property], hash, options, env);
<ide> }
<ide> }
<ide>
<ide><path>packages/ember-htmlbars/tests/helpers/bind_test.js
<ide> test("it should render the current value of a path on the context", function() {
<ide> equal(view.$().text(), "MWEEER", "value can be updated");
<ide> });
<ide>
<add>test("it should render the current value of a string path on the context", function() {
<add> view = EmberView.create({
<add> template: compile('{{bind "foo.bar"}}'),
<add> context: EmberObject.create({
<add> foo: {
<add> bar: "BORK"
<add> }
<add> })
<add> });
<add>
<add> appendView(view);
<add>
<add> equal(view.$().text(), "BORK", "initial value is rendered");
<add>
<add> run(view, view.set, 'context.foo.bar', 'MWEEER');
<add>
<add> equal(view.$().text(), "MWEEER", "value can be updated");
<add>});
<add>
<ide> QUnit.module("ember-htmlbars: {{bind}} with a container, block forms", {
<ide> setup: function() {
<ide> container = new Container(); | 2 |
Python | Python | correct an issue with the kill function | f43ed60ce86430efc88be114f29f89cc4dc5dd57 | <ide><path>glances/outputs/glances_curses.py
<ide> def display(self, stats, cs_status=None):
<ide> # Display kill process confirmation popup
<ide> # Only in standalone mode (cs_status is None)
<ide> if self.kill_process and cs_status is None:
<del> self.kill_process(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
<add> logger.info(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
<add> self.kill(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
<ide> elif self.kill_process and cs_status is not None:
<ide> self.display_popup('Kill process only available for local processes')
<ide> self.kill_process = False
<ide> def display(self, stats, cs_status=None):
<ide>
<ide> return True
<ide>
<del> def kill_process(self, process):
<add> def kill(self, process):
<ide> """Kill a process, or a list of process if the process has a childrens field.
<ide>
<ide> :param process | 1 |
Ruby | Ruby | add address wrapping | 731bfa7cf45b8b849e63990d933fc65a14a6b860 | <ide><path>lib/action_mailbox/mail_ext/address_wrapping.rb
<add>class Mail::Address
<add> def self.wrap(address)
<add> address.is_a?(Mail::Address) ? address : Mail::Address.new(address)
<add> end
<add>end
<ide><path>test/unit/mail_ext/address_wrapping_test.rb
<add>require_relative '../../test_helper'
<add>
<add>module MailExt
<add> class AddressWrappingTest < ActiveSupport::TestCase
<add> test "wrap" do
<add> needing_wrapping = Mail::Address.wrap("david@basecamp.com")
<add> wrapping_not_needed = Mail::Address.wrap(Mail::Address.new("david@basecamp.com"))
<add> assert_equal needing_wrapping.address, wrapping_not_needed.address
<add> end
<add> end
<add>end | 2 |
PHP | PHP | remove extra argument | 313ce9c9b96e9c2c329d1d77d303492854f07e31 | <ide><path>src/View/Cell.php
<ide> public function __get($name)
<ide> if (in_array($name, $protected, true)) {
<ide> deprecationWarning(sprintf(
<ide> 'Cell::$%s is now protected and shouldn\'t be accessed from outside a child class.',
<del> $name,
<del> $method
<add> $name
<ide> ));
<ide> }
<ide>
<ide> public function __set($name, $value)
<ide> if (in_array($name, $protected, true)) {
<ide> deprecationWarning(sprintf(
<ide> 'Cell::$%s is now protected and shouldn\'t be accessed from outside a child class.',
<del> $name,
<del> $method
<add> $name
<ide> ));
<ide> }
<ide> | 1 |
Go | Go | defer udev wait during removal | cef27e1d6c0bd302e1c58e9478a0fba99fd3a2d0 | <ide><path>pkg/devicemapper/devmapper.go
<ide> func RemoveDevice(name string) error {
<ide> if err := task.SetCookie(&cookie, 0); err != nil {
<ide> return fmt.Errorf("Can not set cookie: %s", err)
<ide> }
<add> defer UdevWait(cookie)
<ide>
<add> dmSawBusy = false // reset before the task is run
<ide> if err = task.Run(); err != nil {
<ide> if dmSawBusy {
<ide> return ErrBusy
<ide> }
<ide> return fmt.Errorf("Error running RemoveDevice %s", err)
<ide> }
<ide>
<del> UdevWait(cookie)
<del>
<ide> return nil
<ide> }
<ide>
<ide> func CreateDevice(poolName string, deviceId *int) error {
<ide> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<del> dmSawExist = false
<add> dmSawExist = false // reset before the task is run
<ide> if err := task.Run(); err != nil {
<ide> if dmSawExist {
<ide> // Already exists, try next id
<ide> func CreateSnapDevice(poolName string, deviceId *int, baseName string, baseDevic
<ide> return fmt.Errorf("Can't set message %s", err)
<ide> }
<ide>
<del> dmSawExist = false
<add> dmSawExist = false // reset before the task is run
<ide> if err := task.Run(); err != nil {
<ide> if dmSawExist {
<ide> // Already exists, try next id | 1 |
Ruby | Ruby | add helper for printing file listings | d2d4813a07ccc077690bb86e522744fa19d2bdd4 | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def find_relative_paths *relative_paths
<ide> found + relative_paths.map{|f| File.join(prefix, f) }.select{|f| File.exist? f }
<ide> end
<ide> end
<add>
<add> def inject_file_list(list, str)
<add> list.inject(str) { |s, f| s << " #{f}\n" }
<add> end
<ide> ############# END HELPERS
<ide>
<ide> # See https://github.com/mxcl/homebrew/pull/9986
<ide> def check_for_stray_dylibs
<ide>
<ide> Unexpected dylibs:
<ide> EOS
<del> bad_dylibs.each { |f| s << " #{f}" }
<del> s
<add> inject_file_list(bad_dylibs, s)
<ide> end
<ide>
<ide> def check_for_stray_static_libs
<ide> def check_for_stray_static_libs
<ide>
<ide> Unexpected static libraries:
<ide> EOS
<del> bad_alibs.each{ |f| s << " #{f}" }
<del> s
<add> inject_file_list(bad_alibs, s)
<ide> end
<ide>
<ide> def check_for_stray_pcs
<ide> def check_for_stray_pcs
<ide>
<ide> Unexpected .pc files:
<ide> EOS
<del> bad_pcs.each{ |f| s << " #{f}" }
<del> s
<add> inject_file_list(bad_pcs, s)
<ide> end
<ide>
<ide> def check_for_stray_las
<ide> def check_for_stray_las
<ide>
<ide> Unexpected .la files:
<ide> EOS
<del> bad_las.each{ |f| s << " #{f}" }
<del> s
<add> inject_file_list(bad_las, s)
<ide> end
<ide>
<ide> def check_for_other_package_managers
<ide> def check_for_gettext
<ide> These files can cause compilation and link failures, especially if they
<ide> are compiled with improper architectures. Consider removing these files:
<ide> EOS
<del> @found.inject(s) { |s, f| s << " #{f}\n" }
<add> inject_file_list(@found, s)
<ide> end
<ide>
<ide> def check_for_iconv
<ide> def check_for_iconv
<ide>
<ide> tl;dr: delete these files:
<ide> EOS
<del> @found.inject(s){|s, f| s << " #{f}\n" }
<add> inject_file_list(@found, s)
<ide> end
<ide> end
<ide> end | 1 |
Mixed | Ruby | remove the dependent_restrict_raises option | 5ad79989ef0a015fd22cfed90b2e8a56881e6c36 | <ide><path>activerecord/CHANGELOG.md
<ide> * Added the `ActiveRecord::NullRelation` class implementing the null
<ide> object pattern for the Relation class. *Juanjo Bazán*
<ide>
<del>* Added deprecation for the `:dependent => :restrict` association option.
<add>* Added new `:dependent => :restrict_with_error` option. This will add
<add> an error to the model, rather than raising an exception.
<ide>
<del> Please note:
<del>
<del> * Up until now `has_many` and `has_one`, `:dependent => :restrict`
<del> option raised a `DeleteRestrictionError` at the time of destroying
<del> the object. Instead, it will add an error on the model.
<del>
<del> * To fix this warning, make sure your code isn't relying on a
<del> `DeleteRestrictionError` and then add
<del> `config.active_record.dependent_restrict_raises = false` to your
<del> application config.
<del>
<del> * New rails application would be generated with the
<del> `config.active_record.dependent_restrict_raises = false` in the
<del> application config.
<add> The `:restrict` option is renamed to `:restrict_with_exception` to
<add> make this distinction explicit.
<ide>
<del> *Manoj Kumar*
<add> *Manoj Kumar & Jon Leighton*
<ide>
<ide> * Added `create_join_table` migration helper to create HABTM join tables
<ide>
<ide><path>activerecord/lib/active_record/associations.rb
<ide> module ClassMethods
<ide> # [:primary_key]
<ide> # Specify the method that returns the primary key used for the association. By default this is +id+.
<ide> # [:dependent]
<del> # If set to <tt>:destroy</tt> all the associated objects are destroyed
<del> # alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
<del> # objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
<del> # objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. If set to
<del> # <tt>:restrict</tt> an error will be added to the object, preventing its deletion, if any associated
<del> # objects are present.
<add> # Controls what happens to the associated objects when
<add> # their owner is destroyed:
<add> #
<add> # * <tt>:destroy</tt> causes all the associated objects to also be destroyed
<add> # * <tt>:delete_all</tt> causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute)
<add> # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
<add> # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records
<add> # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects
<ide> #
<ide> # If using with the <tt>:through</tt> option, the association on the join model must be
<ide> # a +belongs_to+, and the records which get deleted are the join records, rather than
<ide> def has_many(name, scope = nil, options = {}, &extension)
<ide> # from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
<ide> # if the real class name is Person, you'll have to specify it with this option.
<ide> # [:dependent]
<del> # If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
<del> # <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method.
<del> # If set to <tt>:nullify</tt>, the associated object's foreign key is set to +NULL+.
<del> # If set to <tt>:restrict</tt>, an error will be added to the object, preventing its deletion, if an
<del> # associated object is present.
<add> # Controls what happens to the associated objects when
<add> # their owner is destroyed:
<add> #
<add> # * <tt>:destroy</tt> causes all the associated objects to also be destroyed
<add> # * <tt>:delete</tt> causes all the asssociated objects to be deleted directly from the database (so callbacks will not execute)
<add> # * <tt>:nullify</tt> causes the foreign keys to be set to +NULL+. Callbacks are not executed.
<add> # * <tt>:restrict_with_exception</tt> causes an exception to be raised if there are any associated records
<add> # * <tt>:restrict_with_error</tt> causes an error to be added to the owner if there are any associated objects
<ide> # [:foreign_key]
<ide> # Specify the foreign key used for the association. By default this is guessed to be the name
<ide> # of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association
<ide><path>activerecord/lib/active_record/associations/builder/association.rb
<ide> def check_valid_dependent!(dependent, valid_options)
<ide> raise ArgumentError, "The :dependent option expects either " \
<ide> "#{valid_options_message} (#{dependent.inspect})"
<ide> end
<del> end
<ide>
<del> def dependent_restrict_raises?
<del> ActiveRecord::Base.dependent_restrict_raises == true
<add> if dependent == :restrict
<add> ActiveSupport::Deprecation.warn(
<add> "The :restrict option is deprecated. Please use :restrict_with_exception instead, which " \
<add> "provides the same functionality."
<add> )
<add> end
<ide> end
<ide>
<del> def dependent_restrict_deprecation_warning
<del> if dependent_restrict_raises?
<del> msg = "In the next release, `:dependent => :restrict` will not raise a `DeleteRestrictionError`. "\
<del> "Instead, it will add an error on the model. To fix this warning, make sure your code " \
<del> "isn't relying on a `DeleteRestrictionError` and then add " \
<del> "`config.active_record.dependent_restrict_raises = false` to your application config."
<del> ActiveSupport::Deprecation.warn msg
<add> def define_restrict_with_exception_dependency_method
<add> name = self.name
<add> mixin.redefine_method(dependency_method_name) do
<add> has_one_macro = association(name).reflection.macro == :has_one
<add> if has_one_macro ? !send(name).nil? : send(name).exists?
<add> raise ActiveRecord::DeleteRestrictionError.new(name)
<add> end
<ide> end
<ide> end
<add> alias define_restrict_dependency_method define_restrict_with_exception_dependency_method
<ide>
<del> def define_restrict_dependency_method
<add> def define_restrict_with_error_dependency_method
<ide> name = self.name
<ide> mixin.redefine_method(dependency_method_name) do
<ide> has_one_macro = association(name).reflection.macro == :has_one
<ide> if has_one_macro ? !send(name).nil? : send(name).exists?
<del> if dependent_restrict_raises?
<del> raise ActiveRecord::DeleteRestrictionError.new(name)
<del> else
<del> key = has_one_macro ? "one" : "many"
<del> errors.add(:base, :"restrict_dependent_destroy.#{key}",
<del> :record => self.class.human_attribute_name(name).downcase)
<del> return false
<del> end
<add> key = has_one_macro ? "one" : "many"
<add> errors.add(:base, :"restrict_dependent_destroy.#{key}",
<add> :record => self.class.human_attribute_name(name).downcase)
<add> false
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/associations/builder/has_many.rb
<ide> def build
<ide>
<ide> def configure_dependency
<ide> if dependent = options[:dependent]
<del> check_valid_dependent! dependent, [:destroy, :delete_all, :nullify, :restrict]
<del> dependent_restrict_deprecation_warning if dependent == :restrict
<add> check_valid_dependent! dependent, [:destroy, :delete_all, :nullify, :restrict,
<add> :restrict_with_error, :restrict_with_exception]
<ide>
<ide> send("define_#{dependent}_dependency_method")
<ide> model.before_destroy dependency_method_name
<ide><path>activerecord/lib/active_record/associations/builder/has_one.rb
<ide> def build
<ide>
<ide> def configure_dependency
<ide> if dependent = options[:dependent]
<del> check_valid_dependent! dependent, [:destroy, :delete, :nullify, :restrict]
<del> dependent_restrict_deprecation_warning if dependent == :restrict
<add> check_valid_dependent! dependent, [:destroy, :delete, :nullify, :restrict, :restrict_with_error, :restrict_with_exception]
<ide>
<ide> send("define_#{dependent}_dependency_method")
<ide> model.before_destroy dependency_method_name
<ide><path>activerecord/lib/active_record/core.rb
<ide> module Core
<ide> # The connection handler
<ide> config_attribute :connection_handler
<ide>
<del> ##
<del> # :singleton-method:
<del> # Specifies whether or not has_many or has_one association option
<del> # :dependent => :restrict raises an exception. If set to true, the
<del> # ActiveRecord::DeleteRestrictionError exception will be raised
<del> # along with a DEPRECATION WARNING. If set to false, an error would
<del> # be added to the model instead.
<del> config_attribute :dependent_restrict_raises
<del>
<ide> %w(logger configurations default_timezone schema_format timestamped_migrations).each do |name|
<ide> config_attribute name, global: true
<ide> end
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_depends_and_nullify
<ide> end
<ide>
<ide> def test_restrict
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = true
<del>
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.companies.create(:name => 'child')
<ide>
<ide> assert !firm.companies.empty?
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.companies.exists?(:name => 'child')
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<del> def test_restrict_when_dependent_restrict_raises_config_set_to_false
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = false
<add> def test_restrict_is_deprecated
<add> klass = Class.new(ActiveRecord::Base)
<add> assert_deprecated { klass.has_many :posts, dependent: :restrict }
<add> end
<ide>
<del> firm = RestrictedFirm.create!(:name => 'restrict')
<add> def test_restrict_with_exception
<add> firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
<add> firm.companies.create(:name => 'child')
<add>
<add> assert !firm.companies.empty?
<add> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<add> assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
<add> assert firm.companies.exists?(:name => 'child')
<add> end
<add>
<add> def test_restrict_with_error
<add> firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
<ide> firm.companies.create(:name => 'child')
<ide>
<ide> assert !firm.companies.empty?
<ide> def test_restrict_when_dependent_restrict_raises_config_set_to_false
<ide> assert !firm.errors.empty?
<ide>
<ide> assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
<del> assert RestrictedFirm.exists?(:name => 'restrict')
<add> assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
<ide> assert firm.companies.exists?(:name => 'child')
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<ide> def test_included_in_collection
<ide> def test_replace_returns_target
<ide> assert_equal [bulb1, bulb3], result
<ide> end
<ide>
<del> def test_building_has_many_association_with_restrict_dependency
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = true
<del>
<del> klass = Class.new(ActiveRecord::Base)
<del>
<del> assert_deprecated { klass.has_many :companies, :dependent => :restrict }
<del> assert_not_deprecated { klass.has_many :companies }
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<del> end
<del>
<ide> def test_collection_association_with_private_kernel_method
<ide> firm = companies(:first_firm)
<ide> assert_equal [accounts(:signals37)], firm.accounts.open
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_dependence_with_nil_associate
<ide> assert_nothing_raised { firm.destroy }
<ide> end
<ide>
<del> def test_dependence_with_restrict
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = true
<del>
<add> def test_restrict
<ide> firm = RestrictedFirm.create!(:name => 'restrict')
<ide> firm.create_account(:credit_limit => 10)
<ide>
<ide> def test_dependence_with_restrict
<ide> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<ide> assert RestrictedFirm.exists?(:name => 'restrict')
<ide> assert firm.account.present?
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<del> def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = false
<add> def test_restrict_is_deprecated
<add> klass = Class.new(ActiveRecord::Base)
<add> assert_deprecated { klass.has_one :post, dependent: :restrict }
<add> end
<ide>
<del> firm = RestrictedFirm.create!(:name => 'restrict')
<add> def test_restrict_with_exception
<add> firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
<ide> firm.create_account(:credit_limit => 10)
<ide>
<ide> assert_not_nil firm.account
<ide>
<del> firm.destroy
<del>
<del> assert !firm.errors.empty?
<del> assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
<del> assert RestrictedFirm.exists?(:name => 'restrict')
<add> assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
<add> assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
<ide> assert firm.account.present?
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<ide> end
<ide>
<del> def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false_and_attribute_name
<del> old_backend = I18n.backend
<del> I18n.backend = I18n::Backend::Simple.new
<del> I18n.backend.store_translations 'en', :activerecord => {:attributes => {:restricted_firm => {:account => "account model"}}}
<del>
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = false
<del>
<del> firm = RestrictedFirm.create!(:name => 'restrict')
<add> def test_restrict_with_error
<add> firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
<ide> firm.create_account(:credit_limit => 10)
<ide>
<ide> assert_not_nil firm.account
<ide>
<ide> firm.destroy
<ide>
<ide> assert !firm.errors.empty?
<del> assert_equal "Cannot delete record because a dependent account model exists", firm.errors[:base].first
<del> assert RestrictedFirm.exists?(:name => 'restrict')
<add> assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
<add> assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
<ide> assert firm.account.present?
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<del> I18n.backend = old_backend
<ide> end
<ide>
<ide> def test_successful_build_association
<ide> def test_association_attributes_are_available_to_after_initialize
<ide> assert_equal car.id, bulb.attributes_after_initialize['car_id']
<ide> end
<ide>
<del> def test_building_has_one_association_with_dependent_restrict
<del> option_before = ActiveRecord::Base.dependent_restrict_raises
<del> ActiveRecord::Base.dependent_restrict_raises = true
<del>
<del> klass = Class.new(ActiveRecord::Base)
<del>
<del> assert_deprecated { klass.has_one :account, :dependent => :restrict }
<del> assert_not_deprecated { klass.has_one :account }
<del> ensure
<del> ActiveRecord::Base.dependent_restrict_raises = option_before
<del> end
<del>
<ide> def test_has_one_transaction
<ide> company = companies(:first_firm)
<ide> account = Account.find(1)
<ide><path>activerecord/test/cases/helper.rb
<ide> # Show backtraces for deprecated behavior for quicker cleanup.
<ide> ActiveSupport::Deprecation.debug = true
<ide>
<del># Avoid deprecation warning setting dependent_restrict_raises to false. The default is true
<del>ActiveRecord::Base.dependent_restrict_raises = false
<del>
<ide> # Connect to the database
<ide> ARTest.connect
<ide>
<ide><path>activerecord/test/models/company.rb
<ide> class DependentFirm < Company
<ide> end
<ide>
<ide> class RestrictedFirm < Company
<del> has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict
<del> has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict
<add> ActiveSupport::Deprecation.silence do
<add> has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict
<add> has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict
<add> end
<add>end
<add>
<add>class RestrictedWithExceptionFirm < Company
<add> has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_exception
<add> has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_exception
<add>end
<add>
<add>class RestrictedWithErrorFirm < Company
<add> has_one :account, -> { order("id") }, :foreign_key => "firm_id", :dependent => :restrict_with_error
<add> has_many :companies, -> { order("id") }, :foreign_key => 'client_of', :dependent => :restrict_with_error
<ide> end
<ide>
<ide> class Client < Company
<ide><path>railties/lib/rails/generators/rails/app/templates/config/application.rb
<ide> class Application < Rails::Application
<ide> # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
<ide> # parameters by using an attr_accessible or attr_protected declaration.
<ide> <%= comment_if :skip_active_record %>config.active_record.whitelist_attributes = true
<del>
<del> # Specifies whether or not has_many or has_one association option :dependent => :restrict raises
<del> # an exception. If set to true, then an ActiveRecord::DeleteRestrictionError exception would be
<del> # raised. If set to false, then an error will be added on the model instead.
<del> <%= comment_if :skip_active_record %>config.active_record.dependent_restrict_raises = false
<ide> <% unless options.skip_sprockets? -%>
<ide>
<ide> # Enable the asset pipeline.
<ide><path>railties/test/generators/app_generator_test.rb
<ide> def test_active_record_whitelist_attributes_is_present_application_config
<ide> assert_file "config/application.rb", /config\.active_record\.whitelist_attributes = true/
<ide> end
<ide>
<del> def test_active_record_dependent_restrict_raises_is_present_application_config
<del> run_generator
<del> assert_file "config/application.rb", /config\.active_record\.dependent_restrict_raises = false/
<del> end
<del>
<ide> def test_pretend_option
<ide> output = run_generator [File.join(destination_root, "myapp"), "--pretend"]
<ide> assert_no_match(/run bundle install/, output) | 12 |
Ruby | Ruby | fix mktmp to be generic as-per sus/bsd | 1dc384b4c4e94621b7ba1b62358e5730dfb8e8da | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_multiple_volumes
<ide> # Find the volumes for the TMP folder & HOMEBREW_CELLAR
<ide> real_cellar = HOMEBREW_CELLAR.realpath
<ide>
<del> tmp = Pathname.new with_system_path { `mktemp -d #{HOMEBREW_TEMP}/homebrew-brew-doctor-XXXX` }.strip
<add> tmp = Pathname.new with_system_path { `mktemp -d #{HOMEBREW_TEMP}/homebrew-brew-doctor-XXXXXX` }.strip
<ide> real_temp = tmp.realpath.parent
<ide>
<ide> where_cellar = volumes.which real_cellar
<ide><path>Library/Homebrew/extend/fileutils.rb
<ide> def mktemp(prefix=name)
<ide> # /tmp volume to the other volume. So we let the user override the tmp
<ide> # prefix if they need to.
<ide>
<del> tempd = with_system_path { `mktemp -d #{HOMEBREW_TEMP}/#{prefix}-XXXX` }.chuzzle
<add> tempd = with_system_path { `mktemp -d #{HOMEBREW_TEMP}/#{prefix}-XXXXXX` }.chuzzle
<ide> raise "Failed to create sandbox" if tempd.nil?
<ide> prevd = pwd
<ide> cd tempd | 2 |
Ruby | Ruby | restore definition of effective_sysroot | 706e7e71a07784f14abbdf5f019428e04afcfae6 | <ide><path>Library/Homebrew/extend/os/mac/extend/ENV/super.rb
<ide> def self.bin
<ide> bin.realpath unless bin.nil?
<ide> end
<ide>
<add> def effective_sysroot
<add> MacOS::Xcode.without_clt? ? MacOS.sdk_path.to_s : nil
<add> end
<add>
<ide> def homebrew_extra_paths
<ide> paths = []
<ide> # On 10.9, there are shims for all tools in /usr/bin. | 1 |
Python | Python | fix typo in docstring | 21a9740156eed349b908057856aef9acd0e620a9 | <ide><path>rest_framework/throttling.py
<ide> class SimpleRateThrottle(BaseThrottle):
<ide> A simple cache implementation, that only requires `.get_cache_key()`
<ide> to be overridden.
<ide>
<del> The rate (requests / seconds) is set by a `throttle` attribute on the View
<add> The rate (requests / seconds) is set by a `rate` attribute on the View
<ide> class. The attribute is a string of the form 'number_of_requests/period'.
<ide>
<ide> Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') | 1 |
Ruby | Ruby | add custom comparator for macos.version | b8231fc5f3e93f2d7a230e7880fb2fdc7c04c369 | <ide><path>Library/Homebrew/macos.rb
<ide> module MacOS extend self
<ide> MDITEM_BUNDLE_ID_KEY = "kMDItemCFBundleIdentifier"
<ide>
<ide> def version
<del> MACOS_VERSION
<add> require 'version'
<add> MacOSVersion.new(MACOS_VERSION.to_s)
<ide> end
<ide>
<ide> def cat
<ide><path>Library/Homebrew/test/test_versions.rb
<ide> def test_version_comparisons
<ide> assert_version_comparison 'HEAD', '>', '1.2.3'
<ide> assert_version_comparison '1.2.3', '<', 'HEAD'
<ide> end
<add>
<add> def test_macos_version_comparison
<add> v = MacOSVersion.new(10.6)
<add> assert v == 10.6
<add> assert v == :snow_leopard
<add> assert v < :lion
<add> end
<ide> end
<ide>
<ide> class VersionParsingTests < Test::Unit::TestCase
<ide><path>Library/Homebrew/version.rb
<ide> def detect_from_symbol
<ide> raise "Unknown version scheme #{@scheme} was requested."
<ide> end
<ide> end
<add>
<add># Enable things like "MacOS.version >= :lion"
<add>class MacOSVersion < Version
<add> compare do |other|
<add> case other
<add> when Symbol, Fixnum, Float, Version
<add> super Version.new case other
<add> when :mountain_lion then 10.8
<add> when :lion then 10.7
<add> when :snow_leopard then 10.6
<add> when :leopard then 10.5
<add> else other
<add> end
<add> else
<add> nil
<add> end
<add> end
<add>end | 3 |
Ruby | Ruby | use `searchable` module | 717032d86dd458539004b67e1ac883937df0121f | <ide><path>Library/Homebrew/cmd/desc.rb
<ide> def desc
<ide> results.print
<ide> elsif search_type.size > 1
<ide> odie "Pick one, and only one, of -s/--search, -n/--name, or -d/--description."
<del> elsif arg = ARGV.named.join(" ")
<del> regex = query_regexp(arg)
<del> results = Descriptions.search(regex, search_type.first)
<add> elsif !ARGV.named.empty?
<add> arg = ARGV.named.join(" ")
<add> string_or_regex = query_regexp(arg)
<add> results = Descriptions.search(string_or_regex, search_type.first)
<ide> results.print
<ide> else
<ide> odie "You must provide a search term."
<ide><path>Library/Homebrew/cmd/install.rb
<ide> #: creating patches to the software.
<ide>
<ide> require "missing_formula"
<del>require "cmd/search"
<ide> require "formula_installer"
<ide> require "development_tools"
<ide> require "install"
<add>require "search"
<ide>
<ide> module Homebrew
<ide> module_function
<ide>
<add> extend Search
<add>
<ide> def install
<ide> raise FormulaUnspecifiedError if ARGV.named.empty?
<ide>
<ide> def install
<ide> return
<ide> end
<ide>
<del> regex = query_regexp(e.name)
<del>
<ide> ohai "Searching for similarly named formulae..."
<del> formulae_search_results = search_formulae(regex)
<add> formulae_search_results = search_formulae(e.name)
<ide> case formulae_search_results.length
<ide> when 0
<ide> ofail "No similarly named formulae found."
<ide><path>Library/Homebrew/cmd/search.rb
<ide> def search(argv = ARGV)
<ide> if args.remaining.empty?
<ide> puts Formatter.columns(Formula.full_names.sort)
<ide> elsif args.desc?
<del> query = args.remaining.first
<del> regex = query_regexp(query)
<del> Descriptions.search(regex, :desc).print
<add> query = args.remaining.join(" ")
<add> string_or_regex = query_regexp(query)
<add> Descriptions.search(string_or_regex, :desc).print
<ide> elsif args.remaining.first =~ HOMEBREW_TAP_FORMULA_REGEX
<ide> query = args.remaining.first
<ide>
<ide> def search(argv = ARGV)
<ide>
<ide> puts Formatter.columns(results) unless results.empty?
<ide> else
<del> query = args.remaining.first
<del> regex = query_regexp(query)
<del> local_results = search_formulae(regex)
<add> query = args.remaining.join(" ")
<add> string_or_regex = query_regexp(query)
<add> local_results = search_formulae(string_or_regex)
<ide> puts Formatter.columns(local_results.sort) unless local_results.empty?
<ide>
<ide> tap_results = search_taps(query).flatten.sort
<ide><path>Library/Homebrew/descriptions.rb
<ide> require "formula"
<ide> require "formula_versions"
<ide> require "search"
<add>require "searchable"
<ide>
<ide> class Descriptions
<ide> extend Homebrew::Search
<ide> def self.uncache_formulae(formula_names, options = { save: true })
<ide> end
<ide>
<ide> # Given a regex, find all formulae whose specified fields contain a match.
<del> def self.search(regex, field = :either)
<add> def self.search(string_or_regex, field = :either)
<ide> ensure_cache
<ide>
<add> @cache.extend(Searchable)
<add>
<ide> results = case field
<ide> when :name
<del> @cache.select { |name, _| simplify_string(name).match?(regex) }
<add> @cache.search(string_or_regex) { |name, _| name }
<ide> when :desc
<del> @cache.select { |_, desc| simplify_string(desc).match?(regex) }
<add> @cache.search(string_or_regex) { |_, desc| desc }
<ide> when :either
<del> @cache.select { |name, desc| simplify_string(name).match?(regex) || simplify_string(desc).match?(regex) }
<add> @cache.search(string_or_regex)
<ide> end
<ide>
<ide> new(results)
<ide><path>Library/Homebrew/search.rb
<add>require "searchable"
<add>
<ide> module Homebrew
<ide> module Search
<del> def simplify_string(string)
<del> string.downcase.gsub(/[^a-z\d]/i, "")
<del> end
<del>
<ide> def query_regexp(query)
<ide> if m = query.match(%r{^/(.*)/$})
<ide> Regexp.new(m[1])
<ide> else
<del> Regexp.new(simplify_string(query), Regexp::IGNORECASE)
<add> query
<ide> end
<ide> rescue RegexpError
<ide> raise "#{query} is not a valid regex."
<ide> def search_taps(query, silent: false)
<ide> [[], []]
<ide> end
<ide>
<del> def search_formulae(regex)
<add> def search_formulae(string_or_regex)
<ide> # Use stderr to avoid breaking parsed output
<ide> $stderr.puts Formatter.headline("Searching local taps...", color: :blue)
<ide>
<ide> aliases = Formula.alias_full_names
<ide> results = (Formula.full_names + aliases)
<del> .select { |name| simplify_string(name).match?(regex) }
<add> .extend(Searchable)
<add> .search(string_or_regex)
<ide> .sort
<ide>
<ide> results.map do |name|
<ide><path>Library/Homebrew/test/cask/cli/search_spec.rb
<ide> describe Hbc::CLI::Search, :cask do
<ide> before do
<ide> allow(Tty).to receive(:width).and_return(0)
<add> ENV.delete("HOMEBREW_NO_GITHUB_API")
<ide> end
<ide>
<ide> it_behaves_like "a command that handles invalid options"
<ide> end
<ide>
<ide> it "doesn't output anything to non-TTY stdout when there are no matches" do
<add> allow(GitHub).to receive(:search_code).and_return([])
<add>
<ide> expect { Hbc::CLI::Search.run("foo-bar-baz") }
<ide> .to not_to_output.to_stdout
<ide> .and not_to_output.to_stderr
<ide><path>Library/Homebrew/test/search_spec.rb
<ide> end
<ide> end
<ide>
<del> describe "#simplify_string" do
<del> it "simplifies a query with dashes" do
<del> expect(mod.query_regexp("que-ry")).to eq(/query/i)
<del> end
<del>
<del> it "simplifies a query with @ symbols" do
<del> expect(mod.query_regexp("query@1")).to eq(/query1/i)
<del> end
<del> end
<del>
<ide> describe "#query_regexp" do
<ide> it "correctly parses a regex query" do
<ide> expect(mod.query_regexp("/^query$/")).to eq(/^query$/)
<ide> end
<ide>
<del> it "correctly converts a query string to a regex" do
<del> expect(mod.query_regexp("query")).to eq(/query/i)
<del> end
<del>
<del> it "simplifies a query with special symbols" do
<del> expect(mod.query_regexp("que-ry")).to eq(/query/i)
<add> it "returns the original string if it is not a regex query" do
<add> expect(mod.query_regexp("query")).to eq("query")
<ide> end
<ide>
<ide> it "raises an error if the query is an invalid regex" do | 7 |
Go | Go | organize server pre-func logic in middlewares | 0fea04d27ee91d7b57e0a77b110db1c861768c74 | <ide><path>api/server/middleware.go
<add>package server
<add>
<add>import (
<add> "net/http"
<add> "runtime"
<add> "strings"
<add>
<add> "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/api"
<add> "github.com/docker/docker/autogen/dockerversion"
<add> "github.com/docker/docker/context"
<add> "github.com/docker/docker/errors"
<add> "github.com/docker/docker/pkg/stringid"
<add> "github.com/docker/docker/pkg/version"
<add>)
<add>
<add>// middleware is an adapter to allow the use of ordinary functions as Docker API filters.
<add>// Any function that has the appropriate signature can be register as a middleware.
<add>type middleware func(handler HTTPAPIFunc) HTTPAPIFunc
<add>
<add>// loggingMiddleware logs each request when logging is enabled.
<add>func (s *Server) loggingMiddleware(handler HTTPAPIFunc) HTTPAPIFunc {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if s.cfg.Logging {
<add> logrus.Infof("%s %s", r.Method, r.RequestURI)
<add> }
<add> return handler(ctx, w, r, vars)
<add> }
<add>}
<add>
<add>// requestIDMiddleware generates a uniq ID for each request.
<add>// This ID travels inside the context for tracing purposes.
<add>func requestIDMiddleware(handler HTTPAPIFunc) HTTPAPIFunc {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
<add> ctx = context.WithValue(ctx, context.RequestID, reqID)
<add> return handler(ctx, w, r, vars)
<add> }
<add>}
<add>
<add>// userAgentMiddleware checks the User-Agent header looking for a valid docker client spec.
<add>func (s *Server) userAgentMiddleware(handler HTTPAPIFunc) HTTPAPIFunc {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<add> dockerVersion := version.Version(s.cfg.Version)
<add>
<add> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<add>
<add> // v1.20 onwards includes the GOOS of the client after the version
<add> // such as Docker/1.7.0 (linux)
<add> if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
<add> userAgent[1] = strings.Split(userAgent[1], " ")[0]
<add> }
<add>
<add> if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
<add> logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
<add> }
<add> }
<add> return handler(ctx, w, r, vars)
<add> }
<add>}
<add>
<add>// corsMiddleware sets the CORS header expectations in the server.
<add>func (s *Server) corsMiddleware(handler HTTPAPIFunc) HTTPAPIFunc {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
<add> // otherwise, all head values will be passed to HTTP handler
<add> corsHeaders := s.cfg.CorsHeaders
<add> if corsHeaders == "" && s.cfg.EnableCors {
<add> corsHeaders = "*"
<add> }
<add>
<add> if corsHeaders != "" {
<add> writeCorsHeaders(w, r, corsHeaders)
<add> }
<add> return handler(ctx, w, r, vars)
<add> }
<add>}
<add>
<add>// versionMiddleware checks the api version requirements before passing the request to the server handler.
<add>func versionMiddleware(handler HTTPAPIFunc) HTTPAPIFunc {
<add> return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> apiVersion := version.Version(vars["version"])
<add> if apiVersion == "" {
<add> apiVersion = api.Version
<add> }
<add>
<add> if apiVersion.GreaterThan(api.Version) {
<add> return errors.ErrorCodeNewerClientVersion.WithArgs(apiVersion, api.Version)
<add> }
<add> if apiVersion.LessThan(api.MinVersion) {
<add> return errors.ErrorCodeOldClientVersion.WithArgs(apiVersion, api.Version)
<add> }
<add>
<add> w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
<add> ctx = context.WithValue(ctx, context.APIVersion, apiVersion)
<add> return handler(ctx, w, r, vars)
<add> }
<add>}
<add>
<add>// handleWithGlobalMiddlwares wraps the handler function for a request with
<add>// the server's global middlewares. The order of the middlewares is backwards,
<add>// meaning that the first in the list will be evaludated last.
<add>//
<add>// Example: handleWithGlobalMiddlewares(s.getContainersName)
<add>//
<add>// requestIDMiddlware(
<add>// s.loggingMiddleware(
<add>// s.userAgentMiddleware(
<add>// s.corsMiddleware(
<add>// versionMiddleware(s.getContainersName)
<add>// )
<add>// )
<add>// )
<add>// )
<add>func (s *Server) handleWithGlobalMiddlewares(handler HTTPAPIFunc) HTTPAPIFunc {
<add> middlewares := []middleware{
<add> versionMiddleware,
<add> s.corsMiddleware,
<add> s.userAgentMiddleware,
<add> s.loggingMiddleware,
<add> requestIDMiddleware,
<add> }
<add>
<add> h := handler
<add> for _, m := range middlewares {
<add> h = m(h)
<add> }
<add> return h
<add>}
<ide><path>api/server/middleware_test.go
<add>package server
<add>
<add>import (
<add> "net/http"
<add> "net/http/httptest"
<add> "testing"
<add>
<add> "github.com/docker/distribution/registry/api/errcode"
<add> "github.com/docker/docker/context"
<add> "github.com/docker/docker/errors"
<add>)
<add>
<add>func TestVersionMiddleware(t *testing.T) {
<add> handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if ctx.Version() == "" {
<add> t.Fatalf("Expected version, got empty string")
<add> }
<add> return nil
<add> }
<add>
<add> h := versionMiddleware(handler)
<add>
<add> req, _ := http.NewRequest("GET", "/containers/json", nil)
<add> resp := httptest.NewRecorder()
<add> ctx := context.Background()
<add> if err := h(ctx, resp, req, map[string]string{}); err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<add>
<add>func TestVersionMiddlewareWithErrors(t *testing.T) {
<add> handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if ctx.Version() == "" {
<add> t.Fatalf("Expected version, got empty string")
<add> }
<add> return nil
<add> }
<add>
<add> h := versionMiddleware(handler)
<add>
<add> req, _ := http.NewRequest("GET", "/containers/json", nil)
<add> resp := httptest.NewRecorder()
<add> ctx := context.Background()
<add>
<add> vars := map[string]string{"version": "0.1"}
<add> err := h(ctx, resp, req, vars)
<add> if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeOldClientVersion {
<add> t.Fatalf("Expected ErrorCodeOldClientVersion, got %v", err)
<add> }
<add>
<add> vars["version"] = "100000"
<add> err = h(ctx, resp, req, vars)
<add> if derr, ok := err.(errcode.Error); !ok || derr.ErrorCode() != errors.ErrorCodeNewerClientVersion {
<add> t.Fatalf("Expected ErrorCodeNewerClientVersion, got %v", err)
<add> }
<add>}
<add>
<add>func TestRequestIDMiddleware(t *testing.T) {
<add> handler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if ctx.RequestID() == "" {
<add> t.Fatalf("Expected request-id, got empty string")
<add> }
<add> return nil
<add> }
<add>
<add> h := requestIDMiddleware(handler)
<add>
<add> req, _ := http.NewRequest("GET", "/containers/json", nil)
<add> resp := httptest.NewRecorder()
<add> ctx := context.Background()
<add> if err := h(ctx, resp, req, map[string]string{}); err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<ide><path>api/server/server.go
<ide> import (
<ide> "net"
<ide> "net/http"
<ide> "os"
<del> "runtime"
<ide> "strings"
<ide>
<ide> "github.com/gorilla/mux"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/distribution/registry/api/errcode"
<ide> "github.com/docker/docker/api"
<del> "github.com/docker/docker/autogen/dockerversion"
<ide> "github.com/docker/docker/context"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/pkg/sockets"
<del> "github.com/docker/docker/pkg/stringid"
<del> "github.com/docker/docker/pkg/version"
<ide> )
<ide>
<ide> // Config provides the configuration for the API server
<ide> func New(cfg *Config) *Server {
<ide> cfg: cfg,
<ide> start: make(chan struct{}),
<ide> }
<del> r := createRouter(srv)
<del> srv.router = r
<add> srv.router = createRouter(srv)
<ide> return srv
<ide> }
<ide>
<ide> func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
<ide> return
<ide> }
<ide>
<del>func makeHTTPHandler(logging bool, localMethod string, localRoute string, handlerFunc HTTPAPIFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
<add>func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<add> // log the handler generation
<add> logrus.Debugf("Calling %s %s", localMethod, localRoute)
<add>
<ide> // Define the context that we'll pass around to share info
<ide> // like the docker-request-id.
<ide> //
<ide> // The 'context' will be used for global data that should
<ide> // apply to all requests. Data that is specific to the
<ide> // immediate function being called should still be passed
<ide> // as 'args' on the function call.
<del>
<del> reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
<del> apiVersion := version.Version(mux.Vars(r)["version"])
<del> if apiVersion == "" {
<del> apiVersion = api.Version
<del> }
<del>
<ide> ctx := context.Background()
<del> ctx = context.WithValue(ctx, context.RequestID, reqID)
<del> ctx = context.WithValue(ctx, context.APIVersion, apiVersion)
<del>
<del> // log the request
<del> logrus.Debugf("Calling %s %s", localMethod, localRoute)
<del>
<del> if logging {
<del> logrus.Infof("%s %s", r.Method, r.RequestURI)
<del> }
<del>
<del> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<del> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<del>
<del> // v1.20 onwards includes the GOOS of the client after the version
<del> // such as Docker/1.7.0 (linux)
<del> if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
<del> userAgent[1] = strings.Split(userAgent[1], " ")[0]
<del> }
<del>
<del> if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
<del> logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
<del> }
<del> }
<del> if corsHeaders != "" {
<del> writeCorsHeaders(w, r, corsHeaders)
<del> }
<del>
<del> if apiVersion.GreaterThan(api.Version) {
<del> http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", apiVersion, api.Version).Error(), http.StatusBadRequest)
<del> return
<del> }
<del> if apiVersion.LessThan(api.MinVersion) {
<del> http.Error(w, fmt.Errorf("client is too old, minimum supported API version is %s, please upgrade your client to a newer version", api.MinVersion).Error(), http.StatusBadRequest)
<del> return
<del> }
<del>
<del> w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
<add> handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
<ide>
<ide> if err := handlerFunc(ctx, w, r, mux.Vars(r)); err != nil {
<ide> logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
<ide> func makeHTTPHandler(logging bool, localMethod string, localRoute string, handle
<ide> }
<ide> }
<ide>
<add>// createRouter initializes the main router the server uses.
<ide> // we keep enableCors just for legacy usage, need to be removed in the future
<ide> func createRouter(s *Server) *mux.Router {
<ide> r := mux.NewRouter()
<ide> func createRouter(s *Server) *mux.Router {
<ide> },
<ide> }
<ide>
<del> // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
<del> // otherwise, all head values will be passed to HTTP handler
<del> corsHeaders := s.cfg.CorsHeaders
<del> if corsHeaders == "" && s.cfg.EnableCors {
<del> corsHeaders = "*"
<del> }
<del>
<ide> for method, routes := range m {
<ide> for route, fct := range routes {
<ide> logrus.Debugf("Registering %s, %s", method, route)
<ide> func createRouter(s *Server) *mux.Router {
<ide> localMethod := method
<ide>
<ide> // build the handler function
<del> f := makeHTTPHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
<add> f := s.makeHTTPHandler(localMethod, localRoute, localFct)
<ide>
<ide> // add the new route
<ide> if localRoute == "" {
<ide><path>api/server/server_test.go
<add>package server
<add>
<add>import (
<add> "net/http"
<add> "net/http/httptest"
<add> "testing"
<add>
<add> "github.com/docker/docker/context"
<add>)
<add>
<add>func TestMiddlewares(t *testing.T) {
<add> cfg := &Config{}
<add> srv := &Server{
<add> cfg: cfg,
<add> }
<add>
<add> req, _ := http.NewRequest("GET", "/containers/json", nil)
<add> resp := httptest.NewRecorder()
<add> ctx := context.Background()
<add>
<add> localHandler := func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if ctx.Version() == "" {
<add> t.Fatalf("Expected version, got empty string")
<add> }
<add> if ctx.RequestID() == "" {
<add> t.Fatalf("Expected request-id, got empty string")
<add> }
<add> return nil
<add> }
<add>
<add> handlerFunc := srv.handleWithGlobalMiddlewares(localHandler)
<add> if err := handlerFunc(ctx, resp, req, map[string]string{}); err != nil {
<add> t.Fatal(err)
<add> }
<add>}
<ide><path>errors/server.go
<add>package errors
<add>
<add>import (
<add> "net/http"
<add>
<add> "github.com/docker/distribution/registry/api/errcode"
<add>)
<add>
<add>var (
<add> // ErrorCodeNewerClientVersion is generated when a request from a client
<add> // specifies a higher version than the server supports.
<add> ErrorCodeNewerClientVersion = errcode.Register(errGroup, errcode.ErrorDescriptor{
<add> Value: "NEWERCLIENTVERSION",
<add> Message: "client is newer than server (client API version: %s, server API version: %s)",
<add> Description: "The client version is higher than the server version",
<add> HTTPStatusCode: http.StatusBadRequest,
<add> })
<add>
<add> // ErrorCodeOldClientVersion is generated when a request from a client
<add> // specifies a version lower than the minimum version supported by the server.
<add> ErrorCodeOldClientVersion = errcode.Register(errGroup, errcode.ErrorDescriptor{
<add> Value: "OLDCLIENTVERSION",
<add> Message: "client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version",
<add> Description: "The client version is too old for the server",
<add> HTTPStatusCode: http.StatusBadRequest,
<add> })
<add>) | 5 |
Python | Python | drop unneeded assert | 4e9385e709bcee87456a99839841ecf6b56f337a | <ide><path>rest_framework/tests/test_renderers.py
<ide> def test_parse_error_renderers_browsable_api(self):
<ide> """Invalid data should still render the browsable API correctly."""
<ide> resp = self.client.post('/parseerror', data='foobar', content_type='application/json', HTTP_ACCEPT='text/html')
<ide> self.assertEqual(resp['Content-Type'], 'text/html; charset=utf-8')
<del> self.assertIn('Mock Post', resp.content)
<ide> self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)
<ide>
<ide> _flat_repr = '{"foo": ["bar", "baz"]}' | 1 |
Ruby | Ruby | remove side effects of [5684] | 906bd93f4fdbad429cca8a0cfa7f32ec1eb7960a | <ide><path>activerecord/lib/active_record/associations/association_collection.rb
<ide> def destroy_all
<ide> end
<ide>
<ide> def create(attrs = {})
<del> record = @reflection.klass.with_scope(construct_scope) { @reflection.klass.create(attrs) }
<add> record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create(attrs) }
<ide> @target ||= [] unless loaded?
<ide> @target << record
<ide> record
<ide> end
<ide>
<ide> def create!(attrs = {})
<del> record = @reflection.klass.with_scope(construct_scope) { @reflection.klass.create!(attrs) }
<add> record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create!(attrs) }
<ide> @target ||= [] unless loaded?
<ide> @target << record
<ide> record
<ide><path>activerecord/lib/active_record/associations/has_one_association.rb
<ide> def initialize(owner, reflection)
<ide> end
<ide>
<ide> def create(attrs = {}, replace_existing = true)
<del> record = @reflection.klass.with_scope(construct_scope) { @reflection.klass.create(attrs) }
<add> record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create(attrs) }
<ide>
<ide> if replace_existing
<ide> replace(record, true)
<ide> def create(attrs = {}, replace_existing = true)
<ide> end
<ide>
<ide> def create!(attrs = {}, replace_existing = true)
<del> record = @reflection.klass.with_scope(construct_scope) { @reflection.klass.create!(attrs) }
<add> record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create!(attrs) }
<ide>
<ide> if replace_existing
<ide> replace(record, true) | 2 |
Ruby | Ruby | add collectionproxy#delete documentation | 29463aa15dd670621ad0de861b5aa66feeb09ffa | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> class CollectionProxy < Relation
<ide> ##
<ide> # :method: delete_all
<ide> #
<add> # :call-seq:
<add> # delete_all()
<add> #
<ide> # Deletes all the records from the collection. For +has_many+ asssociations,
<ide> # the deletion is done according to the strategy specified by the <tt>:dependent</tt>
<ide> # option. Returns an array with the deleted records.
<ide> class CollectionProxy < Relation
<ide> ##
<ide> # :method: destroy_all
<ide> #
<add> # :call-seq:
<add> # destroy_all()
<add> #
<ide> # Deletes the records of the collection directly from the database.
<ide> # This will _always_ remove the records ignoring the +:dependent+
<ide> # option.
<ide> class CollectionProxy < Relation
<ide> #
<ide> # Pet.find(1) # => Couldn't find Pet with id=1
<ide>
<add> ##
<add> # :method: delete
<add> #
<add> # :call-seq:
<add> # delete(*records)
<add> #
<add> # Deletes the +records+ supplied and remove them from the collection. For
<add> # +has_many+ associations, the deletion is done according to the strategy
<add> # specified by the <tt>:dependent</tt> option. Returns an array with the
<add> # deleted records.
<add> #
<add> # If no <tt>:dependent</tt> option is given, then it will follow the default
<add> # strategy. The default strategy is <tt>:nullify</tt>. This sets the foreign
<add> # keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>, the default
<add> # strategy is +delete_all+.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets # dependent: :nullify option by default
<add> # end
<add> #
<add> # person.pets.size # => 3
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # person.pets.delete(Pet.find(1))
<add> # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
<add> #
<add> # person.pets.size # => 2
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # Pet.find(1)
<add> # # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
<add> #
<add> # If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
<add> # their +destroy+ method. See +destroy+ for more information.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets, dependent: :destroy
<add> # end
<add> #
<add> # person.pets.size # => 3
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # person.pets.delete([Pet.find(1), Pet.find(3)])
<add> # # => [
<add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # person.pets.size # => 1
<add> # person.pets
<add> # # => [#<Pet id: 2, name: "Spook", person_id: 1>]
<add> #
<add> # Pet.find(1, 3)
<add> # # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)
<add> #
<add> # If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
<add> # *without* calling their +destroy+ method.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets, dependent: :delete_all
<add> # end
<add> #
<add> # person.pets.size # => 3
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # person.pets.delete(Pet.find(1))
<add> # # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
<add> #
<add> # person.pets.size # => 2
<add> # person.pets
<add> # # => [
<add> # # #<Pet id: 2, name: "Spook", person_id: 1>,
<add> # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
<add> # # ]
<add> #
<add> # Pet.find(1)
<add> # # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1
<add>
<ide> ##
<ide> # :method: destroy
<ide> #
<ide> # :call-seq:
<ide> # destroy(*records)
<ide> #
<del> # Destroy the +records+ supplied and remove them from the collection.
<add> # Destroys the +records+ supplied and remove them from the collection.
<ide> # This method will _always_ remove record from the database ignoring
<ide> # the +:dependent+ option. Returns an array with the removed records.
<ide> # | 1 |
Javascript | Javascript | use monotonic clock instead of currenttimemillis | ac03c47895f59842a4e6528e8272f371d61e41cf | <ide><path>Libraries/Utilities/PerformanceLogger.js
<ide> */
<ide> 'use strict';
<ide>
<del>var BatchedBridge = require('BatchedBridge');
<add>const BatchedBridge = require('BatchedBridge');
<add>const fbjsPerformanceNow = require('fbjs/lib/performanceNow');
<ide>
<del>var performanceNow = require('fbjs/lib/performanceNow');
<add>const performanceNow = global.nativePerformanceNow || fbjsPerformanceNow;
<ide>
<ide> var timespans = {};
<ide> var extras = {}; | 1 |
Mixed | Go | remove duplicate keys in labels of `docker info` | e4c9079d091a2eeac8a74a0356e3f348db873b87 | <ide><path>cli/command/system/info.go
<ide> func prettyPrintInfo(dockerCli *command.DockerCli, info types.Info) error {
<ide> for _, attribute := range info.Labels {
<ide> fmt.Fprintf(dockerCli.Out(), " %s\n", attribute)
<ide> }
<add> // TODO: Engine labels with duplicate keys has been deprecated in 1.13 and will be error out
<add> // after 3 release cycles (1.16). For now, a WARNING will be generated. The following will
<add> // be removed eventually.
<add> labelMap := map[string]string{}
<add> for _, label := range info.Labels {
<add> stringSlice := strings.SplitN(label, "=", 2)
<add> if len(stringSlice) > 1 {
<add> // If there is a conflict we will throw out an warning
<add> if v, ok := labelMap[stringSlice[0]]; ok && v != stringSlice[1] {
<add> fmt.Fprintln(dockerCli.Err(), "WARNING: labels with duplicate keys and conflicting values have been deprecated")
<add> break
<add> }
<add> labelMap[stringSlice[0]] = stringSlice[1]
<add> }
<add> }
<ide> }
<ide>
<ide> ioutils.FprintfIfTrue(dockerCli.Out(), "Experimental: %v\n", info.ExperimentalBuild)
<ide><path>cmd/dockerd/daemon.go
<ide> func loadDaemonCliConfig(opts daemonOptions) (*daemon.Config, error) {
<ide> return nil, err
<ide> }
<ide>
<add> // Labels of the docker engine used to allow multiple values associated with the same key.
<add> // This is deprecated in 1.13, and, be removed after 3 release cycles.
<add> // The following will check the conflict of labels, and report a warning for deprecation.
<add> //
<add> // TODO: After 3 release cycles (1.16) an error will be returned, and labels will be
<add> // sanitized to consolidate duplicate key-value pairs (config.Labels = newLabels):
<add> //
<add> // newLabels, err := daemon.GetConflictFreeLabels(config.Labels)
<add> // if err != nil {
<add> // return nil, err
<add> // }
<add> // config.Labels = newLabels
<add> //
<add> if _, err := daemon.GetConflictFreeLabels(config.Labels); err != nil {
<add> logrus.Warnf("Engine labels with duplicate keys and conflicting values have been deprecated: %s", err)
<add> }
<add>
<ide> // Regardless of whether the user sets it to true or false, if they
<ide> // specify TLSVerify at all then we need to turn on TLS
<ide> if config.IsValueSet(cliflags.FlagTLSVerify) {
<ide><path>daemon/config.go
<ide> func parseClusterAdvertiseSettings(clusterStore, clusterAdvertise string) (strin
<ide> return advertise, nil
<ide> }
<ide>
<add>// GetConflictFreeLabels validate Labels for conflict
<add>// In swarm the duplicates for labels are removed
<add>// so we only take same values here, no conflict values
<add>// If the key-value is the same we will only take the last label
<add>func GetConflictFreeLabels(labels []string) ([]string, error) {
<add> labelMap := map[string]string{}
<add> for _, label := range labels {
<add> stringSlice := strings.SplitN(label, "=", 2)
<add> if len(stringSlice) > 1 {
<add> // If there is a conflict we will return an error
<add> if v, ok := labelMap[stringSlice[0]]; ok && v != stringSlice[1] {
<add> return nil, fmt.Errorf("conflict labels for %s=%s and %s=%s", stringSlice[0], stringSlice[1], stringSlice[0], v)
<add> }
<add> labelMap[stringSlice[0]] = stringSlice[1]
<add> }
<add> }
<add>
<add> newLabels := []string{}
<add> for k, v := range labelMap {
<add> newLabels = append(newLabels, fmt.Sprintf("%s=%s", k, v))
<add> }
<add> return newLabels, nil
<add>}
<add>
<ide> // ReloadConfiguration reads the configuration in the host and reloads the daemon and server.
<ide> func ReloadConfiguration(configFile string, flags *pflag.FlagSet, reload func(*Config)) error {
<ide> logrus.Infof("Got signal to reload configuration, reloading from: %s", configFile)
<ide> func ReloadConfiguration(configFile string, flags *pflag.FlagSet, reload func(*C
<ide> return fmt.Errorf("file configuration validation failed (%v)", err)
<ide> }
<ide>
<add> // Labels of the docker engine used to allow multiple values associated with the same key.
<add> // This is deprecated in 1.13, and, be removed after 3 release cycles.
<add> // The following will check the conflict of labels, and report a warning for deprecation.
<add> //
<add> // TODO: After 3 release cycles (1.16) an error will be returned, and labels will be
<add> // sanitized to consolidate duplicate key-value pairs (config.Labels = newLabels):
<add> //
<add> // newLabels, err := GetConflictFreeLabels(newConfig.Labels)
<add> // if err != nil {
<add> // return err
<add> // }
<add> // newConfig.Labels = newLabels
<add> //
<add> if _, err := GetConflictFreeLabels(newConfig.Labels); err != nil {
<add> logrus.Warnf("Engine labels with duplicate keys and conflicting values have been deprecated: %s", err)
<add> }
<add>
<ide> reload(newConfig)
<ide> return nil
<ide> }
<ide><path>docs/deprecated.md
<ide> see [Feature Deprecation Policy](index.md#feature-deprecation-policy).
<ide>
<ide> The daemon is moved to a separate binary (`dockerd`), and should be used instead.
<ide>
<add>### Duplicate keys with conflicting values in engine labels
<add>**Deprecated In Release: [v1.13](https://github.com/docker/docker/releases/)**
<add>
<add>**Target For Removal In Release: v1.16**
<add>
<add>Duplicate keys with conflicting values have been deprecated. A warning is displayed
<add>in the output, and an error will be returned in the future.
<add>
<ide> ### Three argument form in `docker import`
<ide> **Deprecated In Release: [v0.6.7](https://github.com/docker/docker/releases/tag/v0.6.7)**
<ide>
<ide><path>integration-cli/docker_cli_info_test.go
<ide> func (s *DockerDaemonSuite) TestRegistryMirrors(c *check.C) {
<ide> c.Assert(out, checker.Contains, fmt.Sprintf(" %s", registryMirror1))
<ide> c.Assert(out, checker.Contains, fmt.Sprintf(" %s", registryMirror2))
<ide> }
<add>
<add>// Test case for #24392
<add>func (s *DockerDaemonSuite) TestInfoLabels(c *check.C) {
<add> testRequires(c, SameHostDaemon, DaemonIsLinux)
<add>
<add> err := s.d.Start("--label", `test.empty=`, "--label", `test.empty=`, "--label", `test.label="1"`, "--label", `test.label="2"`)
<add> c.Assert(err, checker.IsNil)
<add>
<add> out, err := s.d.Cmd("info")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(out, checker.Contains, "WARNING: labels with duplicate keys and conflicting values have been deprecated")
<add>} | 5 |
Javascript | Javascript | fix tab completion for a non-global context | d735b2c6ef9dc710a2e8c58bf56dc6d28f5a4bd3 | <ide><path>lib/repl.js
<ide> REPLServer.prototype.complete = function(line, callback) {
<ide> if (!expr) {
<ide> // If context is instance of vm.ScriptContext
<ide> // Get global vars synchronously
<del> if (this.useGlobal ||
<del> this.context.constructor &&
<del> this.context.constructor.name === 'Context') {
<add> if (this.useGlobal || vm.isContext(this.context)) {
<ide> var contextProto = this.context;
<ide> while (contextProto = Object.getPrototypeOf(contextProto)) {
<ide> completionGroups.push(Object.getOwnPropertyNames(contextProto));
<ide><path>test/parallel/test-repl-tab-complete.js
<ide> testMe.complete('require(\'n', function(error, data) {
<ide> assert.strictEqual(error, null);
<ide> assert.deepEqual(data, [['net'], 'n']);
<ide> });
<add>
<add>// Make sure tab completion works on context properties
<add>putIn.run(['.clear']);
<add>
<add>putIn.run([
<add> 'var custom = "test";'
<add>]);
<add>testMe.complete('cus', function(error, data) {
<add> assert.deepEqual(data, [['custom'], 'cus']);
<add>}); | 2 |
PHP | PHP | fix bug with provider booting | 05dccf1b72c38cba55db4f2b9140e305792657c9 | <ide><path>src/Illuminate/Exception/Handler.php
<ide> protected function handlesException(Closure $handler, $exception)
<ide> {
<ide> $reflection = new ReflectionFunction($handler);
<ide>
<del> return $reflection->getNumberOfParameters() == 0 or $this->hints($reflection, $exception);
<add> return $reflection->getNumberOfParameters() == 0 || $this->hints($reflection, $exception);
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Application.php
<ide> public function register($provider, $options = array())
<ide>
<ide> $this->markAsRegistered($provider);
<ide>
<add> // If the application has already booted, we will call this boot method on
<add> // the provider class so it has an opportunity to do its boot logic and
<add> // will be ready for any usage by the developer's application logics.
<add> if ($this->booted) $provider->boot();
<add>
<ide> return $provider;
<ide> }
<ide> | 2 |
Javascript | Javascript | remove `view#destroyelement` method | 5327eb0f699761c33341487d46334b56bbc4b57a | <ide><path>packages/ember-views/lib/mixins/view_support.js
<ide> export default Mixin.create({
<ide> */
<ide> willClearRender: K,
<ide>
<del> /**
<del> Destroys any existing element along with the element for any child views
<del> as well. If the view does not currently have a element, then this method
<del> will do nothing.
<del>
<del> If you implement `willDestroyElement()` on your view, then this method will
<del> be invoked on your view before your element is destroyed to give you a
<del> chance to clean up any event handlers, etc.
<del>
<del> If you write a `willDestroyElement()` handler, you can assume that your
<del> `didInsertElement()` handler was called earlier for the same element.
<del>
<del> You should not call or override this method yourself, but you may
<del> want to implement the above callbacks.
<del>
<del> @method destroyElement
<del> @return {Ember.View} receiver
<del> @private
<del> */
<del> destroyElement() {
<del> this._currentState.destroyElement(this);
<del> return this;
<del> },
<del>
<ide> /**
<ide> You must call `destroy` on a view to destroy the view (and all of its
<ide> child views). This will remove the view from any parent node, then make
<ide><path>packages/ember-views/lib/views/states/default.js
<ide> export default {
<ide> return true; // continue event propagation
<ide> },
<ide>
<del> destroyElement() { },
<del>
<ide> destroy() { },
<ide>
<ide> rerender(view) {
<ide><path>packages/ember-views/lib/views/states/destroying.js
<ide> assign(destroying, {
<ide> },
<ide> rerender() {
<ide> throw new EmberError('You can\'t call rerender on a view being destroyed');
<del> },
<del> destroyElement() {
<del> throw new EmberError('You can\'t call destroyElement on a view being destroyed');
<ide> }
<ide> });
<ide>
<ide><path>packages/ember-views/lib/views/states/has_element.js
<ide> assign(hasElement, {
<ide> view.renderer.rerender(view);
<ide> },
<ide>
<del> destroyElement(view) {
<del> view.renderer.remove(view, false);
<del> },
<del>
<ide> destroy(view) {
<ide> view.renderer.remove(view, true);
<ide> },
<ide><path>packages/ember-views/tests/views/view/append_to_test.js
<ide> QUnit.test('raises an assert when a target does not exist in the DOM', function(
<ide> });
<ide>
<ide>
<del>QUnit.test('remove removes an element from the DOM', function() {
<del> willDestroyCalled = 0;
<del>
<del> view = View.create({
<del> willDestroyElement() {
<del> willDestroyCalled++;
<del> }
<del> });
<del>
<del> ok(!get(view, 'element'), 'precond - should not have an element');
<del>
<del> run(() => view.append());
<del>
<del> ok(jQuery('#' + get(view, 'elementId')).length === 1, 'precond - element was inserted');
<del>
<del> run(() => view.destroyElement());
<del>
<del> ok(jQuery('#' + get(view, 'elementId')).length === 0, 'remove removes an element from the DOM');
<del> ok(!get(view, 'element'), 'remove nulls out the element');
<del> equal(willDestroyCalled, 1, 'the willDestroyElement hook was called once');
<del>});
<del>
<ide> QUnit.test('destroy more forcibly removes the view', function() {
<ide> willDestroyCalled = 0;
<ide>
<ide><path>packages/ember-views/tests/views/view/destroy_element_test.js
<del>import { get } from 'ember-metal/property_get';
<del>import run from 'ember-metal/run_loop';
<del>import EmberView from 'ember-views/views/view';
<del>
<del>let view;
<del>
<del>QUnit.module('EmberView#destroyElement', {
<del> teardown() {
<del> run(() => view.destroy());
<del> }
<del>});
<del>
<del>QUnit.test('if it has no element, does nothing', function() {
<del> let callCount = 0;
<del> view = EmberView.create({
<del> willDestroyElement() { callCount++; }
<del> });
<del>
<del> ok(!get(view, 'element'), 'precond - does NOT have element');
<del>
<del> run(() => view.destroyElement());
<del>
<del> equal(callCount, 0, 'did not invoke callback');
<del>});
<del>
<del>QUnit.test('returns receiver', function() {
<del> let ret;
<del> view = EmberView.create();
<del>
<del> run(() => {
<del> view.createElement();
<del> ret = view.destroyElement();
<del> });
<del>
<del> equal(ret, view, 'returns receiver');
<del>});
<del>
<del>QUnit.test('removes element from parentNode if in DOM', function() {
<del> view = EmberView.create();
<del>
<del> run(() => view.append());
<del>
<del> let parent = view.$().parent();
<del>
<del> ok(get(view, 'element'), 'precond - has element');
<del>
<del> run(() => view.destroyElement());
<del>
<del> equal(view.$(), undefined, 'view has no selector');
<del> ok(!parent.find('#' + view.get('elementId')).length, 'element no longer in parent node');
<del>}); | 6 |
Text | Text | explain git_remote_ref in collaborator_guide | c8d00d9ed06a9983c02d7a250d96c81980e0e3a6 | <ide><path>COLLABORATOR_GUIDE.md
<ide> Build". It is in the left navigation of the relevant `node-test-pull-request`
<ide> job. It will preserve all the green results from the current job but re-run
<ide> everything else.
<ide>
<add>Some of the CI Jobs may require `GIT_REMOTE_REF` which is the remote portion
<add>of Git refspec. To specify the branch this way `refs/heads/BRANCH` is used
<add>(i.e for `master` -> `refs/heads/master`).
<add>For pull requests it will look like `refs/pull/PR_NUMBER/head`
<add>(i.e. for PR#42 -> `refs/pull/42/head`).
<add>
<ide> #### Useful CI Jobs
<ide>
<ide> * [`node-test-pull-request`](https://ci.nodejs.org/job/node-test-pull-request/) | 1 |
Python | Python | add missing whitespace to multiline strings | 57420b103e2a99aea0f5f80e98216029f7349af2 | <ide><path>src/transformers/benchmark/benchmark_args.py
<ide> def __init__(self, **kwargs):
<ide> default="O1",
<ide> metadata={
<ide> "help": (
<del> "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
<add> "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
<ide> "See details at https://nvidia.github.io/apex/amp.html"
<ide> )
<ide> },
<ide><path>src/transformers/benchmark/benchmark_tf.py
<ide> def _measure_speed(self, func) -> float:
<ide>
<ide> def _measure_memory(self, func: Callable[[], None]) -> [Memory, MemorySummary]:
<ide> logger.info(
<del> "Note that TensorFlow allocates more memory than"
<del> "it might need to speed up computation."
<del> "The memory reported here corresponds to the memory"
<del> "reported by `nvidia-smi`, which can vary depending"
<add> "Note that TensorFlow allocates more memory than "
<add> "it might need to speed up computation. "
<add> "The memory reported here corresponds to the memory "
<add> "reported by `nvidia-smi`, which can vary depending "
<ide> "on total available memory on the GPU that is used."
<ide> )
<ide> with self.args.strategy.scope():
<ide><path>src/transformers/benchmark/benchmark_utils.py
<ide> def environment_info(self):
<ide> info["cpu_ram_mb"] = bytes_to_mega_bytes(psutil.virtual_memory().total)
<ide> else:
<ide> logger.warning(
<del> "Psutil not installed, we won't log available CPU memory."
<add> "Psutil not installed, we won't log available CPU memory. "
<ide> "Install psutil (pip install psutil) to log available CPU memory."
<ide> )
<ide> info["cpu_ram_mb"] = "N/A"
<ide><path>src/transformers/configuration_utils.py
<ide> def __init__(self, **kwargs):
<ide> allowed_problem_types = ("regression", "single_label_classification", "multi_label_classification")
<ide> if self.problem_type is not None and self.problem_type not in allowed_problem_types:
<ide> raise ValueError(
<del> f"The config parameter `problem_type` was not understood: received {self.problem_type}"
<add> f"The config parameter `problem_type` was not understood: received {self.problem_type} "
<ide> "but only 'regression', 'single_label_classification' and 'multi_label_classification' are valid."
<ide> )
<ide>
<ide><path>src/transformers/convert_pytorch_checkpoint_to_tf2.py
<ide> def convert_all_pt_checkpoints_to_tf(
<ide> type=str,
<ide> help="The config json file corresponding to the pre-trained model. \n"
<ide> "This specifies the model architecture. If not given and "
<del> "--pytorch_checkpoint_path is not given or is a shortcut name"
<add> "--pytorch_checkpoint_path is not given or is a shortcut name "
<ide> "use the configuration associated to the shortcut name on the AWS",
<ide> )
<ide> parser.add_argument(
<ide><path>src/transformers/data/data_collator.py
<ide> def _whole_word_mask(self, input_tokens: List[str], max_predictions=512):
<ide> """
<ide> if not isinstance(self.tokenizer, (BertTokenizer, BertTokenizerFast)):
<ide> warnings.warn(
<del> "DataCollatorForWholeWordMask is only suitable for BertTokenizer-like tokenizers."
<add> "DataCollatorForWholeWordMask is only suitable for BertTokenizer-like tokenizers. "
<ide> "Please refer to the documentation for more information."
<ide> )
<ide>
<ide><path>src/transformers/feature_extraction_sequence_utils.py
<ide> def pad(
<ide> # The model's main input name, usually `input_values`, has be passed for padding
<ide> if self.model_input_names[0] not in processed_features:
<ide> raise ValueError(
<del> "You should supply an instance of :class:`~transformers.BatchFeature` or list of :class:`~transformers.BatchFeature` to this method"
<add> "You should supply an instance of :class:`~transformers.BatchFeature` or list of :class:`~transformers.BatchFeature` to this method "
<ide> f"that includes {self.model_input_names[0]}, but you provided {list(processed_features.keys())}"
<ide> )
<ide>
<ide><path>src/transformers/generation_beam_search.py
<ide> def __init__(
<ide>
<ide> if "max_length" in kwargs:
<ide> warnings.warn(
<del> "Passing `max_length` to BeamSearchScorer is deprecated and has no effect."
<add> "Passing `max_length` to BeamSearchScorer is deprecated and has no effect. "
<ide> "`max_length` should be passed directly to `beam_search(...)`, `beam_sample(...)`"
<del> ",or `group_beam_search(...)`."
<add> ", or `group_beam_search(...)`."
<ide> )
<ide>
<ide> @property
<ide><path>src/transformers/generation_logits_process.py
<ide> def _set_scores_to_inf_for_banned_tokens(
<ide> banned_mask_list.append([idx, token])
<ide> else:
<ide> logger.error(
<del> f"An invalid bad word ID is defined: {token}. This ID is not contained in the"
<add> f"An invalid bad word ID is defined: {token}. This ID is not contained in the "
<ide> f"vocabulary, and is therefore ignored."
<ide> )
<ide> if not banned_mask_list and self.static_bad_words_mask is None:
<ide><path>src/transformers/generation_tf_utils.py
<ide> def generate(
<ide> # We cannot generate if the model does not have a LM head
<ide> if self.get_output_embeddings() is None:
<ide> raise AttributeError(
<del> "You tried to generate sequences with a model that does not have a LM Head."
<add> "You tried to generate sequences with a model that does not have a LM Head. "
<ide> "Please use another model class (e.g. `TFOpenAIGPTLMHeadModel`, `TFXLNetLMHeadModel`, `TFGPT2LMHeadModel`, `TFCTRLLMHeadModel`, `TFT5ForConditionalGeneration`, `TFTransfoXLLMHeadModel`)"
<ide> )
<ide>
<ide><path>src/transformers/generation_utils.py
<ide> def generate(
<ide> if input_ids.shape[-1] >= max_length:
<ide> input_ids_string = "decoder_input_ids" if self.config.is_encoder_decoder else "input_ids"
<ide> logger.warning(
<del> f"Input length of {input_ids_string} is {input_ids.shape[-1]}, but ``max_length`` is set to {max_length}."
<add> f"Input length of {input_ids_string} is {input_ids.shape[-1]}, but ``max_length`` is set to {max_length}. "
<ide> "This can lead to unexpected behavior. You should consider increasing ``config.max_length`` or ``max_length``."
<ide> )
<ide>
<ide><path>src/transformers/hf_argparser.py
<ide> def _add_dataclass_arguments(self, dtype: DataClassType):
<ide> # it is provided as a third-party extension mechanism.
<ide> if isinstance(field.type, str):
<ide> raise ImportError(
<del> "This implementation is not compatible with Postponed Evaluation of Annotations (PEP 563),"
<del> "which can be opted in from Python 3.7 with `from __future__ import annotations`."
<add> "This implementation is not compatible with Postponed Evaluation of Annotations (PEP 563), "
<add> "which can be opted in from Python 3.7 with `from __future__ import annotations`. "
<ide> "We will add compatibility when Python 3.9 is released."
<ide> )
<ide> typestring = str(field.type)
<ide><path>src/transformers/modeling_flax_pytorch_utils.py
<ide> def load_flax_weights_in_pytorch_model(pt_model, flax_state):
<ide> if flax_key in pt_model_dict:
<ide> if flax_tensor.shape != pt_model_dict[flax_key].shape:
<ide> raise ValueError(
<del> f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected"
<add> f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected "
<ide> f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."
<ide> )
<ide> else:
<ide><path>src/transformers/modeling_tf_utils.py
<ide> def booleans_processing(config, **kwargs):
<ide> or ("use_cache" in kwargs and kwargs["use_cache"] not in (None, config.use_cache))
<ide> ):
<ide> tf_logger.warning(
<del> "The parameters `output_attentions`, `output_hidden_states` and `use_cache` cannot be updated when calling a model."
<add> "The parameters `output_attentions`, `output_hidden_states` and `use_cache` cannot be updated when calling a model. "
<ide> "They have to be set to True/False in the config object (i.e.: `config=XConfig.from_pretrained('name', output_attentions=True)`)."
<ide> )
<ide>
<ide><path>src/transformers/modeling_utils.py
<ide> def _get_resized_embeddings(
<ide>
<ide> if not isinstance(old_embeddings, nn.Embedding):
<ide> raise TypeError(
<del> f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}."
<add> f"Old embeddings are of type {type(old_embeddings)}, which is not an instance of {nn.Embedding}. "
<ide> f"You should either use a different resize function or make sure that `old_embeddings` are an instance of {nn.Embedding}."
<ide> )
<ide>
<ide> def _get_resized_lm_head(
<ide>
<ide> if not isinstance(old_lm_head, nn.Linear):
<ide> raise TypeError(
<del> f"Old language model head is of type {type(old_lm_head)}, which is not an instance of {nn.Linear}."
<add> f"Old language model head is of type {type(old_lm_head)}, which is not an instance of {nn.Linear}. "
<ide> f"You should either use a different resize function or make sure that `old_lm_head` are an instance of {nn.Linear}."
<ide> )
<ide>
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> except (UnicodeDecodeError, ValueError):
<ide> raise OSError(
<ide> f"Unable to load weights from pytorch checkpoint file for '{pretrained_model_name_or_path}' "
<del> f"at '{resolved_archive_file}'"
<del> "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. "
<add> f"at '{resolved_archive_file}'. "
<add> "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True."
<ide> )
<ide>
<ide> # set dtype to instantiate the model under:
<ide><path>src/transformers/models/bart/configuration_bart.py
<ide> def __init__(
<ide> if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated", False):
<ide> self.forced_bos_token_id = self.bos_token_id
<ide> warnings.warn(
<del> f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions."
<add> f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
<ide> "The config can simply be saved and uploaded again to be fixed."
<ide> )
<ide>
<ide><path>src/transformers/models/beit/feature_extraction_beit.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
<ide> )
<ide>
<ide><path>src/transformers/models/bert_japanese/tokenization_bert_japanese.py
<ide> def __init__(
<ide> dic_dir = unidic.DICDIR
<ide> if not os.path.isdir(dic_dir):
<ide> raise RuntimeError(
<del> "The unidic dictionary itself is not found."
<add> "The unidic dictionary itself is not found. "
<ide> "See https://github.com/polm/unidic-py for installation."
<ide> )
<ide>
<ide><path>src/transformers/models/big_bird/modeling_big_bird.py
<ide> def forward(
<ide> "+ additional buffer: config.num_random_blocks * config.block_size "
<ide> f"= {max_tokens_to_attend} with config.block_size "
<ide> f"= {self.config.block_size}, config.num_random_blocks "
<del> f"= {self.config.num_random_blocks}."
<add> f"= {self.config.num_random_blocks}. "
<ide> "Changing attention type to 'original_full'..."
<ide> )
<ide> self.set_attention_type("original_full")
<ide><path>src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py
<ide> def forward(
<ide> "+ additional buffer: config.num_random_blocks * config.block_size "
<ide> f"= {max_tokens_to_attend} with config.block_size "
<ide> f"= {self.config.block_size}, config.num_random_blocks "
<del> f"= {self.config.num_random_blocks}."
<add> f"= {self.config.num_random_blocks}. "
<ide> "Changing attention type to 'original_full'..."
<ide> )
<ide> self.set_attention_type("original_full")
<ide><path>src/transformers/models/canine/modeling_canine.py
<ide> def __init__(
<ide> self.local = local
<ide> if attend_from_chunk_width < attend_from_chunk_stride:
<ide> raise ValueError(
<del> "`attend_from_chunk_width` < `attend_from_chunk_stride`"
<add> "`attend_from_chunk_width` < `attend_from_chunk_stride` "
<ide> "would cause sequence positions to get skipped."
<ide> )
<ide> if attend_to_chunk_width < attend_to_chunk_stride:
<ide><path>src/transformers/models/clip/feature_extraction_clip.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
<ide> )
<ide>
<ide><path>src/transformers/models/cpm/tokenization_cpm.py
<ide> def __init__(self, *args, **kwargs):
<ide> import jieba
<ide> except ModuleNotFoundError as error:
<ide> raise error.__class__(
<del> "You need to install jieba to use CpmTokenizer or CpmTokenizerFast."
<add> "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
<ide> "See https://pypi.org/project/jieba/ for installation."
<ide> )
<ide> self.jieba = jieba
<ide><path>src/transformers/models/cpm/tokenization_cpm_fast.py
<ide> def __init__(self, *args, **kwargs):
<ide> import jieba
<ide> except ModuleNotFoundError as error:
<ide> raise error.__class__(
<del> "You need to install jieba to use CpmTokenizer or CpmTokenizerFast."
<add> "You need to install jieba to use CpmTokenizer or CpmTokenizerFast. "
<ide> "See https://pypi.org/project/jieba/ for installation."
<ide> )
<ide> self.jieba = jieba
<ide><path>src/transformers/models/deit/feature_extraction_deit.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
<ide> )
<ide>
<ide><path>src/transformers/models/detr/feature_extraction_detr.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
<ide> )
<ide>
<ide><path>src/transformers/models/electra/modeling_electra.py
<ide> class ElectraForPreTrainingOutput(ModelOutput):
<ide> @add_start_docstrings(
<ide> "The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to "
<ide> "the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the "
<del> "hidden size and embedding size are different."
<add> "hidden size and embedding size are different. "
<ide> ""
<ide> "Both the generator and discriminator checkpoints may be loaded into this model.",
<ide> ELECTRA_START_DOCSTRING,
<ide><path>src/transformers/models/electra/modeling_tf_electra.py
<ide> class TFElectraForPreTrainingOutput(ModelOutput):
<ide> @add_start_docstrings(
<ide> "The bare Electra Model transformer outputting raw hidden-states without any specific head on top. Identical to "
<ide> "the BERT model except that it uses an additional linear layer between the embedding layer and the encoder if the "
<del> "hidden size and embedding size are different."
<add> "hidden size and embedding size are different. "
<ide> ""
<ide> "Both the generator and discriminator checkpoints may be loaded into this model.",
<ide> ELECTRA_START_DOCSTRING,
<ide><path>src/transformers/models/encoder_decoder/modeling_encoder_decoder.py
<ide> def prepare_inputs_for_generation(
<ide>
<ide> def resize_token_embeddings(self, *args, **kwargs):
<ide> raise NotImplementedError(
<del> "Resizing the embedding layers via the EncoderDecoderModel directly is not supported."
<add> "Resizing the embedding layers via the EncoderDecoderModel directly is not supported. "
<ide> "Please use the respective methods of the wrapped objects (model.encoder.resize_token_embeddings(...) or model.decoder.resize_token_embeddings(...))"
<ide> )
<ide>
<ide><path>src/transformers/models/gpt_neo/configuration_gpt_neo.py
<ide> def __init__(
<ide>
<ide> if len(self.attention_layers) != self.num_layers:
<ide> raise ValueError(
<del> "Configuration for convolutional module is incorrect."
<del> "It is required that `len(config.attention_layers)` == `config.num_layers`"
<del> f"but is `len(config.attention_layers) = {len(self.attention_layers)}`,"
<del> f"`config.num_layers = {self.num_layers}`."
<del> "`config.attention_layers` is prepared using `config.attention_types`."
<add> "Configuration for convolutional module is incorrect. "
<add> "It is required that `len(config.attention_layers)` == `config.num_layers` "
<add> f"but is `len(config.attention_layers) = {len(self.attention_layers)}`, "
<add> f"`config.num_layers = {self.num_layers}`. "
<add> "`config.attention_layers` is prepared using `config.attention_types`. "
<ide> "Please verify the value of `config.attention_types` argument."
<ide> )
<ide>
<ide><path>src/transformers/models/hubert/configuration_hubert.py
<ide> def __init__(
<ide> or (len(self.conv_dim) != self.num_feat_extract_layers)
<ide> ):
<ide> raise ValueError(
<del> "Configuration for convolutional layers is incorrect."
<del> "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
<del> f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)"
<add> "Configuration for convolutional layers is incorrect. "
<add> "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, "
<add> f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) "
<ide> f"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`."
<ide> )
<ide>
<ide><path>src/transformers/models/layoutlmv2/feature_extraction_layoutlmv2.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples), "
<ide> f"but is of type {type(images)}."
<ide> )
<ide><path>src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
<ide> def _is_valid_text_input(t):
<ide> raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
<ide> if not isinstance(text_pair, (list, tuple)):
<ide> raise ValueError(
<del> "words must of type `List[str]` (single pretokenized example),"
<add> "words must of type `List[str]` (single pretokenized example), "
<ide> "or `List[List[str]]` (batch of pretokenized examples)."
<ide> )
<ide> else:
<ide> def _batch_encode_plus(
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<ide> "transformers.PreTrainedTokenizerFast."
<ide> )
<ide> def _encode_plus(
<ide> ) -> BatchEncoding:
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<del> "transformers.PreTrainedTokenizerFast."
<add> "transformers.PreTrainedTokenizerFast. "
<ide> "More information on available tokenizers at "
<ide> "https://github.com/huggingface/transformers/pull/2674"
<ide> )
<ide> def truncate_sequences(
<ide> labels = labels[:-num_tokens_to_remove]
<ide> else:
<ide> logger.error(
<del> f"We need to remove {num_tokens_to_remove} to truncate the input"
<add> f"We need to remove {num_tokens_to_remove} to truncate the input "
<ide> f"but the first sequence has a length {len(ids)}. "
<ide> f"Please select another truncation strategy than {truncation_strategy}, "
<ide> f"for instance 'longest_first' or 'only_second'."
<ide> def truncate_sequences(
<ide> pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
<ide> else:
<ide> logger.error(
<del> f"We need to remove {num_tokens_to_remove} to truncate the input"
<add> f"We need to remove {num_tokens_to_remove} to truncate the input "
<ide> f"but the second sequence has a length {len(pair_ids)}. "
<ide> f"Please select another truncation strategy than {truncation_strategy}, "
<ide> f"for instance 'longest_first' or 'only_first'."
<ide><path>src/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py
<ide> def _is_valid_text_input(t):
<ide> raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
<ide> if not isinstance(text_pair, (list, tuple)):
<ide> raise ValueError(
<del> "words must of type `List[str]` (single pretokenized example),"
<add> "words must of type `List[str]` (single pretokenized example), "
<ide> "or `List[List[str]]` (batch of pretokenized examples)."
<ide> )
<ide> else:
<ide><path>src/transformers/models/luke/tokenization_luke.py
<ide> def _encode_plus(
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<del> "transformers.PreTrainedTokenizerFast."
<add> "transformers.PreTrainedTokenizerFast. "
<ide> "More information on available tokenizers at "
<ide> "https://github.com/huggingface/transformers/pull/2674"
<ide> )
<ide> def _batch_encode_plus(
<ide> ) -> BatchEncoding:
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<ide> "transformers.PreTrainedTokenizerFast."
<ide> )
<ide> def pad(
<ide> # The model's main input name, usually `input_ids`, has be passed for padding
<ide> if self.model_input_names[0] not in encoded_inputs:
<ide> raise ValueError(
<del> "You should supply an encoding or a list of encodings to this method"
<add> "You should supply an encoding or a list of encodings to this method "
<ide> f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
<ide> )
<ide>
<ide><path>src/transformers/models/rag/retrieval_rag.py
<ide> def _resolve_path(self, index_path, filename):
<ide> except EnvironmentError:
<ide> msg = (
<ide> f"Can't load '{archive_file}'. Make sure that:\n\n"
<del> f"- '{index_path}' is a correct remote path to a directory containing a file named {filename}"
<add> f"- '{index_path}' is a correct remote path to a directory containing a file named {filename}\n\n"
<ide> f"- or '{index_path}' is the correct path to a directory containing a file named {filename}.\n\n"
<ide> )
<ide> raise EnvironmentError(msg)
<ide><path>src/transformers/models/roformer/tokenization_roformer.py
<ide> def __init__(
<ide> import rjieba
<ide> except ImportError:
<ide> raise ImportError(
<del> "You need to install rjieba to use RoFormerTokenizer."
<add> "You need to install rjieba to use RoFormerTokenizer. "
<ide> "See https://pypi.org/project/rjieba/ for installation."
<ide> )
<ide> self.jieba = rjieba
<ide><path>src/transformers/models/roformer/tokenization_utils.py
<ide> def __init__(self, vocab) -> None:
<ide> import rjieba
<ide> except ImportError:
<ide> raise ImportError(
<del> "You need to install rjieba to use RoFormerTokenizer."
<add> "You need to install rjieba to use RoFormerTokenizer. "
<ide> "See https://pypi.org/project/rjieba/ for installation."
<ide> )
<ide> self.jieba = rjieba
<ide><path>src/transformers/models/speech_encoder_decoder/modeling_speech_encoder_decoder.py
<ide> def from_encoder_decoder_pretrained(
<ide> decoder_config = AutoConfig.from_pretrained(decoder_pretrained_model_name_or_path)
<ide> if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False:
<ide> logger.info(
<del> f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model."
<add> f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. "
<ide> "Cross attention layers are added to {decoder_pretrained_model_name_or_path} "
<ide> "and randomly initialized if {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers."
<ide> )
<ide> def from_encoder_decoder_pretrained(
<ide>
<ide> if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False:
<ide> logger.warning(
<del> f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder."
<add> f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. "
<ide> f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, "
<del> "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config`"
<add> "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` "
<ide> "passed to `.from_encoder_decoder_pretrained(...)` are set to `True` or do not pass a `decoder_config` to `.from_encoder_decoder_pretrained(...)`"
<ide> )
<ide>
<ide> def prepare_inputs_for_generation(
<ide>
<ide> def resize_token_embeddings(self, *args, **kwargs):
<ide> raise NotImplementedError(
<del> "Resizing the embedding layers via the SpeechEncoderDecoderModel directly is not supported."
<add> "Resizing the embedding layers via the SpeechEncoderDecoderModel directly is not supported. "
<ide> "Please use the respective methods of the wrapped decoder object (model.decoder.resize_token_embeddings(...))"
<ide> )
<ide>
<ide><path>src/transformers/models/speech_to_text/configuration_speech_to_text.py
<ide> def __init__(
<ide>
<ide> if len(self.conv_kernel_sizes) != self.num_conv_layers:
<ide> raise ValueError(
<del> "Configuration for convolutional module is incorrect."
<del> "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers`"
<del> f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`,"
<add> "Configuration for convolutional module is incorrect. "
<add> "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` "
<add> f"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, "
<ide> f"`config.num_conv_layers = {self.num_conv_layers}`."
<ide> )
<ide>
<ide><path>src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py
<ide> def __call__(
<ide> if sampling_rate is not None:
<ide> if sampling_rate != self.sampling_rate:
<ide> raise ValueError(
<del> f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of {self.sampling_rate}."
<add> f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of {self.sampling_rate}. "
<ide> f"Please make sure that the provided `raw_speech` input was sampled with {self.sampling_rate} and not {sampling_rate}."
<ide> )
<ide> else:
<ide> logger.warning(
<del> "It is strongly recommended to pass the `sampling_rate` argument to this function."
<add> "It is strongly recommended to pass the `sampling_rate` argument to this function. "
<ide> "Failing to do so can result in silent errors that might be hard to debug."
<ide> )
<ide>
<ide><path>src/transformers/models/squeezebert/modeling_squeezebert.py
<ide> def __init__(self, config):
<ide> super().__init__()
<ide>
<ide> assert config.embedding_size == config.hidden_size, (
<del> "If you want embedding_size != intermediate hidden_size,"
<add> "If you want embedding_size != intermediate hidden_size, "
<ide> "please insert a Conv1d layer to adjust the number of channels "
<ide> "before the first SqueezeBertModule."
<ide> )
<ide><path>src/transformers/models/tapas/modeling_tapas.py
<ide> from torch_scatter import scatter
<ide> except OSError:
<ide> logger.error(
<del> "TAPAS models are not usable since `torch_scatter` can't be loaded."
<del> "It seems you have `torch_scatter` installed with the wrong CUDA version."
<add> "TAPAS models are not usable since `torch_scatter` can't be loaded. "
<add> "It seems you have `torch_scatter` installed with the wrong CUDA version. "
<ide> "Please try to reinstall it following the instructions here: https://github.com/rusty1s/pytorch_scatter."
<ide> )
<ide>
<ide><path>src/transformers/models/tapas/tokenization_tapas.py
<ide> def batch_encode_plus(
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<ide> "transformers.PreTrainedTokenizerFast."
<ide> )
<ide> def encode_plus(
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<ide> "transformers.PreTrainedTokenizerFast."
<ide> )
<ide> def prepare_for_model(
<ide>
<ide> if max_length is not None and len(input_ids) > max_length:
<ide> raise ValueError(
<del> "Could not encode the query and table header given the maximum length. Encoding the query and table"
<add> "Could not encode the query and table header given the maximum length. Encoding the query and table "
<ide> f"header results in a length of {len(input_ids)} which is higher than the max_length of {max_length}"
<ide> )
<ide>
<ide><path>src/transformers/models/transfo_xl/tokenization_transfo_xl.py
<ide> def __init__(
<ide> except Exception as e:
<ide> raise ValueError(
<ide> f"Unable to parse file {pretrained_vocab_file}. Unknown format. "
<del> "If you tried to load a model saved through TransfoXLTokenizerFast,"
<add> "If you tried to load a model saved through TransfoXLTokenizerFast, "
<ide> "please note they are not compatible."
<ide> ) from e
<ide>
<ide><path>src/transformers/models/visual_bert/modeling_visual_bert.py
<ide> def forward(
<ide> if visual_position_embeddings.size(1) != visual_embeds.size(1):
<ide> if visual_position_embeddings.size(1) < visual_embeds.size(1):
<ide> raise ValueError(
<del> f"Visual position embeddings length: {visual_position_embeddings.size(1)}"
<add> f"Visual position embeddings length: {visual_position_embeddings.size(1)} "
<ide> f"should be the same as `visual_embeds` length: {visual_embeds.size(1)}"
<ide> )
<ide> visual_position_embeddings = visual_position_embeddings[:, : visual_embeds.size(1), :]
<ide> def forward(
<ide> total_size = attention_mask.size(-1) + visual_attention_mask.size(-1)
<ide> if labels.size(-1) != total_size:
<ide> raise ValueError(
<del> f"The labels provided should have same sequence length as total attention mask."
<add> f"The labels provided should have same sequence length as total attention mask. "
<ide> f"Found labels with sequence length {labels.size(-1)}, expected {total_size}."
<ide> )
<ide>
<ide> def forward(
<ide> total_size = attention_mask.size(-1) + visual_attention_mask.size(-1)
<ide> if labels.size(-1) != total_size:
<ide> raise ValueError(
<del> f"The labels provided should have same sequence length as total attention mask."
<add> f"The labels provided should have same sequence length as total attention mask. "
<ide> f"Found labels with sequence length {labels.size(-1)}, expected {total_size}."
<ide> )
<ide>
<ide><path>src/transformers/models/vit/feature_extraction_vit.py
<ide> def __call__(
<ide>
<ide> if not valid_images:
<ide> raise ValueError(
<del> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example),"
<add> "Images must of type `PIL.Image.Image`, `np.ndarray` or `torch.Tensor` (single example), "
<ide> "`List[PIL.Image.Image]`, `List[np.ndarray]` or `List[torch.Tensor]` (batch of examples)."
<ide> )
<ide>
<ide><path>src/transformers/models/wav2vec2/configuration_wav2vec2.py
<ide> def __init__(
<ide> or (len(self.conv_dim) != self.num_feat_extract_layers)
<ide> ):
<ide> raise ValueError(
<del> "Configuration for convolutional layers is incorrect."
<del> "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
<del> f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride)"
<add> "Configuration for convolutional layers is incorrect. "
<add> "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`, "
<add> f"but is `len(config.conv_dim) = {len(self.conv_dim)}`, `len(config.conv_stride) "
<ide> f"= {len(self.conv_stride)}`, `len(config.conv_kernel) = {len(self.conv_kernel)}`."
<ide> )
<ide>
<ide><path>src/transformers/models/wav2vec2/feature_extraction_wav2vec2.py
<ide> def __call__(
<ide> if sampling_rate is not None:
<ide> if sampling_rate != self.sampling_rate:
<ide> raise ValueError(
<del> f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of {self.sampling_rate}."
<add> f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of {self.sampling_rate}. "
<ide> f"Please make sure that the provided `raw_speech` input was sampled with {self.sampling_rate} and not {sampling_rate}."
<ide> )
<ide> else:
<ide> logger.warning(
<del> "It is strongly recommended to pass the ``sampling_rate`` argument to this function."
<add> "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
<ide> "Failing to do so can result in silent errors that might be hard to debug."
<ide> )
<ide>
<ide><path>src/transformers/models/wav2vec2/modeling_wav2vec2.py
<ide> def __init__(self, config):
<ide> raise ValueError(
<ide> f"You are trying to instantiate {self.__class__} with a configuration that "
<ide> "does not define the vocabulary size of the language model head. Please "
<del> "instantiate the model as follows: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`."
<add> "instantiate the model as follows: `Wav2Vec2ForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
<ide> "or define `vocab_size` of your model's configuration."
<ide> )
<ide> self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
<ide><path>src/transformers/models/xlm_prophetnet/tokenization_xlm_prophetnet.py
<ide> def __init__(
<ide> import sentencepiece as spm
<ide> except ImportError:
<ide> logger.warning(
<del> "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
<add> "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece "
<ide> "pip install sentencepiece"
<ide> )
<ide> raise
<ide> def __setstate__(self, d):
<ide> import sentencepiece as spm
<ide> except ImportError:
<ide> logger.warning(
<del> "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
<add> "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece "
<ide> "pip install sentencepiece"
<ide> )
<ide> raise
<ide><path>src/transformers/onnx/features.py
<ide> def get_model_from_feature(feature: str, model: str):
<ide> task = FeaturesManager.feature_to_task(feature)
<ide> if task not in FeaturesManager._TASKS_TO_AUTOMODELS:
<ide> raise KeyError(
<del> f"Unknown task: {feature}."
<add> f"Unknown task: {feature}. "
<ide> f"Possible values are {list(FeaturesManager._TASKS_TO_AUTOMODELS.values())}"
<ide> )
<ide>
<ide><path>src/transformers/tokenization_utils.py
<ide> def get_input_ids(text):
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<del> "transformers.PreTrainedTokenizerFast."
<add> "transformers.PreTrainedTokenizerFast. "
<ide> "More information on available tokenizers at "
<ide> "https://github.com/huggingface/transformers/pull/2674"
<ide> )
<ide> def get_input_ids(text):
<ide>
<ide> if return_offsets_mapping:
<ide> raise NotImplementedError(
<del> "return_offset_mapping is not available when using Python tokenizers."
<add> "return_offset_mapping is not available when using Python tokenizers. "
<ide> "To use this feature, change your tokenizer to one deriving from "
<ide> "transformers.PreTrainedTokenizerFast."
<ide> )
<ide><path>src/transformers/tokenization_utils_base.py
<ide> def truncate_sequences(
<ide> pair_ids = pair_ids[:-num_tokens_to_remove]
<ide> else:
<ide> logger.error(
<del> f"We need to remove {num_tokens_to_remove} to truncate the input"
<add> f"We need to remove {num_tokens_to_remove} to truncate the input "
<ide> f"but the second sequence has a length {len(pair_ids)}. "
<ide> f"Please select another truncation strategy than {truncation_strategy}, "
<ide> f"for instance 'longest_first' or 'only_first'."
<ide> def get_special_tokens_mask(
<ide> """
<ide> assert already_has_special_tokens and token_ids_1 is None, (
<ide> "You cannot use ``already_has_special_tokens=False`` with this tokenizer. "
<del> "Please use a slow (full python) tokenizer to activate this argument."
<add> "Please use a slow (full python) tokenizer to activate this argument. "
<ide> "Or set `return_special_tokens_mask=True` when calling the encoding method "
<ide> "to get the special tokens mask in any tokenizer. "
<ide> )
<ide><path>src/transformers/trainer.py
<ide> def __init__(
<ide> self.optimizer, self.lr_scheduler = optimizers
<ide> if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):
<ide> raise RuntimeError(
<del> "Passing a `model_init` is incompatible with providing the `optimizers` argument."
<add> "Passing a `model_init` is incompatible with providing the `optimizers` argument. "
<ide> "You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method."
<ide> )
<ide> default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
<ide> def hyperparameter_search(
<ide> if backend is None:
<ide> raise RuntimeError(
<ide> "At least one of optuna or ray should be installed. "
<del> "To install optuna run `pip install optuna`."
<del> "To install ray run `pip install ray[tune]`."
<add> "To install optuna run `pip install optuna`. "
<add> "To install ray run `pip install ray[tune]`. "
<ide> "To install sigopt run `pip install sigopt`."
<ide> )
<ide> backend = HPSearchBackend(backend)
<ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> default=False,
<ide> metadata={
<ide> "help": (
<del> "Overwrite the content of the output directory."
<add> "Overwrite the content of the output directory. "
<ide> "Use this to continue training if output_dir points to a checkpoint directory."
<ide> )
<ide> },
<ide> class TrainingArguments:
<ide> per_gpu_eval_batch_size: Optional[int] = field(
<ide> default=None,
<ide> metadata={
<del> "help": "Deprecated, the use of `--per_device_eval_batch_size` is preferred."
<add> "help": "Deprecated, the use of `--per_device_eval_batch_size` is preferred. "
<ide> "Batch size per GPU/TPU core/CPU for evaluation."
<ide> },
<ide> )
<ide> class TrainingArguments:
<ide> default=None,
<ide> metadata={
<ide> "help": (
<del> "Limit the total amount of checkpoints."
<add> "Limit the total amount of checkpoints. "
<ide> "Deletes the older checkpoints in the output_dir. Default is unlimited checkpoints"
<ide> )
<ide> },
<ide> class TrainingArguments:
<ide> default="O1",
<ide> metadata={
<ide> "help": (
<del> "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
<add> "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
<ide> "See details at https://nvidia.github.io/apex/amp.html"
<ide> )
<ide> }, | 56 |
Javascript | Javascript | remove error catch and use update method | fd442c55bb6006268de16dc4eaabf3a31ab51c4c | <ide><path>common/models/user.js
<ide> module.exports = function(User) {
<ide> renderSignUpEmail : renderSignInEmail;
<ide>
<ide> // create a temporary access token with ttl for 1 hour
<del> user.createAccessToken({ ttl: 60 * 60 * 1000 }, (err, token) => {
<add> return user.createAccessToken({ ttl: 60 * 60 * 1000 }, (err, token) => {
<ide> if (err) { throw err; }
<ide>
<ide> const { id: loginToken } = token;
<ide> module.exports = function(User) {
<ide> } else {
<ide> console.log('~~~~\n' + mailOptions.text + '~~~~\n');
<ide> }
<del> user.emailAuthLinkTTL = token.created;
<del> user.save(err =>{ if (err) { throw err; }});
<del> });
<add> const emailAuthLinkTTL = token.created;
<add> this.update$({
<add> emailAuthLinkTTL
<add> })
<add> .do(() => {
<add> this.emailAuthLinkTTL = emailAuthLinkTTL;
<add> });
<ide>
<del> return dedent`
<del> If you entered a valid email, a magic link is on its way.
<del> Please follow that link to sign in.
<del> `;
<add> return dedent`
<add> If you entered a valid email, a magic link is on its way.
<add> Please follow that link to sign in.
<add> `;
<add> });
<ide> })
<ide> .map((msg) => {
<ide> if (msg) { return msg; }
<ide> return dedent`
<ide> Oops, something is not right, please try again later.
<ide> `;
<ide> })
<del> .catch(error => {
<del> debug(error);
<del> return Observable.throw(
<del> 'Oops, something went wrong, please try again later.'
<del> );
<del> })
<ide> .toPromise();
<ide> };
<ide> | 1 |
Mixed | Javascript | specify `options` parameter type in zlib.md | 811598bcdae74ed8460ccb265d9939f36858f75a | <ide><path>doc/api/zlib.md
<ide> Provides an object enumerating Zlib-related constants.
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`Deflate`][] object with the given [`options`][].
<add>Creates and returns a new [`Deflate`][] object.
<ide>
<ide> ## zlib.createDeflateRaw([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`DeflateRaw`][] object with the given [`options`][].
<add>Creates and returns a new [`DeflateRaw`][] object.
<ide>
<ide> An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits`
<ide> is set to 8 for raw deflate streams. zlib would automatically set `windowBits`
<ide> that effectively uses an 8-bit window only.
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`Gunzip`][] object with the given [`options`][].
<add>Creates and returns a new [`Gunzip`][] object.
<ide>
<ide> ## zlib.createGzip([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`Gzip`][] object with the given [`options`][].
<add>Creates and returns a new [`Gzip`][] object.
<ide>
<ide> ## zlib.createInflate([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`Inflate`][] object with the given [`options`][].
<add>Creates and returns a new [`Inflate`][] object.
<ide>
<ide> ## zlib.createInflateRaw([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`InflateRaw`][] object with the given [`options`][].
<add>Creates and returns a new [`InflateRaw`][] object.
<ide>
<ide> ## zlib.createUnzip([options])
<ide> <!-- YAML
<ide> added: v0.5.8
<ide> -->
<ide>
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<del>Creates and returns a new [`Unzip`][] object with the given [`options`][].
<add>Creates and returns a new [`Unzip`][] object.
<ide>
<ide> ## Convenience Methods
<ide>
<ide> changes:
<ide> description: The `buffer` parameter can be an `Uint8Array` now.
<ide> -->
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.deflateSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Compress a chunk of data with [`Deflate`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.deflateRawSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Compress a chunk of data with [`DeflateRaw`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.gunzipSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Decompress a chunk of data with [`Gunzip`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.gzipSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Compress a chunk of data with [`Gzip`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.inflateSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Decompress a chunk of data with [`Inflate`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.inflateRawSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Decompress a chunk of data with [`InflateRaw`][].
<ide>
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide> * `callback` {Function}
<ide>
<ide> ### zlib.unzipSync(buffer[, options])
<ide> changes:
<ide> -->
<ide>
<ide> * `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string}
<del>* `options` {Object}
<add>* `options` {zlib options}
<ide>
<ide> Decompress a chunk of data with [`Unzip`][].
<ide>
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> [`InflateRaw`]: #zlib_class_zlib_inflateraw
<ide> [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
<ide> [`Unzip`]: #zlib_class_zlib_unzip
<del>[`options`]: #zlib_class_options
<ide> [`zlib.bytesWritten`]: #zlib_zlib_byteswritten
<ide> [Memory Usage Tuning]: #zlib_memory_usage_tuning
<ide> [pool size]: cli.html#cli_uv_threadpool_size_size
<ide><path>tools/doc/type-parser.js
<ide> const customTypesMap = {
<ide> 'URL': 'url.html#url_the_whatwg_url_api',
<ide> 'URLSearchParams': 'url.html#url_class_urlsearchparams',
<ide>
<del> 'MessagePort': 'worker_threads.html#worker_threads_class_messageport'
<add> 'MessagePort': 'worker_threads.html#worker_threads_class_messageport',
<add>
<add> 'zlib options': 'zlib.html#zlib_class_options',
<ide> };
<ide>
<ide> const arrayPart = /(?:\[])+$/; | 2 |
Ruby | Ruby | add high_precision_current_timestamp to adapters | da41061b4ea1162fefe3a12b6215e4280ca42bf1 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
<ide> def with_yaml_fallback(value) # :nodoc:
<ide> end
<ide> end
<ide>
<add> # This is a safe default, even if not high precision on all databases
<add> HIGH_PRECISION_CURRENT_TIMESTAMP = Arel.sql("CURRENT_TIMESTAMP").freeze # :nodoc:
<add> private_constant :HIGH_PRECISION_CURRENT_TIMESTAMP
<add>
<add> # Returns an Arel SQL literal for the CURRENT_TIMESTAMP for usage with
<add> # arbitrary precision date/time columns.
<add> #
<add> # Adapters supporting datetime with precision should override this to
<add> # provide as much precision as is available.
<add> def high_precision_current_timestamp
<add> HIGH_PRECISION_CURRENT_TIMESTAMP
<add> end
<add>
<ide> private
<ide> def execute_batch(statements, name = nil)
<ide> statements.each do |statement|
<ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb
<ide> def exec_delete(sql, name = nil, binds = []) # :nodoc:
<ide> end
<ide> alias :exec_update :exec_delete
<ide>
<add> # https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_current-timestamp
<add> # https://dev.mysql.com/doc/refman/5.7/en/date-and-time-type-syntax.html
<add> HIGH_PRECISION_CURRENT_TIMESTAMP = Arel.sql("CURRENT_TIMESTAMP(6)").freeze # :nodoc:
<add> private_constant :HIGH_PRECISION_CURRENT_TIMESTAMP
<add>
<add> def high_precision_current_timestamp
<add> HIGH_PRECISION_CURRENT_TIMESTAMP
<add> end
<add>
<ide> private
<ide> def execute_batch(statements, name = nil)
<ide> combine_multi_statements(statements).each do |statement|
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
<ide> def exec_rollback_db_transaction # :nodoc:
<ide> execute("ROLLBACK", "TRANSACTION")
<ide> end
<ide>
<add> # From https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT
<add> HIGH_PRECISION_CURRENT_TIMESTAMP = Arel.sql("CURRENT_TIMESTAMP").freeze # :nodoc:
<add> private_constant :HIGH_PRECISION_CURRENT_TIMESTAMP
<add>
<add> def high_precision_current_timestamp
<add> HIGH_PRECISION_CURRENT_TIMESTAMP
<add> end
<add>
<ide> private
<ide> def execute_batch(statements, name = nil)
<ide> execute(combine_multi_statements(statements))
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/database_statements.rb
<ide> def exec_rollback_db_transaction # :nodoc:
<ide> reset_read_uncommitted
<ide> end
<ide>
<add> # https://stackoverflow.com/questions/17574784
<add> # https://www.sqlite.org/lang_datefunc.html
<add> HIGH_PRECISION_CURRENT_TIMESTAMP = Arel.sql("STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW')").freeze # :nodoc:
<add> private_constant :HIGH_PRECISION_CURRENT_TIMESTAMP
<add>
<add> def high_precision_current_timestamp
<add> HIGH_PRECISION_CURRENT_TIMESTAMP
<add> end
<add>
<ide> private
<ide> def reset_read_uncommitted
<ide> read_uncommitted = Thread.current.thread_variable_get("read_uncommitted") | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.