content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
save one byte
d41ac85ca3773f1be5dd91d59060fc064ac22673
<ide><path>src/manipulation.js <ide> function cloneCopyEvent( src, dest ) { <ide> } <ide> } <ide> <add>function getAll( context, tag ) { <add> var elems, elem, <add> i = 0, <add> ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : <add> typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : <add> undefined; <add> <add> if ( !ret ) { <add> for ( ret = [], elems = context.childNodes || context; (elem = elems[ i ]) != null; i++ ) { <add> core_push.apply( ret, !tag || jQuery.nodeName( elem, tag ) ? <add> getAll( elem, tag ) : <add> elems ); <add> } <add> } <add> <add> return tag === undefined || tag && jQuery.nodeName( context, tag ) ? <add> jQuery.merge( [ context ], ret ) : <add> ret; <add>} <add> <ide> function fixCloneNodeIssues( src, dest ) { <ide> var nodeName; <ide> <ide> function fixCloneNodeIssues( src, dest ) { <ide> dest.defaultValue = src.defaultValue; <ide> } <ide> } <del> <del>function getAll( context, tag ) { <del> var elems, elem, <del> i = 0, <del> ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : <del> typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : <del> undefined; <del> <del> if ( !ret ) { <del> for ( ret = [], elems = context.childNodes || context; (elem = elems[ i ]) != null; i++ ) { <del> core_push.apply( ret, !tag || jQuery.nodeName( elem, tag ) ? <del> getAll( elem, tag ) : <del> elems ); <del> } <del> } <del> <del> return tag === undefined || tag && jQuery.nodeName( context, tag ) ? <del> jQuery.merge( [ context ], ret ) : <del> ret; <del>}
1
Javascript
Javascript
remove reference to `diffuse` parameter
43bedce7868cc5786641e8b32333af2e0249a046
<ide><path>examples/js/loaders/MTLLoader.js <ide> THREE.MTLLoader.MaterialCreator.prototype = { <ide> <ide> // Diffuse color (color under white light) using RGB values <ide> <del> params[ 'diffuse' ] = new THREE.Color().fromArray( value ); <add> params[ 'color' ] = new THREE.Color().fromArray( value ); <ide> <ide> break; <ide> <ide> THREE.MTLLoader.MaterialCreator.prototype = { <ide> <ide> } <ide> <del> if ( params[ 'diffuse' ] ) { <del> <del> params[ 'color' ] = params[ 'diffuse' ]; <del> <del> } <del> <ide> this.materials[ materialName ] = new THREE.MeshPhongMaterial( params ); <ide> return this.materials[ materialName ]; <ide>
1
Python
Python
add config.py for paddle example
d0c999e0ad26c0c8565b1fe119fd5761adac3a33
<ide><path>examples/paddle/sentiment_bilstm/config.py <add>from paddle.trainer_config_helpers import * <add> <add>define_py_data_sources2(train_list='train.list', <add> test_list='test.list', <add> module="dataprovider", <add> obj="process") <add> <add>settings( <add> batch_size=128, <add> learning_rate=2e-3, <add> learning_method=AdamOptimizer(), <add> regularization=L2Regularization(8e-4), <add> gradient_clipping_threshold=25 <add>)
1
Javascript
Javascript
implement unit testing and sanitize data values
323e86c442782f12c137f62f6d530bc920e6fa8d
<ide><path>src/core/annotation.js <ide> var TextWidgetAnnotation = (function TextWidgetAnnotationClosure() { <ide> function TextWidgetAnnotation(params) { <ide> WidgetAnnotation.call(this, params); <ide> <del> this.data.textAlignment = Util.getInheritableProperty(params.dict, 'Q'); <del> this.data.maxLen = Util.getInheritableProperty(params.dict, 'MaxLen'); <add> // Determine the alignment of text in the field. <add> var alignment = Util.getInheritableProperty(params.dict, 'Q'); <add> if (!isInt(alignment) || alignment < 0 || alignment > 2) { <add> alignment = null; <add> } <add> this.data.textAlignment = alignment; <add> <add> // Determine the maximum length of text in the field. <add> var maximumLength = Util.getInheritableProperty(params.dict, 'MaxLen'); <add> if (!isInt(maximumLength) || maximumLength < 0) { <add> maximumLength = null; <add> } <add> this.data.maxLen = maximumLength; <ide> } <ide> <ide> Util.inherit(TextWidgetAnnotation, WidgetAnnotation, { <ide><path>src/display/annotation_layer.js <ide> <ide> var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; <ide> var AnnotationType = sharedUtil.AnnotationType; <del>var isInt = sharedUtil.isInt; <ide> var Util = sharedUtil.Util; <ide> var addLinkAttributes = displayDOMUtils.addLinkAttributes; <ide> var LinkTarget = displayDOMUtils.LinkTarget; <ide> var TextWidgetAnnotationElement = ( <ide> element.type = 'text'; <ide> element.value = this.data.fieldValue; <ide> <del> if (isInt(this.data.maxLen)) { <add> if (this.data.maxLen !== null) { <ide> element.maxLength = this.data.maxLen; <ide> } <ide> } else { <ide> var TextWidgetAnnotationElement = ( <ide> this._setTextStyle(element, font); <ide> } <ide> <del> if (isInt(this.data.textAlignment)) { <add> if (this.data.textAlignment !== null) { <ide> element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; <ide> } <ide> <ide><path>test/unit/annotation_layer_spec.js <ide> describe('Annotation layer', function() { <ide> }); <ide> }); <ide> <add> describe('TextWidgetAnnotation', function() { <add> var textWidgetDict; <add> <add> beforeEach(function (done) { <add> textWidgetDict = new Dict(); <add> textWidgetDict.set('Type', Name.get('Annot')); <add> textWidgetDict.set('Subtype', Name.get('Widget')); <add> textWidgetDict.set('FT', Name.get('Tx')); <add> <add> done(); <add> }); <add> <add> afterEach(function () { <add> textWidgetDict = null; <add> }); <add> <add> it('should handle unknown text alignment and maximum length', function() { <add> var textWidgetRef = new Ref(124, 0); <add> var xref = new XRefMock([ <add> { ref: textWidgetRef, data: textWidgetDict, } <add> ]); <add> <add> var textWidgetAnnotation = annotationFactory.create(xref, textWidgetRef); <add> expect(textWidgetAnnotation.data.textAlignment).toEqual(null); <add> expect(textWidgetAnnotation.data.maxLen).toEqual(null); <add> }); <add> <add> it('should not set invalid text alignment and maximum length', function() { <add> textWidgetDict.set('Q', 'center'); <add> textWidgetDict.set('MaxLen', 'five'); <add> <add> var textWidgetRef = new Ref(43, 0); <add> var xref = new XRefMock([ <add> { ref: textWidgetRef, data: textWidgetDict, } <add> ]); <add> <add> var textWidgetAnnotation = annotationFactory.create(xref, textWidgetRef); <add> expect(textWidgetAnnotation.data.textAlignment).toEqual(null); <add> expect(textWidgetAnnotation.data.maxLen).toEqual(null); <add> }); <add> <add> it('should set valid text alignment and maximum length', function() { <add> textWidgetDict.set('Q', 1); <add> textWidgetDict.set('MaxLen', 20); <add> <add> var textWidgetRef = new Ref(84, 0); <add> var xref = new XRefMock([ <add> { ref: textWidgetRef, data: textWidgetDict, } <add> ]); <add> <add> var textWidgetAnnotation = annotationFactory.create(xref, textWidgetRef); <add> expect(textWidgetAnnotation.data.textAlignment).toEqual(1); <add> expect(textWidgetAnnotation.data.maxLen).toEqual(20); <add> }); <add> }); <add> <ide> describe('FileAttachmentAnnotation', function() { <ide> var loadingTask; <ide> var annotations;
3
Text
Text
add introduction to higher-order reducers
5b0fc91f2079fd7fd864757cfc356763f381021c
<ide><path>docs/recipes/ImplementingUndoHistory.md <ide> # Implementing Undo History <ide> <add>To add undo functionality (or any other functionality) to your existing <add>reducers, you need to create a higher-order reducer, which is a function <add>(reducer) that returns a reducer. This returned reducer is enhanced with undo <add>functionality (or any other functionality). It could look like this: <add> <add>```js <add>export default function undoable(reducer) { <add> return (state, action) => { <add> switch (action.type) { <add> case 'UNDO_ACTION': <add> return undo(state); // undo here and return the past state <add> case 'REDO_ACTION': <add> return redo(state); // redo here and return the future state <add> default: <add> let res = reducer(state, action); <add> return { <add> present: res, <add> history: updateHistory(res, state.history) // store `res` in history <add> } <add> } <add> } <add>} <add>``` <add> <add>Fortunately, you won't have to implement all that, because there's already a <add>library that does this. <add> <add> <add>## Introducing redux-undo <add> <ide> [redux-undo](https://github.com/omnidan/redux-undo) is a library that provides simple undo/redo functionality for any part of your redux tree. <ide> <ide> In this recipe, you will learn how to make the [Todo List example](http://rackt.github.io/redux/docs/basics/ExampleTodoList.html) undoable - all it takes are [two lines of code](https://twitter.com/dan_abramov/status/647040825826918400) and a few terminal commands! <ide> export default class Footer extends Component { <ide> </p> <ide> ); <ide> } <del> <add> <ide> render() { <ide> return ( <ide> <div>
1
Javascript
Javascript
fix reference to mustfix in rctlog
4b78ed2123e638f4169ee59fede35ac5ec204107
<ide><path>Libraries/Utilities/RCTLog.js <ide> var levelsMap = { <ide> info: 'info', <ide> warn: 'warn', <ide> error: 'error', <del> mustfix: 'error', <add> fatal: 'error', <ide> }; <ide> <ide> class RCTLog {
1
PHP
PHP
add public validate method to the validator
8a73322ef2c56fa70d68d18a0fdc5265582539de
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> public function render($request, Exception $e) <ide> $e = new NotFoundHttpException($e->getMessage(), $e); <ide> } elseif ($e instanceof AuthorizationException) { <ide> $e = new HttpException(403, $e->getMessage()); <del> } elseif ($e instanceof ValidationException && $e->getResponse()) { <del> return $e->getResponse(); <add> } elseif ($e instanceof ValidationException) { <add> return $this->convertValidationExceptionToResponse($e, $request); <ide> } <ide> <ide> if ($this->isHttpException($e)) { <ide> protected function renderHttpException(HttpException $e) <ide> } <ide> } <ide> <add> /** <add> * Create a response object from the given validation exception. <add> * <add> * @param \Illuminate\Validation\ValidationException $e <add> * @param \Illuminate\Http\Request $request <add> * @return \Symfony\Component\HttpFoundation\Response <add> */ <add> protected function convertValidationExceptionToResponse(ValidationException $e, $request) <add> { <add> if ($e->response) { <add> return $e->response; <add> } <add> <add> $errors = $e->validator->errors()->getMessages(); <add> <add> if (($request->ajax() && ! $request->pjax()) || $request->wantsJson()) { <add> return response()->json($errors, 422); <add> } <add> <add> return redirect()->back()->withInput($request->input())->withErrors($errors); <add> } <add> <ide> /** <ide> * Create a Symfony response for the given exception. <ide> * <ide><path>src/Illuminate/Validation/ValidationException.php <ide> class ValidationException extends Exception <ide> /** <ide> * The validator instance. <ide> * <del> * @var \Illuminate\Validation\Validator <add> * @var \Illuminate\Contracts\Validation\Validator <ide> */ <ide> public $validator; <ide> <ide> class ValidationException extends Exception <ide> /** <ide> * Create a new exception instance. <ide> * <del> * @param \Illuminate\Validation\Validator $validator <add> * @param \Illuminate\Contracts\Validation\Validator $validator <ide> * @param \Illuminate\Http\Response $response <ide> * @return void <ide> */ <ide> public function __construct($validator, $response = null) <ide> /** <ide> * Get the underlying response instance. <ide> * <del> * @return \Symfony\Component\HttpFoundation\Response <add> * @return \Symfony\Component\HttpFoundation\Response|null <ide> */ <ide> public function getResponse() <ide> { <ide><path>src/Illuminate/Validation/Validator.php <ide> public function passes() <ide> // the other error messages, returning true if we don't have messages. <ide> foreach ($this->rules as $attribute => $rules) { <ide> foreach ($rules as $rule) { <del> $this->validate($attribute, $rule); <add> $this->validateAttribute($attribute, $rule); <ide> <ide> if ($this->shouldStopValidating($attribute)) { <ide> break; <ide> public function fails() <ide> return ! $this->passes(); <ide> } <ide> <add> /** <add> * Run the validator's rules against its data. <add> * <add> * @return void <add> * <add> * @throws \Illuminate\Validation\ValidationException <add> */ <add> public function validate() <add> { <add> if ($this->fails()) { <add> throw new ValidationException($this); <add> } <add> } <add> <ide> /** <ide> * Validate a given attribute against a rule. <ide> * <ide> * @param string $attribute <ide> * @param string $rule <ide> * @return void <ide> */ <del> protected function validate($attribute, $rule) <add> protected function validateAttribute($attribute, $rule) <ide> { <ide> list($rule, $parameters) = $this->parseRule($rule); <ide>
3
Javascript
Javascript
use const instead of var
b5d8e974517593d2b82d7a234eddf81e9006892d
<ide><path>lib/WebAssemblyParser.js <ide> */ <ide> "use strict"; <ide> <del>var Tools = require("webassembly-interpreter/lib/tools"); <add>const Tools = require("webassembly-interpreter/lib/tools"); <ide> <ide> const Tapable = require("tapable").Tapable; <ide> const WebAssemblyImportDependency = require("./dependencies/WebAssemblyImportDependency");
1
Python
Python
fix typos and indentation in lfads.py
730b778ebb95b663237a82649c92e47e9453a123
<ide><path>research/lfads/lfads.py <ide> 'train_ext_input' and 'valid_ext_input', if there are know external inputs <ide> to the system being modeled, these take on dimensions: <ide> ExTxI, E - # examples, T - # time steps, I = # dimensions in input. <del> 'alignment_matrix_cxf' - If you are using multiple days data, it's possible <del> that one can align the channels (see manuscript). If so each dataset will <del> contain this matrix, which will be used for both the input adapter and the <del> output adapter for each dataset. These matrices, if provided, must be of <del> size [data_dim x factors] where data_dim is the number of neurons recorded <del> on that day, and factors is chosen and set through the '--factors' flag. <del> 'alignment_bias_c' - See alignment_matrix_cxf. This bias will used to <del> the offset for the alignment transformation. It will *subtract* off the <del> bias from the data, so pca style inits can align factors across sessions. <add> 'alignment_matrix_cxf' - If you are using multiple days data, it's possible <add> that one can align the channels (see manuscript). If so each dataset will <add> contain this matrix, which will be used for both the input adapter and the <add> output adapter for each dataset. These matrices, if provided, must be of <add> size [data_dim x factors] where data_dim is the number of neurons recorded <add> on that day, and factors is chosen and set through the '--factors' flag. <add> 'alignment_bias_c' - See alignment_matrix_cxf. This bias will used to <add> the offset for the alignment transformation. It will *subtract* off the <add> bias from the data, so pca style inits can align factors across sessions. <ide> <ide> <ide> If one runs LFADS on data where the true rates are known for some trials, <ide> def __init__(self, num_units, forget_bias=1.0, weight_scale=1.0, <ide> """Create a GRU object. <ide> <ide> Args: <del> num_units: Number of units in the GRU <add> num_units: Number of units in the GRU. <ide> forget_bias (optional): Hack to help learning. <del> weight_scale (optional): weights are scaled by ws/sqrt(#inputs), with <del> ws being the weight scale. <del> clip_value (optional): if the recurrent values grow above this value, <add> weight_scale (optional): Weights are scaled by ws/sqrt(#inputs), with <add> ws being the weight scale. <add> clip_value (optional): If the recurrent values grow above this value, <ide> clip them. <del> collections (optional): List of additonal collections variables should <add> collections (optional): List of additional collections variables should <ide> belong to. <ide> """ <ide> self._num_units = num_units <ide> def __init__(self, num_units, forget_bias=1.0, <ide> """Create a GRU object. <ide> <ide> Args: <del> num_units: Number of units in the GRU <add> num_units: Number of units in the GRU. <ide> forget_bias (optional): Hack to help learning. <del> input_weight_scale (optional): weights are scaled ws/sqrt(#inputs), with <add> input_weight_scale (optional): Weights are scaled ws/sqrt(#inputs), with <ide> ws being the weight scale. <del> rec_weight_scale (optional): weights are scaled ws/sqrt(#inputs), <add> rec_weight_scale (optional): Weights are scaled ws/sqrt(#inputs), <ide> with ws being the weight scale. <del> clip_value (optional): if the recurrent values grow above this value, <add> clip_value (optional): If the recurrent values grow above this value, <ide> clip them. <del> input_collections (optional): List of additonal collections variables <add> input_collections (optional): List of additional collections variables <ide> that input->rec weights should belong to. <del> recurrent_collections (optional): List of additonal collections variables <add> recurrent_collections (optional): List of additional collections variables <ide> that rec->rec weights should belong to. <ide> """ <ide> self._num_units = num_units <ide> class LFADS(object): <ide> various factors, such as an initial condition, a generative <ide> dynamical system, inferred inputs to that generator, and a low <ide> dimensional description of the observed data, called the factors. <del> Additoinally, the observations have a noise model (in this case <add> Additionally, the observations have a noise model (in this case <ide> Poisson), so a denoised version of the observations is also created <ide> (e.g. underlying rates of a Poisson distribution given the observed <ide> event counts). <ide> def __init__(self, hps, kind="train", datasets=None): <ide> <ide> Args: <ide> hps: The dictionary of hyper parameters. <del> kind: the type of model to build (see above). <del> datasets: a dictionary of named data_dictionaries, see top of lfads.py <add> kind: The type of model to build (see above). <add> datasets: A dictionary of named data_dictionaries, see top of lfads.py <ide> """ <ide> print("Building graph...") <ide> all_kinds = ['train', 'posterior_sample_and_average', 'posterior_push_mean', <ide> def encode_data(dataset_bxtxd, enc_cell, name, forward_or_reverse, <ide> if kind != "train": <ide> # save every so often <ide> self.seso_saver = tf.train.Saver(tf.global_variables(), <del> max_to_keep=hps.max_ckpt_to_keep) <add> max_to_keep=hps.max_ckpt_to_keep) <ide> # lowest validation error <ide> self.lve_saver = tf.train.Saver(tf.global_variables(), <ide> max_to_keep=hps.max_ckpt_to_keep_lve) <ide> def encode_data(dataset_bxtxd, enc_cell, name, forward_or_reverse, <ide> zip(grads, tvars), global_step=self.train_step) <ide> <ide> self.seso_saver = tf.train.Saver(tf.global_variables(), <del> max_to_keep=hps.max_ckpt_to_keep) <add> max_to_keep=hps.max_ckpt_to_keep) <ide> <ide> # lowest validation error <ide> self.lve_saver = tf.train.Saver(tf.global_variables(), <ide> def encode_data(dataset_bxtxd, enc_cell, name, forward_or_reverse, <ide> self.example_image = tf.placeholder(tf.float32, shape=[1,None,None,3], <ide> name='image_tensor') <ide> self.example_summ = tf.summary.image("LFADS example", self.example_image, <del> collections=["example_summaries"]) <add> collections=["example_summaries"]) <ide> <ide> # general training summaries <ide> self.lr_summ = tf.summary.scalar("Learning rate", self.learning_rate) <ide> def build_feed_dict(self, train_name, data_bxtxd, ext_input_bxtxi=None, <ide> Args: <ide> train_name: The key into the datasets, to set the tf.case statement for <ide> the proper readin / readout matrices. <del> data_bxtxd: The data tensor <del> ext_input_bxtxi (optional): The external input tensor <add> data_bxtxd: The data tensor. <add> ext_input_bxtxi (optional): The external input tensor. <ide> keep_prob: The drop out keep probability. <ide> <ide> Returns: <ide> def get_batch(data_extxd, ext_input_extxi=None, batch_size=None, <ide> # examples x # time steps x # dimensions <ide> ext_input_extxi (optional): The external inputs, numpy tensor with shape: <ide> # examples x # time steps x # external input dimensions <del> batch_size: The size of the batch to return <add> batch_size: The size of the batch to return. <ide> example_idxs (optional): The example indices used to select examples. <ide> <ide> Returns: <ide> def randomize_example_idxs_mod_batch_size(nexamples, batch_size): <ide> is managed by drawing randomly from 1:nexamples. <ide> <ide> Args: <del> nexamples: number of examples to randomize <del> batch_size: number of elements in batch <add> nexamples: Number of examples to randomize. <add> batch_size: Number of elements in batch. <ide> <ide> Returns: <ide> The randomized, properly shaped indicies. <ide> def shuffle_spikes_in_time(self, data_bxtxd): <ide> enough to pick up dynamics that you may not want. <ide> <ide> Args: <del> data_bxtxd: numpy array of spike count data to be shuffled. <add> data_bxtxd: Numpy array of spike count data to be shuffled. <ide> Returns: <ide> S_bxtxd, a numpy array with the same dimensions and contents as <ide> data_bxtxd, but shuffled appropriately. <ide> def train_epoch(self, datasets, batch_size=None, do_save_ckpt=True): <ide> Args: <ide> datasets: A dict of data dicts. The dataset dict is simply a <ide> name(string)-> data dictionary mapping (See top of lfads.py). <del> batch_size (optional): The batch_size to use <add> batch_size (optional): The batch_size to use. <ide> do_save_ckpt (optional): Should the routine save a checkpoint on this <ide> training epoch? <ide> <ide> def run_epoch(self, datasets, ops_to_eval, kind="train", batch_size=None, <ide> name(string)-> data dictionary mapping (See top of lfads.py). <ide> ops_to_eval: A list of tensorflow operations that will be evaluated in <ide> the tf.session.run() call. <del> batch_size (optional): The batch_size to use <add> batch_size (optional): The batch_size to use. <ide> do_collect (optional): Should the routine collect all session.run <ide> output as a list, and return it? <ide> keep_prob (optional): The dropout keep probability. <ide> def summarize_all(self, datasets, summary_values): <ide> <ide> Args: <ide> datasets, the dictionary of datasets used in the study. <del> summary_values: These summary values are created from the training loop, <add> summary_values: These summary values are created from the training loop, <ide> and so summarize the entire set of datasets. <ide> """ <ide> hps = self.hps <ide> def eval_model_runs_batch(self, data_name, data_bxtxd, ext_input_bxtxi=None, <ide> Args: <ide> data_name: The name of the data dict, to select which in/out matrices <ide> to use. <del> data_bxtxd: Numpy array training data with shape: <add> data_bxtxd: Numpy array training data with shape: <ide> batch_size x # time steps x # dimensions <ide> ext_input_bxtxi: Numpy array training external input with shape: <ide> batch_size x # time steps x # external input dims <ide> do_eval_cost (optional): If true, the IWAE (Importance Weighted <del> Autoencoder) log likeihood bound, instead of the VAE version. <add> Autoencoder) log likeihood bound, instead of the VAE version. <ide> do_average_batch (optional): average over the batch, useful for getting <ide> good IWAE costs, and model outputs for a single data point. <ide> <ide> def eval_model_runs_avg_epoch(self, data_name, data_extxd, <ide> Args: <ide> data_name: The name of the data dict, to select which in/out matrices <ide> to use. <del> data_extxd: Numpy array training data with shape: <add> data_extxd: Numpy array training data with shape: <ide> # examples x # time steps x # dimensions <ide> ext_input_extxi (optional): Numpy array training external input with <ide> shape: # examples x # time steps x # external input dims <ide> def eval_model_runs_avg_epoch(self, data_name, data_extxd, <ide> <ide> def eval_model_runs_push_mean(self, data_name, data_extxd, <ide> ext_input_extxi=None): <del> """Returns values of interest for the model by pushing the means through <add> """Returns values of interest for the model by pushing the means through <ide> <ide> The mean values for both initial conditions and the control inputs are <ide> pushed through the model instead of sampling (as is done in <ide> def eval_model_runs_push_mean(self, data_name, data_extxd, <ide> Args: <ide> data_name: The name of the data dict, to select which in/out matrices <ide> to use. <del> data_extxd: Numpy array training data with shape: <add> data_extxd: Numpy array training data with shape: <ide> # examples x # time steps x # dimensions <ide> ext_input_extxi (optional): Numpy array training external input with <ide> shape: # examples x # time steps x # external input dims <ide> def write_model_runs(self, datasets, output_fname=None, push_mean=False): <ide> saved. They are: <ide> The mean and variance of the prior of g0. <ide> The mean and variance of approximate posterior of g0. <del> The control inputs (if enabled) <add> The control inputs (if enabled). <ide> The initial conditions, g0, for all examples. <ide> The generator states for all time. <ide> The factors for all time. <ide> The output distribution parameters (e.g. rates) for all time. <ide> <ide> Args: <del> datasets: a dictionary of named data_dictionaries, see top of lfads.py <add> datasets: A dictionary of named data_dictionaries, see top of lfads.py <ide> output_fname: a file name stem for the output files. <del> push_mean: if False (default), generates batch_size samples for each trial <add> push_mean: If False (default), generates batch_size samples for each trial <ide> and averages the results. if True, runs each trial once without noise, <ide> pushing the posterior mean initial conditions and control inputs through <ide> the trained model. False is used for posterior_sample_and_average, True <ide> def write_model_samples(self, dataset_name, output_fname=None): <ide> LFADS generates a number of outputs for each sample, and these are all <ide> saved. They are: <ide> The mean and variance of the prior of g0. <del> The control inputs (if enabled) <add> The control inputs (if enabled). <ide> The initial conditions, g0, for all examples. <ide> The generator states for all time. <ide> The factors for all time. <ide> def spikify_rates(rates_bxtxd): <ide> """Randomly spikify underlying rates according a Poisson distribution <ide> <ide> Args: <del> rates_bxtxd: a numpy tensor with shape: <add> rates_bxtxd: A numpy tensor with shape: <ide> <ide> Returns: <ide> A numpy array with the same shape as rates_bxtxd, but with the event
1
Text
Text
fix missing parentport link in worker_threads
182ee78164a261836464364e6b5131df5c2c4d77
<ide><path>doc/api/worker_threads.md <ide> active handle in the event system. If the worker is already `unref()`ed calling <ide> [`require('worker_threads').on('workerMessage')`]: #worker_threads_event_workermessage <ide> [`require('worker_threads').postMessage()`]: #worker_threads_worker_postmessage_value_transferlist <ide> [`require('worker_threads').isMainThread`]: #worker_threads_worker_ismainthread <add>[`require('worker_threads').parentPort`]: #worker_threads_worker_parentport <ide> [`require('worker_threads').threadId`]: #worker_threads_worker_threadid <ide> [`cluster` module]: cluster.html <ide> [`inspector`]: inspector.html
1
Text
Text
add url argument with http/https request
60d14c870274e9f193a81e8eb9b6a74fba3b4178
<ide><path>doc/api/http.md <ide> added to the [`'request'`][] event. <ide> ## http.get(options[, callback]) <ide> <!-- YAML <ide> added: v0.3.6 <add>changes: <add> - version: v7.5.0 <add> pr-url: https://github.com/nodejs/node/pull/10638 <add> description: The `options` parameter can be a WHATWG `URL` object. <ide> --> <ide> <del>* `options` {Object | string} Accepts the same `options` as <add>* `options` {Object | string | URL} Accepts the same `options` as <ide> [`http.request()`][], with the `method` always set to `GET`. <ide> Properties that are inherited from the prototype are ignored. <ide> * `callback` {Function} <ide> requests. <ide> ## http.request(options[, callback]) <ide> <!-- YAML <ide> added: v0.3.6 <add>changes: <add> - version: v7.5.0 <add> pr-url: https://github.com/nodejs/node/pull/10638 <add> description: The `options` parameter can be a WHATWG `URL` object. <ide> --> <ide> <del>* `options` {Object | string} <add>* `options` {Object | string | URL} <ide> * `protocol` {string} Protocol to use. Defaults to `http:`. <ide> * `host` {string} A domain name or IP address of the server to issue the <ide> request to. Defaults to `localhost`. <ide> added: v0.3.6 <ide> Node.js maintains several connections per server to make HTTP requests. <ide> This function allows one to transparently issue requests. <ide> <del>`options` can be an object or a string. If `options` is a string, it is <del>automatically parsed with [`url.parse()`][]. <add>`options` can be an object, a string, or a [`URL`][] object. If `options` is a <add>string, it is automatically parsed with [`url.parse()`][]. If it is a [`URL`][] <add>object, it will be automatically converted to an ordinary `options` object. <ide> <ide> The optional `callback` parameter will be added as a one time listener for <ide> the [`'response'`][] event. <ide> There are a few special headers that should be noted. <ide> * Sending an Authorization header will override using the `auth` option <ide> to compute basic authentication. <ide> <add>Example using a [`URL`][] as `options`: <add> <add>```js <add>const { URL } = require('url'); <add> <add>const options = new URL('http://abc:xyz@example.com'); <add> <add>const req = http.request(options, (res) => { <add> // ... <add>}); <add>``` <add> <ide> [`'checkContinue'`]: #http_event_checkcontinue <ide> [`'listening'`]: net.html#net_event_listening <ide> [`'request'`]: #http_event_request <ide> [`'response'`]: #http_event_response <ide> [`Agent`]: #http_class_http_agent <ide> [`EventEmitter`]: events.html#events_class_eventemitter <ide> [`TypeError`]: errors.html#errors_class_typeerror <add>[`URL`]: url.html#url_the_whatwg_url_api <ide> [`agent.createConnection()`]: #http_agent_createconnection_options_callback <ide> [`destroy()`]: #http_agent_destroy <ide> [`http.Agent`]: #http_class_http_agent <ide><path>doc/api/https.md <ide> See [`http.listen()`][] for details. <ide> ## https.get(options[, callback]) <ide> <!-- YAML <ide> added: v0.3.6 <add>changes: <add> - version: v7.5.0 <add> pr-url: https://github.com/nodejs/node/pull/10638 <add> description: The `options` parameter can be a WHATWG `URL` object. <ide> --> <del>- `options` {Object | string} Accepts the same `options` as <add>- `options` {Object | string | URL} Accepts the same `options` as <ide> [`https.request()`][], with the `method` always set to `GET`. <ide> - `callback` {Function} <ide> <ide> Like [`http.get()`][] but for HTTPS. <ide> <del>`options` can be an object or a string. If `options` is a string, it is <del>automatically parsed with [`url.parse()`][]. <add>`options` can be an object, a string, or a [`URL`][] object. If `options` is a <add>string, it is automatically parsed with [`url.parse()`][]. If it is a [`URL`][] <add>object, it will be automatically converted to an ordinary `options` object. <ide> <ide> Example: <ide> <ide> Global instance of [`https.Agent`][] for all HTTPS client requests. <ide> ## https.request(options[, callback]) <ide> <!-- YAML <ide> added: v0.3.6 <add>changes: <add> - version: v7.5.0 <add> pr-url: https://github.com/nodejs/node/pull/10638 <add> description: The `options` parameter can be a WHATWG `URL` object. <ide> --> <del>- `options` {Object | string} Accepts all `options` from [`http.request()`][], <add>- `options` {Object | string | URL} Accepts all `options` from [`http.request()`][], <ide> with some differences in default values: <ide> - `protocol` Defaults to `https:` <ide> - `port` Defaults to `443`. <ide> The following additional `options` from [`tls.connect()`][] are also accepted wh <ide> custom [`Agent`][]: <ide> `pfx`, `key`, `passphrase`, `cert`, `ca`, `ciphers`, `rejectUnauthorized`, `secureProtocol`, `servername` <ide> <del>`options` can be an object or a string. If `options` is a string, it is <del>automatically parsed with [`url.parse()`][]. <add>`options` can be an object, a string, or a [`URL`][] object. If `options` is a <add>string, it is automatically parsed with [`url.parse()`][]. If it is a [`URL`][] <add>object, it will be automatically converted to an ordinary `options` object. <ide> <ide> Example: <ide> <ide> const req = https.request(options, (res) => { <ide> }); <ide> ``` <ide> <add>Example using a [`URL`][] as `options`: <add> <add>```js <add>const { URL } = require('url'); <add> <add>const options = new URL('https://abc:xyz@example.com'); <add> <add>const req = https.request(options, (res) => { <add> // ... <add>}); <add>``` <add> <ide> [`Agent`]: #https_class_https_agent <add>[`URL`]: url.html#url_the_whatwg_url_api <ide> [`http.Agent`]: http.html#http_class_http_agent <ide> [`http.Server#keepAliveTimeout`]: http.html#http_server_keepalivetimeout <ide> [`http.Server#setTimeout()`]: http.html#http_server_settimeout_msecs_callback
2
Javascript
Javascript
fix onhashchange tests for ie
0ad39dde4f4dd4c50e08ccfdc086fad3fe576ff2
<ide><path>test/BrowserSpecs.js <ide> describe('browser', function(){ <ide> expect(type).toEqual('hashchange'); <ide> onHashChngListener = listener; <ide> }, <del> removeEventListener: angular.noop <add> attachEvent: function(type, listener) { <add> expect(type).toEqual('onhashchange'); <add> onHashChngListener = listener; <add> }, <add> removeEventListener: angular.noop, <add> detachEvent: angular.noop <ide> }; <ide> fakeWindow.onhashchange = true; <ide>
1
Text
Text
add active job to configuring guide [ci skip]
fc11ea4a0dea9b103544d1ae6ee3e92fa14432de
<ide><path>guides/CHANGELOG.md <add>* New section in Configuring: Configuring Active Job <add> <add> *Eliot Sykes* <add> <ide> * New section in Active Record Association Basics: Single Table Inheritance <ide> <ide> *Andrey Nering* <ide><path>guides/source/configuring.md <ide> There are a few configuration options available in Active Support: <ide> <ide> * `ActiveSupport::Deprecation.silenced` sets whether or not to display deprecation warnings. <ide> <add>### Configuring Active Job <add> <add>`config.active_job` provides the following configuration options: <add> <add>* `config.active_job.queue_adapter` sets the adapter for the queueing backend. The default adapter is `:inline` which will perform jobs immediately. For an up-to-date list of built-in adapters see the [ActiveJob::QueueAdapters API documentation](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html). <add> <add> ```ruby <add> # Be sure to have the adapter's gem in your Gemfile <add> # and follow the adapter's specific installation <add> # and deployment instructions. <add> config.active_job.queue_adapter = :sidekiq <add> ``` <add> <add>* `config.active_job.default_queue_name` can be used to change the default queue name. By default this is `"default"`. <add> <add> ```ruby <add> config.active_job.default_queue_name = :medium_priority <add> ``` <add> <add>* `config.active_job.queue_name_prefix` allows you to set an optional, non-blank, queue name prefix for all jobs. By default it is blank and not used. <add> <add> The following configuration would queue the given job on the `production_high_priority` queue when run in production: <add> <add> ```ruby <add> config.active_job.queue_name_prefix = Rails.env <add> ``` <add> <add> ```ruby <add> class GuestsCleanupJob < ActiveJob::Base <add> queue_as :high_priority <add> #.... <add> end <add> ``` <add> <add>* `config.active_job.queue_name_delimiter` has a default value of `'_'`. If `queue_name_prefix` is set, then `queue_name_delimiter` joins the prefix and the non-prefixed queue name. <add> <add> The following configuration would queue the provided job on the `video_server.low_priority` queue: <add> <add> ```ruby <add> # prefix must be set for delimiter to be used <add> config.active_job.queue_name_prefix = 'video_server' <add> config.active_job.queue_name_delimiter = '.' <add> ``` <add> <add> ```ruby <add> class EncoderJob < ActiveJob::Base <add> queue_as :low_priority <add> #.... <add> end <add> ``` <add> <add>* `config.active_job.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Active Job. You can retrieve this logger by calling `logger` on either an Active Job class or an Active Job instance. Set to `nil` to disable logging. <ide> <ide> ### Configuring a Database <ide> <ide> Below is a comprehensive list of all the initializers found in Rails in the orde <ide> <ide> * `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`. <ide> <add>* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set - to `Rails.logger` <add> <add>* `active_job.set_configs` Sets up Active Job by using the settings in `config.active_job` by `send`'ing the method names as setters to `ActiveJob::Base` and passing the values through. <add> <ide> * `action_mailer.logger` Sets `ActionMailer::Base.logger` - if it's not already set - to `Rails.logger`. <ide> <ide> * `action_mailer.set_configs` Sets up Action Mailer by using the settings in `config.action_mailer` by `send`'ing the method names as setters to `ActionMailer::Base` and passing the values through.
2
Javascript
Javascript
fix animation of pdp dismissal
d1b507a5c371f308d6c8e56acfe96c03e9922084
<ide><path>Libraries/Animated/src/createAnimatedComponent.js <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> }; <ide> <ide> _waitForUpdate = (): void => { <del> // If this works well on iOS, we should remove this check <ide> if (this._isFabric()) { <ide> if (this._animatedComponentId === -1) { <ide> this._animatedComponentId = animatedComponentNextId++; <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> }; <ide> <ide> _markUpdateComplete = (): void => { <del> // If this works well on iOS, we should remove this check <ide> if (this._isFabric()) { <ide> NativeAnimatedHelper.API.unsetWaitingForIdentifier( <ide> this._animatedComponentId, <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> {...passthruProps} <ide> style={mergedStyle} <ide> ref={this._setComponentRef} <add> nativeID={this._isFabric() ? 'animatedComponent' : undefined} <ide> // The native driver updates views directly through the UI thread so we <ide> // have to make sure the view doesn't get optimized away because it cannot <ide> // go through the NativeViewHierarchyManager since it operates on the shadow
1
Ruby
Ruby
fix typo in headers comment
67263020ec4c40ff1cef5080056b233e9d723116
<ide><path>actionpack/lib/action_dispatch/http/headers.rb <ide> module Http <ide> # env = { "CONTENT_TYPE" => "text/plain", "HTTP_USER_AGENT" => "curl/7.43.0" } <ide> # headers = ActionDispatch::Http::Headers.new(env) <ide> # headers["Content-Type"] # => "text/plain" <del> # headers["User-Agent"] # => "curl/7/43/0" <add> # headers["User-Agent"] # => "curl/7.43.0" <ide> # <ide> # Also note that when headers are mapped to CGI-like variables by the Rack <ide> # server, both dashes and underscores are converted to underscores. This
1
Python
Python
make textvectorization work with list input
f604d042f892ded1d47c6ecbb6b8a9e71a0f1367
<ide><path>keras/layers/preprocessing/text_vectorization.py <ide> def build(self, input_shape): <ide> # expression to evaluate to False instead of True if the shape is undefined; <ide> # the expression needs to evaluate to True in that case. <ide> if self._split is not None: <del> if input_shape.ndims > 1 and not input_shape[-1] == 1: # pylint: disable=g-comparison-negation <add> if (input_shape is not None and input_shape.ndims > 1 and <add> not input_shape[-1] == 1): # pylint: disable=g-comparison-negation <ide> raise RuntimeError( <ide> "When using TextVectorization to tokenize strings, the innermost " <ide> "dimension of the input array must be 1, got shape " <ide><path>keras/layers/preprocessing/text_vectorization_test.py <ide> def test_layer_dimensionality_handling_with_split(self, data, expected): <ide> output = vectorization(tf.ragged.constant(data, inner_shape=(1,))) <ide> self.assertAllEqual(expected, output) <ide> <add> def test_layer_list_input(self): <add> layer = text_vectorization.TextVectorization(vocabulary=["a", "b", "c"]) <add> output = layer(["a", "b", "c"]) <add> expected_output = [[2], [3], [4]] <add> self.assertEqual(output.numpy().tolist(), expected_output) <add> <ide> <ide> @keras_parameterized.run_all_keras_modes(always_skip_v1=True) <ide> class TextVectorizationPreprocessingTest(
2
Javascript
Javascript
ensure options.flag defaults to 'r' in readfile
2cd3e61b2f222c1e9e396dce6310203fdd960143
<ide><path>lib/internal/fs/promises.js <ide> async function readFileHandle(filehandle, options) { <ide> } <ide> <ide> if (size === 0) <del> return Buffer.alloc(0); <add> return options.encoding ? '' : Buffer.alloc(0); <ide> <ide> if (size > kMaxLength) <ide> throw new ERR_FS_FILE_TOO_LARGE(size); <ide> async function appendFile(path, data, options) { <ide> <ide> async function readFile(path, options) { <ide> options = getOptions(options, { flag: 'r' }); <add> const flag = options.flag || 'r'; <ide> <ide> if (path instanceof FileHandle) <ide> return readFileHandle(path, options); <ide> <del> const fd = await open(path, options.flag, 0o666); <add> const fd = await open(path, flag, 0o666); <ide> return readFileHandle(fd, options).finally(fd.close.bind(fd)); <ide> } <ide> <ide><path>test/parallel/test-fs-promises-readfile-empty.js <add>'use strict'; <add>const common = require('../common'); <add> <add>const assert = require('assert'); <add>const { promises: fs } = require('fs'); <add>const fixtures = require('../common/fixtures'); <add> <add>const fn = fixtures.path('empty.txt'); <add> <add>common.crashOnUnhandledRejection(); <add> <add>fs.readFile(fn) <add> .then(assert.ok); <add> <add>fs.readFile(fn, 'utf8') <add> .then(assert.strictEqual.bind(this, '')); <add> <add>fs.readFile(fn, { encoding: 'utf8' }) <add> .then(assert.strictEqual.bind(this, '')); <ide><path>test/parallel/test-fs-readfile-empty.js <ide> fs.readFile(fn, 'utf8', function(err, data) { <ide> assert.strictEqual('', data); <ide> }); <ide> <add>fs.readFile(fn, { encoding: 'utf8' }, function(err, data) { <add> assert.strictEqual('', data); <add>}); <add> <ide> assert.ok(fs.readFileSync(fn)); <ide> assert.strictEqual('', fs.readFileSync(fn, 'utf8'));
3
PHP
PHP
fix unexpected output. flush expections
c90fc5f6b8e91e3f6b0f2f3a74cad7d8a49bc71b
<ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php <ide> trait InteractsWithConsole <ide> public $expectedOutput = []; <ide> <ide> /** <del> * All of the output lines that are expected to never be output. <add> * All of the output lines that aren't expected to be displayed. <ide> * <ide> * @var array <ide> */ <del> public $expectedOutputNever = []; <add> public $unexpectedOutput = []; <ide> <ide> /** <ide> * All of the expected ouput tables. <ide><path>src/Illuminate/Testing/PendingCommand.php <ide> public function expectsOutput($output) <ide> * @param string $output <ide> * @return $this <ide> */ <del> public function expectsOutputNever($output) <add> public function doesntExpectOutput($output) <ide> { <del> $this->test->expectedOutputNever[$output] = false; <add> $this->test->unexpectedOutput[$output] = false; <ide> <ide> return $this; <ide> } <ide> public function run() <ide> } <ide> <ide> $this->verifyExpectations(); <add> $this->flushExpectations(); <ide> <ide> return $exitCode; <ide> } <ide> protected function verifyExpectations() <ide> $this->test->fail('Output "'.Arr::first($this->test->expectedOutput).'" was not printed.'); <ide> } <ide> <del> if ($output = array_search(true, $this->test->expectedOutputNever)) { <add> if ($output = array_search(true, $this->test->unexpectedOutput)) { <ide> $this->test->fail('Output "'.$output.'" was printed.'); <ide> } <ide> } <ide> private function createABufferedOutputMock() <ide> }); <ide> } <ide> <del> foreach ($this->test->expectedOutputNever as $output => $displayed) { <add> foreach ($this->test->unexpectedOutput as $output => $displayed) { <ide> $mock->shouldReceive('doWrite') <ide> ->once() <ide> ->ordered() <ide> ->with($output, Mockery::any()) <ide> ->andReturnUsing(function () use ($output) { <del> $this->test->expectedOutputNever[$output] = true; <add> $this->test->unexpectedOutput[$output] = true; <ide> }); <ide> } <ide> <ide> private function applyTableOutputExpectations($mock) <ide> } <ide> } <ide> <add> /** <add> * Flush the expectations from the test case. <add> * <add> * @return void <add> */ <add> protected function flushExpectations() <add> { <add> $this->test->expectedOutput = []; <add> $this->test->unexpectedOutput = []; <add> $this->test->expectedTables = []; <add> $this->test->expectedQuestions = []; <add> $this->test->expectedChoices = []; <add> } <add> <ide> /** <ide> * Handle the object's destruction. <ide> *
2
Javascript
Javascript
remove unnecessary wrapping of jqlite element
4daafd3dbe6a80d578f5a31df1bb99c77559543e
<ide><path>src/Angular.js <ide> function baseExtend(dst, objs, deep) { <ide> } else if (src.nodeName) { <ide> dst[key] = src.cloneNode(true); <ide> } else if (isElement(src)) { <del> dst[key] = jqLite(src).clone(); <add> dst[key] = src.clone(); <ide> } else { <ide> if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {}; <ide> baseExtend(dst[key], [src], true); <ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> <ide> <ide> it('should copy(clone) elements', function() { <del> var src = { element: document.createElement('div'), <del> jqObject: jqLite("<p><span>s1</span><span>s2</span></p>").find("span") }; <add> var src = { <add> element: document.createElement('div'), <add> jqObject: jqLite('<p><span>s1</span><span>s2</span></p>').find('span') <add> }; <ide> var dst = {}; <ide> <ide> merge(dst, src); <ide> describe('angular', function() { <ide> expect(isElement(dst.element)).toBeTruthy(); <ide> expect(dst.element.nodeName).toBeDefined(); // i.e it is a DOM element <ide> expect(isElement(dst.jqObject)).toBeTruthy(); <del> expect(dst.jqObject.nodeName).toBeUndefined(dst.jqObject); // i.e it is a jqLite/jquery object <add> expect(dst.jqObject.nodeName).toBeUndefined(); // i.e it is a jqLite/jQuery object <ide> }); <ide> }); <ide>
2
PHP
PHP
add union with limit and offset test for postgres
06d37a4ee79da306d30f7daa89a612a3f859b34a
<ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testUnionLimitsAndOffsets() <ide> $builder->union($this->getBuilder()->select('*')->from('dogs')); <ide> $builder->skip(5)->take(10); <ide> $this->assertEquals('select * from "users" union select * from "dogs" limit 10 offset 5', $builder->toSql()); <add> <add> $expectedSql = '(select * from "users") union (select * from "dogs") limit 10 offset 5'; <add> $builder = $this->getPostgresBuilder(); <add> $builder->select('*')->from('users'); <add> $builder->union($this->getBuilder()->select('*')->from('dogs')); <add> $builder->skip(5)->take(10); <add> $this->assertEquals($expectedSql, $builder->toSql()); <add> <add> $expectedSql = '(select * from "users" limit 11) union (select * from "dogs" limit 22) limit 10 offset 5'; <add> $builder = $this->getPostgresBuilder(); <add> $builder->select('*')->from('users')->limit(11); <add> $builder->union($this->getBuilder()->select('*')->from('dogs')->limit(22)); <add> $builder->skip(5)->take(10); <add> $this->assertEquals($expectedSql, $builder->toSql()); <ide> } <ide> <ide> public function testUnionWithJoin()
1
Javascript
Javascript
fix missing return in example
354e1cb5088a43fd4116504a34a65ca53c4de71b
<ide><path>Libraries/Text/Text.js <ide> const viewConfig = { <ide> * ```javascript <ide> * class MyAppHeaderText extends Component { <ide> * render() { <del> * <MyAppText> <del> * <Text style={{fontSize: 20}}> <del> * {this.props.children} <del> * </Text> <del> * </MyAppText> <add> * return ( <add> * <MyAppText> <add> * <Text style={{fontSize: 20}}> <add> * {this.props.children} <add> * </Text> <add> * </MyAppText> <add> * ); <ide> * } <ide> * } <ide> * ```
1
Javascript
Javascript
add spanish translation of comments
bd7bf6971f7bd0460211f9c2173b1c39da090687
<ide><path>curriculum/dictionaries/espanol/comments.js <add>/* eslint-disable max-len */ <add>// NOTE: updates to translations will not appear until the client is restarted <add>// i.e. close it and run npm run develop <add> <add>// Only translate the text that is not surround by single backticks <add>const TRANSLATIONS = [ <add> { <add> id: 'hyek8f', <add> text: '24.44 en Celsius' <add> }, <add> { <add> id: 'rscjup', <add> text: '26 en Celsius' <add> }, <add> { <add> id: 'am2xch', <add> text: 'Una lista de cadenas de texto representando tareas por hacer:' <add> }, <add> { <add> id: '6rztdg', <add> text: 'Agrega un registro aquí' <add> }, <add> { <add> id: 'to1vwe', <add> text: 'Agrega los métodos handleChange() y submitMessage() aquí' <add> }, <add> { <add> id: '31b7ey', <add> text: 'Agrega tu código encima de esta línea' <add> }, <add> { <add> id: 'c24by8', <add> text: 'Agrega tu código debajo de esta línea' <add> }, <add> { <add> id: 'jbrt8k', <add> text: 'Agrega la fila número m a newArray' <add> }, <add> { <add> id: 'zkh12d', <add> text: <add> 'Después de pasar el desafío experimenta con myString y observa cómo funciona la agrupación' <add> }, <add> { <add> id: 'mobihi', <add> text: 'Asigna 5 a oopsGlobal aquí' <add> }, <add> { <add> id: 'v3ups9', <add> text: 'Llama scale con un argumento aquí' <add> }, <add> { <add> id: 'iw4a3a', <add> text: 'Caso 1: El objetivo no tiene hijo' <add> }, <add> { <add> id: '463xp8', <add> text: 'Caso 2: El objetivo tiene un hijo' <add> }, <add> { <add> id: 'u3inrm', <add> text: 'caso 3: El objetivo tiene dos hijos' <add> }, <add> { <add> id: 'axnbgg', <add> text: 'Cambia el código encima de esta línea' <add> }, <add> { <add> id: 'i2kck7', <add> text: 'Cambia el código debajo de esta línea' <add> }, <add> { <add> id: 'dlbobn', <add> text: 'Cambia esta línea' <add> }, <add> { <add> id: 'v127zb', <add> text: <add> 'Verifica las dos consolas para ver la diferencia. La consola de freeCodeCamp debería haber impreso la variable dos veces, una por cada prueba de este desafío. La consola del navegador solo debería imprimir la variable una vez dado que la limpiaste primero.' <add> }, <add> { <add> id: 'ejm0ql', <add> text: 'Cierra la tercera pestaña en videoWindow y une' <add> }, <add> { <add> id: 'iwch6t', <add> text: 'Completa el método de abajo e implementa los otros de manera similar' <add> }, <add> { <add> id: 'hihhyz', <add> text: 'Completa la sentencia return:' <add> }, <add> { <add> id: 'sdxti5', <add> text: 'Cuenta los hijos del objetivo a eliminar' <add> }, <add> { <add> id: 'wfw6sc', <add> text: 'Crea una escala de X y Y' <add> }, <add> { <add> id: 'sjw6f4', <add> text: 'Crea la escala aquí' <add> }, <add> { <add> id: 'nupsh2', <add> text: 'Crea un arreglo de 2 dimensiones con m filas y n columnas de ceros' <add> }, <add> { <add> id: 'xfjb3s', <add> text: 'Declara la variable myGlobal debajo de esta línea' <add> }, <add> { <add> id: 'htpjk7', <add> text: 'Define una constante para acciones de decremento' <add> }, <add> { <add> id: 'tfzdsp', <add> text: 'Define una constante para acciones de incremento' <add> }, <add> { <add> id: 'zh20mi', <add> text: 'Define ADD, addMessage(), messageReducer(), y store aquí:' <add> }, <add> { <add> id: '43qs4c', <add> text: 'Define un creador de acción para decrementar' <add> }, <add> { <add> id: 'nen3qo', <add> text: 'Define un creador de acción para incrementar' <add> }, <add> { <add> id: '0cwyam', <add> text: 'Define un creador de acción aquí:' <add> }, <add> { <add> id: 'fq0wsg', <add> text: 'Define una acción aquí:' <add> }, <add> { <add> id: 'tegkqa', <add> text: 'Define el componente Container aquí:' <add> }, <add> { <add> id: 'b5oihn', <add> text: <add> 'Define el reductor counter que aumentará o disminuirá el estado en función de la acción que reciba' <add> }, <add> { <add> id: '91y4pd', <add> text: 'Define el store de Redux aquí, pasando tus reductores' <add> }, <add> { <add> id: 'eie1vk', <add> text: 'Define el reductor root aquí' <add> }, <add> { <add> id: '5s7nnl', <add> text: 'Define el store aquí:' <add> }, <add> { <add> id: '34qe2q', <add> text: 'El diccionario almacenará elementos de nuestro conjunto' <add> }, <add> { <add> id: '2c1wra', <add> text: 'Despacha la acción received data aquí' <add> }, <add> { <add> id: '923cpg', <add> text: 'Despacha la acción request aquí' <add> }, <add> { <add> id: 'picsyf', <add> text: 'Despacha la acción aquí:' <add> }, <add> { <add> id: 'ysjr1s', <add> text: 'Muestra el código' <add> }, <add> { <add> id: 'kjd1am', <add> text: 'No mutes el estado aquí o la prueba fallará' <add> }, <add> { <add> id: '5tx4ow', <add> text: 'Sitios de entretenimiento' <add> }, <add> { <add> id: '9yu58b', <add> text: 'Ejemplo listas de inventario' <add> }, <add> { <add> id: 'ciddtb', <add> text: 'Encuentra el valor del objetivo y su padre' <add> }, <add> { <add> id: 'ixx548', <add> text: 'Arregla el código de abajo para que evalúe a true' <add> }, <add> { <add> id: '6mbhjj', <add> text: 'Por ejemplo: Redux.createStore()' <add> }, <add> { <add> id: 'jshtzq', <add> text: <add> 'Función que retorna una cadena de texto representando una taza de té negro' <add> }, <add> { <add> id: 'cw1ghf', <add> text: <add> 'Función que retorna una cadena de texto representando una taza de té verde' <add> }, <add> { <add> id: 'iuccln', <add> text: 'Genera un arreglo lleno al azar' <add> }, <add> { <add> id: 'bm2mop', <add> text: 'Obtiene las pestañas después de la pestaña' <add> }, <add> { <add> id: 'kchz5k', <add> text: 'Obtiene las pestañas antes de la pestaña' <add> }, <add> { <add> id: 'bfd23c', <add> text: `Dada una función (representando el tipo de té) y el número de tazas necesarias, la <add> siguiente función retorna un arreglo de cadenas de texto (cada una representando un tipo específico de té).` <add> }, <add> { <add> id: 'ead98i', <add> text: 'Variable global count:' <add> }, <add> { <add> id: '7zf0i2', <add> text: 'Únelos juntos' <add> }, <add> { <add> id: '5j2l88', <add> text: 'Vamos a crear tres ventanas del navegador' <add> }, <add> { <add> id: 'e843r9', <add> text: 'Abramos una nueva pestaña por ahora' <add> }, <add> { <add> id: '5fvehh', <add> text: 'myVar no está definida afuera de myLocalScope' <add> }, <add> { <add> id: 'qn720a', <add> text: <add> 'Ahora, agrega console.clear() antes de tu console.log() para limpiar la consola del navegador y pasar la prueba' <add> }, <add> { <add> id: 'j86mef', <add> text: <add> 'Ahora completa la apertura de la pestaña, cierre, y otras operaciones' <add> }, <add> { <add> id: 'mk7rvy', <add> text: 'Ahora remueve la línea del console log para pasar la prueba' <add> }, <add> { <add> id: 'n7vm1s', <add> text: 'Cambia solo el código encima de esta línea' <add> }, <add> { <add> id: 'cvh4x7', <add> text: 'Cambia solo el código debajo de esta línea' <add> }, <add> { <add> id: 'lvmnm7', <add> text: 'Abre una nueva pestaña para memes de gatos' <add> }, <add> { <add> id: 'avpx79', <add> text: 'Abre la consola de tu navegador.' <add> }, <add> { <add> id: '0b5ps6', <add> text: 'Relleno entre el límite del canvas SVG y el gráfico' <add> }, <add> { <add> id: 'uemoej', <add> text: 'Inserta n ceros a la fila actual para crear las columnas' <add> }, <add> { <add> id: 'lm86nf', <add> text: 'Inserta la fila actual, que ahora contiene n ceros, al arreglo' <add> }, <add> { <add> id: 'qscelx', <add> text: 'Los métodos Redux están disponibles desde un objeto Redux' <add> }, <add> { <add> id: 'atqiig', <add> text: 'Renderiza un input, button, y ul debajo de esta línea' <add> }, <add> { <add> id: 'yq81wg', <add> text: 'Renderiza el Provider debajo de esta línea' <add> }, <add> { <add> id: 'kxio9j', <add> text: <add> 'responseFromServer es establecido a false para representar una respuesta no satisfactoria del servidor' <add> }, <add> { <add> id: 'alh6pw', <add> text: <add> 'responseFromServer es establecido a true para representar una respuesta satisfactoria del servidor' <add> }, <add> { <add> id: '1cfidd', <add> text: 'responseFromServer representa una respuesta de un servidor' <add> }, <add> { <add> id: '96tntk', <add> text: 'Retorna 30' <add> }, <add> { <add> id: '58a5g7', <add> text: 'Ejecuta y verifica la consola' <add> }, <add> { <add> id: '71bus9', <add> text: 'Ejecuta las pruebas para ver la diferencia entre las dos consolas.' <add> }, <add> { <add> id: '7wp46n', <add> text: 'Ajuste en escala Farenheit' <add> }, <add> { <add> id: 'oefvg5', <add> text: 'Configuración' <add> }, <add> { <add> id: 'mnt4d3', <add> text: "Debería mostrar 'carrot'" <add> }, <add> { <add> id: 'fhe9m4', <add> text: 'Sitios sociales' <add> }, <add> { <add> id: 'za434b', <add> text: 'La tabla de barras apiladas de entrenamiento semanal' <add> }, <add> { <add> id: '7c1fv9', <add> text: 'La tabla de barras apiladas irá aquí' <add> }, <add> { <add> id: 'r44ovx', <add> text: <add> 'tabs es un arreglo de títulos de cada sítio abierto dentro de la ventana' <add> }, <add> { <add> id: 'cl8peb', <add> text: 'arreglo de prueba:' <add> }, <add> { <add> id: '1xi3cv', <add> text: 'La variable global' <add> }, <add> { <add> id: '3gc01a', <add> text: 'El archivo main.scss' <add> }, <add> { <add> id: '14kfog', <add> text: 'Este es nuestro método de intersección' <add> }, <add> { <add> id: 'd1shtt', <add> text: 'Este es nuestro método de unión' <add> }, <add> { <add> id: 'pqq6sy', <add> text: 'Este método agregará un elemento al conjunto' <add> }, <add> { <add> id: 'nd2oxy', <add> text: <add> 'Este método verificará la existencia de un elemento y retornará true o false' <add> }, <add> { <add> id: 'ocm81t', <add> text: 'Este método removerá un elemento del conjunto' <add> }, <add> { <add> id: 'or9p5p', <add> text: 'Este método retornará todos los valores del conjunto' <add> }, <add> { <add> id: 'g1608f', <add> text: 'Este método retornará el tamaño del conjunto' <add> }, <add> { <add> id: 'bheu99', <add> text: 'Esto almacenará el conjunto' <add> }, <add> { <add> id: 'x1djjr', <add> text: <add> 'Usa console.clear() en la siguiente línea para limpiar la consola del navegador.' <add> }, <add> { <add> id: '22ta95', <add> text: 'Usa console.log() para imprimir la variable output.' <add> }, <add> { <add> id: 'w43c7l', <add> text: 'Usar s = [2, 5, 7] sería inválido' <add> }, <add> { <add> id: 'pgckoj', <add> text: 'Asignación de variables' <add> }, <add> { <add> id: '2xiqvv', <add> text: 'Declaración de variables' <add> }, <add> { <add> id: '2sx8zg', <add> text: 'Mantenemos un registro del arreglo dentro del objeto' <add> }, <add> { <add> id: 'xmjfd8', <add> text: 'Cuando cierras una pestaña' <add> }, <add> { <add> id: 'es69h6', <add> text: 'Cuando unes dos ventanas en una' <add> }, <add> { <add> id: 'fho5t5', <add> text: 'Cuando abres una nueva pestaña al final' <add> }, <add> { <add> id: '00kcrm', <add> text: 'produce true' <add> }, <add> { <add> id: 'sxpg2a', <add> text: 'Tu casilla de correo, drive y otros sitios de trabajo' <add> } <add>]; <add> <add>module.exports = TRANSLATIONS;
1
Ruby
Ruby
remove duplicated code in `type_to_sql`
ab9cb600769acc6007521930857efd5699420f8d
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # <ide> when 5..8; "bigint" <ide> else raise ArgumentError, "No integer type has byte size #{limit}. Use a numeric with scale 0 instead." <ide> end <del> when "interval" <del> case precision <del> when nil; "interval" <del> when 0..6; "interval(#{precision})" <del> else raise(ActiveRecordError, "No interval type has precision of #{precision}. The allowed range of precision is from 0 to 6") <del> end <ide> else <ide> super <ide> end
1
Javascript
Javascript
remove an unnecessary space
99a7cb9fdff3c4968ccd4c78d00bc7f5cac5f333
<ide><path>src/textures/Texture.js <ide> Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), { <ide> width: mipmap.width, <ide> height: mipmap.height, <ide> type: mipmap.data.constructor.name, <del> array: Array.prototype.slice.call( mipmap.data ) <add> array: Array.prototype.slice.call( mipmap.data ) <ide> } ); <ide> <ide> } else {
1
Python
Python
add volume methods in packet compute driver
1a6a1c5f5ccf8575be066d5db1f2d5c4d155f18d
<ide><path>libcloud/compute/drivers/packet.py <ide> """ <ide> Packet Driver <ide> """ <del>try: <add>try: # Try to use asyncio to perform requests in parallel across projects <ide> import asyncio <del>except ImportError: <add>except ImportError: # If not available will do things serially <ide> asyncio = None <ide> <add>import dateutil.parser <add> <ide> from libcloud.utils.py3 import httplib <ide> <ide> from libcloud.common.base import ConnectionKey, JsonResponse <ide> from libcloud.compute.types import Provider, NodeState, InvalidCredsError <ide> from libcloud.compute.base import NodeDriver, Node <ide> from libcloud.compute.base import NodeImage, NodeSize, NodeLocation <ide> from libcloud.compute.base import KeyPair <add>from libcloud.compute.base import StorageVolume, VolumeSnapshot <ide> <ide> PACKET_ENDPOINT = "api.packet.net" <ide> <ide> def ex_list_projects(self): <ide> def list_nodes(self, ex_project_id=None): <ide> if ex_project_id: <ide> return self.list_nodes_for_project(ex_project_id=ex_project_id) <del> else: <del> # if project has been specified during driver initialization, then <del> # return nodes for this project only <del> if self.project_id: <del> return self.list_nodes_for_project( <del> ex_project_id=self.project_id) <del> <del> # In case of Python2 perform requests serially <del> if asyncio is None: <del> nodes = [] <del> for project in self.projects: <del> nodes.extend( <del> self.list_nodes_for_project(ex_project_id=project.id) <del> ) <del> return nodes <del> <del> # In case of Python3 use asyncio to perform requests in parallel <del> # The _list_nodes function is defined dynamically using exec in <del> # order to prevent a SyntaxError in Python2 due to "yield from". <del> # This cruft can be removed once Python2 support is no longer <del> # required. <del> glob = globals() <del> loc = locals() <del> exec(""" <add> <add> # if project has been specified during driver initialization, then <add> # return nodes for this project only <add> if self.project_id: <add> return self.list_nodes_for_project( <add> ex_project_id=self.project_id) <add> <add> # In case of Python2 perform requests serially <add> if asyncio is None: <add> nodes = [] <add> for project in self.projects: <add> nodes.extend( <add> self.list_nodes_for_project(ex_project_id=project.id) <add> ) <add> return nodes <add> # In case of Python3 use asyncio to perform requests in parallel <add> return self.list_resources_async('nodes') <add> <add> def list_resources_async(self, resource_type): <add> # The _list_nodes function is defined dynamically using exec in <add> # order to prevent a SyntaxError in Python2 due to "yield from". <add> # This cruft can be removed once Python2 support is no longer <add> # required. <add> assert resource_type in ['nodes', 'volumes'] <add> glob = globals() <add> loc = locals() <add> exec(""" <ide> import asyncio <ide> @asyncio.coroutine <del>def _list_nodes(driver): <add>def _list_async(driver): <ide> projects = [project.id for project in driver.projects] <ide> loop = asyncio.get_event_loop() <ide> futures = [ <del> loop.run_in_executor(None, driver.list_nodes_for_project, p) <add> loop.run_in_executor(None, driver.list_%s_for_project, p) <ide> for p in projects <ide> ] <del> nodes = [] <add> retval = [] <ide> for future in futures: <ide> result = yield from future <del> nodes.extend(result) <del> return nodes""", glob, loc) <del> loop = asyncio.get_event_loop() <del> nodes = loop.run_until_complete(loc['_list_nodes'](loc['self'])) <del> return nodes <add> retval.extend(result) <add> return retval""" % resource_type, glob, loc) <add> loop = asyncio.get_event_loop() <add> return loop.run_until_complete(loc['_list_async'](loc['self'])) <ide> <ide> def list_nodes_for_project(self, ex_project_id, include='plan', page=1, <ide> per_page=1000): <ide> def ex_disassociate_address(self, address_uuid, include=None): <ide> path, params=params, method='DELETE').object <ide> return result <ide> <add> def list_volumes(self, ex_project_id=None): <add> if ex_project_id: <add> return self.list_volumes_for_project(ex_project_id=ex_project_id) <add> <add> # if project has been specified during driver initialization, then <add> # return nodes for this project only <add> if self.project_id: <add> return self.list_volumes_for_project( <add> ex_project_id=self.project_id) <add> <add> # In case of Python2 perform requests serially <add> if asyncio is None: <add> nodes = [] <add> for project in self.projects: <add> nodes.extend( <add> self.list_volumes_for_project(ex_project_id=project.id) <add> ) <add> return nodes <add> # In case of Python3 use asyncio to perform requests in parallel <add> return self.list_resources_async('volumes') <add> <add> def list_volumes_for_project(self, ex_project_id, include='plan', page=1, <add> per_page=1000): <add> params = { <add> 'include': include, <add> 'page': page, <add> 'per_page': per_page <add> } <add> data = self.connection.request( <add> '/projects/%s/storage' % (ex_project_id), <add> params=params).object['volumes'] <add> return list(map(self._to_volume, data)) <add> <add> def _to_volume(self, data): <add> return StorageVolume(id=data['id'], name=data['name'], <add> size=data['size'], driver=self, <add> extra=data) <add> <add> def create_volume(self, size, location, plan='storage_1', description='', <add> ex_project_id=None, locked=False, billing_cycle=None, <add> customdata='', snapshot_policies=None): <add> """ <add> Create a new volume. <add> <add> :param size: Size of volume in gigabytes (required) <add> :type size: ``int`` <add> <add> :param name: Name of the volume to be created <add> :type name: ``str`` <add> <add> :param location: Which data center to create a volume in. If <add> empty, undefined behavior will be selected. <add> (optional) <add> :type location: :class:`.NodeLocation` <add> :return: The newly created volume. <add> :rtype: :class:`StorageVolume` <add> """ <add> path = '/projects/%s/storage' % (ex_project_id or self.projects[0].id) <add> params = { <add> 'facility': location.id, <add> 'plan': plan, <add> 'size': size, <add> 'locked': locked <add> } <add> if description: <add> params['description'] = description <add> if customdata: <add> params['customdata'] = customdata <add> if billing_cycle: <add> params['billing_cycle'] = billing_cycle <add> if snapshot_policies: <add> params['snapshot_policies'] = snapshot_policies <add> data = self.connection.request(path, params=params, method='POST').object <add> return self._to_volume(data) <add> <add> def destroy_volume(self, volume): <add> """ <add> Destroys a storage volume. <add> <add> :param volume: Volume to be destroyed <add> :type volume: :class:`StorageVolume` <add> <add> :rtype: ``bool`` <add> """ <add> path = '/storage/%s' % volume.id <add> res = self.connection.request(path, method='DELETE') <add> return res.status == httplib.NO_CONTENT <add> <add> def create_volume_snapshot(self, volume, name=''): <add> """ <add> Create a new volume snapshot. <add> <add> :param volume: Volume to create a snapshot for <add> :type volume: class:`StorageVolume` <add> <add> :return: The newly created volume snapshot. <add> :rtype: :class:`VolumeSnapshot` <add> """ <add> path = '/storage/%s/snapshots' % volume.id <add> res = self.connection.request(path, method='POST') <add> assert res.status == httplib.ACCEPTED <add> return volume.list_snapshots()[-1] <add> <add> def destroy_volume_snapshot(self, snapshot): <add> """ <add> Delete a volume snapshot <add> <add> :param snapshot: volume snapshot to delete <add> :type snapshot: class:`VolumeSnapshot` <add> <add> :rtype: ``bool`` <add> """ <add> volume_id = snapshot.extra['volume']['href'].split('/')[-1] <add> path = '/storage/%s/snapshots/%s' % (volume_id, snapshot.id) <add> res = self.connection.request(path, method='DELETE') <add> return res.status == httplib.NO_CONTENT <add> <add> def list_volume_snapshots(self, volume, include=''): <add> """ <add> List snapshots for a volume. <add> <add> :param volume: Volume to list snapshots for <add> :type volume: class:`StorageVolume` <add> <add> :return: List of volume snapshots. <add> :rtype: ``list`` of :class: `VolumeSnapshot` <add> """ <add> path = '/storage/%s/snapshots' % volume.id <add> params = {} <add> if include: <add> params['include'] = include <add> data = self.connection.request(path, params=params).object['snapshots'] <add> return list(map(self._to_volume_snapshot, data)) <add> <add> def _to_volume_snapshot(self, data): <add> created = dateutil.parser.parse(data['created_at']) <add> return VolumeSnapshot(id=data['id'], <add> name=data['id'], <add> created=created, <add> state=data['status'], <add> driver=self, extra=data) <add> <add> def ex_modify_volume(self, volume, description=None, size=None, <add> locked=None, billing_cycle=None, <add> customdata=None): <add> path = '/storage/%s' % volume.id <add> params = {} <add> if description: <add> params['description'] = description <add> if size: <add> params['size'] = size <add> if locked != None: <add> params['locked'] = locked <add> if billing_cycle: <add> params['billing_cycle'] = billing_cycle <add> res = self.connection.request(path, params=params, method='PUT') <add> return self._to_volume(res.object) <add> <add> def ex_restore_volume(self, snapshot): <add> volume_id = snapshot.extra['volume']['href'].split('/')[-1] <add> ts = snapshot.extra['timestamp'] <add> path = '/storage/%s/restore?restore_point=%s' % (volume_id, ts) <add> res = self.connection.request(path, method='POST') <add> return res.status == httplib.NO_CONTENT <add> <add> def ex_clone_volume(self, volume, snapshot=None): <add> path = '/storage/%s/clone' % volume.id <add> if snapshot: <add> path += '?snapshot_timestamp=%s' % snapshot.extra['timestamp'] <add> res = self.connection.request(path, method='POST') <add> return res.status == httplib.NO_CONTENT <add> <add> def ex_describe_volume(self, volume_id): <add> path = '/storage/%s' % volume_id <add> data = self.connection.request(path).object <add> return self._to_volume(data) <ide> <ide> class Project(object): <ide> def __init__(self, project):
1
Text
Text
add a bit about contributing to the guide
9fcac1ab1cb48c50fdd21914678c632a568b2340
<ide><path>docs/upgrading/upgrading-your-package.md <ide> atom.workspaceView.command 'core:close core:cancel', -> <ide> <ide> Many selectors have changed, and we have introduced the [Shadow DOM][shadowdom] to the editor. See [Upgrading Your Package Selectors guide][upgrading-selectors] for more information in upgrading your package stylesheets. <ide> <add>## Help us improve this guide! <add> <add>Did you hit something painful that wasn't in here? Want to reword some bit of it? Find something incorrect? Please edit [this file][guide], and send a pull request. Contributions are greatly appreciated. <add> <add> <add> <add> <ide> [texteditorview]:https://github.com/atom/atom-space-pen-views#texteditorview <ide> [scrollview]:https://github.com/atom/atom-space-pen-views#scrollview <ide> [selectlistview]:https://github.com/atom/atom-space-pen-views#selectlistview <ide> Many selectors have changed, and we have introduced the [Shadow DOM][shadowdom] <ide> [commands-add]:https://atom.io/docs/api/latest/CommandRegistry#instance-add <ide> [upgrading-selectors]:upgrading-your-ui-theme <ide> [shadowdom]:http://blog.atom.io/2014/11/18/avoiding-style-pollution-with-the-shadow-dom.html <add>[guide]:https://github.com/atom/atom/blob/master/docs/upgrading/upgrading-your-package.md
1
Text
Text
translate ref 04 to korean
ade720d4d9ffb44afb9d0a245fbc37a5b6fdb61f
<ide><path>docs/docs/ref-04-tags-and-attributes.ko-KR.md <add>--- <add>id: tags-and-attributes-ko-KR <add>title: 태그와 어트리뷰트 <add>permalink: tags-and-attributes.ko-KR.html <add>prev: component-specs.ko-KR.html <add>next: events.ko-KR.html <add>--- <add> <add>## 지원되는 태그 <add> <add>React는 모든 공통 엘리먼트를 지원하려 합니다. 필요한 엘리먼트가 리스트에 없다면, 이슈로 등록해 주세요. <add> <add>### HTML 엘리먼트 <add> <add>이런 HTML 엘리먼트가 지원됩니다. <add> <add>``` <add>a abbr address area article aside audio b base bdi bdo big blockquote body br <add>button canvas caption cite code col colgroup data datalist dd del details dfn <add>dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 <add>h6 head header hr html i iframe img input ins kbd keygen label legend li link <add>main map mark menu menuitem meta meter nav noscript object ol optgroup option <add>output p param picture pre progress q rp rt ruby s samp script section select <add>small source span strong style sub summary sup table tbody td textarea tfoot th <add>thead time title tr track u ul var video wbr <add>``` <add> <add>### SVG 엘리먼트 <add> <add>이런 SVG 엘리먼트가 지원됩니다. <add> <add>``` <add>circle defs ellipse g line linearGradient mask path pattern polygon polyline <add>radialGradient rect stop svg text tspan <add>``` <add> <add>아마 Canvas, SVG, VML(IE8 전용)에 렌더할 때 쓰는 React의 드로잉 라이브러리인 [react-art](https://github.com/facebook/react-art)도 흥미 있으실 수 있습니다. <add> <add> <add>## 지원되는 어트리뷰트 <add> <add>React는 모든 `data-*`, `aria-*` 어트리뷰트와 밑에 있는 모든 어트리뷰트를 지원합니다. <add> <add>> 주의: <add>> <add>> 모든 어트리뷰트는 카멜케이스이고, `class` `for` 어트리뷰트는 각각 DOM API의 사양에 맞춰서 `className` `htmlFor` 가 됩니다. <add> <add>이벤트의 목록을 보시려면 [지원되는 이벤트](/react/docs/events.html)를 확인하세요. <add> <add>### HTML 어트리뷰트 <add> <add>이런 표준 어트리뷰트가 지원됩니다. <add> <add>``` <add>accept acceptCharset accessKey action allowFullScreen allowTransparency alt <add>async autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked classID <add>className cols colSpan content contentEditable contextMenu controls coords <add>crossOrigin data dateTime defer dir disabled download draggable encType form <add>formAction formEncType formMethod formNoValidate formTarget frameBorder height <add>hidden href hrefLang htmlFor httpEquiv icon id label lang list loop manifest <add>marginHeight marginWidth max maxLength media mediaGroup method min multiple <add>muted name noValidate open pattern placeholder poster preload radioGroup <add>readOnly rel required role rows rowSpan sandbox scope scrolling seamless <add>selected shape size sizes span spellCheck src srcDoc srcSet start step style <add>tabIndex target title type useMap value width wmode <add>``` <add> <add>덧붙여, 이런 비표준 어트리뷰트도 지원됩니다. <add> <add>- 모바일 사파리를 위한 `autoCapitalize autoCorrect`. <add>- [오픈 그래프](http://ogp.me/) 메타 태그를 위한 `property`. <add>- [HTML5 마이크로데이터](http://schema.org/docs/gs.html)를 위한 `itemProp itemScope itemType itemRef itemId`. <add> <add>컴포넌트에 직접 HTML 스트링을 넣을 때 사용하는, React 전용 어트리뷰트 `dangerouslySetInnerHTML`([자세한 정보는 여기](/react/docs/special-non-dom-attributes.html))도 있습니다. <add> <add>### SVG 어트리뷰트 <add> <add>``` <add>cx cy d dx dy fill fillOpacity fontFamily fontSize fx fy gradientTransform <add>gradientUnits markerEnd markerMid markerStart offset opacity <add>patternContentUnits patternUnits points preserveAspectRatio r rx ry <add>spreadMethod stopColor stopOpacity stroke strokeDasharray strokeLinecap <add>strokeOpacity strokeWidth textAnchor transform version viewBox x1 x2 x y1 y2 y <add>```
1
Javascript
Javascript
fix another regression on pdf.pdf#5
8145c00215f9d0c8c5b81fcd069961bf32d6b98b
<ide><path>fonts.js <ide> var Font = (function Font() { <ide> <ide> // Wrap the CFF data inside an OTF font file <ide> data = this.convert(name, cff, properties); <del> writeToFile(data, "/tmp/" + name + ".otf"); <ide> break; <ide> <ide> case 'TrueType': <ide> var Type2CFF = (function() { <ide> <ide> var charstrings = []; <ide> var differences = properties.differences; <del> var index = 1; <add> var index = 0; <ide> var kCmapGlyphOffset = 0xE000; <ide> for (var i = 1; i < charsets.length; i++) { <ide> var glyph = charsets[i]; <ide> var Type2CFF = (function() { <ide> } <ide> <ide> var code = differences.indexOf(glyph); <add> if (code == -1) <add> code = properties.glyphs[glyph] || index; <add> <ide> var width = widths[code] || defaultWidth; <ide> properties.encoding[index] = index + kCmapGlyphOffset; <ide> charstrings.push({unicode: code + kCmapGlyphOffset, width: width, gid: i});
1
Text
Text
correct typos in make an rpg
ec5b25ee1a5b09849503f76932102e973e6d1776
<ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a3b49686792938718b90d3.md <ide> dashedName: step-26 <ide> <ide> # --description-- <ide> <del>The variables you have assigned have all had values that are numbers. JavaScript has multiple different data types. The next one you will be use is the <dfn>string</dfn>. Strings are used to store things like words or text. Strings are surrounded with double quotes, single quotes, or backticks. Here is an example of declaring a variable with a string: <add>The variables you have assigned have all had values that are numbers. JavaScript has multiple different data types. The next one you will use is the <dfn>string</dfn>. Strings are used to store things like words or text. Strings are surrounded with double quotes, single quotes, or backticks. Here is an example of declaring a variable with a string: <ide> <ide> ```js <ide> let developer = "Naomi"; <ide><path>curriculum/challenges/english/15-javascript-algorithms-and-data-structures-22/learn-basic-javascript-by-building-a-role-playing-game/62a7bfabe119461eb13ccbd6.md <ide> Now you need to modify your display text. Change the `innerText` of the `text` t <ide> <ide> # --hints-- <ide> <del>You should use dot notation to access the `innerText` propertry of `text`. <add>You should use dot notation to access the `innerText` property of `text`. <ide> <ide> ```js <ide> assert.match(code, /text\.innerText/);
2
Go
Go
add exported status code from a job
f90029611fec082a41b5629e43a88a39f0674fe2
<ide><path>engine/job.go <ide> func (job *Job) Error(err error) Status { <ide> fmt.Fprintf(job.Stderr, "%s\n", err) <ide> return StatusErr <ide> } <add> <add>func (job *Job) StatusCode() int { <add> return int(job.status) <add>}
1
Python
Python
fix serialization during training
0a9016cadeb93b33deb711764177127c5f187a09
<ide><path>spacy/cli/train.py <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0, <ide> util.set_env_log(False) <ide> epoch_model_path = output_path / ('model%d' % i) <ide> nlp.to_disk(epoch_model_path) <del> #nlp_loaded = lang_class(pipeline=pipeline) <del> #nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <add> nlp_loaded = lang_class(pipeline=pipeline) <add> nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <ide> scorer = nlp.evaluate( <ide> corpus.dev_docs( <ide> nlp,
1
PHP
PHP
fix incorrect return type
7c1f079ce047b83cdee0787bea86468262a0f22d
<ide><path>src/Illuminate/Cache/RedisStore.php <ide> public function tags($names) <ide> /** <ide> * Get the Redis connection instance. <ide> * <del> * @return \Predis\ClientInterface <add> * @return \Illuminate\Redis\Connections\Connection <ide> */ <ide> public function connection() <ide> {
1
Javascript
Javascript
support a matching function for data param
08daa7797bce5207916251d4a0ab3d5c93e5529a
<ide><path>src/ngMock/angular-mocks.js <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * <ide> * @param {string} method HTTP method. <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header <ide> * object and returns true if the headers match the current definition. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * Creates a new backend definition for POST requests. For more info see `when()`. <ide> * <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {(Object|function(Object))=} headers HTTP headers. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> * request is handled. <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * Creates a new backend definition for PUT requests. For more info see `when()`. <ide> * <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {(Object|function(Object))=} headers HTTP headers. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> * request is handled. <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * <ide> * @param {string} method HTTP method. <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header <ide> * object and returns true if the headers match the current expectation. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * Creates a new request expectation for POST requests. For more info see `expect()`. <ide> * <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {Object=} headers HTTP headers. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> * request is handled. <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * Creates a new request expectation for PUT requests. For more info see `expect()`. <ide> * <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {Object=} headers HTTP headers. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> * request is handled. <ide> function createHttpBackendMock($rootScope, $delegate, $browser) { <ide> * Creates a new request expectation for PATCH requests. For more info see `expect()`. <ide> * <ide> * @param {string|RegExp} url HTTP url. <del> * @param {(string|RegExp)=} data HTTP request body. <add> * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives <add> * data string and returns true if the data is as expected. <ide> * @param {Object=} headers HTTP headers. <ide> * @returns {requestHandler} Returns an object with `respond` method that control how a matched <ide> * request is handled. <ide> function MockHttpExpectation(method, url, data, headers) { <ide> this.matchData = function(d) { <ide> if (angular.isUndefined(data)) return true; <ide> if (data && angular.isFunction(data.test)) return data.test(d); <add> if (data && angular.isFunction(data)) return data(d); <ide> if (data && !angular.isString(data)) return angular.toJson(data) == d; <ide> return data == d; <ide> }; <ide><path>test/ngMock/angular-mocksSpec.js <ide> describe('ngMock', function() { <ide> }); <ide> <ide> <add> it('should accept data as function', function() { <add> var dataValidator = function(data) { <add> var json = angular.fromJson(data); <add> return !!json.id && json.status === 'N'; <add> }; <add> var exp = new MockHttpExpectation('POST', '/url', dataValidator); <add> <add> expect(exp.matchData({})).toBe(false); <add> expect(exp.match('POST', '/url', '{"id": "xxx", "status": "N"}')).toBe(true); <add> expect(exp.match('POST', '/url', {"id": "xxx", "status": "N"})).toBe(true); <add> }); <add> <add> <ide> it('should ignore data only if undefined (not null or false)', function() { <ide> var exp = new MockHttpExpectation('POST', '/url', null); <ide> expect(exp.matchData(null)).toBe(true);
2
Go
Go
remove unused authconfig from session
541ed077a66894c96f22eb1f1a74a504fa014567
<ide><path>registry/service.go <ide> func (s *DefaultService) Search(ctx context.Context, term string, limit int, aut <ide> } <ide> } <ide> <del> r := newSession(client, authConfig, endpoint) <add> r := newSession(client, endpoint) <ide> <ide> if index.Official { <ide> // If pull "library/foo", it's stored locally under "foo" <ide><path>registry/session.go <ide> import ( <ide> type Session struct { <ide> indexEndpoint *V1Endpoint <ide> client *http.Client <del> // TODO(tiborvass): remove authConfig <del> authConfig *types.AuthConfig <del> id string <add> id string <ide> } <ide> <ide> type authTransport struct { <ide> func authorizeClient(client *http.Client, authConfig *types.AuthConfig, endpoint <ide> return nil <ide> } <ide> <del>func newSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) *Session { <add>func newSession(client *http.Client, endpoint *V1Endpoint) *Session { <ide> return &Session{ <del> authConfig: authConfig, <ide> client: client, <ide> indexEndpoint: endpoint, <ide> id: stringid.GenerateRandomID(), <ide> func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1E <ide> return nil, err <ide> } <ide> <del> return newSession(client, authConfig, endpoint), nil <add> return newSession(client, endpoint), nil <ide> } <ide> <ide> // SearchRepositories performs a search against the remote repository
2
Text
Text
fix 3 typos in #explanation
30b8d414218e91fe9c48f2e3a9c5b32a56e61a5d
<ide><path>guide/english/c/hello-world/index.md <ide> To write on console you can use the function `printf()` contained in the library <ide> * The stdio.h file contains functions such as scanf() and printf() to take input and display output respectively. <ide> * If you use printf() function without writing #include <stdio.h>, the program will not be compiled. <ide> * The execution of a C program starts from the main() function. <del> * The printf() is a library function to send formatted output to the screen. In this program, the printf() displays Hello, World! text on the screen. <add> * The printf() is a library function to send formatted output to the screen. In this program, the printf() displays `Hello, World!` text on the screen. <ide> * The \n in printf creates a new line for the forthcoming text. <ide> * The return 0; statement is the "Exit status" of the program. In simple terms, program ends with this statement <ide>
1
Javascript
Javascript
fix trailing build issues
34c4474472d6877f970c3763de4769d2b98718ab
<ide><path>grunt/config/browserify.js <ide> var SECRET_INTERNALS_NAME = 'React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_ <ide> var shimSharedModules = globalShim.configure({ <ide> './ReactCurrentOwner': SECRET_INTERNALS_NAME + '.ReactCurrentOwner', <ide> './ReactComponentTreeHook': SECRET_INTERNALS_NAME + '.ReactComponentTreeHook', <del> // All these methods are shared are exposed. <add> // The methods we used here are exposed on the main React export. <add> // TODO: Change all renderer code to require the isomorphic React directly <add> // instead of these internals. <ide> './ReactElement': 'React', <ide> './ReactPropTypes': 'React.PropTypes', <ide> './ReactChildren': 'React.Children', <ide> }); <ide> <ide> var shimDOMModules = aliasify.configure({ <ide> 'aliases': { <del> './ReactAddonsDOMDependencies': './build/modules/ReactAddonsDOMDependenciesUMDShim.js', <add> './ReactAddonsDOMDependencies': {relative: './ReactAddonsDOMDependenciesUMDShim'}, <ide> }, <ide> }); <ide> <ide><path>src/renderers/dom/client/ReactMount.js <ide> if (__DEV__) { <ide> TopLevelWrapper.prototype.render = function() { <ide> return this.props.child; <ide> }; <add>TopLevelWrapper.isReactTopLevelWrapper = true; <ide> <ide> /** <ide> * Mounting is the process of initializing a React component by creating its <ide><path>src/renderers/shared/stack/reconciler/ReactUpdates.js <ide> function runBatchedUpdates(transaction) { <ide> if (ReactFeatureFlags.logTopLevelRenders) { <ide> var namedComponent = component; <ide> // Duck type TopLevelWrapper. This is probably always true. <del> if ( <del> component._currentElement.props.child === <del> component._renderedComponent._currentElement <del> ) { <add> if (component._currentElement.type.isReactTopLevelWrapper) { <ide> namedComponent = component._renderedComponent; <ide> } <ide> markerName = 'React update: ' + namedComponent.getName();
3
Ruby
Ruby
remove unused argument
cadd9661ad407340a297bd8f1c71a4c02a808f0c
<ide><path>activerecord/lib/active_record/connection_handling.rb <ide> def connected_to(database: nil, role: nil, shard: nil, prevent_writes: false, &b <ide> <ide> with_handler(role, &blk) <ide> elsif shard <del> with_shard(connection_specification_name, shard, role || current_role, prevent_writes, &blk) <add> with_shard(shard, role || current_role, prevent_writes, &blk) <ide> elsif role <ide> with_role(role, prevent_writes, &blk) <ide> else <ide> def with_role(role, prevent_writes, &blk) <ide> end <ide> end <ide> <del> def with_shard(connection_specification_name, pool_key, role, prevent_writes) <add> def with_shard(pool_key, role, prevent_writes) <ide> old_pool_key = current_pool_key <ide> <ide> with_role(role, prevent_writes) do
1
Javascript
Javascript
simplify previousnode boundary calculation
b5714ce1dfca743733e84431161fc888fdcad24a
<ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> key = (collection === collectionKeys) ? index : collectionKeys[index]; <ide> value = collection[key]; <ide> block = nextBlockOrder[index]; <del> if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]); <ide> <ide> if (block.scope) { <ide> // if we have already seen this object, then we need to reuse the <ide> var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { <ide> $transclude(function ngRepeatTransclude(clone, scope) { <ide> block.scope = scope; <ide> // http://jsperf.com/clone-vs-createcomment <del> clone[clone.length++] = ngRepeatEndComment.cloneNode(); <add> var endNode = ngRepeatEndComment.cloneNode(); <add> clone[clone.length++] = endNode; <ide> $animate.enter(clone, null, jqLite(previousNode)); <del> previousNode = clone; <add> previousNode = endNode; <ide> // Note: We only need the first/last node of the cloned nodes. <ide> // However, we need to keep the reference to the jqlite wrapper as it might be changed later <ide> // by a directive with templateUrl when its template arrives.
1
Mixed
Go
add short flag for force
955c35b6a62f26e7ca36fa6378110ce7af8916a4
<ide><path>cli/command/node/remove.go <ide> func newRemoveCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> }, <ide> } <ide> flags := cmd.Flags() <del> flags.BoolVar(&opts.force, "force", false, "Force remove a node from the swarm") <add> flags.BoolVarP(&opts.force, "force", "f", false, "Force remove a node from the swarm") <ide> return cmd <ide> } <ide> <ide><path>cli/command/swarm/leave.go <ide> func newLeaveCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> } <ide> <ide> flags := cmd.Flags() <del> flags.BoolVar(&opts.force, "force", false, "Force this node to leave the swarm, ignoring warnings") <add> flags.BoolVarP(&opts.force, "force", "f", false, "Force this node to leave the swarm, ignoring warnings") <ide> return cmd <ide> } <ide> <ide><path>docs/reference/commandline/node_rm.md <ide> keywords: "node, remove" <ide> # node rm <ide> <ide> ```markdown <del>Usage: docker node rm [OPTIONS] NODE [NODE...] <add>Usage: docker node rm [OPTIONS] NODE [NODE...] <ide> <ide> Remove one or more nodes from the swarm <ide> <ide> Aliases: <ide> rm, remove <ide> <ide> Options: <del> --force Force remove a node from the swarm <del> --help Print usage <add> -f, --force Force remove a node from the swarm <add> --help Print usage <ide> ``` <ide> <ide> When run from a manager node, removes the specified nodes from a swarm. <ide><path>docs/reference/commandline/swarm_leave.md <ide> keywords: "swarm, leave" <ide> # swarm leave <ide> <ide> ```markdown <del>Usage: docker swarm leave [OPTIONS] <add>Usage: docker swarm leave [OPTIONS] <ide> <del>Leave the swarm (workers only). <add>Leave the swarm (workers only) <ide> <ide> Options: <del> --force Force this node to leave the swarm, ignoring warnings <add> -f, --force Force this node to leave the swarm, ignoring warnings <ide> --help Print usage <ide> ``` <ide>
4
Ruby
Ruby
remove unnecessary variable
d274f7a8a0db4eef81d0b754e2b5e1c135fff10b
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def version_for_sha sha <ide> # Unload the class so Formula#version returns the correct value <ide> begin <ide> Object.send(:remove_const, Formula.class_s(name)) <del> version = nostdout { Formula.factory(path).version } <del> version <add> nostdout { Formula.factory(path).version } <ide> rescue SyntaxError, TypeError, NameError, ArgumentError <ide> # We rescue these so that we can skip bad versions and <ide> # continue walking the history
1
Python
Python
fix bart type hints
59a9c83e40f879f5060eff99968dc688a56d0d0d
<ide><path>src/transformers/models/plbart/modeling_plbart.py <ide> import copy <ide> import math <ide> import random <del>from typing import List, Optional, Tuple, Union <add>from typing import Any, Dict, List, Optional, Tuple, Union <ide> <ide> import torch <ide> import torch.utils.checkpoint <ide> def get_decoder(self): <ide> ) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> decoder_input_ids=None, <del> decoder_attention_mask=None, <del> head_mask=None, <del> decoder_head_mask=None, <del> cross_attn_head_mask=None, <del> encoder_outputs=None, <del> past_key_values=None, <del> inputs_embeds=None, <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.LongTensor] = None, <add> decoder_input_ids: Optional[torch.LongTensor] = None, <add> decoder_attention_mask: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> decoder_head_mask: Optional[torch.LongTensor] = None, <add> cross_attn_head_mask: Optional[torch.Tensor] = None, <add> encoder_outputs: Optional[List[torch.FloatTensor]] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <ide> decoder_inputs_embeds=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <ide> ): <ide> output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions <ide> output_hidden_states = ( <ide> def set_output_embeddings(self, new_embeddings): <ide> @add_end_docstrings(PLBART_GENERATION_EXAMPLE) <ide> def forward( <ide> self, <del> input_ids=None, <del> attention_mask=None, <del> decoder_input_ids=None, <del> decoder_attention_mask=None, <del> head_mask=None, <del> decoder_head_mask=None, <del> cross_attn_head_mask=None, <del> encoder_outputs=None, <del> past_key_values=None, <del> inputs_embeds=None, <add> input_ids: Optional[torch.LongTensor] = None, <add> attention_mask: Optional[torch.LongTensor] = None, <add> decoder_input_ids: Optional[torch.LongTensor] = None, <add> decoder_attention_mask: Optional[torch.Tensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> decoder_head_mask: Optional[torch.LongTensor] = None, <add> cross_attn_head_mask: Optional[torch.Tensor] = None, <add> encoder_outputs: Optional[List[torch.FloatTensor]] = None, <add> past_key_values: Optional[List[torch.FloatTensor]] = None, <add> inputs_embeds: Optional[torch.FloatTensor] = None, <ide> decoder_inputs_embeds=None, <del> labels=None, <del> use_cache=None, <del> output_attentions=None, <del> output_hidden_states=None, <del> return_dict=None, <del> ): <add> labels: Optional[torch.Tensor] = None, <add> use_cache: Optional[bool] = None, <add> output_attentions: Optional[bool] = None, <add> output_hidden_states: Optional[bool] = None, <add> return_dict: Optional[bool] = None, <add> ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]: <ide> r""" <ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., <ide> def forward( <ide> <ide> def prepare_inputs_for_generation( <ide> self, <del> decoder_input_ids, <del> past=None, <del> attention_mask=None, <del> head_mask=None, <del> decoder_head_mask=None, <del> cross_attn_head_mask=None, <del> use_cache=None, <del> encoder_outputs=None, <add> decoder_input_ids: torch.LongTensor, <add> past: Optional[List[torch.FloatTensor]] = None, <add> attention_mask: Optional[torch.LongTensor] = None, <add> head_mask: Optional[torch.Tensor] = None, <add> decoder_head_mask: Optional[torch.Tensor] = None, <add> cross_attn_head_mask: Optional[torch.Tensor] = None, <add> use_cache: Optional[bool] = None, <add> encoder_outputs: Optional[List[torch.FloatTensor]] = None, <ide> **kwargs # TODO: Check if this is needed. It is unused? <del> ): <add> ) -> Dict[str, Any]: <ide> # cut decoder_input_ids if past is used <ide> if past is not None: <ide> decoder_input_ids = decoder_input_ids[:, -1:]
1
Text
Text
update wasi example to use import.meta.url
162f07b7af24692de32d47b26e7cc5e52fc4e0c2
<ide><path>doc/api/wasi.md <ide> specification. WASI gives sandboxed WebAssembly applications access to the <ide> underlying operating system via a collection of POSIX-like functions. <ide> <ide> ```mjs <del>import fs from 'fs'; <add>import { readFile } from 'fs/promises'; <ide> import { WASI } from 'wasi'; <ide> import { argv, env } from 'process'; <ide> <ide> const wasi = new WASI({ <ide> '/sandbox': '/some/real/path/that/wasm/can/access' <ide> } <ide> }); <add> <add>// Some WASI binaries require: <add>// const importObject = { wasi_unstable: wasi.wasiImport }; <ide> const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; <ide> <del>const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm')); <add>const wasm = await WebAssembly.compile( <add> await readFile(new URL('./demo.wasm', import.meta.url)) <add>); <ide> const instance = await WebAssembly.instantiate(wasm, importObject); <ide> <ide> wasi.start(instance); <ide> ``` <ide> <ide> ```cjs <ide> 'use strict'; <del>const fs = require('fs'); <add>const { readFile } = require('fs/promises'); <ide> const { WASI } = require('wasi'); <ide> const { argv, env } = require('process'); <add>const { join } = require('path'); <ide> <ide> const wasi = new WASI({ <ide> args: argv, <ide> const wasi = new WASI({ <ide> '/sandbox': '/some/real/path/that/wasm/can/access' <ide> } <ide> }); <add> <add>// Some WASI binaries require: <add>// const importObject = { wasi_unstable: wasi.wasiImport }; <ide> const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; <ide> <ide> (async () => { <del> const wasm = await WebAssembly.compile(fs.readFileSync('./demo.wasm')); <add> const wasm = await WebAssembly.compile( <add> await readFile(join(__dirname, 'demo.wasm')) <add> ); <ide> const instance = await WebAssembly.instantiate(wasm, importObject); <ide> <ide> wasi.start(instance);
1
Text
Text
add v1.2.5 changes
e9c79cad437605171894e2d1aad842e662b8579c
<ide><path>CHANGELOG.md <add><a name="1.2.5"></a> <add># 1.2.5 singularity-expansion (2013-12-13) <add> <add> <add>## Bug Fixes <add> <add>- **$compile:** allow literals in isolate scope references <add> ([43072e38](https://github.com/angular/angular.js/commit/43072e3812e32b89b97ad03144577cba50d4b776), <add> [#5296](https://github.com/angular/angular.js/issues/5296)) <add>- **angular-mocks:** use copy of mock data in $httpBackend <add> ([f69dc162](https://github.com/angular/angular.js/commit/f69dc16241c8b631123ad0b09674f0a5e0ff32fe)) <add>- **closure:** add missing FormController extern definitions <add> ([1d5e18b0](https://github.com/angular/angular.js/commit/1d5e18b062c3e33b2a8d96aa58d905ed2cd48649), <add> [#5303](https://github.com/angular/angular.js/issues/5303)) <add>- **ngInclude:** add template to DOM before linking other directives <add> ([30a8b7d0](https://github.com/angular/angular.js/commit/30a8b7d0b5d4882c2bf3b20eb696a02f5b667726), <add> [#5247](https://github.com/angular/angular.js/issues/5247)) <add>- **ngView:** add template to DOM before linking other directives <add> ([f8944efe](https://github.com/angular/angular.js/commit/f8944efe70b81e02704df9b53ea2546c80c73d3b)) <add> <add> <add>## Performance Improvements <add> <add>- **$injector:** remove invoke optimization that doesn't work <add> ([05e4fd34](https://github.com/angular/angular.js/commit/05e4fd3488b89e670c36869f18defe26deac2efa), <add> [#5388](https://github.com/angular/angular.js/issues/5388)) <add>- **$resource:** use shallow copy instead of angular.copy <add> ([fcd2a813](https://github.com/angular/angular.js/commit/fcd2a8131a3cb3e59a616bf31e61510b5c3a97d3), <add> [#5300](https://github.com/angular/angular.js/issues/5300)) <add>- **a:** do not link when href or name exists in template <add> ([f3de5b6e](https://github.com/angular/angular.js/commit/f3de5b6eac90baf649506072162f36dbc6d2f028), <add> [#5362](https://github.com/angular/angular.js/issues/5362)) <add>- **jqLite:** implement and use the `empty` method in place of `html(‘’)` <add> ([3410f65e](https://github.com/angular/angular.js/commit/3410f65e790a81d457b4f4601a1e760a6f8ede5e), <add> [#4457](https://github.com/angular/angular.js/issues/4457)) <add> <add>## Breaking Changes <add> <add>- **angular-mocks:** due to [f69dc162](https://github.com/angular/angular.js/commit/f69dc16241c8b631123ad0b09674f0a5e0ff32fe), <add> some tests that rely on identity comparison rather than equality comparison in checking mock http responses will be broken, <add> since now each mock response is a copy of the original response. This is usually fixable by changing a `.toBe()` comparison <add> to `toEqual()` inside of tests. <add> <ide> <a name="1.2.4"></a> <ide> # 1.2.4 wormhole-blaster (2013-12-06) <ide>
1
Text
Text
add v3.25.0-beta.1 to changelog
2bb644532d407d4b4700a81f510c5aed4caf5d84
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.25.0-beta.1 (December 28, 2020) <add> <add>- [#19302](https://github.com/emberjs/ember.js/pull/19302) / [#19306](https://github.com/emberjs/ember.js/pull/19306) / [#19319](https://github.com/emberjs/ember.js/pull/19319) [FEATURE] Implement the [Handlebars Strict Mode RFC](https://github.com/emberjs/rfcs/blob/master/text/0496-handlebars-strict-mode.md). <add>- [#19318](https://github.com/emberjs/ember.js/pull/19318) [FEATURE] Implement the [Named Blocks RFC](https://github.com/emberjs/rfcs/blob/master/text/0460-yieldable-named-blocks.md). <add>- [#18148](https://github.com/emberjs/ember.js/pull/18148) [BUGFIX] Fix empty `htmlSafe` string to be treated as falsy <add>- [#19320](https://github.com/emberjs/ember.js/pull/19320) / [#19317](https://github.com/emberjs/ember.js/pull/19317) / [#19297](https://github.com/emberjs/ember.js/pull/19297) / [#19293](https://github.com/emberjs/ember.js/pull/19293) / [#19278](https://github.com/emberjs/ember.js/pull/19278) / [#19275](https://github.com/emberjs/ember.js/pull/19275) Update rendering engine to `@glimmer/*` 0.73.1 for various features and bugfixes including ensuring `{{component.name}}` works with implicit this fallback <add> <ide> ### v3.24.0 (December 28, 2020) <ide> <ide> - [#19224](https://github.com/emberjs/ember.js/pull/19224) [FEATURE] Add `{{page-title}}` helper to route template blueprints to implement [RFC #0654](https://github.com/emberjs/rfcs/blob/master/text/0645-add-ember-page-title-addon.md).
1
Javascript
Javascript
add leanpub to the list of showcase apps
19df8ba698e3b7c597a5522d6b229737f5aaadab
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/youmeyou/id949540333?mt=8', <ide> author: 'youmeyou, LLC', <ide> }, <add> { <add> name: 'Leanpub', <add> icon: 'http://a2.mzstatic.com/us/r30/Purple6/v4/9f/4a/6f/9f4a6f8c-8951-ed89-4083-74ace23df9ef/icon350x350.jpeg', <add> link: 'https://itunes.apple.com/us/app/leanpub/id913517110?ls=1&mt=8', <add> author: 'Leanpub' <add> }, <ide> ]; <ide> <ide> var showcase = React.createClass({
1
Mixed
Ruby
add config option for cookies digest
29be3f5d8386fc9a8a67844fa9b7d6860574e715
<ide><path>actionpack/CHANGELOG.md <add>* Add `config.action_dispatch.cookies_digest` option for setting custom <add> digest. The default remains the same - 'SHA1'. <add> <add> *Łukasz Strzałkowski* <add> <ide> * Extract source code for the entire exception stack trace for <ide> better debugging and diagnosis. <ide> <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> class Cookies <ide> SECRET_TOKEN = "action_dispatch.secret_token".freeze <ide> SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze <ide> COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze <add> COOKIES_DIGEST = "action_dispatch.cookies_digest".freeze <ide> <ide> # Cookies can typically store 4096 bytes. <ide> MAX_COOKIE_SIZE = 4096 <ide> def self.options_for_env(env) #:nodoc: <ide> secret_token: env[SECRET_TOKEN], <ide> secret_key_base: env[SECRET_KEY_BASE], <ide> upgrade_legacy_signed_cookies: env[SECRET_TOKEN].present? && env[SECRET_KEY_BASE].present?, <del> serializer: env[COOKIES_SERIALIZER] <add> serializer: env[COOKIES_SERIALIZER], <add> digest: env[COOKIES_DIGEST] <ide> } <ide> end <ide> <ide> def serializer <ide> serializer <ide> end <ide> end <add> <add> def digest <add> @options[:digest] || 'SHA1' <add> end <ide> end <ide> <ide> class SignedCookieJar #:nodoc: <ide> def initialize(parent_jar, key_generator, options = {}) <ide> @parent_jar = parent_jar <ide> @options = options <ide> secret = key_generator.generate_key(@options[:signed_cookie_salt]) <del> @verifier = ActiveSupport::MessageVerifier.new(secret, serializer: NullSerializer) <add> @verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: NullSerializer) <ide> end <ide> <ide> def [](name) <ide> def initialize(parent_jar, key_generator, options = {}) <ide> @options = options <ide> secret = key_generator.generate_key(@options[:encrypted_cookie_salt]) <ide> sign_secret = key_generator.generate_key(@options[:encrypted_signed_cookie_salt]) <del> @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: NullSerializer) <add> @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: NullSerializer) <ide> end <ide> <ide> def [](name) <ide><path>actionpack/test/dispatch/cookies_test.rb <ide> def test_read_permanent_cookie <ide> assert_equal 'Jamie', @controller.send(:cookies).permanent[:user_name] <ide> end <ide> <add> def test_signed_cookie_using_default_digest <add> get :set_signed_cookie <add> cookies = @controller.send :cookies <add> assert_not_equal 45, cookies[:user_id] <add> assert_equal 45, cookies.signed[:user_id] <add> <add> key_generator = @request.env["action_dispatch.key_generator"] <add> signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"] <add> secret = key_generator.generate_key(signed_cookie_salt) <add> <add> verifier = ActiveSupport::MessageVerifier.new(secret, serializer: Marshal, digest: 'SHA1') <add> assert_equal verifier.generate(45), cookies[:user_id] <add> end <add> <add> def test_signed_cookie_using_custom_digest <add> @request.env["action_dispatch.cookies_digest"] = 'SHA256' <add> get :set_signed_cookie <add> cookies = @controller.send :cookies <add> assert_not_equal 45, cookies[:user_id] <add> assert_equal 45, cookies.signed[:user_id] <add> <add> key_generator = @request.env["action_dispatch.key_generator"] <add> signed_cookie_salt = @request.env["action_dispatch.signed_cookie_salt"] <add> secret = key_generator.generate_key(signed_cookie_salt) <add> <add> verifier = ActiveSupport::MessageVerifier.new(secret, serializer: Marshal, digest: 'SHA256') <add> assert_equal verifier.generate(45), cookies[:user_id] <add> end <add> <ide> def test_signed_cookie_using_default_serializer <ide> get :set_signed_cookie <ide> cookies = @controller.send :cookies <ide> def test_encrypted_cookie_using_custom_serializer <ide> assert_equal 'bar was dumped and loaded', cookies.encrypted[:foo] <ide> end <ide> <add> def test_encrypted_cookie_using_custom_digest <add> @request.env["action_dispatch.cookies_digest"] = 'SHA256' <add> get :set_encrypted_cookie <add> cookies = @controller.send :cookies <add> assert_not_equal 'bar', cookies[:foo] <add> assert_equal 'bar', cookies.encrypted[:foo] <add> <add> sign_secret = @request.env["action_dispatch.key_generator"].generate_key(@request.env["action_dispatch.encrypted_signed_cookie_salt"]) <add> <add> sha1_verifier = ActiveSupport::MessageVerifier.new(sign_secret, serializer: ActionDispatch::Cookies::NullSerializer, digest: 'SHA1') <add> sha256_verifier = ActiveSupport::MessageVerifier.new(sign_secret, serializer: ActionDispatch::Cookies::NullSerializer, digest: 'SHA256') <add> <add> assert_raises(ActiveSupport::MessageVerifier::InvalidSignature) do <add> sha1_verifier.verify(cookies[:foo]) <add> end <add> <add> assert_nothing_raised do <add> sha256_verifier.verify(cookies[:foo]) <add> end <add> end <add> <ide> def test_encrypted_cookie_using_hybrid_serializer_can_migrate_marshal_dumped_value_to_json <ide> @request.env["action_dispatch.cookies_serializer"] = :hybrid <ide> <ide><path>activesupport/lib/active_support/message_encryptor.rb <ide> class InvalidMessage < StandardError; end <ide> # Options: <ide> # * <tt>:cipher</tt> - Cipher to use. Can be any cipher returned by <ide> # <tt>OpenSSL::Cipher.ciphers</tt>. Default is 'aes-256-cbc'. <add> # * <tt>:digest</tt> - String of digest to use for signing. Default is +SHA1+. <ide> # * <tt>:serializer</tt> - Object serializer to use. Default is +Marshal+. <ide> def initialize(secret, *signature_key_or_options) <ide> options = signature_key_or_options.extract_options! <ide> sign_secret = signature_key_or_options.first <ide> @secret = secret <ide> @sign_secret = sign_secret <ide> @cipher = options[:cipher] || 'aes-256-cbc' <del> @verifier = MessageVerifier.new(@sign_secret || @secret, :serializer => NullSerializer) <add> @verifier = MessageVerifier.new(@sign_secret || @secret, digest: options[:digest] || 'SHA1', serializer: NullSerializer) <ide> @serializer = options[:serializer] || Marshal <ide> end <ide> <ide><path>railties/lib/rails/application.rb <ide> def env_config <ide> "action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt, <ide> "action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt, <ide> "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt, <del> "action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer <add> "action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer, <add> "action_dispatch.cookies_digest" => config.action_dispatch.cookies_digest <ide> }) <ide> end <ide> end
5
Ruby
Ruby
collapse checkable_urls methods into one method
064e93df5b32c9914fcfaf9702cd32ba4d7b7ebb
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def print_latest_version(info, args:) <ide> puts "#{formula_or_cask_s} : #{current_s} ==> #{latest_s}" <ide> end <ide> <del> # Returns an Array containing the formula URLs that can be used by livecheck. <add> # Returns an Array containing the formula/cask URLs that can be used by livecheck. <ide> # @return [Array] <del> def checkable_formula_urls(formula) <add> def checkable_urls(formula_or_cask) <ide> urls = [] <del> urls << formula.head.url if formula.head <del> if formula.stable <del> urls << formula.stable.url <del> urls.concat(formula.stable.mirrors) <del> end <del> urls << formula.homepage if formula.homepage <ide> <del> urls.compact <del> end <add> case formula_or_cask <add> when Formula <add> urls << formula_or_cask.head.url if formula_or_cask.head <add> if formula_or_cask.stable <add> urls << formula_or_cask.stable.url <add> urls.concat(formula_or_cask.stable.mirrors) <add> end <add> urls << formula_or_cask.homepage if formula_or_cask.homepage <add> when Cask::Cask <add> urls << formula_or_cask.appcast.to_s if formula_or_cask.appcast <add> urls << formula_or_cask.url.to_s if formula_or_cask.url <add> urls << formula_or_cask.homepage if formula_or_cask.homepage <add> end <ide> <del> def checkable_cask_urls(cask) <del> urls = [] <del> urls << cask.appcast.to_s if cask.appcast <del> urls << cask.url.to_s <del> urls << cask.homepage if cask.homepage <ide> urls.compact <ide> end <ide> <del> def checkable_urls(formula_or_cask) <del> if formula_or_cask.is_a?(Formula) <del> checkable_formula_urls(formula_or_cask) <del> else <del> checkable_cask_urls(formula_or_cask) <del> end <del> end <del> <ide> # Preprocesses and returns the URL used by livecheck. <ide> # @return [String] <ide> def preprocess_url(url)
1
PHP
PHP
add env variable for compiled view path
5ea6fe18a89c3d0f5c0860d3777bff97510577b5
<ide><path>config/view.php <ide> | <ide> */ <ide> <del> 'compiled' => realpath(storage_path('framework/views')), <add> 'compiled' => env( <add> 'VIEW_COMPILED_PATH', <add> realpath(storage_path('framework/views')) <add> ), <ide> <ide> ];
1
Text
Text
update installation instructions in readme
99041de31a80af789441a84181953a7282d6c64d
<ide><path>README.md <ide> <ide> ## Installation <ide> <del>You can download the latest version of [Chart.js on GitHub](https://github.com/chartjs/Chart.js/releases/latest) or just use these [Chart.js CDN](https://cdnjs.com/libraries/Chart.js) links. <add>You can download the latest version of Chart.js from the [GitHub releases](https://github.com/chartjs/Chart.js/releases/latest) or use a [Chart.js CDN](https://cdnjs.com/libraries/Chart.js). <ide> <ide> To install via npm: <ide> <ide> ```bash <ide> npm install chart.js --save <ide> ``` <ide> <del>To Install via bower, please follow [these instructions](http://www.chartjs.org/docs/#getting-started-installation). <add>To install via bower: <add>```bash <add>bower install chart.js --save <add>``` <add> <add>#### Selecting the Correct Build <add> <add>Chart.js provides two different builds that are available for your use. The `Chart.js` and `Chart.min.js` files include Chart.js and the accompanying color parsing library. If this version is used and you require the use of the time axis, [Moment.js](http://momentjs.com/) will need to be included before Chart.js. <add> <add>The `Chart.bundle.js` and `Chart.bundle.min.js` builds include Moment.js in a single file. This version should be used if you require time axes and want a single file to include, select this version. Do not use this build if your application already includes Moment.js. If you do, Moment.js will be included twice, increasing the page load time and potentially introducing version issues. <ide> <ide> ## Documentation <ide>
1
Ruby
Ruby
optimize layout lookup to avoid double calls
239262fee03096d1e52acf8fe69de736726d87e0
<ide><path>actionpack/lib/abstract_controller/layouts.rb <ide> module Layouts <ide> included do <ide> class_attribute :_layout_conditions <ide> remove_possible_method :_layout_conditions <del> delegate :_layout_conditions, :to => :'self.class' <ide> self._layout_conditions = {} <ide> _write_layout_method <ide> end <ide> <add> delegate :_layout_conditions, :to => "self.class" <add> <ide> module ClassMethods <ide> def inherited(klass) <ide> super <ide> module LayoutConditions <ide> # <ide> # ==== Returns <ide> # * <tt> Boolean</tt> - True if the action has a layout, false otherwise. <del> def action_has_layout? <add> def conditional_layout? <ide> return unless super <ide> <ide> conditions = _layout_conditions <ide> def _implied_layout_name <ide> def _write_layout_method <ide> remove_possible_method(:_layout) <ide> <del> prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] <add> prefixes = _implied_layout_name =~ /\blayouts/ ? [] : ["layouts"] <add> name_clause = if name <add> <<-RUBY <add> lookup_context.find_all("#{_implied_layout_name}", #{prefixes.inspect}).first || super <add> RUBY <add> end <add> <ide> layout_definition = case defined?(@_layout) ? @_layout : nil <ide> when String <ide> @_layout.inspect <ide> def _write_layout_method <ide> when true <ide> raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" <ide> when nil <del> if name <del> <<-RUBY <del> if template_exists?("#{_implied_layout_name}", #{prefixes.inspect}) <del> "#{_implied_layout_name}" <del> else <del> super <del> end <del> RUBY <del> end <add> name_clause <ide> end <ide> <ide> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def _layout <del> if action_has_layout? <add> if conditional_layout? <ide> #{layout_definition} <del> elsif self.class.name <del> if template_exists?("#{_implied_layout_name}", #{prefixes.inspect}) <del> "#{_implied_layout_name}" <del> else <del> super <del> end <add> else <add> #{name_clause} <ide> end <ide> end <ide> RUBY <ide> def _normalize_options(options) <ide> <ide> if _include_layout?(options) <ide> layout = options.key?(:layout) ? options.delete(:layout) : :default <del> value = _layout_for_option(layout) <del> options[:layout] = (value =~ /\blayouts/ ? value : "layouts/#{value}") if value <add> options[:layout] = Proc.new { _normalize_layout(_layout_for_option(layout)) } <ide> end <ide> end <ide> <ide> def action_has_layout? <ide> @_action_has_layout <ide> end <ide> <add> def conditional_layout? <add> true <add> end <add> <ide> private <ide> <ide> # This will be overwritten by _write_layout_method <ide> def _layout_for_option(name) <ide> end <ide> end <ide> <add> def _normalize_layout(value) <add> value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value <add> end <add> <ide> # Returns the default layout for this controller. <ide> # Optionally raises an exception if the layout could not be found. <ide> # <ide> def _layout_for_option(name) <ide> # * <tt>template</tt> - The template object for the default layout (or nil) <ide> def _default_layout(require_layout = false) <ide> begin <del> layout_name = _layout <add> value = _layout if action_has_layout? <ide> rescue NameError => e <ide> raise e, "Could not render layout: #{e.message}" <ide> end <ide> <del> if require_layout && action_has_layout? && !layout_name <add> if require_layout && action_has_layout? && !value <ide> raise ArgumentError, <ide> "There was no default layout for #{self.class} in #{view_paths.inspect}" <ide> end <ide> <del> layout_name <add> value <ide> end <ide> <ide> def _include_layout?(options) <ide><path>actionpack/lib/abstract_controller/view_paths.rb <ide> module ViewPaths <ide> self._view_paths.freeze <ide> end <ide> <del> delegate :find_template, :template_exists?, :view_paths, :formats, :formats=, <add> delegate :template_exists?, :view_paths, :formats, :formats=, <ide> :locale, :locale=, :to => :lookup_context <ide> <ide> module ClassMethods <ide><path>actionpack/lib/action_view/lookup_context.rb <ide> def locale=(value) <ide> end <ide> <ide> # A method which only uses the first format in the formats array for layout lookup. <del> # This method plays straight with instance variables for performance reasons. <ide> def with_layout_format <ide> if formats.size == 1 <ide> yield <ide><path>actionpack/lib/action_view/renderer/template_renderer.rb <ide> def render_with_layout(path, locals) #:nodoc: <ide> # context object. If no layout is found, it checks if at least a layout with <ide> # the given name exists across all details before raising the error. <ide> def find_layout(layout, keys) <del> begin <del> with_layout_format do <del> layout =~ /^\// ? <del> with_fallbacks { find_template(layout, nil, false, keys, @details) } : find_template(layout, nil, false, keys, @details) <add> with_layout_format { resolve_layout(layout, keys) } <add> end <add> <add> def resolve_layout(layout, keys) <add> case layout <add> when String <add> if layout =~ /^\// <add> with_fallbacks { find_template(layout, nil, false, keys, @details) } <add> else <add> find_template(layout, nil, false, keys, @details) <ide> end <del> rescue ActionView::MissingTemplate <del> all_details = @details.merge(:formats => @lookup_context.default_formats) <del> raise unless template_exists?(layout, nil, false, keys, all_details) <add> when Proc <add> resolve_layout(layout.call, keys) <add> else <add> layout <ide> end <ide> end <ide> end
4
Javascript
Javascript
improve getid guard
45eef8b6b5df27c661b3e33e579abc11b563c65b
<ide><path>packages/react-devtools-shared/src/backend/legacy/renderer.js <ide> export function attach( <ide> } <ide> <ide> function getID(internalInstance: InternalInstance): number { <del> if (typeof internalInstance !== 'object') { <add> if (typeof internalInstance !== 'object' || internalInstance === null) { <ide> throw new Error('Invalid internal instance: ' + internalInstance); <ide> } <ide> if (!internalInstanceToIDMap.has(internalInstance)) {
1
PHP
PHP
fix path output for cli
da7f3d87c393db17be249746f3a3a60ace90c237
<ide><path>src/Console/Command/HelpCommand.php <ide> protected function outputPaths(ConsoleIo $io): void <ide> { <ide> $paths = []; <ide> if (Configure::check('App.dir')) { <add> $appPath = rtrim(Configure::read('App.dir'), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; <ide> // Extra space is to align output <del> $paths['app'] = ' ' . Configure::read('App.dir'); <add> $paths['app'] = ' ' . $appPath; <ide> } <ide> if (defined('ROOT')) { <del> $paths['root'] = rtrim(ROOT, DIRECTORY_SEPARATOR); <add> $paths['root'] = rtrim(ROOT, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; <ide> } <ide> if (defined('CORE_PATH')) { <del> $paths['core'] = rtrim(CORE_PATH, DIRECTORY_SEPARATOR); <add> $paths['core'] = rtrim(CORE_PATH, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; <ide> } <ide> if (!count($paths)) { <ide> return;
1
Ruby
Ruby
teach download strategies to take a softwarespec
56fe164e952e888496bc81495cfc0f66338d50d5
<ide><path>Library/Homebrew/cmd/create.rb <ide> def generate <ide> <ide> unless ARGV.include? "--no-fetch" and version <ide> strategy = DownloadStrategyDetector.new(url).detect <del> @sha1 = strategy.new(url, name, version, nil).fetch.sha1 if strategy == CurlDownloadStrategy <add> spec = SoftwareSpec.new <add> spec.url(url) <add> spec.version(version) <add> @sha1 = strategy.new(name, spec).fetch.sha1 if strategy == CurlDownloadStrategy <ide> end <ide> <ide> path.write ERB.new(template, nil, '>').result(binding) <ide><path>Library/Homebrew/download_strategy.rb <ide> class AbstractDownloadStrategy <del> def initialize url, name, version, specs <del> @url=url <del> case specs when Hash <del> @spec = specs.keys.first # only use first spec <del> @ref = specs.values.first <add> def initialize name, package <add> @url = package.url <add> @specs = package.specs <add> <add> case @specs <add> when Hash <add> @spec = @specs.keys.first # only use first spec <add> @ref = @specs.values.first <ide> end <ide> end <ide> <ide> def quiet_safe_system *args <ide> class CurlDownloadStrategy < AbstractDownloadStrategy <ide> attr_reader :tarball_path <ide> <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <del> @unique_token="#{name}-#{version}" unless name.to_s.empty? or name == '__UNKNOWN__' <add> @mirrors = package.mirrors <add> @unique_token = "#{name}-#{package.version}" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> if @unique_token <ide> @tarball_path=HOMEBREW_CACHE+(@unique_token+ext) <ide> else <ide> def fetch <ide> puts "Already downloaded: #{@tarball_path}" <ide> end <ide> return @tarball_path # thus performs checksum verification <add> rescue CurlDownloadStrategyError <add> raise if @mirrors.empty? <add> puts "Trying a mirror..." <add> @url = @mirrors.shift <add> retry <ide> end <ide> <ide> def stage <ide> def _fetch <ide> <ide> # This strategy extracts our binary packages. <ide> class CurlBottleDownloadStrategy < CurlDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <del> @tarball_path = HOMEBREW_CACHE/"#{name}-#{version}#{ext}" <add> @tarball_path = HOMEBREW_CACHE/"#{name}-#{package.version}#{ext}" <ide> <ide> unless @tarball_path.exist? <ide> # Stop people redownloading bottles just because I (Mike) was stupid. <del> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{version}-bottle.tar.gz" <del> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{version}.#{MacOS.cat}.bottle-bottle.tar.gz" unless old_bottle_path.exist? <del> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{version}-7.#{MacOS.cat}.bottle.tar.gz" unless old_bottle_path.exist? or name != "imagemagick" <add> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{package.version}-bottle.tar.gz" <add> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{package.version}.#{MacOS.cat}.bottle-bottle.tar.gz" unless old_bottle_path.exist? <add> old_bottle_path = HOMEBREW_CACHE/"#{name}-#{package.version}-7.#{MacOS.cat}.bottle.tar.gz" unless old_bottle_path.exist? or name != "imagemagick" <ide> FileUtils.mv old_bottle_path, @tarball_path if old_bottle_path.exist? <ide> end <ide> end <ide> def stage <ide> end <ide> <ide> class SubversionDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--svn" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @unique_token += "-HEAD" if ARGV.include? '--HEAD' <ide> def fetch_repo target, url, revision=nil, ignore_externals=false <ide> end <ide> <ide> class GitDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--git" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @clone=HOMEBREW_CACHE+@unique_token <ide> def stage <ide> end <ide> <ide> class CVSDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--cvs" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @co=HOMEBREW_CACHE+@unique_token <ide> def split_url(in_url) <ide> end <ide> <ide> class MercurialDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--hg" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @clone=HOMEBREW_CACHE+@unique_token <ide> def stage <ide> end <ide> <ide> class BazaarDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--bzr" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @clone=HOMEBREW_CACHE+@unique_token <ide> def stage <ide> end <ide> <ide> class FossilDownloadStrategy < AbstractDownloadStrategy <del> def initialize url, name, version, specs <add> def initialize name, package <ide> super <ide> @unique_token="#{name}--fossil" unless name.to_s.empty? or name == '__UNKNOWN__' <ide> @clone=HOMEBREW_CACHE+@unique_token <ide><path>Library/Homebrew/formula.rb <ide> def initialize name='__UNKNOWN__', path=nil <ide> <ide> # If we got an explicit path, use that, else determine from the name <ide> @path = path.nil? ? self.class.path(name) : Pathname.new(path) <del> @downloader = download_strategy.new(@active_spec.url, name, @active_spec.version, @active_spec.specs) <add> @downloader = download_strategy.new(name, @active_spec) <ide> end <ide> <ide> # Derive specs from class ivars <ide> def system cmd, *args <ide> <ide> # For brew-fetch and others. <ide> def fetch <del> downloader = @downloader <del> mirror_list = case @active_spec <del> when @stable, @devel then @active_spec.mirrors <del> else [] <del> end <del> <ide> # Ensure the cache exists <ide> HOMEBREW_CACHE.mkpath <ide> <del> # TODO teach download strategies to take a SoftwareSpec <del> # object, and move mirror handling into CurlDownloadStrategy <del> begin <del> fetched = downloader.fetch <del> rescue CurlDownloadStrategyError => e <del> raise e if mirror_list.empty? <del> puts "Trying a mirror..." <del> url, specs = mirror_list.shift.values_at :url, :specs <del> downloader = download_strategy.new url, name, version, specs <del> retry <del> end <del> <del> return fetched, downloader <add> return @downloader.fetch, @downloader <ide> end <ide> <ide> # For FormulaInstaller. <ide> def version val=nil <ide> @stable.version(val) <ide> end <ide> <del> def mirror val, specs=nil <add> def mirror val <ide> @stable ||= SoftwareSpec.new <del> @stable.mirror(val, specs) <add> @stable.mirror(val) <ide> end <ide> <ide> def dependencies <ide><path>Library/Homebrew/formula_support.rb <ide> def version val=nil <ide> return @version <ide> end <ide> <del> def mirror val, specs=nil <add> def mirror val <ide> @mirrors ||= [] <del> @mirrors << { :url => val, :specs => specs } <add> @mirrors << val <ide> end <ide> end <ide>
4
Javascript
Javascript
fix typechecks for isrenderedbyreact()
1be6c592a64ac8c996763b875a80b17c0193b309
<ide><path>src/core/ReactInstanceHandles.js <ide> var ReactInstanceHandles = { <ide> /** <ide> * True if the supplied `node` is rendered by React. <ide> * <del> * @param {DOMEventTarget} node DOM Element to check. <add> * @param {*} node DOM Element to check. <ide> * @return {boolean} True if the DOM Element appears to be rendered by React. <del> * @private <add> * @internal <ide> */ <ide> isRenderedByReact: function(node) { <add> if (node.nodeType !== 1) { <add> // Not a DOMElement, therefore not a React component <add> return false; <add> } <ide> var id = getDOMNodeID(node); <ide> return id ? id.charAt(0) === SEPARATOR : false; <ide> }, <ide><path>src/core/ReactMount.js <ide> var containersByReactRootID = {}; <ide> <ide> /** <ide> * @param {DOMElement} container DOM element that may contain a React component <del> * @return {?DOMElement} DOM element that may have the reactRoot ID, or null. <add> * @return {?*} DOM element that may have the reactRoot ID, or null. <ide> */ <ide> function getReactRootElementInContainer(container) { <ide> return container.firstChild; <ide><path>src/core/__tests__/ReactInstanceHandles-test.js <ide> describe('ReactInstanceHandles.getReactRootIDFromNodeID', function() { <ide> expect(actual).toEqual(expected); <ide> }); <ide> }); <add> <add>describe('ReactInstanceHandles.isRenderedByReact', function() { <add> it('should not crash on text nodes', function() { <add> expect(function() { <add> ReactInstanceHandles.isRenderedByReact(document.createTextNode('yolo')) <add> }).not.toThrow(); <add> }); <add>});
3
Javascript
Javascript
fix bad test in test-cli-eval.js
f9cfd709460e04c8417e7784e6e3b264d3ff6c69
<ide><path>test/simple/test-cli-eval.js <ide> child.exec(nodejs + ' --eval 42', <ide> assert.equal(stdout, ''); <ide> }); <ide> <del>// assert that nothing is written to stdout <del>child.exec(nodejs + ' --eval console.log(42)', <add>// assert that "42\n" is written to stderr <add>child.exec(nodejs + ' --eval \'console.error(42)\'', <ide> function(err, stdout, stderr) { <del> assert.equal(stdout, ''); <add> assert.equal(stderr, "42\n"); <ide> }); <ide> <ide> // assert that module loading works
1
Java
Java
delete unused imports
ac22b786be71972f9da39836020516b92c021d5c
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/InterceptorRegistryTests.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2014 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> <ide> import org.junit.Before; <ide> import org.junit.Test; <del>import org.mockito.Mock; <ide> import org.mockito.Mockito; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <ide> package org.springframework.web.servlet.mvc.annotation; <ide> <ide> import static org.junit.Assert.*; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> <del>import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.i18n.LocaleContextHolder; <ide> import org.springframework.context.support.StaticMessageSource; <ide> import org.springframework.http.HttpStatus; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> import org.springframework.web.bind.annotation.ResponseStatus; <del>import org.springframework.web.context.support.StaticWebApplicationContext; <ide> import org.springframework.web.servlet.ModelAndView; <ide> <ide> /** @author Arjen Poutsma */ <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <ide> import org.springframework.web.util.UriComponents; <del>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> import java.util.Arrays; <ide> import java.util.List; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2014 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> import org.junit.Before; <ide> import org.junit.BeforeClass; <ide> import org.junit.Test; <add> <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> import org.springframework.ui.Model; <del>import org.springframework.web.bind.WebDataBinder; <ide> import org.springframework.web.bind.annotation.ControllerAdvice; <del>import org.springframework.web.bind.annotation.InitBinder; <ide> import org.springframework.web.bind.annotation.ModelAttribute; <ide> import org.springframework.web.bind.annotation.SessionAttributes; <ide> import org.springframework.web.context.support.StaticWebApplicationContext; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 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> import org.springframework.beans.propertyeditors.CustomCollectionEditor; <ide> import org.springframework.format.Formatter; <ide> import org.springframework.format.support.FormattingConversionService; <del>import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.tests.sample.beans.TestBean; <ide> import org.springframework.validation.BeanPropertyBindingResult; <ide> import org.springframework.validation.BindingResult; <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 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> import org.junit.After; <ide> import org.junit.Before; <ide> import org.junit.Test; <add> <ide> import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockHttpServletResponse; <ide> <ide> import static org.junit.Assert.*; <ide> import static org.mockito.BDDMockito.*; <del>import static org.mockito.Mockito.*; <ide> <ide> /** <ide> * @author Arjen Poutsma <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 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> <ide> package org.springframework.web.servlet.view.freemarker; <ide> <del>import static org.hamcrest.Matchers.instanceOf; <del>import static org.junit.Assert.assertThat; <del> <ide> import java.io.IOException; <ide> import java.util.HashMap; <ide> import java.util.Properties; <ide> <del>import freemarker.cache.ClassTemplateLoader; <del>import freemarker.cache.MultiTemplateLoader; <del>import freemarker.cache.TemplateLoader; <del>import freemarker.template.Configuration; <del>import freemarker.template.Template; <del>import freemarker.template.TemplateException; <del>import junit.framework.TestCase; <add>import org.junit.Test; <ide> <ide> import org.springframework.core.io.ByteArrayResource; <ide> import org.springframework.core.io.FileSystemResource; <ide> import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; <ide> import org.springframework.ui.freemarker.SpringTemplateLoader; <ide> <add>import freemarker.template.Configuration; <add>import freemarker.template.Template; <add> <add>import static org.hamcrest.Matchers.*; <add>import static org.junit.Assert.*; <add> <ide> /** <ide> * @author Juergen Hoeller <ide> * @since 14.03.2004 <ide> */ <del>public class FreeMarkerConfigurerTests extends TestCase { <add>public class FreeMarkerConfigurerTests { <ide> <del> public void testFreemarkerConfigurationFactoryBeanWithConfigLocation() throws TemplateException { <add> @Test(expected = IOException.class) <add> public void freemarkerConfigurationFactoryBeanWithConfigLocation() throws Exception { <ide> FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); <ide> fcfb.setConfigLocation(new FileSystemResource("myprops.properties")); <ide> Properties props = new Properties(); <ide> props.setProperty("myprop", "/mydir"); <ide> fcfb.setFreemarkerSettings(props); <del> try { <del> fcfb.afterPropertiesSet(); <del> fail("Should have thrown IOException"); <del> } <del> catch (IOException ex) { <del> // expected <del> } <add> fcfb.afterPropertiesSet(); <ide> } <ide> <del> public void testFreeMarkerConfigurationFactoryBeanWithResourceLoaderPath() throws Exception { <add> @Test <add> public void freeMarkerConfigurationFactoryBeanWithResourceLoaderPath() throws Exception { <ide> FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); <ide> fcfb.setTemplateLoaderPath("file:/mydir"); <ide> fcfb.afterPropertiesSet(); <ide> Configuration cfg = fcfb.getObject(); <ide> assertTrue(cfg.getTemplateLoader() instanceof SpringTemplateLoader); <ide> } <ide> <del> public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() <del> throws IOException, TemplateException { <add> @Test <add> @SuppressWarnings("rawtypes") <add> public void freemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath() throws Exception { <ide> FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean(); <ide> fcfb.setTemplateLoaderPath("file:/mydir"); <ide> Properties settings = new Properties(); <ide> settings.setProperty("localized_lookup", "false"); <ide> fcfb.setFreemarkerSettings(settings); <ide> fcfb.setResourceLoader(new ResourceLoader() { <add> <ide> @Override <ide> public Resource getResource(String location) { <ide> if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) { <ide> throw new IllegalArgumentException(location); <ide> } <ide> return new ByteArrayResource("test".getBytes(), "test"); <ide> } <add> <ide> @Override <ide> public ClassLoader getClassLoader() { <ide> return getClass().getClassLoader();
7
Python
Python
add code to detect msvc used to build python
0ba62e66aef44d52f228c351366c4c021fd7a0fb
<ide><path>numpy/random/setup.py <ide> from os.path import join, split <add>import sys <add> <add>def msvc_version(): <add> """Return the msvc version used to build the running python, None if not <add> built with MSVC.""" <add> msc_pos = sys.version.find('MSC v.') <add> if msc_pos != -1: <add> return sys.version[msc_pos+6:msc_pos+10] <add> return None <ide> <ide> def configuration(parent_package='',top_path=None): <ide> from numpy.distutils.misc_util import Configuration, get_mathlibs
1
Javascript
Javascript
use a set for better performance
dab1c30b8f479bc279845cb02253898812668595
<ide><path>lib/util/propertyAccess.js <ide> "use strict"; <ide> <ide> const SAFE_IDENTIFIER = /^[_a-zA-Z$][_a-zA-Z$0-9]*$/; <del>const RESERVED_IDENTIFER = [ <add>const RESERVED_IDENTIFER = new Set([ <ide> "break", <ide> "case", <ide> "catch", <ide> const RESERVED_IDENTIFER = [ <ide> "null", <ide> "true", <ide> "false" <del>]; <add>]); <ide> <ide> const propertyAccess = (properties, start = 0) => { <ide> let str = ""; <ide> for (let i = start; i < properties.length; i++) { <ide> const p = properties[i]; <ide> if (`${+p}` === p) { <ide> str += `[${p}]`; <del> } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFER.includes(p)) { <add> } else if (SAFE_IDENTIFIER.test(p) && !RESERVED_IDENTIFER.has(p)) { <ide> str += `.${p}`; <ide> } else { <ide> str += `[${JSON.stringify(p)}]`;
1
PHP
PHP
add test for assertstatuscode and cleanup
9f4865f287d28dc5cc57bd17aa739149160aef37
<ide><path>src/TestSuite/IntegrationTestCase.php <ide> abstract class IntegrationTestCase extends TestCase { <ide> protected $_requestSession; <ide> <ide> /** <del> * Reset the EventManager for before each test. <add> * Resets the EventManager for before each test. <ide> * <ide> * @return void <ide> */ <ide> public function setUp() { <ide> } <ide> <ide> /** <del> * Clear the state used for requests. <add> * Clears the state used for requests. <ide> * <ide> * @return void <ide> */ <ide> public function tearDown() { <ide> } <ide> <ide> /** <del> * Configure the data for the *next* request. <add> * Configures the data for the *next* request. <ide> * <ide> * This data is cleared in the tearDown() method. <ide> * <ide> public function configRequest(array $data) { <ide> } <ide> <ide> /** <del> * Set session data. <add> * Sets session data. <ide> * <ide> * This method lets you configure the session data <ide> * you want to be used for requests that follow. The session <ide> public function session(array $data) { <ide> } <ide> <ide> /** <del> * Set a request cookie for future requests. <add> * Sets a request cookie for future requests. <ide> * <ide> * This method lets you configure the session data <ide> * you want to be used for requests that follow. The session <ide> public function cookie($name, $value) { <ide> } <ide> <ide> /** <del> * Perform a GET request using the current request data. <add> * Performs a GET request using the current request data. <ide> * <ide> * The response of the dispatched request will be stored as <ide> * a property. You can use various assert methods to check the <ide> public function get($url) { <ide> } <ide> <ide> /** <del> * Perform a POST request using the current request data. <add> * Performs a POST request using the current request data. <ide> * <ide> * The response of the dispatched request will be stored as <ide> * a property. You can use various assert methods to check the <ide> public function post($url, $data = []) { <ide> } <ide> <ide> /** <del> * Perform a PATCH request using the current request data. <add> * Performs a PATCH request using the current request data. <ide> * <ide> * The response of the dispatched request will be stored as <ide> * a property. You can use various assert methods to check the <ide> public function patch($url, $data = []) { <ide> } <ide> <ide> /** <del> * Perform a PUT request using the current request data. <add> * Performs a PUT request using the current request data. <ide> * <ide> * The response of the dispatched request will be stored as <ide> * a property. You can use various assert methods to check the <ide> public function put($url, $data = []) { <ide> } <ide> <ide> /** <del> * Perform a DELETE request using the current request data. <add> * Performs a DELETE request using the current request data. <ide> * <ide> * The response of the dispatched request will be stored as <ide> * a property. You can use various assert methods to check the <ide> public function delete($url) { <ide> } <ide> <ide> /** <del> * Create and send the request into a Dispatcher instance. <add> * Creates and send the request into a Dispatcher instance. <ide> * <ide> * Receives and stores the response for future inspection. <ide> * <ide> protected function _sendRequest($url, $method, $data = []) { <ide> } <ide> <ide> /** <del> * Add additional event spies to the controller/view event manager. <add> * Adds additional event spies to the controller/view event manager. <ide> * <ide> * @param \Cake\Event\Event $event A dispatcher event. <ide> * @return void <ide> public function controllerSpy($event) { <ide> } <ide> <ide> /** <del> * Attempt to render an error response for a given exception. <add> * Attempts to render an error response for a given exception. <ide> * <ide> * This method will attempt to use the configured exception renderer. <ide> * If that class does not exist, the built-in renderer will be used. <ide> protected function _handleError($exception) { <ide> } <ide> <ide> /** <del> * Create a request object with the configured options and parameters. <add> * Creates a request object with the configured options and parameters. <ide> * <ide> * @param string|array $url The URL <ide> * @param string $method The HTTP method <ide> protected function _buildRequest($url, $method, $data) { <ide> } <ide> <ide> /** <del> * Assert that the response status code is in the 2xx range. <add> * Fetches a view variable by name. <add> * <add> * If the view variable does not exist, null will be returned. <add> * <add> * @param string $name The view variable to get. <add> * @return mixed The view variable if set. <add> */ <add> public function viewVariable($name) { <add> if (empty($this->_controller->viewVars)) { <add> $this->fail('There are no view variables, perhaps you need to run a request?'); <add> } <add> if (isset($this->_controller->viewVars[$name])) { <add> return $this->_controller->viewVars[$name]; <add> } <add> return null; <add> } <add> <add>/** <add> * Asserts that the response status code is in the 2xx range. <ide> * <ide> * @return void <ide> */ <ide> public function assertResponseOk() { <ide> } <ide> <ide> /** <del> * Assert that the response status code is in the 4xx range. <add> * Asserts that the response status code is in the 4xx range. <ide> * <ide> * @return void <ide> */ <ide> public function assertResponseError() { <ide> } <ide> <ide> /** <del> * Assert that the response status code is in the 5xx range. <add> * Asserts that the response status code is in the 5xx range. <ide> * <ide> * @return void <ide> */ <ide> protected function _assertStatus($min, $max, $message) { <ide> } <ide> <ide> /** <del> * Assert that the Location header is correct. <add> * Asserts that the Location header is correct. <ide> * <ide> * @param string|array $url The url you expected the client to go to. This <ide> * can either be a string URL or an array compatible with Router::url() <ide> public function assertRedirect($url, $message = '') { <ide> } <ide> <ide> /** <del> * Assert response headers <add> * Asserts response headers <ide> * <ide> * @param string $header The header to check <ide> * @param string $content The content to check for. <ide> public function assertHeader($header, $content, $message = '') { <ide> } <ide> <ide> /** <del> * Assert content type <add> * Asserts content type <ide> * <ide> * @param string $type The content-type to check for. <ide> * @param string $message The failure message that will be appended to the generated message. <ide> public function assertContentType($type, $message = '') { <ide> } <ide> <ide> /** <del> * Assert content exists in the response body. <add> * Asserts content exists in the response body. <ide> * <ide> * @param string $content The content to check for. <ide> * @param string $message The failure message that will be appended to the generated message. <ide> public function assertResponseContains($content, $message = '') { <ide> } <ide> <ide> /** <del> * Assert that the search string was in the template name. <add> * Asserts that the search string was in the template name. <ide> * <ide> * @param string $content The content to check for. <ide> * @param string $message The failure message that will be appended to the generated message. <ide> public function assertTemplate($content, $message = '') { <ide> } <ide> <ide> /** <del> * Assert that the search string was in the layout name. <add> * Asserts that the search string was in the layout name. <ide> * <ide> * @param string $content The content to check for. <ide> * @param string $message The failure message that will be appended to the generated message. <ide> public function assertLayout($content, $message = '') { <ide> } <ide> <ide> /** <del> * Fetch a view variable by name. <del> * <del> * If the view variable does not exist null will be returned. <del> * <del> * @param string $name The view variable to get. <del> * @return mixed The view variable if set. <del> */ <del> public function viewVariable($name) { <del> if (empty($this->_controller->viewVars)) { <del> $this->fail('There are no view variables, perhaps you need to run a request?'); <del> } <del> if (isset($this->_controller->viewVars[$name])) { <del> return $this->_controller->viewVars[$name]; <del> } <del> return null; <del> } <del> <del>/** <del> * Assert session contents <add> * Asserts session contents <ide> * <ide> * @param string $expected The expected contents. <ide> * @param string $path The session data path. Uses Hash::get() compatible notation <ide> public function assertSession($expected, $path, $message = '') { <ide> } <ide> <ide> /** <del> * Assert cookie values <add> * Asserts cookie values <ide> * <ide> * @param string $expected The expected contents. <ide> * @param string $name The cookie name. <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function testAssertResponseStatusCodes() { <ide> <ide> $this->_response->statusCode(505); <ide> $this->assertResponseFailure(); <add> <add> $this->_response->statusCode(301); <add> $this->assertResponseCode(301); <ide> } <ide> <ide> /**
2
Ruby
Ruby
use redefine_method since baz is already defined
3e336f9ab70305386e941b2bed34e1dfac80a9f8
<ide><path>actionpack/test/fixtures/alternate_helpers/foo_helper.rb <ide> module FooHelper <del> def baz() end <add> redefine_method(:baz) {} <ide> end
1
Text
Text
use combinereducers like everywhere
5b1645ccebc81f3d4dda2565ce8d51f6972d01d2
<ide><path>docs/api/applyMiddleware.md <ide> Middleware is not baked into [`createStore`](createStore.md) and is not a fundam <ide> #### Example: Using Thunk Middleware for Async Actions <ide> <ide> ```js <del>import { createStore, applyMiddleware } from 'redux'; <add>import { createStore, combineReducers, applyMiddleware } from 'redux'; <ide> import thunk from 'redux-thunk'; <del>import sandwiches from './reducers'; <add>import * as reducers from './reducers'; <ide> <ide> // applyMiddleware supercharges createStore with middleware: <ide> let createStoreWithMiddleware = applyMiddleware(thunk)(createStore); <ide> <ide> // We can use it exactly like “vanilla” createStore. <del>let store = createStoreWithMiddleware(sandwiches); <add>let reducer = combineReducers(reducers); <add>let store = createStoreWithMiddleware(reducer); <ide> <ide> function fetchSecretSauce() { <ide> return fetch('https://www.google.com/search?q=secret+sauce');
1
Python
Python
add mixed precision support to transformer
f8ec01aec2535993881b018a84be4545ea64e7a7
<ide><path>official/transformer/model/model_utils.py <ide> <ide> import math <ide> <add>import numpy as np <ide> import tensorflow as tf <ide> <del>_NEG_INF = -1e9 <add># Very low numbers to represent -infinity. We do not actually use -Inf, since we <add># want to be able to multiply these values by zero to get zero. (-Inf * 0 = NaN) <add>_NEG_INF_FP32 = -1e9 <add>_NEG_INF_FP16 = np.finfo(np.float16).min <ide> <ide> <ide> def get_position_encoding( <ide> def get_position_encoding( <ide> Returns: <ide> Tensor with shape [length, hidden_size] <ide> """ <add> # We compute the positional encoding in float32 even if the model uses <add> # float16, as many of the ops used, like log and exp, are numerically unstable <add> # in float16. <ide> position = tf.cast(tf.range(length), tf.float32) <ide> num_timescales = hidden_size // 2 <ide> log_timescale_increment = ( <ide> def get_position_encoding( <ide> return signal <ide> <ide> <del>def get_decoder_self_attention_bias(length): <add>def get_decoder_self_attention_bias(length, dtype=tf.float32): <ide> """Calculate bias for decoder that maintains model's autoregressive property. <ide> <ide> Creates a tensor that masks out locations that correspond to illegal <ide> def get_decoder_self_attention_bias(length): <ide> <ide> Args: <ide> length: int length of sequences in batch. <add> dtype: The dtype of the return value. <ide> <ide> Returns: <ide> float tensor of shape [1, 1, length, length] <ide> """ <add> neg_inf = _NEG_INF_FP16 if dtype == tf.float16 else _NEG_INF_FP32 <ide> with tf.name_scope("decoder_self_attention_bias"): <del> valid_locs = tf.linalg.band_part(tf.ones([length, length]), -1, 0) <add> valid_locs = tf.linalg.band_part(tf.ones([length, length], dtype=dtype), <add> -1, 0) <ide> valid_locs = tf.reshape(valid_locs, [1, 1, length, length]) <del> decoder_bias = _NEG_INF * (1.0 - valid_locs) <add> decoder_bias = neg_inf * (1.0 - valid_locs) <ide> return decoder_bias <ide> <ide> <del>def get_padding(x, padding_value=0): <add>def get_padding(x, padding_value=0, dtype=tf.float32): <ide> """Return float tensor representing the padding values in x. <ide> <ide> Args: <ide> x: int tensor with any shape <ide> padding_value: int value that <add> dtype: The dtype of the return value. <ide> <ide> Returns: <ide> float tensor with same shape as x containing values 0 or 1. <ide> 0 -> non-padding, 1 -> padding <ide> """ <ide> with tf.name_scope("padding"): <del> return tf.cast(tf.equal(x, padding_value), tf.float32) <add> return tf.cast(tf.equal(x, padding_value), dtype) <ide> <ide> <ide> def get_padding_bias(x): <ide> def get_padding_bias(x): <ide> """ <ide> with tf.name_scope("attention_bias"): <ide> padding = get_padding(x) <del> attention_bias = padding * _NEG_INF <add> attention_bias = padding * _NEG_INF_FP32 <ide> attention_bias = tf.expand_dims( <ide> tf.expand_dims(attention_bias, axis=1), axis=1) <ide> return attention_bias <ide><path>official/transformer/v2/attention_layer.py <ide> import tensorflow as tf <ide> <ide> <add>def _float32_softmax(logits, name=None): <add> """Computes a softmax activation in float32. <add> <add> When training a model using float16, softmax is still done in float32 for <add> numeric stability. <add> <add> Args: <add> logits: A tensor, with any shape accepted by `tf.nn.softmax`. <add> <add> Returns: <add> A tensor with the same dtype as `logits`. <add> """ <add> input_dtype = logits.dtype <add> logits = tf.cast(logits, tf.float32) <add> output = tf.nn.softmax(logits, name=name) <add> return tf.cast(output, input_dtype) <add> <add> <ide> class Attention(tf.keras.layers.Layer): <ide> """Multi-headed attention layer.""" <ide> <ide> def call(self, x, y, bias, training, cache=None): <ide> <ide> if cache is not None: <ide> # Combine cached keys and values with new keys and values. <del> k = tf.concat([cache["k"], k], axis=1) <del> v = tf.concat([cache["v"], v], axis=1) <add> k = tf.concat([tf.cast(cache["k"], k.dtype), k], axis=1) <add> v = tf.concat([tf.cast(cache["v"], k.dtype), v], axis=1) <ide> <ide> # Update cache <ide> cache["k"] = k <ide> def call(self, x, y, bias, training, cache=None): <ide> # Calculate dot product attention <ide> logits = tf.matmul(q, k, transpose_b=True) <ide> logits += bias <del> weights = tf.nn.softmax(logits, name="attention_weights") <add> weights = _float32_softmax(logits, name="attention_weights") <ide> if training: <ide> weights = tf.nn.dropout(weights, rate=self.attention_dropout) <ide> attention_output = tf.matmul(weights, v) <ide><path>official/transformer/v2/misc.py <ide> def define_transformer_flags(): <ide> intra_op=False, <ide> synthetic_data=True, <ide> max_train_steps=False, <del> dtype=False, <add> dtype=True, <add> loss_scale=True, <ide> all_reduce_alg=True, <ide> enable_xla=True <ide> ) <ide><path>official/transformer/v2/transformer.py <ide> def call(self, inputs, training): <ide> returns a dictionary { <ide> outputs: [batch_size, decoded length] <ide> scores: [batch_size, float]} <add> Even when float16 is used, the output tensor(s) are always float32. <ide> """ <ide> if len(inputs) == 2: <ide> inputs, targets = inputs[0], inputs[1] <ide> def encode(self, inputs, attention_bias, training): <ide> # Prepare inputs to the layer stack by adding positional encodings and <ide> # applying dropout. <ide> embedded_inputs = self.embedding_softmax_layer(inputs) <add> embedded_inputs = tf.cast(embedded_inputs, self.params["dtype"]) <ide> inputs_padding = model_utils.get_padding(inputs) <add> attention_bias = tf.cast(attention_bias, self.params["dtype"]) <ide> <ide> with tf.name_scope("add_pos_encoding"): <ide> length = tf.shape(embedded_inputs)[1] <ide> pos_encoding = model_utils.get_position_encoding( <ide> length, self.params["hidden_size"]) <add> pos_encoding = tf.cast(pos_encoding, self.params["dtype"]) <ide> encoder_inputs = embedded_inputs + pos_encoding <ide> <ide> if training: <ide> def decode(self, targets, encoder_outputs, attention_bias, training): <ide> # Prepare inputs to decoder layers by shifting targets, adding positional <ide> # encoding and applying dropout. <ide> decoder_inputs = self.embedding_softmax_layer(targets) <add> decoder_inputs = tf.cast(decoder_inputs, self.params['dtype']) <add> attention_bias = tf.cast(attention_bias, self.params["dtype"]) <ide> with tf.name_scope("shift_targets"): <ide> # Shift targets to the right, and remove the last element <ide> decoder_inputs = tf.pad(decoder_inputs, <ide> [[0, 0], [1, 0], [0, 0]])[:, :-1, :] <ide> with tf.name_scope("add_pos_encoding"): <ide> length = tf.shape(decoder_inputs)[1] <del> decoder_inputs += model_utils.get_position_encoding( <add> pos_encoding = model_utils.get_position_encoding( <ide> length, self.params["hidden_size"]) <add> pos_encoding = tf.cast(pos_encoding, self.params["dtype"]) <add> decoder_inputs += pos_encoding <ide> if training: <ide> decoder_inputs = tf.nn.dropout( <ide> decoder_inputs, rate=self.params["layer_postprocess_dropout"]) <ide> <ide> # Run values <ide> decoder_self_attention_bias = model_utils.get_decoder_self_attention_bias( <del> length) <add> length, dtype=self.params['dtype']) <ide> outputs = self.decoder_stack( <ide> decoder_inputs, <ide> encoder_outputs, <ide> decoder_self_attention_bias, <ide> attention_bias, <ide> training=training) <ide> logits = self.embedding_softmax_layer(outputs, mode="linear") <add> logits = tf.cast(logits, tf.float32) <ide> return logits <ide> <ide> def _get_symbols_to_logits_fn(self, max_decode_length, training): <ide> def symbols_to_logits_fn(ids, i, cache): <ide> <ide> def predict(self, encoder_outputs, encoder_decoder_attention_bias, training): <ide> """Return predicted sequence.""" <add> # Currently, we always do prediction in float32. <add> # TODO(reedwm): Add float16 support. <add> encoder_outputs = tf.cast(encoder_outputs, tf.float32) <ide> batch_size = tf.shape(encoder_outputs)[0] <ide> input_length = tf.shape(encoder_outputs)[1] <ide> max_decode_length = input_length + self.params["extra_decode_length"] <ide> def __init__(self, hidden_size): <ide> <ide> def build(self, input_shape): <ide> """Builds the layer.""" <add> # Passing experimental_autocast=False causes these variables to not be <add> # automatically casted to fp16 when mixed precision is used. Since we use <add> # float32 in call() for numeric stability, we do not want variables to be <add> # casted to fp16. <ide> self.scale = self.add_weight( <ide> "layer_norm_scale", <ide> shape=[self.hidden_size], <ide> dtype="float32", <del> initializer=tf.ones_initializer()) <add> initializer=tf.ones_initializer(), <add> experimental_autocast=False) <ide> self.bias = self.add_weight( <ide> "layer_norm_bias", <ide> shape=[self.hidden_size], <ide> dtype="float32", <del> initializer=tf.zeros_initializer()) <add> initializer=tf.zeros_initializer(), <add> experimental_autocast=False) <ide> super(LayerNormalization, self).build(input_shape) <ide> <ide> def get_config(self): <ide> def get_config(self): <ide> } <ide> <ide> def call(self, x, epsilon=1e-6): <add> input_dtype = x.dtype <add> if input_dtype == tf.float16: <add> x = tf.cast(x, tf.float32) <ide> mean = tf.reduce_mean(x, axis=[-1], keepdims=True) <ide> variance = tf.reduce_mean(tf.square(x - mean), axis=[-1], keepdims=True) <ide> norm_x = (x - mean) * tf.math.rsqrt(variance + epsilon) <del> return norm_x * self.scale + self.bias <add> return tf.cast(norm_x * self.scale + self.bias, input_dtype) <ide> <ide> <ide> class PrePostProcessingWrapper(tf.keras.layers.Layer): <ide><path>official/transformer/v2/transformer_main.py <ide> def __init__(self, flags_obj): <ide> params["use_synthetic_data"] = flags_obj.use_synthetic_data <ide> params["batch_size"] = flags_obj.batch_size or params["default_batch_size"] <ide> params["repeat_dataset"] = None <add> params["dtype"] = flags_core.get_tf_dtype(flags_obj) <ide> <ide> def train(self): <ide> """Trains the model.""" <ide> def _create_optimizer(self): <ide> params["optimizer_adam_beta1"], <ide> params["optimizer_adam_beta2"], <ide> epsilon=params["optimizer_adam_epsilon"]) <add> if params["dtype"] == tf.float16: <add> opt = tf.keras.mixed_precision.experimental.LossScaleOptimizer( <add> opt, loss_scale=flags_core.get_loss_scale(self.flags_obj, <add> default_for_fp16="dynamic")) <ide> return opt <ide> <ide> <ide> def _ensure_dir(log_dir): <ide> def main(_): <ide> flags_obj = flags.FLAGS <ide> with logger.benchmark_context(flags_obj): <add> if flags_core.get_tf_dtype(flags_obj) == 'float16': <add> policy = tf.keras.mixed_precision.experimental.Policy( <add> 'infer_float32_vars') <add> tf.keras.mixed_precision.experimental.set_policy(policy) <add> <ide> task = TransformerTask(flags_obj) <ide> if flags_obj.mode == "train": <ide> task.train() <ide><path>official/transformer/v2/transformer_main_test.py <ide> def setUp(self): <ide> FLAGS.batch_size = 8 <ide> FLAGS.num_gpus = 1 <ide> FLAGS.distribution_strategy = "off" <add> FLAGS.dtype = "fp32" <ide> self.model_dir = FLAGS.model_dir <ide> self.temp_dir = temp_dir <ide> self.vocab_file = os.path.join(temp_dir, "vocab") <ide> self.vocab_size = misc.get_model_params(FLAGS.param_set, 0)["vocab_size"] <ide> self.bleu_source = os.path.join(temp_dir, "bleu_source") <ide> self.bleu_ref = os.path.join(temp_dir, "bleu_ref") <add> self.orig_policy = tf.keras.mixed_precision.experimental.global_policy() <add> <add> def tearDown(self): <add> tf.keras.mixed_precision.experimental.set_policy(self.orig_policy) <ide> <ide> def _assert_exists(self, filepath): <ide> self.assertTrue(os.path.exists(filepath)) <ide> def test_train_2_gpu(self): <ide> t = tm.TransformerTask(FLAGS) <ide> t.train() <ide> <add> def test_train_2_gpu_fp16(self): <add> FLAGS.distribution_strategy = "mirrored" <add> FLAGS.num_gpus = 2 <add> FLAGS.param_set = "base" <add> FLAGS.dtype = "fp16" <add> policy = tf.keras.mixed_precision.experimental.Policy( <add> 'infer_float32_vars') <add> tf.keras.mixed_precision.experimental.set_policy(policy) <add> t = tm.TransformerTask(FLAGS) <add> t.train() <add> <ide> def _prepare_files_and_flags(self, *extra_flags): <ide> # Make log dir. <ide> if not os.path.exists(self.temp_dir): <ide> def test_predict(self): <ide> t = tm.TransformerTask(FLAGS) <ide> t.predict() <ide> <add> def test_predict_fp16(self): <add> self._prepare_files_and_flags("--dtype=fp16") <add> policy = tf.keras.mixed_precision.experimental.Policy( <add> 'infer_float32_vars') <add> tf.keras.mixed_precision.experimental.set_policy(policy) <add> t = tm.TransformerTask(FLAGS) <add> t.predict() <add> <ide> def test_eval(self): <ide> self._prepare_files_and_flags() <ide> t = tm.TransformerTask(FLAGS) <ide><path>official/transformer/v2/transformer_test.py <ide> def setUp(self): <ide> params["vocab_size"] = 41 <ide> params["extra_decode_length"] = 2 <ide> params["beam_size"] = 3 <add> params["dtype"] = tf.float32 <ide> <ide> def test_create_model_train(self): <ide> model = transformer.create_model(self.params, True)
7
Ruby
Ruby
replace guides.ror.org/v4.2.0 with guides.ror.org
902da271f54c9f3ceec93c66c1d9b4f7856c8f4d
<ide><path>activejob/lib/active_job/queue_adapters/inline_adapter.rb <ide> def enqueue(job) #:nodoc: <ide> end <ide> <ide> def enqueue_at(*) #:nodoc: <del> raise NotImplementedError.new("Use a queueing backend to enqueue jobs in the future. Read more at http://guides.rubyonrails.org/v4.2.0/active_job_basics.html") <add> raise NotImplementedError.new("Use a queueing backend to enqueue jobs in the future. Read more at http://guides.rubyonrails.org/active_job_basics.html") <ide> end <ide> end <ide> end
1
Javascript
Javascript
fix broken link in module.html
e9639ee7e8705516e3b4b9ba7ee19d8e210afa9a
<ide><path>tools/doc/type-parser.js <ide> const customTypesMap = { <ide> 'module': 'modules.html#modules_the_module_object', <ide> <ide> 'module.SourceMap': <del> 'modules_module.html#modules_module_class_module_sourcemap', <add> 'module.html#module_class_module_sourcemap', <ide> <ide> 'require': 'modules.html#modules_require_id', <ide>
1
Ruby
Ruby
use the right indentation
5487f627413e77cfa7f0d6cc2fe9c214ffb299ba
<ide><path>actionview/lib/action_view/layouts.rb <ide> def inherited(klass) # :nodoc: <ide> # This module is mixed in if layout conditions are provided. This means <ide> # that if no layout conditions are used, this method is not used <ide> module LayoutConditions # :nodoc: <del> private <add> private <ide> <ide> # Determines whether the current action has a layout definition by <ide> # checking the action name against the :only and :except conditions
1
Ruby
Ruby
use strip_heredoc where possible
a4f812f512cf83f5330562bcdf0b2a4199179466
<ide><path>railties/lib/rails/generators/app_base.rb <ide> def set_default_accessors! <ide> <ide> def database_gemfile_entry <ide> options[:skip_active_record] ? "" : <del> <<-GEMFILE.gsub(/^ {12}/, '').strip <add> <<-GEMFILE.strip_heredoc.chomp <ide> # Use #{options[:database]} as the database for ActiveRecord <ide> gem '#{gem_for_database}' <ide> GEMFILE <ide> def assets_gemfile_entry <ide> return if options[:skip_sprockets] <ide> <ide> gemfile = if options.dev? || options.edge? <del> <<-GEMFILE.gsub(/^ {12}/, '') <add> <<-GEMFILE.strip_heredoc <ide> # Use edge version of sprockets-rails <ide> gem 'sprockets-rails', github: 'rails/sprockets-rails' <ide> <ide> # Use SCSS for stylesheets <del> gem 'sass-rails', github: 'rails/sass-rails' <add> gem 'sass-rails', github: 'rails/sass-rails' <ide> <ide> # Use Uglifier as compressor for JavaScript assets <ide> gem 'uglifier', '~> 1.3' <ide> GEMFILE <ide> else <del> <<-GEMFILE.gsub(/^ {12}/, '') <add> <<-GEMFILE.strip_heredoc <ide> # Use SCSS for stylesheets <del> gem 'sass-rails', '~> 4.0.0.beta1' <add> gem 'sass-rails', '~> 4.0.0.beta1' <ide> <ide> # Use Uglifier as compressor for JavaScript assets <ide> gem 'uglifier', '~> 1.3' <ide> GEMFILE <ide> end <ide> <ide> if options[:skip_javascript] <del> gemfile += <<-GEMFILE.gsub(/^ {12}/, '') <add> gemfile += <<-GEMFILE <ide> #{coffee_gemfile_entry} <ide> #{javascript_runtime_gemfile_entry} <ide> GEMFILE <ide> end <ide> <del> gemfile.strip_heredoc.gsub(/^[ \t]*$/, '') <add> gemfile.gsub(/^[ \t]+/, '') <ide> end <ide> <ide> def coffee_gemfile_entry <del> gemfile = if options.dev? || options.edge? <del> <<-GEMFILE.gsub(/^ {12}/, '') <add> if options.dev? || options.edge? <add> <<-GEMFILE <ide> # Use CoffeeScript for .js.coffee assets and views <ide> gem 'coffee-rails', github: 'rails/coffee-rails' <ide> GEMFILE <ide> else <del> <<-GEMFILE.gsub(/^ {12}/, '') <add> <<-GEMFILE <ide> # Use CoffeeScript for .js.coffee assets and views <ide> gem 'coffee-rails', '~> 4.0.0.beta1' <ide> GEMFILE <ide> end <del> <del> gemfile.strip_heredoc.gsub(/^[ \t]*$/, '') <ide> end <ide> <ide> def javascript_gemfile_entry <ide> unless options[:skip_javascript] <del> <<-GEMFILE.gsub(/^ {12}/, '').strip_heredoc <add> <<-GEMFILE.gsub(/^[ \t]+/, '') <ide> #{coffee_gemfile_entry} <ide> #{javascript_runtime_gemfile_entry} <ide> # Use #{options[:javascript]} as the JavaScript library <ide> def javascript_runtime_gemfile_entry <ide> else <ide> "# gem 'therubyracer', platforms: :ruby" <ide> end <del> <<-GEMFILE.gsub(/^ {10}/, '') <add> <<-GEMFILE <ide> # See https://github.com/sstephenson/execjs#readme for more supported runtimes <ide> #{runtime} <ide> GEMFILE
1
Go
Go
add tests for case a) and d) in
6d23c3c57a733436d902b7883f2f0b00846df9e2
<ide><path>integration-cli/docker_cli_pull_test.go <ide> func (s *DockerHubPullSuite) TestPullClientDisconnect(c *check.C) { <ide> _, err = s.CmdWithError("inspect", repoName) <ide> c.Assert(err, checker.NotNil, check.Commentf("image was pulled after client disconnected")) <ide> } <add> <add>func (s *DockerRegistryAuthSuite) TestPullNoCredentialsNotFound(c *check.C) { <add> // we don't care about the actual image, we just want to see image not found <add> // because that means v2 call returned 401 and we fell back to v1 which usually <add> // gives a 404 (in this case the test registry doesn't handle v1 at all) <add> out, _, err := dockerCmdWithError("pull", privateRegistryURL+"/busybox") <add> c.Assert(err, check.NotNil, check.Commentf(out)) <add> c.Assert(out, checker.Contains, "Error: image busybox not found") <add>} <ide><path>integration-cli/docker_cli_push_test.go <ide> func (s *DockerRegistryAuthSuite) TestPushNoCredentialsNoRetry(c *check.C) { <ide> c.Assert(out, check.Not(checker.Contains), "Retrying") <ide> c.Assert(out, checker.Contains, "no basic auth credentials") <ide> } <add> <add>// This may be flaky but it's needed not to regress on unauthorized push, see #21054 <add>func (s *DockerSuite) TestPushToCentralRegistryUnauthorized(c *check.C) { <add> testRequires(c, Network) <add> repoName := "test/busybox" <add> dockerCmd(c, "tag", "busybox", repoName) <add> out, _, err := dockerCmdWithError("push", repoName) <add> c.Assert(err, check.NotNil, check.Commentf(out)) <add> c.Assert(out, checker.Contains, "unauthorized: access to the requested resource is not authorized") <add>}
2
Javascript
Javascript
provide rtl support for swipeablerow
7e5fc179839d1f0e5b82df307e9a0ef19f2874b1
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableRow.js <ide> const {PropTypes} = React; <ide> <ide> const emptyFunction = require('fbjs/lib/emptyFunction'); <ide> <add>const I18nManager = require('NativeModules').I18nManager || {}; <add>const IS_RTL = I18nManager.isRTL; <add> <ide> // NOTE: Eventually convert these consts to an input object of configurations <ide> <ide> // Position of the left of the swipable item when closed <ide> const SwipeableRow = React.createClass({ <ide> }, <ide> <ide> _isSwipingRightFromClosed(gestureState: Object): boolean { <del> return this._previousLeft === CLOSED_LEFT_POSITION && gestureState.dx > 0; <add> const gestureStateDx = IS_RTL ? -gestureState.dx : gestureState.dx; <add> return this._previousLeft === CLOSED_LEFT_POSITION && gestureStateDx > 0; <ide> }, <ide> <ide> _swipeFullSpeed(gestureState: Object): void { <ide> const SwipeableRow = React.createClass({ <ide> * swiping is available, but swiping right does not do anything <ide> * functionally. <ide> */ <add> const gestureStateDx = IS_RTL ? -gestureState.dx : gestureState.dx; <ide> return ( <ide> this._isSwipingRightFromClosed(gestureState) && <del> gestureState.dx > RIGHT_SWIPE_THRESHOLD <add> gestureStateDx > RIGHT_SWIPE_THRESHOLD <ide> ); <ide> }, <ide> <ide> const SwipeableRow = React.createClass({ <ide> }, <ide> <ide> _animateToOpenPosition(): void { <del> this._animateTo(-this.props.maxSwipeDistance); <add> const maxSwipeDistance = IS_RTL ? -this.props.maxSwipeDistance : this.props.maxSwipeDistance; <add> this._animateTo(-maxSwipeDistance); <ide> }, <ide> <ide> _animateToClosedPosition(duration: number = SWIPE_DURATION): void { <ide> const SwipeableRow = React.createClass({ <ide> * When swiping right, we want to bounce back past closed position on release <ide> * so users know they should swipe right to get content. <ide> */ <add> const swipeBounceBackDistance = IS_RTL ? -RIGHT_SWIPE_BOUNCE_BACK_DISTANCE : RIGHT_SWIPE_BOUNCE_BACK_DISTANCE; <ide> this._animateTo( <del> -RIGHT_SWIPE_BOUNCE_BACK_DISTANCE, <add> -swipeBounceBackDistance, <ide> duration, <ide> this._animateToClosedPositionDuringBounce, <ide> ); <ide> const SwipeableRow = React.createClass({ <ide> }, <ide> <ide> _handlePanResponderEnd(event: Object, gestureState: Object): void { <del> const horizontalDistance = gestureState.dx; <del> <add> const horizontalDistance = IS_RTL ? -gestureState.dx : gestureState.dx; <ide> if (this._isSwipingRightFromClosed(gestureState)) { <ide> this.props.onOpen(); <ide> this._animateBounceBack(RIGHT_SWIPE_BOUNCE_BACK_DURATION);
1
Text
Text
fix broken link
74f50df250ba08c47d90c53bc2d590c43d9c95fe
<ide><path>docs/configuration/index.md <ide> Chart type determines the main type of the chart. <ide> <ide> ### data <ide> <del>See [Data Structures](../general/data-structures) for details. <add>See [Data Structures](../general/data-structures.md) for details. <ide> <ide> ### options <ide>
1
Python
Python
ignore none in config_list
567a14be00a4638b0dd822909ac50c27ecf979f3
<ide><path>scipy_distutils/misc_util.py <ide> def get_frame(level=0): <ide> def merge_config_dicts(config_list): <ide> result = default_config_dict() <ide> for d in config_list: <add> if not d: continue <ide> name = d.get('name',None) <ide> if name is not None: <ide> result['name'] = name <ide> break <ide> for d in config_list: <add> if not d: continue <ide> for key in list_keys: <ide> result[key].extend(d.get(key,[])) <ide> for key in dict_keys:
1
PHP
PHP
remove old property
9c48671932c6ee631b5c2a6ee6513582062c5b92
<ide><path>src/Illuminate/Notifications/Notification.php <ide> class Notification <ide> */ <ide> public $notifiables; <ide> <del> /** <del> * The channels that the notification should be sent through. <del> */ <del> public $via = []; <del> <ide> /** <ide> * The name of the application sending the notification. <ide> *
1
Javascript
Javascript
add count() method to reactchildren
1aa9cc6a8b33b6b9f9fcfee12ed812dbae003be7
<ide><path>src/utils/ReactChildren.js <ide> function mapChildren(children, func, context) { <ide> return mapResult; <ide> } <ide> <add>/** <add>* Count the number of children that are typically specified as <add>* `props.children`. <add>*/ <add> <add>function forEachSingleChildDummy(traverseContext, child, name, i) { <add> return null; <add>} <add> <add>function countChildren(children, context) { <add> var numberOfChildren = traverseAllChildren(children, forEachSingleChildDummy, <add> null); <add> return numberOfChildren; <add>} <add> <ide> var ReactChildren = { <ide> forEach: forEachChildren, <del> map: mapChildren <add> map: mapChildren, <add> count: countChildren <ide> }; <ide> <ide> module.exports = ReactChildren; <ide><path>src/utils/__tests__/ReactChildren-test.js <ide> describe('ReactChildren', function() { <ide> expect(console.warn.calls.length).toEqual(1); <ide> expect(mapped).toEqual({'.$something': zero}); <ide> }); <add> <add> it('should return 0 for null children', function() { <add> var numberOfChildren = ReactChildren.count(null); <add> expect(numberOfChildren).toBe(0); <add> }); <add> <add> it('should return 0 for undefined children', function() { <add> var numberOfChildren = ReactChildren.count(undefined); <add> expect(numberOfChildren).toBe(0); <add> }); <add> <add> it('should return 1 for single child', function() { <add> var simpleKid = <span key="simple" />; <add> var instance = <div>{simpleKid}</div>; <add> var numberOfChildren = ReactChildren.count(instance.props.children); <add> expect(numberOfChildren).toBe(1); <add> }); <add> <add> it('should count the number of children in flat structure', function() { <add> var zero = <div key="keyZero" />; <add> var one = null; <add> var two = <div key="keyTwo" />; <add> var three = null; <add> var four = <div key="keyFour" />; <add> <add> var instance = ( <add> <div> <add> {zero} <add> {one} <add> {two} <add> {three} <add> {four} <add> </div> <add> ); <add> var numberOfChildren = ReactChildren.count(instance.props.children); <add> expect(numberOfChildren).toBe(5); <add> }); <add> <add> it('should count the number of children in nested structure', function() { <add> var zero = <div key="keyZero" />; <add> var one = null; <add> var two = <div key="keyTwo" />; <add> var three = null; <add> var four = <div key="keyFour" />; <add> var five = <div key="keyFiveInner" />; <add> // five is placed into a JS object with a key that is joined to the <add> // component key attribute. <add> // Precedence is as follows: <add> // 1. If grouped in an Object, the object key combined with `key` prop <add> // 2. If grouped in an Array, the `key` prop, falling back to array index <add> <add> var instance = ( <add> <div>{ <add> [{ <add> firstHalfKey: [zero, one, two], <add> secondHalfKey: [three, four], <add> keyFive: five <add> }] <add> }</div> <add> ); <add> var numberOfChildren = ReactChildren.count(instance.props.children); <add> expect(numberOfChildren).toBe(6); <add> }); <ide> }); <ide><path>src/utils/traverseAllChildren.js <ide> var traverseAllChildrenImpl = <ide> * @param {?*} children Children tree object. <ide> * @param {!function} callback To invoke upon traversing each child. <ide> * @param {?*} traverseContext Context for traversal. <add> * @return {!number} The number of children in this subtree. <ide> */ <ide> function traverseAllChildren(children, callback, traverseContext) { <ide> if (children !== null && children !== undefined) { <del> traverseAllChildrenImpl(children, '', 0, callback, traverseContext); <add> return traverseAllChildrenImpl(children, '', 0, callback, traverseContext); <add> } <add> else { <add> return 0; <ide> } <ide> } <ide>
3
Javascript
Javascript
expand quickstart widget with cuda 11.1 and 11.2
3e5bd5055e8cd2198f4432fa765be11bb2f47ddd
<ide><path>website/src/widgets/quickstart-install.js <ide> const CUDA = { <ide> '10.1': 'cuda101', <ide> '10.2': 'cuda102', <ide> '11.0': 'cuda110', <add> '11.1': 'cuda111', <add> '11.2': 'cuda112', <ide> } <ide> const LANG_EXTRAS = ['ja'] // only for languages with models <ide>
1
Java
Java
improve error handling of user provided observers
38e9e3fbf8e9e705b2ba23443c6976ac46d9fb8e
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> import java.util.concurrent.CountDownLatch; <ide> import java.util.concurrent.Future; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicInteger; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.junit.Before; <ide> import rx.operators.OperationDefer; <ide> import rx.operators.OperationDematerialize; <ide> import rx.operators.OperationFilter; <del>import rx.operators.OperationTake; <del>import rx.operators.OperationTakeWhile; <del>import rx.operators.OperationWhere; <ide> import rx.operators.OperationMap; <ide> import rx.operators.OperationMaterialize; <ide> import rx.operators.OperationMerge; <ide> import rx.operators.OperationScan; <ide> import rx.operators.OperationSkip; <ide> import rx.operators.OperationSynchronize; <add>import rx.operators.OperationTake; <ide> import rx.operators.OperationTakeLast; <add>import rx.operators.OperationTakeWhile; <ide> import rx.operators.OperationToObservableFuture; <ide> import rx.operators.OperationToObservableIterable; <ide> import rx.operators.OperationToObservableList; <ide> import rx.operators.OperationToObservableSortedList; <add>import rx.operators.OperationWhere; <ide> import rx.operators.OperationZip; <ide> import rx.operators.OperatorGroupBy; <ide> import rx.operators.OperatorTakeUntil; <ide> import rx.operators.OperatorToIterator; <ide> import rx.plugins.RxJavaErrorHandler; <ide> import rx.plugins.RxJavaPlugins; <add>import rx.subscriptions.BooleanSubscription; <ide> import rx.subscriptions.Subscriptions; <ide> import rx.util.AtomicObservableSubscription; <ide> import rx.util.AtomicObserver; <ide> public class Observable<T> { <ide> <ide> private final Func1<Observer<T>, Subscription> onSubscribe; <del> private final boolean isTrusted; <ide> <ide> protected Observable() { <del> this(null, false); <add> this(null); <ide> } <ide> <ide> /** <ide> protected Observable() { <ide> * {@link Func1} to be executed when {@link #subscribe(Observer)} is called. <ide> */ <ide> protected Observable(Func1<Observer<T>, Subscription> onSubscribe) { <del> this(onSubscribe, false); <del> } <del> <del> /** <del> * @param onSubscribe <del> * {@link Func1} to be executed when {@link #subscribe(Observer)} is called. <del> * @param isTrusted <del> * boolean true if the <code>onSubscribe</code> function is guaranteed to conform to the correct contract and thus shortcuts can be taken. <del> */ <del> private Observable(Func1<Observer<T>, Subscription> onSubscribe, boolean isTrusted) { <ide> this.onSubscribe = onSubscribe; <del> this.isTrusted = isTrusted; <ide> } <ide> <ide> /** <ide> public Subscription subscribe(Observer<T> observer) { <ide> // the subscribe function can also be overridden but generally that's not the appropriate approach so I won't mention that in the exception <ide> } <ide> try { <del> if (isTrusted) { <add> /** <add> * See https://github.com/Netflix/RxJava/issues/216 for discussion on "Guideline 6.4: Protect calls to user code from within an operator" <add> */ <add> if (observer.getClass().getPackage().getName().startsWith("rx")) { <ide> Subscription s = onSubscribe.call(observer); <ide> if (s == null) { <ide> // this generally shouldn't be the case on a 'trusted' onSubscribe but in case it happens <ide> public Subscription call(Observer<T> t1) { <ide> return Subscriptions.empty(); <ide> } <ide> <del> }, true); <add> }); <ide> } <ide> } <ide> <ide> public Subscription call(Observer<T> observer) { <ide> return Subscriptions.empty(); <ide> } <ide> <del> }, true); <add> }); <ide> } <ide> <ide> } <ide> public static <T> Observable<T> create(Func1<Observer<T>, Subscription> func) { <ide> return new Observable<T>(func); <ide> } <ide> <del> /* <del> * Private version that creates a 'trusted' Observable to allow performance optimizations. <del> */ <del> private static <T> Observable<T> _create(Func1<Observer<T>, Subscription> func) { <del> return new Observable<T>(func, true); <del> } <del> <ide> /** <ide> * Creates an Observable that will execute the given function when a {@link Observer} subscribes to it. <ide> * <p> <ide> public static <T> Observable<T> error(Exception exception) { <ide> * @return an Observable that emits only those items in the original Observable that the filter evaluates as true <ide> */ <ide> public static <T> Observable<T> filter(Observable<T> that, Func1<T, Boolean> predicate) { <del> return _create(OperationFilter.filter(that, predicate)); <add> return create(OperationFilter.filter(that, predicate)); <ide> } <ide> <ide> /** <ide> public Boolean call(T t1) { <ide> * Filters an Observable by discarding any of its emissions that do not meet some test. <ide> * <p> <ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/filter.png"> <del> * <add> * <ide> * @param that <ide> * the Observable to filter <ide> * @param predicate <ide> * a function that evaluates the items emitted by the source Observable, returning <code>true</code> if they pass the filter <ide> * @return an Observable that emits only those items in the original Observable that the filter evaluates as true <ide> */ <ide> public static <T> Observable<T> where(Observable<T> that, Func1<T, Boolean> predicate) { <del> return _create(OperationWhere.where(that, predicate)); <add> return create(OperationWhere.where(that, predicate)); <ide> } <ide> <ide> /** <ide> public static Observable<Integer> range(int start, int count) { <ide> * @return the observable sequence whose observers trigger an invocation of the given observable factory function. <ide> */ <ide> public static <T> Observable<T> defer(Func0<Observable<T>> observableFactory) { <del> return _create(OperationDefer.defer(observableFactory)); <add> return create(OperationDefer.defer(observableFactory)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> defer(Object observableFactory) { <ide> @SuppressWarnings("rawtypes") <ide> final FuncN _f = Functions.from(observableFactory); <ide> <del> return _create(OperationDefer.defer(new Func0<Observable<T>>() { <add> return create(OperationDefer.defer(new Func0<Observable<T>>() { <ide> <ide> @Override <ide> @SuppressWarnings("unchecked") <ide> public Boolean call(T args) { <ide> * in the sequence emitted by the source Observable <ide> */ <ide> public static <T, R> Observable<R> map(Observable<T> sequence, Func1<T, R> func) { <del> return _create(OperationMap.map(sequence, func)); <add> return create(OperationMap.map(sequence, func)); <ide> } <ide> <ide> /** <ide> public R call(T t1) { <ide> * the Observables obtained from this transformation <ide> */ <ide> public static <T, R> Observable<R> mapMany(Observable<T> sequence, Func1<T, Observable<R>> func) { <del> return _create(OperationMap.mapMany(sequence, func)); <add> return create(OperationMap.mapMany(sequence, func)); <ide> } <ide> <ide> /** <ide> public R call(T t1) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229453(v=VS.103).aspx">MSDN: Observable.Materialize</a> <ide> */ <ide> public static <T> Observable<Notification<T>> materialize(final Observable<T> sequence) { <del> return _create(OperationMaterialize.materialize(sequence)); <add> return create(OperationMaterialize.materialize(sequence)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<Notification<T>> materialize(final Observable<T> se <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229047(v=vs.103).aspx">MSDN: Observable.Dematerialize</a> <ide> */ <ide> public static <T> Observable<T> dematerialize(final Observable<Notification<T>> sequence) { <del> return _create(OperationDematerialize.dematerialize(sequence)); <add> return create(OperationDematerialize.dematerialize(sequence)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> dematerialize(final Observable<Notification<T>> <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge</a> <ide> */ <ide> public static <T> Observable<T> merge(List<Observable<T>> source) { <del> return _create(OperationMerge.merge(source)); <add> return create(OperationMerge.merge(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> merge(List<Observable<T>> source) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> <ide> */ <ide> public static <T> Observable<T> merge(Observable<Observable<T>> source) { <del> return _create(OperationMerge.merge(source)); <add> return create(OperationMerge.merge(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> merge(Observable<Observable<T>> source) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> <ide> */ <ide> public static <T> Observable<T> merge(Observable<T>... source) { <del> return _create(OperationMerge.merge(source)); <add> return create(OperationMerge.merge(source)); <ide> } <ide> <ide> /** <ide> public static <T, E> Observable<T> takeUntil(final Observable<T> source, final O <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable.concat(v=vs.103).aspx">MSDN: Observable.Concat Method</a> <ide> */ <ide> public static <T> Observable<T> concat(Observable<T>... source) { <del> return _create(OperationConcat.concat(source)); <add> return create(OperationConcat.concat(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> concat(Observable<T>... source) { <ide> * @return an observable of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. <ide> */ <ide> public static <K, T, R> Observable<GroupedObservable<K, R>> groupBy(Observable<T> source, final Func1<T, K> keySelector, final Func1<T, R> elementSelector) { <del> return _create(OperatorGroupBy.groupBy(source, keySelector, elementSelector)); <add> return create(OperatorGroupBy.groupBy(source, keySelector, elementSelector)); <ide> } <ide> <ide> /** <ide> public static <K, T, R> Observable<GroupedObservable<K, R>> groupBy(Observable<T <ide> * @return an observable of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. <ide> */ <ide> public static <K, T> Observable<GroupedObservable<K, T>> groupBy(Observable<T> source, final Func1<T, K> keySelector) { <del> return _create(OperatorGroupBy.groupBy(source, keySelector)); <add> return create(OperatorGroupBy.groupBy(source, keySelector)); <ide> } <ide> <ide> /** <ide> public static <K, T> Observable<GroupedObservable<K, T>> groupBy(Observable<T> s <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> <ide> */ <ide> public static <T> Observable<T> mergeDelayError(List<Observable<T>> source) { <del> return _create(OperationMergeDelayError.mergeDelayError(source)); <add> return create(OperationMergeDelayError.mergeDelayError(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> mergeDelayError(List<Observable<T>> source) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> <ide> */ <ide> public static <T> Observable<T> mergeDelayError(Observable<Observable<T>> source) { <del> return _create(OperationMergeDelayError.mergeDelayError(source)); <add> return create(OperationMergeDelayError.mergeDelayError(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> mergeDelayError(Observable<Observable<T>> source <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a> <ide> */ <ide> public static <T> Observable<T> mergeDelayError(Observable<T>... source) { <del> return _create(OperationMergeDelayError.mergeDelayError(source)); <add> return create(OperationMergeDelayError.mergeDelayError(source)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> never() { <ide> * @return the source Observable, with its behavior modified as described <ide> */ <ide> public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Func1<Exception, Observable<T>> resumeFunction) { <del> return _create(OperationOnErrorResumeNextViaFunction.onErrorResumeNextViaFunction(that, resumeFunction)); <add> return create(OperationOnErrorResumeNextViaFunction.onErrorResumeNextViaFunction(that, resumeFunction)); <ide> } <ide> <ide> /** <ide> public Observable<T> call(Exception e) { <ide> * @return the source Observable, with its behavior modified as described <ide> */ <ide> public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, final Observable<T> resumeSequence) { <del> return _create(OperationOnErrorResumeNextViaObservable.onErrorResumeNextViaObservable(that, resumeSequence)); <add> return create(OperationOnErrorResumeNextViaObservable.onErrorResumeNextViaObservable(that, resumeSequence)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> onErrorResumeNext(final Observable<T> that, fina <ide> * @return the source Observable, with its behavior modified as described <ide> */ <ide> public static <T> Observable<T> onErrorReturn(final Observable<T> that, Func1<Exception, T> resumeFunction) { <del> return _create(OperationOnErrorReturn.onErrorReturn(that, resumeFunction)); <add> return create(OperationOnErrorReturn.onErrorReturn(that, resumeFunction)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> onErrorReturn(final Observable<T> that, Func1<Ex <ide> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> <ide> */ <ide> public static <T> Observable<T> reduce(Observable<T> sequence, Func2<T, T, T> accumulator) { <del> return takeLast(_create(OperationScan.scan(sequence, accumulator)), 1); <add> return takeLast(create(OperationScan.scan(sequence, accumulator)), 1); <ide> } <ide> <ide> /** <ide> public T call(T t1, T t2) { <ide> * @see <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Wikipedia: Fold (higher-order function)</a> <ide> */ <ide> public static <T> Observable<T> reduce(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { <del> return takeLast(_create(OperationScan.scan(sequence, initialValue, accumulator)), 1); <add> return takeLast(create(OperationScan.scan(sequence, initialValue, accumulator)), 1); <ide> } <ide> <ide> /** <ide> public T call(T t1, T t2) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> <ide> */ <ide> public static <T> Observable<T> scan(Observable<T> sequence, Func2<T, T, T> accumulator) { <del> return _create(OperationScan.scan(sequence, accumulator)); <add> return create(OperationScan.scan(sequence, accumulator)); <ide> } <ide> <ide> /** <ide> public T call(T t1, T t2) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211665(v%3Dvs.103).aspx">MSDN: Observable.Scan</a> <ide> */ <ide> public static <T> Observable<T> scan(Observable<T> sequence, T initialValue, Func2<T, T, T> accumulator) { <del> return _create(OperationScan.scan(sequence, initialValue, accumulator)); <add> return create(OperationScan.scan(sequence, initialValue, accumulator)); <ide> } <ide> <ide> /** <ide> public T call(T t1, T t2) { <ide> <ide> /** <ide> * Determines whether all elements of an observable sequence satisfies a condition. <del> * @param sequence an observable sequence whose elements to apply the predicate to. <del> * @param predicate a function to test each element for a condition. <del> * @param <T> the type of observable. <add> * <add> * @param sequence <add> * an observable sequence whose elements to apply the predicate to. <add> * @param predicate <add> * a function to test each element for a condition. <add> * @param <T> <add> * the type of observable. <ide> * @return true if all elements of an observable sequence satisfies a condition; otherwise, false. <ide> */ <ide> public static <T> Observable<Boolean> all(final Observable<T> sequence, final Func1<T, Boolean> predicate) { <del> return _create(OperationAll.all(sequence, predicate)); <add> return create(OperationAll.all(sequence, predicate)); <ide> } <ide> <ide> /** <ide> * Determines whether all elements of an observable sequence satisfies a condition. <del> * @param sequence an observable sequence whose elements to apply the predicate to. <del> * @param predicate a function to test each element for a condition. <del> * @param <T> the type of observable. <add> * <add> * @param sequence <add> * an observable sequence whose elements to apply the predicate to. <add> * @param predicate <add> * a function to test each element for a condition. <add> * @param <T> <add> * the type of observable. <ide> * @return true if all elements of an observable sequence satisfies a condition; otherwise, false. <ide> */ <ide> public static <T> Observable<Boolean> all(final Observable<T> sequence, Object predicate) { <ide> public Boolean call(T t) { <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229847(v=vs.103).aspx">MSDN: Observable.Skip Method</a> <ide> */ <ide> public static <T> Observable<T> skip(final Observable<T> items, int num) { <del> return _create(OperationSkip.skip(items, num)); <add> return create(OperationSkip.skip(items, num)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> skip(final Observable<T> items, int num) { <ide> * @return an Observable that is a chronologically well-behaved version of the source Observable <ide> */ <ide> public static <T> Observable<T> synchronize(Observable<T> observable) { <del> return _create(OperationSynchronize.synchronize(observable)); <add> return create(OperationSynchronize.synchronize(observable)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> synchronize(Observable<T> observable) { <ide> * Observable <ide> */ <ide> public static <T> Observable<T> take(final Observable<T> items, final int num) { <del> return _create(OperationTake.take(items, num)); <add> return create(OperationTake.take(items, num)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> take(final Observable<T> items, final int num) { <ide> * Observable <ide> */ <ide> public static <T> Observable<T> takeLast(final Observable<T> items, final int count) { <del> return _create(OperationTakeLast.takeLast(items, count)); <add> return create(OperationTakeLast.takeLast(items, count)); <ide> } <ide> <ide> /** <ide> public Boolean call(T t, Integer integer) <ide> * items emitted by the source Observable <ide> */ <ide> public static <T> Observable<List<T>> toList(final Observable<T> that) { <del> return _create(OperationToObservableList.toObservableList(that)); <add> return create(OperationToObservableList.toObservableList(that)); <ide> } <ide> <ide> /** <ide> private static <T> T singleOrDefault(Observable<T> that, boolean hasDefault, T d <ide> * @return an Observable that emits each item in the source Iterable sequence <ide> */ <ide> public static <T> Observable<T> toObservable(Iterable<T> iterable) { <del> return _create(OperationToObservableIterable.toObservableIterable(iterable)); <add> return create(OperationToObservableIterable.toObservableIterable(iterable)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> toObservable(Iterable<T> iterable) { <ide> * @return an Observable that emits the item from the source Future <ide> */ <ide> public static <T> Observable<T> toObservable(Future<T> future) { <del> return _create(OperationToObservableFuture.toObservableFuture(future)); <add> return create(OperationToObservableFuture.toObservableFuture(future)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> toObservable(Future<T> future) { <ide> * @return an Observable that emits the item from the source Future <ide> */ <ide> public static <T> Observable<T> toObservable(Future<T> future, long time, TimeUnit unit) { <del> return _create(OperationToObservableFuture.toObservableFuture(future, time, unit)); <add> return create(OperationToObservableFuture.toObservableFuture(future, time, unit)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<T> toObservable(T... items) { <ide> * @return <ide> */ <ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { <del> return _create(OperationToObservableSortedList.toSortedList(sequence)); <add> return create(OperationToObservableSortedList.toSortedList(sequence)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence) { <ide> * @return <ide> */ <ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2<T, T, Integer> sortFunction) { <del> return _create(OperationToObservableSortedList.toSortedList(sequence, sortFunction)); <add> return create(OperationToObservableSortedList.toSortedList(sequence, sortFunction)); <ide> } <ide> <ide> /** <ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, Func2 <ide> public static <T> Observable<List<T>> toSortedList(Observable<T> sequence, final Object sortFunction) { <ide> @SuppressWarnings("rawtypes") <ide> final FuncN _f = Functions.from(sortFunction); <del> return _create(OperationToObservableSortedList.toSortedList(sequence, new Func2<T, T, Integer>() { <add> return create(OperationToObservableSortedList.toSortedList(sequence, new Func2<T, T, Integer>() { <ide> <ide> @Override <ide> public Integer call(T t1, T t2) { <ide> public Integer call(T t1, T t2) { <ide> * @return an Observable that emits the zipped results <ide> */ <ide> public static <R, T0, T1> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Func2<T0, T1, R> reduceFunction) { <del> return _create(OperationZip.zip(w0, w1, reduceFunction)); <add> return create(OperationZip.zip(w0, w1, reduceFunction)); <ide> } <ide> <ide> /** <ide> public R call(T0 t0, T1 t1) { <ide> * @return an Observable that emits the zipped results <ide> */ <ide> public static <R, T0, T1, T2> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Func3<T0, T1, T2, R> function) { <del> return _create(OperationZip.zip(w0, w1, w2, function)); <add> return create(OperationZip.zip(w0, w1, w2, function)); <ide> } <ide> <ide> /** <ide> public R call(T0 t0, T1 t1, T2 t2) { <ide> * @return an Observable that emits the zipped results <ide> */ <ide> public static <R, T0, T1, T2, T3> Observable<R> zip(Observable<T0> w0, Observable<T1> w1, Observable<T2> w2, Observable<T3> w3, Func4<T0, T1, T2, T3, R> reduceFunction) { <del> return _create(OperationZip.zip(w0, w1, w2, w3, reduceFunction)); <add> return create(OperationZip.zip(w0, w1, w2, w3, reduceFunction)); <ide> } <ide> <ide> /** <ide> public Boolean call(T t1) { <ide> * Filters an Observable by discarding any of its emissions that do not meet some test. <ide> * <p> <ide> * <img width="640" src="https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/filter.png"> <del> * <add> * <ide> * @param predicate <ide> * a function that evaluates the items emitted by the source Observable, returning <ide> * <code>true</code> if they pass the filter <ide> public Observable<Notification<T>> materialize() { <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public <T2> Observable<T2> dematerialize() { <del> return dematerialize((Observable<Notification<T2>>)this); <add> return dematerialize((Observable<Notification<T2>>) this); <ide> } <ide> <ide> /** <ide> public Observable<T> scan(final T initialValue, final Object accumulator) { <ide> <ide> /** <ide> * Determines whether all elements of an observable sequence satisfies a condition. <del> * @param predicate a function to test each element for a condition. <add> * <add> * @param predicate <add> * a function to test each element for a condition. <ide> * @return true if all elements of an observable sequence satisfies a condition; otherwise, false. <ide> */ <ide> public Observable<Boolean> all(Func1<T, Boolean> predicate) { <ide> public Observable<Boolean> all(Func1<T, Boolean> predicate) { <ide> <ide> /** <ide> * Determines whether all elements of an observable sequence satisfies a condition. <del> * @param predicate a function to test each element for a condition. <add> * <add> * @param predicate <add> * a function to test each element for a condition. <ide> * @return true if all elements of an observable sequence satisfies a condition; otherwise, false. <ide> */ <ide> public Observable<Boolean> all(Object predicate) { <ide> public void testMaterializeDematerializeChaining() { <ide> verify(observer, times(0)).onError(any(Exception.class)); <ide> } <ide> <add> /** <add> * The error from the user provided Observer is not handled by the subscribe method try/catch. <add> * <add> * It is handled by the AtomicObserver that wraps the provided Observer. <add> * <add> * Result: Passes (if AtomicObserver functionality exists) <add> */ <add> @Test <add> public void testCustomObservableWithErrorInObserverAsynchronous() throws InterruptedException { <add> final CountDownLatch latch = new CountDownLatch(1); <add> final AtomicInteger count = new AtomicInteger(); <add> final AtomicReference<Exception> error = new AtomicReference<Exception>(); <add> Observable.create(new Func1<Observer<String>, Subscription>() { <add> <add> @Override <add> public Subscription call(final Observer<String> observer) { <add> final BooleanSubscription s = new BooleanSubscription(); <add> new Thread(new Runnable() { <add> <add> @Override <add> public void run() { <add> try { <add> if (!s.isUnsubscribed()) { <add> observer.onNext("1"); <add> observer.onNext("2"); <add> observer.onNext("three"); <add> observer.onNext("4"); <add> observer.onCompleted(); <add> } <add> } finally { <add> latch.countDown(); <add> } <add> } <add> }).start(); <add> return s; <add> } <add> }).subscribe(new AtomicObserver<String>(new AtomicObservableSubscription(), new Observer<String>() { <add> // we are manually wrapping in AtomicObserver here to simulate <add> // what will happen when a user provided Observer implementation is passed in <add> // since the subscribe method will wrap it in AtomicObserver if it's not in an rx.* package <add> <add> @Override <add> public void onCompleted() { <add> System.out.println("completed"); <add> } <add> <add> @Override <add> public void onError(Exception e) { <add> error.set(e); <add> System.out.println("error"); <add> e.printStackTrace(); <add> } <add> <add> @Override <add> public void onNext(String v) { <add> int num = Integer.parseInt(v); <add> System.out.println(num); <add> // doSomething(num); <add> count.incrementAndGet(); <add> } <add> <add> })); <add> <add> // wait for async sequence to complete <add> latch.await(); <add> <add> assertEquals(2, count.get()); <add> assertNotNull(error.get()); <add> if (!(error.get() instanceof NumberFormatException)) { <add> fail("It should be a NumberFormatException"); <add> } <add> } <add> <add> /** <add> * The error from the user provided Observer is handled by the subscribe try/catch because this is synchronous <add> * <add> * Result: Passes <add> */ <add> @Test <add> public void testCustomObservableWithErrorInObserverSynchronous() { <add> final AtomicInteger count = new AtomicInteger(); <add> final AtomicReference<Exception> error = new AtomicReference<Exception>(); <add> Observable.create(new Func1<Observer<String>, Subscription>() { <add> <add> @Override <add> public Subscription call(Observer<String> observer) { <add> observer.onNext("1"); <add> observer.onNext("2"); <add> observer.onNext("three"); <add> observer.onNext("4"); <add> observer.onCompleted(); <add> return Subscriptions.empty(); <add> } <add> }).subscribe(new Observer<String>() { <add> <add> @Override <add> public void onCompleted() { <add> System.out.println("completed"); <add> } <add> <add> @Override <add> public void onError(Exception e) { <add> error.set(e); <add> System.out.println("error"); <add> e.printStackTrace(); <add> } <add> <add> @Override <add> public void onNext(String v) { <add> int num = Integer.parseInt(v); <add> System.out.println(num); <add> // doSomething(num); <add> count.incrementAndGet(); <add> } <add> <add> }); <add> assertEquals(2, count.get()); <add> assertNotNull(error.get()); <add> if (!(error.get() instanceof NumberFormatException)) { <add> fail("It should be a NumberFormatException"); <add> } <add> } <add> <add> /** <add> * The error from the user provided Observable is handled by the subscribe try/catch because this is synchronous <add> * <add> * <add> * Result: Passes <add> */ <add> @Test <add> public void testCustomObservableWithErrorInObservableSynchronous() { <add> final AtomicInteger count = new AtomicInteger(); <add> final AtomicReference<Exception> error = new AtomicReference<Exception>(); <add> Observable.create(new Func1<Observer<String>, Subscription>() { <add> <add> @Override <add> public Subscription call(Observer<String> observer) { <add> observer.onNext("1"); <add> observer.onNext("2"); <add> throw new NumberFormatException(); <add> } <add> }).subscribe(new Observer<String>() { <add> <add> @Override <add> public void onCompleted() { <add> System.out.println("completed"); <add> } <add> <add> @Override <add> public void onError(Exception e) { <add> error.set(e); <add> System.out.println("error"); <add> e.printStackTrace(); <add> } <add> <add> @Override <add> public void onNext(String v) { <add> System.out.println(v); <add> count.incrementAndGet(); <add> } <add> <add> }); <add> assertEquals(2, count.get()); <add> assertNotNull(error.get()); <add> if (!(error.get() instanceof NumberFormatException)) { <add> fail("It should be a NumberFormatException"); <add> } <add> } <add> <ide> private static class TestException extends RuntimeException { <ide> private static final long serialVersionUID = 1L; <ide> } <ide><path>rxjava-core/src/main/java/rx/operators/OperationTake.java <ide> import static org.junit.Assert.*; <ide> import static org.mockito.Matchers.*; <ide> import static org.mockito.Mockito.*; <del>import static rx.operators.AbstractOperation.UnitTest.*; <add>import static rx.operators.Tester.UnitTest.*; <ide> <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> public void run() { <ide> } <ide> <ide> } <add> <ide> } <ide> <ide> } <ide><path>rxjava-core/src/main/java/rx/operators/OperationTakeWhile.java <ide> import rx.Observable; <ide> import rx.Observer; <ide> import rx.Subscription; <add>import rx.subjects.Subject; <ide> import rx.subscriptions.Subscriptions; <ide> import rx.util.AtomicObservableSubscription; <add>import rx.util.AtomicObserver; <ide> import rx.util.functions.Func1; <ide> import rx.util.functions.Func2; <del>import rx.subjects.Subject; <add> <ide> /** <ide> * Returns values from an observable sequence as long as a specified condition is true, and then skips the remaining values. <ide> */ <ide> public final class OperationTakeWhile { <ide> * @return <ide> */ <ide> public static <T> Func1<Observer<T>, Subscription> takeWhile(final Observable<T> items, final Func1<T, Boolean> predicate) { <del> return takeWhileWithIndex(items, OperationTakeWhile.<T>skipIndex(predicate)); <add> return takeWhileWithIndex(items, OperationTakeWhile.<T> skipIndex(predicate)); <ide> } <ide> <ide> /** <ide> private class ItemObserver implements Observer<T> { <ide> private final Observer<T> observer; <ide> <ide> public ItemObserver(Observer<T> observer) { <del> this.observer = observer; <add> // Using AtomicObserver because the unsubscribe, onCompleted, onError and error handling behavior <add> // needs "isFinished" logic to not send duplicated events <add> // The 'testTakeWhile1' and 'testTakeWhile2' tests fail without this. <add> this.observer = new AtomicObserver<T>(subscription, observer); <ide> } <ide> <ide> @Override <ide> public void onNext(T args) { <ide> Boolean isSelected; <ide> try { <ide> isSelected = predicate.call(args, counter.getAndIncrement()); <del> } <del> catch (Exception e) { <add> } catch (Exception e) { <ide> observer.onError(e); <ide> return; <ide> } <ide> public Boolean call(Integer input) <ide> @Test <ide> public void testTakeWhileOnSubject1() { <ide> Subject<Integer> s = Subject.create(); <del> Observable<Integer> w = (Observable<Integer>)s; <add> Observable<Integer> w = (Observable<Integer>) s; <ide> Observable<Integer> take = Observable.create(takeWhile(w, new Func1<Integer, Boolean>() <ide> { <ide> @Override <add><path>rxjava-core/src/main/java/rx/operators/Tester.java <del><path>rxjava-core/src/main/java/rx/operators/AbstractOperation.java <ide> import rx.util.functions.Func1; <ide> <ide> /** <del> * Common utility functions for operator implementations and tests. <add> * Common utility functions for testing operator implementations. <ide> */ <del>/* package */class AbstractOperation <del>{ <del> private AbstractOperation() { <add>/* package */class Tester { <add> /* <add> * This is purposefully package-only so it does not leak into the public API outside of this package. <add> * <add> * This package is implementation details and not part of the Javadocs and thus can change without breaking backwards compatibility. <add> */ <add> <add> private Tester() { <ide> } <ide> <ide> public static class UnitTest { <ide><path>rxjava-core/src/main/java/rx/util/AtomicObserver.java <ide> package rx.util; <ide> <add>import java.util.Arrays; <ide> import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> import rx.Observer; <add>import rx.plugins.RxJavaPlugins; <ide> <ide> /** <ide> * Wrapper around Observer to ensure compliance with Rx contract. <ide> * <li>When onError or onComplete occur it will unsubscribe from the Observable (if executing asynchronously).</li> <ide> * </ul> <ide> * <p> <del> * It will not synchronized onNext execution. Use the {@link SynchronizedObserver} to do that. <add> * It will not synchronize onNext execution. Use the {@link SynchronizedObserver} to do that. <ide> * <ide> * @param <T> <ide> */ <ide> public AtomicObserver(AtomicObservableSubscription subscription, Observer<T> act <ide> @Override <ide> public void onCompleted() { <ide> if (isFinished.compareAndSet(false, true)) { <del> actual.onCompleted(); <add> try { <add> actual.onCompleted(); <add> } catch (Exception e) { <add> // handle errors if the onCompleted implementation fails, not just if the Observable fails <add> onError(e); <add> } <ide> // auto-unsubscribe <ide> subscription.unsubscribe(); <ide> } <ide> public void onCompleted() { <ide> @Override <ide> public void onError(Exception e) { <ide> if (isFinished.compareAndSet(false, true)) { <del> actual.onError(e); <add> try { <add> actual.onError(e); <add> } catch (Exception e2) { <add> // if the onError itself fails then pass to the plugin <add> // see https://github.com/Netflix/RxJava/issues/216 for further discussion <add> RxJavaPlugins.getInstance().getErrorHandler().handleError(e); <add> RxJavaPlugins.getInstance().getErrorHandler().handleError(e2); <add> // and throw exception despite that not being proper for Rx <add> // https://github.com/Netflix/RxJava/issues/198 <add> throw new RuntimeException("Error occurred when trying to propagate error to Observer.onError", new CompositeException(Arrays.asList(e, e2))); <add> } <ide> // auto-unsubscribe <ide> subscription.unsubscribe(); <ide> }
5
Javascript
Javascript
use dedupe plugin later in compilation
3419ddcb299fdde6bd226c0d5d9b31a0404ea358
<ide><path>lib/Compilation.js <ide> Compilation.prototype.seal = function seal(callback) { <ide> return callback(err); <ide> } <ide> <add> this.applyPlugins("after-optimize-tree", this.chunks, this.modules); <add> <ide> var shouldRecord = this.applyPluginsBailResult("should-record") !== false; <ide> <ide> this.applyPlugins("revive-modules", this.modules, this.records); <ide><path>lib/optimize/DedupePlugin.js <ide> DedupePlugin.prototype.apply = function(compiler) { <ide> } <ide> }); <ide> }); <del> compilation.plugin("after-optimize-chunks", function(chunks) { <add> compilation.plugin("after-optimize-tree", function(chunks) { <ide> var entryChunks = chunks.filter(function(c) { return c.entry; }); <ide> entryChunks.forEach(function(chunk) { // for each entry chunk <ide> var hasDeduplicatedModules = false;
2
Text
Text
remove superfluous text in onboarding-extras
6ec41bbdd7755e25049a584f2080d1bdfd7314c0
<ide><path>doc/onboarding-extras.md <ide> If you cannot find who to cc for a file, `git shortlog -n -s <file>` may help. <ide> <ide> ## Labels <ide> <del>### By Subsystem <del> <del>Subsystems include: <add>### Subsystems <ide> <ide> * `lib/*.js` (`assert`, `buffer`, etc.) <ide> * `build` <ide> request. <ide> <ide> ### General <ide> <del>Please use these when possible / appropriate <del> <ide> * `confirmed-bug` - Bugs you have verified exist <ide> * `discuss` - Things that need larger discussion <ide> * `feature request` - Any issue that requests a new feature (usually not PRs)
1
Python
Python
move loadtxt bytes/str detection much earlier
3affc1738f656445493b8976a489f562a97cfb0c
<ide><path>numpy/lib/npyio.py <ide> def read_data(lineno_words_iter, chunk_size): <ide> if _is_string_like(fname): <ide> fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) <ide> fencoding = getattr(fh, 'encoding', 'latin1') <del> fh = iter(fh) <add> line_iter = iter(fh) <ide> fown = True <ide> else: <del> fh = iter(fname) <add> line_iter = iter(fname) <ide> fencoding = getattr(fname, 'encoding', 'latin1') <add> try: <add> first_line = next(line_iter) <add> except StopIteration: <add> pass # Nothing matters if line_iter is empty. <add> else: <add> # Put first_line back. <add> line_iter = itertools.chain([first_line], line_iter) <add> if isinstance(first_line, bytes): <add> # Using latin1 matches _decode_line's behavior. <add> decoder = methodcaller( <add> "decode", <add> encoding if encoding is not None else "latin1") <add> line_iter = map(decoder, line_iter) <ide> except TypeError as e: <ide> raise ValueError( <ide> f"fname must be a string, filehandle, list of strings,\n" <ide> def read_data(lineno_words_iter, chunk_size): <ide> try: <ide> # Skip the first `skiprows` lines <ide> for i in range(skiprows): <del> next(fh) <add> next(line_iter) <ide> <ide> # Read until we find a line with some values, and use it to determine <ide> # the need for decoding and estimate the number of columns. <del> for first_line in fh: <del> ncols = len(usecols <del> or split_line(_decode_line(first_line, encoding))) <add> for first_line in line_iter: <add> ncols = len(usecols or split_line(first_line)) <ide> if ncols: <add> # Put first_line back. <add> line_iter = itertools.chain([first_line], line_iter) <ide> break <ide> else: # End of lines reached <del> first_line = '' <ide> ncols = len(usecols or []) <ide> warnings.warn('loadtxt: Empty input file: "%s"' % fname, <ide> stacklevel=2) <ide> <del> line_iter = itertools.islice( <del> itertools.chain([first_line], fh), max_rows) <del> if isinstance(first_line, bytes): <del> decoder = methodcaller( # latin1 matches _decode_line's behavior. <del> "decode", encoding if encoding is not None else "latin1") <del> line_iter = map(decoder, line_iter) <del> <add> line_iter = itertools.islice(line_iter, max_rows) <ide> lineno_words_iter = filter( <ide> itemgetter(1), # item[1] is words; filter skips empty lines. <ide> enumerate(map(split_line, line_iter), 1 + skiprows))
1
Python
Python
use integer shape if available
b5df1c617029faf675cdb681a9e0033497245992
<ide><path>keras/backend/tensorflow_backend.py <ide> def dot(x, y): <ide> if ndim(x) is not None and (ndim(x) > 2 or ndim(y) > 2): <ide> x_shape = [] <ide> for i, s in zip(int_shape(x), tf.unpack(tf.shape(x))): <del> if s is None: <add> if i is not None: <ide> x_shape.append(i) <ide> else: <ide> x_shape.append(s) <ide> x_shape = tuple(x_shape) <ide> y_shape = [] <ide> for i, s in zip(int_shape(y), tf.unpack(tf.shape(y))): <del> if s is None: <add> if i is not None: <ide> y_shape.append(i) <ide> else: <ide> y_shape.append(s)
1
Javascript
Javascript
fix fragment handling in totree()
8b83ea02f5abc7bf526b7e104a2cb73b034df5c2
<ide><path>packages/react-test-renderer/src/ReactTestRenderer.js <ide> import { <ide> FunctionalComponent, <ide> ClassComponent, <ide> HostComponent, <add> HostPortal, <ide> HostText, <ide> HostRoot, <ide> } from 'shared/ReactTypeOfWork'; <ide> function toJSON(inst: Instance | TextInstance): ReactTestRendererNode { <ide> } <ide> } <ide> <del>function nodeAndSiblingsTrees(nodeWithSibling: ?Fiber) { <add>function childrenToTree(node) { <add> if (!node) { <add> return null; <add> } <add> const children = nodeAndSiblingsArray(node); <add> if (children.length === 0) { <add> return null; <add> } else if (children.length === 1) { <add> return toTree(children[0]); <add> } <add> return flatten(children.map(toTree)); <add>} <add> <add>function nodeAndSiblingsArray(nodeWithSibling) { <ide> const array = []; <ide> let node = nodeWithSibling; <ide> while (node != null) { <ide> array.push(node); <ide> node = node.sibling; <ide> } <del> const trees = array.map(toTree); <del> return trees.length ? trees : null; <add> return array; <ide> } <ide> <del>function hasSiblings(node: ?Fiber) { <del> return node && node.sibling; <add>function flatten(arr) { <add> const result = []; <add> const stack = [{i: 0, array: arr}]; <add> while (stack.length) { <add> const n = stack.pop(); <add> while (n.i < n.array.length) { <add> const el = n.array[n.i]; <add> n.i += 1; <add> if (Array.isArray(el)) { <add> stack.push(n); <add> stack.push({i: 0, array: el}); <add> break; <add> } <add> result.push(el); <add> } <add> } <add> return result; <ide> } <ide> <ide> function toTree(node: ?Fiber) { <ide> if (node == null) { <ide> return null; <ide> } <ide> switch (node.tag) { <del> case HostRoot: // 3 <del> return toTree(node.child); <add> case HostRoot: <add> return childrenToTree(node.child); <add> case HostPortal: <add> return childrenToTree(node.child); <ide> case ClassComponent: <ide> return { <ide> nodeType: 'component', <ide> type: node.type, <ide> props: {...node.memoizedProps}, <ide> instance: node.stateNode, <del> rendered: hasSiblings(node.child) <del> ? nodeAndSiblingsTrees(node.child) <del> : toTree(node.child), <add> rendered: childrenToTree(node.child), <ide> }; <del> case FunctionalComponent: // 1 <add> case FunctionalComponent: <ide> return { <ide> nodeType: 'component', <ide> type: node.type, <ide> props: {...node.memoizedProps}, <ide> instance: null, <del> rendered: hasSiblings(node.child) <del> ? nodeAndSiblingsTrees(node.child) <del> : toTree(node.child), <add> rendered: childrenToTree(node.child), <ide> }; <del> case HostComponent: // 5 <add> case HostComponent: { <ide> return { <ide> nodeType: 'host', <ide> type: node.type, <ide> props: {...node.memoizedProps}, <ide> instance: null, // TODO: use createNodeMock here somehow? <del> rendered: nodeAndSiblingsTrees(node.child), <add> rendered: flatten(nodeAndSiblingsArray(node.child).map(toTree)), <ide> }; <del> case HostText: // 6 <add> } <add> case HostText: <ide> return node.stateNode.text; <del> case Fragment: // 10 <del> return toTree(node.child); <add> case Fragment: <add> return childrenToTree(node.child); <ide> default: <ide> invariant( <ide> false, <ide><path>packages/react-test-renderer/src/__tests__/ReactTestRenderer-test.js <ide> describe('ReactTestRenderer', () => { <ide> ); <ide> }); <ide> <del> it('toTree() handles complicated tree of fragments', () => { <add> it('toTree() handles complicated tree of arrays', () => { <ide> class Foo extends React.Component { <ide> render() { <ide> return this.props.children; <ide> describe('ReactTestRenderer', () => { <ide> ); <ide> }); <ide> <add> it('toTree() handles complicated tree of fragments', () => { <add> const renderer = ReactTestRenderer.create( <add> <React.Fragment> <add> <React.Fragment> <add> <div>One</div> <add> <div>Two</div> <add> <React.Fragment> <add> <div>Three</div> <add> </React.Fragment> <add> </React.Fragment> <add> <div>Four</div> <add> </React.Fragment>, <add> ); <add> <add> const tree = renderer.toTree(); <add> <add> cleanNodeOrArray(tree); <add> <add> expect(prettyFormat(tree)).toEqual( <add> prettyFormat([ <add> { <add> type: 'div', <add> nodeType: 'host', <add> props: {}, <add> instance: null, <add> rendered: ['One'], <add> }, <add> { <add> type: 'div', <add> nodeType: 'host', <add> props: {}, <add> instance: null, <add> rendered: ['Two'], <add> }, <add> { <add> type: 'div', <add> nodeType: 'host', <add> props: {}, <add> instance: null, <add> rendered: ['Three'], <add> }, <add> { <add> type: 'div', <add> nodeType: 'host', <add> props: {}, <add> instance: null, <add> rendered: ['Four'], <add> }, <add> ]), <add> ); <add> }); <add> <ide> it('root instance and createNodeMock ref return the same value', () => { <ide> const createNodeMock = ref => ({node: ref}); <ide> let refInst = null;
2
Java
Java
fix showshorizontalscrollindicator for scrollview
e6ad91b5a218bec73a10a9064e9178235b12c557
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollViewManager.java <ide> import javax.annotation.Nullable; <ide> <ide> import com.facebook.react.bridge.ReadableArray; <add>import com.facebook.react.uimanager.ReactProp; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> import com.facebook.react.uimanager.ViewGroupManager; <ide> <ide> public ReactHorizontalScrollView createViewInstance(ThemedReactContext context) <ide> return new ReactHorizontalScrollView(context); <ide> } <ide> <add> @ReactProp(name = "showsHorizontalScrollIndicator") <add> public void setShowsHorizontalScrollIndicator(ReactHorizontalScrollView view, boolean value) { <add> view.setHorizontalScrollBarEnabled(value); <add> } <add> <ide> @Override <ide> public void receiveCommand( <ide> ReactHorizontalScrollView scrollView, <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java <ide> public void setShowsVerticalScrollIndicator(ReactScrollView view, boolean value) <ide> view.setVerticalScrollBarEnabled(value); <ide> } <ide> <del> @ReactProp(name = "showsHorizontalScrollIndicator") <del> public void setShowsHorizontalScrollIndicator(ReactScrollView view, boolean value) { <del> view.setHorizontalScrollBarEnabled(value); <del> } <del> <ide> @ReactProp(name = ReactClippingViewGroupHelper.PROP_REMOVE_CLIPPED_SUBVIEWS) <ide> public void setRemoveClippedSubviews(ReactScrollView view, boolean removeClippedSubviews) { <ide> view.setRemoveClippedSubviews(removeClippedSubviews);
2
Javascript
Javascript
create experiment for `collapsable` (ios)
f598dd0ee3670075e8f9480aeb1489e7ad5c63e8
<ide><path>Libraries/Components/View/ViewInjection.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow strict <add> * @format <add> */ <add> <add>export default { <add> unstable_enableCollapsable: false, <add>}; <ide><path>Libraries/Components/View/ViewNativeComponent.js <ide> import {type HostComponent} from '../../Renderer/shims/ReactNativeTypes'; <ide> import Platform from '../../Utilities/Platform'; <ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands'; <ide> import ReactNativeViewViewConfigAndroid from './ReactNativeViewViewConfigAndroid'; <add>import ViewInjection from './ViewInjection'; <ide> import {type ViewProps as Props} from './ViewPropTypes'; <ide> import * as React from 'react'; <add>import ReactNativeViewConfigRegistry from '../../Renderer/shims/ReactNativeViewConfigRegistry'; <ide> <ide> const ViewNativeComponent: HostComponent<Props> = NativeComponentRegistry.get<Props>( <ide> 'RCTView', <ide> const ViewNativeComponent: HostComponent<Props> = NativeComponentRegistry.get<Pr <ide> : {uiViewClassName: 'RCTView'}, <ide> ); <ide> <add>if (Platform.OS === 'ios') { <add> if (ViewInjection.unstable_enableCollapsable) { <add> const viewConfig = ReactNativeViewConfigRegistry.get('RCTView'); <add> // $FlowFixMe - Yes, knowingly writing to a read-only property. <add> viewConfig.validAttributes.collapsable = true; <add> } <add>} <add> <ide> interface NativeCommands { <ide> +hotspotUpdate: ( <ide> viewRef: React.ElementRef<HostComponent<mixed>>,
2
Text
Text
add dash between sha and pr in changelog
420d4e461dcb64bd52b6cce97bcff405efd6878a
<ide><path>doc/changelogs/CHANGELOG_V8.md <ide> Big thanks to @addaleax who prepared the vast majority of this release. <ide> * **Build** <ide> * The compiler version requirement to build Node with GCC has been raised to <ide> GCC 4.9.4. <del> [[`820b011ed6`](https://github.com/nodejs/node/commit/820b011ed6)] <add> [[`820b011ed6`](https://github.com/nodejs/node/commit/820b011ed6)] - <ide> [#13466](https://github.com/nodejs/node/pull/13466) <ide> <ide> * **Cluster** <ide> * Users now have more fine-grained control over the inspector port used by <ide> individual cluster workers. Previously, cluster workers were restricted to <ide> incrementing from the master's debug port. <del> [[`dfc46e262a`](https://github.com/nodejs/node/commit/dfc46e262a)] <add> [[`dfc46e262a`](https://github.com/nodejs/node/commit/dfc46e262a)] - <ide> [#14140](https://github.com/nodejs/node/pull/14140) <ide> <ide> * **DNS** <ide> * The server used for DNS queries can now use a custom port. <del> [[`ebe7bb29aa`](https://github.com/nodejs/node/commit/ebe7bb29aa)] <add> [[`ebe7bb29aa`](https://github.com/nodejs/node/commit/ebe7bb29aa)] - <ide> [#13723](https://github.com/nodejs/node/pull/13723) <ide> * Support for `dns.resolveAny()` has been added. <del> [[`6e30e2558e`](https://github.com/nodejs/node/commit/6e30e2558e)] <add> [[`6e30e2558e`](https://github.com/nodejs/node/commit/6e30e2558e)] - <ide> [#13137](https://github.com/nodejs/node/pull/13137) <ide> <ide> * **npm** <ide> * The `npm` CLI has been updated to version 5.3.0. In particular, it now comes <ide> with the `npx` binary, which is also shipped with Node. <del> [[`dc3f6b9ac1`](https://github.com/nodejs/node/commit/dc3f6b9ac1)] <add> [[`dc3f6b9ac1`](https://github.com/nodejs/node/commit/dc3f6b9ac1)] - <ide> [#14235](https://github.com/nodejs/node/pull/14235) <ide> * `npm` Changelogs: <ide> * [v5.0.4](https://github.com/npm/npm/releases/tag/v5.0.4) <ide> This is a security release. All Node.js users should consult the security releas <ide> Two regressions with the `stream` module have been fixed: <ide> * The `finish` event will now always be emitted after the `error` event <ide> if one is emitted: <del> [[`0a9e96e86c`](https://github.com/nodejs/node/commit/0a9e96e86c)] <add> [[`0a9e96e86c`](https://github.com/nodejs/node/commit/0a9e96e86c)] - <ide> [#13850](https://github.com/nodejs/node/pull/13850) <ide> * In object mode, readable streams can now use `undefined` again. <del> [[`5840138e70`](https://github.com/nodejs/node/commit/5840138e70)] <add> [[`5840138e70`](https://github.com/nodejs/node/commit/5840138e70)] - <ide> [#13760](https://github.com/nodejs/node/pull/13760) <ide> <ide> ### Commits <ide> Ref: https://github.com/nodejs/node/issues/13667 <ide> * `stdout` and `stderr` are now available on the error output of a <ide> failed call to the `util.promisify()`ed version of <ide> `child_process.exec`. <del> [[`d66d4fc94c`](https://github.com/nodejs/node/commit/d66d4fc94c)] <add> [[`d66d4fc94c`](https://github.com/nodejs/node/commit/d66d4fc94c)] - <ide> [#13388](https://github.com/nodejs/node/pull/13388) <ide> <ide> * **HTTP** <ide> * A regression that broke certain scenarios in which HTTP is used together <ide> with the `cluster` module has been fixed. <del> [[`fff8a56d6f`](https://github.com/nodejs/node/commit/fff8a56d6f)] <add> [[`fff8a56d6f`](https://github.com/nodejs/node/commit/fff8a56d6f)] - <ide> [#13578](https://github.com/nodejs/node/pull/13578) <ide> <ide> * **HTTPS** <ide> * The `rejectUnauthorized` option now works properly for unix sockets. <del> [[`c4cbd99d37`](https://github.com/nodejs/node/commit/c4cbd99d37)] <add> [[`c4cbd99d37`](https://github.com/nodejs/node/commit/c4cbd99d37)] - <ide> [#13505](https://github.com/nodejs/node/pull/13505) <ide> <ide> * **Readline** <ide> * A change that broke `npm init` and other code which uses `readline` <ide> multiple times on the same input stream is reverted. <del> [[`0df6c0b5f0`](https://github.com/nodejs/node/commit/0df6c0b5f0)] <add> [[`0df6c0b5f0`](https://github.com/nodejs/node/commit/0df6c0b5f0)] - <ide> [#13560](https://github.com/nodejs/node/pull/13560) <ide> <ide> ### Commits <ide> Ref: https://github.com/nodejs/node/issues/13667 <ide> * **Async Hooks** <ide> * When one `Promise` leads to the creation of a new `Promise`, the parent <ide> `Promise` will be identified as the trigger <del> [[`135f4e6643`](https://github.com/nodejs/node/commit/135f4e6643)] <add> [[`135f4e6643`](https://github.com/nodejs/node/commit/135f4e6643)] - <ide> [#13367](https://github.com/nodejs/node/pull/13367). <ide> * **Dependencies** <ide> * libuv has been updated to 1.12.0 <del> [[`968596ec77`](https://github.com/nodejs/node/commit/968596ec77)] <add> [[`968596ec77`](https://github.com/nodejs/node/commit/968596ec77)] - <ide> [#13306](https://github.com/nodejs/node/pull/13306). <ide> * npm has been updated to 5.0.3 <del> [[`ffa7debd7a`](https://github.com/nodejs/node/commit/ffa7debd7a)] <add> [[`ffa7debd7a`](https://github.com/nodejs/node/commit/ffa7debd7a)] - <ide> [#13487](https://github.com/nodejs/node/pull/13487). <ide> * **File system** <ide> * The `fs.exists()` function now works correctly with `util.promisify()` <del> [[`6e0eccd7a1`](https://github.com/nodejs/node/commit/6e0eccd7a1)] <add> [[`6e0eccd7a1`](https://github.com/nodejs/node/commit/6e0eccd7a1)] - <ide> [#13316](https://github.com/nodejs/node/pull/13316). <ide> * fs.Stats times are now also available as numbers <del> [[`c756efb25a`](https://github.com/nodejs/node/commit/c756efb25a)] <add> [[`c756efb25a`](https://github.com/nodejs/node/commit/c756efb25a)] - <ide> [#13173](https://github.com/nodejs/node/pull/13173). <ide> * **Inspector** <ide> * It is now possible to bind to a random port using `--inspect=0` <del> [[`cc6ec2fb27`](https://github.com/nodejs/node/commit/cc6ec2fb27)] <add> [[`cc6ec2fb27`](https://github.com/nodejs/node/commit/cc6ec2fb27)] - <ide> [#5025](https://github.com/nodejs/node/pull/5025). <ide> * **Zlib** <ide> * A regression in the Zlib module that made it impossible to properly <ide> subclasses `zlib.Deflate` and other Zlib classes has been fixed. <del> [[`6aeb555cc4`](https://github.com/nodejs/node/commit/6aeb555cc4)] <add> [[`6aeb555cc4`](https://github.com/nodejs/node/commit/6aeb555cc4)] - <ide> [#13374](https://github.com/nodejs/node/pull/13374). <ide> <ide> ### Commits <ide> LTS codename `'Carbon'`. Note that the <ide> <ide> * **Async Hooks** <ide> * The `async_hooks` module has landed in core <del> [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] <add> [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] - <ide> [#12892](https://github.com/nodejs/node/pull/12892). <ide> <ide> * **Buffer** <ide> * Using the `--pending-deprecation` flag will cause Node.js to emit a <ide> deprecation warning when using `new Buffer(num)` or `Buffer(num)`. <del> [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] <add> [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] - <ide> [#11968](https://github.com/nodejs/node/pull/11968). <ide> * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances <del> [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] <add> [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] - <ide> [#12141](https://github.com/nodejs/node/pull/12141). <ide> * Many `Buffer` methods now accept `Uint8Array` as input <del> [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] <add> [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] - <ide> [#10236](https://github.com/nodejs/node/pull/10236). <ide> <ide> * **Child Process** <ide> * Argument and kill signal validations have been improved <del> [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] <add> [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] - <ide> [#12348](https://github.com/nodejs/node/pull/12348), <del> [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] <add> [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] - <ide> [#10423](https://github.com/nodejs/node/pull/10423). <ide> * Child Process methods accept `Uint8Array` as input <del> [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] <add> [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] - <ide> [#10653](https://github.com/nodejs/node/pull/10653). <ide> <ide> * **Console** <ide> * Error events emitted when using `console` methods are now supressed. <del> [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] <add> [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] - <ide> [#9744](https://github.com/nodejs/node/pull/9744). <ide> <ide> * **Dependencies** <ide> * The npm client has been updated to 5.0.0 <del> [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] <add> [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] - <ide> [#12936](https://github.com/nodejs/node/pull/12936). <ide> * V8 has been updated to 5.8 with forward ABI stability to 6.0 <del> [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] <add> [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] - <ide> [#12784](https://github.com/nodejs/node/pull/12784). <ide> <ide> * **Domains** <ide> * Native `Promise` instances are now `Domain` aware <del> [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] <add> [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] - <ide> [#12489](https://github.com/nodejs/node/pull/12489). <ide> <ide> * **Errors** <ide> LTS codename `'Carbon'`. Note that the <ide> <ide> * **File System** <ide> * The utility class `fs.SyncWriteStream` has been deprecated <del> [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] <add> [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] - <ide> [#10467](https://github.com/nodejs/node/pull/10467). <ide> * The deprecated `fs.read()` string interface has been removed <del> [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] <add> [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] - <ide> [#9683](https://github.com/nodejs/node/pull/9683). <ide> <ide> * **HTTP** <ide> * Improved support for userland implemented Agents <del> [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] <add> [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] - <ide> [#11567](https://github.com/nodejs/node/pull/11567). <ide> * Outgoing Cookie headers are concatenated into a single string <del> [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] <add> [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] - <ide> [#11259](https://github.com/nodejs/node/pull/11259). <ide> * The `httpResponse.writeHeader()` method has been deprecated <del> [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] <add> [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] - <ide> [#11355](https://github.com/nodejs/node/pull/11355). <ide> * New methods for accessing HTTP headers have been added to `OutgoingMessage` <del> [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] <add> [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] - <ide> [#10805](https://github.com/nodejs/node/pull/10805). <ide> <ide> * **Lib** <ide> * All deprecation messages have been assigned static identifiers <del> [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] <add> [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] - <ide> [#10116](https://github.com/nodejs/node/pull/10116). <ide> * The legacy `linkedlist` module has been removed <del> [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] <add> [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] - <ide> [#12113](https://github.com/nodejs/node/pull/12113). <ide> <ide> * **N-API** <ide> * Experimental support for the new N-API API has been added <del> [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] <add> [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] - <ide> [#11975](https://github.com/nodejs/node/pull/11975). <ide> <ide> * **Process** <ide> * Process warning output can be redirected to a file using the <ide> `--redirect-warnings` command-line argument <del> [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] <add> [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] - <ide> [#10116](https://github.com/nodejs/node/pull/10116). <ide> * Process warnings may now include additional detail <del> [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] <add> [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] - <ide> [#12725](https://github.com/nodejs/node/pull/12725). <ide> <ide> * **REPL** <ide> * REPL magic mode has been deprecated <del> [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] <add> [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] - <ide> [#11599](https://github.com/nodejs/node/pull/11599). <ide> <ide> * **Src** <ide> * `NODE_MODULE_VERSION` has been updated to 57 <del> [[`ec7cbaf266`](https://github.com/nodejs/node/commit/ec7cbaf266)] <add> [[`ec7cbaf266`](https://github.com/nodejs/node/commit/ec7cbaf266)] - <ide> [#12995](https://github.com/nodejs/node/pull/12995). <ide> * Add `--pending-deprecation` command-line argument and <ide> `NODE_PENDING_DEPRECATION` environment variable <del> [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] <add> [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] - <ide> [#11968](https://github.com/nodejs/node/pull/11968). <ide> * The `--debug` command-line argument has been deprecated. Note that <ide> using `--debug` will enable the *new* Inspector-based debug protocol <ide> as the legacy Debugger protocol previously used by Node.js has been <del> removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] <add> removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] - <ide> [#12949](https://github.com/nodejs/node/pull/12949). <ide> * Throw when the `-c` and `-e` command-line arguments are used at the same <del> time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] <add> time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] - <ide> [#11689](https://github.com/nodejs/node/pull/11689). <ide> * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line <ide> arguments are used at the same time. <del> [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] <add> [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] - <ide> [#12087](https://github.com/nodejs/node/pull/12087). <ide> <ide> * **Stream** <ide> * `Stream` now supports `destroy()` and `_destroy()` APIs <del> [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] <add> [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] - <ide> [#12925](https://github.com/nodejs/node/pull/12925). <ide> * `Stream` now supports the `_final()` API <del> [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] <add> [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] - <ide> [#12828](https://github.com/nodejs/node/pull/12828). <ide> <ide> * **TLS** <ide> * The `rejectUnauthorized` option now defaults to `true` <del> [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] <add> [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] - <ide> [#5923](https://github.com/nodejs/node/pull/5923). <ide> * The `tls.createSecurePair()` API now emits a runtime deprecation <del> [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] <add> [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] - <ide> [#11349](https://github.com/nodejs/node/pull/11349). <ide> * A runtime deprecation will now be emitted when `dhparam` is less than <del> 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] <add> 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] - <ide> [#11447](https://github.com/nodejs/node/pull/11447). <ide> <ide> * **URL** <ide> * The WHATWG URL implementation is now a fully-supported Node.js API <del> [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] <add> [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] - <ide> [#12710](https://github.com/nodejs/node/pull/12710). <ide> <ide> * **Util** <ide> * `Symbol` keys are now displayed by default when using `util.inspect()` <del> [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] <add> [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] - <ide> [#9726](https://github.com/nodejs/node/pull/9726). <ide> * `toJSON` errors will be thrown when formatting `%j` <del> [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] <add> [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] - <ide> [#11708](https://github.com/nodejs/node/pull/11708). <ide> * Convert `inspect.styles` and `inspect.colors` to prototype-less objects <del> [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] <add> [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] - <ide> [#11624](https://github.com/nodejs/node/pull/11624). <ide> * The new `util.promisify()` API has been added <del> [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] <add> [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] - <ide> [#12442](https://github.com/nodejs/node/pull/12442). <ide> <ide> * **Zlib** <ide> * Support `Uint8Array` in Zlib convenience methods <del> [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] <add> [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] - <ide> [#12001](https://github.com/nodejs/node/pull/12001). <ide> * Zlib errors now use `RangeError` and `TypeError` consistently <del> [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] <add> [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] - <ide> [#11391](https://github.com/nodejs/node/pull/11391). <ide> <ide> ### Commits <ide><path>doc/changelogs/CHANGELOG_V9.md <ide> Fixes for the following CVEs are included in this release: <ide> ### Notable Changes <ide> <ide> * **Async hooks** <del> * Older experimental APIs have been removed. [[`d731369b1d`](https://github.com/nodejs/node/commit/d731369b1d)] [#14414](https://github.com/nodejs/node/pull/14414) <add> * Older experimental APIs have been removed. [[`d731369b1d`](https://github.com/nodejs/node/commit/d731369b1d)] - [#14414](https://github.com/nodejs/node/pull/14414) <ide> <ide> * **Errors** <del> * Improvements have been made to `buffer` module error messages. [[`9e0f771224`](https://github.com/nodejs/node/commit/9e0f771224)] [#14975](https://github.com/nodejs/node/pull/14975) <add> * Improvements have been made to `buffer` module error messages. [[`9e0f771224`](https://github.com/nodejs/node/commit/9e0f771224)] - [#14975](https://github.com/nodejs/node/pull/14975) <ide> * The assignment of static error codes to Node.js error continues: <del> * `buffer`: [[`e79a61cf80`](https://github.com/nodejs/node/commit/e79a61cf80)] [#16352](https://github.com/nodejs/node/pull/16352), [[`dbfe8c4ea2`](https://github.com/nodejs/node/commit/dbfe8c4ea2)] [#13976](https://github.com/nodejs/node/pull/13976) <del> * `child_process`: [[`fe730d34ce`](https://github.com/nodejs/node/commit/fe730d34ce)] [#14009](https://github.com/nodejs/node/pull/14009) <del> * `console`: [[`0ecdf29340`](https://github.com/nodejs/node/commit/0ecdf29340)] [#11340](https://github.com/nodejs/node/pull/11340) <del> * `crypto`: [[`ee76f3153b`](https://github.com/nodejs/node/commit/ee76f3153b)] [#16428](https://github.com/nodejs/node/pull/16428), [[`df8c6c3651`](https://github.com/nodejs/node/commit/df8c6c3651)] [#16453](https://github.com/nodejs/node/pull/16453), [[`0a03e350fb`](https://github.com/nodejs/node/commit/0a03e350fb)] [#16454](https://github.com/nodejs/node/pull/16454), [[`eeada6ca63`](https://github.com/nodejs/node/commit/eeada6ca63)] [#16448](https://github.com/nodejs/node/pull/16448), [[`a78327f48b`](https://github.com/nodejs/node/commit/a78327f48b)] [#16429](https://github.com/nodejs/node/pull/16429), [[`b8bc652869`](https://github.com/nodejs/node/commit/b8bc652869)] [#15757](https://github.com/nodejs/node/pull/15757), [[`7124b466d9`](https://github.com/nodejs/node/commit/7124b466d9)] [#15746](https://github.com/nodejs/node/pull/15746), [[`3ddc88b5c2`](https://github.com/nodejs/node/commit/3ddc88b5c2)] [#15756](https://github.com/nodejs/node/pull/15756) <del> * `dns`: [[`9cb390d899`](https://github.com/nodejs/node/commit/9cb390d899)] [#14212](https://github.com/nodejs/node/pull/14212) <del> * `events`: [[`e5ad5456a2`](https://github.com/nodejs/node/commit/e5ad5456a2)] [#15623](https://github.com/nodejs/node/pull/15623) <del> * `fs`: [[`219932a9f7`](https://github.com/nodejs/node/commit/219932a9f7)] [#15043](https://github.com/nodejs/node/pull/15043), [[`b61cab2234`](https://github.com/nodejs/node/commit/b61cab2234)] [#11317](https://github.com/nodejs/node/pull/11317) <del> * `http`: [[`11a2ca29ba`](https://github.com/nodejs/node/commit/11a2ca29ba)] [#14735](https://github.com/nodejs/node/pull/14735), [[`a9f798ebcc`](https://github.com/nodejs/node/commit/a9f798ebcc)] [#13301](https://github.com/nodejs/node/pull/13301), [[`bdfbce9241`](https://github.com/nodejs/node/commit/bdfbce9241)] [#14423](https://github.com/nodejs/node/pull/14423), [[`4843c2f415`](https://github.com/nodejs/node/commit/4843c2f415)] [#15603](https://github.com/nodejs/node/pull/15603) <del> * `inspector`: [[`4cf56ad6f2`](https://github.com/nodejs/node/commit/4cf56ad6f2)] [#15619](https://github.com/nodejs/node/pull/15619) <del> * `net`: [[`a03d8cee1f`](https://github.com/nodejs/node/commit/a03d8cee1f)] [#11356](https://github.com/nodejs/node/pull/11356), [[`7f55349079`](https://github.com/nodejs/node/commit/7f55349079)] [#14782](https://github.com/nodejs/node/pull/14782) <del> * `path`: [[`dcfbbacba8`](https://github.com/nodejs/node/commit/dcfbbacba8)] [#11319](https://github.com/nodejs/node/pull/11319) <del> * `process`: [[`a0f7284346`](https://github.com/nodejs/node/commit/a0f7284346)] [#13739](https://github.com/nodejs/node/pull/13739), [[`062071a9c3`](https://github.com/nodejs/node/commit/062071a9c3)] [#13285](https://github.com/nodejs/node/pull/13285), [[`3129b2c035`](https://github.com/nodejs/node/commit/3129b2c035)] [#13982](https://github.com/nodejs/node/pull/13982) <del> * `querystring`: [[`9788e96836`](https://github.com/nodejs/node/commit/9788e96836)] [#15565](https://github.com/nodejs/node/pull/15565) <del> * `readline`: [[`7f3f72c19b`](https://github.com/nodejs/node/commit/7f3f72c19b)] [#11390](https://github.com/nodejs/node/pull/11390) <del> * `repl`: [[`aff8d358fa`](https://github.com/nodejs/node/commit/aff8d358fa)] [#11347](https://github.com/nodejs/node/pull/11347), [[`28227963fa`](https://github.com/nodejs/node/commit/28227963fa)] [#13299](https://github.com/nodejs/node/pull/13299) <del> * `streams`: [[`d50a802feb`](https://github.com/nodejs/node/commit/d50a802feb)] [#13310](https://github.com/nodejs/node/pull/13310), [[`d2913384aa`](https://github.com/nodejs/node/commit/d2913384aa)] [#13291](https://github.com/nodejs/node/pull/13291), [[`6e86a6651c`](https://github.com/nodejs/node/commit/6e86a6651c)] [#16589](https://github.com/nodejs/node/pull/16589), [[`88fb359c57`](https://github.com/nodejs/node/commit/88fb359c57)] [#15042](https://github.com/nodejs/node/pull/15042), [[`db7d1339c3`](https://github.com/nodejs/node/commit/db7d1339c3)] [#15665](https://github.com/nodejs/node/pull/15665) <del> * `string_decoder`: [[`eb4940e2d2`](https://github.com/nodejs/node/commit/eb4940e2d2)] [#14682](https://github.com/nodejs/node/pull/14682) <del> * `timers`: [[`4d893e093a`](https://github.com/nodejs/node/commit/4d893e093a)] [#14659](https://github.com/nodejs/node/pull/14659) <del> * `tls`: [[`f67aa566a6`](https://github.com/nodejs/node/commit/f67aa566a6)] [#13476](https://github.com/nodejs/node/pull/13476), [[`3ccfeb483d`](https://github.com/nodejs/node/commit/3ccfeb483d)] [#13994](https://github.com/nodejs/node/pull/13994) <del> * `url`: [[`473f0eff29`](https://github.com/nodejs/node/commit/473f0eff29)] [#13963](https://github.com/nodejs/node/pull/13963) <del> * `util`: [[`de4a749788`](https://github.com/nodejs/node/commit/de4a749788)] [#11301](https://github.com/nodejs/node/pull/11301), [[`1609899142`](https://github.com/nodejs/node/commit/1609899142)] [#13293](https://github.com/nodejs/node/pull/13293) <del> * `v8`: [[`ef238fb485`](https://github.com/nodejs/node/commit/ef238fb485)] [#16535](https://github.com/nodejs/node/pull/16535) <del> * `zlib`: [[`896eaf6820`](https://github.com/nodejs/node/commit/896eaf6820)] [#16540](https://github.com/nodejs/node/pull/16540), [[`74891412f1`](https://github.com/nodejs/node/commit/74891412f1)] [#15618](https://github.com/nodejs/node/pull/15618) <add> * `buffer`: [[`e79a61cf80`](https://github.com/nodejs/node/commit/e79a61cf80)] - [#16352](https://github.com/nodejs/node/pull/16352), [[`dbfe8c4ea2`](https://github.com/nodejs/node/commit/dbfe8c4ea2)] - [#13976](https://github.com/nodejs/node/pull/13976) <add> * `child_process`: [[`fe730d34ce`](https://github.com/nodejs/node/commit/fe730d34ce)] - [#14009](https://github.com/nodejs/node/pull/14009) <add> * `console`: [[`0ecdf29340`](https://github.com/nodejs/node/commit/0ecdf29340)] - [#11340](https://github.com/nodejs/node/pull/11340) <add> * `crypto`: [[`ee76f3153b`](https://github.com/nodejs/node/commit/ee76f3153b)] - [#16428](https://github.com/nodejs/node/pull/16428), [[`df8c6c3651`](https://github.com/nodejs/node/commit/df8c6c3651)] - [#16453](https://github.com/nodejs/node/pull/16453), [[`0a03e350fb`](https://github.com/nodejs/node/commit/0a03e350fb)] - [#16454](https://github.com/nodejs/node/pull/16454), [[`eeada6ca63`](https://github.com/nodejs/node/commit/eeada6ca63)] - [#16448](https://github.com/nodejs/node/pull/16448), [[`a78327f48b`](https://github.com/nodejs/node/commit/a78327f48b)] - [#16429](https://github.com/nodejs/node/pull/16429), [[`b8bc652869`](https://github.com/nodejs/node/commit/b8bc652869)] - [#15757](https://github.com/nodejs/node/pull/15757), [[`7124b466d9`](https://github.com/nodejs/node/commit/7124b466d9)] - [#15746](https://github.com/nodejs/node/pull/15746), [[`3ddc88b5c2`](https://github.com/nodejs/node/commit/3ddc88b5c2)] - [#15756](https://github.com/nodejs/node/pull/15756) <add> * `dns`: [[`9cb390d899`](https://github.com/nodejs/node/commit/9cb390d899)] - [#14212](https://github.com/nodejs/node/pull/14212) <add> * `events`: [[`e5ad5456a2`](https://github.com/nodejs/node/commit/e5ad5456a2)] - [#15623](https://github.com/nodejs/node/pull/15623) <add> * `fs`: [[`219932a9f7`](https://github.com/nodejs/node/commit/219932a9f7)] - [#15043](https://github.com/nodejs/node/pull/15043), [[`b61cab2234`](https://github.com/nodejs/node/commit/b61cab2234)] - [#11317](https://github.com/nodejs/node/pull/11317) <add> * `http`: [[`11a2ca29ba`](https://github.com/nodejs/node/commit/11a2ca29ba)] - [#14735](https://github.com/nodejs/node/pull/14735), [[`a9f798ebcc`](https://github.com/nodejs/node/commit/a9f798ebcc)] - [#13301](https://github.com/nodejs/node/pull/13301), [[`bdfbce9241`](https://github.com/nodejs/node/commit/bdfbce9241)] - [#14423](https://github.com/nodejs/node/pull/14423), [[`4843c2f415`](https://github.com/nodejs/node/commit/4843c2f415)] - [#15603](https://github.com/nodejs/node/pull/15603) <add> * `inspector`: [[`4cf56ad6f2`](https://github.com/nodejs/node/commit/4cf56ad6f2)] - [#15619](https://github.com/nodejs/node/pull/15619) <add> * `net`: [[`a03d8cee1f`](https://github.com/nodejs/node/commit/a03d8cee1f)] - [#11356](https://github.com/nodejs/node/pull/11356), [[`7f55349079`](https://github.com/nodejs/node/commit/7f55349079)] - [#14782](https://github.com/nodejs/node/pull/14782) <add> * `path`: [[`dcfbbacba8`](https://github.com/nodejs/node/commit/dcfbbacba8)] - [#11319](https://github.com/nodejs/node/pull/11319) <add> * `process`: [[`a0f7284346`](https://github.com/nodejs/node/commit/a0f7284346)] - [#13739](https://github.com/nodejs/node/pull/13739), [[`062071a9c3`](https://github.com/nodejs/node/commit/062071a9c3)] - [#13285](https://github.com/nodejs/node/pull/13285), [[`3129b2c035`](https://github.com/nodejs/node/commit/3129b2c035)] - [#13982](https://github.com/nodejs/node/pull/13982) <add> * `querystring`: [[`9788e96836`](https://github.com/nodejs/node/commit/9788e96836)] - [#15565](https://github.com/nodejs/node/pull/15565) <add> * `readline`: [[`7f3f72c19b`](https://github.com/nodejs/node/commit/7f3f72c19b)] - [#11390](https://github.com/nodejs/node/pull/11390) <add> * `repl`: [[`aff8d358fa`](https://github.com/nodejs/node/commit/aff8d358fa)] - [#11347](https://github.com/nodejs/node/pull/11347), [[`28227963fa`](https://github.com/nodejs/node/commit/28227963fa)] - [#13299](https://github.com/nodejs/node/pull/13299) <add> * `streams`: [[`d50a802feb`](https://github.com/nodejs/node/commit/d50a802feb)] - [#13310](https://github.com/nodejs/node/pull/13310), [[`d2913384aa`](https://github.com/nodejs/node/commit/d2913384aa)] - [#13291](https://github.com/nodejs/node/pull/13291), [[`6e86a6651c`](https://github.com/nodejs/node/commit/6e86a6651c)] - [#16589](https://github.com/nodejs/node/pull/16589), [[`88fb359c57`](https://github.com/nodejs/node/commit/88fb359c57)] - [#15042](https://github.com/nodejs/node/pull/15042), [[`db7d1339c3`](https://github.com/nodejs/node/commit/db7d1339c3)] - [#15665](https://github.com/nodejs/node/pull/15665) <add> * `string_decoder`: [[`eb4940e2d2`](https://github.com/nodejs/node/commit/eb4940e2d2)] - [#14682](https://github.com/nodejs/node/pull/14682) <add> * `timers`: [[`4d893e093a`](https://github.com/nodejs/node/commit/4d893e093a)] - [#14659](https://github.com/nodejs/node/pull/14659) <add> * `tls`: [[`f67aa566a6`](https://github.com/nodejs/node/commit/f67aa566a6)] - [#13476](https://github.com/nodejs/node/pull/13476), [[`3ccfeb483d`](https://github.com/nodejs/node/commit/3ccfeb483d)] - [#13994](https://github.com/nodejs/node/pull/13994) <add> * `url`: [[`473f0eff29`](https://github.com/nodejs/node/commit/473f0eff29)] - [#13963](https://github.com/nodejs/node/pull/13963) <add> * `util`: [[`de4a749788`](https://github.com/nodejs/node/commit/de4a749788)] - [#11301](https://github.com/nodejs/node/pull/11301), [[`1609899142`](https://github.com/nodejs/node/commit/1609899142)] - [#13293](https://github.com/nodejs/node/pull/13293) <add> * `v8`: [[`ef238fb485`](https://github.com/nodejs/node/commit/ef238fb485)] - [#16535](https://github.com/nodejs/node/pull/16535) <add> * `zlib`: [[`896eaf6820`](https://github.com/nodejs/node/commit/896eaf6820)] - [#16540](https://github.com/nodejs/node/pull/16540), [[`74891412f1`](https://github.com/nodejs/node/commit/74891412f1)] - [#15618](https://github.com/nodejs/node/pull/15618) <ide> <ide> * **Child Processes** <del> * Errors are emitted on process nextTick. [[`f2b01cba7b`](https://github.com/nodejs/node/commit/f2b01cba7b)] [#4670](https://github.com/nodejs/node/pull/4670) <add> * Errors are emitted on process nextTick. [[`f2b01cba7b`](https://github.com/nodejs/node/commit/f2b01cba7b)] - [#4670](https://github.com/nodejs/node/pull/4670) <ide> <ide> * **Domains** <del> * The long-deprecated `.dispose()` method has been removed [[`602fd36d95`](https://github.com/nodejs/node/commit/602fd36d95)] [#15412](https://github.com/nodejs/node/pull/15412) <add> * The long-deprecated `.dispose()` method has been removed [[`602fd36d95`](https://github.com/nodejs/node/commit/602fd36d95)] - [#15412](https://github.com/nodejs/node/pull/15412) <ide> <ide> * **fs** <del> * The `fs.ReadStream` and `fs.WriteStream` classes now use `destroy()`. [[`e5c290bed9`](https://github.com/nodejs/node/commit/e5c290bed9)] [#15407](https://github.com/nodejs/node/pull/15407) <del> * `fs` module callbacks are now invoked with an undefined context. [[`2249234fee`](https://github.com/nodejs/node/commit/2249234fee)] [#14645](https://github.com/nodejs/node/pull/14645) <add> * The `fs.ReadStream` and `fs.WriteStream` classes now use `destroy()`. [[`e5c290bed9`](https://github.com/nodejs/node/commit/e5c290bed9)] - [#15407](https://github.com/nodejs/node/pull/15407) <add> * `fs` module callbacks are now invoked with an undefined context. [[`2249234fee`](https://github.com/nodejs/node/commit/2249234fee)] - [#14645](https://github.com/nodejs/node/pull/14645) <ide> <ide> * **HTTP/1** <del> * A 400 Bad Request response will now be sent when parsing fails. [[`f2f391e575`](https://github.com/nodejs/node/commit/f2f391e575)] [#15324](https://github.com/nodejs/node/pull/15324) <del> * Socket timeout will be set when the socket connects. [[`10be20a0e8`](https://github.com/nodejs/node/commit/10be20a0e8)] [#8895](https://github.com/nodejs/node/pull/8895) <del> * A bug causing the request `'error'` event to fire twice was fixed. [[`620ba41694`](https://github.com/nodejs/node/commit/620ba41694)] [#14659](https://github.com/nodejs/node/pull/14659) <del> * HTTP clients may now use generic `Duplex` streams in addition to `net.Socket`. [[`3e25e4d00f`](https://github.com/nodejs/node/commit/3e25e4d00f)] [#16267](https://github.com/nodejs/node/pull/16267) <add> * A 400 Bad Request response will now be sent when parsing fails. [[`f2f391e575`](https://github.com/nodejs/node/commit/f2f391e575)] - [#15324](https://github.com/nodejs/node/pull/15324) <add> * Socket timeout will be set when the socket connects. [[`10be20a0e8`](https://github.com/nodejs/node/commit/10be20a0e8)] - [#8895](https://github.com/nodejs/node/pull/8895) <add> * A bug causing the request `'error'` event to fire twice was fixed. [[`620ba41694`](https://github.com/nodejs/node/commit/620ba41694)] - [#14659](https://github.com/nodejs/node/pull/14659) <add> * HTTP clients may now use generic `Duplex` streams in addition to `net.Socket`. [[`3e25e4d00f`](https://github.com/nodejs/node/commit/3e25e4d00f)] - [#16267](https://github.com/nodejs/node/pull/16267) <ide> <ide> * **Intl** <del> * The deprecated `Intl.v8BreakIterator` has been removed. [[`668ad44922`](https://github.com/nodejs/node/commit/668ad44922)] [#15238](https://github.com/nodejs/node/pull/15238) <add> * The deprecated `Intl.v8BreakIterator` has been removed. [[`668ad44922`](https://github.com/nodejs/node/commit/668ad44922)] - [#15238](https://github.com/nodejs/node/pull/15238) <ide> <ide> * **OS** <del> * The `os.EOL` property is now read-only [[`f6caeb9526`](https://github.com/nodejs/node/commit/f6caeb9526)] [#14622](https://github.com/nodejs/node/pull/14622) <add> * The `os.EOL` property is now read-only [[`f6caeb9526`](https://github.com/nodejs/node/commit/f6caeb9526)] - [#14622](https://github.com/nodejs/node/pull/14622) <ide> <ide> * **Timers** <del> * `setTimeout()` will emit a warning if the timeout is larger that the maximum 32-bit unsigned integer. [[`ce3586da31`](https://github.com/nodejs/node/commit/ce3586da31)] [#15627](https://github.com/nodejs/node/pull/15627) <add> * `setTimeout()` will emit a warning if the timeout is larger that the maximum 32-bit unsigned integer. [[`ce3586da31`](https://github.com/nodejs/node/commit/ce3586da31)] - [#15627](https://github.com/nodejs/node/pull/15627) <ide> <ide> ### Commits <ide>
2
Javascript
Javascript
remove unused polyvinyl functions
128cb813cb9d145dce3ee2e7c48384046a1af7b0
<ide><path>client/src/templates/Challenges/rechallenge/transformers.js <ide> import { <ide> <ide> import protect from '@freecodecamp/loop-protect'; <ide> <del>import * as vinyl from '../../../../../utils/polyvinyl.js'; <add>import { <add> transformContents, <add> transformHeadTailAndContents, <add> setExt, <add> compileHeadTail <add>} from '../../../../../utils/polyvinyl'; <ide> import createWorker from '../utils/worker-executor'; <ide> <ide> // the config files are created during the build, but not before linting <ide> export const testJS$JSX = overSome(testJS, testJSX); <ide> export const replaceNBSP = cond([ <ide> [ <ide> testHTML$JS$JSX, <del> partial(vinyl.transformContents, contents => contents.replace(NBSPReg, ' ')) <add> partial(transformContents, contents => contents.replace(NBSPReg, ' ')) <ide> ], <ide> [stubTrue, identity] <ide> ]); <ide> const babelTransformer = options => { <ide> await loadPresetEnv(); <ide> const babelOptions = getBabelOptions(options); <ide> return partial( <del> vinyl.transformHeadTailAndContents, <add> transformHeadTailAndContents, <ide> tryTransform(babelTransformCode(babelOptions)) <ide> )(code); <ide> } <ide> const babelTransformer = options => { <ide> await loadPresetReact(); <ide> return flow( <ide> partial( <del> vinyl.transformHeadTailAndContents, <add> transformHeadTailAndContents, <ide> tryTransform(babelTransformCode(babelOptionsJSX)) <ide> ), <del> partial(vinyl.setExt, 'js') <add> partial(setExt, 'js') <ide> )(code); <ide> } <ide> ], <ide> const transformHtml = async function (file) { <ide> const div = document.createElement('div'); <ide> div.innerHTML = file.contents; <ide> await Promise.all([transformSASS(div), transformScript(div)]); <del> return vinyl.transformContents(() => div.innerHTML, file); <add> return transformContents(() => div.innerHTML, file); <ide> }; <ide> <ide> export const composeHTML = cond([ <ide> [ <ide> testHTML, <ide> flow( <del> partial(vinyl.transformHeadTailAndContents, source => { <add> partial(transformHeadTailAndContents, source => { <ide> const div = document.createElement('div'); <ide> div.innerHTML = source; <ide> return div.innerHTML; <ide> }), <del> partial(vinyl.compileHeadTail, '') <add> partial(compileHeadTail, '') <ide> ) <ide> ], <ide> [stubTrue, identity] <ide><path>utils/polyvinyl.js <ide> // originally based off of https://github.com/gulpjs/vinyl <ide> const invariant = require('invariant'); <del>const { of, from, isObservable } = require('rxjs'); <del>const { map, switchMap } = require('rxjs/operators'); <del> <del>function isPromise(value) { <del> return ( <del> value && <del> typeof value.subscribe !== 'function' && <del> typeof value.then === 'function' <del> ); <del>} <del> <del>function castToObservable(maybe) { <del> if (isObservable(maybe)) { <del> return maybe; <del> } <del> if (isPromise(maybe)) { <del> return from(maybe); <del> } <del> return of(maybe); <del>} <del> <del>// createFileStream( <del>// files: [...PolyVinyl] <del>// ) => Observable[...Observable[...PolyVinyl]] <del>function createFileStream(files = []) { <del> return of(from(files)); <del>} <del> <del>// Observable::pipe( <del>// project( <del>// file: PolyVinyl <del>// ) => PolyVinyl|Observable[PolyVinyl]|Promise[PolyVinyl] <del>// ) => Observable[...Observable[...PolyVinyl]] <del>function pipe(project) { <del> const source = this; <del> return source.pipe( <del> map(files => { <del> return files.pipe(switchMap(file => castToObservable(project(file)))); <del> }) <del> ); <del>} <ide> <ide> // interface PolyVinyl { <ide> // source: String, <ide> function checkPoly(poly) { <ide> ); <ide> } <ide> <del>// isEmpty(poly: PolyVinyl) => Boolean, throws <del>function isEmpty(poly) { <del> checkPoly(poly); <del> return !!poly.contents; <del>} <del> <ide> // setContent(contents: String, poly: PolyVinyl) => PolyVinyl <ide> // setContent will loose source if set <ide> function setContent(contents, poly) { <ide> function setExt(ext, poly) { <ide> return newPoly; <ide> } <ide> <del>// setName(name: String, poly: PolyVinyl) => PolyVinyl <del>function setName(name, poly) { <del> checkPoly(poly); <del> const newPoly = { <del> ...poly, <del> name, <del> path: name + '.' + poly.ext, <del> key: name + poly.ext <del> }; <del> newPoly.history = [...poly.history, newPoly.path]; <del> return newPoly; <del>} <del> <del>// setError(error: Object, poly: PolyVinyl) => PolyVinyl <del>function setError(error, poly) { <del> invariant( <del> typeof error === 'object', <del> 'error must be an object or null, but got %', <del> error <del> ); <del> checkPoly(poly); <del> return { <del> ...poly, <del> error <del> }; <del>} <del> <ide> // clearHeadTail(poly: PolyVinyl) => PolyVinyl <ide> function clearHeadTail(poly) { <ide> checkPoly(poly); <ide> function clearHeadTail(poly) { <ide> }; <ide> } <ide> <del>// appendToTail (tail: String, poly: PolyVinyl) => PolyVinyl <del>function appendToTail(tail, poly) { <del> checkPoly(poly); <del> return { <del> ...poly, <del> tail: poly.tail.concat(tail) <del> }; <del>} <del> <ide> // compileHeadTail(padding: String, poly: PolyVinyl) => PolyVinyl <ide> function compileHeadTail(padding = '', poly) { <ide> return clearHeadTail( <ide> function transformHeadTailAndContents(wrap, poly) { <ide> }; <ide> } <ide> <del>function testContents(predicate, poly) { <del> return !!predicate(poly.contents); <del>} <del> <del>function updateFileFromSpec(spec, poly) { <del> return setContent(poly.contents, createPoly(spec)); <del>} <del> <ide> module.exports = { <del> isPromise, <del> castToObservable, <del> createFileStream, <del> pipe, <ide> createPoly, <ide> isPoly, <del> checkPoly, <del> isEmpty, <ide> setContent, <ide> setExt, <del> setName, <del> setError, <del> clearHeadTail, <del> appendToTail, <ide> compileHeadTail, <ide> transformContents, <del> transformHeadTailAndContents, <del> testContents, <del> updateFileFromSpec <add> transformHeadTailAndContents <ide> };
2
Go
Go
fix memory swappiness lxc
a38b544ef082bcea76c4ea13e19d935ac09d3498
<ide><path>daemon/execdriver/lxc/lxc_template.go <ide> lxc.cgroup.blkio.weight = {{.Resources.BlkioWeight}} <ide> {{if .Resources.OomKillDisable}} <ide> lxc.cgroup.memory.oom_control = {{.Resources.OomKillDisable}} <ide> {{end}} <del>{{if .Resources.MemorySwappiness}} <add>{{if gt .Resources.MemorySwappiness 0}} <ide> lxc.cgroup.memory.swappiness = {{.Resources.MemorySwappiness}} <ide> {{end}} <ide> {{end}}
1
Javascript
Javascript
add switch example
c9c14ef6872eb90b7305e0bc19cded76ce851186
<ide><path>packages/rn-tester/js/examples/Switch/SwitchExample.js <ide> 'use strict'; <ide> <ide> const React = require('react'); <del>const {Switch, Text, View} = require('react-native'); <add>const {Switch, Text, View, Platform} = require('react-native'); <ide> <ide> type OnOffIndicatorProps = $ReadOnly<{|on: boolean, testID: string|}>; <ide> function OnOffIndicator({on, testID}: OnOffIndicatorProps) { <ide> class EventSwitchExample extends React.Component<{...}, $FlowFixMeState> { <ide> } <ide> } <ide> <add>class IOSBackgroundColEx extends React.Component<{...}, $FlowFixMeState> { <add> state = { <add> iosBackgroundColor: '#ffa500', <add> }; <add> <add> render() { <add> return ( <add> <View> <add> <Switch <add> disabled <add> ios_backgroundColor={this.state.iosBackgroundColor} <add> style={{marginBottom: 20}} <add> /> <add> <Text> <add> The background color can be seen either when the switch value is false <add> or when the switch is disabled (and the switch is translucent).{' '} <add> </Text> <add> </View> <add> ); <add> } <add>} <add> <add>class OnChangeExample extends React.Component<{...}, $FlowFixMeState> { <add> render() { <add> return ( <add> <View> <add> <Switch onChange={() => alert('OnChange Called')} /> <add> </View> <add> ); <add> } <add>} <add> <ide> exports.title = 'Switch'; <ide> exports.documentationURL = 'https://reactnative.dev/docs/switch'; <ide> exports.category = 'UI'; <ide> exports.examples = [ <ide> return <ColorSwitchExample />; <ide> }, <ide> }, <add> { <add> title: 'OnChange receives the change event as an argument', <add> render(): React.Element<any> { <add> return <OnChangeExample />; <add> }, <add> }, <ide> ]; <add> <add>if (Platform.OS === 'ios') { <add> exports.examples.push({ <add> title: '[iOS Only] Custom background colors can be set', <add> render(): React.Element<any> { <add> return <IOSBackgroundColEx />; <add> }, <add> }); <add>}
1
Ruby
Ruby
handle nil runtime_dependencies
4e5c8a35e54cf999b85eb3f393b043d208bae2c3
<ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade_formula(f) <ide> # @private <ide> def depends_on(a, b) <ide> if a.opt_or_installed_prefix_keg <del> .runtime_dependencies <del> .any? { |d| d["full_name"] == b.full_name } <add> &.runtime_dependencies <add> &.any? { |d| d["full_name"] == b.full_name } <ide> 1 <ide> else <ide> a <=> b
1
Javascript
Javascript
use primordials when calling methods of error
1da672994ac26658375db2b6a60fb00e56d02a4d
<ide><path>lib/assert.js <ide> <ide> const { <ide> Error, <add> ErrorCaptureStackTrace, <ide> ObjectAssign, <ide> ObjectIs, <ide> ObjectKeys, <ide> function getErrMessage(message, fn) { <ide> // We only need the stack trace. To minimize the overhead use an object <ide> // instead of an error. <ide> const err = {}; <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(err, fn); <add> ErrorCaptureStackTrace(err, fn); <ide> Error.stackTraceLimit = tmpLimit; <ide> <ide> overrideStackTrace.set(err, (_, stack) => stack); <ide> function hasMatchingError(actual, expected) { <ide> if (expected.prototype !== undefined && actual instanceof expected) { <ide> return true; <ide> } <del> if (Error.isPrototypeOf(expected)) { <add> if (ObjectPrototypeIsPrototypeOf(Error, expected)) { <ide> return false; <ide> } <ide> return expected.call({}, actual) === true; <ide><path>lib/events.js <ide> const { <ide> Boolean, <ide> Error, <add> ErrorCaptureStackTrace, <ide> MathMin, <ide> NumberIsNaN, <ide> ObjectCreate, <ide> EventEmitter.prototype.emit = function emit(type, ...args) { <ide> if (er instanceof Error) { <ide> try { <ide> const capture = {}; <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(capture, EventEmitter.prototype.emit); <add> ErrorCaptureStackTrace(capture, EventEmitter.prototype.emit); <ide> ObjectDefineProperty(er, kEnhanceStackBeforeInspector, { <ide> value: enhanceStackTrace.bind(this, er, capture), <ide> configurable: true <ide><path>lib/internal/assert/assertion_error.js <ide> <ide> const { <ide> Error, <add> ErrorCaptureStackTrace, <ide> MathMax, <ide> ObjectCreate, <ide> ObjectDefineProperty, <ide> class AssertionError extends Error { <ide> this.expected = expected; <ide> this.operator = operator; <ide> } <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(this, stackStartFn || stackStartFunction); <add> ErrorCaptureStackTrace(this, stackStartFn || stackStartFunction); <ide> // Create error message including the error code in the name. <ide> this.stack; <ide> // Reset the name. <ide><path>lib/internal/async_hooks.js <ide> <ide> const { <ide> ArrayPrototypeUnshift, <del> Error, <add> ErrorCaptureStackTrace, <ide> FunctionPrototypeBind, <ide> ObjectPrototypeHasOwnProperty, <ide> ObjectDefineProperty, <ide> function fatalError(e) { <ide> process._rawDebug(e.stack); <ide> } else { <ide> const o = { message: e }; <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(o, fatalError); <add> ErrorCaptureStackTrace(o, fatalError); <ide> process._rawDebug(o.stack); <ide> } <ide> <ide><path>lib/internal/console/constructor.js <ide> const { <ide> ArrayFrom, <ide> ArrayIsArray, <ide> Boolean, <del> Error, <add> ErrorCaptureStackTrace, <ide> Map, <ide> MathFloor, <ide> Number, <ide> const consoleMethods = { <ide> name: 'Trace', <ide> message: this[kFormatForStderr](args) <ide> }; <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(err, trace); <add> ErrorCaptureStackTrace(err, trace); <ide> this.error(err.stack); <ide> }, <ide> <ide><path>lib/internal/errors.js <ide> const { <ide> ArrayIsArray, <ide> Error, <add> ErrorCaptureStackTrace, <ide> ErrorPrototypeToString, <ide> JSONStringify, <ide> Map, <ide> function hideStackFrames(fn) { <ide> function addCodeToName(err, name, code) { <ide> // Set the stack <ide> if (excludedStackFn !== undefined) { <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(err, excludedStackFn); <add> ErrorCaptureStackTrace(err, excludedStackFn); <ide> } <ide> // Add the error code to the name to include it in the stack trace. <ide> err.name = `${name} [${code}]`; <ide> function uvException(ctx) { <ide> if (dest) { <ide> err.dest = dest; <ide> } <del> <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(err, excludedStackFn || uvException); <add> ErrorCaptureStackTrace(err, excludedStackFn || uvException); <ide> return err; <ide> } <ide> <ide> function uvExceptionWithHostPort(err, syscall, address, port) { <ide> if (port) { <ide> ex.port = port; <ide> } <del> <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(ex, excludedStackFn || uvExceptionWithHostPort); <add> ErrorCaptureStackTrace(ex, excludedStackFn || uvExceptionWithHostPort); <ide> return ex; <ide> } <ide> <ide> function errnoException(err, syscall, original) { <ide> ex.errno = err; <ide> ex.code = code; <ide> ex.syscall = syscall; <del> <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(ex, excludedStackFn || errnoException); <add> ErrorCaptureStackTrace(ex, excludedStackFn || errnoException); <ide> return ex; <ide> } <ide> <ide> function exceptionWithHostPort(err, syscall, address, port, additional) { <ide> if (port) { <ide> ex.port = port; <ide> } <del> <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(ex, excludedStackFn || exceptionWithHostPort); <add> ErrorCaptureStackTrace(ex, excludedStackFn || exceptionWithHostPort); <ide> return ex; <ide> } <ide> <ide> function dnsException(code, syscall, hostname) { <ide> if (hostname) { <ide> ex.hostname = hostname; <ide> } <del> <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(ex, excludedStackFn || dnsException); <add> ErrorCaptureStackTrace(ex, excludedStackFn || dnsException); <ide> return ex; <ide> } <ide> <ide><path>lib/internal/fs/utils.js <ide> const { <ide> ArrayIsArray, <ide> BigInt, <ide> DateNow, <del> Error, <add> ErrorCaptureStackTrace, <ide> ObjectPrototypeHasOwnProperty, <ide> Number, <ide> NumberIsFinite, <ide> function getOptions(options, defaultOptions) { <ide> function handleErrorFromBinding(ctx) { <ide> if (ctx.errno !== undefined) { // libuv error numbers <ide> const err = uvException(ctx); <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(err, handleErrorFromBinding); <add> ErrorCaptureStackTrace(err, handleErrorFromBinding); <ide> throw err; <ide> } <ide> if (ctx.error !== undefined) { // Errors created in C++ land. <ide> // TODO(joyeecheung): currently, ctx.error are encoding errors <ide> // usually caused by memory problems. We need to figure out proper error <ide> // code(s) for this. <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(ctx.error, handleErrorFromBinding); <add> ErrorCaptureStackTrace(ctx.error, handleErrorFromBinding); <ide> throw ctx.error; <ide> } <ide> } <ide><path>lib/internal/process/warning.js <ide> const { <ide> ArrayIsArray, <ide> Error, <add> ErrorCaptureStackTrace, <ide> String, <ide> } = primordials; <ide> <ide> function createWarningObject(warning, type, code, ctor, detail) { <ide> warning.name = String(type || 'Warning'); <ide> if (code !== undefined) warning.code = code; <ide> if (detail !== undefined) warning.detail = detail; <del> // eslint-disable-next-line no-restricted-syntax <del> Error.captureStackTrace(warning, ctor || process.emitWarning); <add> ErrorCaptureStackTrace(warning, ctor || process.emitWarning); <ide> return warning; <ide> } <ide>
8
Javascript
Javascript
remove cachegroup argument from addmodule
52634e7a2dc616942e47f4a52157dda7b3de00f6
<ide><path>lib/Compilation.js <ide> class Compilation { <ide> <ide> /** <ide> * @param {Module} module module to be added that was created <del> * @param {any=} cacheGroup cacheGroup it is apart of <ide> * @returns {Module} returns the module in the compilation, <ide> * it could be the passed one (if new), or an already existing in the compilation <ide> */ <del> addModule(module, cacheGroup) { <add> addModule(module) { <ide> const identifier = module.identifier(); <ide> const alreadyAddedModule = this._modules.get(identifier); <ide> if (alreadyAddedModule) { <ide> return alreadyAddedModule; <ide> } <del> const cacheName = (cacheGroup || "m") + identifier; <add> const cacheName = "m" + identifier; <ide> if (this.cache && this.cache[cacheName]) { <ide> const cacheModule = this.cache[cacheName]; <ide>
1
Go
Go
introduce a checkcontainer to remove duplication
12485d62eeba27119260dc5eb54ac4fa83c3130b
<ide><path>daemon/container.go <ide> func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, e <ide> return daemon.containers.Get(containerID), nil <ide> } <ide> <add>// checkContainer make sure the specified container validates the specified conditions <add>func (daemon *Daemon) checkContainer(container *container.Container, conditions ...func(*container.Container) error) error { <add> for _, condition := range conditions { <add> if err := condition(container); err != nil { <add> return err <add> } <add> } <add> return nil <add>} <add> <ide> // Exists returns a true if a container of the specified ID or name exists, <ide> // false otherwise. <ide> func (daemon *Daemon) Exists(id string) bool { <ide><path>daemon/container_operations_unix.go <ide> func (daemon *Daemon) setupLinkedContainers(container *container.Container) ([]s <ide> <ide> func (daemon *Daemon) getIpcContainer(container *container.Container) (*container.Container, error) { <ide> containerID := container.HostConfig.IpcMode.Container() <del> c, err := daemon.GetContainer(containerID) <add> container, err := daemon.GetContainer(containerID) <ide> if err != nil { <del> return nil, err <add> return nil, errors.Wrapf(err, "cannot join IPC of a non running container: %s", container.ID) <ide> } <del> if !c.IsRunning() { <del> return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID) <del> } <del> if c.IsRestarting() { <del> return nil, errContainerIsRestarting(container.ID) <del> } <del> return c, nil <add> return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting) <ide> } <ide> <ide> func (daemon *Daemon) getPidContainer(container *container.Container) (*container.Container, error) { <ide> containerID := container.HostConfig.PidMode.Container() <del> c, err := daemon.GetContainer(containerID) <add> container, err := daemon.GetContainer(containerID) <ide> if err != nil { <del> return nil, err <add> return nil, errors.Wrapf(err, "cannot join PID of a non running container: %s", container.ID) <ide> } <add> return container, daemon.checkContainer(container, containerIsRunning, containerIsNotRestarting) <add>} <add> <add>func containerIsRunning(c *container.Container) error { <ide> if !c.IsRunning() { <del> return nil, fmt.Errorf("cannot join PID of a non running container: %s", containerID) <add> return errors.Errorf("container %s is not running", c.ID) <ide> } <add> return nil <add>} <add> <add>func containerIsNotRestarting(c *container.Container) error { <ide> if c.IsRestarting() { <del> return nil, errContainerIsRestarting(container.ID) <add> return errContainerIsRestarting(c.ID) <ide> } <del> return c, nil <add> return nil <ide> } <ide> <ide> func (daemon *Daemon) setupIpcDirs(c *container.Container) error {
2
Text
Text
add link to 3.x reference
e2e91fed7048b9f5190c46a007d9cec362f40ead
<ide><path>API.md <ide> # D3 API Reference <ide> <del>D3 4.0 is a [collection of modules](https://github.com/d3) that are designed to work together; you can use the modules independently, or you can use them together as part of the default build. The source and documentation for each module is available in its repository. Follow the links below to learn more. For an overview of changes between D3 3.x and 4.0, see [CHANGES](https://github.com/d3/d3/blob/master/CHANGES.md). <add>D3 4.0 is a [collection of modules](https://github.com/d3) that are designed to work together; you can use the modules independently, or you can use them together as part of the default build. The source and documentation for each module is available in its repository. Follow the links below to learn more. For an overview of changes between D3 3.x and 4.0, see [CHANGES](https://github.com/d3/d3/blob/master/CHANGES.md); see also the [3.x API reference](https://github.com/d3/d3-3.x-api-reference/blob/master/API-Reference.md). <ide> <ide> * [Arrays](#arrays-d3-array) ([Statistics](#statistics), [Search](#search), [Transformations](#transformations), [Histograms](#histograms)) <ide> * [Axes](#axes-d3-axis)
1
Ruby
Ruby
move auditor classes into separate files
dc11f02e16a223098f0ffc087764fe24c34ce973
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> require "digest" <ide> require "cli/parser" <ide> require "json" <add>require "formula_auditor" <ide> require "tap_auditor" <ide> <ide> module Homebrew <ide> def format_problem_lines(problems) <ide> def format_problem(message, location) <ide> "* #{location&.to_s&.dup&.concat(": ")}#{message.chomp.gsub("\n", "\n ")}" <ide> end <del> <del> class FormulaText <del> def initialize(path) <del> @text = path.open("rb", &:read) <del> @lines = @text.lines.to_a <del> end <del> <del> def without_patch <del> @text.split("\n__END__").first <del> end <del> <del> def trailing_newline? <del> /\Z\n/ =~ @text <del> end <del> <del> def =~(other) <del> other =~ @text <del> end <del> <del> def include?(s) <del> @text.include? s <del> end <del> <del> def line_number(regex, skip = 0) <del> index = @lines.drop(skip).index { |line| line =~ regex } <del> index ? index + 1 : nil <del> end <del> <del> def reverse_line_number(regex) <del> index = @lines.reverse.index { |line| line =~ regex } <del> index ? @lines.count - index : nil <del> end <del> end <del> <del> class FormulaAuditor <del> include FormulaCellarChecks <del> <del> attr_reader :formula, :text, :problems, :new_formula_problems <del> <del> def initialize(formula, options = {}) <del> @formula = formula <del> @versioned_formula = formula.versioned_formula? <del> @new_formula_inclusive = options[:new_formula] <del> @new_formula = options[:new_formula] && !@versioned_formula <del> @strict = options[:strict] <del> @online = options[:online] <del> @build_stable = options[:build_stable] <del> @git = options[:git] <del> @display_cop_names = options[:display_cop_names] <del> @only = options[:only] <del> @except = options[:except] <del> # Accept precomputed style offense results, for efficiency <del> @style_offenses = options[:style_offenses] <del> # Allow the formula tap to be set as homebrew/core, for testing purposes <del> @core_tap = formula.tap&.core_tap? || options[:core_tap] <del> @problems = [] <del> @new_formula_problems = [] <del> @text = FormulaText.new(formula.path) <del> @specs = %w[stable head].map { |s| formula.send(s) }.compact <del> @spdx_license_data = options[:spdx_license_data] <del> @spdx_exception_data = options[:spdx_exception_data] <del> @tap_audit_exceptions = options[:tap_audit_exceptions] <del> end <del> <del> def audit_style <del> return unless @style_offenses <del> <del> @style_offenses.each do |offense| <del> correction_status = "#{Tty.green}[Corrected]#{Tty.reset} " if offense.corrected? <del> <del> cop_name = "#{offense.cop_name}: " if @display_cop_names <del> message = "#{cop_name}#{correction_status}#{offense.message}" <del> <del> problem message, location: offense.location <del> end <del> end <del> <del> def audit_file <del> if formula.core_formula? && @versioned_formula <del> unversioned_formula = begin <del> # build this ourselves as we want e.g. homebrew/core to be present <del> full_name = if formula.tap <del> "#{formula.tap}/#{formula.name}" <del> else <del> formula.name <del> end <del> Formulary.factory(full_name.gsub(/@.*$/, "")).path <del> rescue FormulaUnavailableError, TapFormulaAmbiguityError, <del> TapFormulaWithOldnameAmbiguityError <del> Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb") <del> end <del> unless unversioned_formula.exist? <del> unversioned_name = unversioned_formula.basename(".rb") <del> problem "#{formula} is versioned but no #{unversioned_name} formula exists" <del> end <del> elsif @build_stable && <del> formula.stable? && <del> !@versioned_formula && <del> (versioned_formulae = formula.versioned_formulae - [formula]) && <del> versioned_formulae.present? <del> versioned_aliases = formula.aliases.grep(/.@\d/) <del> _, last_alias_version = versioned_formulae.map(&:name).last.split("@") <del> alias_name_major = "#{formula.name}@#{formula.version.major}" <del> alias_name_major_minor = "#{alias_name_major}.#{formula.version.minor}" <del> alias_name = if last_alias_version.split(".").length == 1 <del> alias_name_major <del> else <del> alias_name_major_minor <del> end <del> valid_alias_names = [alias_name_major, alias_name_major_minor] <del> <del> unless @core_tap <del> versioned_aliases.map! { |a| "#{formula.tap}/#{a}" } <del> valid_alias_names.map! { |a| "#{formula.tap}/#{a}" } <del> end <del> <del> # Fix naming based on what people expect. <del> if alias_name_major_minor == "adoptopenjdk@1.8" <del> valid_alias_names << "adoptopenjdk@8" <del> valid_alias_names.delete "adoptopenjdk@1" <del> end <del> <del> valid_versioned_aliases = versioned_aliases & valid_alias_names <del> invalid_versioned_aliases = versioned_aliases - valid_alias_names <del> <del> if valid_versioned_aliases.empty? <del> if formula.tap <del> problem <<~EOS <del> Formula has other versions so create a versioned alias: <del> cd #{formula.tap.alias_dir} <del> ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name} <del> EOS <del> else <del> problem "Formula has other versions so create an alias named #{alias_name}." <del> end <del> end <del> <del> if invalid_versioned_aliases.present? <del> problem <<~EOS <del> Formula has invalid versioned aliases: <del> #{invalid_versioned_aliases.join("\n ")} <del> EOS <del> end <del> end <del> end <del> <del> def self.aliases <del> # core aliases + tap alias names + tap alias full name <del> @aliases ||= Formula.aliases + Formula.tap_aliases <del> end <del> <del> def audit_formula_name <del> return unless @strict <del> return unless @core_tap <del> <del> name = formula.name <del> <del> problem "'#{name}' is not allowed in homebrew/core." if MissingFormula.disallowed_reason(name) <del> <del> if Formula.aliases.include? name <del> problem "Formula name conflicts with existing aliases in homebrew/core." <del> return <del> end <del> <del> if oldname = CoreTap.instance.formula_renames[name] <del> problem "'#{name}' is reserved as the old name of #{oldname} in homebrew/core." <del> return <del> end <del> <del> return if formula.core_formula? <del> return unless Formula.core_names.include?(name) <del> <del> problem "Formula name conflicts with existing core formula." <del> end <del> <del> PROVIDED_BY_MACOS_DEPENDS_ON_ALLOWLIST = %w[ <del> apr <del> apr-util <del> libressl <del> openblas <del> openssl@1.1 <del> ].freeze <del> <del> PERMITTED_LICENSE_MISMATCHES = { <del> "AGPL-3.0" => ["AGPL-3.0-only", "AGPL-3.0-or-later"], <del> "GPL-2.0" => ["GPL-2.0-only", "GPL-2.0-or-later"], <del> "GPL-3.0" => ["GPL-3.0-only", "GPL-3.0-or-later"], <del> "LGPL-2.1" => ["LGPL-2.1-only", "LGPL-2.1-or-later"], <del> "LGPL-3.0" => ["LGPL-3.0-only", "LGPL-3.0-or-later"], <del> }.freeze <del> <del> PERMITTED_FORMULA_LICENSE_MISMATCHES = { <del> "cmockery" => "0.1.2", <del> "scw@1" => "1.20", <del> }.freeze <del> <del> def audit_license <del> if formula.license.present? <del> licenses, exceptions = SPDX.parse_license_expression formula.license <del> <del> non_standard_licenses = licenses.reject { |license| SPDX.valid_license? license } <del> if non_standard_licenses.present? <del> problem <<~EOS <del> Formula #{formula.name} contains non-standard SPDX licenses: #{non_standard_licenses}. <del> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <del> EOS <del> end <del> <del> if @strict <del> deprecated_licenses = licenses.select do |license| <del> SPDX.deprecated_license? license <del> end <del> if deprecated_licenses.present? <del> problem <<~EOS <del> Formula #{formula.name} contains deprecated SPDX licenses: #{deprecated_licenses}. <del> You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). <del> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <del> EOS <del> end <del> end <del> <del> invalid_exceptions = exceptions.reject { |exception| SPDX.valid_license_exception? exception } <del> if invalid_exceptions.present? <del> problem <<~EOS <del> Formula #{formula.name} contains invalid or deprecated SPDX license exceptions: #{invalid_exceptions}. <del> For a list of valid license exceptions check: <del> #{Formatter.url("https://spdx.org/licenses/exceptions-index.html")} <del> EOS <del> end <del> <del> return unless @online <del> <del> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) <del> return if user.blank? <del> <del> github_license = GitHub.get_repo_license(user, repo) <del> return unless github_license <del> return if (licenses + ["NOASSERTION"]).include?(github_license) <del> return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| licenses.include? license } <del> return if PERMITTED_FORMULA_LICENSE_MISMATCHES[formula.name] == formula.version <del> <del> problem "Formula license #{licenses} does not match GitHub license #{Array(github_license)}." <del> <del> elsif @new_formula && @core_tap <del> problem "Formulae in homebrew/core must specify a license." <del> end <del> end <del> <del> # TODO: try to remove these, it's not a good user experience <del> VERSIONED_DEPENDENCIES_CONFLICTS_ALLOWLIST = %w[ <del> agda <del> anjuta <del> fdroidserver <del> gradio <del> predictionio <del> sqoop <del> visp <del> ].freeze <del> <del> def audit_deps <del> @specs.each do |spec| <del> # Check for things we don't like to depend on. <del> # We allow non-Homebrew installs whenever possible. <del> spec.deps.each do |dep| <del> begin <del> dep_f = dep.to_formula <del> rescue TapFormulaUnavailableError <del> # Don't complain about missing cross-tap dependencies <del> next <del> rescue FormulaUnavailableError <del> problem "Can't find dependency #{dep.name.inspect}." <del> next <del> rescue TapFormulaAmbiguityError <del> problem "Ambiguous dependency #{dep.name.inspect}." <del> next <del> rescue TapFormulaWithOldnameAmbiguityError <del> problem "Ambiguous oldname dependency #{dep.name.inspect}." <del> next <del> end <del> <del> if dep_f.oldname && dep.name.split("/").last == dep_f.oldname <del> problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'." <del> end <del> <del> if self.class.aliases.include?(dep.name) && <del> dep_f.core_formula? && !dep_f.versioned_formula? <del> problem "Dependency '#{dep.name}' from homebrew/core is an alias; " \ <del> "use the canonical name '#{dep.to_formula.full_name}'." <del> end <del> <del> if @core_tap && <del> @new_formula && <del> dep_f.keg_only? && <del> dep_f.keg_only_reason.provided_by_macos? && <del> dep_f.keg_only_reason.applicable? && <del> !PROVIDED_BY_MACOS_DEPENDS_ON_ALLOWLIST.include?(dep.name) <del> new_formula_problem( <del> "Dependency '#{dep.name}' is provided by macOS; " \ <del> "please replace 'depends_on' with 'uses_from_macos'.", <del> ) <del> end <del> <del> dep.options.each do |opt| <del> next if @core_tap <del> next if dep_f.option_defined?(opt) <del> next if dep_f.requirements.find do |r| <del> if r.recommended? <del> opt.name == "with-#{r.name}" <del> elsif r.optional? <del> opt.name == "without-#{r.name}" <del> end <del> end <del> <del> problem "Dependency #{dep} does not define option #{opt.name.inspect}" <del> end <del> <del> problem "Don't use git as a dependency (it's always available)" if @new_formula && dep.name == "git" <del> <del> problem "Dependency '#{dep.name}' is marked as :run. Remove :run; it is a no-op." if dep.tags.include?(:run) <del> <del> next unless @core_tap <del> <del> if dep.tags.include?(:recommended) || dep.tags.include?(:optional) <del> problem "Formulae in homebrew/core should not have optional or recommended dependencies" <del> end <del> end <del> <del> next unless @core_tap <del> <del> if spec.requirements.map(&:recommended?).any? || spec.requirements.map(&:optional?).any? <del> problem "Formulae in homebrew/core should not have optional or recommended requirements" <del> end <del> end <del> <del> return unless @core_tap <del> return if VERSIONED_DEPENDENCIES_CONFLICTS_ALLOWLIST.include?(formula.name) <del> <del> # The number of conflicts on Linux is absurd. <del> # TODO: remove this and check these there too. <del> return if OS.linux? <del> <del> recursive_runtime_formulae = formula.runtime_formula_dependencies(undeclared: false) <del> version_hash = {} <del> version_conflicts = Set.new <del> recursive_runtime_formulae.each do |f| <del> name = f.name <del> unversioned_name, = name.split("@") <del> version_hash[unversioned_name] ||= Set.new <del> version_hash[unversioned_name] << name <del> next if version_hash[unversioned_name].length < 2 <del> <del> version_conflicts += version_hash[unversioned_name] <del> end <del> <del> return if version_conflicts.empty? <del> <del> problem <<~EOS <del> #{formula.full_name} contains conflicting version recursive dependencies: <del> #{version_conflicts.to_a.join ", "} <del> View these with `brew deps --tree #{formula.full_name}`. <del> EOS <del> end <del> <del> def audit_conflicts <del> formula.conflicts.each do |c| <del> Formulary.factory(c.name) <del> rescue TapFormulaUnavailableError <del> # Don't complain about missing cross-tap conflicts. <del> next <del> rescue FormulaUnavailableError <del> problem "Can't find conflicting formula #{c.name.inspect}." <del> rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError <del> problem "Ambiguous conflicting formula #{c.name.inspect}." <del> end <del> end <del> <del> def audit_postgresql <del> return unless formula.name == "postgresql" <del> return unless @core_tap <del> <del> major_version = formula.version.major.to_i <del> previous_major_version = major_version - 1 <del> previous_formula_name = "postgresql@#{previous_major_version}" <del> begin <del> Formula[previous_formula_name] <del> rescue FormulaUnavailableError <del> problem "Versioned #{previous_formula_name} in homebrew/core must be created for " \ <del> "`brew-postgresql-upgrade-database` and `pg_upgrade` to work." <del> end <del> end <del> <del> # openssl@1.1 only needed for Linux <del> VERSIONED_KEG_ONLY_ALLOWLIST = %w[ <del> autoconf@2.13 <del> bash-completion@2 <del> clang-format@8 <del> gnupg@1.4 <del> libsigc++@2 <del> lua@5.1 <del> numpy@1.16 <del> openssl@1.1 <del> python@3.8 <del> python@3.9 <del> ].freeze <del> <del> def audit_versioned_keg_only <del> return unless @versioned_formula <del> return unless @core_tap <del> <del> if formula.keg_only? <del> return if formula.keg_only_reason.versioned_formula? <del> if formula.name.start_with?("openssl", "libressl") && <del> formula.keg_only_reason.by_macos? <del> return <del> end <del> end <del> <del> return if VERSIONED_KEG_ONLY_ALLOWLIST.include?(formula.name) <del> return if formula.name.start_with?("adoptopenjdk@") <del> return if formula.name.start_with?("gcc@") <del> <del> problem "Versioned formulae in homebrew/core should use `keg_only :versioned_formula`" <del> end <del> <del> CERT_ERROR_ALLOWLIST = { <del> "hashcat" => "https://hashcat.net/hashcat/", <del> "jinx" => "https://www.jinx-lang.org/", <del> "lmod" => "https://www.tacc.utexas.edu/research-development/tacc-projects/lmod", <del> "micropython" => "https://www.micropython.org/", <del> "monero" => "https://www.getmonero.org/", <del> }.freeze <del> <del> def audit_homepage <del> homepage = formula.homepage <del> <del> return if homepage.nil? || homepage.empty? <del> <del> return unless @online <del> <del> return if CERT_ERROR_ALLOWLIST[formula.name] == homepage <del> <del> return unless DevelopmentTools.curl_handles_most_https_certificates? <del> <del> if http_content_problem = curl_check_http_content(homepage, <del> user_agents: [:browser, :default], <del> check_content: true, <del> strict: @strict) <del> problem http_content_problem <del> end <del> end <del> <del> def audit_bottle_spec <del> # special case: new versioned formulae should be audited <del> return unless @new_formula_inclusive <del> return unless @core_tap <del> <del> return if formula.bottle_disabled? <del> <del> return unless formula.bottle_defined? <del> <del> new_formula_problem "New formulae in homebrew/core should not have a `bottle do` block" <del> end <del> <del> def audit_bottle_disabled <del> return unless formula.bottle_disabled? <del> return if formula.bottle_unneeded? <del> <del> problem "Unrecognized bottle modifier" unless formula.bottle_disable_reason.valid? <del> <del> return unless @core_tap <del> <del> problem "Formulae in homebrew/core should not use `bottle :disabled`" <del> end <del> <del> def audit_github_repository_archived <del> return if formula.deprecated? <del> <del> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online <del> return if user.blank? <del> <del> metadata = SharedAudits.github_repo_data(user, repo) <del> return if metadata.nil? <del> <del> problem "GitHub repo is archived" if metadata["archived"] <del> end <del> <del> def audit_gitlab_repository_archived <del> return if formula.deprecated? <del> <del> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online <del> return if user.blank? <del> <del> metadata = SharedAudits.gitlab_repo_data(user, repo) <del> return if metadata.nil? <del> <del> problem "GitLab repo is archived" if metadata["archived"] <del> end <del> <del> def audit_github_repository <del> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @new_formula <del> <del> return if user.blank? <del> <del> warning = SharedAudits.github(user, repo) <del> return if warning.nil? <del> <del> new_formula_problem warning <del> end <del> <del> def audit_gitlab_repository <del> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @new_formula <del> return if user.blank? <del> <del> warning = SharedAudits.gitlab(user, repo) <del> return if warning.nil? <del> <del> new_formula_problem warning <del> end <del> <del> def audit_bitbucket_repository <del> user, repo = get_repo_data(%r{https?://bitbucket\.org/([^/]+)/([^/]+)/?.*}) if @new_formula <del> return if user.blank? <del> <del> warning = SharedAudits.bitbucket(user, repo) <del> return if warning.nil? <del> <del> new_formula_problem warning <del> end <del> <del> def get_repo_data(regex) <del> return unless @core_tap <del> return unless @online <del> <del> _, user, repo = *regex.match(formula.stable.url) if formula.stable <del> _, user, repo = *regex.match(formula.homepage) unless user <del> _, user, repo = *regex.match(formula.head.url) if !user && formula.head <del> return if !user || !repo <del> <del> repo.delete_suffix!(".git") <del> <del> [user, repo] <del> end <del> <del> UNSTABLE_ALLOWLIST = { <del> "aalib" => "1.4rc", <del> "automysqlbackup" => "3.0-rc", <del> "aview" => "1.3.0rc", <del> "elm-format" => "0.6.0-alpha", <del> "ftgl" => "2.1.3-rc", <del> "hidapi" => "0.8.0-rc", <del> "libcaca" => "0.99b", <del> "premake" => "4.4-beta", <del> "pwnat" => "0.3-beta", <del> "recode" => "3.7-beta", <del> "speexdsp" => "1.2rc", <del> "sqoop" => "1.4.", <del> "tcptraceroute" => "1.5beta", <del> "tiny-fugue" => "5.0b", <del> "vbindiff" => "3.0_beta", <del> }.freeze <del> <del> # Used for formulae that are unstable but need CI run without being in homebrew/core <del> UNSTABLE_DEVEL_ALLOWLIST = { <del> }.freeze <del> <del> GNOME_DEVEL_ALLOWLIST = { <del> "libart" => "2.3", <del> "gtk-mac-integration" => "2.1", <del> "gtk-doc" => "1.31", <del> "gcab" => "1.3", <del> "libepoxy" => "1.5", <del> }.freeze <del> <del> def audit_specs <del> problem "Head-only (no stable download)" if head_only?(formula) <del> <del> %w[Stable HEAD].each do |name| <del> spec_name = name.downcase.to_sym <del> next unless spec = formula.send(spec_name) <del> <del> ra = ResourceAuditor.new(spec, spec_name, online: @online, strict: @strict).audit <del> ra.problems.each do |message| <del> problem "#{name}: #{message}" <del> end <del> <del> spec.resources.each_value do |resource| <del> problem "Resource name should be different from the formula name" if resource.name == formula.name <del> <del> ra = ResourceAuditor.new(resource, spec_name, online: @online, strict: @strict).audit <del> ra.problems.each do |message| <del> problem "#{name} resource #{resource.name.inspect}: #{message}" <del> end <del> end <del> <del> next if spec.patches.empty? <del> next unless @new_formula <del> <del> new_formula_problem( <del> "Formulae should not require patches to build. " \ <del> "Patches should be submitted and accepted upstream first.", <del> ) <del> end <del> <del> if stable = formula.stable <del> version = stable.version <del> problem "Stable: version (#{version}) is set to a string without a digit" if version.to_s !~ /\d/ <del> if version.to_s.start_with?("HEAD") <del> problem "Stable: non-HEAD version name (#{version}) should not begin with HEAD" <del> end <del> end <del> <del> return unless @core_tap <del> <del> if formula.head && @versioned_formula && <del> !tap_audit_exception(:versioned_head_spec_allowlist, formula.name) <del> problem "Versioned formulae should not have a `HEAD` spec" <del> end <del> <del> stable = formula.stable <del> return unless stable <del> return unless stable.url <del> <del> stable_version_string = stable.version.to_s <del> stable_url_version = Version.parse(stable.url) <del> stable_url_minor_version = stable_url_version.minor.to_i <del> <del> formula_suffix = stable.version.patch.to_i <del> throttled_rate = tap_audit_exception(:throttled_formulae, formula.name) <del> if throttled_rate && formula_suffix.modulo(throttled_rate).nonzero? <del> problem "should only be updated every #{throttled_rate} releases on multiples of #{throttled_rate}" <del> end <del> <del> case (url = stable.url) <del> when /[\d._-](alpha|beta|rc\d)/ <del> matched = Regexp.last_match(1) <del> version_prefix = stable_version_string.sub(/\d+$/, "") <del> return if UNSTABLE_ALLOWLIST[formula.name] == version_prefix <del> return if UNSTABLE_DEVEL_ALLOWLIST[formula.name] == version_prefix <del> <del> problem "Stable version URLs should not contain #{matched}" <del> when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i <del> version_prefix = stable.version.major_minor <del> return if GNOME_DEVEL_ALLOWLIST[formula.name] == version_prefix <del> return if stable_url_version < Version.create("1.0") <del> return if stable_url_minor_version.even? <del> <del> problem "#{stable.version} is a development release" <del> when %r{isc.org/isc/bind\d*/}i <del> return if stable_url_minor_version.even? <del> <del> problem "#{stable.version} is a development release" <del> <del> when %r{https?://gitlab\.com/([\w-]+)/([\w-]+)} <del> owner = Regexp.last_match(1) <del> repo = Regexp.last_match(2) <del> <del> tag = SharedAudits.gitlab_tag_from_url(url) <del> tag ||= stable.specs[:tag] <del> tag ||= stable.version <del> <del> if @online <del> error = SharedAudits.gitlab_release(owner, repo, tag, formula: formula) <del> problem error if error <del> end <del> when %r{^https://github.com/([\w-]+)/([\w-]+)} <del> owner = Regexp.last_match(1) <del> repo = Regexp.last_match(2) <del> tag = SharedAudits.github_tag_from_url(url) <del> tag ||= formula.stable.specs[:tag] <del> <del> if @online <del> error = SharedAudits.github_release(owner, repo, tag, formula: formula) <del> problem error if error <del> end <del> end <del> end <del> <del> def audit_revision_and_version_scheme <del> return unless @git <del> return unless formula.tap # skip formula not from core or any taps <del> return unless formula.tap.git? # git log is required <del> return if formula.stable.blank? <del> <del> fv = FormulaVersions.new(formula) <del> <del> current_version = formula.stable.version <del> current_checksum = formula.stable.checksum <del> current_version_scheme = formula.version_scheme <del> current_revision = formula.revision <del> current_url = formula.stable.url <del> <del> previous_version = nil <del> previous_version_scheme = nil <del> previous_revision = nil <del> <del> newest_committed_version = nil <del> newest_committed_checksum = nil <del> newest_committed_revision = nil <del> newest_committed_url = nil <del> <del> fv.rev_list("origin/master") do |rev| <del> begin <del> fv.formula_at_revision(rev) do |f| <del> stable = f.stable <del> next if stable.blank? <del> <del> previous_version = stable.version <del> previous_checksum = stable.checksum <del> previous_version_scheme = f.version_scheme <del> previous_revision = f.revision <del> <del> newest_committed_version ||= previous_version <del> newest_committed_checksum ||= previous_checksum <del> newest_committed_revision ||= previous_revision <del> newest_committed_url ||= stable.url <del> end <del> rescue MacOSVersionError <del> break <del> end <del> <del> break if previous_version && current_version != previous_version <del> break if previous_revision && current_revision != previous_revision <del> end <del> <del> if current_version == newest_committed_version && <del> current_url == newest_committed_url && <del> current_checksum != newest_committed_checksum && <del> current_checksum.present? && newest_committed_checksum.present? <del> problem( <del> "stable sha256 changed without the url/version also changing; " \ <del> "please create an issue upstream to rule out malicious " \ <del> "circumstances and to find out why the file changed.", <del> ) <del> end <del> <del> if !newest_committed_version.nil? && <del> current_version < newest_committed_version && <del> current_version_scheme == previous_version_scheme <del> problem "stable version should not decrease (from #{newest_committed_version} to #{current_version})" <del> end <del> <del> unless previous_version_scheme.nil? <del> if current_version_scheme < previous_version_scheme <del> problem "version_scheme should not decrease (from #{previous_version_scheme} " \ <del> "to #{current_version_scheme})" <del> elsif current_version_scheme > (previous_version_scheme + 1) <del> problem "version_schemes should only increment by 1" <del> end <del> end <del> <del> if (previous_version != newest_committed_version || <del> current_version != newest_committed_version) && <del> !current_revision.zero? && <del> current_revision == newest_committed_revision && <del> current_revision == previous_revision <del> problem "'revision #{current_revision}' should be removed" <del> elsif current_version == previous_version && <del> !previous_revision.nil? && <del> current_revision < previous_revision <del> problem "revision should not decrease (from #{previous_revision} to #{current_revision})" <del> elsif newest_committed_revision && <del> current_revision > (newest_committed_revision + 1) <del> problem "revisions should only increment by 1" <del> end <del> end <del> <del> def audit_text <del> bin_names = Set.new <del> bin_names << formula.name <del> bin_names += formula.aliases <del> [formula.bin, formula.sbin].each do |dir| <del> next unless dir.exist? <del> <del> bin_names += dir.children.map(&:basename).map(&:to_s) <del> end <del> shell_commands = ["system", "shell_output", "pipe_output"] <del> bin_names.each do |name| <del> shell_commands.each do |cmd| <del> if text.to_s.match?(/test do.*#{cmd}[(\s]+['"]#{Regexp.escape(name)}[\s'"]/m) <del> problem %Q(fully scope test #{cmd} calls, e.g. #{cmd} "\#{bin}/#{name}") <del> end <del> end <del> end <del> end <del> <del> def audit_reverse_migration <del> # Only enforce for new formula being re-added to core <del> return unless @strict <del> return unless @core_tap <del> return unless formula.tap.tap_migrations.key?(formula.name) <del> <del> problem <<~EOS <del> #{formula.name} seems to be listed in tap_migrations.json! <del> Please remove #{formula.name} from present tap & tap_migrations.json <del> before submitting it to Homebrew/homebrew-#{formula.tap.repo}. <del> EOS <del> end <del> <del> def audit_prefix_has_contents <del> return unless formula.prefix.directory? <del> return unless Keg.new(formula.prefix).empty_installation? <del> <del> problem <<~EOS <del> The installation seems to be empty. Please ensure the prefix <del> is set correctly and expected files are installed. <del> The prefix configure/make argument may be case-sensitive. <del> EOS <del> end <del> <del> def quote_dep(dep) <del> dep.is_a?(Symbol) ? dep.inspect : "'#{dep}'" <del> end <del> <del> def problem_if_output(output) <del> problem(output) if output <del> end <del> <del> def audit <del> only_audits = @only <del> except_audits = @except <del> <del> methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name| <del> name = audit_method_name.delete_prefix("audit_") <del> if only_audits <del> next unless only_audits.include?(name) <del> elsif except_audits <del> next if except_audits.include?(name) <del> end <del> send(audit_method_name) <del> end <del> end <del> <del> private <del> <del> def problem(message, location: nil) <del> @problems << ({ message: message, location: location }) <del> end <del> <del> def new_formula_problem(message, location: nil) <del> @new_formula_problems << ({ message: message, location: location }) <del> end <del> <del> def head_only?(formula) <del> formula.head && formula.stable.nil? <del> end <del> <del> def tap_audit_exception(list, formula, value = nil) <del> return false unless @tap_audit_exceptions.key? list <del> <del> list = @tap_audit_exceptions[list] <del> <del> case list <del> when Array <del> list.include? formula <del> when Hash <del> return false unless list.include? formula <del> return list[formula] if value.blank? <del> <del> list[formula] == value <del> end <del> end <del> end <del> <del> class ResourceAuditor <del> attr_reader :name, :version, :checksum, :url, :mirrors, :using, :specs, :owner, :spec_name, :problems <del> <del> def initialize(resource, spec_name, options = {}) <del> @name = resource.name <del> @version = resource.version <del> @checksum = resource.checksum <del> @url = resource.url <del> @mirrors = resource.mirrors <del> @using = resource.using <del> @specs = resource.specs <del> @owner = resource.owner <del> @spec_name = spec_name <del> @online = options[:online] <del> @strict = options[:strict] <del> @problems = [] <del> end <del> <del> def audit <del> audit_version <del> audit_download_strategy <del> audit_urls <del> self <del> end <del> <del> def audit_version <del> if version.nil? <del> problem "missing version" <del> elsif !version.detected_from_url? <del> version_text = version <del> version_url = Version.detect(url, **specs) <del> if version_url.to_s == version_text.to_s && version.instance_of?(Version) <del> problem "version #{version_text} is redundant with version scanned from URL" <del> end <del> end <del> end <del> <del> def audit_download_strategy <del> url_strategy = DownloadStrategyDetector.detect(url) <del> <del> if (using == :git || url_strategy == GitDownloadStrategy) && specs[:tag] && !specs[:revision] <del> problem "Git should specify :revision when a :tag is specified." <del> end <del> <del> return unless using <del> <del> if using == :cvs <del> mod = specs[:module] <del> <del> problem "Redundant :module value in URL" if mod == name <del> <del> if url.match?(%r{:[^/]+$}) <del> mod = url.split(":").last <del> <del> if mod == name <del> problem "Redundant CVS module appended to URL" <del> else <del> problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL" <del> end <del> end <del> end <del> <del> return unless url_strategy == DownloadStrategyDetector.detect("", using) <del> <del> problem "Redundant :using value in URL" <del> end <del> <del> def self.curl_openssl_and_deps <del> @curl_openssl_and_deps ||= begin <del> formulae_names = ["curl", "openssl"] <del> formulae_names += formulae_names.flat_map do |f| <del> Formula[f].recursive_dependencies.map(&:name) <del> end <del> formulae_names.uniq <del> rescue FormulaUnavailableError <del> [] <del> end <del> end <del> <del> def audit_urls <del> return unless @online <del> <del> urls = [url] + mirrors <del> urls.each do |url| <del> next if !@strict && mirrors.include?(url) <del> <del> strategy = DownloadStrategyDetector.detect(url, using) <del> if strategy <= CurlDownloadStrategy && !url.start_with?("file") <del> # A `brew mirror`'ed URL is usually not yet reachable at the time of <del> # pull request. <del> next if url.match?(%r{^https://dl.bintray.com/homebrew/mirror/}) <del> <del> if http_content_problem = curl_check_http_content(url) <del> problem http_content_problem <del> end <del> elsif strategy <= GitDownloadStrategy <del> problem "The URL #{url} is not a valid git URL" unless Utils::Git.remote_exists? url <del> elsif strategy <= SubversionDownloadStrategy <del> next unless DevelopmentTools.subversion_handles_most_https_certificates? <del> next unless Utils::Svn.available? <del> <del> problem "The URL #{url} is not a valid svn URL" unless Utils::Svn.remote_exists? url <del> end <del> end <del> end <del> <del> def problem(text) <del> @problems << text <del> end <del> end <ide> end <ide><path>Library/Homebrew/formula_auditor.rb <add># typed: false <add># frozen_string_literal: true <add> <add>require "formula_text_auditor" <add>require "resource_auditor" <add> <add>module Homebrew <add> # Auditor for checking common violations in {Formula}e. <add> # <add> # @api private <add> class FormulaAuditor <add> include FormulaCellarChecks <add> <add> attr_reader :formula, :text, :problems, :new_formula_problems <add> <add> def initialize(formula, options = {}) <add> @formula = formula <add> @versioned_formula = formula.versioned_formula? <add> @new_formula_inclusive = options[:new_formula] <add> @new_formula = options[:new_formula] && !@versioned_formula <add> @strict = options[:strict] <add> @online = options[:online] <add> @build_stable = options[:build_stable] <add> @git = options[:git] <add> @display_cop_names = options[:display_cop_names] <add> @only = options[:only] <add> @except = options[:except] <add> # Accept precomputed style offense results, for efficiency <add> @style_offenses = options[:style_offenses] <add> # Allow the formula tap to be set as homebrew/core, for testing purposes <add> @core_tap = formula.tap&.core_tap? || options[:core_tap] <add> @problems = [] <add> @new_formula_problems = [] <add> @text = FormulaTextAuditor.new(formula.path) <add> @specs = %w[stable head].map { |s| formula.send(s) }.compact <add> @spdx_license_data = options[:spdx_license_data] <add> @spdx_exception_data = options[:spdx_exception_data] <add> @tap_audit_exceptions = options[:tap_audit_exceptions] <add> end <add> <add> def audit_style <add> return unless @style_offenses <add> <add> @style_offenses.each do |offense| <add> correction_status = "#{Tty.green}[Corrected]#{Tty.reset} " if offense.corrected? <add> <add> cop_name = "#{offense.cop_name}: " if @display_cop_names <add> message = "#{cop_name}#{correction_status}#{offense.message}" <add> <add> problem message, location: offense.location <add> end <add> end <add> <add> def audit_file <add> if formula.core_formula? && @versioned_formula <add> unversioned_formula = begin <add> # build this ourselves as we want e.g. homebrew/core to be present <add> full_name = if formula.tap <add> "#{formula.tap}/#{formula.name}" <add> else <add> formula.name <add> end <add> Formulary.factory(full_name.gsub(/@.*$/, "")).path <add> rescue FormulaUnavailableError, TapFormulaAmbiguityError, <add> TapFormulaWithOldnameAmbiguityError <add> Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb") <add> end <add> unless unversioned_formula.exist? <add> unversioned_name = unversioned_formula.basename(".rb") <add> problem "#{formula} is versioned but no #{unversioned_name} formula exists" <add> end <add> elsif @build_stable && <add> formula.stable? && <add> !@versioned_formula && <add> (versioned_formulae = formula.versioned_formulae - [formula]) && <add> versioned_formulae.present? <add> versioned_aliases = formula.aliases.grep(/.@\d/) <add> _, last_alias_version = versioned_formulae.map(&:name).last.split("@") <add> alias_name_major = "#{formula.name}@#{formula.version.major}" <add> alias_name_major_minor = "#{alias_name_major}.#{formula.version.minor}" <add> alias_name = if last_alias_version.split(".").length == 1 <add> alias_name_major <add> else <add> alias_name_major_minor <add> end <add> valid_alias_names = [alias_name_major, alias_name_major_minor] <add> <add> unless @core_tap <add> versioned_aliases.map! { |a| "#{formula.tap}/#{a}" } <add> valid_alias_names.map! { |a| "#{formula.tap}/#{a}" } <add> end <add> <add> # Fix naming based on what people expect. <add> if alias_name_major_minor == "adoptopenjdk@1.8" <add> valid_alias_names << "adoptopenjdk@8" <add> valid_alias_names.delete "adoptopenjdk@1" <add> end <add> <add> valid_versioned_aliases = versioned_aliases & valid_alias_names <add> invalid_versioned_aliases = versioned_aliases - valid_alias_names <add> <add> if valid_versioned_aliases.empty? <add> if formula.tap <add> problem <<~EOS <add> Formula has other versions so create a versioned alias: <add> cd #{formula.tap.alias_dir} <add> ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name} <add> EOS <add> else <add> problem "Formula has other versions so create an alias named #{alias_name}." <add> end <add> end <add> <add> if invalid_versioned_aliases.present? <add> problem <<~EOS <add> Formula has invalid versioned aliases: <add> #{invalid_versioned_aliases.join("\n ")} <add> EOS <add> end <add> end <add> end <add> <add> def self.aliases <add> # core aliases + tap alias names + tap alias full name <add> @aliases ||= Formula.aliases + Formula.tap_aliases <add> end <add> <add> def audit_formula_name <add> return unless @strict <add> return unless @core_tap <add> <add> name = formula.name <add> <add> problem "'#{name}' is not allowed in homebrew/core." if MissingFormula.disallowed_reason(name) <add> <add> if Formula.aliases.include? name <add> problem "Formula name conflicts with existing aliases in homebrew/core." <add> return <add> end <add> <add> if oldname = CoreTap.instance.formula_renames[name] <add> problem "'#{name}' is reserved as the old name of #{oldname} in homebrew/core." <add> return <add> end <add> <add> return if formula.core_formula? <add> return unless Formula.core_names.include?(name) <add> <add> problem "Formula name conflicts with existing core formula." <add> end <add> <add> PROVIDED_BY_MACOS_DEPENDS_ON_ALLOWLIST = %w[ <add> apr <add> apr-util <add> libressl <add> openblas <add> openssl@1.1 <add> ].freeze <add> <add> PERMITTED_LICENSE_MISMATCHES = { <add> "AGPL-3.0" => ["AGPL-3.0-only", "AGPL-3.0-or-later"], <add> "GPL-2.0" => ["GPL-2.0-only", "GPL-2.0-or-later"], <add> "GPL-3.0" => ["GPL-3.0-only", "GPL-3.0-or-later"], <add> "LGPL-2.1" => ["LGPL-2.1-only", "LGPL-2.1-or-later"], <add> "LGPL-3.0" => ["LGPL-3.0-only", "LGPL-3.0-or-later"], <add> }.freeze <add> <add> PERMITTED_FORMULA_LICENSE_MISMATCHES = { <add> "cmockery" => "0.1.2", <add> "scw@1" => "1.20", <add> }.freeze <add> <add> def audit_license <add> if formula.license.present? <add> licenses, exceptions = SPDX.parse_license_expression formula.license <add> <add> non_standard_licenses = licenses.reject { |license| SPDX.valid_license? license } <add> if non_standard_licenses.present? <add> problem <<~EOS <add> Formula #{formula.name} contains non-standard SPDX licenses: #{non_standard_licenses}. <add> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <add> EOS <add> end <add> <add> if @strict <add> deprecated_licenses = licenses.select do |license| <add> SPDX.deprecated_license? license <add> end <add> if deprecated_licenses.present? <add> problem <<~EOS <add> Formula #{formula.name} contains deprecated SPDX licenses: #{deprecated_licenses}. <add> You may need to add `-only` or `-or-later` for GNU licenses (e.g. `GPL`, `LGPL`, `AGPL`, `GFDL`). <add> For a list of valid licenses check: #{Formatter.url("https://spdx.org/licenses/")} <add> EOS <add> end <add> end <add> <add> invalid_exceptions = exceptions.reject { |exception| SPDX.valid_license_exception? exception } <add> if invalid_exceptions.present? <add> problem <<~EOS <add> Formula #{formula.name} contains invalid or deprecated SPDX license exceptions: #{invalid_exceptions}. <add> For a list of valid license exceptions check: <add> #{Formatter.url("https://spdx.org/licenses/exceptions-index.html")} <add> EOS <add> end <add> <add> return unless @online <add> <add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) <add> return if user.blank? <add> <add> github_license = GitHub.get_repo_license(user, repo) <add> return unless github_license <add> return if (licenses + ["NOASSERTION"]).include?(github_license) <add> return if PERMITTED_LICENSE_MISMATCHES[github_license]&.any? { |license| licenses.include? license } <add> return if PERMITTED_FORMULA_LICENSE_MISMATCHES[formula.name] == formula.version <add> <add> problem "Formula license #{licenses} does not match GitHub license #{Array(github_license)}." <add> <add> elsif @new_formula && @core_tap <add> problem "Formulae in homebrew/core must specify a license." <add> end <add> end <add> <add> # TODO: try to remove these, it's not a good user experience <add> VERSIONED_DEPENDENCIES_CONFLICTS_ALLOWLIST = %w[ <add> agda <add> anjuta <add> fdroidserver <add> gradio <add> predictionio <add> sqoop <add> visp <add> ].freeze <add> <add> def audit_deps <add> @specs.each do |spec| <add> # Check for things we don't like to depend on. <add> # We allow non-Homebrew installs whenever possible. <add> spec.deps.each do |dep| <add> begin <add> dep_f = dep.to_formula <add> rescue TapFormulaUnavailableError <add> # Don't complain about missing cross-tap dependencies <add> next <add> rescue FormulaUnavailableError <add> problem "Can't find dependency #{dep.name.inspect}." <add> next <add> rescue TapFormulaAmbiguityError <add> problem "Ambiguous dependency #{dep.name.inspect}." <add> next <add> rescue TapFormulaWithOldnameAmbiguityError <add> problem "Ambiguous oldname dependency #{dep.name.inspect}." <add> next <add> end <add> <add> if dep_f.oldname && dep.name.split("/").last == dep_f.oldname <add> problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'." <add> end <add> <add> if self.class.aliases.include?(dep.name) && <add> dep_f.core_formula? && !dep_f.versioned_formula? <add> problem "Dependency '#{dep.name}' from homebrew/core is an alias; " \ <add> "use the canonical name '#{dep.to_formula.full_name}'." <add> end <add> <add> if @core_tap && <add> @new_formula && <add> dep_f.keg_only? && <add> dep_f.keg_only_reason.provided_by_macos? && <add> dep_f.keg_only_reason.applicable? && <add> !PROVIDED_BY_MACOS_DEPENDS_ON_ALLOWLIST.include?(dep.name) <add> new_formula_problem( <add> "Dependency '#{dep.name}' is provided by macOS; " \ <add> "please replace 'depends_on' with 'uses_from_macos'.", <add> ) <add> end <add> <add> dep.options.each do |opt| <add> next if @core_tap <add> next if dep_f.option_defined?(opt) <add> next if dep_f.requirements.find do |r| <add> if r.recommended? <add> opt.name == "with-#{r.name}" <add> elsif r.optional? <add> opt.name == "without-#{r.name}" <add> end <add> end <add> <add> problem "Dependency #{dep} does not define option #{opt.name.inspect}" <add> end <add> <add> problem "Don't use git as a dependency (it's always available)" if @new_formula && dep.name == "git" <add> <add> problem "Dependency '#{dep.name}' is marked as :run. Remove :run; it is a no-op." if dep.tags.include?(:run) <add> <add> next unless @core_tap <add> <add> if dep.tags.include?(:recommended) || dep.tags.include?(:optional) <add> problem "Formulae in homebrew/core should not have optional or recommended dependencies" <add> end <add> end <add> <add> next unless @core_tap <add> <add> if spec.requirements.map(&:recommended?).any? || spec.requirements.map(&:optional?).any? <add> problem "Formulae in homebrew/core should not have optional or recommended requirements" <add> end <add> end <add> <add> return unless @core_tap <add> return if VERSIONED_DEPENDENCIES_CONFLICTS_ALLOWLIST.include?(formula.name) <add> <add> # The number of conflicts on Linux is absurd. <add> # TODO: remove this and check these there too. <add> return if OS.linux? <add> <add> recursive_runtime_formulae = formula.runtime_formula_dependencies(undeclared: false) <add> version_hash = {} <add> version_conflicts = Set.new <add> recursive_runtime_formulae.each do |f| <add> name = f.name <add> unversioned_name, = name.split("@") <add> version_hash[unversioned_name] ||= Set.new <add> version_hash[unversioned_name] << name <add> next if version_hash[unversioned_name].length < 2 <add> <add> version_conflicts += version_hash[unversioned_name] <add> end <add> <add> return if version_conflicts.empty? <add> <add> problem <<~EOS <add> #{formula.full_name} contains conflicting version recursive dependencies: <add> #{version_conflicts.to_a.join ", "} <add> View these with `brew deps --tree #{formula.full_name}`. <add> EOS <add> end <add> <add> def audit_conflicts <add> formula.conflicts.each do |c| <add> Formulary.factory(c.name) <add> rescue TapFormulaUnavailableError <add> # Don't complain about missing cross-tap conflicts. <add> next <add> rescue FormulaUnavailableError <add> problem "Can't find conflicting formula #{c.name.inspect}." <add> rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError <add> problem "Ambiguous conflicting formula #{c.name.inspect}." <add> end <add> end <add> <add> def audit_postgresql <add> return unless formula.name == "postgresql" <add> return unless @core_tap <add> <add> major_version = formula.version.major.to_i <add> previous_major_version = major_version - 1 <add> previous_formula_name = "postgresql@#{previous_major_version}" <add> begin <add> Formula[previous_formula_name] <add> rescue FormulaUnavailableError <add> problem "Versioned #{previous_formula_name} in homebrew/core must be created for " \ <add> "`brew-postgresql-upgrade-database` and `pg_upgrade` to work." <add> end <add> end <add> <add> # openssl@1.1 only needed for Linux <add> VERSIONED_KEG_ONLY_ALLOWLIST = %w[ <add> autoconf@2.13 <add> bash-completion@2 <add> clang-format@8 <add> gnupg@1.4 <add> libsigc++@2 <add> lua@5.1 <add> numpy@1.16 <add> openssl@1.1 <add> python@3.8 <add> python@3.9 <add> ].freeze <add> <add> def audit_versioned_keg_only <add> return unless @versioned_formula <add> return unless @core_tap <add> <add> if formula.keg_only? <add> return if formula.keg_only_reason.versioned_formula? <add> if formula.name.start_with?("openssl", "libressl") && <add> formula.keg_only_reason.by_macos? <add> return <add> end <add> end <add> <add> return if VERSIONED_KEG_ONLY_ALLOWLIST.include?(formula.name) <add> return if formula.name.start_with?("adoptopenjdk@") <add> return if formula.name.start_with?("gcc@") <add> <add> problem "Versioned formulae in homebrew/core should use `keg_only :versioned_formula`" <add> end <add> <add> CERT_ERROR_ALLOWLIST = { <add> "hashcat" => "https://hashcat.net/hashcat/", <add> "jinx" => "https://www.jinx-lang.org/", <add> "lmod" => "https://www.tacc.utexas.edu/research-development/tacc-projects/lmod", <add> "micropython" => "https://www.micropython.org/", <add> "monero" => "https://www.getmonero.org/", <add> }.freeze <add> <add> def audit_homepage <add> homepage = formula.homepage <add> <add> return if homepage.nil? || homepage.empty? <add> <add> return unless @online <add> <add> return if CERT_ERROR_ALLOWLIST[formula.name] == homepage <add> <add> return unless DevelopmentTools.curl_handles_most_https_certificates? <add> <add> if http_content_problem = curl_check_http_content(homepage, <add> user_agents: [:browser, :default], <add> check_content: true, <add> strict: @strict) <add> problem http_content_problem <add> end <add> end <add> <add> def audit_bottle_spec <add> # special case: new versioned formulae should be audited <add> return unless @new_formula_inclusive <add> return unless @core_tap <add> <add> return if formula.bottle_disabled? <add> <add> return unless formula.bottle_defined? <add> <add> new_formula_problem "New formulae in homebrew/core should not have a `bottle do` block" <add> end <add> <add> def audit_bottle_disabled <add> return unless formula.bottle_disabled? <add> return if formula.bottle_unneeded? <add> <add> problem "Unrecognized bottle modifier" unless formula.bottle_disable_reason.valid? <add> <add> return unless @core_tap <add> <add> problem "Formulae in homebrew/core should not use `bottle :disabled`" <add> end <add> <add> def audit_github_repository_archived <add> return if formula.deprecated? <add> <add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.blank? <add> <add> metadata = SharedAudits.github_repo_data(user, repo) <add> return if metadata.nil? <add> <add> problem "GitHub repo is archived" if metadata["archived"] <add> end <add> <add> def audit_gitlab_repository_archived <add> return if formula.deprecated? <add> <add> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @online <add> return if user.blank? <add> <add> metadata = SharedAudits.gitlab_repo_data(user, repo) <add> return if metadata.nil? <add> <add> problem "GitLab repo is archived" if metadata["archived"] <add> end <add> <add> def audit_github_repository <add> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @new_formula <add> <add> return if user.blank? <add> <add> warning = SharedAudits.github(user, repo) <add> return if warning.nil? <add> <add> new_formula_problem warning <add> end <add> <add> def audit_gitlab_repository <add> user, repo = get_repo_data(%r{https?://gitlab\.com/([^/]+)/([^/]+)/?.*}) if @new_formula <add> return if user.blank? <add> <add> warning = SharedAudits.gitlab(user, repo) <add> return if warning.nil? <add> <add> new_formula_problem warning <add> end <add> <add> def audit_bitbucket_repository <add> user, repo = get_repo_data(%r{https?://bitbucket\.org/([^/]+)/([^/]+)/?.*}) if @new_formula <add> return if user.blank? <add> <add> warning = SharedAudits.bitbucket(user, repo) <add> return if warning.nil? <add> <add> new_formula_problem warning <add> end <add> <add> def get_repo_data(regex) <add> return unless @core_tap <add> return unless @online <add> <add> _, user, repo = *regex.match(formula.stable.url) if formula.stable <add> _, user, repo = *regex.match(formula.homepage) unless user <add> _, user, repo = *regex.match(formula.head.url) if !user && formula.head <add> return if !user || !repo <add> <add> repo.delete_suffix!(".git") <add> <add> [user, repo] <add> end <add> <add> UNSTABLE_ALLOWLIST = { <add> "aalib" => "1.4rc", <add> "automysqlbackup" => "3.0-rc", <add> "aview" => "1.3.0rc", <add> "elm-format" => "0.6.0-alpha", <add> "ftgl" => "2.1.3-rc", <add> "hidapi" => "0.8.0-rc", <add> "libcaca" => "0.99b", <add> "premake" => "4.4-beta", <add> "pwnat" => "0.3-beta", <add> "recode" => "3.7-beta", <add> "speexdsp" => "1.2rc", <add> "sqoop" => "1.4.", <add> "tcptraceroute" => "1.5beta", <add> "tiny-fugue" => "5.0b", <add> "vbindiff" => "3.0_beta", <add> }.freeze <add> <add> # Used for formulae that are unstable but need CI run without being in homebrew/core <add> UNSTABLE_DEVEL_ALLOWLIST = { <add> }.freeze <add> <add> GNOME_DEVEL_ALLOWLIST = { <add> "libart" => "2.3", <add> "gtk-mac-integration" => "2.1", <add> "gtk-doc" => "1.31", <add> "gcab" => "1.3", <add> "libepoxy" => "1.5", <add> }.freeze <add> <add> def audit_specs <add> problem "Head-only (no stable download)" if head_only?(formula) <add> <add> %w[Stable HEAD].each do |name| <add> spec_name = name.downcase.to_sym <add> next unless spec = formula.send(spec_name) <add> <add> ra = ResourceAuditor.new(spec, spec_name, online: @online, strict: @strict).audit <add> ra.problems.each do |message| <add> problem "#{name}: #{message}" <add> end <add> <add> spec.resources.each_value do |resource| <add> problem "Resource name should be different from the formula name" if resource.name == formula.name <add> <add> ra = ResourceAuditor.new(resource, spec_name, online: @online, strict: @strict).audit <add> ra.problems.each do |message| <add> problem "#{name} resource #{resource.name.inspect}: #{message}" <add> end <add> end <add> <add> next if spec.patches.empty? <add> next unless @new_formula <add> <add> new_formula_problem( <add> "Formulae should not require patches to build. " \ <add> "Patches should be submitted and accepted upstream first.", <add> ) <add> end <add> <add> if stable = formula.stable <add> version = stable.version <add> problem "Stable: version (#{version}) is set to a string without a digit" if version.to_s !~ /\d/ <add> if version.to_s.start_with?("HEAD") <add> problem "Stable: non-HEAD version name (#{version}) should not begin with HEAD" <add> end <add> end <add> <add> return unless @core_tap <add> <add> if formula.head && @versioned_formula && <add> !tap_audit_exception(:versioned_head_spec_allowlist, formula.name) <add> problem "Versioned formulae should not have a `HEAD` spec" <add> end <add> <add> stable = formula.stable <add> return unless stable <add> return unless stable.url <add> <add> stable_version_string = stable.version.to_s <add> stable_url_version = Version.parse(stable.url) <add> stable_url_minor_version = stable_url_version.minor.to_i <add> <add> formula_suffix = stable.version.patch.to_i <add> throttled_rate = tap_audit_exception(:throttled_formulae, formula.name) <add> if throttled_rate && formula_suffix.modulo(throttled_rate).nonzero? <add> problem "should only be updated every #{throttled_rate} releases on multiples of #{throttled_rate}" <add> end <add> <add> case (url = stable.url) <add> when /[\d._-](alpha|beta|rc\d)/ <add> matched = Regexp.last_match(1) <add> version_prefix = stable_version_string.sub(/\d+$/, "") <add> return if UNSTABLE_ALLOWLIST[formula.name] == version_prefix <add> return if UNSTABLE_DEVEL_ALLOWLIST[formula.name] == version_prefix <add> <add> problem "Stable version URLs should not contain #{matched}" <add> when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i <add> version_prefix = stable.version.major_minor <add> return if GNOME_DEVEL_ALLOWLIST[formula.name] == version_prefix <add> return if stable_url_version < Version.create("1.0") <add> return if stable_url_minor_version.even? <add> <add> problem "#{stable.version} is a development release" <add> when %r{isc.org/isc/bind\d*/}i <add> return if stable_url_minor_version.even? <add> <add> problem "#{stable.version} is a development release" <add> <add> when %r{https?://gitlab\.com/([\w-]+)/([\w-]+)} <add> owner = Regexp.last_match(1) <add> repo = Regexp.last_match(2) <add> <add> tag = SharedAudits.gitlab_tag_from_url(url) <add> tag ||= stable.specs[:tag] <add> tag ||= stable.version <add> <add> if @online <add> error = SharedAudits.gitlab_release(owner, repo, tag, formula: formula) <add> problem error if error <add> end <add> when %r{^https://github.com/([\w-]+)/([\w-]+)} <add> owner = Regexp.last_match(1) <add> repo = Regexp.last_match(2) <add> tag = SharedAudits.github_tag_from_url(url) <add> tag ||= formula.stable.specs[:tag] <add> <add> if @online <add> error = SharedAudits.github_release(owner, repo, tag, formula: formula) <add> problem error if error <add> end <add> end <add> end <add> <add> def audit_revision_and_version_scheme <add> return unless @git <add> return unless formula.tap # skip formula not from core or any taps <add> return unless formula.tap.git? # git log is required <add> return if formula.stable.blank? <add> <add> fv = FormulaVersions.new(formula) <add> <add> current_version = formula.stable.version <add> current_checksum = formula.stable.checksum <add> current_version_scheme = formula.version_scheme <add> current_revision = formula.revision <add> current_url = formula.stable.url <add> <add> previous_version = nil <add> previous_version_scheme = nil <add> previous_revision = nil <add> <add> newest_committed_version = nil <add> newest_committed_checksum = nil <add> newest_committed_revision = nil <add> newest_committed_url = nil <add> <add> fv.rev_list("origin/master") do |rev| <add> begin <add> fv.formula_at_revision(rev) do |f| <add> stable = f.stable <add> next if stable.blank? <add> <add> previous_version = stable.version <add> previous_checksum = stable.checksum <add> previous_version_scheme = f.version_scheme <add> previous_revision = f.revision <add> <add> newest_committed_version ||= previous_version <add> newest_committed_checksum ||= previous_checksum <add> newest_committed_revision ||= previous_revision <add> newest_committed_url ||= stable.url <add> end <add> rescue MacOSVersionError <add> break <add> end <add> <add> break if previous_version && current_version != previous_version <add> break if previous_revision && current_revision != previous_revision <add> end <add> <add> if current_version == newest_committed_version && <add> current_url == newest_committed_url && <add> current_checksum != newest_committed_checksum && <add> current_checksum.present? && newest_committed_checksum.present? <add> problem( <add> "stable sha256 changed without the url/version also changing; " \ <add> "please create an issue upstream to rule out malicious " \ <add> "circumstances and to find out why the file changed.", <add> ) <add> end <add> <add> if !newest_committed_version.nil? && <add> current_version < newest_committed_version && <add> current_version_scheme == previous_version_scheme <add> problem "stable version should not decrease (from #{newest_committed_version} to #{current_version})" <add> end <add> <add> unless previous_version_scheme.nil? <add> if current_version_scheme < previous_version_scheme <add> problem "version_scheme should not decrease (from #{previous_version_scheme} " \ <add> "to #{current_version_scheme})" <add> elsif current_version_scheme > (previous_version_scheme + 1) <add> problem "version_schemes should only increment by 1" <add> end <add> end <add> <add> if (previous_version != newest_committed_version || <add> current_version != newest_committed_version) && <add> !current_revision.zero? && <add> current_revision == newest_committed_revision && <add> current_revision == previous_revision <add> problem "'revision #{current_revision}' should be removed" <add> elsif current_version == previous_version && <add> !previous_revision.nil? && <add> current_revision < previous_revision <add> problem "revision should not decrease (from #{previous_revision} to #{current_revision})" <add> elsif newest_committed_revision && <add> current_revision > (newest_committed_revision + 1) <add> problem "revisions should only increment by 1" <add> end <add> end <add> <add> def audit_text <add> bin_names = Set.new <add> bin_names << formula.name <add> bin_names += formula.aliases <add> [formula.bin, formula.sbin].each do |dir| <add> next unless dir.exist? <add> <add> bin_names += dir.children.map(&:basename).map(&:to_s) <add> end <add> shell_commands = ["system", "shell_output", "pipe_output"] <add> bin_names.each do |name| <add> shell_commands.each do |cmd| <add> if text.to_s.match?(/test do.*#{cmd}[(\s]+['"]#{Regexp.escape(name)}[\s'"]/m) <add> problem %Q(fully scope test #{cmd} calls, e.g. #{cmd} "\#{bin}/#{name}") <add> end <add> end <add> end <add> end <add> <add> def audit_reverse_migration <add> # Only enforce for new formula being re-added to core <add> return unless @strict <add> return unless @core_tap <add> return unless formula.tap.tap_migrations.key?(formula.name) <add> <add> problem <<~EOS <add> #{formula.name} seems to be listed in tap_migrations.json! <add> Please remove #{formula.name} from present tap & tap_migrations.json <add> before submitting it to Homebrew/homebrew-#{formula.tap.repo}. <add> EOS <add> end <add> <add> def audit_prefix_has_contents <add> return unless formula.prefix.directory? <add> return unless Keg.new(formula.prefix).empty_installation? <add> <add> problem <<~EOS <add> The installation seems to be empty. Please ensure the prefix <add> is set correctly and expected files are installed. <add> The prefix configure/make argument may be case-sensitive. <add> EOS <add> end <add> <add> def quote_dep(dep) <add> dep.is_a?(Symbol) ? dep.inspect : "'#{dep}'" <add> end <add> <add> def problem_if_output(output) <add> problem(output) if output <add> end <add> <add> def audit <add> only_audits = @only <add> except_audits = @except <add> <add> methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name| <add> name = audit_method_name.delete_prefix("audit_") <add> if only_audits <add> next unless only_audits.include?(name) <add> elsif except_audits <add> next if except_audits.include?(name) <add> end <add> send(audit_method_name) <add> end <add> end <add> <add> private <add> <add> def problem(message, location: nil) <add> @problems << ({ message: message, location: location }) <add> end <add> <add> def new_formula_problem(message, location: nil) <add> @new_formula_problems << ({ message: message, location: location }) <add> end <add> <add> def head_only?(formula) <add> formula.head && formula.stable.nil? <add> end <add> <add> def tap_audit_exception(list, formula, value = nil) <add> return false unless @tap_audit_exceptions.key? list <add> <add> list = @tap_audit_exceptions[list] <add> <add> case list <add> when Array <add> list.include? formula <add> when Hash <add> return false unless list.include? formula <add> return list[formula] if value.blank? <add> <add> list[formula] == value <add> end <add> end <add> end <add>end <ide><path>Library/Homebrew/formula_text_auditor.rb <add># typed: false <add># frozen_string_literal: true <add> <add>module Homebrew <add> # Auditor for checking common violations in {Formula} text content. <add> # <add> # @api private <add> class FormulaTextAuditor <add> def initialize(path) <add> @text = path.open("rb", &:read) <add> @lines = @text.lines.to_a <add> end <add> <add> def without_patch <add> @text.split("\n__END__").first <add> end <add> <add> def trailing_newline? <add> /\Z\n/ =~ @text <add> end <add> <add> def =~(other) <add> other =~ @text <add> end <add> <add> def include?(s) <add> @text.include? s <add> end <add> <add> def line_number(regex, skip = 0) <add> index = @lines.drop(skip).index { |line| line =~ regex } <add> index ? index + 1 : nil <add> end <add> <add> def reverse_line_number(regex) <add> index = @lines.reverse.index { |line| line =~ regex } <add> index ? @lines.count - index : nil <add> end <add> end <add>end <ide><path>Library/Homebrew/resource_auditor.rb <add># typed: false <add># frozen_string_literal: true <add> <add>module Homebrew <add> # Auditor for checking common violations in {Resource}s. <add> # <add> # @api private <add> class ResourceAuditor <add> attr_reader :name, :version, :checksum, :url, :mirrors, :using, :specs, :owner, :spec_name, :problems <add> <add> def initialize(resource, spec_name, options = {}) <add> @name = resource.name <add> @version = resource.version <add> @checksum = resource.checksum <add> @url = resource.url <add> @mirrors = resource.mirrors <add> @using = resource.using <add> @specs = resource.specs <add> @owner = resource.owner <add> @spec_name = spec_name <add> @online = options[:online] <add> @strict = options[:strict] <add> @problems = [] <add> end <add> <add> def audit <add> audit_version <add> audit_download_strategy <add> audit_urls <add> self <add> end <add> <add> def audit_version <add> if version.nil? <add> problem "missing version" <add> elsif !version.detected_from_url? <add> version_text = version <add> version_url = Version.detect(url, **specs) <add> if version_url.to_s == version_text.to_s && version.instance_of?(Version) <add> problem "version #{version_text} is redundant with version scanned from URL" <add> end <add> end <add> end <add> <add> def audit_download_strategy <add> url_strategy = DownloadStrategyDetector.detect(url) <add> <add> if (using == :git || url_strategy == GitDownloadStrategy) && specs[:tag] && !specs[:revision] <add> problem "Git should specify :revision when a :tag is specified." <add> end <add> <add> return unless using <add> <add> if using == :cvs <add> mod = specs[:module] <add> <add> problem "Redundant :module value in URL" if mod == name <add> <add> if url.match?(%r{:[^/]+$}) <add> mod = url.split(":").last <add> <add> if mod == name <add> problem "Redundant CVS module appended to URL" <add> else <add> problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL" <add> end <add> end <add> end <add> <add> return unless url_strategy == DownloadStrategyDetector.detect("", using) <add> <add> problem "Redundant :using value in URL" <add> end <add> <add> def self.curl_openssl_and_deps <add> @curl_openssl_and_deps ||= begin <add> formulae_names = ["curl", "openssl"] <add> formulae_names += formulae_names.flat_map do |f| <add> Formula[f].recursive_dependencies.map(&:name) <add> end <add> formulae_names.uniq <add> rescue FormulaUnavailableError <add> [] <add> end <add> end <add> <add> def audit_urls <add> return unless @online <add> <add> urls = [url] + mirrors <add> urls.each do |url| <add> next if !@strict && mirrors.include?(url) <add> <add> strategy = DownloadStrategyDetector.detect(url, using) <add> if strategy <= CurlDownloadStrategy && !url.start_with?("file") <add> # A `brew mirror`'ed URL is usually not yet reachable at the time of <add> # pull request. <add> next if url.match?(%r{^https://dl.bintray.com/homebrew/mirror/}) <add> <add> if http_content_problem = curl_check_http_content(url) <add> problem http_content_problem <add> end <add> elsif strategy <= GitDownloadStrategy <add> problem "The URL #{url} is not a valid git URL" unless Utils::Git.remote_exists? url <add> elsif strategy <= SubversionDownloadStrategy <add> next unless DevelopmentTools.subversion_handles_most_https_certificates? <add> next unless Utils::Svn.available? <add> <add> problem "The URL #{url} is not a valid svn URL" unless Utils::Svn.remote_exists? url <add> end <add> end <add> end <add> <add> def problem(text) <add> @problems << text <add> end <add> end <add>end <ide><path>Library/Homebrew/tap_auditor.rb <ide> # frozen_string_literal: true <ide> <ide> module Homebrew <del> # Auditor for checking common violations in taps. <add> # Auditor for checking common violations in {Tap}s. <ide> # <ide> # @api private <ide> class TapAuditor <ide><path>Library/Homebrew/test/dev-cmd/audit_spec.rb <ide> def self.increment <ide> end <ide> <ide> module Homebrew <del> describe FormulaText do <add> describe FormulaTextAuditor do <ide> alias_matcher :have_data, :be_data <ide> alias_matcher :have_end, :be_end <ide> alias_matcher :have_trailing_newline, :be_trailing_newline
6
Text
Text
update releaser in v12.18.4 changelog
524123fbf064ff64bb6fcd83485cfc27db932f68
<ide><path>doc/changelogs/CHANGELOG_V12.md <ide> * [Archive](CHANGELOG_ARCHIVE.md) <ide> <ide> <a id="12.18.4"></a> <del>## 2020-09-15, Version 12.18.4 'Erbium' (LTS), @targos <add>## 2020-09-15, Version 12.18.4 'Erbium' (LTS), @BethGriggs prepared by @targos <ide> <ide> ### Notable Changes <ide>
1
Ruby
Ruby
extend fileutils rather than include it
67c3f1b2b4e4697af93a3e78e31fd00df2d02966
<ide><path>Library/Homebrew/extend/fileutils.rb <ide> require 'fileutils' <ide> <ide> # We enhance FileUtils to make our Formula code more readable. <del>module Homebrew::FileUtils <del> include FileUtils <add>module FileUtils extend self <ide> <ide> # Create a temporary directory then yield. When the block returns, <ide> # recursively delete the temporary directory. <ide> def mktemp <ide> <ide> # A version of mkdir that also changes to that folder in a block. <ide> def mkdir name, &block <del> super(name) <add> FileUtils.mkdir(name) <ide> if block_given? <ide> chdir name do <ide> yield <ide><path>Library/Homebrew/formula.rb <ide> <ide> # Derive and define at least @url, see Library/Formula for examples <ide> class Formula <del> include Homebrew::FileUtils <add> include FileUtils <ide> <ide> attr_reader :name, :path, :url, :version, :homepage, :specs, :downloader <ide> attr_reader :standard, :unstable
2
PHP
PHP
move location of laravel_start
18cda5037ae4d500d59e43dced68d63b20c5c791
<ide><path>bootstrap/autoload.php <ide> <?php <ide> <add>define('LARAVEL_START', microtime(true)); <add> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | Register The Composer Auto Loader <ide><path>public/index.php <ide> * @author Taylor Otwell <taylorotwell@gmail.com> <ide> */ <ide> <del>define('LARAVEL_START', microtime(true)); <del> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | Register The Auto Loader
2
PHP
PHP
change code style to match with style ci
ba3bcebbe32f87a54da37ef99581c164fe22ef2c
<ide><path>src/Illuminate/Cache/FileStore.php <ide> public function put($key, $value, $minutes) <ide> protected function createCacheDirectory($path) <ide> { <ide> try { <del> if (!file_exists(dirname($path))) { <add> if (! file_exists(dirname($path))) { <ide> $this->files->makeDirectory(dirname($path), 0777, true, true); <ide> } <ide> } catch (Exception $e) {
1
Javascript
Javascript
make rest of code review changes
30ec96f80cc38fabb0506b39d0dbb65248d727f8
<ide><path>src/lib/duration/constructor.js <ide> export function Duration (duration) { <ide> milliseconds = normalizedInput.millisecond || 0; <ide> <ide> this._isValid = isDurationValid(normalizedInput); <del> this.isValid = function () { <del> return this._isValid; <del> }; <ide> <ide> // representation for dateAddRemove <ide> this._milliseconds = +milliseconds + <ide><path>src/lib/duration/prototype.js <ide> import { get, milliseconds, seconds, minutes, hours, days, months, years, weeks <ide> import { humanize } from './humanize'; <ide> import { toISOString } from './iso-string'; <ide> import { lang, locale, localeData } from '../moment/locale'; <del>import isDurationValid from './valid'; <add>import { isValid } from './valid'; <ide> <add>proto.isValid = isValid; <ide> proto.abs = abs; <ide> proto.add = add; <ide> proto.subtract = subtract; <ide> proto.toString = toISOString; <ide> proto.toJSON = toISOString; <ide> proto.locale = locale; <ide> proto.localeData = localeData; <del>proto.isValid = isDurationValid; <ide> <ide> // Deprecations <ide> import { deprecate } from '../utils/deprecate'; <ide><path>src/lib/duration/valid.js <ide> export default function isDurationValid(m) { <ide> <ide> return true; <ide> } <add> <add>export function isValid() { <add> return this._isValid; <add>} <ide><path>src/test/moment/duration_invalid.js <ide> test('invalid duration', function (assert) { <ide> assert.ok(isNaN(m.valueOf())); <ide> }); <ide> <add>test('valid duration - as per @ichernev', function (assert) { <add> var m = moment.duration({d: null}); // should be valid, for now <add> assert.equal(m.isValid(), true); <add> assert.equal(m.valueOf(), 0); <add>}); <add> <ide> test('invalid duration - only smallest unit can have decimal', function (assert) { <ide> var m = moment.duration({'days': 3.5, 'hours': 1.1}); // should be invalid <ide> assert.equal(m.isValid(), false);
4
Javascript
Javascript
remove prop `onnavigate`
fb0007d85323909ab652bf97166744fa7e17daab
<ide><path>Examples/UIExplorer/NavigationExperimental/NavigationCardStack-example.js <ide> const NavigationExampleRow = require('./NavigationExampleRow'); <ide> const React = require('react'); <ide> const ReactNative = require('react-native'); <ide> <del>const emptyFunction = require('fbjs/lib/emptyFunction'); <del> <ide> /** <ide> * Basic example that shows how to use <NavigationCardStack /> to build <ide> * an app with controlled navigation system. <ide> class YourNavigator extends React.Component { <ide> <ide> // Now use the `NavigationCardStack` to render the scenes. <ide> render(): ReactElement { <del> // TODO(hedger): prop `onNavigate` will be deprecated soon. For now, <del> // use `emptyFunction` as a placeholder. <ide> return ( <ide> <NavigationCardStack <del> onNavigate={emptyFunction} <ide> onNavigateBack={this._onPopRoute} <ide> navigationState={this.props.navigationState} <ide> renderScene={this._renderScene} <ide><path>Examples/UIExplorer/NavigationExperimental/NavigationHeaderScenesTabs-example.js <ide> const YourNavigator = createAppNavigationContainer(class extends Component { <ide> // This sets up the methods (e.g. Pop, Push) for navigation. <ide> constructor(props: any, context: any) { <ide> super(props, context); <add> this._back = this._back.bind(this); <ide> this._renderHeader = this._renderHeader.bind(this); <ide> this._renderScene = this._renderScene.bind(this); <ide> } <ide> const YourNavigator = createAppNavigationContainer(class extends Component { <ide> <View style={styles.navigator}> <ide> <NavigationCardStack <ide> key={'stack_' + tabKey} <del> onNavigate={this.props.navigate} <add> onNavigateBack={this._back} <ide> navigationState={scenes} <ide> renderOverlay={this._renderHeader} <ide> renderScene={this._renderScene} <ide> const YourNavigator = createAppNavigationContainer(class extends Component { <ide> /> <ide> ); <ide> } <add> <add> _back() { <add> this.props.navigate({type: 'pop'}); <add> } <ide> }); <ide> <ide> // Next step. <ide> const YourHeader = createAppNavigationContainer(class extends Component { <ide> <ide> constructor(props: Object, context: any) { <ide> super(props, context); <add> this._back = this._back.bind(this); <ide> this._renderTitleComponent = this._renderTitleComponent.bind(this); <ide> } <ide> <ide> const YourHeader = createAppNavigationContainer(class extends Component { <ide> <NavigationHeader <ide> {...this.props} <ide> renderTitleComponent={this._renderTitleComponent} <del> onNavigate={this.props.navigate} <add> onNavigateBack={this._back} <ide> /> <ide> ); <ide> } <ide> <add> _back(): void { <add> this.props.navigate({type: 'pop'}); <add> } <add> <ide> _renderTitleComponent(): ReactElement { <ide> return ( <ide> <NavigationHeader.Title> <ide><path>Examples/UIExplorer/UIExplorerApp.ios.js <ide> type State = UIExplorerNavigationState & { <ide> const APP_STATE_KEY = 'UIExplorerAppState.v1'; <ide> <ide> class UIExplorerApp extends React.Component { <add> _handleBack: Function; <add> _handleAction: Function; <add> _renderCard: Function; <ide> _renderOverlay: Function; <ide> _renderScene: Function; <del> _renderCard: Function; <ide> _renderTitleComponent: Function; <del> _handleAction: Function; <ide> state: State; <ide> <ide> constructor(props: Props) { <ide> class UIExplorerApp extends React.Component { <ide> <ide> componentWillMount() { <ide> this._handleAction = this._handleAction.bind(this); <add> this._handleBack = this._handleAction.bind(this, {type: 'back'}); <ide> this._renderOverlay = this._renderOverlay.bind(this); <ide> this._renderScene = this._renderScene.bind(this); <ide> this._renderTitleComponent = this._renderTitleComponent.bind(this); <ide> class UIExplorerApp extends React.Component { <ide> style={styles.container} <ide> renderOverlay={this._renderOverlay} <ide> renderScene={this._renderScene} <del> onNavigate={this._handleAction} <add> <ide> /> <ide> ); <ide> } <ide> class UIExplorerApp extends React.Component { <ide> return ( <ide> <NavigationHeader <ide> {...props} <add> onNavigateBack={this._handleBack} <ide> renderTitleComponent={this._renderTitleComponent} <ide> /> <ide> ); <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCard.js <ide> type SceneViewProps = { <ide> <ide> type Props = NavigationSceneRendererProps & { <ide> onComponentRef: (ref: any) => void, <add> onNavigateBack: ?Function, <ide> panHandlers: ?NavigationPanPanHandlers, <ide> pointerEvents: string, <ide> renderScene: NavigationSceneRenderer, <ide> class NavigationCard extends React.Component<any, Props, any> { <ide> static propTypes = { <ide> ...NavigationPropTypes.SceneRendererProps, <ide> onComponentRef: PropTypes.func.isRequired, <add> onNavigateBack: PropTypes.func, <ide> panHandlers: NavigationPropTypes.panHandlers, <ide> pointerEvents: PropTypes.string.isRequired, <ide> renderScene: PropTypes.func.isRequired, <ide> class NavigationCard extends React.Component<any, Props, any> { <ide> style; <ide> <ide> const viewPanHandlers = panHandlers === undefined ? <del> NavigationCardStackPanResponder.forHorizontal(props) : <add> NavigationCardStackPanResponder.forHorizontal({ <add> ...props, <add> onNavigateBack: this.props.onNavigateBack, <add> }) : <ide> panHandlers; <ide> <ide> return ( <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStack.js <ide> const {PropTypes} = React; <ide> const {Directions} = NavigationCardStackPanResponder; <ide> <ide> import type { <del> NavigationActionCaller, <ide> NavigationState, <ide> NavigationSceneRenderer, <ide> NavigationSceneRendererProps, <ide> import type { <ide> type Props = { <ide> direction: NavigationGestureDirection, <ide> navigationState: NavigationState, <del> onNavigate: NavigationActionCaller, <add> onNavigateBack: ?Function, <ide> renderOverlay: ?NavigationSceneRenderer, <ide> renderScene: NavigationSceneRenderer, <add> style: any, <ide> }; <ide> <ide> type DefaultProps = { <ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> { <ide> static propTypes = { <ide> direction: PropTypes.oneOf([Directions.HORIZONTAL, Directions.VERTICAL]), <ide> navigationState: NavigationPropTypes.navigationState.isRequired, <del> onNavigate: NavigationPropTypes.SceneRendererProps.onNavigate, <add> onNavigateBack: PropTypes.func, <ide> renderOverlay: PropTypes.func, <ide> renderScene: PropTypes.func.isRequired, <ide> }; <ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> { <ide> navigationState={this.props.navigationState} <ide> renderOverlay={this.props.renderOverlay} <ide> renderScene={this._renderScene} <del> onNavigate={this.props.onNavigate} <del> // $FlowFixMe - style should be declared <ide> style={[styles.animatedView, this.props.style]} <ide> /> <ide> ); <ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> { <ide> NavigationCardStackStyleInterpolator.forVertical(props) : <ide> NavigationCardStackStyleInterpolator.forHorizontal(props); <ide> <add> const panHandlersProps = { <add> ...props, <add> onNavigateBack: this.props.onNavigateBack, <add> }; <ide> const panHandlers = isVertical ? <del> NavigationCardStackPanResponder.forVertical(props) : <del> NavigationCardStackPanResponder.forHorizontal(props); <add> NavigationCardStackPanResponder.forVertical(panHandlersProps) : <add> NavigationCardStackPanResponder.forHorizontal(panHandlersProps); <ide> <ide> return ( <ide> <NavigationCard <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStackPanResponder.js <ide> import type { <ide> const ANIMATION_DURATION = 250; <ide> <ide> /** <del> * The threshold to invoke the `onNavigate` action. <add> * The threshold to invoke the `onNavigateBack` action. <ide> * For instance, `1 / 3` means that moving greater than 1 / 3 of the width of <ide> * the view will navigate. <ide> */ <ide> const Directions = { <ide> <ide> export type NavigationGestureDirection = 'horizontal' | 'vertical'; <ide> <del>/** <del> * Primitive gesture actions. <del> */ <del>const Actions = { <del> // The gesture to navigate backward. <del> // This is done by swiping from the left to the right or from the top to the <del> // bottom. <del> BACK: {type: 'back'}, <add>type Props = NavigationSceneRendererProps & { <add> onNavigateBack: ?Function, <ide> }; <ide> <ide> /** <ide> class NavigationCardStackPanResponder extends NavigationAbstractPanResponder { <ide> <ide> _isResponding: boolean; <ide> _isVertical: boolean; <del> _props: NavigationSceneRendererProps; <add> _props: Props; <ide> _startValue: number; <ide> <ide> constructor( <ide> direction: NavigationGestureDirection, <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ) { <ide> super(); <ide> this._isResponding = false; <ide> class NavigationCardStackPanResponder extends NavigationAbstractPanResponder { <ide> <ide> props.position.stopAnimation((value: number) => { <ide> this._reset(); <del> if (distance > DISTANCE_THRESHOLD || value <= index - POSITION_THRESHOLD) { <del> props.onNavigate(Actions.BACK); <add> <add> if (!props.onNavigateBack) { <add> return; <add> } <add> <add> if ( <add> distance > DISTANCE_THRESHOLD || <add> value <= index - POSITION_THRESHOLD <add> ) { <add> props.onNavigateBack(); <ide> } <ide> }); <ide> } <ide> class NavigationCardStackPanResponder extends NavigationAbstractPanResponder { <ide> <ide> function createPanHandlers( <ide> direction: NavigationGestureDirection, <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ): NavigationPanPanHandlers { <ide> const responder = new NavigationCardStackPanResponder(direction, props); <ide> return responder.panHandlers; <ide> } <ide> <ide> function forHorizontal( <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ): NavigationPanPanHandlers { <ide> return createPanHandlers(Directions.HORIZONTAL, props); <ide> } <ide> <ide> function forVertical( <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ): NavigationPanPanHandlers { <ide> return createPanHandlers(Directions.VERTICAL, props); <ide> } <ide> module.exports = { <ide> RESPOND_THRESHOLD, <ide> <ide> // enums <del> Actions, <ide> Directions, <ide> <ide> // methods. <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationHeader.js <ide> const { <ide> } = ReactNative; <ide> <ide> import type { <del> NavigationActionCaller, <del> NavigationSceneRenderer, <ide> NavigationSceneRendererProps, <ide> NavigationStyleInterpolator, <ide> } from 'NavigationTypeDefinition'; <ide> <add>type SubViewProps = NavigationSceneRendererProps & { <add> onNavigateBack: ?Function, <add>}; <add> <add>type SubViewRenderer = (subViewProps: SubViewProps) => ?ReactElement<any>; <add> <ide> type DefaultProps = { <del> renderLeftComponent: NavigationSceneRenderer, <del> renderRightComponent: NavigationSceneRenderer, <del> renderTitleComponent: NavigationSceneRenderer, <add> renderLeftComponent: SubViewRenderer, <add> renderRightComponent: SubViewRenderer, <add> renderTitleComponent: SubViewRenderer, <ide> }; <ide> <ide> type Props = NavigationSceneRendererProps & { <del> renderLeftComponent: NavigationSceneRenderer, <del> renderRightComponent: NavigationSceneRenderer, <del> renderTitleComponent: NavigationSceneRenderer, <del> onNavigate: NavigationActionCaller, <add> onNavigateBack: ?Function, <add> renderLeftComponent: SubViewRenderer, <add> renderRightComponent: SubViewRenderer, <add> renderTitleComponent: SubViewRenderer, <ide> style?: any, <ide> viewProps?: any, <ide> }; <ide> class NavigationHeader extends React.Component<DefaultProps, Props, any> { <ide> <ide> static defaultProps = { <ide> <del> renderTitleComponent: (props: NavigationSceneRendererProps) => { <add> renderTitleComponent: (props: SubViewProps) => { <ide> const {navigationState} = props; <ide> const title = String(navigationState.title || ''); <ide> return <NavigationHeaderTitle>{title}</NavigationHeaderTitle>; <ide> }, <ide> <del> renderLeftComponent: (props: NavigationSceneRendererProps) => { <del> if (props.scene.index === 0) { <add> renderLeftComponent: (props: SubViewProps) => { <add> if (props.scene.index === 0 || !props.onNavigateBack) { <ide> return null; <ide> } <ide> return ( <ide> <NavigationHeaderBackButton <del> onNavigate={props.onNavigate} <add> onPress={props.onNavigateBack} <ide> /> <ide> ); <ide> }, <ide> <del> renderRightComponent: (props: NavigationSceneRendererProps) => { <add> renderRightComponent: (props: SubViewProps) => { <ide> return null; <ide> }, <ide> }; <ide> <ide> static propTypes = { <ide> ...NavigationPropTypes.SceneRendererProps, <add> onNavigateBack: PropTypes.func, <ide> renderLeftComponent: PropTypes.func, <ide> renderRightComponent: PropTypes.func, <ide> renderTitleComponent: PropTypes.func, <ide> class NavigationHeader extends React.Component<DefaultProps, Props, any> { <ide> _renderSubView( <ide> props: NavigationSceneRendererProps, <ide> name: SubViewName, <del> renderer: NavigationSceneRenderer, <add> renderer: SubViewRenderer, <ide> styleInterpolator: NavigationStyleInterpolator, <ide> ): ?ReactElement<any> { <ide> const { <ide> class NavigationHeader extends React.Component<DefaultProps, Props, any> { <ide> return null; <ide> } <ide> <del> const subView = renderer(props); <add> const subViewProps = {...props, onNavigateBack: this.props.onNavigateBack}; <add> const subView = renderer(subViewProps); <ide> if (subView === null) { <ide> return null; <ide> } <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationHeaderBackButton.js <ide> const { <ide> } = ReactNative; <ide> <ide> type Props = { <del> onNavigate: Function <del>} <add> onPress: Function, <add>}; <ide> <ide> const NavigationHeaderBackButton = (props: Props) => ( <del> <TouchableOpacity style={styles.buttonContainer} onPress={() => props.onNavigate({type: 'BackAction'})}> <add> <TouchableOpacity style={styles.buttonContainer} onPress={props.onPress}> <ide> <Image style={styles.button} source={require('./assets/back-icon.png')} /> <ide> </TouchableOpacity> <ide> ); <ide> <ide> NavigationHeaderBackButton.propTypes = { <del> onNavigate: React.PropTypes.func.isRequired <add> onPress: React.PropTypes.func.isRequired <ide> }; <ide> <ide> const styles = StyleSheet.create({ <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationPagerPanResponder.js <ide> import type { <ide> NavigationGestureDirection, <ide> } from 'NavigationCardStackPanResponder'; <ide> <del> <add>type Props = NavigationSceneRendererProps & { <add> onNavigateBack: ?Function, <add> onNavigateForward: ?Function, <add>}; <ide> <ide> /** <ide> * Primitive gesture directions. <ide> const { <ide> Directions, <ide> } = NavigationCardStackPanResponder; <ide> <del>/** <del> * Primitive gesture actions. <del> */ <del>const Actions = { <del> JUMP_BACK: {type: 'jump_back'}, <del> JUMP_FORWARD: {type: 'jump_forward'}, <del>}; <del> <ide> /** <ide> * Pan responder that handles gesture for a card in the cards list. <ide> * <ide> class NavigationPagerPanResponder extends NavigationAbstractPanResponder { <ide> <ide> _isResponding: boolean; <ide> _isVertical: boolean; <del> _props: NavigationSceneRendererProps; <add> _props: Props; <ide> _startValue: number; <ide> <ide> constructor( <ide> direction: NavigationGestureDirection, <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ) { <ide> super(); <ide> this._isResponding = false; <ide> class NavigationPagerPanResponder extends NavigationAbstractPanResponder { <ide> <ide> const { <ide> navigationState, <del> onNavigate, <add> onNavigateBack, <add> onNavigateForward, <ide> position, <ide> } = this._props; <ide> <ide> class NavigationPagerPanResponder extends NavigationAbstractPanResponder { <ide> distance > DISTANCE_THRESHOLD || <ide> value <= index - POSITION_THRESHOLD <ide> ) { <del> onNavigate(Actions.JUMP_BACK); <add> onNavigateBack && onNavigateBack(); <ide> return; <ide> } <ide> <ide> if ( <ide> distance < -DISTANCE_THRESHOLD || <ide> value >= index + POSITION_THRESHOLD <ide> ) { <del> onNavigate(Actions.JUMP_FORWARD); <add> onNavigateForward && onNavigateForward(); <ide> } <ide> }); <ide> } <ide> class NavigationPagerPanResponder extends NavigationAbstractPanResponder { <ide> <ide> function createPanHandlers( <ide> direction: NavigationGestureDirection, <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ): NavigationPanPanHandlers { <ide> const responder = new NavigationPagerPanResponder(direction, props); <ide> return responder.panHandlers; <ide> } <ide> <ide> function forHorizontal( <del> props: NavigationSceneRendererProps, <add> props: Props, <ide> ): NavigationPanPanHandlers { <ide> return createPanHandlers(Directions.HORIZONTAL, props); <ide> } <ide> <ide> module.exports = { <del> Actions, <ide> forHorizontal, <ide> }; <ide><path>Libraries/NavigationExperimental/NavigationAnimatedView.js <ide> const StyleSheet = require('StyleSheet'); <ide> const View = require('View'); <ide> <ide> import type { <del> NavigationActionCaller, <ide> NavigationAnimatedValue, <ide> NavigationAnimationSetter, <ide> NavigationLayout, <ide> import type { <ide> type Props = { <ide> applyAnimation: NavigationAnimationSetter, <ide> navigationState: NavigationState, <del> onNavigate: NavigationActionCaller, <ide> renderOverlay: ?NavigationSceneRenderer, <ide> renderScene: NavigationSceneRenderer, <ide> style: any, <ide> class NavigationAnimatedView <ide> static propTypes = { <ide> applyAnimation: PropTypes.func, <ide> navigationState: NavigationPropTypes.navigationState.isRequired, <del> onNavigate: PropTypes.func.isRequired, <ide> renderOverlay: PropTypes.func, <ide> renderScene: PropTypes.func.isRequired, <ide> }; <ide> class NavigationAnimatedView <ide> _renderScene(scene: NavigationScene): ?ReactElement<any> { <ide> const { <ide> navigationState, <del> onNavigate, <ide> renderScene, <ide> } = this.props; <ide> <ide> class NavigationAnimatedView <ide> return renderScene({ <ide> layout: this.state.layout, <ide> navigationState, <del> onNavigate, <ide> position, <ide> progress, <ide> scene, <ide> class NavigationAnimatedView <ide> if (this.props.renderOverlay) { <ide> const { <ide> navigationState, <del> onNavigate, <ide> renderOverlay, <ide> } = this.props; <ide> <ide> class NavigationAnimatedView <ide> return renderOverlay({ <ide> layout: this.state.layout, <ide> navigationState, <del> onNavigate, <ide> position, <ide> progress, <ide> scene: scenes[navigationState.index], <ide><path>Libraries/NavigationExperimental/NavigationPropTypes.js <ide> const scene = PropTypes.shape({ <ide> const SceneRendererProps = { <ide> layout: layout.isRequired, <ide> navigationState: navigationState.isRequired, <del> onNavigate: PropTypes.func.isRequired, <ide> position: animatedValue.isRequired, <ide> progress: animatedValue.isRequired, <ide> scene: scene.isRequired, <ide> function extractSceneRendererProps( <ide> return { <ide> layout: props.layout, <ide> navigationState: props.navigationState, <del> onNavigate: props.onNavigate, <ide> position: props.position, <ide> progress: props.progress, <ide> scene: props.scene, <ide><path>Libraries/NavigationExperimental/NavigationTransitioner.js <ide> const View = require('View'); <ide> const invariant = require('fbjs/lib/invariant'); <ide> <ide> import type { <del> NavigationActionCaller, <ide> NavigationAnimatedValue, <ide> NavigationLayout, <ide> NavigationState, <ide> import type { <ide> type Props = { <ide> configureTransition: NavigationTransitionConfigurator, <ide> navigationState: NavigationState, <del> onNavigate: NavigationActionCaller, <ide> onTransitionEnd: () => void, <ide> onTransitionStart: () => void, <ide> renderOverlay: ?NavigationSceneRenderer, <ide> class NavigationTransitioner extends React.Component<any, Props, State> { <ide> static propTypes = { <ide> configureTransition: PropTypes.func, <ide> navigationState: NavigationPropTypes.navigationState.isRequired, <del> onNavigate: PropTypes.func.isRequired, <ide> onTransitionEnd: PropTypes.func, <ide> onTransitionStart: PropTypes.func, <ide> renderOverlay: PropTypes.func, <ide> class NavigationTransitioner extends React.Component<any, Props, State> { <ide> _renderScene(scene: NavigationScene): ?ReactElement<any> { <ide> const { <ide> navigationState, <del> onNavigate, <ide> renderScene, <ide> } = this.props; <ide> <ide> class NavigationTransitioner extends React.Component<any, Props, State> { <ide> return renderScene({ <ide> layout: this.state.layout, <ide> navigationState, <del> onNavigate, <ide> position, <ide> progress, <ide> scene, <ide> class NavigationTransitioner extends React.Component<any, Props, State> { <ide> if (this.props.renderOverlay) { <ide> const { <ide> navigationState, <del> onNavigate, <ide> renderOverlay, <ide> } = this.props; <ide> <ide> class NavigationTransitioner extends React.Component<any, Props, State> { <ide> return renderOverlay({ <ide> layout: this.state.layout, <ide> navigationState, <del> onNavigate, <ide> position, <ide> progress, <ide> scene: activeScene, <ide><path>Libraries/NavigationExperimental/NavigationTypeDefinition.js <ide> export type NavigationState = { <ide> routes: Array<NavigationRoute>, <ide> }; <ide> <del>export type NavigationAction = any; <del> <ide> export type NavigationLayout = { <ide> height: NavigationAnimatedValue, <ide> initHeight: number, <ide> export type NavigationSceneRendererProps = { <ide> // The navigation state of the containing view. <ide> navigationState: NavigationState, <ide> <del> // Callback to navigation with an action. <del> onNavigate: NavigationActionCaller, <del> <ide> // The progressive index of the containing view's navigation state. <ide> position: NavigationAnimatedValue, <ide> <ide> export type NavigationTransitionSpec = { <ide> <ide> // Functions. <ide> <del>export type NavigationActionCaller = Function; <del> <ide> export type NavigationAnimationSetter = ( <ide> position: NavigationAnimatedValue, <ide> newState: NavigationState, <ide> lastState: NavigationState, <ide> ) => void; <ide> <del>export type NavigationRenderer = ( <del> navigationState: ?NavigationRoute, <del> onNavigate: NavigationActionCaller, <del>) => ReactElement<any>; <del> <del>export type NavigationReducer = ( <del> state: ?NavigationRoute, <del> action: ?NavigationAction, <del>) => NavigationRoute; <del> <ide> export type NavigationSceneRenderer = ( <ide> props: NavigationSceneRendererProps, <ide> ) => ?ReactElement<any>;
13
Ruby
Ruby
build scope chain functionally and remove caching
3553fe03ad974bad6a97b1853b1b27c4798f1d06
<ide><path>activerecord/lib/active_record/reflection.rb <ide> def counter_must_be_updated_by_has_many? <ide> def alias_candidate(name) <ide> "#{plural_name}_#{name}" <ide> end <add> <add> def chain <add> collect_join_chain <add> end <ide> end <ide> <ide> # Base class for AggregateReflection and AssociationReflection. Objects of <ide> def source_reflection <ide> <ide> # A chain of reflections from this one back to the owner. For more see the explanation in <ide> # ThroughReflection. <del> def chain <add> def collect_join_chain <ide> [self] <ide> end <ide> <ide> def polymorphic? <ide> VALID_AUTOMATIC_INVERSE_MACROS = [:has_many, :has_one, :belongs_to] <ide> INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key] <ide> <add> def add_as_source(seed) <add> seed <add> end <add> <add> def add_as_polymorphic_through(reflection, seed) <add> seed + [PolymorphicReflection.new(self, reflection)] <add> end <add> <add> def add_as_through(seed) <add> seed + [self] <add> end <add> <ide> protected <ide> <ide> def actual_source_reflection # FIXME: this is a horrible name <ide> def through_reflection <ide> # # => [<ActiveRecord::Reflection::ThroughReflection: @delegate_reflection=#<ActiveRecord::Reflection::HasManyReflection: @name=:tags...>, <ide> # <ActiveRecord::Reflection::HasManyReflection: @name=:taggings, @options={}, @active_record=Post>] <ide> # <del> def chain <del> @chain ||= begin <del> a = source_reflection.chain <del> b = through_reflection.chain.map(&:dup) <del> <del> if options[:source_type] <del> b[0] = PolymorphicReflection.new(b[0], self) <del> end <del> <del> chain = a + b <del> chain[0] = self # Use self so we don't lose the information from :source_type <del> chain <del> end <add> def collect_join_chain <add> collect_join_reflections [self] <ide> end <ide> <ide> # This is for clearing cache on the reflection. Useful for tests that need to compare <ide> def constraints <ide> scope_chain <ide> end <ide> <add> def add_as_source(seed) <add> collect_join_reflections seed <add> end <add> <add> def add_as_polymorphic_through(reflection, seed) <add> collect_join_reflections(seed + [PolymorphicReflection.new(self, reflection)]) <add> end <add> <add> def add_as_through(seed) <add> collect_join_reflections(seed + [self]) <add> end <add> <add> def collect_join_reflections(seed) <add> a = source_reflection.add_as_source seed <add> if options[:source_type] <add> through_reflection.add_as_polymorphic_through self, a <add> else <add> through_reflection.add_as_through a <add> end <add> end <add> <ide> protected <ide> <ide> def actual_source_reflection # FIXME: this is a horrible name
1
Text
Text
remove rails/actioncable travis badge
70e593d99877bce8dd6f27b2a080d5936e071709
<ide><path>actioncable/README.md <del># Action Cable – Integrated WebSockets for Rails <del>[![Build Status](https://travis-ci.org/rails/actioncable.svg)](https://travis-ci.org/rails/actioncable) <add># Action Cable –- Integrated WebSockets for Rails <ide> <ide> Action Cable seamlessly integrates WebSockets with the rest of your Rails application. <ide> It allows for real-time features to be written in Ruby in the same style
1
Python
Python
add lang attribute to english and german
8c8f5c62c6680f2700d7488555916dd89d4befcd
<ide><path>spacy/de/__init__.py <ide> from os import path <ide> <ide> from ..language import Language <add>from ..attrs import LANG <ide> from . import language_data <ide> <ide> <ide> class German(Language): <ide> <ide> class Defaults(Language.Defaults): <ide> tokenizer_exceptions = dict(language_data.TOKENIZER_EXCEPTIONS) <add> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <add> lex_attr_getters[LANG] = lambda text: 'de' <ide> <ide> prefixes = tuple(language_data.TOKENIZER_PREFIXES) <ide> <ide><path>spacy/en/__init__.py <ide> from ..lemmatizer import Lemmatizer <ide> from ..vocab import Vocab <ide> from ..tokenizer import Tokenizer <add>from ..attrs import LANG <ide> <ide> <ide> class English(Language): <ide> lang = 'en' <ide> <ide> class Defaults(Language.Defaults): <ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters) <add> lex_attr_getters[LANG] = lambda text: 'en' <ide> <ide> tokenizer_exceptions = dict(language_data.TOKENIZER_EXCEPTIONS) <del> <add> <ide> prefixes = tuple(language_data.TOKENIZER_PREFIXES) <del> <add> <ide> suffixes = tuple(language_data.TOKENIZER_SUFFIXES) <del> <add> <ide> infixes = tuple(language_data.TOKENIZER_INFIXES) <ide> <ide> tag_map = dict(language_data.TAG_MAP)
2