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
|
---|---|---|---|---|---|
PHP | PHP | use safeemail instead | 00e5c4465cd42c4ed8be3c8ee8aa9c6f09df5f87 | <ide><path>database/factories/ModelFactory.php
<ide> $factory->define(App\User::class, function (Faker\Generator $faker) {
<ide> return [
<ide> 'name' => $faker->name,
<del> 'email' => $faker->email,
<add> 'email' => $faker->safeEmail,
<ide> 'password' => bcrypt(str_random(10)),
<ide> 'remember_token' => str_random(10),
<ide> ]; | 1 |
Java | Java | fix typo in javadoc | e95391765ce7632bcef77b957855f2e100c5fee0 | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java
<ide> public String getNamespaceURI(Node node) {
<ide> }
<ide>
<ide> /**
<del> * Ges the local name for the supplied {@link Node}.
<add> * Get the local name for the supplied {@link Node}.
<ide> * <p>The default implementation calls {@link Node#getLocalName}.
<ide> * Subclasses may override the default implementation to provide a
<ide> * different mechanism for getting the local name. | 1 |
Ruby | Ruby | create readme in tap path | 881d68d35556097ef62031b7e5728e445d74d558 | <ide><path>Library/Homebrew/cmd/tap-readme.rb
<ide> def tap_readme
<ide> EOS
<ide>
<ide> puts template if ARGV.verbose?
<del> path = Pathname.new("./README.md")
<add> path = HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-#{name}/README.md"
<ide> raise "#{path} already exists" if path.exist?
<ide> path.write template
<ide> end | 1 |
Python | Python | add f2py2e f2cmap flag test | 55b16bf711c7d1d1e7405320a0ead7d664c1278e | <ide><path>numpy/f2py/tests/test_f2py2e.py
<ide> def retreal_f77(tmpdir_factory):
<ide> fn.write_text(fdat, encoding="ascii")
<ide> return fn
<ide>
<add>@pytest.fixture(scope="session")
<add>def f2cmap_f90(tmpdir_factory):
<add> """Generates a single f90 file for testing"""
<add> fdat = util.getpath("tests", "src", "f2cmap", "isoFortranEnvMap.f90").read_text()
<add> f2cmap = util.getpath("tests", "src", "f2cmap", ".f2py_f2cmap").read_text()
<add> fn = tmpdir_factory.getbasetemp() / "f2cmap.f90"
<add> fmap = tmpdir_factory.getbasetemp() / "mapfile"
<add> fn.write_text(fdat, encoding="ascii")
<add> fmap.write_text(f2cmap, encoding="ascii")
<add> return fn
<add>
<ide>
<ide> def test_gen_pyf(capfd, hello_world_f90, monkeypatch):
<ide> """Ensures that a signature file is generated via the CLI
<ide> def test_hlink():
<ide> pass
<ide>
<ide>
<del>def test_f2cmap():
<add>def test_f2cmap(capfd, f2cmap_f90, monkeypatch):
<ide> """Check that Fortran-to-Python KIND specs can be passed
<ide>
<ide> CLI :: --f2cmap
<ide> """
<del> # TODO: populate
<del> pass
<add> ipath = Path(f2cmap_f90)
<add> monkeypatch.setattr(sys, "argv", f'f2py -m blah {ipath} --f2cmap mapfile'.split())
<add>
<add> with util.switchdir(ipath.parent):
<add> f2pycli()
<add> out, _ = capfd.readouterr()
<add> assert "Reading f2cmap from 'mapfile' ..." in out
<add> assert "Mapping \"real(kind=real32)\" to \"float\"" in out
<add> assert "Mapping \"real(kind=real64)\" to \"double\"" in out
<add> assert "Mapping \"integer(kind=int64)\" to \"long_long\"" in out
<add> assert "Successfully applied user defined f2cmap changes" in out
<ide>
<ide>
<ide> def test_quiet(capfd, hello_world_f90, monkeypatch): | 1 |
Python | Python | replace deprecated get_or_create_global_step | a2b2088c52635b86f4a2ac70391118b9419b3c55 | <ide><path>research/adversarial_text/graphs.py
<ide> class VatxtModel(object):
<ide> """
<ide>
<ide> def __init__(self, cl_logits_input_dim=None):
<del> self.global_step = tf.contrib.framework.get_or_create_global_step()
<add> self.global_step = tf.train.get_or_create_global_step()
<ide> self.vocab_freqs = _get_vocab_freqs()
<ide>
<ide> # Cache VatxtInput objects
<ide><path>research/learning_to_remember_rare_events/model.py
<ide> def __init__(self, input_dim, output_dim, rep_dim, memory_size, vocab_size,
<ide> self.memory = self.get_memory()
<ide> self.classifier = self.get_classifier()
<ide>
<del> self.global_step = tf.contrib.framework.get_or_create_global_step()
<add> self.global_step = tf.train.get_or_create_global_step()
<ide>
<ide> def get_embedder(self):
<ide> return LeNet(int(self.input_dim ** 0.5), 1, self.rep_dim)
<ide><path>research/pcl_rl/trainer.py
<ide> def init_fn(sess, saver):
<ide>
<ide> if FLAGS.supervisor:
<ide> with tf.device(tf.ReplicaDeviceSetter(FLAGS.ps_tasks, merge_devices=True)):
<del> self.global_step = tf.contrib.framework.get_or_create_global_step()
<add> self.global_step = tf.train.get_or_create_global_step()
<ide> tf.set_random_seed(FLAGS.tf_seed)
<ide> self.controller = self.get_controller()
<ide> self.model = self.controller.model
<ide> def init_fn(sess, saver):
<ide> sess = sv.PrepareSession(FLAGS.master)
<ide> else:
<ide> tf.set_random_seed(FLAGS.tf_seed)
<del> self.global_step = tf.contrib.framework.get_or_create_global_step()
<add> self.global_step = tf.train.get_or_create_global_step()
<ide> self.controller = self.get_controller()
<ide> self.model = self.controller.model
<ide> self.controller.setup()
<ide><path>research/resnet/resnet_model.py
<ide> def __init__(self, hps, images, labels, mode):
<ide>
<ide> def build_graph(self):
<ide> """Build a whole graph for the model."""
<del> self.global_step = tf.contrib.framework.get_or_create_global_step()
<add> self.global_step = tf.train.get_or_create_global_step()
<ide> self._build_model()
<ide> if self.mode == 'train':
<ide> self._build_train_op()
<ide><path>research/slim/nets/nasnet/nasnet_utils.py
<ide> def _apply_drop_path(self, net):
<ide> tf.summary.scalar('layer_ratio', layer_ratio)
<ide> drop_path_keep_prob = 1 - layer_ratio * (1 - drop_path_keep_prob)
<ide> # Decrease the keep probability over time
<del> current_step = tf.cast(tf.contrib.framework.get_or_create_global_step(),
<add> current_step = tf.cast(tf.train.get_or_create_global_step(),
<ide> tf.float32)
<add> print("HERE")
<ide> drop_path_burn_in_steps = self._total_training_steps
<ide> current_ratio = (
<ide> current_step / drop_path_burn_in_steps)
<ide><path>tutorials/image/cifar10/cifar10_train.py
<ide> def train():
<ide> """Train CIFAR-10 for a number of steps."""
<ide> with tf.Graph().as_default():
<del> global_step = tf.contrib.framework.get_or_create_global_step()
<add> global_step = tf.train.get_or_create_global_step()
<ide>
<ide> # Get images and labels for CIFAR-10.
<ide> # Force input pipeline to CPU:0 to avoid operations sometimes ending up on
<ide><path>tutorials/rnn/ptb/ptb_word_lm.py
<ide> def __init__(self, is_training, config, input_):
<ide> optimizer = tf.train.GradientDescentOptimizer(self._lr)
<ide> self._train_op = optimizer.apply_gradients(
<ide> zip(grads, tvars),
<del> global_step=tf.contrib.framework.get_or_create_global_step())
<add> global_step=tf.train.get_or_create_global_step())
<ide>
<ide> self._new_lr = tf.placeholder(
<ide> tf.float32, shape=[], name="new_learning_rate") | 7 |
Text | Text | modify example of usage | 235777ccc99ddfaa6d0e8c6510fb804c5deef234 | <ide><path>model_cards/mrm8488/electricidad-small-discriminator/README.md
<ide> import torch
<ide> discriminator = ElectraForPreTraining.from_pretrained("mrm8488/electricidad-small-discriminator")
<ide> tokenizer = ElectraTokenizerFast.from_pretrained("mrm8488/electricidad-small-discriminator")
<ide>
<del>sentence = "El rápido zorro marrón salta sobre el perro perezoso"
<del>fake_sentence = "El rápido zorro marrón falsea sobre el perro perezoso"
<add>sentence = "el zorro rojo es muy rápido"
<add>fake_sentence = "el zorro rojo es muy ser"
<ide>
<ide> fake_tokens = tokenizer.tokenize(sentence)
<ide> fake_inputs = tokenizer.encode(sentence, return_tensors="pt")
<ide> predictions = torch.round((torch.sign(discriminator_outputs[0]) + 1) / 2)
<ide>
<ide> [print("%7s" % token, end="") for token in fake_tokens]
<ide>
<del>[print("%7s" % prediction, end="") for prediction in predictions.tolist()]
<add>[print("%7s" % int(prediction), end="") for prediction in predictions.tolist()[1:-1]]
<add>
<add># Output:
<add>'''
<add>el zorro rojo es muy ser 0 0 0 0 0 1[None, None, None, None, None, None]
<add>'''
<ide> ```
<ide>
<add>As you can see there is a **1** in the place where the model detected the fake token (**ser**). So, it works! 🎉
<add>
<ide> ## Acknowledgments
<ide>
<ide> I thank [🤗/transformers team](https://github.com/huggingface/transformers) for answering my doubts and Google for helping me with the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) program. | 1 |
Javascript | Javascript | add $touched and $untouched states | adcc5a00bf582d2b291c18e99093bb0854f7217c | <ide><path>src/ng/directive/input.js
<ide> -VALID_CLASS,
<ide> -INVALID_CLASS,
<ide> -PRISTINE_CLASS,
<del> -DIRTY_CLASS
<add> -DIRTY_CLASS,
<add> -UNTOUCHED_CLASS,
<add> -TOUCHED_CLASS
<ide> */
<ide>
<ide> var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
<ide> var inputDirective = ['$browser', '$sniffer', '$filter', function($browser, $sni
<ide> var VALID_CLASS = 'ng-valid',
<ide> INVALID_CLASS = 'ng-invalid',
<ide> PRISTINE_CLASS = 'ng-pristine',
<del> DIRTY_CLASS = 'ng-dirty';
<add> DIRTY_CLASS = 'ng-dirty',
<add> UNTOUCHED_CLASS = 'ng-untouched',
<add> TOUCHED_CLASS = 'ng-touched';
<ide>
<ide> /**
<ide> * @ngdoc type
<ide> var VALID_CLASS = 'ng-valid',
<ide> *
<ide> * @property {Object} $error An object hash with all errors as keys.
<ide> *
<add> * @property {boolean} $untouched True if control has not lost focus yet.
<add> * @property {boolean} $touched True if control has lost focus.
<ide> * @property {boolean} $pristine True if user has not interacted with the control yet.
<ide> * @property {boolean} $dirty True if user has already interacted with the control.
<ide> * @property {boolean} $valid True if there is no error.
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> this.$parsers = [];
<ide> this.$formatters = [];
<ide> this.$viewChangeListeners = [];
<add> this.$untouched = true;
<add> this.$touched = false;
<ide> this.$pristine = true;
<ide> this.$dirty = false;
<ide> this.$valid = true;
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide>
<ide>
<ide> // Setup initial state of the control
<del> $element.addClass(PRISTINE_CLASS);
<add> $element
<add> .addClass(PRISTINE_CLASS)
<add> .addClass(UNTOUCHED_CLASS);
<ide> toggleValidCss(true);
<ide>
<ide> // convenience method for easy toggling of classes
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
<ide> $animate.addClass($element, PRISTINE_CLASS);
<ide> };
<ide>
<add> /**
<add> * @ngdoc method
<add> * @name ngModel.NgModelController#$setUntouched
<add> *
<add> * @description
<add> * Sets the control to its untouched state.
<add> *
<add> * This method can be called to remove the 'ng-touched' class and set the control to its
<add> * untouched state (ng-untouched class).
<add> */
<add> this.$setUntouched = function() {
<add> ctrl.$touched = false;
<add> ctrl.$untouched = true;
<add> $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
<add> };
<add>
<add> /**
<add> * @ngdoc method
<add> * @name ngModel.NgModelController#$setTouched
<add> *
<add> * @description
<add> * Sets the control to its touched state.
<add> *
<add> * This method can be called to remove the 'ng-untouched' class and set the control to its
<add> * touched state (ng-touched class).
<add> */
<add> this.$setTouched = function() {
<add> ctrl.$touched = true;
<add> ctrl.$untouched = false;
<add> $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
<add> };
<add>
<ide> /**
<ide> * @ngdoc method
<ide> * @name ngModel.NgModelController#$rollbackViewValue
<ide> var ngModelDirective = function() {
<ide> });
<ide> });
<ide> }
<add>
<add> element.on('blur', function(ev) {
<add> scope.$apply(function() {
<add> modelCtrl.$setTouched();
<add> });
<add> });
<ide> }
<ide> }
<ide> };
<ide><path>test/helpers/matchers.js
<ide> beforeEach(function() {
<ide> toBeValid: cssMatcher('ng-valid', 'ng-invalid'),
<ide> toBeDirty: cssMatcher('ng-dirty', 'ng-pristine'),
<ide> toBePristine: cssMatcher('ng-pristine', 'ng-dirty'),
<add> toBeUntouched: cssMatcher('ng-untouched', 'ng-touched'),
<add> toBeTouched: cssMatcher('ng-touched', 'ng-untouched'),
<ide> toBeShown: function() {
<ide> this.message = valueFn(
<ide> "Expected element " + (this.isNot ? "": "not ") + "to have 'ng-hide' class");
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('NgModelController', function() {
<ide>
<ide>
<ide> it('should init the properties', function() {
<add> expect(ctrl.$untouched).toBe(true);
<add> expect(ctrl.$touched).toBe(false);
<ide> expect(ctrl.$dirty).toBe(false);
<ide> expect(ctrl.$pristine).toBe(true);
<ide> expect(ctrl.$valid).toBe(true);
<ide> describe('NgModelController', function() {
<ide> });
<ide> });
<ide>
<add> describe('setUntouched', function() {
<add>
<add> it('should set control to its untouched state', function() {
<add> ctrl.$setTouched();
<add>
<add> ctrl.$setUntouched();
<add> expect(ctrl.$touched).toBe(false);
<add> expect(ctrl.$untouched).toBe(true);
<add> });
<add> });
<add>
<add> describe('setTouched', function() {
<add>
<add> it('should set control to its touched state', function() {
<add> ctrl.$setUntouched();
<add>
<add> ctrl.$setTouched();
<add> expect(ctrl.$touched).toBe(true);
<add> expect(ctrl.$untouched).toBe(false);
<add> });
<add> });
<add>
<ide> describe('view -> model', function() {
<ide>
<ide> it('should set the value to $viewValue', function() {
<ide> describe('NgModelController', function() {
<ide>
<ide> describe('ngModel', function() {
<ide>
<del> it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty)',
<add> it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty, ng-untouched, ng-touched)',
<ide> inject(function($compile, $rootScope, $sniffer) {
<ide> var element = $compile('<input type="email" ng-model="value" />')($rootScope);
<ide>
<ide> $rootScope.$digest();
<ide> expect(element).toBeValid();
<ide> expect(element).toBePristine();
<add> expect(element).toBeUntouched();
<ide> expect(element.hasClass('ng-valid-email')).toBe(true);
<ide> expect(element.hasClass('ng-invalid-email')).toBe(false);
<ide>
<ide> describe('ngModel', function() {
<ide> expect(element.hasClass('ng-valid-email')).toBe(true);
<ide> expect(element.hasClass('ng-invalid-email')).toBe(false);
<ide>
<add> browserTrigger(element, 'blur');
<add> expect(element).toBeTouched();
<add>
<ide> dealoc(element);
<ide> }));
<ide>
<ide> describe('ngModel', function() {
<ide> expect(element).toHaveClass('ng-invalid-required');
<ide> }));
<ide>
<add> it('should set the control touched state on "blur" event', inject(function($compile, $rootScope) {
<add> var element = $compile('<form name="myForm">' +
<add> '<input name="myControl" ng-model="value" >' +
<add> '</form>')($rootScope);
<add> var inputElm = element.find('input');
<add> var control = $rootScope.myForm.myControl;
<add>
<add> expect(control.$touched).toBe(false);
<add> expect(control.$untouched).toBe(true);
<add>
<add> browserTrigger(inputElm, 'blur');
<add> expect(control.$touched).toBe(true);
<add> expect(control.$untouched).toBe(false);
<add>
<add> dealoc(element);
<add> }));
<add>
<ide>
<ide> it('should register/deregister a nested ngModel with parent form when entering or leaving DOM',
<ide> inject(function($compile, $rootScope) {
<ide> describe('NgModel animations', function() {
<ide> assertValidAnimation(animations[1], 'addClass', 'ng-pristine');
<ide> }));
<ide>
<add> it('should trigger an animation when untouched', inject(function($animate) {
<add> model.$setUntouched();
<add>
<add> var animations = findElementAnimations(input, $animate.queue);
<add> assertValidAnimation(animations[0], 'setClass', 'ng-untouched');
<add> expect(animations[0].args[2]).toBe('ng-touched');
<add> }));
<add>
<add> it('should trigger an animation when touched', inject(function($animate) {
<add> model.$setTouched();
<add>
<add> var animations = findElementAnimations(input, $animate.queue);
<add> assertValidAnimation(animations[0], 'setClass', 'ng-touched', 'ng-untouched');
<add> expect(animations[0].args[2]).toBe('ng-untouched');
<add> }));
<add>
<ide> it('should trigger custom errors as addClass/removeClass when invalid/valid', inject(function($animate) {
<ide> model.$setValidity('custom-error', false);
<ide> | 3 |
Ruby | Ruby | move methods to analytics_table function | 1ab86acb0fb13bb9f52189a2ca410c461ce084fc | <ide><path>Library/Homebrew/cmd/info.rb
<ide> def formulae_api_json(endpoint)
<ide> end
<ide>
<ide> def analytics_table(category, days, results, os_version: false, cask_install: false)
<add> valid_days = %w[30 90 365]
<add> if days.present?
<add> raise UsageError, "day must be one of #{valid_days.join(", ")}" unless valid_days.include?(days.to_s)
<add> end
<add>
<add> valid_categories = %w[install install-on-request cask-install build-error os-version]
<add> if category.present?
<add> unless valid_categories.include?(category.tr("_", "-"))
<add> raise UsageError, "category must be one of #{valid_categories.join(", ")}"
<add> end
<add> end
<add>
<ide> oh1 "#{category} (#{days} days)"
<ide> total_count = results.values.inject("+")
<ide> formatted_total_count = format_count(total_count)
<ide> def output_analytics(filter: nil)
<ide> end
<ide>
<ide> def output_formula_analytics(f)
<del> valid_days = %w[30 90 365]
<del> valid_categories = %w[install install-on-request build-error]
<ide> json = formulae_api_json("formula/#{f}.json")
<ide> return if json.blank? || json["analytics"].blank?
<ide>
<ide> def output_formula_analytics(f)
<ide> days = days.to_i
<ide> if full_analytics
<ide> if args.days.present?
<del> raise UsageError, "day must be one of #{valid_days.join(", ")}" unless valid_days.include?(args.days)
<ide> next if args.days&.to_i != days
<ide> end
<ide>
<ide> if args.category.present?
<del> unless valid_categories.include?(args.category)
<del> raise UsageError, "category must be one of #{valid_categories.join(", ")}"
<del> end
<ide> next if args.category.tr("-", "_") != category
<ide> end
<ide> | 1 |
Javascript | Javascript | use cache api in reducecomputed | b1fe599c68339d69a34ce78f5b4611a5b30c34ec | <ide><path>packages/ember-metal/lib/computed.js
<ide> Ember.computed = function(func) {
<ide> to return
<ide> @return {Object} the cached value
<ide> */
<del>Ember.cacheFor = function cacheFor(obj, key) {
<add>var cacheFor = Ember.cacheFor = function cacheFor(obj, key) {
<ide> var meta = obj[META_KEY],
<ide> cache = meta && meta.cache,
<ide> ret = cache && cache[key];
<ide> Ember.cacheFor = function cacheFor(obj, key) {
<ide> return ret;
<ide> };
<ide>
<add>cacheFor.set = function(cache, key, value) {
<add> if (value === undefined) {
<add> cache[key] = UNDEFINED;
<add> } else {
<add> cache[key] = value;
<add> }
<add>};
<add>
<add>cacheFor.get = function(cache, key) {
<add> var ret = cache[key];
<add> if (ret === UNDEFINED) { return undefined; }
<add> return ret;
<add>};
<add>
<add>cacheFor.remove = function(cache, key) {
<add> cache[key] = undefined;
<add>};
<add>
<ide> function getProperties(self, propertyNames) {
<ide> var ret = {};
<ide> for(var i = 0; i < propertyNames.length; i++) {
<ide><path>packages/ember-runtime/lib/computed/reduce_computed.js
<ide> var e_get = Ember.get,
<ide> set = Ember.set,
<ide> guidFor = Ember.guidFor,
<ide> metaFor = Ember.meta,
<add> cacheFor = Ember.cacheFor,
<add> cacheSet = cacheFor.set,
<add> cacheGet = cacheFor.get,
<add> cacheRemove = cacheFor.remove,
<ide> propertyWillChange = Ember.propertyWillChange,
<ide> propertyDidChange = Ember.propertyDidChange,
<ide> addBeforeObserver = Ember.addBeforeObserver,
<ide> function ReduceComputedPropertyInstanceMeta(context, propertyName, initialValue)
<ide>
<ide> ReduceComputedPropertyInstanceMeta.prototype = {
<ide> getValue: function () {
<del> if (this.propertyName in this.cache) {
<del> return this.cache[this.propertyName];
<add> var value = cacheGet(this.cache, this.propertyName);
<add> if (value !== undefined) {
<add> return value;
<ide> } else {
<ide> return this.initialValue;
<ide> }
<ide> ReduceComputedPropertyInstanceMeta.prototype = {
<ide> setValue: function(newValue, triggerObservers) {
<ide> // This lets sugars force a recomputation, handy for very simple
<ide> // implementations of eg max.
<del> if (newValue === this.cache[this.propertyName]) {
<add> if (newValue === cacheGet(this.cache, this.propertyName)) {
<ide> return;
<ide> }
<ide>
<ide> ReduceComputedPropertyInstanceMeta.prototype = {
<ide> }
<ide>
<ide> if (newValue === undefined) {
<del> delete this.cache[this.propertyName];
<add> cacheRemove(this.cache, this.propertyName);
<ide> } else {
<del> this.cache[this.propertyName] = newValue;
<add> cacheSet(this.cache, this.propertyName, newValue);
<ide> }
<ide>
<ide> if (triggerObservers) { | 2 |
Javascript | Javascript | improve modal docs describing ios only support | ca9f0adee22280f20ba96563be1553b7a975923f | <ide><path>Libraries/Modal/Modal.js
<ide> var RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
<ide> * Navigator instead of Modal. With a top-level Navigator, you have more control
<ide> * over how to present the modal scene over the rest of your app by using the
<ide> * configureScene property.
<add> *
<add> * This component is only available in iOS at this time.
<ide> */
<ide> class Modal extends React.Component {
<ide> render(): ?ReactElement { | 1 |
Java | Java | fix javadoc in mockrestserviceserver | ccb1153440e87c57f229f559f7754e7096a70b11 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
<ide> * // Use the hotel instance...
<ide> *
<ide> * mockServer.verify();
<add> * </pre>
<ide> *
<ide> * <p>To create an instance of this class, use {@link #createServer(RestTemplate)}
<ide> * and provide the {@code RestTemplate} to set up for the mock testing. | 1 |
Javascript | Javascript | remove unused function | c820054a20766645e2812f50b0eb763eec080118 | <ide><path>lib/Module.js
<ide> const sortByDebugId = (a, b) => {
<ide>
<ide> const getFrozenArray = set => Object.freeze(Array.from(set));
<ide>
<del>/* istanbul ignore next */
<del>const getDebugIdent = set => {
<del> set.sortWith(sortByDebugId);
<del> const chunks = set;
<del> const list = [];
<del> for(const chunk of chunks) {
<del> const debugId = chunk.debugId;
<del>
<del> if(typeof debugId !== "number") {
<del> return null;
<del> }
<del>
<del> list.push(debugId);
<del> }
<del>
<del> return list.join(",");
<del>};
<del>
<ide> class Module extends DependenciesBlock {
<ide>
<ide> constructor(type) { | 1 |
Python | Python | fix position biases + better tests | 268d4f2099f90bb62949988c3b78596242e1d753 | <ide><path>transformers/modeling_t5.py
<ide> def forward(self, hidden_states, attention_mask=None, position_bias=None,
<ide> position_bias=position_bias,
<ide> head_mask=head_mask)
<ide> hidden_states = self_attention_outputs[0]
<del> outputs = self_attention_outputs[1:]
<add> outputs = self_attention_outputs[1:] # Keep self-attention outputs and relative position weights
<ide>
<ide> if not self.is_decoder:
<ide> hidden_states = self.layer[1](hidden_states)
<ide> def forward(self, hidden_states, attention_mask=None, position_bias=None,
<ide> position_bias=encoder_decoder_position_bias,
<ide> head_mask=head_mask)
<ide> hidden_states = cross_attention_outputs[0]
<del> outputs = cross_attention_outputs[1:] + outputs
<add> outputs = outputs + cross_attention_outputs[1:] # Keep cross-attention outputs and relative position weights
<ide> hidden_states = self.layer[2](hidden_states)
<ide>
<ide> outputs = (hidden_states,) + outputs # add attentions if we output them
<del> return outputs
<add> return outputs # hidden-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
<ide>
<ide>
<ide> class T5PreTrainedModel(PreTrainedModel):
<ide> def forward(self,
<ide> encoder_attention_mask=encoder_extended_attention_mask,
<ide> encoder_decoder_position_bias=encoder_decoder_position_bias,
<ide> head_mask=head_mask[i])
<add> # layer_outputs is a tuple with:
<add> # hidden-states, (self-attention weights), (self-attention position bias), (cross-attention weights), (cross-attention position bias)
<ide> hidden_states = layer_outputs[0]
<ide> if i == 0:
<add> # We share the position biases between the layers - the first layer store them
<ide> position_bias = layer_outputs[2 if self.output_attentions else 1]
<ide> if self.is_decoder:
<ide> encoder_decoder_position_bias = layer_outputs[4 if self.output_attentions else 2]
<ide>
<ide> if self.output_attentions:
<del> all_attentions = all_attentions + (layer_outputs[1],)
<add> all_attentions = all_attentions + (layer_outputs[1],) # We keep only self-attention weights for now
<ide>
<ide> hidden_states = self.final_layer_norm(hidden_states)
<ide> layer_output = self.dropout(hidden_states)
<ide><path>transformers/tests/modeling_t5_test.py
<ide> class T5ModelTester(object):
<ide> def __init__(self,
<ide> parent,
<ide> batch_size=13,
<del> seq_length=7,
<add> encoder_seq_length=7,
<add> decoder_seq_length=9,
<ide> is_training=True,
<del> use_input_mask=True,
<add> use_attention_mask=True,
<ide> use_labels=True,
<ide> vocab_size=99,
<ide> n_positions=14,
<ide> def __init__(self,
<ide> ):
<ide> self.parent = parent
<ide> self.batch_size = batch_size
<del> self.seq_length = seq_length
<add> self.encoder_seq_length = encoder_seq_length
<add> self.decoder_seq_length = decoder_seq_length
<ide> self.is_training = is_training
<del> self.use_input_mask = use_input_mask
<add> self.use_attention_mask = use_attention_mask
<ide> self.use_labels = use_labels
<ide> self.vocab_size = vocab_size
<ide> self.n_positions = n_positions
<ide> def __init__(self,
<ide> self.scope = scope
<ide>
<ide> def prepare_config_and_inputs(self):
<del> input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
<add> encoder_input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
<add> decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
<ide>
<del> input_mask = None
<del> if self.use_input_mask:
<del> input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
<add> encoder_attention_mask = None
<add> decoder_attention_mask = None
<add> if self.use_attention_mask:
<add> encoder_attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
<add> decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
<ide>
<del> token_labels = None
<add> decoder_lm_labels = None
<ide> if self.use_labels:
<del> token_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
<add> decoder_lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
<ide>
<ide> config = T5Config(
<ide> vocab_size_or_config_json_file=self.vocab_size,
<ide> def prepare_config_and_inputs(self):
<ide> dropout_rate=self.dropout_rate,
<ide> initializer_factor=self.initializer_factor)
<ide>
<del> return (config, input_ids, input_mask, token_labels)
<add> return (config, encoder_input_ids, decoder_input_ids, encoder_attention_mask, decoder_attention_mask, decoder_lm_labels)
<ide>
<ide> def check_loss_output(self, result):
<ide> self.parent.assertListEqual(
<ide> list(result["loss"].size()),
<ide> [])
<ide>
<del> def create_and_check_t5_model(self, config, input_ids, input_mask, token_labels):
<add> def create_and_check_t5_model(self, config, encoder_input_ids, decoder_input_ids, encoder_attention_mask, decoder_attention_mask, decoder_lm_labels):
<ide> model = T5Model(config=config)
<ide> model.eval()
<del> encoder_output, decoder_output = model(encoder_input_ids=input_ids,
<del> decoder_input_ids=input_ids,
<del> decoder_attention_mask=input_mask)
<del> encoder_output, decoder_output = model(encoder_input_ids=input_ids,
<del> decoder_input_ids=input_ids)
<add> decoder_output, encoder_output = model(encoder_input_ids=encoder_input_ids,
<add> decoder_input_ids=decoder_input_ids,
<add> encoder_attention_mask=encoder_attention_mask,
<add> decoder_attention_mask=decoder_attention_mask)
<add> decoder_output, encoder_output = model(encoder_input_ids=encoder_input_ids,
<add> decoder_input_ids=decoder_input_ids)
<ide>
<ide> result = {
<ide> "encoder_output": encoder_output,
<ide> "decoder_output": decoder_output,
<ide> }
<ide> self.parent.assertListEqual(
<ide> list(result["encoder_output"].size()),
<del> [self.batch_size, self.seq_length, self.hidden_size])
<add> [self.batch_size, self.encoder_seq_length, self.hidden_size])
<ide> self.parent.assertListEqual(
<ide> list(result["decoder_output"].size()),
<del> [self.batch_size, self.seq_length, self.hidden_size])
<add> [self.batch_size, self.decoder_seq_length, self.hidden_size])
<ide>
<ide>
<del> def create_and_check_t5_with_lm_head(self, config, input_ids, input_mask, token_labels):
<add> def create_and_check_t5_with_lm_head(self, config, encoder_input_ids, decoder_input_ids, encoder_attention_mask, decoder_attention_mask, decoder_lm_labels):
<ide> model = T5WithLMHeadModel(config=config)
<ide> model.eval()
<del> outputs = model(encoder_input_ids=input_ids, decoder_input_ids=input_ids,
<del> decoder_attention_mask=input_mask, decoder_lm_labels=token_labels)
<add> outputs = model(encoder_input_ids=encoder_input_ids, decoder_input_ids=decoder_input_ids,
<add> decoder_attention_mask=decoder_attention_mask, decoder_lm_labels=decoder_lm_labels)
<ide> loss, prediction_scores = outputs[0], outputs[1]
<ide> result = {
<ide> "loss": loss,
<ide> "prediction_scores": prediction_scores,
<ide> }
<ide> self.parent.assertListEqual(
<ide> list(result["prediction_scores"].size()),
<del> [self.batch_size, self.seq_length, self.vocab_size])
<add> [self.batch_size, self.decoder_seq_length, self.vocab_size])
<ide> self.check_loss_output(result)
<ide>
<ide> def prepare_config_and_inputs_for_common(self):
<ide> config_and_inputs = self.prepare_config_and_inputs()
<del> (config, input_ids, input_mask, token_labels) = config_and_inputs
<del> inputs_dict = {'encoder_input_ids': input_ids,
<del> 'decoder_input_ids': input_ids,
<del> 'decoder_attention_mask': input_mask}
<add> (config, encoder_input_ids, decoder_input_ids, encoder_attention_mask,
<add> decoder_attention_mask, decoder_lm_labels) = config_and_inputs
<add> inputs_dict = {'encoder_input_ids': encoder_input_ids,
<add> 'decoder_input_ids': decoder_input_ids,
<add> 'decoder_attention_mask': decoder_attention_mask,
<add> 'encoder_attention_mask': encoder_attention_mask}
<ide> return config, inputs_dict
<ide>
<ide> def setUp(self): | 2 |
Text | Text | wrap the tip from at 80 chars [ci skip] | 0e9a7059664eb9dee8e3afae60d26ff858d0d84b | <ide><path>guides/source/active_record_migrations.md
<ide> change_column_default :products, :approved, false
<ide> This sets `:name` field on products to a `NOT NULL` column and the default
<ide> value of the `:approved` field to false.
<ide>
<del>TIP: Unlike `change_column` (and `change_column_default`), `change_column_null` is reversible.
<add>TIP: Unlike `change_column` (and `change_column_default`), `change_column_null`
<add>is reversible.
<ide>
<ide> ### Column Modifiers
<ide> | 1 |
Python | Python | use dict instead of if/else logic | 0e79aba40d2497218736448ced708fcf4f8943b3 | <ide><path>flask/sessions.py
<ide> class TaggedJSONSerializer(object):
<ide> def dumps(self, value):
<ide> return json.dumps(_tag(value), separators=(',', ':'))
<ide>
<add> LOADS_MAP = {
<add> ' t': tuple,
<add> ' u': uuid.UUID,
<add> ' b': b64decode,
<add> ' m': Markup,
<add> ' d': parse_date,
<add> }
<add>
<ide> def loads(self, value):
<ide> def object_hook(obj):
<ide> if len(obj) != 1:
<ide> return obj
<ide> the_key, the_value = next(iteritems(obj))
<del> if the_key == ' t':
<del> return tuple(the_value)
<del> elif the_key == ' u':
<del> return uuid.UUID(the_value)
<del> elif the_key == ' b':
<del> return b64decode(the_value)
<del> elif the_key == ' m':
<del> return Markup(the_value)
<del> elif the_key == ' d':
<del> return parse_date(the_value)
<add> # Check the key for a corresponding function
<add> return_function = self.LOADS_MAP.get(the_key)
<add> if return_function:
<add> # Pass the value to the function
<add> return return_function(the_value)
<add> # Didn't find a function for this object
<ide> return obj
<ide> return json.loads(value, object_hook=object_hook)
<ide> | 1 |
Ruby | Ruby | move assertion setup into formula_assertions.rb | 4bdfb27d9fb4958a5845e598fd7b9c7cefab94e7 | <ide><path>Library/Homebrew/cmd/test.rb
<ide> require "extend/ENV"
<ide> require "timeout"
<ide> require "debrew"
<add>require "formula_assertions"
<ide>
<ide> module Homebrew
<ide> TEST_TIMEOUT_SECONDS = 5*60
<ide>
<del> if defined?(Gem)
<del> begin
<del> gem "minitest", "< 5.0.0"
<del> rescue Gem::LoadError
<del> require "test/unit/assertions"
<del> else
<del> require "minitest/unit"
<del> require "test/unit/assertions"
<del> end
<del> else
<del> require "test/unit/assertions"
<del> end
<del>
<del> if defined?(MiniTest::Assertion)
<del> FailedAssertion = MiniTest::Assertion
<del> elsif defined?(Minitest::Assertion)
<del> FailedAssertion = Minitest::Assertion
<del> else
<del> FailedAssertion = Test::Unit::AssertionFailedError
<del> end
<del>
<del> require "formula_assertions"
<del>
<ide> def test
<ide> raise FormulaUnspecifiedError if ARGV.named.empty?
<ide>
<ide> def test
<ide>
<ide> puts "Testing #{f.name}"
<ide>
<del> f.extend(Test::Unit::Assertions)
<del> f.extend(Homebrew::Assertions)
<add> f.extend(Assertions)
<ide> f.extend(Debrew::Formula) if ARGV.debug?
<ide>
<ide> env = ENV.to_hash
<ide> def test
<ide> Timeout::timeout TEST_TIMEOUT_SECONDS do
<ide> raise if f.run_test == false
<ide> end
<del> rescue FailedAssertion => e
<add> rescue Assertions::FailedAssertion => e
<ide> ofail "#{f.name}: failed"
<ide> puts e.message
<ide> rescue Exception => e
<ide><path>Library/Homebrew/formula_assertions.rb
<del>require 'test/unit/assertions'
<del>
<ide> module Homebrew
<ide> module Assertions
<add> if defined?(Gem)
<add> begin
<add> gem "minitest", "< 5.0.0"
<add> rescue Gem::LoadError
<add> require "test/unit/assertions"
<add> else
<add> require "minitest/unit"
<add> require "test/unit/assertions"
<add> end
<add> else
<add> require "test/unit/assertions"
<add> end
<add>
<add> if defined?(MiniTest::Assertion)
<add> FailedAssertion = MiniTest::Assertion
<add> elsif defined?(Minitest::Assertion)
<add> FailedAssertion = Minitest::Assertion
<add> else
<add> FailedAssertion = Test::Unit::AssertionFailedError
<add> end
<add>
<ide> include Test::Unit::Assertions
<ide>
<ide> # Returns the output of running cmd, and asserts the exit status | 2 |
Ruby | Ruby | fix failure with minitest 5.0.7 | b77781c012ebb60bfeee114aef6597ab8d3d3016 | <ide><path>actionview/test/template/url_helper_test.rb
<ide> # encoding: utf-8
<ide> require 'abstract_unit'
<add>require 'minitest/mock'
<ide>
<ide> class UrlHelperTest < ActiveSupport::TestCase
<ide> | 1 |
Javascript | Javascript | prevent default on all key navigations | 5b480a85cb17b7455c6896e4d9b2f28abd080fc8 | <ide><path>src/devtools/views/Components/Tree.js
<ide> export default function Tree(props: Props) {
<ide> // eslint-disable-next-line default-case
<ide> switch (event.key) {
<ide> case 'ArrowDown':
<del> selectNextElementInTree();
<ide> event.preventDefault();
<add> selectNextElementInTree();
<ide> break;
<ide> case 'ArrowLeft':
<add> event.preventDefault();
<ide> element =
<ide> selectedElementID !== null
<ide> ? store.getElementByID(selectedElementID)
<ide> export default function Tree(props: Props) {
<ide> }
<ide> break;
<ide> case 'ArrowRight':
<add> event.preventDefault();
<ide> element =
<ide> selectedElementID !== null
<ide> ? store.getElementByID(selectedElementID)
<ide> export default function Tree(props: Props) {
<ide> } else {
<ide> selectNextElementInTree();
<ide> }
<del> event.preventDefault();
<ide> break;
<ide> case 'ArrowUp':
<del> selectPreviousElementInTree();
<ide> event.preventDefault();
<add> selectPreviousElementInTree();
<ide> break;
<ide> }
<ide> }; | 1 |
PHP | PHP | fix empty string check | 0e44e08cc3628e463d8ec654c081022ba70f93fb | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function authCheck(EventInterface $event): ?Response
<ide> /** @var \Cake\Controller\Controller $controller */
<ide> $controller = $event->getSubject();
<ide>
<del> $action = $controller->getRequest()->getParam('action', '');
<del> if (!$controller->isAction($action)) {
<add> $action = $controller->getRequest()->getParam('action');
<add> if ($action !== null && !$controller->isAction($action)) {
<ide> return null;
<ide> }
<ide> | 1 |
Ruby | Ruby | add shebang tests | 3955e7e13b980ad4f8d38ffc3c0253d86204902e | <ide><path>Library/Homebrew/test/language/perl/shebang_spec.rb
<add># frozen_string_literal: true
<add>
<add>require "language/perl"
<add>require "utils/shebang"
<add>
<add>describe Language::Perl::Shebang do
<add> let(:file) { Tempfile.new("perl-shebang") }
<add> let(:perl_f) do
<add> formula "perl" do
<add> url "https://brew.sh/perl-1.0.tgz"
<add> end
<add> end
<add> let(:f) do
<add> formula "foo" do
<add> url "https://brew.sh/foo-1.0.tgz"
<add>
<add> uses_from_macos "perl"
<add> end
<add> end
<add>
<add> before do
<add> file.write <<~EOS
<add> #!/usr/bin/env perl
<add> a
<add> b
<add> c
<add> EOS
<add> file.flush
<add> end
<add>
<add> after { file.unlink }
<add>
<add> describe "#detected_perl_shebang" do
<add> it "can be used to replace Perl shebangs" do
<add> allow(Formulary).to receive(:factory).with(perl_f.name).and_return(perl_f)
<add> Utils::Shebang.rewrite_shebang described_class.detected_perl_shebang(f), file
<add>
<add> expected_shebang = if OS.mac?
<add> "/usr/bin/perl"
<add> else
<add> HOMEBREW_PREFIX/"opt/perl/bin/perl"
<add> end
<add>
<add> expect(File.read(file)).to eq <<~EOS
<add> #!#{expected_shebang}
<add> a
<add> b
<add> c
<add> EOS
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/language/python_spec.rb
<ide>
<ide> require "language/python"
<ide> require "resource"
<add>require "utils/shebang"
<ide>
<ide> describe Language::Python, :needs_python do
<ide> describe "#major_minor_version" do
<ide> end
<ide> end
<ide>
<add>describe Language::Python::Shebang do
<add> let(:file) { Tempfile.new("python-shebang") }
<add> let(:python_f) do
<add> formula "python" do
<add> url "https://brew.sh/python-1.0.tgz"
<add> end
<add> end
<add> let(:f) do
<add> formula "foo" do
<add> url "https://brew.sh/foo-1.0.tgz"
<add>
<add> depends_on "python"
<add> end
<add> end
<add>
<add> before do
<add> file.write <<~EOS
<add> #!/usr/bin/env python3
<add> a
<add> b
<add> c
<add> EOS
<add> file.flush
<add> end
<add>
<add> after { file.unlink }
<add>
<add> describe "#detected_python_shebang" do
<add> it "can be used to replace Python shebangs" do
<add> expect(Formulary).to receive(:factory).with(python_f.name).and_return(python_f)
<add> Utils::Shebang.rewrite_shebang described_class.detected_python_shebang(f), file
<add>
<add> expect(File.read(file)).to eq <<~EOS
<add> #!#{HOMEBREW_PREFIX}/opt/python/bin/python3
<add> a
<add> b
<add> c
<add> EOS
<add> end
<add> end
<add>end
<add>
<ide> describe Language::Python::Virtualenv::Virtualenv do
<ide> subject { described_class.new(formula, dir, "python") }
<ide> | 2 |
Text | Text | add more valid triples to the test | 67450094902c69ca53bd2d9b340056abe5f3b3f8 | <ide><path>curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-9-special-pythagorean-triplet.english.md
<ide> There exists exactly one Pythagorean triplet for which <var>a</var> + <var>b</va
<ide> ```yml
<ide> tests:
<ide> - text: <code>specialPythagoreanTriplet(1000)</code> should return 31875000.
<del> testString: assert.strictEqual(specialPythagoreanTriplet(1000), 31875000, '<code>specialPythagoreanTriplet(1000)</code> should return 31875000.');
<add> testString: assert.strictEqual(specialPythagoreanTriplet(1000), 31875000);
<ide> - text: <code>specialPythagoreanTriplet(24)</code> should return 480.
<del> testString: assert.strictEqual(specialPythagoreanTriplet(24), 480, '<code>specialPythagoreanTriplet(24)</code> should return 480.');
<del> - text: <code>specialPythagoreanTriplet(120)</code> should return 49920.
<del> testString: assert.strictEqual(specialPythagoreanTriplet(120), 49920, '<code>specialPythagoreanTriplet(120)</code> should return 49920.');
<add> testString: assert.strictEqual(specialPythagoreanTriplet(24), 480);
<add> - text: <code>specialPythagoreanTriplet(120)</code> should return 49920, 55080 or 60000
<add> testString: assert([49920, 55080, 60000].includes(specialPythagoreanTriplet(120)));
<ide>
<ide> ```
<ide> | 1 |
Javascript | Javascript | resolve default onrecoverableerror at root init | efd8f6442d1aa7c4566fe812cba03e7e83aaccc3 | <ide><path>packages/react-art/src/ReactARTHostConfig.js
<ide> export function preparePortalMount(portalInstance: any): void {
<ide> export function detachDeletedInstance(node: Instance): void {
<ide> // noop
<ide> }
<del>
<del>export function logRecoverableError(error) {
<del> // noop
<del>}
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> export function getCurrentEventPriority(): * {
<ide> return getEventPriority(currentEvent.type);
<ide> }
<ide>
<del>/* global reportError */
<del>export const logRecoverableError =
<del> typeof reportError === 'function'
<del> ? // In modern browsers, reportError will dispatch an error event,
<del> // emulating an uncaught JavaScript error.
<del> reportError
<del> : (error: mixed) => {
<del> // In older browsers and test environments, fallback to console.error.
<del> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<del> console.error(error);
<del> };
<del>
<ide> export const isPrimaryRenderer = true;
<ide> export const warnsIfNotActing = true;
<ide> // This initialization code may run even on server environments
<ide><path>packages/react-dom/src/client/ReactDOMLegacy.js
<ide> function getReactRootElementInContainer(container: any) {
<ide> }
<ide> }
<ide>
<add>function noopOnRecoverableError() {
<add> // This isn't reachable because onRecoverableError isn't called in the
<add> // legacy API.
<add>}
<add>
<ide> function legacyCreateRootFromDOMContainer(
<ide> container: Container,
<ide> forceHydrate: boolean,
<ide> function legacyCreateRootFromDOMContainer(
<ide> false, // isStrictMode
<ide> false, // concurrentUpdatesByDefaultOverride,
<ide> '', // identifierPrefix
<del> null,
<add> noopOnRecoverableError,
<ide> );
<ide> markContainerAsRoot(root.current, container);
<ide>
<ide><path>packages/react-dom/src/client/ReactDOMRoot.js
<ide> import {
<ide> import {ConcurrentRoot} from 'react-reconciler/src/ReactRootTags';
<ide> import {allowConcurrentByDefault} from 'shared/ReactFeatureFlags';
<ide>
<add>/* global reportError */
<add>const defaultOnRecoverableError =
<add> typeof reportError === 'function'
<add> ? // In modern browsers, reportError will dispatch an error event,
<add> // emulating an uncaught JavaScript error.
<add> reportError
<add> : (error: mixed) => {
<add> // In older browsers and test environments, fallback to console.error.
<add> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<add> console.error(error);
<add> };
<add>
<ide> function ReactDOMRoot(internalRoot: FiberRoot) {
<ide> this._internalRoot = internalRoot;
<ide> }
<ide> export function createRoot(
<ide> let isStrictMode = false;
<ide> let concurrentUpdatesByDefaultOverride = false;
<ide> let identifierPrefix = '';
<del> let onRecoverableError = null;
<add> let onRecoverableError = defaultOnRecoverableError;
<ide> if (options !== null && options !== undefined) {
<ide> if (__DEV__) {
<ide> if ((options: any).hydrate) {
<ide> export function hydrateRoot(
<ide> let isStrictMode = false;
<ide> let concurrentUpdatesByDefaultOverride = false;
<ide> let identifierPrefix = '';
<del> let onRecoverableError = null;
<add> let onRecoverableError = defaultOnRecoverableError;
<ide> if (options !== null && options !== undefined) {
<ide> if (options.unstable_strictMode === true) {
<ide> isStrictMode = true;
<ide><path>packages/react-native-renderer/src/ReactFabric.js
<ide> function sendAccessibilityEvent(handle: any, eventType: string) {
<ide> }
<ide> }
<ide>
<add>function onRecoverableError(error) {
<add> // TODO: Expose onRecoverableError option to userspace
<add> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<add> console.error(error);
<add>}
<add>
<ide> function render(
<ide> element: Element<ElementType>,
<ide> containerTag: number,
<ide> function render(
<ide> false,
<ide> null,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide> roots.set(containerTag, root);
<ide> }
<ide><path>packages/react-native-renderer/src/ReactFabricHostConfig.js
<ide> export function preparePortalMount(portalInstance: Instance): void {
<ide> export function detachDeletedInstance(node: Instance): void {
<ide> // noop
<ide> }
<del>
<del>export function logRecoverableError(error: mixed): void {
<del> // noop
<del>}
<ide><path>packages/react-native-renderer/src/ReactNativeHostConfig.js
<ide> export function preparePortalMount(portalInstance: Instance): void {
<ide> export function detachDeletedInstance(node: Instance): void {
<ide> // noop
<ide> }
<del>
<del>export function logRecoverableError(error: mixed): void {
<del> // noop
<del>}
<ide><path>packages/react-native-renderer/src/ReactNativeRenderer.js
<ide> function sendAccessibilityEvent(handle: any, eventType: string) {
<ide> }
<ide> }
<ide>
<add>function onRecoverableError(error) {
<add> // TODO: Expose onRecoverableError option to userspace
<add> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<add> console.error(error);
<add>}
<add>
<ide> function render(
<ide> element: Element<ElementType>,
<ide> containerTag: number,
<ide> function render(
<ide> false,
<ide> null,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide> roots.set(containerTag, root);
<ide> }
<ide><path>packages/react-noop-renderer/src/createReactNoop.js
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> return NoopRenderer.flushSync(fn);
<ide> }
<ide>
<add> function onRecoverableError(error) {
<add> // TODO: Turn this on once tests are fixed
<add> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<add> // console.error(error);
<add> }
<add>
<ide> let idCounter = 0;
<ide>
<ide> const ReactNoop = {
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> null,
<ide> false,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide> roots.set(rootID, root);
<ide> }
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> null,
<ide> false,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide> return {
<ide> _Scheduler: Scheduler,
<ide> function createReactNoop(reconciler: Function, useMutation: boolean) {
<ide> null,
<ide> false,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide> return {
<ide> _Scheduler: Scheduler,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.new.js
<ide> export function createContainer(
<ide> isStrictMode: boolean,
<ide> concurrentUpdatesByDefaultOverride: null | boolean,
<ide> identifierPrefix: string,
<del> onRecoverableError: null | ((error: mixed) => void),
<add> onRecoverableError: (error: mixed) => void,
<ide> ): OpaqueRoot {
<ide> return createFiberRoot(
<ide> containerInfo,
<ide><path>packages/react-reconciler/src/ReactFiberReconciler.old.js
<ide> export function createContainer(
<ide> isStrictMode: boolean,
<ide> concurrentUpdatesByDefaultOverride: null | boolean,
<ide> identifierPrefix: string,
<del> onRecoverableError: null | ((error: mixed) => void),
<add> onRecoverableError: (error: mixed) => void,
<ide> ): OpaqueRoot {
<ide> return createFiberRoot(
<ide> containerInfo,
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js
<ide> import {
<ide> supportsMicrotasks,
<ide> errorHydratingContainer,
<ide> scheduleMicrotask,
<del> logRecoverableError,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> function commitRootImpl(
<ide> if (recoverableErrors !== null) {
<ide> // There were errors during this render, but recovered from them without
<ide> // needing to surface it to the UI. We log them here.
<add> const onRecoverableError = root.onRecoverableError;
<ide> for (let i = 0; i < recoverableErrors.length; i++) {
<ide> const recoverableError = recoverableErrors[i];
<del> const onRecoverableError = root.onRecoverableError;
<del> if (onRecoverableError !== null) {
<del> onRecoverableError(recoverableError);
<del> } else {
<del> // No user-provided onRecoverableError. Use the default behavior
<del> // provided by the renderer's host config.
<del> logRecoverableError(recoverableError);
<del> }
<add> onRecoverableError(recoverableError);
<ide> }
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> import {
<ide> supportsMicrotasks,
<ide> errorHydratingContainer,
<ide> scheduleMicrotask,
<del> logRecoverableError,
<ide> } from './ReactFiberHostConfig';
<ide>
<ide> import {
<ide> function commitRootImpl(
<ide> if (recoverableErrors !== null) {
<ide> // There were errors during this render, but recovered from them without
<ide> // needing to surface it to the UI. We log them here.
<add> const onRecoverableError = root.onRecoverableError;
<ide> for (let i = 0; i < recoverableErrors.length; i++) {
<ide> const recoverableError = recoverableErrors[i];
<del> const onRecoverableError = root.onRecoverableError;
<del> if (onRecoverableError !== null) {
<del> onRecoverableError(recoverableError);
<del> } else {
<del> // No user-provided onRecoverableError. Use the default behavior
<del> // provided by the renderer's host config.
<del> logRecoverableError(recoverableError);
<del> }
<add> onRecoverableError(recoverableError);
<ide> }
<ide> }
<ide>
<ide><path>packages/react-reconciler/src/ReactInternalTypes.js
<ide> type BaseFiberRootProperties = {|
<ide> // a reference to.
<ide> identifierPrefix: string,
<ide>
<del> onRecoverableError: null | ((error: mixed) => void),
<add> onRecoverableError: (error: mixed) => void,
<ide> |};
<ide>
<ide> // The following attributes are only used by DevTools and are only present in DEV builds.
<ide><path>packages/react-reconciler/src/forks/ReactFiberHostConfig.custom.js
<ide> export const prepareScopeUpdate = $$$hostConfig.preparePortalMount;
<ide> export const getInstanceFromScope = $$$hostConfig.getInstanceFromScope;
<ide> export const getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority;
<ide> export const detachDeletedInstance = $$$hostConfig.detachDeletedInstance;
<del>export const logRecoverableError = $$$hostConfig.logRecoverableError;
<ide>
<ide> // -------------------
<ide> // Microtasks
<ide><path>packages/react-test-renderer/src/ReactTestRenderer.js
<ide> function propsMatch(props: Object, filter: Object): boolean {
<ide> return true;
<ide> }
<ide>
<add>function onRecoverableError(error) {
<add> // TODO: Expose onRecoverableError option to userspace
<add> // eslint-disable-next-line react-internal/no-production-logging, react-internal/warning-args
<add> console.error(error);
<add>}
<add>
<ide> function create(element: React$Element<any>, options: TestRendererOptions) {
<ide> let createNodeMock = defaultTestOptions.createNodeMock;
<ide> let isConcurrent = false;
<ide> function create(element: React$Element<any>, options: TestRendererOptions) {
<ide> isStrictMode,
<ide> concurrentUpdatesByDefault,
<ide> '',
<del> null,
<add> onRecoverableError,
<ide> );
<ide>
<ide> if (root == null) { | 16 |
Ruby | Ruby | check dom equality | 3a62e0e868c8bf8e2c9312b4610ee057d514f038 | <ide><path>actionpack/test/controller/html-scanner/sanitizer_test.rb
<ide> def test_should_sanitize_div_style_expression
<ide> end
<ide>
<ide> def test_should_sanitize_img_vbscript
<del> assert_sanitized %(<img src='vbscript:msgbox("XSS")' />), '<img />'
<add> assert_sanitized %(<img src='vbscript:msgbox("XSS")' />), '<img />'
<ide> end
<ide>
<ide> protected
<ide> def assert_sanitized(input, expected = nil)
<ide> @sanitizer ||= HTML::WhiteListSanitizer.new
<del> assert_equal expected || input, @sanitizer.sanitize(input)
<add> if input
<add> assert_dom_equal expected || input, @sanitizer.sanitize(input)
<add> else
<add> assert_nil @sanitizer.sanitize(input)
<add> end
<ide> end
<del>
<add>
<ide> def sanitize_css(input)
<ide> (@sanitizer ||= HTML::WhiteListSanitizer.new).sanitize_css(input)
<ide> end | 1 |
Javascript | Javascript | change var to let | 615ec972de176f7d14124e96f57595c2e3c05ad1 | <ide><path>lib/buffer.js
<ide> Buffer.from = function from(value, encodingOrOffset, length) {
<ide> // Refs: https://esdiscuss.org/topic/isconstructor#content-11
<ide> const of = (...items) => {
<ide> const newObj = createUnsafeBuffer(items.length);
<del> for (var k = 0; k < items.length; k++)
<add> for (let k = 0; k < items.length; k++)
<ide> newObj[k] = items[k];
<ide> return newObj;
<ide> };
<ide> function fromString(string, encoding) {
<ide> function fromArrayLike(obj) {
<ide> const length = obj.length;
<ide> const b = allocate(length);
<del> for (var i = 0; i < length; i++)
<add> for (let i = 0; i < length; i++)
<ide> b[i] = obj[i];
<ide> return b;
<ide> }
<ide> Buffer.prototype.write = function write(string, offset, length, encoding) {
<ide> Buffer.prototype.toJSON = function toJSON() {
<ide> if (this.length > 0) {
<ide> const data = new Array(this.length);
<del> for (var i = 0; i < this.length; ++i)
<add> for (let i = 0; i < this.length; ++i)
<ide> data[i] = this[i];
<ide> return { type: 'Buffer', data };
<ide> }
<ide> Buffer.prototype.swap16 = function swap16() {
<ide> if (len % 2 !== 0)
<ide> throw new ERR_INVALID_BUFFER_SIZE('16-bits');
<ide> if (len < 128) {
<del> for (var i = 0; i < len; i += 2)
<add> for (let i = 0; i < len; i += 2)
<ide> swap(this, i, i + 1);
<ide> return this;
<ide> }
<ide> Buffer.prototype.swap32 = function swap32() {
<ide> if (len % 4 !== 0)
<ide> throw new ERR_INVALID_BUFFER_SIZE('32-bits');
<ide> if (len < 192) {
<del> for (var i = 0; i < len; i += 4) {
<add> for (let i = 0; i < len; i += 4) {
<ide> swap(this, i, i + 3);
<ide> swap(this, i + 1, i + 2);
<ide> }
<ide> Buffer.prototype.swap64 = function swap64() {
<ide> if (len % 8 !== 0)
<ide> throw new ERR_INVALID_BUFFER_SIZE('64-bits');
<ide> if (len < 192) {
<del> for (var i = 0; i < len; i += 8) {
<add> for (let i = 0; i < len; i += 8) {
<ide> swap(this, i, i + 7);
<ide> swap(this, i + 1, i + 6);
<ide> swap(this, i + 2, i + 5); | 1 |
Javascript | Javascript | add tests for querystring-relative urls | 17716d149913f03f8010ed835c0dd9d411130b99 | <ide><path>test/integration/client-navigation/pages/nav/query-only.js
<add>import Link from 'next/link'
<add>import { useRouter } from 'next/router'
<add>
<add>export async function getServerSideProps({ query: { prop = '' } }) {
<add> return { props: { prop } }
<add>}
<add>
<add>export default function Page({ prop }) {
<add> const router = useRouter()
<add> return (
<add> <>
<add> <div id="prop">{prop}</div>
<add> <Link href="?prop=foo">
<add> <a id="link">Click me</a>
<add> </Link>
<add> <button id="router-push" onClick={() => router.push('?prop=bar')}>
<add> Push me
<add> </button>
<add> <button id="router-replace" onClick={() => router.replace('?prop=baz')}>
<add> Push me
<add> </button>
<add> </>
<add> )
<add>}
<ide><path>test/integration/client-navigation/test/index.test.js
<ide> describe('Client Navigation', () => {
<ide> })
<ide> })
<ide>
<add> describe('with querystring relative urls', () => {
<add> it('should work with Link', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/query-only')
<add> try {
<add> await browser.elementByCss('#link').click()
<add>
<add> await check(() => browser.waitForElementByCss('#prop').text(), 'foo')
<add> } finally {
<add> await browser.close()
<add> }
<add> })
<add>
<add> it('should work with router.push', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/query-only')
<add> try {
<add> await browser.elementByCss('#router-push').click()
<add>
<add> await check(() => browser.waitForElementByCss('#prop').text(), 'bar')
<add> } finally {
<add> await browser.close()
<add> }
<add> })
<add>
<add> it('should work with router.replace', async () => {
<add> const browser = await webdriver(context.appPort, '/nav/query-only')
<add> try {
<add> await browser.elementByCss('#router-replace').click()
<add>
<add> await check(() => browser.waitForElementByCss('#prop').text(), 'baz')
<add> } finally {
<add> await browser.close()
<add> }
<add> })
<add> })
<add>
<ide> describe('with getInitialProp redirect', () => {
<ide> it('should redirect the page via client side', async () => {
<ide> const browser = await webdriver(context.appPort, '/nav') | 2 |
Javascript | Javascript | destroy components when changed on re-render | ac846c375b44089c6e0d9d6c3cb953ced5c30d7d | <ide><path>packages/ember-htmlbars/lib/keywords/component.js
<ide> export default {
<ide> },
<ide>
<ide> render(morph, ...rest) {
<add> if (morph.state.manager) {
<add> morph.state.manager.destroy();
<add> }
<add>
<ide> // Force the component hook to treat this as a first-time render,
<ide> // because normal components (`<foo-bar>`) cannot change at runtime,
<ide> // but the `{{component}}` helper can.
<ide><path>packages/ember-htmlbars/lib/keywords/view.js
<ide> export default {
<ide> options.createOptions._targetObject = node.state.targetObject;
<ide> }
<ide>
<add> if (state.manager) {
<add> state.manager.destroy();
<add> state.manager = null;
<add> }
<add>
<ide> var nodeManager = ViewNodeManager.create(node, env, hash, options, parentView, null, scope, template);
<ide> state.manager = nodeManager;
<ide>
<ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> ComponentNodeManager.prototype.rerender = function(_env, attrs, visitor) {
<ide> }, this);
<ide> };
<ide>
<add>ComponentNodeManager.prototype.destroy = function() {
<add> let component = this.component;
<add>
<add> // Clear component's render node. Normally this gets cleared
<add> // during view destruction, but in this case we're re-assigning the
<add> // node to a different view and it will get cleaned up automatically.
<add> component._renderNode = null;
<add> component.destroy();
<add>};
<ide>
<ide> export function createComponent(_component, isAngleBracket, _props, renderNode, env, attrs = {}) {
<ide> let props = assign({}, _props);
<ide> export function createComponent(_component, isAngleBracket, _props, renderNode,
<ide> }
<ide>
<ide> component._renderNode = renderNode;
<del> if (renderNode.emberView && renderNode.emberView !== component) {
<del> throw new Error('Need to clean up this view before blindly reassigning.');
<del> }
<ide> renderNode.emberView = component;
<ide> return component;
<ide> }
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js
<ide> ViewNodeManager.prototype.rerender = function(env, attrs, visitor) {
<ide> }, this);
<ide> };
<ide>
<add>ViewNodeManager.prototype.destroy = function() {
<add> this.component.destroy();
<add>};
<add>
<ide> function getTemplate(componentOrView) {
<ide> return componentOrView.isComponent ? get(componentOrView, '_template') : get(componentOrView, 'template');
<ide> }
<ide> export function createOrUpdateComponent(component, options, createOptions, rende
<ide>
<ide> component._renderNode = renderNode;
<ide>
<del> if (renderNode.emberView && renderNode.emberView !== component) {
<del> throw new Error('Need to clean up this view before blindly reassigning.');
<del> }
<ide> renderNode.emberView = component;
<ide> return component;
<ide> } | 4 |
Javascript | Javascript | use jpx and jpeg in error messages | e3a3ec6f2e3b57bd310ed8cb0d663946dae9b2d2 | <ide><path>src/jpx.js
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> r = 0;
<ide> }
<del> error('Out of packets');
<add> error('JPX error: Out of packets');
<ide> };
<ide> }
<ide> function ResolutionLayerComponentPositionIterator(context) {
<ide> var JpxImage = (function JpxImageClosure() {
<ide> }
<ide> l = 0;
<ide> }
<del> error('Out of packets');
<add> error('JPX error: Out of packets');
<ide> };
<ide> }
<ide> function buildPackets(context) {
<ide> var JpxImage = (function JpxImageClosure() {
<ide> new ResolutionLayerComponentPositionIterator(context);
<ide> break;
<ide> default:
<del> error('Unsupported progression order ' + progressionOrder);
<add> error('JPX error: Unsupported progression order ' + progressionOrder);
<ide> }
<ide> }
<ide> function parseTilePackets(context, data, offset, dataLength) {
<ide> var JpxImage = (function JpxImageClosure() {
<ide> if (lbox == 0)
<ide> lbox = length - position + headerSize;
<ide> if (lbox < headerSize)
<del> error('Invalid box field size');
<add> error('JPX error: Invalid box field size');
<ide> var dataLength = lbox - headerSize;
<ide> var jumpDataLength = true;
<ide> switch (tbox) {
<ide> var JpxImage = (function JpxImageClosure() {
<ide> scalarExpounded = true;
<ide> break;
<ide> default:
<del> error('Invalid SQcd value ' + sqcd);
<add> error('JPX error: Invalid SQcd value ' + sqcd);
<ide> }
<ide> qcd.noQuantization = spqcdSize == 8;
<ide> qcd.scalarExpounded = scalarExpounded;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> scalarExpounded = true;
<ide> break;
<ide> default:
<del> error('Invalid SQcd value ' + sqcd);
<add> error('JPX error: Invalid SQcd value ' + sqcd);
<ide> }
<ide> qcc.noQuantization = spqcdSize == 8;
<ide> qcc.scalarExpounded = scalarExpounded;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> cod.terminationOnEachCodingPass ||
<ide> cod.verticalyStripe || cod.predictableTermination ||
<ide> cod.segmentationSymbolUsed)
<del> error('Unsupported COD options: ' + uneval(cod));
<add> error('JPX error: Unsupported COD options: ' + uneval(cod));
<ide>
<ide> if (context.mainHeader)
<ide> context.COD = cod;
<ide> var JpxImage = (function JpxImageClosure() {
<ide> // skipping content
<ide> break;
<ide> default:
<del> error('Unknown codestream code: ' + code.toString(16));
<add> error('JPX error: Unknown codestream code: ' + code.toString(16));
<ide> }
<ide> position += length;
<ide> }
<ide><path>src/stream.js
<ide> var JpegStream = (function JpegStreamClosure() {
<ide> this.buffer = data;
<ide> this.bufferLength = data.length;
<ide> } catch (e) {
<del> error(e);
<add> error('JPEG error: ' + e);
<ide> }
<ide> };
<ide> JpegStream.prototype.getIR = function jpegStreamGetIR() {
<ide><path>src/worker.js
<ide> var workerConsole = {
<ide> action: 'console_error',
<ide> data: args
<ide> });
<add> throw 'pdf.js execution error';
<ide> },
<ide>
<ide> time: function time(name) { | 3 |
Javascript | Javascript | add some detail about `$onchanges` | f63c46406f4fe98394e1cfb00d57a535c77cffdc | <ide><path>src/ng/compile.js
<ide> * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
<ide> * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
<ide> * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
<del> * component such as cloning the bound value to prevent accidental mutation of the outer value.
<add> * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
<add> * also be called when your bindings are initialized.
<ide> * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
<ide> * changes. Any actions that you wish to take in response to the changes that you detect must be
<ide> * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook | 1 |
Python | Python | make django rest framework as zip unsafe | 60f5b5d9f364c383662fb6ae8d210f31e9621c09 | <ide><path>setup.py
<ide> def get_package_data(package):
<ide> packages=get_packages('rest_framework'),
<ide> package_data=get_package_data('rest_framework'),
<ide> install_requires=[],
<add> zip_safe=False,
<ide> classifiers=[
<ide> 'Development Status :: 5 - Production/Stable',
<ide> 'Environment :: Web Environment', | 1 |
Ruby | Ruby | make use of tab#to_s | ad58cd88ab04a2c4047fe799b27da78dd67fbb32 | <ide><path>Library/Homebrew/cmd/info.rb
<ide> def info_formula f
<ide> kegs.reject! {|keg| keg.basename.to_s == '.DS_Store' }
<ide> kegs = kegs.map {|keg| Keg.new(keg) }.sort_by {|keg| keg.version }
<ide> kegs.each do |keg|
<del> print "#{keg} (#{keg.abv})"
<del> print " *" if keg.linked?
<del> puts
<del> tab = Tab.for_keg keg
<del>
<del> # Intentionally print no message if this is nil because it's unknown.
<del> case tab.poured_from_bottle
<del> when true then puts "Poured from bottle"
<del> when false then puts "Built from source"
<del> end
<del>
<del> unless tab.used_options.empty?
<del> puts " Installed with: #{tab.used_options*', '}"
<del> end
<add> puts "#{keg} (#{keg.abv})#{' *' if keg.linked?}"
<add> tab = Tab.for_keg(keg).to_s
<add> puts " #{tab}" unless tab.empty?
<ide> end
<ide> else
<ide> puts "Not installed" | 1 |
Text | Text | eliminate _you_ from n-api doc | 4970e2bec8a15739739ac4317158233c8cf32c6d | <ide><path>doc/api/n-api.md
<ide> napi_status napi_fatal_exception(napi_env env, napi_value err);
<ide> ```
<ide>
<ide> - `[in] env`: The environment that the API is invoked under.
<del>- `[in] err`: The error you want to pass to `'uncaughtException'`.
<add>- `[in] err`: The error that is passed to `'uncaughtException'`.
<ide>
<ide> Trigger an `'uncaughtException'` in JavaScript. Useful if an async
<ide> callback throws an exception with no way to recover.
<ide> napi_value Init(napi_env env, napi_value exports) {
<ide> }
<ide> ```
<ide>
<del>If you expect that your module will be loaded multiple times during the lifetime
<del>of the Node.js process, you can use the `NAPI_MODULE_INIT` macro to initialize
<del>your module:
<add>If the module will be loaded multiple times during the lifetime of the Node.js
<add>process, use the `NAPI_MODULE_INIT` macro to initialize the module:
<ide>
<ide> ```C
<ide> NAPI_MODULE_INIT() { | 1 |
Go | Go | trim quotes from tls flags | abe32de6b46825300f612864e6b4c98606a5bb0e | <ide><path>cli/flags/common.go
<ide> func (commonOpts *CommonOptions) InstallFlags(flags *pflag.FlagSet) {
<ide>
<ide> // TODO use flag flags.String("identity"}, "i", "", "Path to libtrust key file")
<ide>
<del> commonOpts.TLSOptions = &tlsconfig.Options{}
<add> commonOpts.TLSOptions = &tlsconfig.Options{
<add> CAFile: filepath.Join(dockerCertPath, DefaultCaFile),
<add> CertFile: filepath.Join(dockerCertPath, DefaultCertFile),
<add> KeyFile: filepath.Join(dockerCertPath, DefaultKeyFile),
<add> }
<ide> tlsOptions := commonOpts.TLSOptions
<del> flags.StringVar(&tlsOptions.CAFile, "tlscacert", filepath.Join(dockerCertPath, DefaultCaFile), "Trust certs signed only by this CA")
<del> flags.StringVar(&tlsOptions.CertFile, "tlscert", filepath.Join(dockerCertPath, DefaultCertFile), "Path to TLS certificate file")
<del> flags.StringVar(&tlsOptions.KeyFile, "tlskey", filepath.Join(dockerCertPath, DefaultKeyFile), "Path to TLS key file")
<add> flags.Var(opts.NewQuotedString(&tlsOptions.CAFile), "tlscacert", "Trust certs signed only by this CA")
<add> flags.Var(opts.NewQuotedString(&tlsOptions.CertFile), "tlscert", "Path to TLS certificate file")
<add> flags.Var(opts.NewQuotedString(&tlsOptions.KeyFile), "tlskey", "Path to TLS key file")
<ide>
<ide> hostOpt := opts.NewNamedListOptsRef("hosts", &commonOpts.Hosts, opts.ValidateHost)
<ide> flags.VarP(hostOpt, "host", "H", "Daemon socket(s) to connect to")
<ide><path>cli/flags/common_test.go
<add>package flags
<add>
<add>import (
<add> "path/filepath"
<add> "testing"
<add>
<add> cliconfig "github.com/docker/docker/cli/config"
<add> "github.com/docker/docker/pkg/testutil/assert"
<add> "github.com/spf13/pflag"
<add>)
<add>
<add>func TestCommonOptionsInstallFlags(t *testing.T) {
<add> flags := pflag.NewFlagSet("testing", pflag.ContinueOnError)
<add> opts := NewCommonOptions()
<add> opts.InstallFlags(flags)
<add>
<add> err := flags.Parse([]string{
<add> "--tlscacert=\"/foo/cafile\"",
<add> "--tlscert=\"/foo/cert\"",
<add> "--tlskey=\"/foo/key\"",
<add> })
<add> assert.NilError(t, err)
<add> assert.Equal(t, opts.TLSOptions.CAFile, "/foo/cafile")
<add> assert.Equal(t, opts.TLSOptions.CertFile, "/foo/cert")
<add> assert.Equal(t, opts.TLSOptions.KeyFile, "/foo/key")
<add>}
<add>
<add>func defaultPath(filename string) string {
<add> return filepath.Join(cliconfig.Dir(), filename)
<add>}
<add>
<add>func TestCommonOptionsInstallFlagsWithDefaults(t *testing.T) {
<add> flags := pflag.NewFlagSet("testing", pflag.ContinueOnError)
<add> opts := NewCommonOptions()
<add> opts.InstallFlags(flags)
<add>
<add> err := flags.Parse([]string{})
<add> assert.NilError(t, err)
<add> assert.Equal(t, opts.TLSOptions.CAFile, defaultPath("ca.pem"))
<add> assert.Equal(t, opts.TLSOptions.CertFile, defaultPath("cert.pem"))
<add> assert.Equal(t, opts.TLSOptions.KeyFile, defaultPath("key.pem"))
<add>}
<ide><path>opts/quotedstring.go
<ide> package opts
<ide>
<ide> // QuotedString is a string that may have extra quotes around the value. The
<ide> // quotes are stripped from the value.
<del>type QuotedString string
<add>type QuotedString struct {
<add> value *string
<add>}
<ide>
<ide> // Set sets a new value
<ide> func (s *QuotedString) Set(val string) error {
<del> *s = QuotedString(trimQuotes(val))
<add> *s.value = trimQuotes(val)
<ide> return nil
<ide> }
<ide>
<ide> func (s *QuotedString) Type() string {
<ide> }
<ide>
<ide> func (s *QuotedString) String() string {
<del> return string(*s)
<add> return string(*s.value)
<ide> }
<ide>
<ide> func trimQuotes(value string) string {
<ide> func trimQuotes(value string) string {
<ide> }
<ide> return value
<ide> }
<add>
<add>// NewQuotedString returns a new quoted string option
<add>func NewQuotedString(value *string) *QuotedString {
<add> return &QuotedString{value: value}
<add>}
<ide><path>opts/quotedstring_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestQuotedStringSetWithQuotes(t *testing.T) {
<del> qs := QuotedString("")
<add> value := ""
<add> qs := NewQuotedString(&value)
<ide> assert.NilError(t, qs.Set("\"something\""))
<ide> assert.Equal(t, qs.String(), "something")
<add> assert.Equal(t, value, "something")
<ide> }
<ide>
<ide> func TestQuotedStringSetWithMismatchedQuotes(t *testing.T) {
<del> qs := QuotedString("")
<add> value := ""
<add> qs := NewQuotedString(&value)
<ide> assert.NilError(t, qs.Set("\"something'"))
<ide> assert.Equal(t, qs.String(), "\"something'")
<ide> }
<ide>
<ide> func TestQuotedStringSetWithNoQuotes(t *testing.T) {
<del> qs := QuotedString("")
<add> value := ""
<add> qs := NewQuotedString(&value)
<ide> assert.NilError(t, qs.Set("something"))
<ide> assert.Equal(t, qs.String(), "something")
<ide> } | 4 |
Java | Java | fix bug with deriving sockjs path | 81bce424cb0abac468ea5c5e1cfa6f8d071e48ba | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/AbstractSockJsService.java
<ide> public abstract class AbstractSockJsService implements SockJsService, SockJsConf
<ide>
<ide> private final TaskScheduler taskScheduler;
<ide>
<del> private final List<String> sockJsPrefixes = new ArrayList<String>();
<add> private final List<String> validSockJsPrefixes = new ArrayList<String>();
<ide>
<del> private final Set<String> sockJsPathCache = new CopyOnWriteArraySet<String>();
<add> private final Set<String> knownSockJsPrefixes = new CopyOnWriteArraySet<String>();
<ide>
<ide>
<ide> public AbstractSockJsService(TaskScheduler scheduler) {
<ide> public String getName() {
<ide> */
<ide> public void setValidSockJsPrefixes(String... prefixes) {
<ide>
<del> this.sockJsPrefixes.clear();
<add> this.validSockJsPrefixes.clear();
<ide> for (String prefix : prefixes) {
<ide> if (prefix.endsWith("/") && (prefix.length() > 1)) {
<ide> prefix = prefix.substring(0, prefix.length() - 1);
<ide> }
<del> this.sockJsPrefixes.add(prefix);
<add> this.validSockJsPrefixes.add(prefix);
<ide> }
<ide>
<ide> // sort with longest prefix at the top
<del> Collections.sort(this.sockJsPrefixes, Collections.reverseOrder(new Comparator<String>() {
<add> Collections.sort(this.validSockJsPrefixes, Collections.reverseOrder(new Comparator<String>() {
<ide> @Override
<ide> public int compare(String o1, String o2) {
<ide> return new Integer(o1.length()).compareTo(new Integer(o2.length()));
<ide> private String getSockJsPath(ServerHttpRequest request) {
<ide> String path = request.getURI().getPath();
<ide>
<ide> // SockJS prefix hints?
<del> if (!this.sockJsPrefixes.isEmpty()) {
<del> for (String prefix : this.sockJsPrefixes) {
<add> if (!this.validSockJsPrefixes.isEmpty()) {
<add> for (String prefix : this.validSockJsPrefixes) {
<ide> int index = path.indexOf(prefix);
<ide> if (index != -1) {
<del> this.sockJsPathCache.add(path.substring(0, index + prefix.length()));
<add> this.knownSockJsPrefixes.add(path.substring(0, index + prefix.length()));
<ide> return path.substring(index + prefix.length());
<ide> }
<ide> }
<ide> private String getSockJsPath(ServerHttpRequest request) {
<ide>
<ide> // SockJS info request?
<ide> if (path.endsWith("/info")) {
<del> this.sockJsPathCache.add(path.substring(0, path.length() - 6));
<add> this.knownSockJsPrefixes.add(path.substring(0, path.length() - "/info".length()));
<ide> return "/info";
<ide> }
<ide>
<ide> // Have we seen this prefix before (following the initial /info request)?
<ide> String match = null;
<del> for (String sockJsPath : this.sockJsPathCache) {
<add> for (String sockJsPath : this.knownSockJsPrefixes) {
<ide> if (path.startsWith(sockJsPath)) {
<ide> if ((match == null) || (match.length() < sockJsPath.length())) {
<ide> match = sockJsPath;
<ide> }
<ide> }
<ide> }
<ide> if (match != null) {
<del> return path.substring(match.length());
<add> String result = path.substring(match.length());
<add> Assert.isTrue(result.charAt(0) == '/', "Invalid SockJS path extracted from incoming path \"" +
<add> path + "\". The extracted SockJS path is \"" + result +
<add> "\". It was extracted from these known SockJS prefixes " + this.knownSockJsPrefixes +
<add> ". Consider setting 'validSockJsPrefixes' on DefaultSockJsService.");
<add> return result;
<ide> }
<ide>
<ide> // SockJS greeting?
<ide> String pathNoSlash = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
<ide> String lastSegment = pathNoSlash.substring(pathNoSlash.lastIndexOf('/') + 1);
<ide>
<ide> if ((TransportType.fromValue(lastSegment) == null) && !lastSegment.startsWith("iframe")) {
<del> this.sockJsPathCache.add(path);
<add> this.knownSockJsPrefixes.add(path);
<ide> return "";
<ide> }
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/AbstractSockJsServiceTests.java
<ide> public void getSockJsPathForGreetingRequest() throws Exception {
<ide> public void getSockJsPathForInfoRequest() throws Exception {
<ide>
<ide> handleRequest("GET", "/a/info", HttpStatus.OK);
<add>
<ide> assertTrue(this.servletResponse.getContentAsString().startsWith("{\"entropy\":"));
<ide>
<add> handleRequest("GET", "/a/server/session/xhr", HttpStatus.OK);
<add>
<add> assertEquals("session", this.service.sessionId);
<add> assertEquals(TransportType.XHR, this.service.transportType);
<add> assertSame(this.handler, this.service.handler);
<add>
<ide> this.service.setValidSockJsPrefixes("/b");
<ide>
<ide> handleRequest("GET", "/a/info", HttpStatus.NOT_FOUND);
<del>
<ide> handleRequest("GET", "/b/info", HttpStatus.OK);
<add>
<ide> assertTrue(this.servletResponse.getContentAsString().startsWith("{\"entropy\":"));
<ide> }
<ide> | 2 |
Text | Text | move new changelog entry to the top | d9039cd9600bcdc7adff41a54787f62658488173 | <ide><path>actionpack/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Prevent raising EOFError on multipart GET request (IE issue). *Adam Stankiewicz*
<add>
<ide> * Rename all action callbacks from *_filter to *_action to avoid the misconception that these
<ide> callbacks are only suited for transforming or halting the response. With the new style,
<ide> it's more inviting to use them as they were intended, like setting shared ivars for views.
<del>
<add>
<ide> Example:
<del>
<add>
<ide> class PeopleController < ActionController::Base
<ide> before_action :set_person, except: [ :index, :new, :create ]
<ide> before_action :ensure_permission, only: [ :edit, :update ]
<del>
<add>
<ide> ...
<del>
<add>
<ide> private
<ide> def set_person
<ide> @person = current_account.people.find(params[:id])
<ide> end
<del>
<add>
<ide> def ensure_permission
<ide> current_person.can_change?(@person)
<ide> end
<ide> end
<del>
<add>
<ide> The old *_filter methods still work with no deprecation notice.
<del>
<add>
<ide> *DHH*
<ide>
<ide> * Add :if / :unless conditions to fragment cache:
<ide> * `ActionView::Helpers::TextHelper#highlight` now defaults to the
<ide> HTML5 `mark` element. *Brian Cardarella*
<ide>
<del>* Prevent raising EOFError on multipart GET request (IE issue). *Adam Stankiewicz*
<del>
<ide> Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/actionpack/CHANGELOG.md) for previous changes. | 1 |
Go | Go | add test coverage to pkg/jsonlog | e7a9a0bed84dc04db8d68dfc48fe095c5ce3edcb | <ide><path>pkg/jsonlog/jsonlog_marshalling.go
<ide> // buf.WriteString(`}`)
<ide> // return nil
<ide> // }
<add>// func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error {
<add>// if len(mj.Log) != 0 {
<add>// - if first == true {
<add>// - first = false
<add>// - } else {
<add>// - buf.WriteString(`,`)
<add>// - }
<add>// + first = false
<add>// buf.WriteString(`"log":`)
<add>// ffjson_WriteJsonString(buf, mj.Log)
<add>// }
<ide>
<ide> package jsonlog
<ide>
<ide> func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error {
<ide> )
<ide> buf.WriteString(`{`)
<ide> if len(mj.Log) != 0 {
<del> if first == true {
<del> first = false
<del> } else {
<del> buf.WriteString(`,`)
<del> }
<add> first = false
<ide> buf.WriteString(`"log":`)
<ide> ffjson_WriteJsonString(buf, mj.Log)
<ide> }
<ide><path>pkg/jsonlog/jsonlog_marshalling_test.go
<add>package jsonlog
<add>
<add>import (
<add> "regexp"
<add> "testing"
<add>)
<add>
<add>func TestJSONLogMarshalJSON(t *testing.T) {
<add> logs := map[JSONLog]string{
<add> JSONLog{Log: `"A log line with \\"`}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: "A log line"}: `^{\"log\":\"A log line\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: "A log line with \r"}: `^{\"log\":\"A log line with \\r\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: "A log line with & < >"}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: "A log line with utf8 : 🚀 ψ ω β"}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":\".{20,}\"}$`,
<add> JSONLog{}: `^{\"time\":\".{20,}\"}$`,
<add> // These ones are a little weird
<add> JSONLog{Log: "\u2028 \u2029"}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: string([]byte{0xaF})}: `^{\"log\":\"\\ufffd\",\"time\":\".{20,}\"}$`,
<add> JSONLog{Log: string([]byte{0x7F})}: `^{\"log\":\"\x7f\",\"time\":\".{20,}\"}$`,
<add> }
<add> for jsonLog, expression := range logs {
<add> data, err := jsonLog.MarshalJSON()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> res := string(data)
<add> t.Logf("Result of WriteLog: %q", res)
<add> logRe := regexp.MustCompile(expression)
<add> if !logRe.MatchString(res) {
<add> t.Fatalf("Log line not in expected format [%v]: %q", expression, res)
<add> }
<add> }
<add>}
<ide><path>pkg/jsonlog/jsonlog_test.go
<ide> import (
<ide> "encoding/json"
<ide> "io/ioutil"
<ide> "regexp"
<add> "strconv"
<ide> "strings"
<ide> "testing"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/timeutils"
<ide> )
<ide>
<del>func TestWriteLog(t *testing.T) {
<add>// Invalid json should return an error
<add>func TestWriteLogWithInvalidJSON(t *testing.T) {
<add> json := strings.NewReader("Invalid json")
<add> w := bytes.NewBuffer(nil)
<add> if err := WriteLog(json, w, "json", time.Time{}); err == nil {
<add> t.Fatalf("Expected an error, got [%v]", w.String())
<add> }
<add>}
<add>
<add>// Any format is valid, it will just print it
<add>func TestWriteLogWithInvalidFormat(t *testing.T) {
<add> testLine := "Line that thinks that it is log line from docker\n"
<ide> var buf bytes.Buffer
<ide> e := json.NewEncoder(&buf)
<add> for i := 0; i < 35; i++ {
<add> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<add> }
<add> w := bytes.NewBuffer(nil)
<add> if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := w.String()
<add> t.Logf("Result of WriteLog: %q", res)
<add> lines := strings.Split(strings.TrimSpace(res), "\n")
<add> expression := "^invalid format Line that thinks that it is log line from docker$"
<add> logRe := regexp.MustCompile(expression)
<add> expectedLines := 35
<add> if len(lines) != expectedLines {
<add> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<add> }
<add> for _, l := range lines {
<add> if !logRe.MatchString(l) {
<add> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<add> }
<add> }
<add>}
<add>
<add>// Having multiple Log/Stream element
<add>func TestWriteLogWithMultipleStreamLog(t *testing.T) {
<ide> testLine := "Line that thinks that it is log line from docker\n"
<del> for i := 0; i < 30; i++ {
<add> var buf bytes.Buffer
<add> e := json.NewEncoder(&buf)
<add> for i := 0; i < 35; i++ {
<ide> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<ide> }
<ide> w := bytes.NewBuffer(nil)
<del> format := timeutils.RFC3339NanoFixed
<del> if err := WriteLog(&buf, w, format, time.Time{}); err != nil {
<add> if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> res := w.String()
<ide> t.Logf("Result of WriteLog: %q", res)
<ide> lines := strings.Split(strings.TrimSpace(res), "\n")
<del> if len(lines) != 30 {
<del> t.Fatalf("Must be 30 lines but got %d", len(lines))
<add> expression := "^invalid format Line that thinks that it is log line from docker$"
<add> logRe := regexp.MustCompile(expression)
<add> expectedLines := 35
<add> if len(lines) != expectedLines {
<add> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<ide> }
<del> // 30+ symbols, five more can come from system timezone
<del> logRe := regexp.MustCompile(`.{30,} Line that thinks that it is log line from docker`)
<ide> for _, l := range lines {
<ide> if !logRe.MatchString(l) {
<del> t.Fatalf("Log line not in expected format: %q", l)
<add> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<add> }
<add> }
<add>}
<add>
<add>// Write log with since after created, it won't print anything
<add>func TestWriteLogWithDate(t *testing.T) {
<add> created, _ := time.Parse("YYYY-MM-dd", "2015-01-01")
<add> var buf bytes.Buffer
<add> testLine := "Line that thinks that it is log line from docker\n"
<add> jsonLog := JSONLog{Log: testLine, Stream: "stdout", Created: created}
<add> if err := json.NewEncoder(&buf).Encode(jsonLog); err != nil {
<add> t.Fatal(err)
<add> }
<add> w := bytes.NewBuffer(nil)
<add> if err := WriteLog(&buf, w, "json", time.Now()); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := w.String()
<add> if res != "" {
<add> t.Fatalf("Expected empty log, got [%v]", res)
<add> }
<add>}
<add>
<add>// Happy path :)
<add>func TestWriteLog(t *testing.T) {
<add> testLine := "Line that thinks that it is log line from docker\n"
<add> format := timeutils.RFC3339NanoFixed
<add> logs := map[string][]string{
<add> "": {"35", "^Line that thinks that it is log line from docker$"},
<add> "json": {"1", `^{\"log\":\"Line that thinks that it is log line from docker\\n\",\"stream\":\"stdout\",\"time\":.{30,}\"}$`},
<add> // 30+ symbols, five more can come from system timezone
<add> format: {"35", `.{30,} Line that thinks that it is log line from docker`},
<add> }
<add> for givenFormat, expressionAndLines := range logs {
<add> expectedLines, _ := strconv.Atoi(expressionAndLines[0])
<add> expression := expressionAndLines[1]
<add> var buf bytes.Buffer
<add> e := json.NewEncoder(&buf)
<add> for i := 0; i < 35; i++ {
<add> e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()})
<add> }
<add> w := bytes.NewBuffer(nil)
<add> if err := WriteLog(&buf, w, givenFormat, time.Time{}); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := w.String()
<add> t.Logf("Result of WriteLog: %q", res)
<add> lines := strings.Split(strings.TrimSpace(res), "\n")
<add> if len(lines) != expectedLines {
<add> t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines))
<add> }
<add> logRe := regexp.MustCompile(expression)
<add> for _, l := range lines {
<add> if !logRe.MatchString(l) {
<add> t.Fatalf("Log line not in expected format [%v]: %q", expression, l)
<add> }
<ide> }
<ide> }
<ide> }
<ide><path>pkg/jsonlog/jsonlogbytes.go
<ide> func (mj *JSONLogBytes) MarshalJSONBuf(buf *bytes.Buffer) error {
<ide>
<ide> buf.WriteString(`{`)
<ide> if len(mj.Log) != 0 {
<del> if first == true {
<del> first = false
<del> } else {
<del> buf.WriteString(`,`)
<del> }
<add> first = false
<ide> buf.WriteString(`"log":`)
<ide> ffjson_WriteJsonBytesAsString(buf, mj.Log)
<ide> }
<ide><path>pkg/jsonlog/jsonlogbytes_test.go
<add>package jsonlog
<add>
<add>import (
<add> "bytes"
<add> "regexp"
<add> "testing"
<add>)
<add>
<add>func TestJSONLogBytesMarshalJSONBuf(t *testing.T) {
<add> logs := map[*JSONLogBytes]string{
<add> &JSONLogBytes{Log: []byte(`"A log line with \\"`)}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte("A log line with \r")}: `^{\"log\":\"A log line with \\r\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte("A log line with & < >")}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":}$`,
<add> &JSONLogBytes{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":}$`,
<add> &JSONLogBytes{Stream: "stdout", Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":}$`,
<add> &JSONLogBytes{Created: "time"}: `^{\"time\":time}$`,
<add> &JSONLogBytes{}: `^{\"time\":}$`,
<add> // These ones are a little weird
<add> &JSONLogBytes{Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":}$`,
<add> &JSONLogBytes{Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":}$`,
<add> }
<add> for jsonLog, expression := range logs {
<add> var buf bytes.Buffer
<add> if err := jsonLog.MarshalJSONBuf(&buf); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := buf.String()
<add> t.Logf("Result of WriteLog: %q", res)
<add> logRe := regexp.MustCompile(expression)
<add> if !logRe.MatchString(res) {
<add> t.Fatalf("Log line not in expected format [%v]: %q", expression, res)
<add> }
<add> }
<add>} | 5 |
Javascript | Javascript | remove old run script | 7d517458278bd364935e58abcae0944ea0766157 | <ide><path>benchmark/run.js
<del>var path = require("path");
<del>var util = require("util");
<del>var childProcess = require("child_process");
<del>var benchmarks = [ "timers.js"
<del> , "process_loop.js"
<del> , "static_http_server.js"
<del> ];
<del>
<del>var benchmarkDir = path.dirname(__filename);
<del>
<del>function exec (script, callback) {
<del> var start = new Date();
<del> var child = childProcess.spawn(process.argv[0], [path.join(benchmarkDir, script)]);
<del> child.addListener("exit", function (code) {
<del> var elapsed = new Date() - start;
<del> callback(elapsed, code);
<del> });
<del>}
<del>
<del>function runNext (i) {
<del> if (i >= benchmarks.length) return;
<del> util.print(benchmarks[i] + ": ");
<del> exec(benchmarks[i], function (elapsed, code) {
<del> if (code != 0) {
<del> console.log("ERROR ");
<del> }
<del> console.log(elapsed);
<del> runNext(i+1);
<del> });
<del>};
<del>runNext(0); | 1 |
Text | Text | add v3.14.1 to changelog.md | b8ebef5d0a14f1f4a67436e6a46699266e81c635 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.14.1 (October 30, 2019)
<add>
<add>- [#18244](https://github.com/emberjs/ember.js/pull/18244) [BUGFIX] Fix query param assertion when using the router services `transitionTo` to redirect _during_ an existing transition.
<add>
<ide> ### v3.14.0 (October 29, 2019)
<ide>
<ide> - [#18345](https://github.com/emberjs/ember.js/pull/18345) / [#18363](https://github.com/emberjs/ember.js/pull/18363) [FEATURE] Implement the [Provide @model named argument to route templates](https://github.com/emberjs/rfcs/blob/master/text/0523-model-argument-for-route-templates.md RFC. | 1 |
PHP | PHP | fix failing test on windows | 691df6f17f1e8ac0c88704d5fb7a05f3c5b4d9ab | <ide><path>lib/Cake/Test/TestCase/BasicsTest.php
<ide> public function testFileExistsInPath() {
<ide>
<ide> $this->assertEquals(fileExistsInPath('file1.php'), $file1);
<ide> $this->assertEquals(fileExistsInPath('file2.php'), $file2);
<del> $this->assertEquals(fileExistsInPath('folder1/file2.php'), $file2);
<add> $this->assertEquals(fileExistsInPath('folder1' . DS . 'file2.php'), $file2);
<ide> $this->assertEquals(fileExistsInPath($file2), $file2);
<ide> $this->assertEquals(fileExistsInPath('file3.php'), $file3);
<ide> $this->assertEquals(fileExistsInPath($file4), $file4); | 1 |
Go | Go | fix hijackedconn reading from buffer | f094a05e260d8748f0fd2018a8a908b4189e454d | <ide><path>client/hijack.go
<ide> func (cli *Client) setupHijackConn(req *http.Request, proto string) (net.Conn, e
<ide> // object that implements CloseWrite iff the underlying connection
<ide> // implements it.
<ide> if _, ok := c.(types.CloseWriter); ok {
<del> c = &hijackedConnCloseWriter{c, br}
<add> c = &hijackedConnCloseWriter{&hijackedConn{c, br}}
<ide> } else {
<ide> c = &hijackedConn{c, br}
<ide> }
<ide> func (c *hijackedConn) Read(b []byte) (int, error) {
<ide> // CloseWrite(). It is returned by setupHijackConn in the case that a) there
<ide> // was already buffered data in the http layer when Hijack() was called, and b)
<ide> // the underlying net.Conn *does* implement CloseWrite().
<del>type hijackedConnCloseWriter hijackedConn
<add>type hijackedConnCloseWriter struct {
<add> *hijackedConn
<add>}
<ide>
<ide> var _ types.CloseWriter = &hijackedConnCloseWriter{}
<ide> | 1 |
Text | Text | add franziska hinkelmann to the ctc | c7e8aff83972fe907c63cbffe25865ec38ff1189 | <ide><path>README.md
<ide> more information about the governance of the Node.js project, see
<ide> **Colin Ihrig** <[email protected]>
<ide> * [evanlucas](https://github.com/evanlucas) -
<ide> **Evan Lucas** <[email protected]> (he/him)
<add>* [fhinkel](https://github.com/fhinkel) -
<add>**Franziska Hinkelmann** <[email protected]>
<ide> * [fishrock123](https://github.com/fishrock123) -
<ide> **Jeremiah Senkpiel** <[email protected]>
<ide> * [indutny](https://github.com/indutny) -
<ide> more information about the governance of the Node.js project, see
<ide> **Alexander Makarenko** <[email protected]>
<ide> * [eugeneo](https://github.com/eugeneo) -
<ide> **Eugene Ostroukhov** <[email protected]>
<del>* [fhinkel](https://github.com/fhinkel) -
<del>**Franziska Hinkelmann** <[email protected]>
<ide> * [firedfox](https://github.com/firedfox) -
<ide> **Daniel Wang** <[email protected]>
<ide> * [geek](https://github.com/geek) - | 1 |
Ruby | Ruby | fix stack trace lines on class_eval | 13e00ce6064fd1ce143071e3531e65f64047b013 | <ide><path>actionpack/lib/action_controller/polymorphic_routes.rb
<ide> def polymorphic_path(record_or_hash_or_array, options = {})
<ide> end
<ide>
<ide> %w(edit new).each do |action|
<del> module_eval <<-EOT, __FILE__, __LINE__
<add> module_eval <<-EOT, __FILE__, __LINE__ + 1
<ide> def #{action}_polymorphic_url(record_or_hash, options = {}) # def edit_polymorphic_url(record_or_hash, options = {})
<ide> polymorphic_url( # polymorphic_url(
<ide> record_or_hash, # record_or_hash,
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb
<ide> def initialize(object_name, object, template, options, proc)
<ide> end
<ide>
<ide> (field_helpers - %w(label check_box radio_button fields_for hidden_field)).each do |selector|
<del> src, file, line = <<-end_src, __FILE__, __LINE__ + 1
<add> src, line = <<-end_src, __LINE__ + 1
<ide> def #{selector}(method, options = {}) # def text_field(method, options = {})
<ide> @template.send( # @template.send(
<ide> #{selector.inspect}, # "text_field",
<ide> def #{selector}(method, options = {}) # def text_field(method, options = {})
<ide> objectify_options(options)) # objectify_options(options))
<ide> end # end
<ide> end_src
<del> class_eval src, file, line
<add> class_eval src, __FILE__, line
<ide> end
<ide>
<ide> def fields_for(record_or_name_or_array, *args, &block)
<ide><path>actionpack/test/template/form_helper_test.rb
<ide> def test_form_for_and_fields_for_with_object
<ide>
<ide> class LabelledFormBuilder < ActionView::Helpers::FormBuilder
<ide> (field_helpers - %w(hidden_field)).each do |selector|
<del> src = <<-END_SRC
<add> src, line = <<-END_SRC, __LINE__ + 1
<ide> def #{selector}(field, *args, &proc)
<ide> ("<label for='\#{field}'>\#{field.to_s.humanize}:</label> " + super + "<br/>").html_safe
<ide> end
<ide> END_SRC
<del> class_eval src, __FILE__, __LINE__
<add> class_eval src, __FILE__, line
<ide> end
<ide> end
<ide>
<ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> def attribute_method_affix(*affixes)
<ide>
<ide> def alias_attribute(new_name, old_name)
<ide> attribute_method_matchers.each do |matcher|
<del> module_eval <<-STR, __FILE__, __LINE__+1
<add> module_eval <<-STR, __FILE__, __LINE__ + 1
<ide> def #{matcher.method_name(new_name)}(*args)
<ide> send(:#{matcher.method_name(old_name)}, *args)
<ide> end
<ide> def define_attribute_methods(attr_names)
<ide> else
<ide> method_name = matcher.method_name(attr_name)
<ide>
<del> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__+1
<add> generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
<ide> if method_defined?(:#{method_name})
<ide> undef :#{method_name}
<ide> end
<ide><path>activemodel/lib/active_model/callbacks.rb
<ide> def define_model_callbacks(*callbacks)
<ide> end
<ide>
<ide> def _define_before_model_callback(klass, callback) #:nodoc:
<del> klass.class_eval <<-CALLBACK, __FILE__, __LINE__
<add> klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
<ide> def self.before_#{callback}(*args, &block)
<ide> set_callback(:#{callback}, :before, *args, &block)
<ide> end
<ide> CALLBACK
<ide> end
<ide>
<ide> def _define_around_model_callback(klass, callback) #:nodoc:
<del> klass.class_eval <<-CALLBACK, __FILE__, __LINE__
<add> klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
<ide> def self.around_#{callback}(*args, &block)
<ide> set_callback(:#{callback}, :around, *args, &block)
<ide> end
<ide> CALLBACK
<ide> end
<ide>
<ide> def _define_after_model_callback(klass, callback) #:nodoc:
<del> klass.class_eval <<-CALLBACK, __FILE__, __LINE__
<add> klass.class_eval <<-CALLBACK, __FILE__, __LINE__ + 1
<ide> def self.after_#{callback}(*args, &block)
<ide> options = args.extract_options!
<ide> options[:prepend] = true
<ide><path>activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
<ide> module ClassMethods
<ide> # This enhanced read method automatically converts the UTC time stored in the database to the time zone stored in Time.zone.
<ide> def define_method_attribute(attr_name)
<ide> if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
<del> method_body = <<-EOV
<add> method_body, line = <<-EOV, __LINE__ + 1
<ide> def #{attr_name}(reload = false)
<ide> cached = @attributes_cache['#{attr_name}']
<ide> return cached if cached && !reload
<ide> time = read_attribute('#{attr_name}')
<ide> @attributes_cache['#{attr_name}'] = time.acts_like?(:time) ? time.in_time_zone : time
<ide> end
<ide> EOV
<del> generated_attribute_methods.module_eval(method_body, __FILE__, __LINE__)
<add> generated_attribute_methods.module_eval(method_body, __FILE__, line)
<ide> else
<ide> super
<ide> end
<ide> def #{attr_name}(reload = false)
<ide> # This enhanced write method will automatically convert the time passed to it to the zone stored in Time.zone.
<ide> def define_method_attribute=(attr_name)
<ide> if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
<del> method_body = <<-EOV
<add> method_body, line = <<-EOV, __LINE__ + 1
<ide> def #{attr_name}=(time)
<ide> unless time.acts_like?(:time)
<ide> time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
<ide> def #{attr_name}=(time)
<ide> write_attribute(:#{attr_name}, time)
<ide> end
<ide> EOV
<del> generated_attribute_methods.module_eval(method_body, __FILE__, __LINE__)
<add> generated_attribute_methods.module_eval(method_body, __FILE__, line)
<ide> else
<ide> super
<ide> end
<ide><path>activerecord/lib/active_record/base.rb
<ide> def method_missing(method_id, *arguments, &block)
<ide> attribute_names = match.attribute_names
<ide> super unless all_attributes_exists?(attribute_names)
<ide> if match.scope?
<del> self.class_eval %{
<add> self.class_eval <<-METHOD, __FILE__, __LINE__ + 1
<ide> def self.#{method_id}(*args) # def self.scoped_by_user_name_and_password(*args)
<ide> options = args.extract_options! # options = args.extract_options!
<ide> attributes = construct_attributes_from_arguments( # attributes = construct_attributes_from_arguments(
<ide> def self.#{method_id}(*args) # def self.scoped_by_user_na
<ide> #
<ide> scoped(:conditions => attributes) # scoped(:conditions => attributes)
<ide> end # end
<del> }, __FILE__, __LINE__
<add> METHOD
<ide> send(method_id, *arguments)
<ide> end
<ide> else
<ide> def compute_type(type_name)
<ide> modularized_name = type_name_with_module(type_name)
<ide> silence_warnings do
<ide> begin
<del> class_eval(modularized_name, __FILE__, __LINE__)
<add> class_eval(modularized_name, __FILE__)
<ide> rescue NameError
<del> class_eval(type_name, __FILE__, __LINE__)
<add> class_eval(type_name, __FILE__)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
<ide> def included(base)
<ide>
<ide> def dirties_query_cache(base, *method_names)
<ide> method_names.each do |method_name|
<del> base.class_eval <<-end_code, __FILE__, __LINE__
<add> base.class_eval <<-end_code, __FILE__, __LINE__ + 1
<ide> def #{method_name}_with_query_dirty(*args) # def update_with_query_dirty(*args)
<ide> clear_query_cache if @query_cache_enabled # clear_query_cache if @query_cache_enabled
<ide> #{method_name}_without_query_dirty(*args) # update_without_query_dirty(*args)
<ide><path>activeresource/lib/active_resource/base.rb
<ide> def prefix=(value = '/')
<ide> @prefix_parameters = nil
<ide>
<ide> # Redefine the new methods.
<del> code = <<-end_code
<add> code, line = <<-end_code, __LINE__ + 1
<ide> def prefix_source() "#{value}" end
<ide> def prefix(options={}) "#{prefix_call}" end
<ide> end_code
<del> silence_warnings { instance_eval code, __FILE__, __LINE__ }
<add> silence_warnings { instance_eval code, __FILE__, line }
<ide> rescue
<ide> logger.error "Couldn't set prefix: #{$!}\n #{code}" if logger
<ide> raise
<ide><path>activeresource/lib/active_resource/http_mock.rb
<ide> def initialize(responses)
<ide> # def post(path, request_headers = {}, body = nil, status = 200, response_headers = {})
<ide> # @responses[Request.new(:post, path, nil, request_headers)] = Response.new(body || "", status, response_headers)
<ide> # end
<del> module_eval <<-EOE, __FILE__, __LINE__
<add> module_eval <<-EOE, __FILE__, __LINE__ + 1
<ide> def #{method}(path, request_headers = {}, body = nil, status = 200, response_headers = {})
<ide> @responses << [Request.new(:#{method}, path, nil, request_headers), Response.new(body || "", status, response_headers)]
<ide> end
<ide> def reset!
<ide> # self.class.requests << request
<ide> # self.class.responses.assoc(request).try(:second) || raise(InvalidRequestError.new("No response recorded for #{request}"))
<ide> # end
<del> module_eval <<-EOE, __FILE__, __LINE__
<add> module_eval <<-EOE, __FILE__, __LINE__ + 1
<ide> def #{method}(path, #{'body, ' if has_body}headers)
<ide> request = ActiveResource::Request.new(:#{method}, path, #{has_body ? 'body, ' : 'nil, '}headers)
<ide> self.class.requests << request
<ide><path>activesupport/lib/active_support/cache/strategy/local_cache.rb
<ide> def with_local_cache
<ide> def middleware
<ide> @middleware ||= begin
<ide> klass = Class.new
<del> klass.class_eval(<<-EOS, __FILE__, __LINE__)
<del> def initialize(app)
<add> klass.class_eval(<<-EOS, __FILE__, __LINE__ + 1)
<add> def initialize(app
<ide> @app = app
<ide> end
<ide>
<ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def __define_runner(symbol) #:nodoc:
<ide> send("_update_#{symbol}_superclass_callbacks")
<ide> body = send("_#{symbol}_callbacks").compile(nil)
<ide>
<del> body, line = <<-RUBY_EVAL, __LINE__
<add> body, line = <<-RUBY_EVAL, __LINE__ + 1
<ide> def _run_#{symbol}_callbacks(key = nil, &blk)
<ide> if self.class.send("_update_#{symbol}_superclass_callbacks")
<ide> self.class.__define_runner(#{symbol.inspect})
<ide><path>activesupport/lib/active_support/core_ext/module/aliasing.rb
<ide> def alias_method_chain(target, feature)
<ide> # e.subject = "Megastars"
<ide> # e.title # => "Megastars"
<ide> def alias_attribute(new_name, old_name)
<del> module_eval <<-STR, __FILE__, __LINE__+1
<add> module_eval <<-STR, __FILE__, __LINE__ + 1
<ide> def #{new_name}; self.#{old_name}; end # def subject; self.title; end
<ide> def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end
<ide> def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end
<ide><path>activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb
<ide> class Module
<ide> def attr_accessor_with_default(sym, default = nil, &block)
<ide> raise 'Default value or block required' unless !default.nil? || block
<ide> define_method(sym, block_given? ? block : Proc.new { default })
<del> module_eval(<<-EVAL, __FILE__, __LINE__)
<add> module_eval(<<-EVAL, __FILE__, __LINE__ + 1)
<ide> def #{sym}=(value) # def age=(value)
<ide> class << self; attr_reader :#{sym} end # class << self; attr_reader :age end
<ide> @#{sym} = value # @age = value
<ide><path>activesupport/lib/active_support/core_ext/module/synchronization.rb
<ide> def synchronize(*methods)
<ide> raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported."
<ide> end
<ide>
<del> module_eval(<<-EOS, __FILE__, __LINE__)
<add> module_eval(<<-EOS, __FILE__, __LINE__ + 1)
<ide> def #{aliased_method}_with_synchronization#{punctuation}(*args, &block) # def expire_with_synchronization(*args, &block)
<ide> #{with}.synchronize do # @@lock.synchronize do
<ide> #{aliased_method}_without_synchronization#{punctuation}(*args, &block) # expire_without_synchronization(*args, &block) | 15 |
Text | Text | fix title level at tls.md | 33aa953f918f624a44e538baf2a3ee41570ac303 | <ide><path>doc/api/tls.md
<ide> As with checking for the server [`secureConnection`](#tls_event_secureconnection
<ide> event, `pair.cleartext.authorized` should be inspected to confirm whether the
<ide> certificate used is properly authorized.
<ide>
<del>## tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])
<add>### tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])
<ide> <!-- YAML
<ide> added: v0.3.2
<ide> deprecated: v0.11.3 | 1 |
Javascript | Javascript | add more data passed through with projectsettings | 1483c0c96d38cdce574960df2662f237168eeea0 | <ide><path>src/atom-environment.js
<ide> class AtomEnvironment {
<ide> })
<ide> this.config.resetUserSettings(userSettings)
<ide>
<del> if (projectSettings != null) {
<del> this.project.resetProjectSettings(projectSettings)
<add> if (projectSettings != null && projectSettings.paths != null || projectSettings.config != null) {
<add> this.project.replaceAtomProject(projectSettings)
<ide> }
<ide>
<ide> this.menu.initialize({resourcePath})
<ide><path>src/config.js
<ide> class Config {
<ide>
<ide> resetProjectSettings (newSettings, options = {}) {
<ide> // Sets the scope and source of all project settings to `path`.
<add> newSettings = Object.assign({}, newSettings)
<ide> this.hasCurrentProject = !options.removeProject
<ide> const pathScopedSettings = {}
<ide> pathScopedSettings[PROJECT] = newSettings
<ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide> }
<ide>
<ide> let openedWindow
<del> if (existingWindow && projectSettings == null) {
<add> if (existingWindow && projectSettings.paths == null && projectSettings.config == null) {
<ide> openedWindow = existingWindow
<ide> openedWindow.openLocations(locationsToOpen)
<ide> if (openedWindow.isMinimized()) {
<ide><path>src/main-process/atom-window.js
<ide> class AtomWindow extends EventEmitter {
<ide> Object.defineProperty(this.browserWindow, 'loadSettingsJSON', {
<ide> get: () => JSON.stringify(Object.assign({
<ide> userSettings: this.atomApplication.configFile.get(),
<del> projectSettings: this.getProjectSettings()
<add> projectSettings: this.projectSettings
<ide> }, this.loadSettings)),
<ide> configurable: true
<ide> })
<ide><path>src/main-process/parse-command-line.js
<ide> module.exports = function parseCommandLine (processArgs) {
<ide> devMode = true
<ide> }
<ide>
<del> let projectSettings
<add> let projectSettings = {}
<ide> if (atomProject) {
<del> const config = readProjectSettingsSync(atomProject, executedFrom)
<del> const paths = config.paths
<del> projectSettings = config.config
<add> const contents = readProjectSettingsSync(atomProject, executedFrom)
<add> const paths = contents.paths
<add> const config = contents.config
<add> const originPath = atomProject
<ide> if (paths != null) {
<ide> pathsToOpen = pathsToOpen.concat(paths)
<ide> }
<add> projectSettings = { originPath, paths, config }
<add>
<ide> }
<ide>
<ide> if (devMode) {
<ide> const readProjectSettingsSync = (filepath, executedFrom) => {
<ide> try {
<ide> const readPath = path.isAbsolute(filepath) ? filepath : path.join(executedFrom, filepath)
<ide> const contents = CSON.readFileSync(readPath)
<del> if (contents.paths || content.config) {
<add> if (contents.paths || contents.config) {
<ide> return contents
<ide> }
<ide>
<ide><path>src/project.js
<ide> class Project extends Model {
<ide> this.retiredBufferIDs = new Set()
<ide> this.retiredBufferPaths = new Set()
<ide> this.subscriptions = new CompositeDisposable()
<add> this.projectFilePath = null
<ide> this.consumeServices(packageManager)
<ide> }
<ide>
<ide> class Project extends Model {
<ide> }
<ide> }
<ide>
<del> resetProjectSettings (newSettings) {
<del> atom.config.resetProjectSettings(newSettings)
<add> // Layers the contents of an atomProject file's config
<add> // on top of the current global config.
<add> replaceAtomProject (newSettings) {
<add> atom.config.resetProjectSettings(newSettings.config)
<add> this.projectFilePath = newSettings.originPath
<ide> }
<ide>
<ide> clearProjectSettings () {
<ide> atom.config.clearProjectSettings()
<ide> }
<ide>
<add> getProjectFilePath () {
<add> return this.projectFilePath
<add> }
<add>
<ide> /*
<ide> Section: Serialization
<ide> */ | 6 |
Javascript | Javascript | add buffer testcase for resetting kzerofill | fea3070ec46d8d231b95ff100170d16306814ee8 | <ide><path>test/parallel/test-buffer.js
<ide> assert.equal(SlowBuffer.prototype.offset, undefined);
<ide> // Check pool offset after that by trying to write string into the pool.
<ide> assert.doesNotThrow(() => Buffer.from('abc'));
<ide> }
<add>
<add>
<add>// Test failed or zero-sized Buffer allocations not affecting typed arrays
<add>{
<add> const zeroArray = new Uint32Array(10).fill(0);
<add> const sizes = [1e10, 0, 0.1, -1, 'a', undefined, null, NaN];
<add> const allocators = [
<add> Buffer,
<add> SlowBuffer,
<add> Buffer.alloc,
<add> Buffer.allocUnsafe,
<add> Buffer.allocUnsafeSlow
<add> ];
<add> for (const allocator of allocators) {
<add> for (const size of sizes) {
<add> try {
<add> allocator(size);
<add> } catch (e) {
<add> assert.deepStrictEqual(new Uint32Array(10), zeroArray);
<add> }
<add> }
<add> }
<add>} | 1 |
Text | Text | add newline formatting for notes tip | 5bfc6de78bf39a523bc51a3619224e14e87f7b51 | <ide><path>docs/how-to-work-on-coding-challenges.md
<ide> The following is an example of code:
<ide> ```
<ide> ````
<ide>
<del>- Additional information in the form of a note should be formatted `**Note:** Rest of note text...`
<del>- If multiple notes are needed, then list all of the notes in separate sentences using the format `**Notes:** First note text. Second note text.`.
<add>- Additional information in the form of a note should be surrounded by blank lines, and formatted: `**Note:** Rest of note text...`
<add>- If multiple notes are needed, then list all of the notes in separate sentences using the format: `**Notes:** First note text. Second note text.`
<ide> - Use single-quotes where applicable
<ide>
<ide> **Note:** The equivalent _Markdown_ should be used in place of _HTML_ tags. | 1 |
Python | Python | add api conversion interface for dense layer | 5516c8fb42f01622c9a4a31c19cb46ae68cfa0f6 | <ide><path>keras/layers/core.py
<ide> from ..utils.generic_utils import func_dump
<ide> from ..utils.generic_utils import func_load
<ide> from ..utils.generic_utils import deserialize_keras_object
<add>from ..legacy import interfaces
<ide>
<ide>
<ide> class Masking(Layer):
<ide> class Dense(Layer):
<ide> the output would have shape `(batch_size, units)`.
<ide> """
<ide>
<add> @interfaces.legacy_dense_support
<ide> def __init__(self, units,
<ide> activation=None,
<ide> use_bias=True,
<ide><path>keras/legacy/interfaces.py
<add>"""Interface converters for Keras 1 support in Keras 2.
<add>"""
<add>import six
<add>import warnings
<add>
<add>
<add>def raise_duplicate_arg_error(old_arg, new_arg):
<add> raise TypeError('For the `' + new_arg + '` argument, '
<add> 'the layer received both '
<add> 'the legacy keyword argument '
<add> '`' + old_arg + '` and the Keras 2 keyword argument '
<add> '`' + new_arg + '`. Stick with the latter!')
<add>
<add>
<add>def legacy_dense_support(func):
<add> """Function wrapper to convert the `Dense` constructor from Keras 1 to 2.
<add>
<add> # Arguments
<add> func: `__init__` method of `Dense`.
<add>
<add> # Returns
<add> A constructor conversion wrapper.
<add> """
<add> @six.wraps(func)
<add> def wrapper(*args, **kwargs):
<add> if len(args) > 2:
<add> # The first entry in `args` is `self`.
<add> raise TypeError('The `Dense` layer can have at most '
<add> 'one positional argument (the `units` argument).')
<add>
<add> # output_dim
<add> if 'output_dim' in kwargs:
<add> if len(args) > 1:
<add> raise TypeError('Got both a positional argument '
<add> 'and keyword argument for argument '
<add> '`units` '
<add> '(`output_dim` in the legacy interface).')
<add> if 'units' in kwargs:
<add> raise_duplicate_arg_error('output_dim', 'units')
<add> output_dim = kwargs.pop('output_dim')
<add> args = (args[0], output_dim)
<add>
<add> converted = []
<add>
<add> # Remaining kwargs.
<add> conversions = [
<add> ('init', 'kernel_initializer'),
<add> ('W_regularizer', 'kernel_regularizer'),
<add> ('b_regularizer', 'bias_regularizer'),
<add> ('W_constraint', 'kernel_constraint'),
<add> ('b_constraint', 'bias_constraint'),
<add> ('bias', 'use_bias'),
<add> ]
<add>
<add> for old_arg, new_arg in conversions:
<add> if old_arg in kwargs:
<add> if new_arg in kwargs:
<add> raise_duplicate_arg_error(old_arg, new_arg)
<add> arg_value = kwargs.pop(old_arg)
<add> kwargs[new_arg] = arg_value
<add> converted.append((new_arg, arg_value))
<add>
<add> if converted:
<add> signature = '`Dense(' + str(args[1])
<add> for name, value in converted:
<add> signature += ', ' + name + '='
<add> if isinstance(value, six.string_types):
<add> signature += ('"' + value + '"')
<add> else:
<add> signature += str(value)
<add> signature += ')`'
<add> warnings.warn('Update your `Dense` layer call '
<add> 'to the Keras 2 API: ' + signature)
<add>
<add> return func(*args, **kwargs)
<add> return wrapper
<ide><path>tests/keras/legacy/interface_test.py
<add>import pytest
<add>import json
<add>from keras.utils.test_utils import keras_test
<add>import keras
<add>
<add>
<add>@keras_test
<add>def test_dense_legacy_interface():
<add> old_layer = keras.layers.Dense(input_dim=3, output_dim=2, name='d')
<add> new_layer = keras.layers.Dense(2, input_shape=(3,), name='d')
<add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config())
<add>
<add> old_layer = keras.layers.Dense(2, bias=False, init='normal',
<add> W_regularizer='l1',
<add> W_constraint='max_norm', name='d')
<add> new_layer = keras.layers.Dense(2, use_bias=False,
<add> kernel_initializer='normal',
<add> kernel_regularizer='l1',
<add> kernel_constraint='max_norm', name='d')
<add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config())
<add>
<add> old_layer = keras.layers.Dense(2, bias=True,
<add> b_regularizer='l1',
<add> b_constraint='max_norm', name='d')
<add> new_layer = keras.layers.Dense(2, use_bias=True,
<add> bias_regularizer='l1',
<add> bias_constraint='max_norm', name='d')
<add> assert json.dumps(old_layer.get_config()) == json.dumps(new_layer.get_config())
<add>
<add>
<add>if __name__ == '__main__':
<add> pytest.main([__file__]) | 3 |
Text | Text | fix typo in blogpost | 96bd63cc4bc36791aa6b7fc4559e5c5e9e00bab7 | <ide><path>docs/_posts/2013-07-17-react-v0-4-0.md
<ide> When you're ready, [go download it](/react/downloads.html)!
<ide>
<ide> * Support for comment nodes `<div>{/* this is a comment and won't be rendered */}</div>`
<ide> * Children are now transformed directly into arguments instead of being wrapped in an array
<del> E.g. `<div><Component1/><Component2></div>` is transformed into `React.DOM.div(null, Component1(null), Component2(null))`.
<add> E.g. `<div><Component1/><Component2/></div>` is transformed into `React.DOM.div(null, Component1(null), Component2(null))`.
<ide> Previously this would be transformed into `React.DOM.div(null, [Component1(null), Component2(null)])`.
<ide> If you were using React without JSX previously, your code should still work.
<ide> | 1 |
PHP | PHP | fix double printing of models in consoleshell | 810fd28186b05462a2b7a1da3bf570c157f985d3 | <ide><path>lib/Cake/Console/Command/ConsoleShell.php
<ide> public function startup() {
<ide>
<ide> foreach ($this->models as $model) {
<ide> $class = $model;
<del> $this->models[$model] = $class;
<ide> App::uses($class, 'Model');
<ide> $this->{$class} = new $class();
<ide> } | 1 |
Javascript | Javascript | add tests for server.connections | 97f001ab167875c8e8e8418fa55ff14ef76a4064 | <ide><path>lib/net.js
<ide> function Server(options, connectionListener) {
<ide> return this._connections;
<ide> }, 'Server.connections property is deprecated. ' +
<ide> 'Use Server.getConnections method instead.'),
<del> set: internalUtil.deprecate((val) => {
<del> return (this._connections = val);
<del> }, 'Server.connections property is deprecated.'),
<add> set: internalUtil.deprecate((val) => (this._connections = val),
<add> 'Server.connections property is deprecated.'),
<ide> configurable: true, enumerable: false
<ide> });
<ide>
<ide><path>test/parallel/test-net-server-connections-child-null.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const fork = require('child_process').fork;
<add>const net = require('net');
<add>
<add>if (process.argv[2] === 'child') {
<add>
<add> process.on('message', (msg, socket) => {
<add> socket.end('goodbye');
<add> });
<add>
<add> process.send('hello');
<add>
<add>} else {
<add>
<add> const child = fork(process.argv[1], ['child']);
<add>
<add> const runTest = common.mustCall(() => {
<add>
<add> const server = net.createServer();
<add>
<add> // server.connections should start as 0
<add> assert.strictEqual(server.connections, 0);
<add> server.on('connection', (socket) => {
<add> child.send({what: 'socket'}, socket);
<add> });
<add> server.on('close', () => {
<add> child.kill();
<add> });
<add>
<add> server.listen(0, common.mustCall(() => {
<add> const connect = net.connect(server.address().port);
<add>
<add> connect.on('close', common.mustCall(() => {
<add> // now server.connections should be null
<add> assert.strictEqual(server.connections, null);
<add> server.close();
<add> }));
<add> }));
<add> });
<add>
<add> child.on('message', runTest);
<add>}
<ide><path>test/parallel/test-net-server-connections.js
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide>
<ide> const net = require('net');
<ide>
<del>// test that server.connections property is no longer enumerable now that it
<del>// has been marked as deprecated
<del>
<ide> const server = new net.Server();
<ide>
<add>const expectedWarning = 'Server.connections property is deprecated. ' +
<add> 'Use Server.getConnections method instead.';
<add>
<add>common.expectWarning('DeprecationWarning', expectedWarning);
<add>
<add>// test that server.connections property is no longer enumerable now that it
<add>// has been marked as deprecated
<ide> assert.strictEqual(Object.keys(server).indexOf('connections'), -1);
<add>
<add>assert.strictEqual(server.connections, 0); | 3 |
Mixed | Ruby | treat invalid uuid as nil | f378f23653259dee98061b279b628eb774e6faf1 | <ide><path>activerecord/CHANGELOG.md
<add>* PostgreSQL invalid `uuid` are convert to nil.
<add>
<add> *Abdelkader Boudih*
<add>
<ide> * Fix the schema dump generated for tables without constraints and with
<ide> primary key with default value of custom PostgreSQL function result.
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/uuid.rb
<ide> module ConnectionAdapters
<ide> module PostgreSQL
<ide> module OID # :nodoc:
<ide> class Uuid < Type::Value # :nodoc:
<add> RFC_4122 = %r{\A\{?[a-fA-F0-9]{4}-?
<add> [a-fA-F0-9]{4}-?
<add> [a-fA-F0-9]{4}-?
<add> [1-5][a-fA-F0-9]{3}-?
<add> [8-Bab][a-fA-F0-9]{3}-?
<add> [a-fA-F0-9]{4}-?
<add> [a-fA-F0-9]{4}-?
<add> [a-fA-F0-9]{4}-?\}?\z}x
<add>
<ide> def type
<ide> :uuid
<ide> end
<ide>
<ide> def type_cast(value)
<del> value.presence
<add> value.to_s[RFC_4122, 0]
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/adapters/postgresql/uuid_test.rb
<ide> def test_treat_blank_uuid_as_nil
<ide> assert_equal(nil, UUIDType.last.guid)
<ide> end
<ide>
<add> def test_treat_invalid_uuid_as_nil
<add> uuid = UUIDType.create! guid: 'foobar'
<add> assert_equal(nil, uuid.guid)
<add> end
<add>
<add> def test_invalid_uuid_dont_modify_before_type_cast
<add> uuid = UUIDType.new guid: 'foobar'
<add> assert_equal 'foobar', uuid.guid_before_type_cast
<add> end
<add>
<add> def test_rfc_4122_regex
<add> # Valid uuids
<add> ['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11',
<add> '{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}',
<add> 'a0eebc999c0b4ef8bb6d6bb9bd380a11',
<add> 'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11',
<add> '{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}'].each do |valid_uuid|
<add> uuid = UUIDType.new guid: valid_uuid
<add> assert_not_nil uuid.guid
<add> end
<add>
<add> # Invalid uuids
<add> [['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'],
<add> Hash.new,
<add> 0,
<add> 0.0,
<add> true,
<add> 'Z0000C99-9C0B-4EF8-BB6D-6BB9BD380A11',
<add> '{a0eebc99-9c0b-4ef8-fb6d-6bb9bd380a11}',
<add> 'a0eebc999r0b4ef8ab6d6bb9bd380a11',
<add> 'a0ee-bc99------4ef8-bb6d-6bb9-bd38-0a11',
<add> '{a0eebc99-bb6d6bb9-bd380a11}'].each do |invalid_uuid|
<add> uuid = UUIDType.new guid: invalid_uuid
<add> assert_nil uuid.guid
<add> end
<add> end
<add>
<ide> def test_uuid_formats
<ide> ["A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11",
<ide> "{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}", | 3 |
Python | Python | add test for poisson exceptions | df09a3feb85079eadb91a5d200494ee3de721c56 | <ide><path>numpy/random/tests/test_random.py
<del>from numpy.testing import TestCase, run_module_suite, assert_
<add>from numpy.testing import TestCase, run_module_suite, assert_,\
<add> assert_raises
<ide> from numpy import random
<ide> import numpy as np
<ide>
<ide> def test_poisson(self):
<ide> [0, 0]])
<ide> np.testing.assert_array_equal(actual, desired)
<ide>
<add> def test_poisson_exceptions(self):
<add> lambig = np.iinfo('l').max
<add> lamneg = -1
<add> assert_raises(ValueError, np.random.poisson, lamneg)
<add> assert_raises(ValueError, np.random.poisson, [lamneg]*10)
<add> assert_raises(ValueError, np.random.poisson, lambig)
<add> assert_raises(ValueError, np.random.poisson, [lambig]*10)
<add>
<ide> def test_power(self):
<ide> np.random.seed(self.seed)
<ide> actual = np.random.power(a =.123456789, size = (3, 2)) | 1 |
PHP | PHP | add all method to console kernel | 81614916082260c524b5a178e896f3f0ce79b820 | <ide><path>src/Illuminate/Contracts/Console/Kernel.php
<ide> public function handle($input, $output = null);
<ide> */
<ide> public function call($command, array $parameters = array());
<ide>
<add> /**
<add> * Get all of the commands registered with the console.
<add> *
<add> * @return array
<add> */
<add> public function all();
<add>
<ide> /**
<ide> * Get the output for the last run command.
<ide> *
<ide><path>src/Illuminate/Foundation/Console/Kernel.php
<ide> public function call($command, array $parameters = array())
<ide> return $this->getArtisan()->call($command, $parameters);
<ide> }
<ide>
<add> /**
<add> * Get all of the commands registered with the console.
<add> *
<add> * @return array
<add> */
<add> public function all()
<add> {
<add> $this->bootstrap();
<add>
<add> return $this->getArtisan()->all();
<add> }
<add>
<ide> /**
<ide> * Get the output for the last run command.
<ide> * | 2 |
Javascript | Javascript | fix some bugs in keystream | 7bb4a5bb8339c0aa0db9afe707989a6fd4aecef7 | <ide><path>packages/ember-metal/lib/streams/key-stream.js
<ide> function KeyStream(source, key) {
<ide>
<ide> this.init();
<ide> this.source = source;
<del> this.obj = undefined;
<add> this.dependency = this.addDependency(source);
<add> this.observedObject = undefined;
<ide> this.key = key;
<ide> }
<ide>
<ide> KeyStream.prototype = create(Stream.prototype);
<ide>
<ide> merge(KeyStream.prototype, {
<ide> compute() {
<del> var obj = read(this.source);
<del> if (obj) {
<del> return get(obj, this.key);
<add> var object = read(this.source);
<add> if (object) {
<add> return get(object, this.key);
<ide> }
<ide> },
<ide>
<ide> becameActive() {
<del> if (this.obj && typeof this.obj === 'object') {
<del> addObserver(this.obj, this.key, this, this.notify);
<add> var object = read(this.source);
<add> if (object && typeof object === 'object') {
<add> addObserver(object, this.key, this, this.notify);
<add> this.observedObject = object;
<ide> }
<ide>
<del> if (nextObj) {
<del> return get(nextObj, this.key);
<add> becameInactive() {
<add> if (this.observedObject) {
<add> removeObserver(this.observedObject, this.key, this, this.notify);
<add> this.observedObject = undefined;
<ide> }
<ide> },
<ide>
<ide> setValue(value) {
<del> if (this.obj) {
<del> set(this.obj, this.key, value);
<add> var object = read(this.source);
<add> if (object) {
<add> set(object, this.key, value);
<ide> }
<ide> },
<ide>
<ide> merge(KeyStream.prototype, {
<ide> this.update(function() {
<ide> this.dependency.replace(nextSource);
<ide> this.source = nextSource;
<del> this.obj = read(nextSource);
<ide> });
<ide> }
<ide>
<ide> merge(KeyStream.prototype, {
<ide> }
<ide>
<ide> this.source = undefined;
<del> this.obj = undefined;
<ide> return true;
<ide> }
<ide> } | 1 |
Javascript | Javascript | add test for `#with view as foo` | c6a8f46f3e9337ccfa962f6a86ee3204758210e8 | <ide><path>packages/ember-handlebars/tests/helpers/with_test.js
<ide> test("it should support #with Foo.bar as qux", function() {
<ide> equal(view.$().text(), "updated", "should update");
<ide> });
<ide>
<add>module("Handlebars {{#with keyword as foo}}");
<add>
<add>test("it should support #with view as foo", function() {
<add> var view = Ember.View.create({
<add> template: Ember.Handlebars.compile("{{#with view as myView}}{{myView.name}}{{/with}}"),
<add> name: "Sonics"
<add> });
<add>
<add> appendView(view);
<add> equal(view.$().text(), "Sonics", "should be properly scoped");
<add>
<add> Ember.run(function() {
<add> Ember.setPath(view, 'name', "Thunder");
<add> });
<add>
<add> equal(view.$().text(), "Thunder", "should update");
<add>});
<add>
<ide> if (Ember.VIEW_PRESERVES_CONTEXT) {
<ide> module("Handlebars {{#with this as foo}}");
<ide> | 1 |
Text | Text | add 4.1.0-beta.1 to changelog | 0c0f62e5e13e856d228c44becd0fd5c5fbf99db7 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.1.0-beta.1 (November 19, 2021)
<add>
<add>- [#19772](https://github.com/emberjs/ember.js/pull/19772) / [#19826](https://github.com/emberjs/ember.js/pull/19826) [FEATURE] Add a `@cached` decorator per [RFC #0566](https://github.com/emberjs/rfcs/blob/af64915b5ecde010fce09309a47ee6d2447588d0/text/0566-memo-decorator.md).
<add>- [#19471](https://github.com/emberjs/ember.js/pull/19471) / [#19834](https://github.com/emberjs/ember.js/pull/19834) [FEATURE] Add `refresh` method to the Router Service per [RFC #0631](https://github.com/emberjs/rfcs/blob/master/text/0631-refresh-method-for-router-service.md).
<add>- [#19776](https://github.com/emberjs/ember.js/pull/19776) [FEATURE] Provide `service` export from `@ember/service` in favour of `inject` implementing [RFC #0752](https://github.com/emberjs/rfcs/blob/master/text/0752-inject-service.md).
<add>- [#19510](https://github.com/emberjs/ember.js/pull/19510) [DEPRECATION] Deprecate auto location per [RFC #0711](https://github.com/emberjs/rfcs/blob/master/text/0711-deprecate-auto-location.md).
<add>- [#17570](https://github.com/emberjs/ember.js/pull/17570) [BUGFIX] Passing ObjectProxy with a property size to `isEmpty` would throw assertion
<add>- [#18269](https://github.com/emberjs/ember.js/pull/18269) [BUGFIX] Fix for when query params are using a nested value
<add>- [#19787](https://github.com/emberjs/ember.js/pull/19787) Setup basic infrastructure to ensure destroyables destroyed
<add>
<ide> ### v4.0.0 (November 15, 2021)
<ide>
<ide> - [#19761](https://github.com/emberjs/ember.js/pull/19761) [BREAKING] Require ember-auto-import >= 2 or higher to enable ember-source to become a v2 addon in the 4.x cycle | 1 |
Ruby | Ruby | use the association directly in other places too | 31d101879f1acae604d24d831a4b82a4482acf31 | <ide><path>activerecord/lib/active_record/associations/association_collection.rb
<ide> def count(column_name = nil, options = {})
<ide>
<ide> @reflection.klass.count_by_sql(custom_counter_sql)
<ide> else
<del>
<ide> if @reflection.options[:uniq]
<ide> # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL.
<ide> column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" unless column_name
<ide> options.merge!(:distinct => true)
<ide> end
<ide>
<del> value = @reflection.klass.send(:with_scope, @scope) { @reflection.klass.count(column_name, options) }
<add> value = scoped.count(column_name, options)
<ide>
<ide> limit = @reflection.options[:limit]
<ide> offset = @reflection.options[:offset]
<ide> def create_record(attrs, &block)
<ide> ensure_owner_is_persisted!
<ide>
<ide> transaction do
<del> with_scope(:create => @scope[:create].merge(scoped.scope_for_create)) do
<del> build_record(attrs, &block)
<del> end
<add> scoped.scoping { build_record(attrs, &block) }
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb
<ide> def count_records
<ide> elsif @reflection.options[:counter_sql] || @reflection.options[:finder_sql]
<ide> @reflection.klass.count_by_sql(custom_counter_sql)
<ide> else
<del> @reflection.klass.count(@scope[:find].slice(:conditions, :joins, :include))
<add> scoped.count
<ide> end
<ide>
<ide> # If there's nothing in the database and @target has no new records
<ide> def delete_records(records)
<ide> updates = { @reflection.foreign_key => nil }
<ide> conditions = { @reflection.association_primary_key => records.map { |r| r.id } }
<ide>
<del> with_scope(@scope) do
<del> @reflection.klass.update_all(updates, conditions)
<del> end
<add> scoped.where(conditions).update_all(updates)
<ide> end
<ide>
<ide> if has_cached_counter? && @reflection.options[:dependent] != :destroy
<ide><path>activerecord/lib/active_record/associations/has_one_association.rb
<ide> def replace(obj, dont_save = false)
<ide>
<ide> private
<ide> def find_target
<del> options = @reflection.options.dup.slice(:select, :order, :include, :readonly)
<del>
<del> the_target = with_scope(:find => @scope[:find]) do
<del> @reflection.klass.find(:first, options)
<del> end
<del> set_inverse_instance(the_target)
<del> the_target
<add> scoped.first.tap { |record| set_inverse_instance(record) }
<ide> end
<ide>
<ide> def construct_find_scope
<del> { :conditions => construct_conditions }
<add> {
<add> :conditions => construct_conditions,
<add> :select => @reflection.options[:select],
<add> :include => @reflection.options[:include],
<add> :readonly => @reflection.options[:readonly],
<add> :order => @reflection.options[:order]
<add> }
<ide> end
<ide>
<ide> def construct_create_scope
<ide> def new_record(replace_existing)
<ide> # instance. Otherwise, if the target has not previously been loaded
<ide> # elsewhere, the instance we create will get orphaned.
<ide> load_target if replace_existing
<del> record = @reflection.klass.send(:with_scope, :create => @scope[:create]) do
<del> yield @reflection
<del> end
<add> record = scoped.scoping { yield @reflection }
<ide>
<ide> if replace_existing
<ide> replace(record, true) | 3 |
Go | Go | add only legacy plugins to the legacy lookup map | 8fd779dc28a11d8727d76e9553379b0c854f7c4c | <ide><path>pkg/plugins/plugins.go
<ide> func (p *Plugin) Client() *Client {
<ide> return p.client
<ide> }
<ide>
<add>// IsLegacy returns true for legacy plugins and false otherwise.
<add>func (p *Plugin) IsLegacy() bool {
<add> return true
<add>}
<add>
<ide> // NewLocalPlugin creates a new local plugin.
<ide> func NewLocalPlugin(name, addr string) *Plugin {
<ide> return &Plugin{
<ide><path>plugin/interface.go
<ide> import "github.com/docker/docker/pkg/plugins"
<ide> type Plugin interface {
<ide> Client() *plugins.Client
<ide> Name() string
<add> IsLegacy() bool
<ide> }
<ide><path>plugin/manager.go
<ide> func (p *plugin) Client() *plugins.Client {
<ide> return p.client
<ide> }
<ide>
<add>// IsLegacy returns true for legacy plugins and false otherwise.
<add>func (p *plugin) IsLegacy() bool {
<add> return false
<add>}
<add>
<ide> func (p *plugin) Name() string {
<ide> name := p.P.Name
<ide> if len(p.P.Tag) > 0 {
<ide><path>volume/drivers/extpoint.go
<ide> func lookup(name string) (volume.Driver, error) {
<ide> return nil, err
<ide> }
<ide>
<del> drivers.extensions[name] = d
<add> if p.IsLegacy() {
<add> drivers.extensions[name] = d
<add> }
<ide> return d, nil
<ide> }
<ide>
<ide> func GetAllDrivers() ([]volume.Driver, error) {
<ide> }
<ide>
<ide> ext = NewVolumeDriver(name, p.Client())
<del> drivers.extensions[name] = ext
<add> if p.IsLegacy() {
<add> drivers.extensions[name] = ext
<add> }
<ide> ds = append(ds, ext)
<ide> }
<ide> return ds, nil | 4 |
Mixed | Ruby | add support for conditional values to tagbuilder | f1c63d8673e87589a0543075534e7ad03b8bd93f | <ide><path>actionview/CHANGELOG.md
<add>* Add support for conditional values to TagBuilder.
<add>
<add> *Joel Hawksley*
<add>
<ide> * Fix `select_tag` so that it doesn't change `options` when `include_blank` is present.
<ide>
<ide> *Younes SERRAJ*
<ide><path>actionview/lib/action_view/helpers/tag_helper.rb
<ide> def boolean_tag_option(key)
<ide> end
<ide>
<ide> def tag_option(key, value, escape)
<del> if value.is_a?(Array)
<add> case value
<add> when Array, Hash
<add> value = build_tag_values(value)
<ide> value = escape ? safe_join(value, " ") : value.join(" ")
<ide> else
<ide> value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s.dup
<ide> def tag_option(key, value, escape)
<ide> end
<ide>
<ide> private
<add>
<add> def build_tag_values(*args)
<add> tag_values = []
<add>
<add> args.each do |tag_value|
<add> case tag_value
<add> when String
<add> tag_values << tag_value if tag_value.present?
<add> when Hash
<add> tag_value.each do |key, val|
<add> tag_values << key if val
<add> end
<add> when Array
<add> tag_values << build_tag_values(*tag_value).presence
<add> end
<add> end
<add>
<add> tag_values.compact.flatten
<add> end
<add>
<ide> def prefix_tag_option(prefix, key, value, escape)
<ide> key = "#{prefix}-#{key.to_s.dasherize}"
<ide> unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal)
<ide> def method_missing(called, *args, &block)
<ide> #
<ide> # tag("div", data: { name: 'Stephen', city_state: %w(Chicago IL) })
<ide> # # => <div data-name="Stephen" data-city-state="["Chicago","IL"]" />
<add> #
<add> # tag("div", class: { highlight: current_user.admin? })
<add> # # => <div class="highlight" />
<ide> def tag(name = nil, options = nil, open = false, escape = true)
<ide> if name.nil?
<ide> tag_builder
<ide> def tag(name = nil, options = nil, open = false, escape = true)
<ide> # # => <div class="strong"><p>Hello world!</p></div>
<ide> # content_tag(:div, "Hello world!", class: ["strong", "highlight"])
<ide> # # => <div class="strong highlight">Hello world!</div>
<add> # content_tag(:div, "Hello world!", class: ["strong", { highlight: current_user.admin? }])
<add> # # => <div class="strong highlight">Hello world!</div>
<ide> # content_tag("select", options, multiple: true)
<ide> # # => <select multiple="multiple">...options...</select>
<ide> #
<ide><path>actionview/test/template/tag_helper_test.rb
<ide> def test_tag_builder_with_unescaped_empty_array_class
<ide> assert_equal '<p class="">limelight</p>', str
<ide> end
<ide>
<add> def test_content_tag_with_conditional_hash_classes
<add> str = content_tag("p", "limelight", class: { "song": true, "play": false })
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: [{ "song": true }, { "play": false }])
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: { song: true, play: false })
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: [{ song: true}, nil, false])
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: ["song", { foo: false}])
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: { "song": true, "play": true })
<add> assert_equal "<p class=\"song play\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", class: { "song": false, "play": false })
<add> assert_equal '<p class="">limelight</p>', str
<add> end
<add>
<add> def test_tag_builder_with_conditional_hash_classes
<add> str = tag.p "limelight", class: { "song": true, "play": false }
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: [{ "song": true }, { "play": false }]
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: { song: true, play: false }
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: [{ song: true}, nil, false]
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: ["song", { foo: false}]
<add> assert_equal "<p class=\"song\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: { "song": true, "play": true }
<add> assert_equal "<p class=\"song play\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: { "song": false, "play": false }
<add> assert_equal '<p class="">limelight</p>', str
<add> end
<add>
<add> def test_content_tag_with_unescaped_conditional_hash_classes
<add> str = content_tag("p", "limelight", { class: { "song": true, "play>": true } }, false)
<add> assert_equal "<p class=\"song play>\">limelight</p>", str
<add>
<add> str = content_tag("p", "limelight", { class: ["song", { "play>": true }] }, false)
<add> assert_equal "<p class=\"song play>\">limelight</p>", str
<add> end
<add>
<add> def test_tag_builder_with_unescaped_conditional_hash_classes
<add> str = tag.p "limelight", class: { "song": true, "play>": true }, escape_attributes: false
<add> assert_equal "<p class=\"song play>\">limelight</p>", str
<add>
<add> str = tag.p "limelight", class: ["song", { "play>": true }], escape_attributes: false
<add> assert_equal "<p class=\"song play>\">limelight</p>", str
<add> end
<add>
<ide> def test_content_tag_with_data_attributes
<ide> assert_dom_equal '<p data-number="1" data-string="hello" data-string-with-quotes="double"quote"party"">limelight</p>',
<ide> content_tag("p", "limelight", data: { number: 1, string: "hello", string_with_quotes: 'double"quote"party"' }) | 3 |
Ruby | Ruby | move skeleton methods from av to absc | aea02eb43001d85def0e69dce76fde0757040089 | <ide><path>actionpack/lib/abstract_controller/rendering.rb
<ide> module Rendering
<ide> self.protected_instance_variables = []
<ide> end
<ide>
<add> # Normalize arguments, options and then delegates render_to_body and
<add> # sticks the result in self.response_body.
<add> # :api: public
<add> def render(*args, &block)
<add> end
<add>
<ide> # Raw rendering of a template to a string.
<ide> #
<ide> # It is similar to render, except that it does not
<ide> module Rendering
<ide> # overridden in order to still return a string.
<ide> # :api: plugin
<ide> def render_to_string(*args, &block)
<add> options = _normalize_render(*args, &block)
<add> render_to_body(options)
<ide> end
<ide>
<ide> # Raw rendering of a template.
<del> # :api: plugin
<del> def render_to_body(options = {})
<del> end
<del>
<del> # Normalize arguments, options and then delegates render_to_body and
<del> # sticks the result in self.response_body.
<ide> # :api: public
<del> def render(*args, &block)
<add> def render_to_body(options = {})
<add> _process_options(options)
<add> _render_template(options)
<ide> end
<ide>
<ide> # Return Content-Type of rendered content
<ide> def _normalize_options(options)
<ide> def _process_options(options)
<ide> options
<ide> end
<add>
<add> # Normalize args and options.
<add> # :api: private
<add> def _normalize_render(*args, &block)
<add> options = _normalize_args(*args, &block)
<add> _normalize_options(options)
<add> options
<add> end
<ide> end
<ide> end
<ide><path>actionview/lib/action_view/rendering.rb
<ide> def render(*args, &block)
<ide> self.response_body = render_to_body(options)
<ide> end
<ide>
<del> # Raw rendering of a template to a string.
<del> # :api: public
<del> def render_to_string(*args, &block)
<del> options = _normalize_render(*args, &block)
<del> render_to_body(options)
<del> end
<del>
<del> # Raw rendering of a template.
<del> # :api: public
<del> def render_to_body(options = {})
<del> _process_options(options)
<del> _render_template(options)
<del> end
<del>
<ide> # Find and renders a template based on the options given.
<ide> # :api: private
<ide> def _render_template(options) #:nodoc:
<ide> def rendered_format
<ide>
<ide> private
<ide>
<del> # Normalize args and options.
<del> # :api: private
<del> def _normalize_render(*args, &block)
<del> options = _normalize_args(*args, &block)
<del> _normalize_options(options)
<del> options
<del> end
<del>
<ide> # Normalize args by converting render "foo" to render :action => "foo" and
<ide> # render "foo/bar" to render :file => "foo/bar".
<ide> # :api: private | 2 |
Text | Text | remove dot character from "pagination_class" | d0995fac70549bd8a4bba4510ab89b95f59ba622 | <ide><path>docs/api-guide/pagination.md
<ide> If you want to modify particular aspects of the pagination style, you'll want to
<ide> page_size_query_param = 'page_size'
<ide> max_page_size = 1000
<ide>
<del>You can then apply your new style to a view using the `.pagination_class` attribute:
<add>You can then apply your new style to a view using the `pagination_class` attribute:
<ide>
<ide> class BillingRecordsView(generics.ListAPIView):
<ide> queryset = Billing.objects.all() | 1 |
Go | Go | make libnetwork compile on freebsd (again) | 94ca1f5bba1aff9c58f9c53390c18a3aef7629f0 | <ide><path>libnetwork/sandbox/interface_freebsd.go
<add>package sandbox
<add>
<add>// IfaceOption is a function option type to set interface options
<add>type IfaceOption func()
<ide><path>libnetwork/sandbox/namespace_unsupported.go
<del>// +build !linux,!windows
<add>// +build !linux,!windows,!freebsd
<ide>
<ide> package sandbox
<ide>
<ide><path>libnetwork/sandbox/neigh_freebsd.go
<add>package sandbox
<add>
<add>// NeighOption is a function option type to set neighbor options
<add>type NeighOption func()
<ide><path>libnetwork/sandbox/sandbox_freebsd.go
<add>package sandbox
<add>
<add>// GenerateKey generates a sandbox key based on the passed
<add>// container id.
<add>func GenerateKey(containerID string) string {
<add> maxLen := 12
<add> if len(containerID) < maxLen {
<add> maxLen = len(containerID)
<add> }
<add>
<add> return containerID[:maxLen]
<add>}
<add>
<add>// NewSandbox provides a new sandbox instance created in an os specific way
<add>// provided a key which uniquely identifies the sandbox
<add>func NewSandbox(key string, osCreate bool) (Sandbox, error) {
<add> return nil, nil
<add>}
<add>
<add>// GC triggers garbage collection of namespace path right away
<add>// and waits for it.
<add>func GC() {
<add>}
<ide><path>libnetwork/sandbox/sandbox_unsupported.go
<del>// +build !linux,!windows
<add>// +build !linux,!windows,!freebsd
<ide>
<ide> package sandbox
<ide> | 5 |
Javascript | Javascript | use the worker | c466450aae05bd29e72d2356b647a6e595a377c8 | <ide><path>worker.js
<ide> var WorkerPDFDoc = (function() {
<ide>
<ide> this.pageCache = [];
<ide>
<del> var useWorker = false;
<add> var useWorker = true;
<ide>
<ide> if (useWorker) {
<ide> var worker = new Worker("../worker/boot.js"); | 1 |
Python | Python | update configure for node.js 12 | 41ba699973388f7ff7464e1606457c630a8189f9 | <ide><path>configure.py
<ide> def check_compiler(o):
<ide> ok, is_clang, clang_version, gcc_version = try_check_compiler(CXX, 'c++')
<ide> if not ok:
<ide> warn('failed to autodetect C++ compiler version (CXX=%s)' % CXX)
<del> elif sys.platform.startswith('aix') and gcc_version < (6, 3, 0):
<del> warn('C++ compiler too old, need g++ 6.3.0 (CXX=%s)' % CXX)
<del> elif clang_version < (3, 4, 2) if is_clang else gcc_version < (4, 9, 4):
<del> warn('C++ compiler too old, need g++ 4.9.4 or clang++ 3.4.2 (CXX=%s)' % CXX)
<add> elif clang_version < (8, 0, 0) if is_clang else gcc_version < (6, 3, 0):
<add> warn('C++ compiler too old, need g++ 6.3.0 or clang++ 8.0.0 (CXX=%s)' % CXX)
<ide>
<ide> ok, is_clang, clang_version, gcc_version = try_check_compiler(CC, 'c')
<ide> if not ok: | 1 |
Text | Text | fix syntax in n-api documentation | b4f745ec5ae515c35aa57c576b997bb1d7f96437 | <ide><path>doc/api/n-api.md
<ide> napiVersion: 1
<ide> ```C
<ide> NAPI_EXTERN napi_status napi_reference_unref(napi_env env,
<ide> napi_ref ref,
<del> uint32_t* result););
<add> uint32_t* result);
<ide> ```
<ide>
<ide> * `[in] env`: The environment that the API is invoked under. | 1 |
Python | Python | add testcase for the fix to bug | 00ee332e9d95362a3d487f784cdc8fc06cf0832c | <ide><path>numpy/ma/tests/test_core.py
<ide> def test_fillvalue_exotic_dtype(self):
<ide> control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype)
<ide> assert_equal(_check_fill_value(0, ndtype), control)
<ide>
<add> def test_fillvalue_datetime_timedelta(self):
<add> # Test default fillvalue for datetime64 and timedelta64 types.
<add> # See issue #4476, this would return '?' which would cause errors
<add> # elsewhere
<add>
<add> for timecode in ("as", "fs", "ps", "ns", "us", "ms", "s", "m",
<add> "h", "D", "W", "M", "Y"):
<add> control = numpy.datetime64("NaT", timecode)
<add> test = default_fill_value(numpy.dtype("<M8[" + timecode + "]"))
<add> assert_equal(test, control)
<add>
<add> control = numpy.timedelta64("NaT", timecode)
<add> test = default_fill_value(numpy.dtype("<m8[" + timecode + "]"))
<add> assert_equal(test, control)
<add>
<ide> def test_extremum_fill_value(self):
<ide> # Tests extremum fill values for flexible type.
<ide> a = array([(1, (2, 3)), (4, (5, 6))], | 1 |
Go | Go | add daniel lewin to names collection | bc0e2f1a6ebf6f9235ee8aa921570533db1ec57a | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> // Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt
<ide> "leavitt",
<ide>
<add> //Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin
<add> "lewin",
<add>
<ide> // Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum
<ide> "lichterman",
<ide> | 1 |
Ruby | Ruby | add pre-defined variant examples | 0d1633c8c7a3e7d645c7d0aa8e9c59594c6ea94b | <ide><path>activestorage/app/models/active_storage/attachment.rb
<ide> def purge_later
<ide>
<ide> # Returns an ActiveStorage::Variant or ActiveStorage::VariantWithRecord
<ide> # instance for the attachment with the set of +transformations+ provided.
<add> # Example:
<add> #
<add> # avatar.variant(resize_to_limit: [100, 100]).processed.url
<add> #
<add> # or if you are using pre-defined variants:
<add> #
<add> # avatar.variant(:thumb).processed.url
<add> #
<ide> # See ActiveStorage::Blob::Representable#variant for more information.
<ide> #
<ide> # Raises an +ArgumentError+ if +transformations+ is a +Symbol+ which is an
<ide> def variant(transformations)
<ide>
<ide> # Returns an ActiveStorage::Preview instance for the attachment with the set
<ide> # of +transformations+ provided.
<add> # Example:
<add> #
<add> # video.preview(resize_to_limit: [100, 100]).processed.url
<add> #
<add> # or if you are using pre-defined variants:
<add> #
<add> # video.preview(:thumb).processed.url
<add> #
<ide> # See ActiveStorage::Blob::Representable#preview for more information.
<ide> #
<ide> # Raises an +ArgumentError+ if +transformations+ is a +Symbol+ which is an
<ide> def preview(transformations)
<ide>
<ide> # Returns an ActiveStorage::Preview or an ActiveStorage::Variant for the
<ide> # attachment with set of +transformations+ provided.
<add> # Example:
<add> #
<add> # avatar.representation(resize_to_limit: [100, 100]).processed.url
<add> #
<add> # or if you are using pre-defined variants:
<add> #
<add> # avatar.representation(:thumb).processed.url
<add> #
<ide> # See ActiveStorage::Blob::Representable#representation for more information.
<ide> #
<ide> # Raises an +ArgumentError+ if +transformations+ is a +Symbol+ which is an | 1 |
Javascript | Javascript | improve docs for coreobject#concatenatedproperties | d74fb5479b8b0a0a9dc2c6f78d728b6bc8bc048f | <ide><path>packages/ember-runtime/lib/system/core_object.js
<ide> CoreObject.PrototypeMixin = Mixin.create({
<ide> are also concatenated, in addition to `classNames`.
<ide>
<ide> This feature is available for you to use throughout the Ember object model,
<del> although typical app developers are likely to use it infrequently.
<add> although typical app developers are likely to use it infrequently. Since
<add> it changes expectations about behavior of properties, you should properly
<add> document its usage in each individual concatenated property (to not
<add> mislead your users to think they can override the property in a subclass).
<ide>
<ide> @property concatenatedProperties
<ide> @type Array | 1 |
Ruby | Ruby | generate unique patch filenames | 54f1837d237b2c1b09d96815bd8a990ac1c951e5 | <ide><path>Library/Homebrew/patches.rb
<ide> class Patches
<ide> def initialize patches
<ide> @patches = []
<ide> return if patches.nil?
<del>
<add> n = 0
<ide> normalize_patches(patches).each do |patch_p, urls|
<ide> # Wrap the urls list in an array if it isn't already;
<ide> # DATA.each does each line, which doesn't work so great
<ide> urls = [urls] unless urls.kind_of? Array
<del> urls.each_with_index do |url, n|
<add> urls.each do |url|
<ide> @patches << Patch.new(patch_p, '%03d-homebrew.diff' % n, url)
<add> n += 1
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | replace regex with instanceof check | 2d6ab89201cbc07e25ecfcb9007fa98873641154 | <ide><path>src/Database/Driver/Sqlserver.php
<ide> class Sqlserver extends \Cake\Database\Driver
<ide> 'username' => '',
<ide> 'password' => '',
<ide> 'database' => 'cake',
<del> 'encoding' => PDO::SQLSRV_ENCODING_UTF8,
<add> // PDO::SQLSRV_ENCODING_UTF8
<add> 'encoding' => 65001,
<ide> 'flags' => [],
<ide> 'init' => [],
<ide> 'settings' => [],
<ide><path>src/Database/Type/BinaryType.php
<ide>
<ide> use Cake\Core\Exception\Exception;
<ide> use Cake\Database\Driver;
<add>use Cake\Database\Driver\Sqlserver;
<ide> use Cake\Database\Type;
<ide> use PDO;
<ide>
<ide> public function toPHP($value, Driver $driver)
<ide> if ($value === null) {
<ide> return null;
<ide> }
<del> if (is_string($value) && preg_match('/^[a-zA-Z0-9]+$/', $value)) {
<add> if (is_string($value) && $driver instanceof Sqlserver) {
<ide> $value = pack('H*', $value);
<ide> }
<ide> if (is_string($value)) {
<ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php
<ide> public function testToPHP()
<ide> {
<ide> $this->assertNull($this->type->toPHP(null, $this->driver));
<ide>
<del> $result = $this->type->toPHP('536F6D652076616C7565', $this->driver);
<del> $this->assertInternalType('resource', $result);
<del> $this->assertSame('Some value', stream_get_contents($result));
<del>
<ide> $result = $this->type->toPHP('some data', $this->driver);
<ide> $this->assertInternalType('resource', $result);
<ide>
<ide> public function testToPHP()
<ide> fclose($fh);
<ide> }
<ide>
<add> /**
<add> * SQLServer returns binary fields as hexidecimal
<add> * Ensure decoding happens for SQLServer drivers
<add> *
<add> * @return void
<add> */
<add> public function testToPHPSqlserver()
<add> {
<add> $driver = $this->getMock('Cake\Database\Driver\Sqlserver', [], [], '', false);
<add> $result = $this->type->toPHP('536F6D652076616C7565', $driver);
<add> $this->assertInternalType('resource', $result);
<add> $this->assertSame('Some value', stream_get_contents($result));
<add> }
<add>
<ide> /**
<ide> * Test exceptions on invalid data.
<ide> * | 3 |
Text | Text | add table of contents in building.md | a21af5b1f2e337395482d1af788c1838bac7b713 | <ide><path>BUILDING.md
<ide> If you can reproduce a test failure consistently, search for it in the
<ide> [Node.js issue tracker](https://github.com/nodejs/node/issues) or
<ide> file a new issue.
<ide>
<add>## Table of Contents
<add>
<add>* [Supported platforms](#supported-platforms)
<add> * [Input](#input)
<add> * [Strategy](#strategy)
<add> * [Supported platforms](#supported-platforms-1)
<add> * [Supported toolchains](#supported-toolchains)
<add> * [Unix](#unix)
<add> * [AIX](#aix)
<add> * [Windows](#windows)
<add> * [OpenSSL asm support](#openssl-asm-support)
<add>* [Building Node.js on supported platforms](#building-nodejs-on-supported-platforms)
<add> * [Unix/macOS](#unixmacos)
<add> * [Prerequisites](#prerequisites)
<add> * [Building Node.js](#building-nodejs-1)
<add> * [Running Tests](#running-tests)
<add> * [Building the documentation](#building-the-documentation)
<add> * [Building a debug build](#building-a-debug-build)
<add> * [Windows](#windows-1)
<add> * [Android/Android-based devices (e.g. Firefox OS)](#androidandroid-based-devices-eg-firefox-os)
<add> * [`Intl` (ECMA-402) support](#intl-ecma-402-support)
<add> * [Default: `small-icu` (English only) support](#default-small-icu-english-only-support)
<add> * [Build with full ICU support (all locales supported by ICU)](#build-with-full-icu-support-all-locales-supported-by-icu)
<add> * [Unix/macOS](#unixmacos-1)
<add> * [Windows](#windows-2)
<add> * [Building without Intl support](#building-without-intl-support)
<add> * [Unix/macOS](#unixmacos-2)
<add> * [Windows](#windows-3)
<add> * [Use existing installed ICU (Unix/macOS only)](#use-existing-installed-icu-unixmacos-only)
<add> * [Build with a specific ICU](#build-with-a-specific-icu)
<add> * [Unix/macOS](#unixmacos-3)
<add> * [Windows](#windows-4)
<add>* [Building Node.js with FIPS-compliant OpenSSL](#building-nodejs-with-fips-compliant-openssl)
<add>* [Building Node.js with external core modules](#building-nodejs-with-external-core-modules)
<add> * [Unix/macOS](#unixmacos-4)
<add> * [Windows](#windows-5)
<add>
<ide> ## Supported platforms
<ide>
<ide> This list of supported platforms is current as of the branch/release to | 1 |
Java | Java | expand scope of springfailontimeouttests | 4f3a7dd9b4b4b95ccebf276185163cbdd815cb8d | <ide><path>spring-test/src/main/java/org/springframework/test/context/junit4/statements/SpringFailOnTimeout.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2018 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr16716/SpringFailOnTimeoutExceptionTest.java
<del>package org.springframework.test.context.junit4.spr16716;
<del>
<del>import org.junit.Test;
<del>import org.junit.runner.RunWith;
<del>import org.junit.runners.model.Statement;
<del>import org.mockito.Mock;
<del>import org.mockito.junit.MockitoJUnitRunner;
<del>import org.mockito.stubbing.Answer;
<del>import org.springframework.test.context.junit4.statements.SpringFailOnTimeout;
<del>
<del>import java.util.concurrent.TimeUnit;
<del>import java.util.concurrent.TimeoutException;
<del>
<del>import static org.mockito.Mockito.doAnswer;
<del>import static org.mockito.Mockito.doThrow;
<del>
<del>/**
<del> * Validate SpringFailOnTimeout contract
<del> * <a href="https://jira.spring.io/browse/SPR-16716" target="_blank">SPR-16716</a>.
<del> *
<del> * @author Igor Suhorukov
<del> * @since 5.0.6
<del> */
<del>@RunWith(MockitoJUnitRunner.class)
<del>public class SpringFailOnTimeoutExceptionTest {
<del>
<del> @Mock
<del> private Statement statement;
<del>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void validateOriginalExceptionFromEvaluateMethod() throws Throwable {
<del> IllegalArgumentException expectedException = new IllegalArgumentException();
<del> doThrow(expectedException).when(statement).evaluate();
<del> new SpringFailOnTimeout(statement, TimeUnit.SECONDS.toMillis(1)).evaluate();
<del> }
<del>
<del> @Test(expected = TimeoutException.class)
<del> public void validateTimeoutException() throws Throwable {
<del> doAnswer((Answer<Void>) invocation -> {
<del> TimeUnit.MILLISECONDS.sleep(50);
<del> return null;
<del> }).when(statement).evaluate();
<del> new SpringFailOnTimeout(statement, TimeUnit.MILLISECONDS.toMillis(1)).evaluate();
<del> }
<del>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/spr16716/SpringFailOnTimeoutTests.java
<add>/*
<add> * Copyright 2002-2018 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>
<add>package org.springframework.test.context.junit4.spr16716;
<add>
<add>import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.TimeoutException;
<add>
<add>import org.junit.Rule;
<add>import org.junit.Test;
<add>import org.junit.rules.ExpectedException;
<add>import org.junit.runners.model.Statement;
<add>import org.mockito.stubbing.Answer;
<add>
<add>import org.springframework.test.context.junit4.statements.SpringFailOnTimeout;
<add>
<add>import static org.mockito.Mockito.*;
<add>
<add>/**
<add> * Unit tests for {@link SpringFailOnTimeout}.
<add> *
<add> * @author Igor Suhorukov
<add> * @author Sam Brannen
<add> * @since 4.3.17
<add> */
<add>public class SpringFailOnTimeoutTests {
<add>
<add> private Statement statement = mock(Statement.class);
<add>
<add> @Rule
<add> public final ExpectedException exception = ExpectedException.none();
<add>
<add>
<add> @Test
<add> public void nullNextStatement() throws Throwable {
<add> exception.expect(IllegalArgumentException.class);
<add> new SpringFailOnTimeout(null, 1);
<add> }
<add>
<add> @Test
<add> public void negativeTimeout() throws Throwable {
<add> exception.expect(IllegalArgumentException.class);
<add> new SpringFailOnTimeout(statement, -1);
<add> }
<add>
<add> @Test
<add> public void userExceptionPropagates() throws Throwable {
<add> doThrow(new Boom()).when(statement).evaluate();
<add>
<add> exception.expect(Boom.class);
<add> new SpringFailOnTimeout(statement, 1).evaluate();
<add> }
<add>
<add> @Test
<add> public void timeoutExceptionThrownIfNoUserException() throws Throwable {
<add> doAnswer((Answer<Void>) invocation -> {
<add> TimeUnit.MILLISECONDS.sleep(50);
<add> return null;
<add> }).when(statement).evaluate();
<add>
<add> exception.expect(TimeoutException.class);
<add> new SpringFailOnTimeout(statement, 1).evaluate();
<add> }
<add>
<add> @Test
<add> public void noExceptionThrownIfNoUserExceptionAndTimeoutDoesNotOccur() throws Throwable {
<add> doAnswer((Answer<Void>) invocation -> {
<add> return null;
<add> }).when(statement).evaluate();
<add>
<add> new SpringFailOnTimeout(statement, 100).evaluate();
<add> }
<add>
<add> private static class Boom extends RuntimeException {
<add> }
<add>
<add>} | 3 |
Text | Text | add translation kr/threejs-material-table.md | 7be4e4279a6f2cf549bc7eaba9b346cdc6b4a223 | <ide><path>threejs/lessons/kr/threejs-material-table.md
<add>Title: 재질(Material) 속성표
<add>Description: Three.js의 각 재질이 지원하는 속성에 대한 표입니다
<add>TOC: 재질(Material) 속성표
<add>
<add>Three.js에서 주로 쓰는 재질(material)은 Mesh 재질입니다. 아래는 각 재질이 지원하는 속성을 표로 나타낸 것입니다.
<add>
<add><div>
<add><div id="material-table" class="threejs_center"></div>
<add><script type="module" src="../resources/threejs-material-table.js"></script>
<add><link rel="stylesheet" href="../resources/threejs-material-table.css">
<add></div>
<add> | 1 |
Ruby | Ruby | preserve installed_on_request for dependencies | ef82b188f2a3977b56db463ef2f0cb0c8f5727e9 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> def install_dependency(dep, inherited_options)
<ide> end
<ide>
<ide> fi = FormulaInstaller.new(df)
<del> fi.options |= tab.used_options
<del> fi.options |= Tab.remap_deprecated_options(df.deprecated_options, dep.options)
<del> fi.options |= inherited_options
<del> fi.options &= df.options
<del> fi.build_from_source = ARGV.build_formula_from_source?(df)
<del> fi.force_bottle = false
<del> fi.verbose = verbose?
<del> fi.quieter = quieter?
<del> fi.debug = debug?
<del> fi.link_keg = keg_was_linked if keg_had_linked_keg
<add> fi.options |= tab.used_options
<add> fi.options |= Tab.remap_deprecated_options(df.deprecated_options, dep.options)
<add> fi.options |= inherited_options
<add> fi.options &= df.options
<add> fi.build_from_source = ARGV.build_formula_from_source?(df)
<add> fi.force_bottle = false
<add> fi.verbose = verbose?
<add> fi.quieter = quieter?
<add> fi.debug = debug?
<add> fi.link_keg = keg_was_linked if keg_had_linked_keg
<ide> fi.installed_as_dependency = true
<del> fi.installed_on_request = false
<add> fi.installed_on_request = df.any_version_installed? && tab.installed_on_request
<ide> fi.prelude
<ide> oh1 "Installing #{formula.full_name} dependency: #{Formatter.identifier(dep.name)}"
<ide> fi.install | 1 |
Ruby | Ruby | provide a post title for sqlite3 | 18aa19c68a0ff2dbb3ab77eb35343b2e2a145441 | <ide><path>activerecord/test/cases/associations/eager_test.rb
<ide> def test_duplicate_middle_objects
<ide> end
<ide>
<ide> def test_including_duplicate_objects_from_belongs_to
<del> popular_post = Post.create!(:body => "I like cars!")
<add> popular_post = Post.create!(:title => 'foo', :body => "I like cars!")
<ide> comment = popular_post.comments.create!(:body => "lol")
<ide> popular_post.readers.create!(:person => people(:michael))
<ide> popular_post.readers.create!(:person => people(:david))
<ide> def test_including_duplicate_objects_from_belongs_to
<ide> end
<ide>
<ide> def test_including_duplicate_objects_from_has_many
<del> car_post = Post.create!(:body => "I like cars!")
<add> car_post = Post.create!(:title => 'foo', :body => "I like cars!")
<ide> car_post.categories << categories(:general)
<ide> car_post.categories << categories(:technology)
<ide> | 1 |
Python | Python | remove unused import | 0e02b74d418d742211c782dfa3e1377a270225e8 | <ide><path>libcloud/test/test_httplib_ssl.py
<ide> import os
<ide> import sys
<ide> import os.path
<del>import warnings
<ide>
<ide> from mock import patch
<ide> | 1 |
Ruby | Ruby | remove dead code | f906d13ef29c102839fd55250adbb01109e8404d | <ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def initialize test, command, options={}
<ide> @time = 0
<ide> end
<ide>
<del> def log_file_path full_path=true
<add> def log_file_path
<ide> file = "#{@category}.#{@name}.txt"
<del> return file unless @test.log_root and full_path
<del> @test.log_root + file
<add> root = @test.log_root
<add> root ? root + file : file
<ide> end
<ide>
<ide> def status_colour | 1 |
Python | Python | update is_new_osx function | 1bf2082ac48ab02300177c8a630e2fa5e74b7b7d | <ide><path>setup.py
<ide> #!/usr/bin/env python
<ide> import sys
<add>import platform
<ide> from distutils.command.build_ext import build_ext
<ide> from distutils.sysconfig import get_python_inc
<ide> import distutils.util
<ide>
<ide>
<ide> def is_new_osx():
<del> """Check whether we're on OSX >= 10.10"""
<add> """Check whether we're on OSX >= 10.7"""
<ide> name = distutils.util.get_platform()
<ide> if sys.platform != "darwin":
<ide> return False
<del> elif name.startswith("macosx-10"):
<del> minor_version = int(name.split("-")[1].split(".")[1])
<add> mac_ver = platform.mac_ver()[0]
<add> if mac_ver.startswith("10"):
<add> minor_version = int(mac_ver.split('.')[1])
<ide> if minor_version >= 7:
<ide> return True
<ide> else:
<ide> return False
<del> else:
<del> return False
<add> return False
<ide>
<ide>
<ide> if is_new_osx(): | 1 |
Ruby | Ruby | remove trailing newline check | 3546c39581aac81e811c7ab26aab0be10c490a8a | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_file
<ide> problem "'inreplace ... do' was used for a single substitution (use the non-block form instead)."
<ide> end
<ide>
<del> problem "File should end with a newline" unless text.trailing_newline?
<del>
<ide> if formula.core_formula? && @versioned_formula
<ide> unversioned_formula = begin
<ide> # build this ourselves as we want e.g. homebrew/core to be present | 1 |
Javascript | Javascript | replace fixturesdir with fixtures module | b93285454ac96952a33ed9655661c2bbea35667f | <ide><path>test/es-module/test-esm-encoded-path-native.js
<ide> 'use strict';
<del>const common = require('../common');
<add>require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> const assert = require('assert');
<ide> const { spawn } = require('child_process');
<ide>
<del>const native = `${common.fixturesDir}/es-module-url/native.mjs`;
<add>const native = fixtures.path('es-module-url/native.mjs');
<ide> const child = spawn(process.execPath, ['--experimental-modules', native]);
<ide> child.on('exit', (code) => {
<ide> assert.strictEqual(code, 1); | 1 |
Javascript | Javascript | improve implementation accordingly to pr reviews | 4510e9311f7477547e82cbed7894772635e88a84 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> } else {
<ide>
<del> geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + primitiveDef.mode;
<add> geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
<ide>
<ide> }
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> for ( var i = 0, il = keys.length; i < il; i ++ ) {
<ide>
<del> attributesKey += keys[ i ] + attributes[ keys[ i ] ];
<add> attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
<ide>
<ide> }
<ide>
<ide> return attributesKey;
<ide>
<ide> }
<ide>
<del> function createArrayKey( a ) {
<add> function createArrayKeyBufferGeometry( a ) {
<ide>
<ide> var arrayKey = '';
<ide>
<ide> for ( var i = 0, il = a.length; i < il; i ++ ) {
<ide>
<del> arrayKey += i + createAttributesKey( a[ i ] );
<add> arrayKey += i + a[ i ].uuid;
<add>
<add> }
<add>
<add> return arrayKey;
<add>
<add> }
<add>
<add> function createArrayKeyGLTFPrimitive( a ) {
<add>
<add> var arrayKey = '';
<add>
<add> for ( var i = 0, il = a.length; i < il; i ++ ) {
<add>
<add> arrayKey += i + createGeometryKey( a[ i ] );
<ide>
<ide> }
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> function createMultiPassGeometryKey( geometry, primitives ) {
<ide>
<del> return createGeometryKey( geometry ) + createArrayKey( primitives );
<add> return createGeometryKey( geometry ) + createArrayKeyGLTFPrimitive( primitives );
<ide>
<ide> }
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> // See if we've already created this combined geometry
<ide> var cache = parser.multiplePrimitivesCache;
<del> var cacheKey = createArrayKey( geometries );
<add> var cacheKey = createArrayKeyBufferGeometry( geometries );
<ide> var cached = cache[ cacheKey ];
<ide>
<ide> if ( cached ) { | 1 |
PHP | PHP | add language line for the in_array validation rule | 789c75c24ace662218d4656d3754fc343e34bac6 | <ide><path>resources/lang/en/validation.php
<ide> 'filled' => 'The :attribute field is required.',
<ide> 'image' => 'The :attribute must be an image.',
<ide> 'in' => 'The selected :attribute is invalid.',
<add> 'in_array' => 'The :attribute field does not exist in :other.',
<ide> 'integer' => 'The :attribute must be an integer.',
<ide> 'ip' => 'The :attribute must be a valid IP address.',
<ide> 'json' => 'The :attribute must be a valid JSON string.', | 1 |
Javascript | Javascript | fix nit and comment | fdc6beed1a3aab063752a395a42432251b3443fe | <ide><path>src/core/ReactNativeComponent.js
<ide> ReactNativeComponent.Mixin = {
<ide> if (nextProp) {
<ide> nextProp = nextProps.style = merge(nextProp);
<ide> }
<del> if (lastProp) {
<del> for (styleName in lastProp) {
<del> if (lastProp.hasOwnProperty(styleName) && !nextProp[styleName]) {
<del> if (!styleUpdates) {
<del> styleUpdates = {};
<del> }
<del> styleUpdates[styleName] = '';
<add> for (styleName in lastProp) {
<add> if (lastProp.hasOwnProperty(styleName) && !nextProp[styleName]) {
<add> if (!styleUpdates) {
<add> styleUpdates = {};
<ide> }
<add> styleUpdates[styleName] = '';
<ide> }
<ide> }
<ide> for (styleName in nextProp) {
<ide><path>src/dom/DOMProperty.js
<ide> var DOMProperty = {
<ide> * attribute). Most default values are '' or false, but not all. Worse yet,
<ide> * some (in particular, `type`) vary depending on the type of element.
<ide> *
<del> * TODO: Is it worth caching the test elements? Caching the properties
<del> * ourselves (as opposed to accessing from a cached test element every time)
<del> * looks probably worth it: http://jsperf.com/object-vs-element
<add> * TODO: Is it better to grab all the possible properties when creating an
<add> * element to avoid having to create the same element twice?
<ide> */
<ide> getDefaultValueForProperty: function(nodeName, prop) {
<ide> var nodeDefaults = defaultValueCache[nodeName]; | 2 |
PHP | PHP | clear commands | fe1cbdf3b51ce1235b8c91f5e603f1e9306e4f6f | <ide><path>src/Illuminate/Foundation/Console/OptimizeClearCommand.php
<add><?php
<add>
<add>namespace Illuminate\Foundation\Console;
<add>
<add>use Illuminate\Console\Command;
<add>
<add>class OptimizeClearCommand extends Command
<add>{
<add> /**
<add> * The console command name.
<add> *
<add> * @var string
<add> */
<add> protected $name = 'optimize:clear';
<add>
<add> /**
<add> * The console command description.
<add> *
<add> * @var string
<add> */
<add> protected $description = 'Clear all caches (routes, config, views, compiled class)';
<add>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function handle()
<add> {
<add> $this->call('cache:clear');
<add> $this->call('route:clear');
<add> $this->call('view:clear');
<add> $this->call('clear-compiled');
<add>
<add> $this->info('Config, routes and view cache cleared successfully!');
<add> }
<add>}
<ide><path>src/Illuminate/Foundation/Console/OptimizeCommand.php
<add><?php
<add>
<add>namespace Illuminate\Foundation\Console;
<add>
<add>use Illuminate\Console\Command;
<add>
<add>class OptimizeCommand extends Command
<add>{
<add> /**
<add> * The console command name.
<add> *
<add> * @var string
<add> */
<add> protected $name = 'optimize';
<add>
<add> /**
<add> * The console command description.
<add> *
<add> * @var string
<add> */
<add> protected $description = 'Optimize everything (cache routes, config)';
<add>
<add> /**
<add> * Execute the console command.
<add> *
<add> * @return void
<add> */
<add> public function handle()
<add> {
<add> $this->call('cache:clear');
<add> $this->call('config:cache');
<add> $this->call('route:clear');
<add> $this->call('route:cache');
<add>
<add> $this->info('Config and routes cached successfully!');
<add> }
<add>}
<ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
<ide> use Illuminate\Foundation\Console\JobMakeCommand;
<ide> use Illuminate\Database\Console\Seeds\SeedCommand;
<ide> use Illuminate\Foundation\Console\MailMakeCommand;
<add>use Illuminate\Foundation\Console\OptimizeCommand;
<ide> use Illuminate\Foundation\Console\RuleMakeCommand;
<ide> use Illuminate\Foundation\Console\TestMakeCommand;
<ide> use Illuminate\Foundation\Console\EventMakeCommand;
<ide> use Illuminate\Foundation\Console\ClearCompiledCommand;
<ide> use Illuminate\Foundation\Console\EventGenerateCommand;
<ide> use Illuminate\Foundation\Console\ExceptionMakeCommand;
<add>use Illuminate\Foundation\Console\OptimizeClearCommand;
<ide> use Illuminate\Foundation\Console\VendorPublishCommand;
<ide> use Illuminate\Console\Scheduling\ScheduleFinishCommand;
<ide> use Illuminate\Database\Console\Seeds\SeederMakeCommand;
<ide> class ArtisanServiceProvider extends ServiceProvider
<ide> 'MigrateReset' => 'command.migrate.reset',
<ide> 'MigrateRollback' => 'command.migrate.rollback',
<ide> 'MigrateStatus' => 'command.migrate.status',
<add> 'Optimize' => 'command.optimize',
<add> 'OptimizeClear' => 'command.optimize.clear',
<ide> 'PackageDiscover' => 'command.package.discover',
<ide> 'Preset' => 'command.preset',
<ide> 'QueueFailed' => 'command.queue.failed',
<ide> protected function registerNotificationMakeCommand()
<ide> });
<ide> }
<ide>
<add> /**
<add> * Register the command.
<add> *
<add> * @return void
<add> */
<add> protected function registerOptimizeCommand()
<add> {
<add> $this->app->singleton('command.optimize', function ($app) {
<add> return new OptimizeCommand;
<add> });
<add> }
<add>
<add> /**
<add> * Register the command.
<add> *
<add> * @return void
<add> */
<add> protected function registerOptimizeClearCommand()
<add> {
<add> $this->app->singleton('command.optimize.clear', function ($app) {
<add> return new OptimizeClearCommand;
<add> });
<add> }
<add>
<ide> /**
<ide> * Register the command.
<ide> * | 3 |
Go | Go | send warnings to stderr | b0efbcc34a77d5d8869cc381064d3741b67f9776 | <ide><path>cli/command/stack/deploy.go
<ide> func runDeploy(dockerCli *command.DockerCli, opts deployOptions) error {
<ide>
<ide> unsupportedProperties := loader.GetUnsupportedProperties(configDetails)
<ide> if len(unsupportedProperties) > 0 {
<del> fmt.Printf("Ignoring unsupported options: %s\n\n",
<add> fmt.Fprintf(dockerCli.Err(), "Ignoring unsupported options: %s\n\n",
<ide> strings.Join(unsupportedProperties, ", "))
<ide> }
<ide>
<ide> deprecatedProperties := loader.GetDeprecatedProperties(configDetails)
<ide> if len(deprecatedProperties) > 0 {
<del> fmt.Printf("Ignoring deprecated options:\n\n%s\n\n",
<add> fmt.Fprintf(dockerCli.Err(), "Ignoring deprecated options:\n\n%s\n\n",
<ide> propertyWarnings(deprecatedProperties))
<ide> }
<ide>
<ide> func convertRestartPolicy(restart string, source *composetypes.RestartPolicy) (*
<ide> }, nil
<ide> }
<ide> }
<del> attempts := uint64(*source.MaxAttempts)
<ide> return &swarm.RestartPolicy{
<ide> Condition: swarm.RestartPolicyCondition(source.Condition),
<ide> Delay: source.Delay,
<del> MaxAttempts: &attempts,
<add> MaxAttempts: source.MaxAttempts,
<ide> Window: source.Window,
<ide> }, nil
<ide> } | 1 |
Text | Text | move tunniclm to emeritus | dd03709148ec49b55792a1e29144634a323326b0 | <ide><path>README.md
<ide> For more information about the governance of the Node.js project, see
<ide> **Trivikram Kamat** <[email protected]>
<ide> * [Trott](https://github.com/Trott) -
<ide> **Rich Trott** <[email protected]> (he/him)
<del>* [tunniclm](https://github.com/tunniclm) -
<del>**Mike Tunnicliffe** <[email protected]>
<ide> * [vdeturckheim](https://github.com/vdeturckheim) -
<ide> **Vladimir de Turckheim** <[email protected]> (he/him)
<ide> * [vkurchatkin](https://github.com/vkurchatkin) -
<ide> For more information about the governance of the Node.js project, see
<ide> **Alex Kocharin** <[email protected]>
<ide> * [tellnes](https://github.com/tellnes) -
<ide> **Christian Tellnes** <[email protected]>
<add>* [tunniclm](https://github.com/tunniclm) -
<add>**Mike Tunnicliffe** <[email protected]>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the Node.js project. | 1 |
Ruby | Ruby | remove unused defined association | c073240f70de81639a340ab68b001a77ffb6237e | <ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> class MergingDifferentRelationsTest < ActiveRecord::TestCase
<ide> assert_equal ["Mary", "Mary", "Mary", "David"], posts_by_author_name
<ide> end
<ide>
<del> test "relation merging (using a proc argument)" do
<add> test "relation merging (using a proc argument)" do
<ide> dev = Developer.where(name: "Jamis").first
<ide>
<ide> comment_1 = dev.comments.create!(body: "I'm Jamis", post: Post.first)
<ide><path>activerecord/test/models/comment.rb
<ide> class Comment < ActiveRecord::Base
<ide> belongs_to :post, counter_cache: true
<ide> belongs_to :author, polymorphic: true
<ide> belongs_to :resource, polymorphic: true
<del> belongs_to :developer
<ide>
<ide> has_many :ratings
<ide> | 2 |
Ruby | Ruby | initialize instance variables | 580333fdc200eb7d2422f087e28d912bc324c42c | <ide><path>railties/lib/rails/application.rb
<ide> def inherited(base)
<ide>
<ide> def initialize
<ide> super
<del> @initialized = false
<del> @reloaders = []
<add> @initialized = false
<add> @reloaders = []
<add> @routes_reloader = nil
<add> @env_config = nil
<add> @ordered_railties = nil
<add> @queue = nil
<ide> end
<ide>
<ide> # This method is called just after an application inherits from Rails::Application, | 1 |
PHP | PHP | remove alias that isnt needed | a14a1208adc2e94e85d1afb0c36c5250a5668b4d | <ide><path>app/Http/Kernel.php
<ide> class Kernel extends HttpKernel
<ide> protected $routeMiddleware = [
<ide> 'auth' => \App\Http\Middleware\Authenticate::class,
<ide> 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
<del> 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
<ide> 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
<ide> 'can' => \Illuminate\Auth\Middleware\Authorize::class,
<ide> 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, | 1 |
Javascript | Javascript | set headers with falsy values | e9a222418a029d830698444cf95bf13f8ad75805 | <ide><path>src/ng/httpBackend.js
<ide> function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument,
<ide> var xhr = new XHR();
<ide> xhr.open(method, url, true);
<ide> forEach(headers, function(value, key) {
<del> if (value) xhr.setRequestHeader(key, value);
<add> if (isDefined(value)) {
<add> xhr.setRequestHeader(key, value);
<add> }
<ide> });
<ide>
<ide> // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
<ide><path>test/ng/httpBackendSpec.js
<ide> describe('$httpBackend', function() {
<ide> });
<ide> });
<ide>
<add> it('should set requested headers even if they have falsy values', function() {
<add> $backend('POST', 'URL', null, noop, {
<add> 'X-header1': 0,
<add> 'X-header2': '',
<add> 'X-header3': false,
<add> 'X-header4': undefined
<add> });
<add>
<add> xhr = MockXhr.$$lastInstance;
<add>
<add> expect(xhr.$$reqHeaders).toEqual({
<add> 'X-header1': 0,
<add> 'X-header2': '',
<add> 'X-header3': false
<add> });
<add> });
<ide>
<ide> it('should abort request on timeout', function() {
<ide> callback.andCallFake(function(status, response) {
<ide> describe('$httpBackend', function() {
<ide> expect(callback).toHaveBeenCalled();
<ide> expect(callback.mostRecentCall.args[0]).toBe(404);
<ide> });
<add>
<ide> });
<ide> });
<ide> | 2 |
Javascript | Javascript | add a new sample with some comments | 519c514092e98750fdc541b50361f9fe1544efb9 | <ide><path>spec/fixtures/sample-with-comments.js
<add>var quicksort = function () {
<add> /*
<add> this is a multiline comment
<add> it is, I promise
<add> */
<add> var sort = function(items) {
<add> // This is a collection of
<add> // single line comments.
<add> // Wowza
<add> if (items.length <= 1) return items;
<add> var pivot = items.shift(), current, left = [], right = [];
<add> while(items.length > 0) {
<add> current = items.shift();
<add> current < pivot ? left.push(current) : right.push(current);
<add> }
<add> return sort(left).concat(pivot).concat(sort(right));
<add> };
<add>
<add> return sort(Array.apply(this, arguments));
<add>};
<ide>\ No newline at end of file | 1 |
Ruby | Ruby | duplicate column_defaults properly (closes ) | c5176023a0585278c533610daf1eaf6ba7d19cd8 | <ide><path>activerecord/lib/active_record/core.rb
<ide> require 'active_support/concern'
<ide> require 'active_support/core_ext/hash/indifferent_access'
<add>require 'active_support/core_ext/object/duplicable'
<ide> require 'thread'
<ide>
<ide> module ActiveRecord
<ide> def relation #:nodoc:
<ide> # # Instantiates a single new object bypassing mass-assignment security
<ide> # User.new({ :first_name => 'Jamie', :is_admin => true }, :without_protection => true)
<ide> def initialize(attributes = nil, options = {})
<del> @attributes = self.class.initialize_attributes(self.class.column_defaults.dup)
<add> # TODO: use deep_dup after fixing it to also dup values
<add> defaults = Hash[self.class.column_defaults.map { |k, v| [k, v.duplicable? ? v.dup : v] }]
<add> @attributes = self.class.initialize_attributes(defaults)
<ide> @columns_hash = self.class.column_types.dup
<ide>
<ide> init_internals
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_marshalling_new_record_round_trip_with_associations
<ide> end
<ide>
<ide> def test_attribute_names
<del> assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id"],
<add> assert_equal ["id", "type", "ruby_type", "firm_id", "firm_name", "name", "client_of", "rating", "account_id", "description"],
<ide> Company.attribute_names
<ide> end
<ide>
<ide> def test_slice
<ide> assert_nil hash['firm_name']
<ide> end
<ide>
<add> def test_default_values_are_deeply_dupped
<add> company = Company.new
<add> company.description << "foo"
<add> assert_equal "", Company.new.description
<add> end
<add>
<ide> ["find_by", "find_by!"].each do |meth|
<ide> test "#{meth} delegates to scoped" do
<ide> record = stub
<ide><path>activerecord/test/schema/schema.rb
<ide> def create_table(*args, &block)
<ide> t.integer :client_of
<ide> t.integer :rating, :default => 1
<ide> t.integer :account_id
<add> t.string :description, :null => false, :default => ""
<ide> end
<ide>
<ide> add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index" | 3 |
Python | Python | fix polynomial tests | a2a9dfb692e36bdaf5667fb0d41e05c79d77f981 | <ide><path>numpy/lib/tests/test_polynomial.py
<ide> def test_polyfit(self) :
<ide> x = np.linspace(0,2,7)
<ide> y = np.polyval(c,x)
<ide> err = [1,-1,1,-1,1,-1,1]
<del> weights = arange(8,1,-1)**2/7.0
<add> weights = np.arange(8,1,-1)**2/7.0
<ide>
<ide> # check 1D case
<ide> m, cov = np.polyfit(x,y+err,2,cov=True)
<ide> def test_polyfit(self) :
<ide> cc = np.concatenate((c,c), axis=1)
<ide> assert_almost_equal(cc, np.polyfit(x,yy,2))
<ide>
<del> m, cov = np.polyfit(x,yy+array(err)[:,np.newaxis],2,cov=True)
<add> m, cov = np.polyfit(x,yy + np.array(err)[:,np.newaxis],2,cov=True)
<ide> assert_almost_equal(est, m[:,0], decimal=4)
<ide> assert_almost_equal(est, m[:,1], decimal=4)
<ide> assert_almost_equal(val0, cov[:,:,0], decimal=4) | 1 |
Go | Go | increase memory limit in test cases | 64fd3e89c7f6164b5522b5e611e7daf4a2bdae9c | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func TestRunEchoStdout(t *testing.T) {
<ide>
<ide> // "test" should be printed
<ide> func TestRunEchoStdoutWithMemoryLimit(t *testing.T) {
<del> runCmd := exec.Command(dockerBinary, "run", "-m", "4m", "busybox", "echo", "test")
<add> runCmd := exec.Command(dockerBinary, "run", "-m", "16m", "busybox", "echo", "test")
<ide> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<ide> if err != nil {
<ide> t.Fatalf("failed to run container: %v, output: %q", err, out)
<ide> func TestRunEchoStdoutWitCPULimit(t *testing.T) {
<ide>
<ide> // "test" should be printed
<ide> func TestRunEchoStdoutWithCPUAndMemoryLimit(t *testing.T) {
<del> runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "4m", "busybox", "echo", "test")
<add> runCmd := exec.Command(dockerBinary, "run", "-c", "1000", "-m", "16m", "busybox", "echo", "test")
<ide> out, _, _, err := runCommandWithStdoutStderr(runCmd)
<ide> if err != nil {
<ide> t.Fatalf("failed to run container: %v, output: %q", err, out) | 1 |
Ruby | Ruby | add -dbuild_testing=off to std_cmake_args | 0db7c0ba8a1e5234c6265c93da96dcf57ceb8f38 | <ide><path>Library/Homebrew/formula.rb
<ide> def std_cmake_args
<ide> -DCMAKE_FIND_FRAMEWORK=LAST
<ide> -DCMAKE_VERBOSE_MAKEFILE=ON
<ide> -Wno-dev
<add> -DBUILD_TESTING=OFF
<ide> ]
<ide>
<ide> # Avoid false positives for clock_gettime support on 10.11. | 1 |
PHP | PHP | fix sqlite fixture generation | 47cad96da0cf5765de3e2105b5b714de96feb931 | <ide><path>src/Database/Schema/SqliteSchema.php
<ide> public function columnSql(Table $table, $name)
<ide> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<del> $out .= ' UNSIGNED';
<add> if ($data['type'] !== 'integer' || [$name] !== (array)$table->primaryKey()) {
<add> $out .= ' UNSIGNED';
<add> }
<ide> }
<ide> $out .= $typeMap[$data['type']];
<ide>
<ide> $hasLength = ['integer', 'string'];
<ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
<del> $out .= '(' . (int)$data['length'] . ')';
<add> if ($data['type'] !== 'integer' || [$name] !== (array)$table->primaryKey()) {
<add> $out .= '(' . (int)$data['length'] . ')';
<add> }
<ide> }
<ide> $hasPrecision = ['float', 'decimal'];
<ide> if (in_array($data['type'], $hasPrecision, true) && | 1 |
PHP | PHP | add stricter validation to testtask | 8981f49bd5ab679b894c70809a47346f7b5b08d1 | <ide><path>lib/Cake/Console/Command/Task/TestTask.php
<ide> public function getClassName($objectType) {
<ide> $this->out(++$key . '. ' . $option);
<ide> $keys[] = $key;
<ide> }
<del> $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
<del> if (isset($options[$selection - 1])) {
<del> $selection = $options[$selection - 1];
<del> }
<del> if ($type !== 'Model') {
<del> $selection = substr($selection, 0, $typeLength * - 1);
<add> while (empty($selection)) {
<add> $selection = $this->in(__d('cake_console', 'Choose an existing class, or enter the name of a class that does not exist'));
<add> if (is_numeric($selection) && isset($options[$selection - 1])) {
<add> $selection = $options[$selection - 1];
<add> }
<add> if ($type !== 'Model') {
<add> $selection = substr($selection, 0, $typeLength * - 1);
<add> }
<ide> }
<ide> return $selection;
<ide> } | 1 |
Text | Text | hide solution from tests in chinese challenge | b1206f0b53062d65f962834c64f014fe03ccbd00 | <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.chinese.md
<ide> localeTitle: 在不创建网格区域模板的情况下使用网格区域
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>item5</code>类应该具有值为<code>3/1/4/4</code>的<code>grid-area</code>属性。
<del> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "<code>item5</code> class should have a <code>grid-area</code> property that has the value of <code>3/1/4/4</code>.");'
<add> - text: <code>item5</code>类应具有<code>grid-area</code>属性,使其位于第三和第四水平线之间以及第一和第四垂直线之间。
<add> testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "<code>item5</code>类应具有<code>grid-area</code>属性,使其位于第三和第四水平线之间以及第一和第四垂直线之间。");'
<ide>
<ide> ```
<ide> | 1 |
Python | Python | increase timeout of running wpt | a157e5565898936b467b416e0215136d9d28ea2f | <ide><path>tools/test.py
<ide> def GetVm(self, arch, mode):
<ide>
<ide> def GetTimeout(self, mode, section=''):
<ide> timeout = self.timeout * TIMEOUT_SCALEFACTOR[ARCH_GUESS or 'ia32'][mode]
<del> if section == 'pummel' or section == 'benchmark' or section == 'wpt':
<add> if section == 'pummel' or section == 'benchmark':
<ide> timeout = timeout * 6
<add> # We run all WPT from one subset in the same process using workers.
<add> # As the number of the tests grow, it can take longer to run some of the
<add> # subsets, but it's still overall faster than running them in different
<add> # processes.
<add> elif section == 'wpt':
<add> timeout = timeout * 12
<ide> return timeout
<ide>
<ide> def RunTestCases(cases_to_run, progress, tasks, flaky_tests_mode, measure_flakiness): | 1 |
Javascript | Javascript | add a way to disable fonts that won't load | d7edbe28e97a0be7d951f9111f27fbd4baf00265 | <ide><path>fonts.js
<ide> var kMaxWaitForFontFace = 1000;
<ide> var fontCount = 0;
<ide> var fontName = "";
<ide>
<add>/**
<add> * If for some reason one want to debug without fonts activated, it just need
<add> * to turn this pref to true/false.
<add> */
<add>var kDisableFonts = false;
<add>
<ide> /**
<ide> * Hold a map of decoded fonts and of the standard fourteen Type1 fonts and
<ide> * their acronyms.
<ide> var Font = function(aName, aFile, aProperties) {
<ide> }
<ide> fontCount++;
<ide>
<add> if (aProperties.ignore || kDisableFonts) {
<add> Fonts[aName] = {
<add> data: aFile,
<add> loading: false,
<add> properties: {},
<add> cache: Object.create(null)
<add> }
<add> return;
<add> }
<add>
<ide> switch (aProperties.type) {
<ide> case "Type1":
<ide> var cff = new CFF(aName, aFile, aProperties);
<ide> Font.prototype = {
<ide> if (debug)
<ide> ctx.fillText(testString, 20, 20);
<ide>
<del> var start = Date.now();
<ide> var interval = window.setInterval(function canvasInterval(self) {
<add> this.start = this.start || Date.now();
<ide> ctx.font = "bold italic 20px " + fontName + ", Symbol, Arial";
<ide>
<ide> // For some reasons the font has not loaded, so mark it loaded for the
<ide> // page to proceed but cry
<del> if ((Date.now() - start) >= kMaxWaitForFontFace) {
<add> if ((Date.now() - this.start) >= kMaxWaitForFontFace) {
<ide> window.clearInterval(interval);
<ide> Fonts[fontName].loading = false;
<ide> warn("Is " + fontName + " for charset: " + charset + " loaded?");
<add> this.start = 0;
<ide> } else if (textWidth != ctx.measureText(testString).width) {
<ide> window.clearInterval(interval);
<ide> Fonts[fontName].loading = false;
<add> this.start = 0;
<ide> }
<ide>
<ide> if (debug)
<ide> var TrueType = function(aName, aFile, aProperties) {
<ide> });
<ide> }
<ide>
<add>
<add> var offsetDelta = 0;
<add>
<ide> // Replace the old CMAP table
<ide> var rewrittedCMAP = this._createCMAPTable(glyphs);
<del> var offsetDelta = rewrittedCMAP.length - originalCMAP.data.length;
<add> offsetDelta = rewrittedCMAP.length - originalCMAP.data.length;
<ide> originalCMAP.data = rewrittedCMAP;
<ide>
<ide> // Rewrite the 'post' table if needed
<ide><path>pdf.js
<ide> var CanvasGraphics = (function() {
<ide> error("FontFile not found for font: " + fontName);
<ide> fontFile = xref.fetchIfRef(fontFile);
<ide>
<add> // Fonts with an embedded cmap but without any assignment in
<add> // it are not yet supported, so ask the fonts loader to ignore
<add> // them to not pay a stupid one sec latence.
<add> var ignoreFont = true;
<add>
<ide> var encodingMap = {};
<ide> var charset = [];
<ide> if (fontDict.has("Encoding")) {
<add> ignoreFont = false;
<add>
<ide> var encoding = xref.fetchIfRef(fontDict.get("Encoding"));
<ide> if (IsDict(encoding)) {
<ide> // Build a map between codes and glyphs
<ide> var CanvasGraphics = (function() {
<ide> error("useCMap is not implemented");
<ide> break;
<ide>
<del> case "begincodespacerange":
<ide> case "beginbfrange":
<add> ignoreFont = false;
<add> case "begincodespacerange":
<ide> token = "";
<ide> tokens = [];
<ide> break;
<ide> var CanvasGraphics = (function() {
<ide> }
<ide> }
<ide> }
<del> }
<add> }
<ide>
<ide> var subType = fontDict.get("Subtype");
<ide> var bbox = descriptor.get("FontBBox");
<ide> var CanvasGraphics = (function() {
<ide> type: subType.name,
<ide> encoding: encodingMap,
<ide> charset: charset,
<del> bbox: bbox
<add> bbox: bbox,
<add> ignore: ignoreFont
<ide> };
<ide>
<ide> return {
<ide> var CanvasGraphics = (function() {
<ide> }
<ide>
<ide> this.current.fontSize = size;
<del> this.ctx.font = this.current.fontSize +'px "' + fontName + '"';
<add> this.ctx.font = this.current.fontSize +'px "' + fontName + '", Symbol';
<ide> },
<ide> setTextRenderingMode: function(mode) {
<ide> TODO("text rendering mode"); | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.