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 |
|---|---|---|---|---|---|
Java | Java | add qualified element on rootbeandefinition | 2b0bf9f04a62fafd9ce28da37dbeb227b82cf462 | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java
<ide> package org.springframework.beans.factory.annotation;
<ide>
<ide> import java.lang.annotation.Annotation;
<add>import java.lang.reflect.AnnotatedElement;
<ide> import java.lang.reflect.Method;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.Map;
<ide> *
<ide> * @author Mark Fisher
<ide> * @author Juergen Hoeller
<add> * @author Stephane Nicoll
<ide> * @since 2.5
<ide> * @see AutowireCandidateQualifier
<ide> * @see Qualifier
<ide> protected boolean checkQualifier(
<ide> qualifier = bd.getQualifier(ClassUtils.getShortName(type));
<ide> }
<ide> if (qualifier == null) {
<del> // First, check annotation on factory method, if applicable
<del> Annotation targetAnnotation = getFactoryMethodAnnotation(bd, type);
<add> // First, check annotation on qualified element, if any
<add> Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type);
<add> // Then, check annotation on factory method, if applicable
<add> if (targetAnnotation == null) {
<add> targetAnnotation = getFactoryMethodAnnotation(bd, type);
<add> }
<ide> if (targetAnnotation == null) {
<ide> RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd);
<ide> if (dbd != null) {
<ide> protected boolean checkQualifier(
<ide> return true;
<ide> }
<ide>
<add> protected Annotation getQualifiedElementAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
<add> AnnotatedElement qualifiedElement = bd.getQualifiedElement();
<add> return (qualifiedElement != null ? AnnotationUtils.getAnnotation(qualifiedElement, type) : null);
<add> }
<add>
<ide> protected Annotation getFactoryMethodAnnotation(RootBeanDefinition bd, Class<? extends Annotation> type) {
<ide> Method resolvedFactoryMethod = bd.getResolvedFactoryMethod();
<ide> return (resolvedFactoryMethod != null ? AnnotationUtils.getAnnotation(resolvedFactoryMethod, type) : null);
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java
<ide>
<ide> package org.springframework.beans.factory.support;
<ide>
<add>import java.lang.reflect.AnnotatedElement;
<ide> import java.lang.reflect.Executable;
<ide> import java.lang.reflect.Member;
<ide> import java.lang.reflect.Method;
<ide> public class RootBeanDefinition extends AbstractBeanDefinition {
<ide>
<ide> boolean isFactoryMethodUnique = false;
<ide>
<add> volatile AnnotatedElement qualifiedElement;
<add>
<ide> /** Package-visible field for caching the determined Class of a given bean definition */
<ide> volatile Class<?> resolvedTargetType;
<ide>
<ide> public RootBeanDefinition(RootBeanDefinition original) {
<ide> this.allowCaching = original.allowCaching;
<ide> this.targetType = original.targetType;
<ide> this.isFactoryMethodUnique = original.isFactoryMethodUnique;
<add> this.qualifiedElement = original.qualifiedElement;
<ide> }
<ide>
<ide> /**
<ide> public void setUniqueFactoryMethodName(String name) {
<ide> this.isFactoryMethodUnique = true;
<ide> }
<ide>
<add> /**
<add> * Specify the {@link AnnotatedElement} defining qualifiers.
<add> * @since 4.3.3
<add> */
<add> public void setQualifiedElement(AnnotatedElement qualifiedElement) {
<add> this.qualifiedElement = qualifiedElement;
<add> }
<add>
<add> /**
<add> * Return the {@link AnnotatedElement} defining qualifiers, if any.
<add> * @since 4.3.3
<add> */
<add> public AnnotatedElement getQualifiedElement() {
<add> return this.qualifiedElement;
<add> }
<add>
<ide> /**
<ide> * Check whether the given candidate qualifies as a factory method.
<ide> */
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java
<ide> import org.springframework.tests.sample.beans.IndexedTestBean;
<ide> import org.springframework.tests.sample.beans.NestedTestBean;
<ide> import org.springframework.tests.sample.beans.TestBean;
<add>import org.springframework.util.ReflectionUtils;
<ide> import org.springframework.util.SerializationTestUtils;
<ide>
<ide> import static org.junit.Assert.*;
<ide> public void testObjectFactoryQualifierInjection() {
<ide> bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierInjectionBean.class));
<ide> RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
<ide> bd.addQualifier(new AutowireCandidateQualifier(Qualifier.class, "testBean"));
<del> bf.registerBeanDefinition("testBean", bd);
<del> bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
<add> bf.registerBeanDefinition("dependencyBean", bd);
<add> bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class));
<ide>
<ide> ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
<del> assertSame(bf.getBean("testBean"), bean.getTestBean());
<add> assertSame(bf.getBean("dependencyBean"), bean.getTestBean());
<add> bf.destroySingletons();
<add> }
<add>
<add> @Test
<add> public void testObjectFactoryQualifierProviderInjection() {
<add> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<add> bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
<add> AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
<add> bpp.setBeanFactory(bf);
<add> bf.addBeanPostProcessor(bpp);
<add> bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(ObjectFactoryQualifierInjectionBean.class));
<add> RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
<add> bd.setQualifiedElement(ReflectionUtils.findMethod(getClass(), "testBeanQualifierProvider"));
<add> bf.registerBeanDefinition("dependencyBean", bd);
<add> bf.registerBeanDefinition("dependencyBean2", new RootBeanDefinition(TestBean.class));
<add>
<add> ObjectFactoryQualifierInjectionBean bean = (ObjectFactoryQualifierInjectionBean) bf.getBean("annotatedBean");
<add> assertSame(bf.getBean("dependencyBean"), bean.getTestBean());
<ide> bf.destroySingletons();
<ide> }
<ide>
<add> @Qualifier("testBean")
<add> private void testBeanQualifierProvider() {}
<add>
<ide> @Test
<ide> public void testObjectFactorySerialization() throws Exception {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<ide> public void testGenericsBasedFieldInjectionWithMocks() {
<ide> rbd.setFactoryBeanName("mocksControl");
<ide> rbd.setFactoryMethodName("createMock");
<ide> rbd.getConstructorArgumentValues().addGenericArgumentValue(Repository.class);
<del> bf.registerBeanDefinition("integerRepo", rbd);
<add> rbd.setQualifiedElement(ReflectionUtils.findField(getClass(), "integerRepositoryQualifierProvider"));
<add> bf.registerBeanDefinition("integerRepository", rbd); // Bean name not matching qualifier
<ide>
<ide> RepositoryFieldInjectionBeanWithQualifiers bean = (RepositoryFieldInjectionBeanWithQualifiers) bf.getBean("annotatedBean");
<ide> Repository<?> sr = bf.getBean("stringRepo", Repository.class);
<del> Repository<?> ir = bf.getBean("integerRepo", Repository.class);
<add> Repository<?> ir = bf.getBean("integerRepository", Repository.class);
<ide> assertSame(sr, bean.stringRepository);
<ide> assertSame(ir, bean.integerRepository);
<ide> assertSame(1, bean.stringRepositoryArray.length);
<ide> public void testGenericsBasedFieldInjectionWithMocks() {
<ide> assertSame(1, bean.stringRepositoryMap.size());
<ide> assertSame(1, bean.integerRepositoryMap.size());
<ide> assertSame(sr, bean.stringRepositoryMap.get("stringRepo"));
<del> assertSame(ir, bean.integerRepositoryMap.get("integerRepo"));
<add> assertSame(ir, bean.integerRepositoryMap.get("integerRepository"));
<ide> }
<ide>
<add> @Qualifier("integerRepo")
<add> private Repository<?> integerRepositoryQualifierProvider;
<add>
<ide> @Test
<ide> public void testGenericsBasedFieldInjectionWithSimpleMatch() {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2016 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void beanDefinitionMerging() {
<ide> bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5));
<ide> bd.getPropertyValues().add("name", "myName");
<ide> bd.getPropertyValues().add("age", "99");
<add> bd.setQualifiedElement(getClass());
<ide>
<ide> GenericBeanDefinition childBd = new GenericBeanDefinition();
<ide> childBd.setParentName("bd");
<ide> public void beanDefinitionMerging() {
<ide>
<ide> mergedBd.getConstructorArgumentValues().getArgumentValue(1, null).setValue(new Integer(9));
<ide> assertEquals(new Integer(5), bd.getConstructorArgumentValues().getArgumentValue(1, null).getValue());
<add> assertEquals(getClass(), bd.getQualifiedElement());
<ide> }
<ide>
<ide> } | 4 |
Ruby | Ruby | remove unused journey code | 639f5fda302ad6b5d535cf393161e4e77ea5050b | <ide><path>actionpack/lib/action_dispatch/journey.rb
<ide> require "action_dispatch/journey/router"
<ide> require "action_dispatch/journey/gtg/builder"
<ide> require "action_dispatch/journey/gtg/simulator"
<del>require "action_dispatch/journey/nfa/builder"
<del>require "action_dispatch/journey/nfa/simulator"
<ide><path>actionpack/lib/action_dispatch/journey/nfa/builder.rb
<del># frozen_string_literal: true
<del>
<del>require "action_dispatch/journey/nfa/transition_table"
<del>require "action_dispatch/journey/gtg/transition_table"
<del>
<del>module ActionDispatch
<del> module Journey # :nodoc:
<del> module NFA # :nodoc:
<del> class Visitor < Visitors::Visitor # :nodoc:
<del> def initialize(tt)
<del> @tt = tt
<del> @i = -1
<del> end
<del>
<del> def visit_CAT(node)
<del> left = visit(node.left)
<del> right = visit(node.right)
<del>
<del> @tt.merge(left.last, right.first)
<del>
<del> [left.first, right.last]
<del> end
<del>
<del> def visit_GROUP(node)
<del> from = @i += 1
<del> left = visit(node.left)
<del> to = @i += 1
<del>
<del> @tt.accepting = to
<del>
<del> @tt[from, left.first] = nil
<del> @tt[left.last, to] = nil
<del> @tt[from, to] = nil
<del>
<del> [from, to]
<del> end
<del>
<del> def visit_OR(node)
<del> from = @i += 1
<del> children = node.children.map { |c| visit(c) }
<del> to = @i += 1
<del>
<del> children.each do |child|
<del> @tt[from, child.first] = nil
<del> @tt[child.last, to] = nil
<del> end
<del>
<del> @tt.accepting = to
<del>
<del> [from, to]
<del> end
<del>
<del> def terminal(node)
<del> from_i = @i += 1 # new state
<del> to_i = @i += 1 # new state
<del>
<del> @tt[from_i, to_i] = node
<del> @tt.accepting = to_i
<del> @tt.add_memo(to_i, node.memo)
<del>
<del> [from_i, to_i]
<del> end
<del> end
<del>
<del> class Builder # :nodoc:
<del> def initialize(ast)
<del> @ast = ast
<del> end
<del>
<del> def transition_table
<del> tt = TransitionTable.new
<del> Visitor.new(tt).accept(@ast)
<del> tt
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>actionpack/lib/action_dispatch/journey/nfa/dot.rb
<ide> def to_dot
<ide> " #{from} -> #{to} [label=\"#{sym || 'ε'}\"];"
<ide> }
<ide>
<del> # memo_nodes = memos.values.flatten.map { |n|
<del> # label = n
<del> # if Journey::Route === n
<del> # label = "#{n.verb.source} #{n.path.spec}"
<del> # end
<del> # " #{n.object_id} [label=\"#{label}\", shape=box];"
<del> # }
<del> # memo_edges = memos.flat_map { |k, memos|
<del> # (memos || []).map { |v| " #{k} -> #{v.object_id};" }
<del> # }.uniq
<del>
<ide> <<-eodot
<ide> digraph nfa {
<ide> rankdir=LR;
<ide><path>actionpack/lib/action_dispatch/journey/nfa/simulator.rb
<del># frozen_string_literal: true
<del>
<del>require "strscan"
<del>
<del>module ActionDispatch
<del> module Journey # :nodoc:
<del> module NFA # :nodoc:
<del> class MatchData # :nodoc:
<del> attr_reader :memos
<del>
<del> def initialize(memos)
<del> @memos = memos
<del> end
<del> end
<del>
<del> class Simulator # :nodoc:
<del> attr_reader :tt
<del>
<del> def initialize(transition_table)
<del> @tt = transition_table
<del> end
<del>
<del> def simulate(string)
<del> input = StringScanner.new(string)
<del> state = tt.eclosure(0)
<del> until input.eos?
<del> sym = input.scan(%r([/.?]|[^/.?]+))
<del> state = tt.eclosure(tt.move(state, sym))
<del> end
<del>
<del> acceptance_states = state.find_all { |s|
<del> tt.accepting?(tt.eclosure(s).sort.last)
<del> }
<del>
<del> return if acceptance_states.empty?
<del>
<del> memos = acceptance_states.flat_map { |x| tt.memo(x) }.compact
<del>
<del> MatchData.new(memos)
<del> end
<del>
<del> alias :=~ :simulate
<del> alias :match :simulate
<del> end
<del> end
<del> end
<del>end
<ide><path>actionpack/lib/action_dispatch/journey/nfa/transition_table.rb
<del># frozen_string_literal: true
<del>
<del>require "action_dispatch/journey/nfa/dot"
<del>
<del>module ActionDispatch
<del> module Journey # :nodoc:
<del> module NFA # :nodoc:
<del> class TransitionTable # :nodoc:
<del> include Journey::NFA::Dot
<del>
<del> attr_accessor :accepting
<del> attr_reader :memos
<del>
<del> def initialize
<del> @table = Hash.new { |h, f| h[f] = {} }
<del> @memos = {}
<del> @accepting = nil
<del> @inverted = nil
<del> end
<del>
<del> def accepting?(state)
<del> accepting == state
<del> end
<del>
<del> def accepting_states
<del> [accepting]
<del> end
<del>
<del> def add_memo(idx, memo)
<del> @memos[idx] = memo
<del> end
<del>
<del> def memo(idx)
<del> @memos[idx]
<del> end
<del>
<del> def []=(i, f, s)
<del> @table[f][i] = s
<del> end
<del>
<del> def merge(left, right)
<del> @memos[right] = @memos.delete(left)
<del> @table[right] = @table.delete(left)
<del> end
<del>
<del> def states
<del> (@table.keys + @table.values.flat_map(&:keys)).uniq
<del> end
<del>
<del> # Returns set of NFA states to which there is a transition on ast symbol
<del> # +a+ from some state +s+ in +t+.
<del> def following_states(t, a)
<del> Array(t).flat_map { |s| inverted[s][a] }.uniq
<del> end
<del>
<del> # Returns set of NFA states to which there is a transition on ast symbol
<del> # +a+ from some state +s+ in +t+.
<del> def move(t, a)
<del> Array(t).map { |s|
<del> inverted[s].keys.compact.find_all { |sym|
<del> sym === a
<del> }.map { |sym| inverted[s][sym] }
<del> }.flatten.uniq
<del> end
<del>
<del> def alphabet
<del> inverted.values.flat_map(&:keys).compact.uniq.sort_by(&:to_s)
<del> end
<del>
<del> # Returns a set of NFA states reachable from some NFA state +s+ in set
<del> # +t+ on nil-transitions alone.
<del> def eclosure(t)
<del> stack = Array(t)
<del> seen = {}
<del> children = []
<del>
<del> until stack.empty?
<del> s = stack.pop
<del> next if seen[s]
<del>
<del> seen[s] = true
<del> children << s
<del>
<del> stack.concat(inverted[s][nil])
<del> end
<del>
<del> children.uniq
<del> end
<del>
<del> def transitions
<del> @table.flat_map { |to, hash|
<del> hash.map { |from, sym| [from, sym, to] }
<del> }
<del> end
<del>
<del> private
<del> def inverted
<del> return @inverted if @inverted
<del>
<del> @inverted = Hash.new { |h, from|
<del> h[from] = Hash.new { |j, s| j[s] = [] }
<del> }
<del>
<del> @table.each { |to, hash|
<del> hash.each { |from, sym|
<del> if sym
<del> sym = Nodes::Symbol === sym ? sym.regexp : sym.left
<del> end
<del>
<del> @inverted[from][sym] << to
<del> }
<del> }
<del>
<del> @inverted
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>actionpack/test/journey/gtg/builder_test.rb
<ide> def test_match_data_ambiguous
<ide> /articles/:id(.:format)
<ide> }
<ide>
<del> sim = NFA::Simulator.new table
<add> sim = Simulator.new table
<ide>
<del> match = sim.match "/articles/new"
<del> assert_equal 2, match.memos.length
<add> memos = sim.memos "/articles/new"
<add> assert_equal 2, memos.length
<ide> end
<ide>
<ide> ##
<ide> def test_match_same_paths
<ide> /articles/new(.:format)
<ide> }
<ide>
<del> sim = NFA::Simulator.new table
<add> sim = Simulator.new table
<ide>
<del> match = sim.match "/articles/new"
<del> assert_equal 2, match.memos.length
<add> memos = sim.memos "/articles/new"
<add> assert_equal 2, memos.length
<ide> end
<ide>
<ide> private
<ide><path>actionpack/test/journey/nfa/simulator_test.rb
<del># frozen_string_literal: true
<del>
<del>require "abstract_unit"
<del>
<del>module ActionDispatch
<del> module Journey
<del> module NFA
<del> class TestSimulator < ActiveSupport::TestCase
<del> def test_simulate_simple
<del> sim = simulator_for ["/foo"]
<del> assert_match sim, "/foo"
<del> end
<del>
<del> def test_simulate_simple_no_match
<del> sim = simulator_for ["/foo"]
<del> assert_no_match sim, "foo"
<del> end
<del>
<del> def test_simulate_simple_no_match_too_long
<del> sim = simulator_for ["/foo"]
<del> assert_no_match sim, "/foo/bar"
<del> end
<del>
<del> def test_simulate_simple_no_match_wrong_string
<del> sim = simulator_for ["/foo"]
<del> assert_no_match sim, "/bar"
<del> end
<del>
<del> def test_simulate_regex
<del> sim = simulator_for ["/:foo/bar"]
<del> assert_match sim, "/bar/bar"
<del> assert_match sim, "/foo/bar"
<del> end
<del>
<del> def test_simulate_or
<del> sim = simulator_for ["/foo", "/bar"]
<del> assert_match sim, "/bar"
<del> assert_match sim, "/foo"
<del> assert_no_match sim, "/baz"
<del> end
<del>
<del> def test_simulate_optional
<del> sim = simulator_for ["/foo(/bar)"]
<del> assert_match sim, "/foo"
<del> assert_match sim, "/foo/bar"
<del> assert_no_match sim, "/foo/"
<del> end
<del>
<del> def test_matchdata_has_memos
<del> paths = %w{ /foo /bar }
<del> parser = Journey::Parser.new
<del> asts = paths.map { |x|
<del> ast = parser.parse x
<del> ast.each { |n| n.memo = ast }
<del> ast
<del> }
<del>
<del> expected = asts.first
<del>
<del> builder = Builder.new Nodes::Or.new asts
<del>
<del> sim = Simulator.new builder.transition_table
<del>
<del> md = sim.match "/foo"
<del> assert_equal [expected], md.memos
<del> end
<del>
<del> def test_matchdata_memos_on_merge
<del> parser = Journey::Parser.new
<del> routes = [
<del> "/articles(.:format)",
<del> "/articles/new(.:format)",
<del> "/articles/:id/edit(.:format)",
<del> "/articles/:id(.:format)",
<del> ].map { |path|
<del> ast = parser.parse path
<del> ast.each { |n| n.memo = ast }
<del> ast
<del> }
<del>
<del> asts = routes.dup
<del>
<del> ast = Nodes::Or.new routes
<del>
<del> nfa = Journey::NFA::Builder.new ast
<del> sim = Simulator.new nfa.transition_table
<del> md = sim.match "/articles"
<del> assert_equal [asts.first], md.memos
<del> end
<del>
<del> def simulator_for(paths)
<del> parser = Journey::Parser.new
<del> asts = paths.map { |x| parser.parse x }
<del> builder = Builder.new Nodes::Or.new asts
<del> Simulator.new builder.transition_table
<del> end
<del> end
<del> end
<del> end
<del>end
<ide><path>actionpack/test/journey/nfa/transition_table_test.rb
<del># frozen_string_literal: true
<del>
<del>require "abstract_unit"
<del>
<del>module ActionDispatch
<del> module Journey
<del> module NFA
<del> class TestTransitionTable < ActiveSupport::TestCase
<del> def setup
<del> @parser = Journey::Parser.new
<del> end
<del>
<del> def test_eclosure
<del> table = tt "/"
<del> assert_equal [0], table.eclosure(0)
<del>
<del> table = tt ":a|:b"
<del> assert_equal 3, table.eclosure(0).length
<del>
<del> table = tt "(:a|:b)"
<del> assert_equal 5, table.eclosure(0).length
<del> assert_equal 5, table.eclosure([0]).length
<del> end
<del>
<del> def test_following_states_one
<del> table = tt "/"
<del>
<del> assert_equal [1], table.following_states(0, "/")
<del> assert_equal [1], table.following_states([0], "/")
<del> end
<del>
<del> def test_following_states_group
<del> table = tt "a|b"
<del> states = table.eclosure 0
<del>
<del> assert_equal 1, table.following_states(states, "a").length
<del> assert_equal 1, table.following_states(states, "b").length
<del> end
<del>
<del> def test_following_states_multi
<del> table = tt "a|a"
<del> states = table.eclosure 0
<del>
<del> assert_equal 2, table.following_states(states, "a").length
<del> assert_equal 0, table.following_states(states, "b").length
<del> end
<del>
<del> def test_following_states_regexp
<del> table = tt "a|:a"
<del> states = table.eclosure 0
<del>
<del> assert_equal 1, table.following_states(states, "a").length
<del> assert_equal 1, table.following_states(states, /[^\.\/\?]+/).length
<del> assert_equal 0, table.following_states(states, "b").length
<del> end
<del>
<del> def test_alphabet
<del> table = tt "a|:a"
<del> assert_equal [/[^\.\/\?]+/, "a"], table.alphabet
<del>
<del> table = tt "a|a"
<del> assert_equal ["a"], table.alphabet
<del> end
<del>
<del> private
<del> def tt(string)
<del> ast = @parser.parse string
<del> builder = Builder.new ast
<del> builder.transition_table
<del> end
<del> end
<del> end
<del> end
<del>end | 8 |
Text | Text | increase macos minimum supported version | 945324050bc9532c241c8c004967133d6c4dd485 | <ide><path>BUILDING.md
<ide> platforms in production.
<ide> |--------------|--------------|----------------------------------|----------------------|------------------|
<ide> | GNU/Linux | Tier 1 | kernel >= 2.6.32, glibc >= 2.12 | x64, arm | |
<ide> | GNU/Linux | Tier 1 | kernel >= 3.10, glibc >= 2.17 | arm64 | |
<del>| macOS/OS X | Tier 1 | >= 10.10 | x64 | |
<add>| macOS/OS X | Tier 1 | >= 10.11 | x64 | |
<ide> | Windows | Tier 1 | >= Windows 7/2008 R2/2012 R2 | x86, x64 | vs2017 |
<ide> | SmartOS | Tier 2 | >= 15 < 16.4 | x86, x64 | see note1 |
<ide> | FreeBSD | Tier 2 | >= 10 | x64 | |
<ide> | GNU/Linux | Tier 2 | kernel >= 3.13.0, glibc >= 2.19 | ppc64le >=power8 | |
<ide> | AIX | Tier 2 | >= 7.1 TL04 | ppc64be >=power7 | |
<ide> | GNU/Linux | Tier 2 | kernel >= 3.10, glibc >= 2.17 | s390x | |
<del>| OS X | Experimental | >= 10.8 < 10.10 | x64 | no test coverage |
<ide> | GNU/Linux | Experimental | kernel >= 2.6.32, glibc >= 2.12 | x86 | limited CI |
<ide> | Linux (musl) | Experimental | musl >= 1.0 | x64 | |
<ide> | 1 |
Python | Python | pin pytorch to make ci green | 0f502682fb08c7dac5b255903f63dcd9cc2d68eb | <ide><path>setup.py
<ide> "timeout-decorator",
<ide> "timm",
<ide> "tokenizers>=0.10.1,<0.11",
<del> "torch>=1.0",
<add> "torch>=1.0,<1.10",
<ide> "torchaudio",
<ide> "tqdm>=4.27",
<ide> "unidic>=1.0.2",
<ide><path>src/transformers/dependency_versions_table.py
<ide> "timeout-decorator": "timeout-decorator",
<ide> "timm": "timm",
<ide> "tokenizers": "tokenizers>=0.10.1,<0.11",
<del> "torch": "torch>=1.0",
<add> "torch": "torch>=1.0,<1.10",
<ide> "torchaudio": "torchaudio",
<ide> "tqdm": "tqdm>=4.27",
<ide> "unidic": "unidic>=1.0.2", | 2 |
Python | Python | shorten long comment line | 815ac8fe897bbf74c92009f53c30dd0bdbbd9e16 | <ide><path>numpy/lib/scimath.py
<ide> """
<ide> Wrapper functions to more user-friendly calling of certain math functions
<del>whose output data-type is different than the input data-type in certain domains of the input.
<add>whose output data-type is different than the input data-type in certain
<add>domains of the input.
<ide> """
<ide>
<ide> __all__ = ['sqrt', 'log', 'log2', 'logn','log10', 'power', 'arccos', | 1 |
Text | Text | normalize internal links in 'why react' article | b872100be6e4793c0b344c72badede7309a1968f | <ide><path>docs/_posts/2013-06-05-why-react.md
<ide> some pretty cool things with it:
<ide> (including IE8) and automatically use
<ide> [event delegation](http://davidwalsh.name/event-delegate).
<ide>
<del>Head on over to
<del>[facebook.github.io/react](http://facebook.github.io/react) to check
<del>out what we have built. Our documentation is geared towards building
<del>apps with the framework, but if you are interested in the
<del>nuts and bolts
<del>[get in touch](http://facebook.github.io/react/support.html) with us!
<add>Head on over to [facebook.github.io/react](/react) to check out what we have
<add>built. Our documentation is geared towards building apps with the framework,
<add>but if you are interested in the nuts and bolts
<add>[get in touch](/react/support.html) with us!
<ide>
<ide> Thanks for reading! | 1 |
Javascript | Javascript | increase default auto scale to 125% | d4cdf5ce41ff50cc4f2033ff72194ebc28b7668c | <ide><path>web/viewer.js
<ide> var CACHE_SIZE = 20;
<ide> var CSS_UNITS = 96.0 / 72.0;
<ide> var SCROLLBAR_PADDING = 40;
<ide> var VERTICAL_PADDING = 5;
<add>var MAX_AUTO_SCALE = 1.25;
<ide> var MIN_SCALE = 0.25;
<ide> var MAX_SCALE = 4.0;
<ide> var SETTINGS_MEMORY = 20;
<ide> var PDFView = {
<ide> scale = Math.min(pageWidthScale, pageHeightScale);
<ide> break;
<ide> case 'auto':
<del> scale = Math.min(1.0, pageWidthScale);
<add> scale = Math.min(MAX_AUTO_SCALE, pageWidthScale);
<ide> break;
<ide> }
<ide> } | 1 |
Javascript | Javascript | call onanimationcomplete when reached last frame | f7e39620870787c4a49ee4c0085a46171d5f57b6 | <ide><path>src/Chart.Core.js
<ide>
<ide> this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject);
<ide>
<add> // Check if executed the last frame.
<ide> if (this.animations[i].animationObject.currentStep == this.animations[i].animationObject.numSteps){
<del> // executed the last frame. Remove the animation.
<add> // Call onAnimationComplete
<add> this.animations[i].animationObject.onAnimationComplete.call(this.animations[i].chartInstance);
<add> // Remove the animation.
<ide> this.animations.splice(i, 1);
<ide> // Keep the index in place to offset the splice
<ide> i--; | 1 |
Javascript | Javascript | reduce scope of eslint disable comment | fa86b36124ec022544256828bb9936ba3ed42ec0 | <ide><path>lib/internal/inspector/_inspect.js
<ide> * IN THE SOFTWARE.
<ide> */
<ide>
<del>// TODO(aduh95): remove restricted syntax errors
<del>/* eslint-disable no-restricted-syntax */
<del>
<ide> 'use strict';
<ide>
<ide> const {
<ide> const { EventEmitter } = require('events');
<ide> const net = require('net');
<ide> const util = require('util');
<ide> const {
<del> setInterval,
<del> setTimeout,
<add> setInterval: pSetInterval,
<add> setTimeout: pSetTimeout,
<ide> } = require('timers/promises');
<ide> const {
<ide> AbortController,
<ide> async function portIsFree(host, port, timeout = 9999) {
<ide> const ac = new AbortController();
<ide> const { signal } = ac;
<ide>
<del> setTimeout(timeout).then(() => ac.abort());
<add> pSetTimeout(timeout).then(() => ac.abort());
<ide>
<del> const asyncIterator = setInterval(retryDelay);
<add> const asyncIterator = pSetInterval(retryDelay);
<ide> while (true) {
<ide> await asyncIterator.next();
<ide> if (signal.aborted) {
<del> throw new StartupError(
<add> throw new StartupError( // eslint-disable-line no-restricted-syntax
<ide> `Timeout (${timeout}) waiting for ${host}:${port} to be free`);
<ide> }
<ide> const error = await new Promise((resolve) => {
<ide> class NodeInspector {
<ide> return;
<ide> } catch (error) {
<ide> debuglog('connect failed', error);
<del> await setTimeout(1000);
<add> await pSetTimeout(1000);
<ide> }
<ide> }
<ide> this.stdout.write(' failed to connect, please retry\n'); | 1 |
Javascript | Javascript | pretify some tests with $destroy events | bca96e7c7cc723a091241fddd6845d6de262a3c9 | <ide><path>test/directive/ngViewSpec.js
<ide> describe('ng-view', function() {
<ide> var createCtrl = function(name) {
<ide> return function($scope) {
<ide> log.push('init-' + name);
<del> var destroy = $scope.$destroy;
<del> $scope.$destroy = function() {
<del> log.push('destroy-' + name);
<del> destroy.call($scope);
<del> }
<add> $scope.$on('$destroy', function() {log.push('destroy-' + name);});
<ide> };
<ide> };
<ide>
<ide> describe('ng-view', function() {
<ide> function createController(name) {
<ide> return function($scope) {
<ide> log.push('init-' + name);
<del> var destroy = $scope.$destroy;
<del> $scope.$destroy = function() {
<del> log.push('destroy-' + name);
<del> destroy.call($scope);
<del> }
<add> $scope.$on('$destroy', logger('destroy-' + name));
<ide> $scope.$on('$routeUpdate', logger('route-update'));
<ide> };
<ide> } | 1 |
Ruby | Ruby | add checks for xcode/clt minimum versions | 4015d0465a975aaac26d5a47395ab61e29d1702f | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide> end
<ide> end
<ide>
<add> def minimum_version
<add> case MacOS.version
<add> when "10.12" then "8.0"
<add> else "2.0"
<add> end
<add> end
<add>
<add> def minimum_version?
<add> version < minimum_version
<add> end
<add>
<ide> def prerelease?
<ide> # TODO: bump to version >= "8.3" after Xcode 8.2 is stable.
<ide> version >= "8.2"
<ide> def latest_version
<ide> end
<ide> end
<ide>
<add> def minimum_version
<add> case MacOS.version
<add> when "10.12" then "8.0.0"
<add> else "4.0.0"
<add> end
<add> end
<add>
<add> def minimum_version?
<add> version < minimum_version
<add> end
<add>
<ide> def outdated?
<ide> if MacOS.version >= :mavericks
<ide> version = Utils.popen_read("#{MAVERICKS_PKG_PATH}/usr/bin/clang --version") | 1 |
Javascript | Javascript | remove simd support from util.format() | 2ba4eeadbb816068139759957c8443565a4d795a | <ide><path>lib/util.js
<ide> const inspectDefaultOptions = Object.seal({
<ide> });
<ide>
<ide> var Debug;
<del>var simdFormatters;
<del>
<del>// SIMD is only available when --harmony_simd is specified on the command line
<del>// and the set of available types differs between v5 and v6, that's why we use
<del>// a map to look up and store the formatters. It also provides a modicum of
<del>// protection against users monkey-patching the SIMD object.
<del>if (typeof global.SIMD === 'object' && global.SIMD !== null) {
<del> simdFormatters = new Map();
<del>
<del> const make =
<del> (extractLane, count) => (ctx, value, recurseTimes, visibleKeys, keys) => {
<del> const output = new Array(count);
<del> for (var i = 0; i < count; i += 1)
<del> output[i] = formatPrimitive(ctx, extractLane(value, i));
<del> return output;
<del> };
<del>
<del> const countPerType = {
<del> Bool16x8: 8,
<del> Bool32x4: 4,
<del> Bool8x16: 16,
<del> Float32x4: 4,
<del> Int16x8: 8,
<del> Int32x4: 4,
<del> Int8x16: 16,
<del> Uint16x8: 8,
<del> Uint32x4: 4,
<del> Uint8x16: 16
<del> };
<del>
<del> for (const key in countPerType) {
<del> const type = global.SIMD[key];
<del> simdFormatters.set(type, make(type.extractLane, countPerType[key]));
<del> }
<del>}
<ide>
<ide> function tryStringify(arg) {
<ide> try {
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> braces = ['{', '}'];
<ide> formatter = formatPromise;
<ide> } else {
<del> let maybeSimdFormatter;
<ide> if (binding.isMapIterator(value)) {
<ide> constructor = { name: 'MapIterator' };
<ide> braces = ['{', '}'];
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> braces = ['{', '}'];
<ide> empty = false;
<ide> formatter = formatCollectionIterator;
<del> } else if (simdFormatters &&
<del> typeof constructor === 'function' &&
<del> (maybeSimdFormatter = simdFormatters.get(constructor))) {
<del> braces = ['[', ']'];
<del> formatter = maybeSimdFormatter;
<ide> } else {
<ide> // Unset the constructor to prevent "Object {...}" for ordinary objects.
<ide> if (constructor && constructor.name === 'Object')
<ide><path>test/parallel/test-util-inspect-simd.js
<del>// Flags: --harmony_simd
<del>/* global SIMD */
<del>'use strict';
<del>
<del>require('../common');
<del>const assert = require('assert');
<del>const inspect = require('util').inspect;
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Bool16x8()),
<del> 'Bool16x8 [ false, false, false, false, false, false, false, false ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Bool32x4()),
<del> 'Bool32x4 [ false, false, false, false ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Bool8x16()),
<del> 'Bool8x16 [\n false,\n false,\n false,\n false,\n false,\n' +
<del> ' false,\n false,\n false,\n false,\n false,\n false,\n' +
<del> ' false,\n false,\n false,\n false,\n false ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Bool32x4()),
<del> 'Bool32x4 [ false, false, false, false ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Float32x4()),
<del> 'Float32x4 [ NaN, NaN, NaN, NaN ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Int16x8()),
<del> 'Int16x8 [ 0, 0, 0, 0, 0, 0, 0, 0 ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Int32x4()),
<del> 'Int32x4 [ 0, 0, 0, 0 ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Int8x16()),
<del> 'Int8x16 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Uint16x8()),
<del> 'Uint16x8 [ 0, 0, 0, 0, 0, 0, 0, 0 ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Uint32x4()),
<del> 'Uint32x4 [ 0, 0, 0, 0 ]');
<del>
<del>assert.strictEqual(
<del> inspect(SIMD.Uint8x16()),
<del> 'Uint8x16 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]');
<del>
<del>// Tests from test-inspect.js that should not fail with --harmony_simd.
<del>assert.strictEqual(inspect([]), '[]');
<del>assert.strictEqual(inspect([0]), '[ 0 ]');
<del>assert.strictEqual(inspect({}), '{}');
<del>assert.strictEqual(inspect({foo: 42}), '{ foo: 42 }');
<del>assert.strictEqual(inspect(null), 'null');
<del>assert.strictEqual(inspect(true), 'true');
<del>assert.strictEqual(inspect(false), 'false'); | 2 |
Ruby | Ruby | implement hash equality for whereclause | 3bac3a4e8bb083daa3e2a0994482f9d944d6896c | <ide><path>activerecord/lib/active_record/relation/where_clause.rb
<ide> def ==(other)
<ide> other.is_a?(WhereClause) &&
<ide> predicates == other.predicates
<ide> end
<add> alias :eql? :==
<add>
<add> def hash
<add> [self.class, predicates].hash
<add> end
<ide>
<ide> def invert
<ide> if predicates.size == 1
<ide><path>activerecord/test/cases/relation/where_clause_test.rb
<ide> class WhereClauseTest < ActiveRecord::TestCase
<ide> assert_equal only_common, common_with_extra.or(only_common)
<ide> end
<ide>
<add> test "supports hash equality" do
<add> h = Hash.new(0)
<add> h[WhereClause.new(["a"])] += 1
<add> h[WhereClause.new(["a"])] += 1
<add> h[WhereClause.new(["b"])] += 1
<add>
<add> expected = {
<add> WhereClause.new(["a"]) => 2,
<add> WhereClause.new(["b"]) => 1
<add> }
<add> assert_equal expected, h
<add> end
<add>
<ide> private
<ide> def table
<ide> Arel::Table.new("table") | 2 |
Ruby | Ruby | fix missing `magenta` in tty | db88ca1e1871df380a6408dadc2bdb81a4b25f3e | <ide><path>Library/Homebrew/cask/lib/hbc/utils.rb
<ide> def odebug(title, *sput)
<ide> if $stdout.tty? && title.to_s.length > width
<ide> title = title.to_s[0, width - 3] + "..."
<ide> end
<del> puts "#{Tty.magenta}==> #{title}#{Tty.reset}"
<add> puts "#{Tty.magenta}==>#{Tty.reset} #{Tty.white}#{title}#{Tty.reset}"
<ide> puts sput unless sput.empty?
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils.rb
<ide> def white
<ide> bold 39
<ide> end
<ide>
<add> def magenta
<add> bold 35
<add> end
<add>
<ide> def red
<ide> underline 31
<ide> end | 2 |
Python | Python | add a unit test for plugin's sorted stats method | 7bd0cff0aaa4bcec32eec67e1a97c4f952eb5091 | <ide><path>unitest.py
<ide> from glances.thresholds import GlancesThresholdWarning
<ide> from glances.thresholds import GlancesThresholdCritical
<ide> from glances.thresholds import GlancesThresholds
<add>from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<ide> # Global variables
<ide> # =================
<ide> def test_013_gpu(self):
<ide> self.assertTrue(type(stats_grab) is list, msg='GPU stats is not a list')
<ide> print('INFO: GPU stats: %s' % stats_grab)
<ide>
<add> def test_014_sorted_stats(self):
<add> """Check sorted stats method."""
<add> print('INFO: [TEST_015] Check sorted stats method')
<add> aliases = {
<add> "key2": "alias11",
<add> "key5": "alias2",
<add> }
<add> unsorted_stats = [
<add> {"key": "key4"},
<add> {"key": "key2"},
<add> {"key": "key5"},
<add> {"key": "key21"},
<add> {"key": "key3"},
<add> ]
<add>
<add> gp = GlancesPlugin()
<add> gp.get_key = lambda: "key"
<add> gp.has_alias = aliases.get
<add> gp.stats = unsorted_stats
<add>
<add> sorted_stats = gp.sorted_stats()
<add> self.assertEqual(len(sorted_stats), 5)
<add> self.assertEqual(sorted_stats[0]["key"], "key5")
<add> self.assertEqual(sorted_stats[1]["key"], "key2")
<add> self.assertEqual(sorted_stats[2]["key"], "key3")
<add> self.assertEqual(sorted_stats[3]["key"], "key4")
<add> self.assertEqual(sorted_stats[4]["key"], "key21")
<add>
<ide> def test_094_thresholds(self):
<ide> """Test thresholds classes"""
<ide> print('INFO: [TEST_094] Thresholds') | 1 |
Mixed | Ruby | remove body content from redirect responses | c2e756a944fd3ca2efa58bd285c0e75e0b4794ab | <ide><path>actionpack/CHANGELOG.md
<add>* Make `redirect_to` return an empty response body.
<add>
<add> Application controllers that wish to add a response body after calling
<add> `redirect_to` can continue to do so.
<add>
<add> *Jon Dufresne*
<add>
<ide> * Use non-capturing group for subdomain matching in `ActionDispatch::HostAuthorization`
<ide>
<ide> Since we do nothing with the captured subdomain group, we can use a non-capturing group instead.
<ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> def redirect_to(options = {}, response_options = {})
<ide>
<ide> self.status = _extract_redirect_to_status(options, response_options)
<ide> self.location = _enforce_open_redirect_protection(_compute_redirect_to_location(request, options), allow_other_host: allow_other_host)
<del> self.response_body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(response.location)}\">redirected</a>.</body></html>"
<add> self.response_body = ""
<ide> end
<ide>
<ide> # Soft deprecated alias for #redirect_back_or_to where the +fallback_location+ location is supplied as a keyword argument instead
<ide><path>actionpack/lib/action_dispatch/middleware/actionable_exceptions.rb
<ide> def redirect_to(location)
<ide> uri = URI.parse location
<ide>
<ide> if uri.relative? || uri.scheme == "http" || uri.scheme == "https"
<del> body = "<html><body>You are being <a href=\"#{ERB::Util.unwrapped_html_escape(location)}\">redirected</a>.</body></html>"
<add> body = ""
<ide> else
<ide> return [400, { "Content-Type" => "text/plain" }, ["Invalid redirection URI"]]
<ide> end
<ide><path>actionpack/lib/action_dispatch/routing/redirection.rb
<ide> def serve(req)
<ide>
<ide> req.commit_flash
<ide>
<del> body = %(<html><body>You are being <a href="#{ERB::Util.unwrapped_html_escape(uri.to_s)}">redirected</a>.</body></html>)
<add> body = ""
<ide>
<ide> headers = {
<ide> "Location" => uri.to_s,
<ide><path>actionpack/test/controller/integration_test.rb
<ide> def test_redirect
<ide> assert_response 302
<ide> assert_response :redirect
<ide> assert_response :found
<del> assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body
<add> assert_equal "", response.body
<ide> assert_kind_of Nokogiri::HTML::Document, html_document
<ide> assert_equal 1, request_count
<ide>
<ide><path>actionpack/test/dispatch/prefix_generation_test.rb
<ide> def setup
<ide> def verify_redirect(url, status = 301)
<ide> assert_equal status, response.status
<ide> assert_equal url, response.headers["Location"]
<del> assert_equal expected_redirect_body(url), response.body
<del> end
<del>
<del> def expected_redirect_body(url)
<del> %(<html><body>You are being <a href="#{url}">redirected</a>.</body></html>)
<add> assert_equal "", response.body
<ide> end
<ide> end
<ide>
<ide> def app
<ide> def verify_redirect(url, status = 301)
<ide> assert_equal status, response.status
<ide> assert_equal url, response.headers["Location"]
<del> assert_equal expected_redirect_body(url), response.body
<del> end
<del>
<del> def expected_redirect_body(url)
<del> %(<html><body>You are being <a href="#{url}">redirected</a>.</body></html>)
<add> assert_equal "", response.body
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def with_https
<ide> def verify_redirect(url, status = 301)
<ide> assert_equal status, @response.status
<ide> assert_equal url, @response.headers["Location"]
<del> assert_equal expected_redirect_body(url), @response.body
<del> end
<del>
<del> def expected_redirect_body(url)
<del> %(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
<add> assert_equal "", @response.body
<ide> end
<ide> end
<ide>
<ide> def app; APP end
<ide> def verify_redirect(url, status = 301)
<ide> assert_equal status, @response.status
<ide> assert_equal url, @response.headers["Location"]
<del> assert_equal expected_redirect_body(url), @response.body
<del> end
<del>
<del> def expected_redirect_body(url)
<del> %(<html><body>You are being <a href="#{ERB::Util.h(url)}">redirected</a>.</body></html>)
<add> assert_equal "", @response.body
<ide> end
<ide> end
<ide> | 7 |
Javascript | Javascript | increase dgram timeout for armv6 | bcc6d4740c7c5243f006a0ca3c28bc2585012e21 | <ide><path>test/internet/test-dgram-broadcast-multi-process.js
<ide> var common = require('../common'),
<ide> Buffer = require('buffer').Buffer,
<ide> fork = require('child_process').fork,
<ide> LOCAL_BROADCAST_HOST = '255.255.255.255',
<del> TIMEOUT = 5000,
<add> TIMEOUT = common.platformTimeout(5000),
<ide> messages = [
<ide> new Buffer('First message to send'),
<ide> new Buffer('Second message to send'),
<ide><path>test/internet/test-dgram-multicast-multi-process.js
<ide> var common = require('../common'),
<ide> Buffer = require('buffer').Buffer,
<ide> fork = require('child_process').fork,
<ide> LOCAL_BROADCAST_HOST = '224.0.0.114',
<del> TIMEOUT = 5000,
<add> TIMEOUT = common.platformTimeout(5000),
<ide> messages = [
<ide> new Buffer('First message to send'),
<ide> new Buffer('Second message to send'), | 2 |
Javascript | Javascript | remove unused injected $window | f132ce740a869ac68d76e88ab1b2d50a829ed52e | <ide><path>src/ng/controller.js
<ide> function $ControllerProvider() {
<ide> }
<ide> };
<ide>
<del> this.$get = ['$injector', '$window', function($injector, $window) {
<add> this.$get = ['$injector', function($injector) {
<ide>
<ide> /**
<ide> * @ngdoc service | 1 |
Text | Text | add a missing definite article | b4905859d55cf756d3855c1deddb68a9509bdab4 | <ide><path>docs/README.md
<ide> aws cloudfront create-invalidation --profile docs.docker.com --distribution-id
<ide> When using Docker on Mac OSX the man pages will be missing by default. You can manually generate them by following these steps:
<ide>
<ide> 1. Checkout the docker source. You must clone into your `/Users` directory because Boot2Docker can only share this path
<del> with docker containers.
<add> with the docker containers.
<ide>
<ide> $ git clone https://github.com/docker/docker.git
<ide> | 1 |
Javascript | Javascript | add minify flag to react-native bundle command | 3f969cb1db3a39dd8a4fd622abbb7e4270a84216 | <ide><path>local-cli/bundle/buildBundle.js
<ide> async function buildBundle(
<ide> maxWorkers: number,
<ide> resetCache: boolean,
<ide> transformer: string,
<add> minify: boolean,
<ide> },
<ide> config: ConfigT,
<ide> output = outputBundle,
<ide> async function buildBundle(
<ide> entryFile: args.entryFile,
<ide> sourceMapUrl,
<ide> dev: args.dev,
<del> minify: !args.dev,
<add> minify: args.minify !== undefined ? args.minify : !args.dev,
<ide> platform: args.platform,
<ide> };
<ide>
<ide><path>local-cli/bundle/bundleCommandLineArgs.js
<ide> module.exports = [
<ide> description: 'If false, warnings are disabled and the bundle is minified',
<ide> parse: (val) => val === 'false' ? false : true,
<ide> default: true,
<add> }, {
<add> command: '--minify [boolean]',
<add> description: 'Allows overriding whether bundle is minified. This defaults to ' +
<add> 'false if dev is true, and true if dev is false. Disabling minification ' +
<add> 'can be useful for speeding up production builds for testing purposes.',
<add> parse: (val) => val === 'false' ? false : true,
<ide> }, {
<ide> command: '--bundle-output <string>',
<ide> description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle', | 2 |
Javascript | Javascript | remove trailing whitespace | 95f8a8bab0cff27025a795cb00bd1e59b28aaded | <ide><path>src/ng/directive/ngBind.js
<ide> var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate
<ide> * @name ngBindHtml
<ide> *
<ide> * @description
<del> * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
<del> * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
<del> * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
<del> * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
<add> * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
<add> * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
<add> * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
<add> * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
<ide> * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
<ide> *
<ide> * You may also bypass sanitization for values you know are safe. To do so, bind to | 1 |
Javascript | Javascript | remove unnecessary comma in mtlloader | 892a92d47eb18ccfc8b0dd69fd09f6966fd55a20 | <ide><path>examples/js/loaders/MTLLoader.js
<ide> THREE.MTLLoader.MaterialCreator.prototype = {
<ide> var texParams = {
<ide>
<ide> scale: new THREE.Vector2( 1, 1 ),
<del> offset: new THREE.Vector2( 0, 0 ),
<add> offset: new THREE.Vector2( 0, 0 )
<ide>
<ide> };
<ide> | 1 |
PHP | PHP | fix failing htmlhelper tests | fd575d4b1fd3227d401e797aee41848b9ad9fa8a | <ide><path>lib/Cake/Test/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testLink() {
<ide> $this->assertTags($result, $expected);
<ide>
<ide> Router::reload();
<add> Router::connect('/:controller', array('action' => 'index'));
<add> Router::connect('/:controller/:action/*');
<ide>
<del> $result = $this->Html->link('Posts', array('controller' => 'posts', 'action' => 'index', 'full_base' => true));
<add> $result = $this->Html->link('Posts', array('controller' => 'posts', 'action' => 'index', '_full' => true));
<ide> $expected = array('a' => array('href' => FULL_BASE_URL . '/posts'), 'Posts', '/a');
<ide> $this->assertTags($result, $expected);
<ide>
<ide> public function testLink() {
<ide> * @return void
<ide> */
<ide> public function testImageTag() {
<add> Router::connect('/:controller', array('action' => 'index'));
<add> Router::connect('/:controller/:action/*');
<add>
<ide> $this->Html->request->webroot = '';
<ide>
<ide> $result = $this->Html->image('test.gif');
<ide> public function testNestedList() {
<ide> * @return void
<ide> */
<ide> public function testMeta() {
<add> Router::connect('/:controller', array('action' => 'index'));
<add>
<ide> $result = $this->Html->meta('this is an rss feed', array('controller' => 'posts', 'ext' => 'rss'));
<ide> $this->assertTags($result, array('link' => array('href' => 'preg:/.*\/posts\.rss/', 'type' => 'application/rss+xml', 'rel' => 'alternate', 'title' => 'this is an rss feed')));
<ide> | 1 |
Javascript | Javascript | combine properties using defineproperties | 0ac04ecee20f00cf3daaf006496d461bb9fecbc2 | <ide><path>lib/_stream_writable.js
<ide> const {
<ide> Boolean,
<ide> FunctionPrototype,
<ide> ObjectDefineProperty,
<add> ObjectDefineProperties,
<ide> ObjectSetPrototypeOf,
<ide> Symbol,
<ide> SymbolHasInstance,
<ide> Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
<ide> return this;
<ide> };
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'writableBuffer', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get: function() {
<del> return this._writableState && this._writableState.getBuffer();
<del> }
<del>});
<del>
<del>ObjectDefineProperty(Writable.prototype, 'writableEnded', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get: function() {
<del> return this._writableState ? this._writableState.ending : false;
<del> }
<del>});
<del>
<del>ObjectDefineProperty(Writable.prototype, 'writableHighWaterMark', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get: function() {
<del> return this._writableState && this._writableState.highWaterMark;
<del> }
<del>});
<del>
<del>ObjectDefineProperty(Writable.prototype, 'writableCorked', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get: function() {
<del> return this._writableState ? this._writableState.corked : 0;
<del> }
<del>});
<del>
<ide> // If we're already writing something, then just put this
<ide> // in the queue, and wait our turn. Otherwise, call _write
<ide> // If we return false, then we need a drain event, so set that flag.
<ide> Writable.prototype.end = function(chunk, encoding, cb) {
<ide> return this;
<ide> };
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'writableLength', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get() {
<del> return this._writableState.length;
<del> }
<del>});
<del>
<ide> function needFinish(state) {
<ide> return (state.ending &&
<ide> state.length === 0 &&
<ide> function onFinished(stream, state, cb) {
<ide> stream.prependListener('error', onerror);
<ide> }
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'writable', {
<del> get() {
<del> const w = this._writableState;
<del> if (!w) return false;
<del> if (w.writable !== undefined) return w.writable;
<del> return Boolean(!w.destroyed && !w.errored && !w.ending);
<add>ObjectDefineProperties(Writable.prototype, {
<add>
<add> destroyed: {
<add> get() {
<add> return this._writableState ? this._writableState.destroyed : false;
<add> },
<add> set(value) {
<add> // Backward compatibility, the user is explicitly managing destroyed
<add> if (this._writableState) {
<add> this._writableState.destroyed = value;
<add> }
<add> }
<add> },
<add>
<add> writable: {
<add> get() {
<add> const w = this._writableState;
<add> if (!w) return false;
<add> if (w.writable !== undefined) return w.writable;
<add> return Boolean(!w.destroyed && !w.errored && !w.ending);
<add> },
<add> set(val) {
<add> // Backwards compatible.
<add> if (this._writableState) {
<add> this._writableState.writable = !!val;
<add> }
<add> }
<ide> },
<del> set(val) {
<del> // Backwards compat.
<del> if (this._writableState) {
<del> this._writableState.writable = !!val;
<add>
<add> writableFinished: {
<add> get() {
<add> return this._writableState ? this._writableState.finished : false;
<ide> }
<del> }
<del>});
<add> },
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'destroyed', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get() {
<del> if (this._writableState === undefined) {
<del> return false;
<add> writableObjectMode: {
<add> get() {
<add> return this._writableState ? this._writableState.objectMode : false;
<ide> }
<del> return this._writableState.destroyed;
<ide> },
<del> set(value) {
<del> // We ignore the value if the stream
<del> // has not been initialized yet
<del> if (!this._writableState) {
<del> return;
<add>
<add> writableBuffer: {
<add> get() {
<add> return this._writableState && this._writableState.getBuffer();
<ide> }
<add> },
<ide>
<del> // Backward compatibility, the user is explicitly
<del> // managing destroyed
<del> this._writableState.destroyed = value;
<del> }
<del>});
<add> writableEnded: {
<add> get() {
<add> return this._writableState ? this._writableState.ending : false;
<add> }
<add> },
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'writableObjectMode', {
<del> enumerable: false,
<del> get() {
<del> return this._writableState ? this._writableState.objectMode : false;
<del> }
<del>});
<add> writableHighWaterMark: {
<add> get() {
<add> return this._writableState && this._writableState.highWaterMark;
<add> }
<add> },
<ide>
<del>ObjectDefineProperty(Writable.prototype, 'writableFinished', {
<del> // Making it explicit this property is not enumerable
<del> // because otherwise some prototype manipulation in
<del> // userland will fail
<del> enumerable: false,
<del> get() {
<del> return this._writableState ? this._writableState.finished : false;
<add> writableCorked: {
<add> get() {
<add> return this._writableState ? this._writableState.corked : 0;
<add> }
<add> },
<add>
<add> writableLength: {
<add> get() {
<add> return this._writableState && this._writableState.length;
<add> }
<ide> }
<ide> });
<ide> | 1 |
Go | Go | remove useless http call from export | 6d9439c627e36349679249d991400da45eb75587 | <ide><path>api/client/export.go
<ide> package client
<ide> import (
<ide> "errors"
<ide> "io"
<del> "net/url"
<ide> "os"
<ide>
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> func (cli *DockerCli) CmdExport(args ...string) error {
<ide> return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.")
<ide> }
<ide>
<del> if len(cmd.Args()) == 1 {
<del> image := cmd.Arg(0)
<del> if err := cli.stream("GET", "/containers/"+image+"/export", nil, output, nil); err != nil {
<del> return err
<del> }
<del> } else {
<del> v := url.Values{}
<del> for _, arg := range cmd.Args() {
<del> v.Add("names", arg)
<del> }
<del> if err := cli.stream("GET", "/containers/get?"+v.Encode(), nil, output, nil); err != nil {
<del> return err
<del> }
<add> image := cmd.Arg(0)
<add> if err := cli.stream("GET", "/containers/"+image+"/export", nil, output, nil); err != nil {
<add> return err
<ide> }
<ide>
<ide> return nil | 1 |
PHP | PHP | fix integration test case with form tampering | f55b44a75c593fc22143c6031c1d952747d00b27 | <ide><path>src/TestSuite/IntegrationTestCase.php
<ide> protected function _buildRequest($url, $method, $data)
<ide> protected function _addTokens($url, $data)
<ide> {
<ide> if ($this->_securityToken === true) {
<del> $keys = Hash::flatten($data);
<del> $tokenData = $this->_buildFieldToken($url, array_keys($keys));
<add> $keys = array_map(function ($field) {
<add> return preg_replace('/(\.\d+)+$/', '', $field);
<add> }, array_keys(Hash::flatten($data)));
<add> $tokenData = $this->_buildFieldToken($url, array_unique($keys));
<ide> $data['_Token'] = $tokenData;
<ide> }
<ide>
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function testPostAndErrorHandling()
<ide> }
<ide>
<ide> /**
<del> * Test posting to a secured form action action.
<add> * Test posting to a secured form action.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testPostSecuredForm()
<ide> $this->assertResponseContains('Request was accepted');
<ide> }
<ide>
<add> /**
<add> * Test posting to a secured form action with nested data.
<add> *
<add> * @return void
<add> */
<add> public function testPostSecuredFormNestedData()
<add> {
<add> $this->enableSecurityToken();
<add> $data = [
<add> 'title' => 'New post',
<add> 'comments' => [
<add> ['comment' => 'A new comment']
<add> ],
<add> 'tags' => ['_ids' => [1, 2, 3, 4]]
<add> ];
<add> $this->post('/posts/securePost', $data);
<add> $this->assertResponseOk();
<add> $this->assertResponseContains('Request was accepted');
<add> }
<add>
<ide> /**
<ide> * Test posting to a secured form action action.
<ide> * | 2 |
Java | Java | transform absolute links in resourcetransformers | 125ae99035653496efbf6d03270bbbdde5828d3a | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/AppCacheManifestTransformer.java
<ide> * applications spec</a>
<ide> * @since 4.1
<ide> */
<del>public class AppCacheManifestTransformer implements ResourceTransformer {
<add>public class AppCacheManifestTransformer extends ResourceTransformerSupport {
<ide>
<ide> private static final String MANIFEST_HEADER = "CACHE MANIFEST";
<ide>
<ide> public Resource transform(HttpServletRequest request, Resource resource, Resourc
<ide> hashBuilder.appendString(line);
<ide> }
<ide> else {
<del> contentWriter.write(currentTransformer.transform(line, hashBuilder, resource, transformerChain) + "\n");
<add> contentWriter.write(currentTransformer.transform(line, hashBuilder, resource, transformerChain, request) + "\n");
<ide> }
<ide> }
<ide>
<ide> private static interface SectionTransformer {
<ide> * for the current manifest section (CACHE, NETWORK, FALLBACK, etc).
<ide> */
<ide> String transform(String line, HashBuilder builder, Resource resource,
<del> ResourceTransformerChain transformerChain) throws IOException;
<add> ResourceTransformerChain transformerChain, HttpServletRequest request) throws IOException;
<ide> }
<ide>
<ide>
<ide> private static class NoOpSection implements SectionTransformer {
<ide>
<del> public String transform(String line, HashBuilder builder, Resource resource, ResourceTransformerChain transformerChain)
<del> throws IOException {
<add> public String transform(String line, HashBuilder builder, Resource resource,
<add> ResourceTransformerChain transformerChain, HttpServletRequest request) throws IOException {
<ide>
<ide> builder.appendString(line);
<ide> return line;
<ide> }
<ide> }
<ide>
<ide>
<del> private static class CacheSection implements SectionTransformer {
<add> private class CacheSection implements SectionTransformer {
<ide>
<ide> private final String COMMENT_DIRECTIVE = "#";
<ide>
<ide> @Override
<del> public String transform(String line, HashBuilder builder,
<del> Resource resource, ResourceTransformerChain transformerChain) throws IOException {
<add> public String transform(String line, HashBuilder builder, Resource resource,
<add> ResourceTransformerChain transformerChain, HttpServletRequest request) throws IOException {
<ide>
<ide> if (isLink(line) && !hasScheme(line)) {
<del> Resource appCacheResource = transformerChain.getResolverChain().resolveResource(null, line, Arrays.asList(resource));
<del> String path = transformerChain.getResolverChain().resolveUrlPath(line, Arrays.asList(resource));
<add> ResourceResolverChain resolverChain = transformerChain.getResolverChain();
<add> Resource appCacheResource = resolverChain.resolveResource(null, line, Arrays.asList(resource));
<add> String path = resolveUrlPath(line, request, resource, transformerChain);
<ide> builder.appendResource(appCacheResource);
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Link modified: " + path + " (original: " + line + ")");
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/CssLinkResourceTransformer.java
<ide> import java.io.StringWriter;
<ide> import java.nio.charset.Charset;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.1
<ide> */
<del>public class CssLinkResourceTransformer implements ResourceTransformer {
<add>public class CssLinkResourceTransformer extends ResourceTransformerSupport {
<ide>
<ide> private static final Log logger = LogFactory.getLog(CssLinkResourceTransformer.class);
<ide>
<ide> public Resource transform(HttpServletRequest request, Resource resource, Resourc
<ide> String link = content.substring(info.getStart(), info.getEnd());
<ide> String newLink = null;
<ide> if (!hasScheme(link)) {
<del> newLink = transformerChain.getResolverChain().resolveUrlPath(link, Arrays.asList(resource));
<add> newLink = resolveUrlPath(link, request, resource, transformerChain);
<ide> }
<ide> if (logger.isTraceEnabled()) {
<ide> if (newLink != null && !link.equals(newLink)) {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceTransformerSupport.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.servlet.resource;
<add>
<add>import java.util.Arrays;
<add>
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>import org.springframework.core.io.Resource;
<add>
<add>/**
<add> * A base class for a {@code ResourceTransformer} with an optional helper method
<add> * for resolving public links within a transformed resource.
<add> *
<add> * @author Brian Clozel
<add> * @author Rossen Stoyanchev
<add> * @since 4.1
<add> */
<add>public abstract class ResourceTransformerSupport implements ResourceTransformer {
<add>
<add> private ResourceUrlProvider resourceUrlProvider;
<add>
<add>
<add> /**
<add> * Configure a {@link ResourceUrlProvider} to use when resolving the public
<add> * URL of links in a transformed resource (e.g. import links in a CSS file).
<add> * This is required only for links expressed as full paths, i.e. including
<add> * context and servlet path, and not for relative links.
<add> *
<add> * <p>By default this property is not set. In that case if a
<add> * {@code ResourceUrlProvider} is needed an attempt is made to find the
<add> * {@code ResourceUrlProvider} exposed through the
<add> * {@link org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor
<add> * ResourceUrlProviderExposingInterceptor} (configured by default in the MVC
<add> * Java config and XML namespace). Therefore explicitly configuring this
<add> * property should not be needed in most cases.
<add> * @param resourceUrlProvider the URL provider to use
<add> */
<add> public void setResourceUrlProvider(ResourceUrlProvider resourceUrlProvider) {
<add> this.resourceUrlProvider = resourceUrlProvider;
<add> }
<add>
<add> /**
<add> * @return the configured {@code ResourceUrlProvider}.
<add> */
<add> public ResourceUrlProvider getResourceUrlProvider() {
<add> return this.resourceUrlProvider;
<add> }
<add>
<add>
<add> /**
<add> * A transformer can use this method when a resource being transformed
<add> * contains links to other resources. Such links need to be replaced with the
<add> * public facing link as determined by the resource resolver chain (e.g. the
<add> * public URL may have a version inserted).
<add> *
<add> * @param resourcePath the path to a resource that needs to be re-written
<add> * @param request the current request
<add> * @param resource the resource being transformed
<add> * @param transformerChain the transformer chain
<add> * @return the resolved URL or null
<add> */
<add> protected String resolveUrlPath(String resourcePath, HttpServletRequest request,
<add> Resource resource, ResourceTransformerChain transformerChain) {
<add>
<add> if (!resourcePath.startsWith("/")) {
<add> // try resolving as relative path
<add> return transformerChain.getResolverChain().resolveUrlPath(resourcePath, Arrays.asList(resource));
<add> }
<add> else {
<add> // full resource path
<add> ResourceUrlProvider urlProvider = findResourceUrlProvider(request);
<add> return (urlProvider != null ? urlProvider.getForRequestUrl(request, resourcePath) : null);
<add> }
<add> }
<add>
<add> private ResourceUrlProvider findResourceUrlProvider(HttpServletRequest request) {
<add> if (this.resourceUrlProvider != null) {
<add> return this.resourceUrlProvider;
<add> }
<add> return (ResourceUrlProvider) request.getAttribute(
<add> ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR);
<add> }
<add>
<add>}
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/LinkRewriteTransformerTests.java
<add>/*
<add> * Copyright 2002-2014 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.servlet.resource;
<add>
<add>import static org.junit.Assert.assertEquals;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import org.springframework.core.io.ClassPathResource;
<add>import org.springframework.core.io.Resource;
<add>import org.springframework.mock.web.test.MockHttpServletRequest;
<add>import org.springframework.web.servlet.HandlerMapping;
<add>
<add>import javax.servlet.http.HttpServletRequest;
<add>
<add>/**
<add> * Unit tests for {@code LinkRewriteTransformer}
<add> *
<add> * @author Brian Clozel
<add> * @author Rossen Stoyanchev
<add> */
<add>public class LinkRewriteTransformerTests {
<add>
<add> private ResourceTransformerChain transformerChain;
<add>
<add> private TestTransformer transformer;
<add>
<add> private MockHttpServletRequest request;
<add>
<add>
<add> @Before
<add> public void setUp() {
<add> VersionResourceResolver versionResolver = new VersionResourceResolver();
<add> versionResolver.setStrategyMap(Collections.singletonMap("/**", new ContentVersionStrategy()));
<add>
<add> List<ResourceResolver> resolvers = new ArrayList<>();
<add> resolvers.add(versionResolver);
<add> resolvers.add(new PathResourceResolver());
<add> this.transformerChain = new DefaultResourceTransformerChain(new DefaultResourceResolverChain(resolvers), null);
<add>
<add> List<Resource> locations = new ArrayList<>();
<add> locations.add(new ClassPathResource("test/", getClass()));
<add>
<add> ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
<add> handler.setLocations(locations);
<add> handler.setResourceResolvers(resolvers);
<add>
<add> ResourceUrlProvider urlProvider = new ResourceUrlProvider();
<add> urlProvider.setHandlerMap(Collections.singletonMap("/resources/**", handler));
<add>
<add> this.transformer = new TestTransformer();
<add> this.transformer.setResourceUrlProvider(urlProvider);
<add>
<add> this.request = new MockHttpServletRequest();
<add> }
<add>
<add> @Test
<add> public void rewriteAbsolutePath() throws Exception {
<add> this.request.setRequestURI("/servlet/context/resources/main.css");
<add> this.request.setMethod("GET");
<add> this.request.setServletPath("/servlet");
<add> this.request.setContextPath("/context");
<add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/resources/main.css");
<add>
<add> String resourcePath = "/servlet/context/resources/bar.css";
<add> Resource mainCss = new ClassPathResource("test/main.css", getClass());
<add> String actual = this.transformer.resolveUrlPath(resourcePath, this.request, mainCss, this.transformerChain);
<add> assertEquals("/servlet/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
<add>
<add> actual = this.transformer.resolveUrlPath("bar.css", this.request, mainCss, this.transformerChain);
<add> assertEquals("bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
<add> }
<add>
<add> @Test
<add> public void rewriteRelativePath() throws Exception {
<add> this.request.setRequestURI("/servlet/context/resources/main.css");
<add> this.request.setMethod("GET");
<add> this.request.setServletPath("/servlet");
<add> this.request.setContextPath("/context");
<add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/resources/main.css");
<add>
<add> Resource mainCss = new ClassPathResource("test/main.css", getClass());
<add> String actual = this.transformer.resolveUrlPath("bar.css", this.request, mainCss, this.transformerChain);
<add> assertEquals("bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
<add> }
<add>
<add> @Test
<add> public void rewriteRelativePathUpperLevel() throws Exception {
<add> this.request.setRequestURI("/servlet/context/resources/images/image.png");
<add> this.request.setMethod("GET");
<add> this.request.setServletPath("/servlet");
<add> this.request.setContextPath("/context");
<add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "/resources/images/image.png");
<add>
<add> Resource imagePng = new ClassPathResource("test/images/image.png", getClass());
<add> String actual = this.transformer.resolveUrlPath("../bar.css", this.request, imagePng, this.transformerChain);
<add> assertEquals("../bar-11e16cf79faee7ac698c805cf28248d2.css", actual);
<add> }
<add>
<add>
<add> private static class TestTransformer extends ResourceTransformerSupport {
<add>
<add> @Override
<add> public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain chain) {
<add> throw new IllegalStateException("Should never be called");
<add> }
<add> }
<add>
<add>} | 4 |
Text | Text | implement minor improvements to building.md text | 398790149d18a26dd4b9ec263214345467d7439e | <ide><path>BUILDING.md
<ide> There are three support tiers:
<ide> platforms are welcome.
<ide>
<ide> Platforms may move between tiers between major release lines. The table below
<del>will be updated to reflect those changes.
<add>will reflect those changes.
<ide>
<ide> ### Platform list
<ide>
<ide> platforms. This is true regardless of entries in the table below.
<ide> | AIX | ppc64be >=power7 | >= 7.2 TL02 | Tier 2 | |
<ide> | FreeBSD | x64 | >= 11 | Experimental | Downgraded as of Node.js 12 <sup>[7](#fn7)</sup> |
<ide>
<del><em id="fn1">1</em>: GCC 6 is not provided on the base platform, users will
<add><em id="fn1">1</em>: GCC 6 is not provided on the base platform. Users will
<ide> need the
<ide> [Toolchain test builds PPA](https://launchpad.net/~ubuntu-toolchain-r/+archive/ubuntu/test?field.series_filter=xenial)
<ide> or similar to source a newer compiler.
<ide>
<del><em id="fn2">2</em>: GCC 6 is not provided on the base platform, users will
<add><em id="fn2">2</em>: GCC 6 is not provided on the base platform. Users will
<ide> need the
<ide> [devtoolset-6](https://www.softwarecollections.org/en/scls/rhscl/devtoolset-6/)
<ide> or later to source a newer compiler.
<ide>
<del><em id="fn3">3</em>: Older kernel versions may work for ARM64, however the
<add><em id="fn3">3</em>: Older kernel versions may work for ARM64. However the
<ide> Node.js test infrastructure only tests >= 4.5.
<ide>
<ide> <em id="fn4">4</em>: On Windows, running Node.js in Windows terminal emulators
<ide> like `mintty` requires the usage of [winpty](https://github.com/rprichard/winpty)
<del> for the tty channels to work correctly (e.g. `winpty node.exe script.js`).
<add> for the tty channels to work (e.g. `winpty node.exe script.js`).
<ide> In "Git bash" if you call the node shell alias (`node` without the `.exe`
<ide> extension), `winpty` is used automatically.
<ide>
<del><em id="fn5">5</em>: The Windows Subsystem for Linux (WSL) is not directly
<add><em id="fn5">5</em>: The Windows Subsystem for Linux (WSL) is not
<ide> supported, but the GNU/Linux build process and binaries should work. The
<ide> community will only address issues that reproduce on native GNU/Linux
<ide> systems. Issues that only reproduce on WSL should be reported in the
<ide> platforms. This is true regardless of entries in the table below.
<ide>
<ide> <em id="fn6">6</em>: Running Node.js on x86 Windows should work and binaries
<ide> are provided. However, tests in our infrastructure only run on WoW64.
<del>Furthermore, compiling on x86 Windows is currently considered Experimental and
<add>Furthermore, compiling on x86 Windows is Experimental and
<ide> may not be possible.
<ide>
<ide> <em id="fn7">7</em>: The default FreeBSD 12.0 compiler is Clang 6.0.1, but
<del>FreeBSD 12.1 upgrades to 8.0.1. Other Clang/LLVM versions are provided
<add>FreeBSD 12.1 upgrades to 8.0.1. Other Clang/LLVM versions are available
<ide> via the system's package manager, including Clang 9.0.
<ide>
<ide> ### Supported toolchains | 1 |
Ruby | Ruby | extract with_environment to helper module | fba00f2bbfd970ece1d2503a333a9a2730ae5b63 | <ide><path>Library/Homebrew/test/helper/env.rb
<add>module Test
<add> module Helper
<add> module Env
<add> def with_environment(partial_env)
<add> old = ENV.to_hash
<add> ENV.update partial_env
<add> begin
<add> yield
<add> ensure
<add> ENV.replace old
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/testing_env.rb
<ide> def after_teardown
<ide> end
<ide>
<ide> class TestCase < ::Minitest::Test
<add> require "test/helper/env"
<ide> require "test/helper/shutup"
<add> include Test::Helper::Env
<ide> include Test::Helper::Shutup
<ide>
<ide> include VersionAssertions
<ide> def bundle_path(name)
<ide> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.bundle")
<ide> end
<ide>
<del> def with_environment(partial_env)
<del> old = ENV.to_hash
<del> ENV.update partial_env
<del> begin
<del> yield
<del> ensure
<del> ENV.replace old
<del> end
<del> end
<del>
<ide> # Use a stubbed {Formulary::FormulaLoader} to make a given formula be found
<ide> # when loading from {Formulary} with `ref`.
<ide> def stub_formula_loader(formula, ref = formula.full_name) | 2 |
Javascript | Javascript | set eof to true at the end of a flatestream | 43847d7ff8da1876975edf741f889342a816e216 | <ide><path>src/core/stream.js
<ide> var FlateStream = (function FlateStreamClosure() {
<ide> var buffer = this.ensureBuffer(bufferLength + blockLen);
<ide> var end = bufferLength + blockLen;
<ide> this.bufferLength = end;
<del> for (var n = bufferLength; n < end; ++n) {
<del> if (typeof (b = bytes[bytesPos++]) == 'undefined') {
<add> if (blockLen === 0) {
<add> if (typeof bytes[bytesPos] == 'undefined') {
<ide> this.eof = true;
<del> break;
<ide> }
<del> buffer[n] = b;
<add> } else {
<add> for (var n = bufferLength; n < end; ++n) {
<add> if (typeof (b = bytes[bytesPos++]) == 'undefined') {
<add> this.eof = true;
<add> break;
<add> }
<add> buffer[n] = b;
<add> }
<ide> }
<ide> this.bytesPos = bytesPos;
<ide> return; | 1 |
Javascript | Javascript | fix misspelling uikit | 688c74693b9d252eefd61a2822dabd81ca9fd1d2 | <ide><path>Libraries/Components/Navigation/NavigatorIOS.ios.js
<ide> type Event = Object;
<ide> * [`UINavigationController`](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UINavigationController_Class/),
<ide> * enabling you to implement a navigation stack. It works exactly the same as it
<ide> * would on a native app using `UINavigationController`, providing the same
<del> * animations and behavior from UIKIt.
<add> * animations and behavior from UIKit.
<ide> *
<ide> * As the name implies, it is only available on iOS. Take a look at
<ide> * [`React Navigation`](https://reactnavigation.org/) for a cross-platform | 1 |
Mixed | Python | rename the default token class to "basictoken" | 3b1404bd7d37d8c60cf45071852f86eea8d4c68f | <ide><path>djangorestframework/tests/authentication.py
<ide> from djangorestframework.views import APIView
<ide> from djangorestframework import permissions
<ide>
<del>from djangorestframework.tokenauth.models import Token
<add>from djangorestframework.tokenauth.models import BasicToken
<ide> from djangorestframework.tokenauth.authentication import TokenAuthentication
<ide>
<ide> import base64
<ide> def setUp(self):
<ide> self.user = User.objects.create_user(self.username, self.email, self.password)
<ide>
<ide> self.key = 'abcd1234'
<del> self.token = Token.objects.create(key=self.key, user=self.user)
<add> self.token = BasicToken.objects.create(key=self.key, user=self.user)
<ide>
<ide> def test_post_form_passing_token_auth(self):
<ide> """Ensure POSTing json over token auth with correct credentials passes and does not require CSRF"""
<ide> def test_post_json_failing_token_auth(self):
<ide>
<ide> def test_token_has_auto_assigned_key_if_none_provided(self):
<ide> """Ensure creating a token with no key will auto-assign a key"""
<del> token = Token.objects.create(user=self.user)
<add> token = BasicToken.objects.create(user=self.user)
<ide> self.assertEqual(len(token.key), 32)
<ide><path>djangorestframework/tokenauth/authentication.py
<ide> from djangorestframework.authentication import BaseAuthentication
<del>from .models import Token
<add>from .models import BasicToken
<ide>
<ide> class TokenAuthentication(BaseAuthentication):
<ide> """
<ide> class TokenAuthentication(BaseAuthentication):
<ide> Authorization: Token 0123456789abcdef0123456789abcdef
<ide>
<ide> """
<del> model = Token
<add> model = BasicToken
<ide>
<ide> def authenticate(self, request):
<ide> auth = request.META.get('HTTP_AUTHORIZATION', '').strip().split()
<ide><path>djangorestframework/tokenauth/models.py
<ide> def save(self, *args, **kwargs):
<ide> return super(BaseToken, self).save(*args, **kwargs)
<ide>
<ide>
<del>class Token(BaseToken):
<add>class BasicToken(BaseToken):
<ide> """
<ide> The default authorization token model class.
<ide> """
<ide><path>docs/api-guide/authentication.md
<ide> This policy uses [HTTP Authentication][basicauth] with a custom authentication s
<ide> If successfully authenticated, `TokenAuthentication` provides the following credentials.
<ide>
<ide> * `request.user` will be a `django.contrib.auth.models.User` instance.
<del>* `request.auth` will be a `djangorestframework.tokenauth.models.Token` instance.
<add>* `request.auth` will be a `djangorestframework.tokenauth.models.BasicToken` instance.
<ide>
<ide> To use the `TokenAuthentication` scheme, you must have a token model. Django REST Framework comes with a minimal default token model. To use it, include `djangorestframework.tokenauth` in your installed applications. To use your own token model, subclass the `djangorestframework.tokenauth.authentication.TokenAuthentication` class and specify a `model` attribute that references your custom token model. The token model must provide `user`, `key`, and `revoked` attributes. For convenience, the `djangorestframework.tokenauth.models.BaseToken` abstract model implements this minimum contract, and also randomly populates the key field when none is provided.
<ide> | 4 |
Ruby | Ruby | audit generic binary names | 81bf8a168ada914ec47ca5b37a9fe44f8d797fea | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_installed
<ide> audit_check_output(check_jars)
<ide> audit_check_output(check_non_libraries)
<ide> audit_check_output(check_non_executables(f.bin))
<add> audit_check_output(check_generic_executables(f.bin))
<ide> audit_check_output(check_non_executables(f.sbin))
<add> audit_check_output(check_generic_executables(f.sbin))
<ide> end
<ide>
<ide> def audit
<ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_non_executables bin
<ide> EOS
<ide> ]
<ide> end
<add>
<add> def check_generic_executables bin
<add> return unless bin.directory?
<add> generics = bin.children.select { |g| g.to_s =~ /\/(run|service)$/}
<add> return if generics.empty?
<add>
<add> ["Generic binaries were installed to \"#{bin}\".",
<add> <<-EOS.undent
<add> Binaries with generic names are likely to conflict with other software,
<add> and suggest that this software should be installed to "libexec" and
<add> then symlinked as needed.
<add>
<add> The offending files are:
<add> #{generics * "\n "}
<add> EOS
<add> ]
<add> end
<ide> end
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def print_check_output warning_and_description
<ide> def audit_bin
<ide> print_check_output(check_PATH(f.bin)) unless f.keg_only?
<ide> print_check_output(check_non_executables(f.bin))
<add> print_check_output(check_generic_executables(f.bin))
<ide> end
<ide>
<ide> def audit_sbin
<ide> print_check_output(check_PATH(f.sbin)) unless f.keg_only?
<ide> print_check_output(check_non_executables(f.sbin))
<add> print_check_output(check_generic_executables(f.sbin))
<ide> end
<ide>
<ide> def audit_lib | 3 |
Text | Text | update example years to 2013 in contributing.md | 94a88069ac57a4a8cc69ca2d72c1a0de69efa9e6 | <ide><path>CONTRIBUTING.md
<ide> present in the framework.
<ide>
<ide> ```java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 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> package ...;
<ide> ## Update Apache license header to modified files as necessary
<ide>
<ide> Always check the date range in the license header. For example, if you've
<del>modified a file in 2012 whose header still reads
<add>modified a file in 2013 whose header still reads
<ide>
<ide> ```java
<ide> * Copyright 2002-2011 the original author or authors.
<ide> ```
<ide>
<del>then be sure to update it to 2012 appropriately
<add>then be sure to update it to 2013 appropriately
<ide>
<ide> ```java
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> ```
<ide>
<ide> ## Use @since tags for newly-added public API types and methods | 1 |
Python | Python | fix cyclic import | e54c3a7d48214e076ce0a5dd1d0ae863b584c155 | <ide><path>glances/core/glances_globals.py
<ide> def get_locale_path(paths):
<ide>
<ide> # Create and init the logging instance
<ide> logger = glances_logger()
<del>
<del># Instances shared between all Glances scripts
<del># ============================================
<del>
<del># Glances_processes for processcount and processlist plugins
<del>from glances.core.glances_processes import GlancesProcesses
<del>glances_processes = GlancesProcesses()
<del>
<del># The global instance for the logs
<del>from glances.core.glances_logs import GlancesLogs
<del>glances_logs = GlancesLogs()
<ide><path>glances/core/glances_logs.py
<ide> from datetime import datetime
<ide>
<ide> # Import Glances libs
<del>from glances.core.glances_globals import glances_processes
<add>from glances.core.glances_processes import glances_processes
<ide>
<ide>
<ide> class GlancesLogs(object):
<ide> def clean(self, critical=False):
<ide> # The list is now the clean one
<ide> self.logs_list = clean_logs_list
<ide> return self.len()
<add>
<add>glances_logs = GlancesLogs()
<ide><path>glances/core/glances_monitor_list.py
<ide> import subprocess
<ide>
<ide> # Import Glances lib
<del>from glances.core.glances_globals import glances_processes, logger
<add>from glances.core.glances_globals import logger
<add>from glances.core.glances_processes import glances_processes
<ide>
<ide>
<ide> class MonitorList(object):
<ide><path>glances/core/glances_processes.py
<ide> def getsortlist(self, sortedby=None):
<ide> reverse=sortedreverse)
<ide>
<ide> return self.processlist
<add>
<add>glances_processes = GlancesProcesses()
<ide><path>glances/core/glances_standalone.py
<ide> """Manage the Glances standalone session."""
<ide>
<ide> # Import Glances libs
<del>from glances.core.glances_globals import glances_processes, is_windows, logger
<add>from glances.core.glances_globals import is_windows, logger
<add>from glances.core.glances_processes import glances_processes
<ide> from glances.core.glances_stats import GlancesStats
<ide> from glances.outputs.glances_curses import GlancesCursesStandalone
<ide>
<ide><path>glances/outputs/glances_curses.py
<ide> import sys
<ide>
<ide> # Import Glances lib
<del>from glances.core.glances_globals import glances_logs, glances_processes, is_mac, is_windows, logger
<add>from glances.core.glances_globals import is_mac, is_windows, logger
<add>from glances.core.glances_logs import glances_logs
<add>from glances.core.glances_processes import glances_processes
<ide> from glances.core.glances_timer import Timer
<ide>
<ide> # Import curses lib for "normal" operating system and consolelog for Windows
<ide><path>glances/plugins/glances_alert.py
<ide> from datetime import datetime
<ide>
<ide> # Import Glances libs
<del>from glances.core.glances_globals import glances_logs
<add>from glances.core.glances_logs import glances_logs
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<ide>
<ide><path>glances/plugins/glances_plugin.py
<ide> from operator import itemgetter
<ide>
<ide> # Import Glances lib
<del>from glances.core.glances_globals import glances_logs, is_py3, logger
<add>from glances.core.glances_globals import is_py3, logger
<add>from glances.core.glances_logs import glances_logs
<ide>
<ide>
<ide> class GlancesPlugin(object):
<ide><path>glances/plugins/glances_processcount.py
<ide> """Process count plugin."""
<ide>
<ide> # Import Glances libs
<del>from glances.core.glances_globals import glances_processes
<add>from glances.core.glances_processes import glances_processes
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<ide> # Note: history items list is not compliant with process count
<ide><path>glances/plugins/glances_processlist.py
<ide> from datetime import timedelta
<ide>
<ide> # Import Glances libs
<del>from glances.core.glances_globals import glances_processes, is_windows
<add>from glances.core.glances_globals import is_windows
<add>from glances.core.glances_processes import glances_processes
<ide> from glances.plugins.glances_plugin import GlancesPlugin
<ide>
<ide> | 10 |
Text | Text | change a to an for html word [ci skip] | f5fced2bb94659253e87b12d35e569322b3098fd | <ide><path>guides/source/layouts_and_rendering.md
<ide> extension for the layout file.
<ide>
<ide> #### Rendering HTML
<ide>
<del>You can send a HTML string back to the browser by using the `:html` option to
<add>You can send an HTML string back to the browser by using the `:html` option to
<ide> `render`:
<ide>
<ide> ```ruby | 1 |
Go | Go | move "logs" to daemon/logs.go | 066330fc9687edd3f8a5066fd4201ea14af15f93 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> if err := eng.Register("commit", daemon.ContainerCommit); err != nil {
<ide> return err
<ide> }
<add> if err := eng.Register("logs", daemon.ContainerLogs); err != nil {
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/logs.go
<add>package daemon
<add>
<add>import (
<add> "bytes"
<add> "encoding/json"
<add> "fmt"
<add> "io"
<add> "os"
<add> "strconv"
<add> "time"
<add>
<add> "github.com/docker/docker/pkg/tailfile"
<add>
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/utils"
<add>)
<add>
<add>func (daemon *Daemon) ContainerLogs(job *engine.Job) engine.Status {
<add> if len(job.Args) != 1 {
<add> return job.Errorf("Usage: %s CONTAINER\n", job.Name)
<add> }
<add>
<add> var (
<add> name = job.Args[0]
<add> stdout = job.GetenvBool("stdout")
<add> stderr = job.GetenvBool("stderr")
<add> tail = job.Getenv("tail")
<add> follow = job.GetenvBool("follow")
<add> times = job.GetenvBool("timestamps")
<add> lines = -1
<add> format string
<add> )
<add> if !(stdout || stderr) {
<add> return job.Errorf("You must choose at least one stream")
<add> }
<add> if times {
<add> format = time.RFC3339Nano
<add> }
<add> if tail == "" {
<add> tail = "all"
<add> }
<add> container := daemon.Get(name)
<add> if container == nil {
<add> return job.Errorf("No such container: %s", name)
<add> }
<add> cLog, err := container.ReadLog("json")
<add> if err != nil && os.IsNotExist(err) {
<add> // Legacy logs
<add> utils.Debugf("Old logs format")
<add> if stdout {
<add> cLog, err := container.ReadLog("stdout")
<add> if err != nil {
<add> utils.Errorf("Error reading logs (stdout): %s", err)
<add> } else if _, err := io.Copy(job.Stdout, cLog); err != nil {
<add> utils.Errorf("Error streaming logs (stdout): %s", err)
<add> }
<add> }
<add> if stderr {
<add> cLog, err := container.ReadLog("stderr")
<add> if err != nil {
<add> utils.Errorf("Error reading logs (stderr): %s", err)
<add> } else if _, err := io.Copy(job.Stderr, cLog); err != nil {
<add> utils.Errorf("Error streaming logs (stderr): %s", err)
<add> }
<add> }
<add> } else if err != nil {
<add> utils.Errorf("Error reading logs (json): %s", err)
<add> } else {
<add> if tail != "all" {
<add> var err error
<add> lines, err = strconv.Atoi(tail)
<add> if err != nil {
<add> utils.Errorf("Failed to parse tail %s, error: %v, show all logs", err)
<add> lines = -1
<add> }
<add> }
<add> if lines != 0 {
<add> if lines > 0 {
<add> f := cLog.(*os.File)
<add> ls, err := tailfile.TailFile(f, lines)
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> tmp := bytes.NewBuffer([]byte{})
<add> for _, l := range ls {
<add> fmt.Fprintf(tmp, "%s\n", l)
<add> }
<add> cLog = tmp
<add> }
<add> dec := json.NewDecoder(cLog)
<add> for {
<add> l := &utils.JSONLog{}
<add>
<add> if err := dec.Decode(l); err == io.EOF {
<add> break
<add> } else if err != nil {
<add> utils.Errorf("Error streaming logs: %s", err)
<add> break
<add> }
<add> logLine := l.Log
<add> if times {
<add> logLine = fmt.Sprintf("%s %s", l.Created.Format(format), logLine)
<add> }
<add> if l.Stream == "stdout" && stdout {
<add> fmt.Fprintf(job.Stdout, "%s", logLine)
<add> }
<add> if l.Stream == "stderr" && stderr {
<add> fmt.Fprintf(job.Stderr, "%s", logLine)
<add> }
<add> }
<add> }
<add> }
<add> if follow {
<add> errors := make(chan error, 2)
<add> if stdout {
<add> stdoutPipe := container.StdoutLogPipe()
<add> go func() {
<add> errors <- utils.WriteLog(stdoutPipe, job.Stdout, format)
<add> }()
<add> }
<add> if stderr {
<add> stderrPipe := container.StderrLogPipe()
<add> go func() {
<add> errors <- utils.WriteLog(stderrPipe, job.Stderr, format)
<add> }()
<add> }
<add> err := <-errors
<add> if err != nil {
<add> utils.Errorf("%s", err)
<add> }
<add> }
<add> return engine.StatusOK
<add>}
<ide><path>server/container.go
<ide> package server
<ide>
<ide> import (
<del> "bytes"
<del> "encoding/json"
<ide> "errors"
<ide> "fmt"
<ide> "io"
<ide> import (
<ide> "path/filepath"
<ide> "strconv"
<ide> "strings"
<del> "time"
<ide>
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/graphdb"
<del> "github.com/docker/docker/pkg/tailfile"
<del> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> func (srv *Server) ContainerTop(job *engine.Job) engine.Status {
<ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>func (srv *Server) ContainerLogs(job *engine.Job) engine.Status {
<del> if len(job.Args) != 1 {
<del> return job.Errorf("Usage: %s CONTAINER\n", job.Name)
<del> }
<del>
<del> var (
<del> name = job.Args[0]
<del> stdout = job.GetenvBool("stdout")
<del> stderr = job.GetenvBool("stderr")
<del> tail = job.Getenv("tail")
<del> follow = job.GetenvBool("follow")
<del> times = job.GetenvBool("timestamps")
<del> lines = -1
<del> format string
<del> )
<del> if !(stdout || stderr) {
<del> return job.Errorf("You must choose at least one stream")
<del> }
<del> if times {
<del> format = time.RFC3339Nano
<del> }
<del> if tail == "" {
<del> tail = "all"
<del> }
<del> container := srv.daemon.Get(name)
<del> if container == nil {
<del> return job.Errorf("No such container: %s", name)
<del> }
<del> cLog, err := container.ReadLog("json")
<del> if err != nil && os.IsNotExist(err) {
<del> // Legacy logs
<del> utils.Debugf("Old logs format")
<del> if stdout {
<del> cLog, err := container.ReadLog("stdout")
<del> if err != nil {
<del> utils.Errorf("Error reading logs (stdout): %s", err)
<del> } else if _, err := io.Copy(job.Stdout, cLog); err != nil {
<del> utils.Errorf("Error streaming logs (stdout): %s", err)
<del> }
<del> }
<del> if stderr {
<del> cLog, err := container.ReadLog("stderr")
<del> if err != nil {
<del> utils.Errorf("Error reading logs (stderr): %s", err)
<del> } else if _, err := io.Copy(job.Stderr, cLog); err != nil {
<del> utils.Errorf("Error streaming logs (stderr): %s", err)
<del> }
<del> }
<del> } else if err != nil {
<del> utils.Errorf("Error reading logs (json): %s", err)
<del> } else {
<del> if tail != "all" {
<del> var err error
<del> lines, err = strconv.Atoi(tail)
<del> if err != nil {
<del> utils.Errorf("Failed to parse tail %s, error: %v, show all logs", err)
<del> lines = -1
<del> }
<del> }
<del> if lines != 0 {
<del> if lines > 0 {
<del> f := cLog.(*os.File)
<del> ls, err := tailfile.TailFile(f, lines)
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> tmp := bytes.NewBuffer([]byte{})
<del> for _, l := range ls {
<del> fmt.Fprintf(tmp, "%s\n", l)
<del> }
<del> cLog = tmp
<del> }
<del> dec := json.NewDecoder(cLog)
<del> for {
<del> l := &utils.JSONLog{}
<del>
<del> if err := dec.Decode(l); err == io.EOF {
<del> break
<del> } else if err != nil {
<del> utils.Errorf("Error streaming logs: %s", err)
<del> break
<del> }
<del> logLine := l.Log
<del> if times {
<del> logLine = fmt.Sprintf("%s %s", l.Created.Format(format), logLine)
<del> }
<del> if l.Stream == "stdout" && stdout {
<del> fmt.Fprintf(job.Stdout, "%s", logLine)
<del> }
<del> if l.Stream == "stderr" && stderr {
<del> fmt.Fprintf(job.Stderr, "%s", logLine)
<del> }
<del> }
<del> }
<del> }
<del> if follow {
<del> errors := make(chan error, 2)
<del> if stdout {
<del> stdoutPipe := container.StdoutLogPipe()
<del> go func() {
<del> errors <- utils.WriteLog(stdoutPipe, job.Stdout, format)
<del> }()
<del> }
<del> if stderr {
<del> stderrPipe := container.StderrLogPipe()
<del> go func() {
<del> errors <- utils.WriteLog(stderrPipe, job.Stderr, format)
<del> }()
<del> }
<del> err := <-errors
<del> if err != nil {
<del> utils.Errorf("%s", err)
<del> }
<del> }
<del> return engine.StatusOK
<del>}
<del>
<ide> func (srv *Server) ContainerCopy(job *engine.Job) engine.Status {
<ide> if len(job.Args) != 2 {
<ide> return job.Errorf("Usage: %s CONTAINER RESOURCE\n", job.Name)
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> "viz": srv.ImagesViz,
<ide> "container_copy": srv.ContainerCopy,
<ide> "log": srv.Log,
<del> "logs": srv.ContainerLogs,
<ide> "changes": srv.ContainerChanges,
<ide> "top": srv.ContainerTop,
<ide> "load": srv.ImageLoad, | 4 |
Python | Python | fix no attribute 'per_replica_batch_size' | c3b4ffc5b1f39443ee471145aeb0f41b552c6575 | <ide><path>research/deep_speech/deep_speech.py
<ide> def generate_dataset(data_dir):
<ide> speech_dataset = dataset.DeepSpeechDataset(train_data_conf)
<ide> return speech_dataset
<ide>
<add>def per_device_batch_size(batch_size, num_gpus):
<add> """For multi-gpu, batch-size must be a multiple of the number of GPUs.
<add>
<add>
<add> Note that distribution strategy handles this automatically when used with
<add> Keras. For using with Estimator, we need to get per GPU batch.
<add>
<add> Args:
<add> batch_size: Global batch size to be divided among devices. This should be
<add> equal to num_gpus times the single-GPU batch_size for multi-gpu training.
<add> num_gpus: How many GPUs are used with DistributionStrategies.
<add>
<add> Returns:
<add> Batch size per device.
<add>
<add> Raises:
<add> ValueError: if batch_size is not divisible by number of devices
<add> """
<add> if num_gpus <= 1:
<add> return batch_size
<add>
<add> remainder = batch_size % num_gpus
<add> if remainder:
<add> err = ('When running with multiple GPUs, batch size '
<add> 'must be a multiple of the number of available GPUs. Found {} '
<add> 'GPUs with a batch size of {}; try --batch_size={} instead.'
<add> ).format(num_gpus, batch_size, batch_size - remainder)
<add> raise ValueError(err)
<add> return int(batch_size / num_gpus)
<ide>
<ide> def run_deep_speech(_):
<ide> """Run deep speech training and eval loop."""
<ide> def run_deep_speech(_):
<ide> model_dir=flags_obj.model_dir,
<ide> batch_size=flags_obj.batch_size)
<ide>
<del> per_replica_batch_size = distribution_utils.per_replica_batch_size(
<del> flags_obj.batch_size, num_gpus)
<add> per_replica_batch_size = per_device_batch_size(flags_obj.batch_size, num_gpus)
<ide>
<ide> def input_fn_train():
<ide> return dataset.input_fn( | 1 |
Javascript | Javascript | add data node to serverstate declaration | f0eacf66eac95db0aea40d502e0d2f049d9be3c7 | <ide><path>examples/with-apollo/lib/withData.js
<ide> export default ComposedComponent => {
<ide>
<ide> static async getInitialProps (ctx) {
<ide> // Initial serverState with apollo (empty)
<del> let serverState = { apollo: { } }
<add> let serverState = {
<add> apollo: {
<add> data: { }
<add> }
<add> }
<ide>
<ide> // Evaluate the composed component's getInitialProps()
<ide> let composedInitialProps = {} | 1 |
Javascript | Javascript | fix typo in variable name | 2ef81bde20bbc74190fa5e2b96c6a783af8de6b0 | <ide><path>client/src/components/settings/Username.js
<ide> class UsernameSettings extends Component {
<ide> isFormPristine: true,
<ide> formValue: props.username,
<ide> characterValidation: { valid: false, error: null },
<del> sumbitClicked: false
<add> submitClicked: false
<ide> };
<ide>
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class UsernameSettings extends Component {
<ide> /* eslint-disable-next-line react/no-did-update-set-state */
<ide> return this.setState({
<ide> isFormPristine: username === formValue,
<del> sumbitClicked: false
<add> submitClicked: false
<ide> });
<ide> }
<ide> return null;
<ide> class UsernameSettings extends Component {
<ide> } = this.state;
<ide>
<ide> return this.setState(
<del> { sumbitClicked: true },
<add> { submitClicked: true },
<ide> () => (valid ? submitNewUsername(formValue) : null)
<ide> );
<ide> }
<ide> class UsernameSettings extends Component {
<ide> isFormPristine,
<ide> formValue,
<ide> characterValidation: { valid, error },
<del> sumbitClicked
<add> submitClicked
<ide> } = this.state;
<ide> const { isValidUsername, validating } = this.props;
<ide>
<ide> class UsernameSettings extends Component {
<ide> <FullWidthRow>
<ide> <BlockSaveButton
<ide> disabled={
<del> !(isValidUsername && valid && !isFormPristine) || sumbitClicked
<add> !(isValidUsername && valid && !isFormPristine) || submitClicked
<ide> }
<ide> />
<ide> </FullWidthRow> | 1 |
PHP | PHP | add missing use statement | 5d0b19fb065e23a05d17b6f27288cac76381e6c3 | <ide><path>App/Controller/PagesController.php
<ide> */
<ide> namespace App\Controller;
<ide>
<add>use Cake\Core\Configure;
<ide> use Cake\Error;
<ide> use Cake\Utility\Inflector;
<ide> | 1 |
PHP | PHP | remove nested ternary | 0e193eaa648ae7c7e60eca806551fe9f8627d231 | <ide><path>src/Illuminate/Notifications/resources/views/email-plain.blade.php
<del>{{ ( $greeting !== null ) ? $greeting : ($level == 'error' ? 'Whoops!' : 'Hello!') }}
<add><?php
<add>if( $greeting !== null ) {
<add> echo e($greeting);
<add>} else {
<add> echo $level == 'error' ? 'Whoops!' : 'Hello!';
<add>}
<add>
<add>?>
<ide>
<ide> <?php
<ide> | 1 |
Javascript | Javascript | add test for http client "aborted" event | 6d6f9e5c023721300ad39440b0f7a4c9168f7975 | <ide><path>test/parallel/test-http-client-aborted-event.js
<add>'use strict';
<add>const common = require('../common');
<add>const http = require('http');
<add>
<add>const server = http.Server(function(req, res) {
<add> res.write('Part of my res.');
<add> res.destroy();
<add>});
<add>
<add>server.listen(0, common.mustCall(function() {
<add> http.get({
<add> port: this.address().port,
<add> headers: { connection: 'keep-alive' }
<add> }, common.mustCall(function(res) {
<add> server.close();
<add> res.on('aborted', common.mustCall(function() {}));
<add> }));
<add>})); | 1 |
Java | Java | use senderror in responsestatusexceptionresolver | 80767ff6e9963761aa7e5516090fcda2c5a3bf74 | <ide><path>spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseStatus.java
<ide> * {@link #reason} that should be returned.
<ide> *
<ide> * <p>The status code is applied to the HTTP response when the handler
<del> * method is invoked, or whenever said exception is thrown.
<add> * method is invoked.
<add> *
<add> * <p><strong>Note:</strong> when using this annotation on an exception class,
<add> * or when setting the {@code reason} attribute of the annotation,
<add> * the {@code HttpServletResponse.sendError} method will be used.
<add> *
<add> * With {@code HttpServletResponse.sendError}, the response is considered
<add> * complete and should not be written to any further.
<add> * Furthermore servlet container will typically write an HTML error page
<add> * therefore making the use of a reason unsuitable for REST APIs.
<add> * For such cases prefer the use of {@link org.springframework.http.ResponseEntity}
<add> * as a return type and avoid {@code ResponseStatus} altogether.
<ide> *
<ide> * @author Arjen Poutsma
<ide> * @author Sam Brannen
<ide> * @see org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver
<add> * @see javax.servlet.http.HttpServletResponse#sendError(int, String)
<ide> * @since 3.0
<ide> */
<ide> @Target({ElementType.TYPE, ElementType.METHOD})
<ide> * typically be changed to something more appropriate.
<ide> * @since 4.2
<ide> * @see javax.servlet.http.HttpServletResponse#setStatus(int)
<add> * @see javax.servlet.http.HttpServletResponse#sendError(int)
<ide> */
<ide> @AliasFor("value")
<ide> HttpStatus code() default HttpStatus.INTERNAL_SERVER_ERROR;
<ide>
<ide> /**
<ide> * The <em>reason</em> to be used for the response.
<del> * <p><strong>Note:</strong> due to the use of
<del> * {@code HttpServletResponse.sendError(int, String)}, the response will be
<del> * considered complete and should not be written to any further. Furthermore
<del> * servlet container will typically write an HTML error page therefore making
<del> * the use of a reason unsuitable for REST APIs. For such cases prefer
<del> * sending error details in the body of the response.
<ide> * @see javax.servlet.http.HttpServletResponse#sendError(int, String)
<ide> */
<ide> String reason() default "";
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java
<ide> protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, Http
<ide> reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale());
<ide> }
<ide> if (!StringUtils.hasLength(reason)) {
<del> response.setStatus(statusCode);
<add> response.sendError(statusCode);
<ide> }
<ide> else {
<ide> response.sendError(statusCode, reason);
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java
<ide> public void statusCode() {
<ide> assertNotNull("No ModelAndView returned", mav);
<ide> assertTrue("No Empty ModelAndView returned", mav.isEmpty());
<ide> assertEquals("Invalid status code", 400, response.getStatus());
<add> assertTrue("Response has not been committed", response.isCommitted());
<ide> }
<ide>
<ide> @Test
<ide> public void statusCodeAndReason() {
<ide> assertTrue("No Empty ModelAndView returned", mav.isEmpty());
<ide> assertEquals("Invalid status code", 410, response.getStatus());
<ide> assertEquals("Invalid status reason", "You suck!", response.getErrorMessage());
<add> assertTrue("Response has not been committed", response.isCommitted());
<ide> }
<ide>
<ide> @Test | 3 |
Mixed | Javascript | remove unintended access to deps/ | 4100001624a4cc88c61143e2678bf80c2aacd922 | <ide><path>doc/api/deprecations.md
<ide> the client and is now unsupported. Use the `ciphers` parameter instead.
<ide> ### DEP0084: requiring bundled internal dependencies
<ide> <!-- YAML
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/25138
<add> description: This functionality has been removed.
<ide> - version: v10.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/16392
<ide> description: Runtime deprecation.
<ide> -->
<ide>
<del>Type: Runtime
<add>Type: End-of-Life
<ide>
<ide> Since Node.js versions 4.4.0 and 5.2.0, several modules only intended for
<del>internal usage are mistakenly exposed to user code through `require()`. These
<del>modules are:
<add>internal usage were mistakenly exposed to user code through `require()`. These
<add>modules were:
<ide>
<ide> - `v8/tools/codemap`
<ide> - `v8/tools/consarray`
<ide><path>lib/internal/bootstrap/loaders.js
<ide> NativeModule.isDepsModule = function(id) {
<ide> };
<ide>
<ide> NativeModule.requireForDeps = function(id) {
<del> if (!NativeModule.exists(id) ||
<del> // TODO(TimothyGu): remove when DEP0084 reaches end of life.
<del> NativeModule.isDepsModule(id)) {
<add> if (!NativeModule.exists(id)) {
<ide> id = `internal/deps/${id}`;
<ide> }
<ide> return NativeModule.require(id);
<ide><path>test/parallel/test-require-deps-deprecation.js
<del>'use strict';
<del>
<del>const common = require('../common');
<del>const assert = require('assert');
<del>
<del>const deprecatedModules = [
<del> 'node-inspect/lib/_inspect',
<del> 'node-inspect/lib/internal/inspect_client',
<del> 'node-inspect/lib/internal/inspect_repl',
<del> 'v8/tools/SourceMap',
<del> 'v8/tools/codemap',
<del> 'v8/tools/consarray',
<del> 'v8/tools/csvparser',
<del> 'v8/tools/logreader',
<del> 'v8/tools/profile',
<del> 'v8/tools/profile_view',
<del> 'v8/tools/splaytree',
<del> 'v8/tools/tickprocessor',
<del> 'v8/tools/tickprocessor-driver'
<del>];
<del>
<del>// Newly added deps that do not have a deprecation wrapper around it would
<del>// throw an error, but no warning would be emitted.
<del>const deps = [
<del> 'acorn/dist/acorn',
<del> 'acorn/dist/walk'
<del>];
<del>
<del>common.expectWarning('DeprecationWarning', deprecatedModules.map((m) => {
<del> return [`Requiring Node.js-bundled '${m}' module is deprecated. ` +
<del> 'Please install the necessary module locally.', 'DEP0084'];
<del>}));
<del>
<del>for (const m of deprecatedModules) {
<del> try {
<del> require(m);
<del> } catch {}
<del>}
<del>
<del>// Instead of checking require, check that resolve isn't pointing toward a
<del>// built-in module, as user might already have node installed with acorn in
<del>// require.resolve range.
<del>// Ref: https://github.com/nodejs/node/issues/17148
<del>for (const m of deps) {
<del> let path;
<del> try {
<del> path = require.resolve(m);
<del> } catch (err) {
<del> assert.ok(err.toString().startsWith('Error: Cannot find module '));
<del> continue;
<del> }
<del> assert.notStrictEqual(path, m);
<del>}
<del>
<del>// The V8 modules add the WebInspector to the globals.
<del>common.allowGlobals(global.WebInspector);
<ide><path>tools/js2c.py
<ide> def ReadMacros(lines):
<ide> );
<ide> """
<ide>
<del>DEPRECATED_DEPS = """\
<del>'use strict';
<del>process.emitWarning(
<del> 'Requiring Node.js-bundled \\'{module}\\' module is deprecated. Please ' +
<del> 'install the necessary module locally.', 'DeprecationWarning', 'DEP0084');
<del>module.exports = require('internal/deps/{module}');
<del>"""
<del>
<ide> def JS2C(source, target):
<ide> modules = []
<ide> consts = {}
<ide> def AddModule(module, source):
<ide> lines = ExpandConstants(lines, consts)
<ide> lines = ExpandMacros(lines, macros)
<ide>
<del> deprecated_deps = None
<del>
<ide> # On Windows, "./foo.bar" in the .gyp file is passed as "foo.bar"
<ide> # so don't assume there is always a slash in the file path.
<ide> if '/' in name or '\\' in name:
<ide> split = re.split('/|\\\\', name)
<ide> if split[0] == 'deps':
<del> if split[1] == 'node-inspect' or split[1] == 'v8':
<del> deprecated_deps = split[1:]
<ide> split = ['internal'] + split
<ide> else:
<ide> split = split[1:]
<ide> def AddModule(module, source):
<ide> else:
<ide> AddModule(name.split('.', 1)[0], lines)
<ide>
<del> # Add deprecated aliases for deps without 'deps/'
<del> if deprecated_deps is not None:
<del> module = '/'.join(deprecated_deps).split('.', 1)[0]
<del> source = DEPRECATED_DEPS.format(module=module)
<del> AddModule(module, source)
<del>
<ide> # Emit result
<ide> output = open(str(target[0]), "w")
<ide> output.write( | 4 |
Java | Java | add defaultrequest option to webclient.builder | 8bffb6a798424b83fa1b20f344650732d2f2c985 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java
<ide> class DefaultWebClient implements WebClient {
<ide> @Nullable
<ide> private final MultiValueMap<String, String> defaultCookies;
<ide>
<add> @Nullable
<add> private final Consumer<RequestHeadersSpec<?>> defaultRequest;
<add>
<ide> private final DefaultWebClientBuilder builder;
<ide>
<ide>
<ide> DefaultWebClient(ExchangeFunction exchangeFunction, @Nullable UriBuilderFactory factory,
<ide> @Nullable HttpHeaders defaultHeaders, @Nullable MultiValueMap<String, String> defaultCookies,
<del> DefaultWebClientBuilder builder) {
<add> @Nullable Consumer<RequestHeadersSpec<?>> defaultRequest, DefaultWebClientBuilder builder) {
<ide>
<ide> this.exchangeFunction = exchangeFunction;
<ide> this.uriBuilderFactory = (factory != null ? factory : new DefaultUriBuilderFactory());
<ide> this.defaultHeaders = defaultHeaders;
<ide> this.defaultCookies = defaultCookies;
<add> this.defaultRequest = defaultRequest;
<ide> this.builder = builder;
<ide> }
<ide>
<ide> public Mono<ClientResponse> exchange() {
<ide> }
<ide>
<ide> private ClientRequest.Builder initRequestBuilder() {
<add> if (defaultRequest != null) {
<add> defaultRequest.accept(this);
<add> }
<ide> URI uri = (this.uri != null ? this.uri : uriBuilderFactory.expand(""));
<ide> return ClientRequest.create(this.httpMethod, uri)
<ide> .headers(headers -> headers.addAll(initHeaders()))
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClientBuilder.java
<ide> final class DefaultWebClientBuilder implements WebClient.Builder {
<ide> @Nullable
<ide> private MultiValueMap<String, String> defaultCookies;
<ide>
<add> @Nullable
<add> private Consumer<WebClient.RequestHeadersSpec<?>> defaultRequest;
<add>
<ide> @Nullable
<ide> private List<ExchangeFilterFunction> filters;
<ide>
<ide> public DefaultWebClientBuilder(DefaultWebClientBuilder other) {
<ide> }
<ide> this.defaultCookies =
<ide> other.defaultCookies != null ? new LinkedMultiValueMap<>(other.defaultCookies) : null;
<add> this.defaultRequest = other.defaultRequest;
<ide> this.filters = other.filters != null ? new ArrayList<>(other.filters) : null;
<ide> this.connector = other.connector;
<ide> this.exchangeFunction = other.exchangeFunction;
<ide> private MultiValueMap<String, String> initCookies() {
<ide> return this.defaultCookies;
<ide> }
<ide>
<add> @Override
<add> public WebClient.Builder defaultRequest(Consumer<WebClient.RequestHeadersSpec<?>> defaultRequest) {
<add> this.defaultRequest = this.defaultRequest != null ?
<add> this.defaultRequest.andThen(defaultRequest) : defaultRequest;
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public WebClient.Builder clientConnector(ClientHttpConnector connector) {
<ide> this.connector = connector;
<ide> public WebClient build() {
<ide> return new DefaultWebClient(filteredExchange, initUriBuilderFactory(),
<ide> this.defaultHeaders != null ? unmodifiableCopy(this.defaultHeaders) : null,
<ide> this.defaultCookies != null ? unmodifiableCopy(this.defaultCookies) : null,
<del> new DefaultWebClientBuilder(this));
<add> this.defaultRequest, new DefaultWebClientBuilder(this));
<ide> }
<ide>
<ide> private ExchangeFunction initExchangeFunction() {
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
<ide> interface Builder {
<ide> Builder uriBuilderFactory(UriBuilderFactory uriBuilderFactory);
<ide>
<ide> /**
<del> * A global option to specify a header to be added to every request,
<add> * Global option to specify a header to be added to every request,
<ide> * if the request does not already contain such a header.
<ide> * @param header the header name
<ide> * @param values the header values
<ide> interface Builder {
<ide> Builder defaultHeaders(Consumer<HttpHeaders> headersConsumer);
<ide>
<ide> /**
<del> * A global option to specify a cookie to be added to every request,
<add> * Global option to specify a cookie to be added to every request,
<ide> * if the request does not already contain such a cookie.
<ide> * @param cookie the cookie name
<ide> * @param values the cookie values
<ide> interface Builder {
<ide> */
<ide> Builder defaultCookies(Consumer<MultiValueMap<String, String>> cookiesConsumer);
<ide>
<add> /**
<add> * Provide a consumer to modify every request being built just before the
<add> * call to {@link RequestHeadersSpec#exchange() exchange()}.
<add> * @param defaultRequest the consumer to use for modifying requests
<add> * @since 5.1
<add> */
<add> Builder defaultRequest(Consumer<RequestHeadersSpec<?>> defaultRequest);
<add>
<ide> /**
<ide> * Add the given filter to the filter chain.
<ide> * @param filter the filter to be added to the chain
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/client/DefaultWebClientTests.java
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.StepVerifier;
<ide>
<add>import org.springframework.core.NamedInheritableThreadLocal;
<add>import org.springframework.core.NamedThreadLocal;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.MediaType;
<ide>
<ide> public void defaultHeaderAndCookieOverrides() {
<ide> verifyNoMoreInteractions(this.exchangeFunction);
<ide> }
<ide>
<add> @Test
<add> public void defaultRequest() {
<add>
<add> ThreadLocal<String> context = new NamedThreadLocal<>("foo");
<add>
<add> Map<String, Object> actual = new HashMap<>();
<add> ExchangeFilterFunction filter = (request, next) -> {
<add> actual.putAll(request.attributes());
<add> return next.exchange(request);
<add> };
<add>
<add> WebClient client = this.builder
<add> .defaultRequest(spec -> spec.attribute("foo", context.get()))
<add> .filter(filter)
<add> .build();
<add>
<add> try {
<add> context.set("bar");
<add> client.get().uri("/path").attribute("foo", "bar").exchange();
<add> }
<add> finally {
<add> context.remove();
<add> }
<add>
<add> assertEquals("bar", actual.get("foo"));
<add> }
<add>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void bodyObjectPublisher() {
<ide> Mono<Void> mono = Mono.empty(); | 4 |
Ruby | Ruby | take last artifact rather than first | 580fb58f6264153f804d681f92be6073a6683014 | <ide><path>Library/Homebrew/utils/github.rb
<ide> def get_artifact_url(workflow_array)
<ide> EOS
<ide> end
<ide>
<del> artifact.first["archive_download_url"]
<add> artifact.last["archive_download_url"]
<ide> end
<ide>
<ide> def public_member_usernames(org, per_page: 100) | 1 |
Python | Python | use nodesize in _to_node for kvm | 868063b4402ccc6c9f3e09bddd5be7aaa8355beb | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> import logging
<ide> import netaddr
<ide> import random
<add>import hashlib
<ide>
<ide> from tempfile import NamedTemporaryFile
<ide> from os.path import join as pjoin
<ide> def _to_node(self, domain):
<ide> state, max_mem, memory, vcpu_count, used_cpu_time = domain.info()
<ide> state = self.NODE_STATE_MAP.get(state, NodeState.UNKNOWN)
<ide>
<add> size_extra = {'cpus': vcpu_count}
<add> id_to_hash = str(memory) + str(vcpu_count)
<add> size_id = hashlib.md5(id_to_hash.encode("utf-8")).hexdigest()
<add> size_name = domain.name() + "-size"
<add> size = NodeSize(id=size_id, name=size_name, ram=memory, disk=0,
<add> bandwidth=0, price=0, driver=self, extra=size_extra)
<add>
<ide> public_ips, private_ips = [], []
<ide>
<ide> ip_addresses = self._get_ip_addresses_for_domain(domain)
<ide> def _to_node(self, domain):
<ide> 'memory': '%s MB' % str(memory / 1024), 'processors': vcpu_count,
<ide> 'used_cpu_time': used_cpu_time, 'xml_description': xml_description}
<ide> node = Node(id=domain.UUIDString(), name=domain.name(), state=state,
<del> public_ips=public_ips, private_ips=private_ips,
<add> public_ips=public_ips, private_ips=private_ips, size=size,
<ide> driver=self, extra=extra)
<ide> node._uuid = domain.UUIDString() # we want to use a custom UUID
<ide> return node | 1 |
Ruby | Ruby | use the supplied bind values | d9a20711da15efb781a8b8402871be4890d05c6d | <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def table_exists?(name)
<ide> SELECT COUNT(*)
<ide> FROM pg_tables
<ide> WHERE tablename = $1
<del> AND schemaname = #{schema ? "'#{schema}'" : "ANY (current_schemas(false))"}
<add> AND schemaname = #{schema ? "$2" : "ANY (current_schemas(false))"}
<ide> SQL
<ide> end
<ide> | 1 |
Text | Text | fix function name ($ngoninit --> $oninit) | a909ed1a5ce2ba4594c63da12034632d5319f690 | <ide><path>CHANGELOG.md
<ide> changes section for more information
<ide> - allow directive definition property `require` to be an object
<ide> ([cd21216f](https://github.com/angular/angular.js/commit/cd21216ff7eb6d81fc9aa1d1ef994c3d8e046394),
<ide> [#8401](https://github.com/angular/angular.js/issues/8401), [#13763](https://github.com/angular/angular.js/issues/13763))
<del> - call `$ngOnInit` on directive controllers after all sibling controllers have been constructed
<add> - call `$onInit` on directive controllers after all sibling controllers have been constructed
<ide> ([3ffdf380](https://github.com/angular/angular.js/commit/3ffdf380c522cbf15a4ce5a8b08d21d40d5f8859),
<ide> [#13763](https://github.com/angular/angular.js/issues/13763))
<ide> - **$locale:** include original locale ID in `$locale` | 1 |
Javascript | Javascript | remove unused types | d9839740ef687bb2ae11cc408f3699aa5c958742 | <ide><path>packages/react-events/src/Focus.js
<ide> type FocusProps = {
<ide> onBlur: (e: FocusEvent) => void,
<ide> onFocus: (e: FocusEvent) => void,
<ide> onFocusChange: boolean => void,
<del> stopPropagation: boolean,
<ide> };
<ide>
<ide> type FocusState = {
<ide> const FocusResponder = {
<ide> focusTarget: null,
<ide> };
<ide> },
<add> stopLocalPropagation: true,
<ide> onEvent(
<ide> event: ReactResponderEvent,
<ide> context: ReactResponderContext,
<ide><path>packages/react-events/src/Hover.js
<ide> type HoverProps = {
<ide> onHoverMove: (e: HoverEvent) => void,
<ide> onHoverStart: (e: HoverEvent) => void,
<ide> preventDefault: boolean,
<del> stopPropagation: boolean,
<ide> };
<ide>
<ide> type HoverState = {
<ide><path>packages/react-events/src/Press.js
<ide> type PressProps = {
<ide> left: number,
<ide> },
<ide> preventDefault: boolean,
<del> stopPropagation: boolean,
<ide> };
<ide>
<ide> type PointerType = '' | 'mouse' | 'keyboard' | 'pen' | 'touch'; | 3 |
Mixed | Python | fix whisper doc | 84125d7e73f07ea6201008b0364bb87f035fbeb1 | <ide><path>README_es.md
<ide> Número actual de puntos de control: ** (from Microsoft Research Asia) released with the paper [LayoutXLM: Multimodal Pre-training for Multilingual Visually-rich Document Understanding](https://arxiv.org/abs/2104.08836) by Yiheng Xu, Tengchao Lv, Lei Cui, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Furu Wei.
<ide> 1. **[LED](https://huggingface.co/docs/transformers/model_doc/led)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
<ide> 1. **[LeViT](https://huggingface.co/docs/transformers/model_doc/levit)** (from Meta AI) released with the paper [LeViT: A Vision Transformer in ConvNet's Clothing for Faster Inference](https://arxiv.org/abs/2104.01136) by Ben Graham, Alaaeldin El-Nouby, Hugo Touvron, Pierre Stock, Armand Joulin, Hervé Jégou, Matthijs Douze.
<add>1. **[LiLT](https://huggingface.co/docs/transformers/main/model_doc/lilt)** (from South China University of Technology) released with the paper [LiLT: A Simple yet Effective Language-Independent Layout Transformer for Structured Document Understanding](https://arxiv.org/abs/2202.13669) by Jiapeng Wang, Lianwen Jin, Kai Ding.
<ide> 1. **[Longformer](https://huggingface.co/docs/transformers/model_doc/longformer)** (from AllenAI) released with the paper [Longformer: The Long-Document Transformer](https://arxiv.org/abs/2004.05150) by Iz Beltagy, Matthew E. Peters, Arman Cohan.
<ide> 1. **[LongT5](https://huggingface.co/docs/transformers/model_doc/longt5)** (from Google AI) released with the paper [LongT5: Efficient Text-To-Text Transformer for Long Sequences](https://arxiv.org/abs/2112.07916) by Mandy Guo, Joshua Ainslie, David Uthus, Santiago Ontanon, Jianmo Ni, Yun-Hsuan Sung, Yinfei Yang.
<ide> 1. **[LUKE](https://huggingface.co/docs/transformers/model_doc/luke)** (from Studio Ousia) released with the paper [LUKE: Deep Contextualized Entity Representations with Entity-aware Self-attention](https://arxiv.org/abs/2010.01057) by Ikuya Yamada, Akari Asai, Hiroyuki Shindo, Hideaki Takeda, Yuji Matsumoto.
<ide><path>src/transformers/models/whisper/modeling_whisper.py
<ide>
<ide> _CONFIG_FOR_DOC = "WhisperConfig"
<ide> _CHECKPOINT_FOR_DOC = "openai/whisper-tiny"
<del>_PROCESSOR_FOR_DOC = "openai/whisper-tiny"
<add>_PROCESSOR_FOR_DOC = "WhisperProcessor"
<ide> _EXPECTED_OUTPUT_SHAPE = [1, 2, 512]
<ide>
<ide> | 2 |
Go | Go | resume healthcheck on restore | 9f39889dee7d96430359d7e1f8970a88acad59e5 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide>
<ide> c.RestartManager().Cancel() // manually start containers because some need to wait for swarm networking
<ide>
<del> if c.IsPaused() && alive {
<add> switch {
<add> case c.IsPaused() && alive:
<ide> s, err := daemon.containerd.Status(context.Background(), c.ID)
<ide> if err != nil {
<ide> logger(c).WithError(err).Error("failed to get container status")
<ide> func (daemon *Daemon) restore() error {
<ide> c.Lock()
<ide> c.Paused = false
<ide> daemon.setStateCounter(c)
<add> daemon.updateHealthMonitor(c)
<ide> if err := c.CheckpointTo(daemon.containersReplica); err != nil {
<ide> log.WithError(err).Error("failed to update paused container state")
<ide> }
<ide> c.Unlock()
<ide> }
<ide> }
<add> case !c.IsPaused() && alive:
<add> logger(c).Debug("restoring healthcheck")
<add> c.Lock()
<add> daemon.updateHealthMonitor(c)
<add> c.Unlock()
<ide> }
<ide>
<ide> if !alive {
<ide><path>integration/container/restart_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/container"
<add> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/testutil/daemon"
<ide> "gotest.tools/v3/assert"
<add> "gotest.tools/v3/poll"
<ide> "gotest.tools/v3/skip"
<ide> )
<ide>
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> xRunning bool
<ide> xRunningLiveRestore bool
<ide> xStart bool
<add> xHealthCheck bool
<ide> }
<ide>
<ide> for _, tc := range []testCase{
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide> xRunningLiveRestore: true,
<ide> xStart: true,
<ide> },
<add> {
<add> desc: "container with restart=always and with healthcheck",
<add> config: &container.Config{Image: "busybox", Cmd: []string{"top"},
<add> Healthcheck: &container.HealthConfig{
<add> Test: []string{"CMD-SHELL", "sleep 1"},
<add> Interval: time.Second,
<add> },
<add> },
<add> hostConfig: &container.HostConfig{RestartPolicy: container.RestartPolicy{Name: "always"}},
<add> xRunning: true,
<add> xRunningLiveRestore: true,
<add> xStart: true,
<add> xHealthCheck: true,
<add> },
<ide> {
<ide> desc: "container created should not be restarted",
<ide> config: &container.Config{Image: "busybox", Cmd: []string{"top"}},
<ide> func TestDaemonRestartKillContainers(t *testing.T) {
<ide>
<ide> }
<ide> assert.Equal(t, expected, running, "got unexpected running state, expected %v, got: %v", expected, running)
<add>
<add> if c.xHealthCheck {
<add> startTime := time.Now()
<add> ctxPoll, cancel := context.WithTimeout(ctx, 30*time.Second)
<add> defer cancel()
<add> poll.WaitOn(t, pollForNewHealthCheck(ctxPoll, client, startTime, resp.ID), poll.WithDelay(100*time.Millisecond))
<add> }
<ide> // TODO(cpuguy83): test pause states... this seems to be rather undefined currently
<ide> })
<ide> }
<ide> }
<ide> }
<ide> }
<add>
<add>func pollForNewHealthCheck(ctx context.Context, client *client.Client, startTime time.Time, containerID string) func(log poll.LogT) poll.Result {
<add> return func(log poll.LogT) poll.Result {
<add> inspect, err := client.ContainerInspect(ctx, containerID)
<add> if err != nil {
<add> return poll.Error(err)
<add> }
<add> healthChecksTotal := len(inspect.State.Health.Log)
<add> if healthChecksTotal > 0 {
<add> if inspect.State.Health.Log[healthChecksTotal-1].Start.After(startTime) {
<add> return poll.Success()
<add> }
<add> }
<add> return poll.Continue("waiting for a new container healthcheck")
<add> }
<add>} | 2 |
Javascript | Javascript | display prompt once after error callback | 9f5977a74d99d9caa5361220eaf3d6189e400b0a | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> self.output.write(self.writer(ret) + '\n');
<ide> }
<ide>
<del> // Display prompt again
<del> self.displayPrompt();
<add> // Display prompt again (unless we already did by emitting the 'error'
<add> // event on the domain instance).
<add> if (!e) {
<add> self.displayPrompt();
<add> }
<ide> }
<ide> });
<ide>
<ide><path>test/parallel/test-repl-uncaught-exception-evalcallback.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const repl = require('repl');
<add>const { PassThrough } = require('stream');
<add>const input = new PassThrough();
<add>const output = new PassThrough();
<add>
<add>const r = repl.start({
<add> input, output,
<add> eval: common.mustCall((code, context, filename, cb) => {
<add> r.setPrompt('prompt! ');
<add> cb(new Error('err'));
<add> })
<add>});
<add>
<add>input.end('foo\n');
<add>
<add>// The output includes exactly one post-error prompt.
<add>const out = output.read().toString();
<add>assert.match(out, /prompt!/);
<add>assert.doesNotMatch(out, /prompt![\S\s]*prompt!/);
<add>output.on('data', common.mustNotCall()); | 2 |
Ruby | Ruby | add support for openjdk formula | cd93d4e38a4a850680cde1edef63448633a9f1dd | <ide><path>Library/Homebrew/extend/os/mac/language/java.rb
<ide> module Language
<ide> module Java
<ide> def self.system_java_home_cmd(version = nil)
<ide> version_flag = " --version #{version}" if version
<del> "/usr/libexec/java_home#{version_flag}"
<add> "/usr/libexec/java_home#{version_flag} --failfast 2>/dev/null"
<ide> end
<ide> private_class_method :system_java_home_cmd
<ide>
<ide> def self.java_home(version = nil)
<add> f = find_openjdk_formula(version)
<add> return f.opt_libexec/"openjdk.jdk/Contents/Home" if f
<add>
<ide> cmd = system_java_home_cmd(version)
<del> Pathname.new Utils.popen_read(cmd).chomp
<add> path = Utils.popen_read(cmd).chomp
<add>
<add> Pathname.new path if path.present?
<ide> end
<ide>
<ide> # @private
<ide> def self.java_home_shell(version = nil)
<add> f = find_openjdk_formula(version)
<add> return (f.opt_libexec/"openjdk.jdk/Contents/Home").to_s if f
<add>
<ide> "$(#{system_java_home_cmd(version)})"
<ide> end
<ide> end
<ide><path>Library/Homebrew/language/java.rb
<ide>
<ide> module Language
<ide> module Java
<add> def self.find_openjdk_formula(version = nil)
<add> can_be_newer = version&.end_with?("+")
<add> version = version.to_i
<add>
<add> openjdk = Formula["openjdk"]
<add> [openjdk, *openjdk.versioned_formulae].find do |f|
<add> next false unless f.any_version_installed?
<add>
<add> unless version.zero?
<add> major = f.version.to_s[/\d+/].to_i
<add> next false if major < version
<add> next false if major > version && !can_be_newer
<add> end
<add>
<add> true
<add> end
<add> rescue FormulaUnavailableError
<add> nil
<add> end
<add> private_class_method :find_openjdk_formula
<add>
<ide> def self.java_home(version = nil)
<add> f = find_openjdk_formula(version)
<add> return f.opt_libexec if f
<add>
<ide> req = JavaRequirement.new [*version]
<ide> raise UnsatisfiedRequirements, req.message unless req.satisfied?
<ide> | 2 |
Python | Python | add order= argument to recarray __new__ | e6f253346d7d87ba362f8283205f09eb336c482d | <ide><path>numpy/core/records.py
<ide> class recarray(ndarray):
<ide> occupy in memory).
<ide> offset : int, optional
<ide> Start reading buffer (`buf`) from this offset onwards.
<add> order : {'C', 'F'}, optional
<add> Row-major or column-major order.
<ide>
<ide> Returns
<ide> -------
<ide> class recarray(ndarray):
<ide> """
<ide> def __new__(subtype, shape, dtype=None, buf=None, offset=0, strides=None,
<ide> formats=None, names=None, titles=None,
<del> byteorder=None, aligned=False):
<add> byteorder=None, aligned=False, order='C'):
<ide>
<ide> if dtype is not None:
<ide> descr = sb.dtype(dtype)
<ide> else:
<ide> descr = format_parser(formats, names, titles, aligned, byteorder)._descr
<ide>
<ide> if buf is None:
<del> self = ndarray.__new__(subtype, shape, (record, descr))
<add> self = ndarray.__new__(subtype, shape, (record, descr), order=order)
<ide> else:
<ide> self = ndarray.__new__(subtype, shape, (record, descr),
<ide> buffer=buf, offset=offset,
<del> strides=strides)
<add> strides=strides, order=order)
<ide> return self
<ide>
<ide> def __getattribute__(self, attr): | 1 |
Python | Python | use less precision for almostequal | 26482c2d7029405fbd818548e4e404504baf240e | <ide><path>celery/tests/test_task.py
<ide> def test_every_minute_execution_is_due(self):
<ide> last_ran = self.now - timedelta(seconds=61)
<ide> due, remaining = EveryMinutePeriodic().is_due(last_ran)
<ide> self.assertTrue(due)
<del> self.assertAlmostEquals(remaining, self.next_minute, 2)
<add> self.assertAlmostEquals(remaining, self.next_minute, 1)
<ide>
<ide> def test_every_minute_execution_is_not_due(self):
<ide> last_ran = self.now - timedelta(seconds=self.now.second)
<ide> due, remaining = EveryMinutePeriodic().is_due(last_ran)
<ide> self.assertFalse(due)
<del> self.assertAlmostEquals(remaining, self.next_minute, 2)
<add> self.assertAlmostEquals(remaining, self.next_minute, 1)
<ide>
<ide> # 29th of May 2010 is a saturday
<ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 29, 10, 30))
<ide> def test_execution_is_due_on_saturday(self):
<ide> last_ran = self.now - timedelta(seconds=61)
<ide> due, remaining = EveryMinutePeriodic().is_due(last_ran)
<ide> self.assertTrue(due)
<del> self.assertAlmostEquals(remaining, self.next_minute, 2)
<add> self.assertAlmostEquals(remaining, self.next_minute, 1)
<ide>
<ide> # 30th of May 2010 is a sunday
<ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 30, 10, 30))
<ide> def test_execution_is_due_on_sunday(self):
<ide> last_ran = self.now - timedelta(seconds=61)
<ide> due, remaining = EveryMinutePeriodic().is_due(last_ran)
<ide> self.assertTrue(due)
<del> self.assertAlmostEquals(remaining, self.next_minute, 2)
<add> self.assertAlmostEquals(remaining, self.next_minute, 1)
<ide>
<ide> # 31st of May 2010 is a monday
<ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 31, 10, 30))
<ide> def test_execution_is_due_on_monday(self):
<ide> last_ran = self.now - timedelta(seconds=61)
<ide> due, remaining = EveryMinutePeriodic().is_due(last_ran)
<ide> self.assertTrue(due)
<del> self.assertAlmostEquals(remaining, self.next_minute, 2)
<add> self.assertAlmostEquals(remaining, self.next_minute, 1)
<ide>
<ide> @patch_crontab_nowfun(HourlyPeriodic, datetime(2010, 5, 10, 10, 30))
<ide> def test_every_hour_execution_is_due(self): | 1 |
Javascript | Javascript | address @ichernev concerns | 3c527715518319a54d42a96658332b9a90c0f24a | <ide><path>moment.js
<ide>
<ide> currentDate = currentDateArray(config);
<ide>
<del> //compute day of the year form weeks and weekdays
<add> //compute day of the year from weeks and weekdays
<ide> if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
<ide> fixYear = function (val) {
<ide> return val ?
<ide> (val.length < 3 ? (parseInt(val, 10) > 68 ? '19' + val : '20' + val) : val) :
<del> (config._a[YEAR] != null ? currentDate[YEAR] :
<del> (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]));
<add> (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]);
<ide> };
<ide>
<ide> w = config._w;
<add> lang = getLangDefinition(config._l);
<ide> if (w.GG != null || w.W != null || w.E != null) {
<del> temp = dayOfYearFromWeeks(fixYear(w.GG), w.W, parseWeekday(w.E, config._l), 4, 1);
<add> temp = dayOfYearFromWeeks(fixYear(w.GG), w.W, w.E, 4, 1);
<add> }
<add> else if (w.d != null) {
<add> temp = dayOfYearFromWeeks(fixYear(w.gg), w.w, parseWeekday(w.d, lang), 6, 0);
<ide> }
<ide> else {
<del> lang = getLangDefinition(config._l);
<del> temp = dayOfYearFromWeeks(fixYear(w.gg), w.w, parseWeekday(w.e || w.d, lang), lang._week.doy, lang._week.dow);
<add> temp = dayOfYearFromWeeks(fixYear(w.gg), w.w, w.e, lang._week.doy, lang._week.dow);
<ide> }
<ide>
<ide> config._a[YEAR] = temp.year;
<ide> };
<ide> }
<ide>
<add> //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
<ide> function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) {
<del> var d = new Date(year, 0).getUTCDay(),
<add> var d = new Date(Date.UTC(year, 0)).getUTCDay(),
<ide> daysToAdd, dayOfYear;
<ide>
<ide> week = week || 1;
<ide><path>test/moment/create.js
<ide> exports.create = {
<ide> test.equal(moment('1999 37', 'GGGG WW').format('YYYY MM DD'), "1999 09 13", 'iso week double');
<ide>
<ide> //year + week + day
<del> test.equal(moment('1999 37 4', 'gggg ww e').format('YYYY MM DD'), "1999 09 09", 'day');
<del> test.equal(moment('1999 37 04', 'gggg ww e').format('YYYY MM DD'), "1999 09 09", 'day');
<ide> test.equal(moment('1999 37 4', 'GGGG WW E').format('YYYY MM DD'), "1999 09 16", 'iso day');
<del> test.equal(moment('1999 37 04', 'GGGG WW E').format('YYYY MM DD'), "1999 09 16", 'iso day');
<add> test.equal(moment('1999 37 04', 'GGGG WW E').format('YYYY MM DD'), "1999 09 16", 'iso day wide');
<add>
<add> test.equal(moment('1999 37 4', 'gggg ww e').format('YYYY MM DD'), "1999 09 09", 'day');
<add> test.equal(moment('1999 37 04', 'gggg ww e').format('YYYY MM DD'), "1999 09 09", 'day wide');
<ide>
<ide> //d
<ide> test.equal(moment('1999 37 4', 'gggg ww d').format('YYYY MM DD'), "1999 09 09", 'd');
<ide> exports.create = {
<ide> //lower-order only
<ide> test.equal(moment('22', 'ww').week(), 22, "week sets the week by itself");
<ide> test.equal(moment('22', 'ww').year(), moment().year(), "week keeps this year");
<del> test.equal(moment('2013 22', 'YYYY ww').year(), 2013, "week keeps parsed year");
<add> test.equal(moment('2012 22', 'YYYY ww').year(), 2012, "week keeps parsed year");
<ide>
<ide> test.equal(moment('22', 'WW').isoWeek(), 22, "iso week sets the week by itself");
<del> test.equal(moment('2013 22', 'YYYY WW').year(), 2013, "iso week keeps parsed year");
<add> test.equal(moment('2012 22', 'YYYY WW').year(), 2012, "iso week keeps parsed year");
<ide> test.equal(moment('22', 'WW').year(), moment().year(), "iso week keeps this year");
<ide>
<ide> //order
<ide> exports.create = {
<ide> test.equals(moment('1999-W37-4 3:30', 'GGGG-[W]WW-E HH:mm').format('YYYY MM DD HH:mm'), '1999 09 16 03:30', "parsing weeks and hours");
<ide>
<ide> test.done();
<add> },
<add>
<add> 'parsing localized weekdays' : function (test) {
<add> try {
<add> moment.lang('fr');
<add> test.equal(moment('1999 37 4', 'gggg ww e').format('YYYY MM DD'), "1999 09 16", 'localized e uses local doy and dow');
<add> test.equal(moment('1999 37 4', 'gggg ww d').format('YYYY MM DD'), "1999 09 09", 'localized d ignores lang entirely');
<add> }
<add> finally {
<add> moment.lang('en');
<add> test.done();
<add> }
<ide> }
<ide> }; | 2 |
Text | Text | add object keys to example | bbce381e16b0687dbcd1919fe40f117530be3c96 | <ide><path>CONTRIBUTING.md
<ide> in the proper package's repository.
<ide> # * `package-disabled` - after the package is disabled.
<ide> #
<ide> # name - The {String} name of the package to disable.
<add># options - The {Object} with disable options (default: {}):
<add># :trackTime - `true` to track the amount of time disabling took.
<add># :ignoreErrors - `true` to catch and ignore errors thrown.
<ide> # callback - The {Function} to call after the package has been disabled.
<ide> #
<ide> # Returns `undefined`.
<del>disablePackage: (name, delay, callback) ->
<add>disablePackage: (name, options, callback) ->
<ide> ``` | 1 |
Python | Python | add more docs to function fromfile() | ae4e6ce449c06b25806b499ff2384d7335583570 | <ide><path>numpy/add_newdocs.py
<ide> """)
<ide>
<ide> add_newdoc('numpy.core.multiarray','fromfile',
<del> """fromfile(file=, dtype=float, count=-1, sep='')
<add> """fromfile(file=, dtype=float, count=-1, sep='') -> array.
<ide>
<del> Return an array of the given data type from a (text or binary) file.
<del> The file argument can be an open file or a string with the name of a
<del> file to read from. If count==-1, then the entire file is read,
<del> otherwise count is the number of items of the given type read in. If
<del> sep is '' then read a binary file, otherwise it gives the separator
<del> between elements in a text file.
<add> Required arguments:
<add> file -- open file object or string containing file name.
<add>
<add> Keyword arguments:
<add> dtype -- type and order of the returned array (default float)
<add> count -- number of items to input (default all)
<add> sep -- separater between items if file is a text file (default "")
<add>
<add> Return an array of the given data type from a text or binary file. The
<add> 'file' argument can be an open file or a string with the name of a file to
<add> read from. If 'count' == -1 the entire file is read, otherwise count is the
<add> number of items of the given type to read in. If 'sep' is "" it means to
<add> read binary data from the file using the specified dtype, otherwise it gives
<add> the separator between elements in a text file. The 'dtype' value is also
<add> used to determine the size and order of the items in binary files.
<ide>
<del> WARNING: This function should be used sparingly, as it is not a
<del> platform-independent method of persistence. But it can be useful to
<del> read in simply-formatted or binary data quickly.
<add>
<add> Data written using the tofile() method can be conveniently recovered using
<add> this function.
<add>
<add> WARNING: This function should be used sparingly as the binary files are not
<add> platform independent. In particular, they contain no endianess or datatype
<add> information. Nevertheless it can be useful for reading in simply formatted
<add> or binary data quickly.
<ide>
<ide> """)
<ide>
<ide> """a.tofile(fid, sep="", format="%s") -> None. Write the data to a file.
<ide>
<ide> Required arguments:
<del> file -- an open file object or a filename
<add> file -- an open file object or a string containing a filename
<ide>
<ide> Keyword arguments:
<ide> sep -- separator for text output. Write binary if empty (default "")
<ide> endianess and precision is lost, so this method is not a good choice for
<ide> files intended to archive data or transport data between machines with
<ide> different endianess. Some of these problems can be overcome by outputting
<del> text files at the expense of speed and file size.
<add> the data as text files at the expense of speed and file size.
<ide>
<ide> If 'sep' is empty this method is equivalent to file.write(a.tostring()). If
<ide> 'sep' is not empty each data item is converted to the nearest Python type
<ide> and formatted using "format"%item. The resulting strings are written to the
<ide> file separated by the contents of 'sep'.
<ide>
<add> The data produced by this method can be recovered by using the function
<add> fromfile().
<add>
<ide> """))
<ide>
<ide> | 1 |
Text | Text | fix checkstyle violation | d9bb9b55eecc87e18ae07a3b7d6d0897addf5741 | <ide><path>import-into-eclipse.md
<ide> _When instructed to execute `./gradlew` from the command line, be sure to execut
<ide>
<ide> 1. Ensure that Eclipse launches with JDK 8.
<ide> - For example, on Mac OS this can be configured in the `Info.plist` file located in the `Contents` folder of the installed Eclipse or STS application (e.g., the `Eclipse.app` file).
<del>1. Install the [Kotlin Plugin for Eclipse](http://marketplace.eclipse.org/content/kotlin-plugin-eclipse) in Eclipse.
<add>1. Install the [Kotlin Plugin for Eclipse](https://marketplace.eclipse.org/content/kotlin-plugin-eclipse) in Eclipse.
<ide> 1. Install the [Eclipse Groovy Development Tools](https://github.com/groovy/groovy-eclipse/wiki) in Eclipse.
<ide> 1. Switch to Groovy 2.5 (Preferences -> Groovy -> Compiler -> Switch to 2.5...) in Eclipse.
<ide> 1. Change the _Forbidden reference (access rule)_ in Eclipse from Error to Warning | 1 |
Text | Text | capitalize url in titles for consistency | e5366448cbffcd0827a5c6646fd2d37cb8094c7c | <ide><path>guide/english/html/url-encoding-reference/index.md
<ide> ---
<del>title: Url Encoding Reference
<add>title: URL Encoding Reference
<ide> ---
<del>## Url Encoding Reference
<add>## URL Encoding Reference
<ide>
<ide> A URL is an address for a website. Just like postal addresses have to follow a specific format to be understood by the postman, URLS have to follow a format to be understood and get you to the right location.
<ide> | 1 |
Java | Java | support stomp disconnect with receipt | 7da3fb4ce6dc90048b2a3f661fa80f38bede8ed9 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java
<ide> else if (logger.isTraceEnabled()) {
<ide> @Override
<ide> public void onSuccess(Void result) {
<ide> if (accessor.getCommand() == StompCommand.DISCONNECT) {
<del> clearConnection();
<add> afterDisconnectSent(accessor);
<ide> }
<ide> }
<ide> @Override
<ide> else if (logger.isErrorEnabled()) {
<ide> return future;
<ide> }
<ide>
<add> /**
<add> * After a DISCONNECT there should be no more client frames so we can
<add> * close the connection pro-actively. However, if the DISCONNECT has a
<add> * receipt header we leave the connection open and expect the server will
<add> * respond with a RECEIPT and then close the connection.
<add> *
<add> * @see <a href="http://stomp.github.io/stomp-specification-1.2.html#DISCONNECT">
<add> * STOMP Specification 1.2 DISCONNECT</a>
<add> */
<add> private void afterDisconnectSent(StompHeaderAccessor accessor) {
<add> if (accessor.getReceipt() == null) {
<add> clearConnection();
<add> }
<add> }
<add>
<ide> /**
<ide> * Clean up state associated with the connection and close it.
<ide> * Any exception arising from closing the connection are propagated.
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java
<ide> public void relayReconnectsIfBrokerComesBackUp() throws Exception {
<ide>
<ide> startActiveMqBroker();
<ide> this.eventPublisher.expectBrokerAvailabilityEvent(true);
<del>
<del> // TODO The event publisher assertions show that the broker's back up and the system relay session
<del> // has reconnected. We need to decide what we want the reconnect behaviour to be for client relay
<del> // sessions and add further message sending and assertions as appropriate. At the moment any client
<del> // sessions will be closed and an ERROR from will be sent.
<ide> }
<ide>
<ide> @Test
<ide> public void disconnectClosesRelaySessionCleanly() throws Exception {
<ide> assertTrue("Unexpected messages: " + this.responseHandler.queue, this.responseHandler.queue.isEmpty());
<ide> }
<ide>
<add> @Test
<add> public void disconnectWithReceipt() throws Exception {
<add>
<add> logger.debug("Starting test disconnectWithReceipt()");
<add>
<add> MessageExchange connect = MessageExchangeBuilder.connect("sess1").build();
<add> this.relay.handleMessage(connect.message);
<add> this.responseHandler.expectMessages(connect);
<add>
<add> MessageExchange disconnect = MessageExchangeBuilder.disconnectWithReceipt("sess1", "r123").build();
<add> this.relay.handleMessage(disconnect.message);
<add>
<add> this.responseHandler.expectMessages(disconnect);
<add> }
<add>
<ide>
<ide> private static class TestEventPublisher implements ApplicationEventPublisher {
<ide>
<ide> public static MessageExchangeBuilder send(String destination, String payload) {
<ide> return new MessageExchangeBuilder(message);
<ide> }
<ide>
<add> public static MessageExchangeBuilder disconnectWithReceipt(String sessionId, String receiptId) {
<add>
<add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
<add> headers.setSessionId(sessionId);
<add> headers.setReceipt(receiptId);
<add> Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
<add>
<add> MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
<add> builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId));
<add> return builder;
<add> }
<add>
<ide> public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) {
<ide> Assert.isTrue(SimpMessageType.MESSAGE.equals(headers.getMessageType()));
<ide> String destination = this.headers.getDestination(); | 2 |
Mixed | Text | remove the word "mongrel" from documents | b9e98d62c24b04937a219285aef69c2a8344beab | <ide><path>activesupport/lib/active_support/backtrace_cleaner.rb
<ide> module ActiveSupport
<ide> #
<ide> # bc = BacktraceCleaner.new
<ide> # bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
<del> # bc.add_silencer { |line| line =~ /mongrel|rubygems/ } # skip any lines from mongrel or rubygems
<add> # bc.add_silencer { |line| line =~ /puma|rubygems/ } # skip any lines from puma or rubygems
<ide> # bc.clean(exception.backtrace) # perform the cleanup
<ide> #
<ide> # To reconfigure an existing BacktraceCleaner (like the default one in Rails)
<ide> def add_filter(&block)
<ide> # Adds a silencer from the block provided. If the silencer returns +true+
<ide> # for a given line, it will be excluded from the clean backtrace.
<ide> #
<del> # # Will reject all lines that include the word "mongrel", like "/gems/mongrel/server.rb" or "/app/my_mongrel_server/rb"
<del> # backtrace_cleaner.add_silencer { |line| line =~ /mongrel/ }
<add> # # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb"
<add> # backtrace_cleaner.add_silencer { |line| line =~ /puma/ }
<ide> def add_silencer(&block)
<ide> @silencers << block
<ide> end
<ide><path>activesupport/lib/active_support/cache/memory_store.rb
<ide> module ActiveSupport
<ide> module Cache
<ide> # A cache store implementation which stores everything into memory in the
<ide> # same process. If you're running multiple Ruby on Rails server processes
<del> # (which is the case if you're using mongrel_cluster or Phusion Passenger),
<add> # (which is the case if you're using Phusion Passenger or puma clustered mode),
<ide> # then this means that Rails server process instances won't be able
<ide> # to share cache data with each other and this may not be the most
<ide> # appropriate cache in that scenario.
<ide><path>guides/source/caching_with_rails.md
<ide> config.cache_store = :memory_store, { size: 64.megabytes }
<ide> ```
<ide>
<ide> If you're running multiple Ruby on Rails server processes (which is the case
<del>if you're using mongrel_cluster or Phusion Passenger), then your Rails server
<add>if you're using Phusion Passenger or puma clustered mode), then your Rails server
<ide> process instances won't be able to share cache data with each other. This cache
<ide> store is not appropriate for large application deployments. However, it can
<ide> work well for small, low traffic sites with only a couple of server processes,
<ide><path>guides/source/configuring.md
<ide> development:
<ide> timeout: 5000
<ide> ```
<ide>
<del>Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, mongrel, Unicorn etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit.
<add>Since the connection pooling is handled inside of Active Record by default, all application servers (Thin, Puma, Unicorn etc.) should behave the same. The database connection pool is initially empty. As demand for connections increases it will create them until it reaches the connection pool limit.
<ide>
<ide> Any one request will check out a connection the first time it requires access to the database. At the end of the request it will check the connection back in. This means that the additional connection slot will be available again for the next request in the queue.
<ide>
<ide><path>guides/source/initialization.md
<ide> def parse!(args)
<ide> args, options = args.dup, {}
<ide>
<ide> opt_parser = OptionParser.new do |opts|
<del> opts.banner = "Usage: rails server [mongrel, thin, etc] [options]"
<add> opts.banner = "Usage: rails server [puma, thin, etc] [options]"
<ide> opts.on("-p", "--port=port", Integer,
<ide> "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
<ide> ...
<ide><path>guides/source/security.md
<ide> It works like this:
<ide> * The user takes the cookie from the first step (which they previously copied) and replaces the current cookie in the browser.
<ide> * The user has their original credit back.
<ide>
<del>Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers (mongrels). Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).
<add>Including a nonce (a random value) in the session solves replay attacks. A nonce is valid only once, and the server has to keep track of all the valid nonces. It gets even more complicated if you have several application servers. Storing nonces in a database table would defeat the entire purpose of CookieStore (avoiding accessing the database).
<ide>
<ide> The best _solution against it is not to store this kind of data in a session, but in the database_. In this case store the credit in the database and the logged_in_user_id in the session.
<ide>
<ide><path>railties/lib/rails/commands/server.rb
<ide> def parse!(args)
<ide>
<ide> def option_parser(options)
<ide> OptionParser.new do |opts|
<del> opts.banner = "Usage: rails server [mongrel, thin etc] [options]"
<add> opts.banner = "Usage: rails server [puma, thin etc] [options]"
<ide> opts.on("-p", "--port=port", Integer,
<ide> "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
<ide> opts.on("-b", "--binding=IP", String, | 7 |
Python | Python | add a device argument to the eval script | 196cce6e9b10c5749daf05fdc02d75b924639b00 | <ide><path>examples/research_projects/robust-speech-event/eval.py
<ide> import re
<ide> from typing import Dict
<ide>
<add>import torch
<ide> from datasets import Audio, Dataset, load_dataset, load_metric
<ide>
<ide> from transformers import AutoFeatureExtractor, pipeline
<ide> def main(args):
<ide> dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
<ide>
<ide> # load eval pipeline
<del> asr = pipeline("automatic-speech-recognition", model=args.model_id)
<add> if args.device is None:
<add> args.device = 0 if torch.cuda.is_available() else -1
<add> asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)
<ide>
<ide> # map function to decode audio
<ide> def map_to_pred(batch):
<ide> def map_to_pred(batch):
<ide> parser.add_argument(
<ide> "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."
<ide> )
<add> parser.add_argument(
<add> "--device",
<add> type=int,
<add> default=None,
<add> help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",
<add> )
<ide> args = parser.parse_args()
<ide>
<ide> main(args) | 1 |
Javascript | Javascript | stop alloc() uninitialized memory return | 40a7beeddac9b9ec9ef5b49157daaf8470648b08 | <ide><path>lib/buffer.js
<ide> function assertSize(size) {
<ide> Buffer.alloc = function alloc(size, fill, encoding) {
<ide> assertSize(size);
<ide> if (fill !== undefined && fill !== 0 && size > 0) {
<del> return _fill(createUnsafeBuffer(size), fill, encoding);
<add> const buf = createUnsafeBuffer(size);
<add> return _fill(buf, fill, 0, buf.length, encoding);
<ide> }
<ide> return new FastBuffer(size);
<ide> };
<ide><path>test/parallel/test-buffer-alloc.js
<ide> common.expectsError(() => {
<ide> code: 'ERR_INVALID_ARG_VALUE',
<ide> type: TypeError
<ide> });
<add>
<add>common.expectsError(() => {
<add> Buffer.alloc(40, 'x', 20);
<add>}, {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError
<add>}); | 2 |
Javascript | Javascript | remove broken code in promises/write | ca6b12e28df53110de7ee58699d5af099d036c67 | <ide><path>lib/internal/fs/promises.js
<ide> async function write(handle, buffer, offset, length, position) {
<ide>
<ide> if (typeof buffer !== 'string')
<ide> buffer += '';
<del> if (typeof position !== 'function') {
<del> if (typeof offset === 'function') {
<del> position = offset;
<del> offset = null;
<del> } else {
<del> position = length;
<del> }
<del> length = 'utf8';
<del> }
<ide> const bytesWritten = (await binding.writeString(handle.fd, buffer, offset,
<ide> length, kUsePromises)) || 0;
<ide> return { bytesWritten, buffer }; | 1 |
Python | Python | drop accidental (uneeded) validation logic | 24ed0fa4b987a4a03b090963965e9865830c943f | <ide><path>rest_framework/serializers.py
<ide> def restore_object(self, attrs, instance=None):
<ide> else:
<ide> instance = self.opts.model(**attrs)
<ide>
<del> try:
<del> instance.full_clean(exclude=self.get_validation_exclusions())
<del> except ValidationError as err:
<del> self._errors = err.message_dict
<del> return None
<del>
<ide> return instance
<ide>
<ide> def from_native(self, data, files): | 1 |
Javascript | Javascript | replace indexof with includes | 01422769775a2ce7dfef8aa6dbda2d326f002e13 | <ide><path>test/addons-napi/test_constructor/test.js
<ide> const propertyNames = [];
<ide> for (const name in test_object) {
<ide> propertyNames.push(name);
<ide> }
<del>assert.ok(propertyNames.indexOf('echo') >= 0);
<del>assert.ok(propertyNames.indexOf('readwriteValue') >= 0);
<del>assert.ok(propertyNames.indexOf('readonlyValue') >= 0);
<del>assert.ok(propertyNames.indexOf('hiddenValue') < 0);
<del>assert.ok(propertyNames.indexOf('readwriteAccessor1') < 0);
<del>assert.ok(propertyNames.indexOf('readwriteAccessor2') < 0);
<del>assert.ok(propertyNames.indexOf('readonlyAccessor1') < 0);
<del>assert.ok(propertyNames.indexOf('readonlyAccessor2') < 0);
<add>assert.ok(propertyNames.includes('echo'));
<add>assert.ok(propertyNames.includes('readwriteValue'));
<add>assert.ok(propertyNames.includes('readonlyValue'));
<add>assert.ok(!propertyNames.includes('hiddenValue'));
<add>assert.ok(!propertyNames.includes('readwriteAccessor1'));
<add>assert.ok(!propertyNames.includes('readwriteAccessor2'));
<add>assert.ok(!propertyNames.includes('readonlyAccessor1'));
<add>assert.ok(!propertyNames.includes('readonlyAccessor2'));
<ide>
<ide> // The napi_writable attribute should be ignored for accessors.
<ide> test_object.readwriteAccessor1 = 1;
<ide><path>test/addons-napi/test_properties/test.js
<ide> const propertyNames = [];
<ide> for (const name in test_object) {
<ide> propertyNames.push(name);
<ide> }
<del>assert.ok(propertyNames.indexOf('echo') >= 0);
<del>assert.ok(propertyNames.indexOf('readwriteValue') >= 0);
<del>assert.ok(propertyNames.indexOf('readonlyValue') >= 0);
<del>assert.ok(propertyNames.indexOf('hiddenValue') < 0);
<del>assert.ok(propertyNames.indexOf('readwriteAccessor1') < 0);
<del>assert.ok(propertyNames.indexOf('readwriteAccessor2') < 0);
<del>assert.ok(propertyNames.indexOf('readonlyAccessor1') < 0);
<del>assert.ok(propertyNames.indexOf('readonlyAccessor2') < 0);
<add>assert.ok(propertyNames.includes('echo'));
<add>assert.ok(propertyNames.includes('readwriteValue'));
<add>assert.ok(propertyNames.includes('readonlyValue'));
<add>assert.ok(!propertyNames.includes('hiddenValue'));
<add>assert.ok(!propertyNames.includes('readwriteAccessor1'));
<add>assert.ok(!propertyNames.includes('readwriteAccessor2'));
<add>assert.ok(!propertyNames.includes('readonlyAccessor1'));
<add>assert.ok(!propertyNames.includes('readonlyAccessor2'));
<ide>
<ide> // The napi_writable attribute should be ignored for accessors.
<ide> test_object.readwriteAccessor1 = 1;
<ide><path>test/inspector/test-inspector.js
<ide> function checkBadPath(err, response) {
<ide> function expectMainScriptSource(result) {
<ide> const expected = helper.mainScriptSource();
<ide> const source = result['scriptSource'];
<del> assert(source && (source.indexOf(expected) >= 0),
<add> assert(source && (source.includes(expected)),
<ide> 'Script source is wrong: ' + source);
<ide> }
<ide>
<ide><path>test/parallel/test-child-process-default-options.js
<ide> child.stdout.on('data', function(chunk) {
<ide> });
<ide>
<ide> process.on('exit', function() {
<del> assert.ok(response.indexOf('HELLO=WORLD') >= 0,
<add> assert.ok(response.includes('HELLO=WORLD'),
<ide> 'spawn did not use process.env as default');
<ide> });
<ide><path>test/parallel/test-child-process-env.js
<ide> child.stdout.on('data', function(chunk) {
<ide> });
<ide>
<ide> process.on('exit', function() {
<del> assert.ok(response.indexOf('HELLO=WORLD') >= 0);
<del> assert.ok(response.indexOf('FOO=BAR') >= 0);
<add> assert.ok(response.includes('HELLO=WORLD'));
<add> assert.ok(response.includes('FOO=BAR'));
<ide> });
<ide><path>test/parallel/test-child-process-exec-env.js
<ide> process.on('exit', function() {
<ide> console.log('response: ', response);
<ide> assert.strictEqual(1, success_count);
<ide> assert.strictEqual(0, error_count);
<del> assert.ok(response.indexOf('HELLO=WORLD') >= 0);
<add> assert.ok(response.includes('HELLO=WORLD'));
<ide> });
<ide><path>test/parallel/test-child-process-spawnsync-input.js
<ide> function verifyBufOutput(ret) {
<ide> assert.deepStrictEqual(ret.stderr, msgErrBuf);
<ide> }
<ide>
<del>if (process.argv.indexOf('spawnchild') !== -1) {
<add>if (process.argv.includes('spawnchild')) {
<ide> switch (process.argv[3]) {
<ide> case '1':
<ide> ret = spawnSync(process.execPath, args, { stdio: 'inherit' });
<ide><path>test/parallel/test-domain-throw-error-then-throw-from-uncaught-exception-handler.js
<ide> const RAN_UNCAUGHT_EXCEPTION_HANDLER_EXIT_CODE = 42;
<ide>
<ide> if (process.argv[2] === 'child') {
<ide> process.on('uncaughtException', common.mustCall(function onUncaught() {
<del> if (process.execArgv.indexOf('--abort-on-uncaught-exception') !== -1) {
<add> if (process.execArgv.includes('--abort-on-uncaught-exception')) {
<ide> // When passing --abort-on-uncaught-exception to the child process,
<ide> // we want to make sure that this handler (the process' uncaughtException
<ide> // event handler) wasn't called. Unfortunately we can't parse the child
<ide><path>test/parallel/test-domain-with-abort-on-uncaught-exception.js
<ide> if (process.argv[2] === 'child') {
<ide> d.on('error', function(err) {
<ide> // Swallowing the error on purpose if 'throwInDomainErrHandler' is not
<ide> // set
<del> if (process.argv.indexOf('throwInDomainErrHandler') !== -1) {
<add> if (process.argv.includes('throwInDomainErrHandler')) {
<ide> // If useTryCatch is set, wrap the throw in a try/catch block.
<ide> // This is to make sure that a caught exception does not trigger
<ide> // an abort.
<del> if (process.argv.indexOf('useTryCatch') !== -1) {
<add> if (process.argv.includes('useTryCatch')) {
<ide> try {
<ide> throw new Error(domainErrHandlerExMessage);
<ide> } catch (e) {
<ide><path>test/parallel/test-error-reporting.js
<ide> function errExec(script, callback) {
<ide> assert.ok(stderr.split('\n').length > 2);
<ide>
<ide> // Assert the script is mentioned in error output.
<del> assert.ok(stderr.indexOf(script) >= 0);
<add> assert.ok(stderr.includes(script));
<ide>
<ide> // Proxy the args for more tests.
<ide> callback(err, stdout, stderr);
<ide><path>test/parallel/test-fs-error-messages.js
<ide> const existingDir2 = path.join(common.fixturesDir, 'keys');
<ide>
<ide> fs.stat(fn, function(err) {
<ide> assert.strictEqual(fn, err.path);
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.lstat(fn, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.readlink(fn, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.link(fn, 'foo', function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.link(existingFile, existingFile2, function(err) {
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<del> assert.ok(0 <= err.message.indexOf(existingFile2));
<add> assert.ok(err.message.includes(existingFile));
<add> assert.ok(err.message.includes(existingFile2));
<ide> });
<ide>
<ide> fs.symlink(existingFile, existingFile2, function(err) {
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<del> assert.ok(0 <= err.message.indexOf(existingFile2));
<add> assert.ok(err.message.includes(existingFile));
<add> assert.ok(err.message.includes(existingFile2));
<ide> });
<ide>
<ide> fs.unlink(fn, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.rename(fn, 'foo', function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.rename(existingDir, existingDir2, function(err) {
<del> assert.ok(0 <= err.message.indexOf(existingDir));
<del> assert.ok(0 <= err.message.indexOf(existingDir2));
<add> assert.ok(err.message.includes(existingDir));
<add> assert.ok(err.message.includes(existingDir2));
<ide> });
<ide>
<ide> fs.rmdir(fn, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.mkdir(existingFile, 0o666, function(err) {
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<add> assert.ok(err.message.includes(existingFile));
<ide> });
<ide>
<ide> fs.rmdir(existingFile, function(err) {
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<add> assert.ok(err.message.includes(existingFile));
<ide> });
<ide>
<ide> fs.chmod(fn, 0o666, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.open(fn, 'r', 0o666, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> fs.readFile(fn, function(err) {
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> });
<ide>
<ide> // Sync
<ide> try {
<ide> fs.statSync(fn);
<ide> } catch (err) {
<ide> errors.push('stat');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.mkdirSync(existingFile, 0o666);
<ide> } catch (err) {
<ide> errors.push('mkdir');
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<add> assert.ok(err.message.includes(existingFile));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.chmodSync(fn, 0o666);
<ide> } catch (err) {
<ide> errors.push('chmod');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.lstatSync(fn);
<ide> } catch (err) {
<ide> errors.push('lstat');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.readlinkSync(fn);
<ide> } catch (err) {
<ide> errors.push('readlink');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.linkSync(fn, 'foo');
<ide> } catch (err) {
<ide> errors.push('link');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.linkSync(existingFile, existingFile2);
<ide> } catch (err) {
<ide> errors.push('link');
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<del> assert.ok(0 <= err.message.indexOf(existingFile2));
<add> assert.ok(err.message.includes(existingFile));
<add> assert.ok(err.message.includes(existingFile2));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.symlinkSync(existingFile, existingFile2);
<ide> } catch (err) {
<ide> errors.push('symlink');
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<del> assert.ok(0 <= err.message.indexOf(existingFile2));
<add> assert.ok(err.message.includes(existingFile));
<add> assert.ok(err.message.includes(existingFile2));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.unlinkSync(fn);
<ide> } catch (err) {
<ide> errors.push('unlink');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.rmdirSync(fn);
<ide> } catch (err) {
<ide> errors.push('rmdir');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.rmdirSync(existingFile);
<ide> } catch (err) {
<ide> errors.push('rmdir');
<del> assert.ok(0 <= err.message.indexOf(existingFile));
<add> assert.ok(err.message.includes(existingFile));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.openSync(fn, 'r');
<ide> } catch (err) {
<ide> errors.push('opens');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.renameSync(fn, 'foo');
<ide> } catch (err) {
<ide> errors.push('rename');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.renameSync(existingDir, existingDir2);
<ide> } catch (err) {
<ide> errors.push('rename');
<del> assert.ok(0 <= err.message.indexOf(existingDir));
<del> assert.ok(0 <= err.message.indexOf(existingDir2));
<add> assert.ok(err.message.includes(existingDir));
<add> assert.ok(err.message.includes(existingDir2));
<ide> }
<ide>
<ide> try {
<ide> ++expected;
<ide> fs.readdirSync(fn);
<ide> } catch (err) {
<ide> errors.push('readdir');
<del> assert.ok(0 <= err.message.indexOf(fn));
<add> assert.ok(err.message.includes(fn));
<ide> }
<ide>
<ide> process.on('exit', function() {
<ide><path>test/parallel/test-http-client-parse-error.js
<ide> net.createServer(function(c) {
<ide> path: '/'
<ide> }).on('error', function(e) {
<ide> console.log('got error from client');
<del> assert.ok(e.message.indexOf('Parse Error') >= 0);
<add> assert.ok(e.message.includes('Parse Error'));
<ide> assert.strictEqual(e.code, 'HPE_INVALID_CONSTANT');
<ide> parseErrors++;
<ide> }).end();
<ide><path>test/parallel/test-http-extra-response.js
<ide> const server = net.createServer(function(socket) {
<ide> socket.on('data', function(chunk) {
<ide> postBody += chunk;
<ide>
<del> if (postBody.indexOf('\r\n') > -1) {
<add> if (postBody.includes('\r\n')) {
<ide> socket.write(fullResponse);
<ide> // omg, I wrote the response twice, what a terrible HTTP server I am.
<ide> socket.end(fullResponse);
<ide><path>test/parallel/test-http-get-pipeline-problem.js
<ide> function checkFiles() {
<ide>
<ide> for (let i = 0; i < total; i++) {
<ide> const fn = i + '.jpg';
<del> assert.ok(files.indexOf(fn) >= 0, "couldn't find '" + fn + "'");
<add> assert.ok(files.includes(fn), "couldn't find '" + fn + "'");
<ide> const stat = fs.statSync(common.tmpDir + '/' + fn);
<ide> assert.strictEqual(image.length, stat.size,
<ide> "size doesn't match on '" + fn +
<ide><path>test/parallel/test-https-strict.js
<ide> function makeReq(path, port, error, host, ca) {
<ide> options.agent = agent0;
<ide> } else {
<ide> if (!Array.isArray(ca)) ca = [ca];
<del> if (-1 !== ca.indexOf(ca1) && -1 !== ca.indexOf(ca2)) {
<add> if (ca.includes(ca1) && ca.includes(ca2)) {
<ide> options.agent = agent3;
<del> } else if (-1 !== ca.indexOf(ca1)) {
<add> } else if (ca.includes(ca1)) {
<ide> options.agent = agent1;
<del> } else if (-1 !== ca.indexOf(ca2)) {
<add> } else if (ca.includes(ca2)) {
<ide> options.agent = agent2;
<ide> } else {
<ide> options.agent = agent0;
<ide><path>test/parallel/test-intl.js
<ide> if (enablei18n === undefined) {
<ide> // Else, returns false
<ide> function haveLocale(loc) {
<ide> const locs = process.config.variables.icu_locales.split(',');
<del> return locs.indexOf(loc) !== -1;
<add> return locs.includes(loc);
<ide> }
<ide>
<ide> // Always run these. They should always pass, even if the locale
<ide><path>test/parallel/test-listen-fd-detached-inherit.js
<ide> function test() {
<ide> let json = '';
<ide> parent.stdout.on('data', function(c) {
<ide> json += c.toString();
<del> if (json.indexOf('\n') !== -1) next();
<add> if (json.includes('\n')) next();
<ide> });
<ide> function next() {
<ide> console.error('output from parent = %s', json);
<ide><path>test/parallel/test-listen-fd-detached.js
<ide> function test() {
<ide> let json = '';
<ide> parent.stdout.on('data', function(c) {
<ide> json += c.toString();
<del> if (json.indexOf('\n') !== -1) next();
<add> if (json.includes('\n')) next();
<ide> });
<ide> function next() {
<ide> console.error('output from parent = %s', json);
<ide><path>test/parallel/test-module-globalpaths-nodepath.js
<ide> if (common.isWindows) {
<ide>
<ide> mod._initPaths();
<ide>
<del>assert.ok(mod.globalPaths.indexOf(partA) !== -1);
<del>assert.ok(mod.globalPaths.indexOf(partB) !== -1);
<del>assert.ok(mod.globalPaths.indexOf(partC) === -1);
<add>assert.ok(mod.globalPaths.includes(partA));
<add>assert.ok(mod.globalPaths.includes(partB));
<add>assert.ok(!mod.globalPaths.includes(partC));
<ide>
<ide> assert.ok(Array.isArray(mod.globalPaths));
<ide><path>test/parallel/test-net-eaddrinuse.js
<ide> const server2 = net.createServer(function(socket) {
<ide> });
<ide> server1.listen(0, function() {
<ide> server2.on('error', function(error) {
<del> assert.strictEqual(true, error.message.indexOf('EADDRINUSE') >= 0);
<add> assert.strictEqual(true, error.message.includes('EADDRINUSE'));
<ide> server1.close();
<ide> });
<ide> server2.listen(this.address().port);
<ide><path>test/parallel/test-process-getactivehandles.js
<ide> function checkAll() {
<ide> const handles = process._getActiveHandles();
<ide>
<ide> clients.forEach(function(item) {
<del> assert.ok(handles.indexOf(item) > -1);
<add> assert.ok(handles.includes(item));
<ide> item.destroy();
<ide> });
<ide>
<ide> connections.forEach(function(item) {
<del> assert.ok(handles.indexOf(item) > -1);
<add> assert.ok(handles.includes(item));
<ide> item.end();
<ide> });
<ide>
<del> assert.ok(handles.indexOf(server) > -1);
<add> assert.ok(handles.includes(server));
<ide> server.close();
<ide> }
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> client_unix.expect :
<ide> JSON.stringify(client_unix.expect)));
<ide>
<del> if (read_buffer.indexOf(prompt_unix) !== -1) {
<add> if (read_buffer.includes(prompt_unix)) {
<ide> // if it's an exact match, then don't do the regexp
<ide> if (read_buffer !== client_unix.expect) {
<ide> let expect = client_unix.expect;
<ide> function error_test() {
<ide> tcp_test();
<ide> }
<ide>
<del> } else if (read_buffer.indexOf(prompt_multiline) !== -1) {
<add> } else if (read_buffer.includes(prompt_multiline)) {
<ide> // Check that you meant to send a multiline test
<ide> assert.strictEqual(prompt_multiline, client_unix.expect);
<ide> read_buffer = '';
<ide> function tcp_test() {
<ide> read_buffer += data.toString('ascii', 0, data.length);
<ide> console.error('TCP data: ' + JSON.stringify(read_buffer) +
<ide> ', expecting ' + JSON.stringify(client_tcp.expect));
<del> if (read_buffer.indexOf(prompt_tcp) !== -1) {
<add> if (read_buffer.includes(prompt_tcp)) {
<ide> assert.strictEqual(client_tcp.expect, read_buffer);
<ide> console.error('match');
<ide> read_buffer = '';
<ide> function unix_test() {
<ide> read_buffer += data.toString('ascii', 0, data.length);
<ide> console.error('Unix data: ' + JSON.stringify(read_buffer) +
<ide> ', expecting ' + JSON.stringify(client_unix.expect));
<del> if (read_buffer.indexOf(prompt_unix) !== -1) {
<add> if (read_buffer.includes(prompt_unix)) {
<ide> assert.strictEqual(client_unix.expect, read_buffer);
<ide> console.error('match');
<ide> read_buffer = '';
<ide><path>test/parallel/test-stream-big-packet.js
<ide> util.inherits(TestStream, stream.Transform);
<ide> TestStream.prototype._transform = function(chunk, encoding, done) {
<ide> if (!passed) {
<ide> // Char 'a' only exists in the last write
<del> passed = chunk.toString().indexOf('a') >= 0;
<add> passed = chunk.toString().includes('a');
<ide> }
<ide> done();
<ide> }; | 23 |
Javascript | Javascript | add a test for a bug fixed on beta | 38c7307cc70fedb9c8554b140f7c187548f140a2 | <ide><path>packages/ember-handlebars/tests/helpers/bound_helper_test.js
<ide> QUnit.module("Handlebars bound helpers", {
<ide> }
<ide> });
<ide>
<add>test("primitives should work correctly", function() {
<add> view = EmberView.create({
<add> prims: Ember.A(["string", 12]),
<add>
<add> template: compile('{{#each view.prims}}{{#if this}}inside-if{{/if}}{{#with this}}inside-with{{/with}}{{/each}}')
<add> });
<add>
<add> appendView(view);
<add>
<add> equal(view.$().text(), 'inside-ifinside-withinside-ifinside-with');
<add>});
<add>
<ide> test("should update bound helpers when properties change", function() {
<ide> EmberHandlebars.helper('capitalize', function(value) {
<ide> return value.toUpperCase(); | 1 |
Ruby | Ruby | remove the #sum method from collectionassociation | fd1c45761e023cecdc9ad472df64f8c265e25aaf | <ide><path>activerecord/lib/active_record/associations/collection_association.rb
<ide> def destroy_all
<ide> end
<ide> end
<ide>
<del> # Calculate sum using SQL, not Enumerable.
<del> def sum(*args)
<del> if block_given?
<del> scope.sum(*args) { |*block_args| yield(*block_args) }
<del> else
<del> scope.sum(*args)
<del> end
<del> end
<del>
<ide> # Count all records using SQL. If the +:counter_sql+ or +:finder_sql+ option is set for the
<ide> # association, it will be used for the query. Otherwise, construct options and pass them with
<ide> # scope to the target class's +count+. | 1 |
Ruby | Ruby | remove dup from post body for forcing encoding | 64b17ba6e99c7a51a25eec24d1901ff5a6343843 | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def raw_post
<ide> # variable is already set, wrap it in a StringIO.
<ide> def body
<ide> if raw_post = get_header("RAW_POST_DATA")
<del> raw_post = raw_post.dup.force_encoding(Encoding::BINARY)
<add> raw_post = (+raw_post).force_encoding(Encoding::BINARY)
<ide> StringIO.new(raw_post)
<ide> else
<ide> body_stream | 1 |
Go | Go | add test for inspect with a sha256 prefix | 61d6240069cda31559523b98cecb6b340a9d45fd | <ide><path>integration-cli/docker_cli_inspect_test.go
<ide> func (s *DockerSuite) TestInspectJSONFields(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(out, checker.Equals, "[]\n")
<ide> }
<add>
<add>func (s *DockerSuite) TestInspectByPrefix(c *check.C) {
<add> id, err := inspectField("busybox", "Id")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(id, checker.HasPrefix, "sha256:")
<add>
<add> id2, err := inspectField(id[:10], "Id")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(id, checker.Equals, id2)
<add>
<add> id3, err := inspectField(strings.TrimPrefix(id, "sha256:")[:10], "Id")
<add> c.Assert(err, checker.IsNil)
<add> c.Assert(id, checker.Equals, id3)
<add>} | 1 |
Javascript | Javascript | convert template and its subclasses to es2015 | c6af4ab3fa30306eed211a603f3b87bd9d3732e2 | <ide><path>lib/ChunkTemplate.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var ConcatSource = require("webpack-sources").ConcatSource;
<del>var Template = require("./Template");
<add>"use strict";
<ide>
<del>function ChunkTemplate(outputOptions) {
<del> Template.call(this, outputOptions);
<del>}
<add>const ConcatSource = require("webpack-sources").ConcatSource;
<add>const Template = require("./Template");
<ide>
<del>module.exports = ChunkTemplate;
<del>
<del>ChunkTemplate.prototype = Object.create(Template.prototype);
<del>ChunkTemplate.prototype.constructor = ChunkTemplate;
<add>module.exports = class ChunkTemplate extends Template {
<add> constructor(outputOptions) {
<add> super(outputOptions);
<add> }
<ide>
<del>ChunkTemplate.prototype.render = function(chunk, moduleTemplate, dependencyTemplates) {
<del> var modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
<del> var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates);
<del> var source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
<del> if(chunk.hasEntryModule()) {
<del> source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
<add> render(chunk, moduleTemplate, dependencyTemplates) {
<add> let modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
<add> let core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates);
<add> let source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
<add> if(chunk.hasEntryModule()) {
<add> source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
<add> }
<add> chunk.rendered = true;
<add> return new ConcatSource(source, ";");
<ide> }
<del> chunk.rendered = true;
<del> return new ConcatSource(source, ";");
<del>};
<ide>
<del>ChunkTemplate.prototype.updateHash = function(hash) {
<del> hash.update("ChunkTemplate");
<del> hash.update("2");
<del> this.applyPlugins("hash", hash);
<del>};
<add> updateHash(hash) {
<add> hash.update("ChunkTemplate");
<add> hash.update("2");
<add> this.applyPlugins("hash", hash);
<add> }
<ide>
<del>ChunkTemplate.prototype.updateHashForChunk = function(hash, chunk) {
<del> this.updateHash(hash);
<del> this.applyPlugins("hash-for-chunk", hash, chunk);
<add> updateHashForChunk(hash, chunk) {
<add> this.updateHash(hash);
<add> this.applyPlugins("hash-for-chunk", hash, chunk);
<add> }
<ide> };
<ide><path>lib/HotUpdateChunkTemplate.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var Template = require("./Template");
<add>"use strict";
<ide>
<del>function HotUpdateChunkTemplate(outputOptions) {
<del> Template.call(this, outputOptions);
<del>}
<add>const Template = require("./Template");
<ide>
<del>module.exports = HotUpdateChunkTemplate;
<add>module.exports = class HotUpdateChunkTemplate extends Template {
<add> constructor(outputOptions) {
<add> super(outputOptions);
<add> }
<ide>
<del>HotUpdateChunkTemplate.prototype = Object.create(Template.prototype);
<del>HotUpdateChunkTemplate.prototype.constructor = HotUpdateChunkTemplate;
<add> render(id, modules, removedModules, hash, moduleTemplate, dependencyTemplates) {
<add> let modulesSource = this.renderChunkModules({
<add> id: id,
<add> modules: modules,
<add> removedModules: removedModules
<add> }, moduleTemplate, dependencyTemplates);
<add> let core = this.applyPluginsWaterfall("modules", modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates);
<add> let source = this.applyPluginsWaterfall("render", core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates);
<add> return source;
<add> }
<ide>
<del>HotUpdateChunkTemplate.prototype.render = function(id, modules, removedModules, hash, moduleTemplate, dependencyTemplates) {
<del> var modulesSource = this.renderChunkModules({
<del> id: id,
<del> modules: modules,
<del> removedModules: removedModules
<del> }, moduleTemplate, dependencyTemplates);
<del> var core = this.applyPluginsWaterfall("modules", modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates);
<del> var source = this.applyPluginsWaterfall("render", core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates);
<del> return source;
<del>};
<del>
<del>HotUpdateChunkTemplate.prototype.updateHash = function(hash) {
<del> hash.update("HotUpdateChunkTemplate");
<del> hash.update("1");
<del> this.applyPlugins("hash", hash);
<add> updateHash(hash) {
<add> hash.update("HotUpdateChunkTemplate");
<add> hash.update("1");
<add> this.applyPlugins("hash", hash);
<add> }
<ide> };
<ide><path>lib/MainTemplate.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var ConcatSource = require("webpack-sources").ConcatSource;
<del>var OriginalSource = require("webpack-sources").OriginalSource;
<del>var PrefixSource = require("webpack-sources").PrefixSource;
<del>var Template = require("./Template");
<add>"use strict";
<add>
<add>const ConcatSource = require("webpack-sources").ConcatSource;
<add>const OriginalSource = require("webpack-sources").OriginalSource;
<add>const PrefixSource = require("webpack-sources").PrefixSource;
<add>const Template = require("./Template");
<ide>
<ide> // require function shortcuts:
<ide> // __webpack_require__.s = the module id of the entry point
<ide> var Template = require("./Template");
<ide> // __webpack_require__.oe = the uncatched error handler for the webpack runtime
<ide> // __webpack_require__.nc = the script nonce
<ide>
<del>function MainTemplate(outputOptions) {
<del> Template.call(this, outputOptions);
<del> this.plugin("startup", function(source, chunk, hash) {
<del> var buf = [];
<del> if(chunk.entryModule) {
<del> buf.push("// Load entry module and return exports");
<del> buf.push("return " + this.renderRequireFunctionForModule(hash, chunk, JSON.stringify(chunk.entryModule.id)) +
<del> "(" + this.requireFn + ".s = " + JSON.stringify(chunk.entryModule.id) + ");");
<del> }
<del> return this.asString(buf);
<del> });
<del> this.plugin("render", function(bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) {
<del> var source = new ConcatSource();
<del> source.add("/******/ (function(modules) { // webpackBootstrap\n");
<del> source.add(new PrefixSource("/******/", bootstrapSource));
<del> source.add("/******/ })\n");
<del> source.add("/************************************************************************/\n");
<del> source.add("/******/ (");
<del> var modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ ");
<del> source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates));
<del> source.add(")");
<del> return source;
<del> });
<del> this.plugin("local-vars", function(source, chunk, hash) {
<del> return this.asString([
<del> source,
<del> "// The module cache",
<del> "var installedModules = {};"
<del> ]);
<del> });
<del> this.plugin("require", function(source, chunk, hash) {
<del> return this.asString([
<del> source,
<del> "// Check if module is in cache",
<del> "if(installedModules[moduleId])",
<del> this.indent("return installedModules[moduleId].exports;"),
<del> "",
<del> "// Create a new module (and put it into the cache)",
<del> "var module = installedModules[moduleId] = {",
<del> this.indent(this.applyPluginsWaterfall("module-obj", "", chunk, hash, "moduleId")),
<del> "};",
<del> "",
<del> this.asString(outputOptions.strictModuleExceptionHandling ? [
<del> "// Execute the module function",
<del> "var threw = true;",
<del> "try {",
<del> this.indent([
<add>module.exports = class MainTemplate extends Template {
<add> constructor(outputOptions) {
<add> super(outputOptions);
<add> this.plugin("startup", (source, chunk, hash) => {
<add> let buf = [];
<add> if(chunk.entryModule) {
<add> buf.push("// Load entry module and return exports");
<add> buf.push("return " + this.renderRequireFunctionForModule(hash, chunk, JSON.stringify(chunk.entryModule.id)) +
<add> "(" + this.requireFn + ".s = " + JSON.stringify(chunk.entryModule.id) + ");");
<add> }
<add> return this.asString(buf);
<add> });
<add> this.plugin("render", (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => {
<add> let source = new ConcatSource();
<add> source.add("/******/ (function(modules) { // webpackBootstrap\n");
<add> source.add(new PrefixSource("/******/", bootstrapSource));
<add> source.add("/******/ })\n");
<add> source.add("/************************************************************************/\n");
<add> source.add("/******/ (");
<add> let modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ ");
<add> source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates));
<add> source.add(")");
<add> return source;
<add> });
<add> this.plugin("local-vars", (source, chunk, hash) => {
<add> return this.asString([
<add> source,
<add> "// The module cache",
<add> "var installedModules = {};"
<add> ]);
<add> });
<add> this.plugin("require", (source, chunk, hash) => {
<add> return this.asString([
<add> source,
<add> "// Check if module is in cache",
<add> "if(installedModules[moduleId])",
<add> this.indent("return installedModules[moduleId].exports;"),
<add> "",
<add> "// Create a new module (and put it into the cache)",
<add> "var module = installedModules[moduleId] = {",
<add> this.indent(this.applyPluginsWaterfall("module-obj", "", chunk, hash, "moduleId")),
<add> "};",
<add> "",
<add> this.asString(outputOptions.strictModuleExceptionHandling ? [
<add> "// Execute the module function",
<add> "var threw = true;",
<add> "try {",
<add> this.indent([
<add> "modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");",
<add> "threw = false;"
<add> ]),
<add> "} finally {",
<add> this.indent([
<add> "if(threw) delete installedModules[moduleId];"
<add> ]),
<add> "}"
<add> ] : [
<add> "// Execute the module function",
<ide> "modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");",
<del> "threw = false;"
<ide> ]),
<del> "} finally {",
<add> "",
<add> "// Flag the module as loaded",
<add> "module.l = true;",
<add> "",
<add> "// Return the exports of the module",
<add> "return module.exports;"
<add> ]);
<add> });
<add> this.plugin("module-obj", (source, chunk, hash, varModuleId) => {
<add> return this.asString([
<add> "i: moduleId,",
<add> "l: false,",
<add> "exports: {}"
<add> ]);
<add> });
<add> this.plugin("require-extensions", (source, chunk, hash) => {
<add> let buf = [];
<add> if(chunk.chunks.length > 0) {
<add> buf.push("// This file contains only the entry chunk.");
<add> buf.push("// The chunk loading function for additional chunks");
<add> buf.push(this.requireFn + ".e = function requireEnsure(chunkId) {");
<add> buf.push(this.indent(this.applyPluginsWaterfall("require-ensure", "throw new Error('Not chunk loading available');", chunk, hash, "chunkId")));
<add> buf.push("};");
<add> }
<add> buf.push("");
<add> buf.push("// expose the modules object (__webpack_modules__)");
<add> buf.push(this.requireFn + ".m = modules;");
<add>
<add> buf.push("");
<add> buf.push("// expose the module cache");
<add> buf.push(this.requireFn + ".c = installedModules;");
<add>
<add> buf.push("");
<add> buf.push("// identity function for calling harmony imports with the correct context");
<add> buf.push(this.requireFn + ".i = function(value) { return value; };");
<add>
<add> buf.push("");
<add> buf.push("// define getter function for harmony exports");
<add> buf.push(this.requireFn + ".d = function(exports, name, getter) {");
<add> buf.push(this.indent([
<add> "if(!" + this.requireFn + ".o(exports, name)) {",
<ide> this.indent([
<del> "if(threw) delete installedModules[moduleId];"
<add> "Object.defineProperty(exports, name, {",
<add> this.indent([
<add> "configurable: false,",
<add> "enumerable: true,",
<add> "get: getter"
<add> ]),
<add> "});"
<ide> ]),
<ide> "}"
<del> ] : [
<del> "// Execute the module function",
<del> "modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");",
<del> ]),
<del> "",
<del> "// Flag the module as loaded",
<del> "module.l = true;",
<del> "",
<del> "// Return the exports of the module",
<del> "return module.exports;"
<del> ]);
<del> });
<del> this.plugin("module-obj", function(source, chunk, hash, varModuleId) {
<del> return this.asString([
<del> "i: moduleId,",
<del> "l: false,",
<del> "exports: {}"
<del> ]);
<del> });
<del> this.plugin("require-extensions", function(source, chunk, hash) {
<del> var buf = [];
<del> if(chunk.chunks.length > 0) {
<del> buf.push("// This file contains only the entry chunk.");
<del> buf.push("// The chunk loading function for additional chunks");
<del> buf.push(this.requireFn + ".e = function requireEnsure(chunkId) {");
<del> buf.push(this.indent(this.applyPluginsWaterfall("require-ensure", "throw new Error('Not chunk loading available');", chunk, hash, "chunkId")));
<add> ]));
<ide> buf.push("};");
<del> }
<del> buf.push("");
<del> buf.push("// expose the modules object (__webpack_modules__)");
<del> buf.push(this.requireFn + ".m = modules;");
<ide>
<del> buf.push("");
<del> buf.push("// expose the module cache");
<del> buf.push(this.requireFn + ".c = installedModules;");
<del>
<del> buf.push("");
<del> buf.push("// identity function for calling harmony imports with the correct context");
<del> buf.push(this.requireFn + ".i = function(value) { return value; };");
<del>
<del> buf.push("");
<del> buf.push("// define getter function for harmony exports");
<del> buf.push(this.requireFn + ".d = function(exports, name, getter) {");
<del> buf.push(this.indent([
<del> "if(!" + this.requireFn + ".o(exports, name)) {",
<del> this.indent([
<del> "Object.defineProperty(exports, name, {",
<add> buf.push("");
<add> buf.push("// getDefaultExport function for compatibility with non-harmony modules");
<add> buf.push(this.requireFn + ".n = function(module) {");
<add> buf.push(this.indent([
<add> "var getter = module && module.__esModule ?",
<ide> this.indent([
<del> "configurable: false,",
<del> "enumerable: true,",
<del> "get: getter"
<add> "function getDefault() { return module['default']; } :",
<add> "function getModuleExports() { return module; };"
<ide> ]),
<del> "});"
<del> ]),
<del> "}"
<del> ]));
<del> buf.push("};");
<add> this.requireFn + ".d(getter, 'a', getter);",
<add> "return getter;"
<add> ]));
<add> buf.push("};");
<ide>
<del> buf.push("");
<del> buf.push("// getDefaultExport function for compatibility with non-harmony modules");
<del> buf.push(this.requireFn + ".n = function(module) {");
<del> buf.push(this.indent([
<del> "var getter = module && module.__esModule ?",
<del> this.indent([
<del> "function getDefault() { return module['default']; } :",
<del> "function getModuleExports() { return module; };"
<del> ]),
<del> this.requireFn + ".d(getter, 'a', getter);",
<del> "return getter;"
<del> ]));
<del> buf.push("};");
<add> buf.push("");
<add> buf.push("// Object.prototype.hasOwnProperty.call");
<add> buf.push(this.requireFn + ".o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };");
<add>
<add> let publicPath = this.getPublicPath({
<add> hash: hash
<add> });
<add> buf.push("");
<add> buf.push("// __webpack_public_path__");
<add> buf.push(this.requireFn + ".p = " + JSON.stringify(publicPath) + ";");
<add> return this.asString(buf);
<add> });
<ide>
<del> buf.push("");
<del> buf.push("// Object.prototype.hasOwnProperty.call");
<del> buf.push(this.requireFn + ".o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };");
<add> this.requireFn = "__webpack_require__";
<add> }
<ide>
<del> var publicPath = this.getPublicPath({
<del> hash: hash
<del> });
<add> render(hash, chunk, moduleTemplate, dependencyTemplates) {
<add> let buf = [];
<add> buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates));
<add> buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash));
<add> buf.push("");
<add> buf.push("// The require function");
<add> buf.push("function " + this.requireFn + "(moduleId) {");
<add> buf.push(this.indent(this.applyPluginsWaterfall("require", "", chunk, hash)));
<add> buf.push("}");
<add> buf.push("");
<add> buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash)));
<ide> buf.push("");
<del> buf.push("// __webpack_public_path__");
<del> buf.push(this.requireFn + ".p = " + JSON.stringify(publicPath) + ";");
<del> return this.asString(buf);
<del> });
<del>}
<del>module.exports = MainTemplate;
<del>
<del>MainTemplate.prototype = Object.create(Template.prototype);
<del>MainTemplate.prototype.constructor = MainTemplate;
<del>MainTemplate.prototype.requireFn = "__webpack_require__";
<del>MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependencyTemplates) {
<del> var buf = [];
<del> buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates));
<del> buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash));
<del> buf.push("");
<del> buf.push("// The require function");
<del> buf.push("function " + this.requireFn + "(moduleId) {");
<del> buf.push(this.indent(this.applyPluginsWaterfall("require", "", chunk, hash)));
<del> buf.push("}");
<del> buf.push("");
<del> buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash)));
<del> buf.push("");
<del> buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash)));
<del> var source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates);
<del> if(chunk.hasEntryModule()) {
<del> source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash);
<add> buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash)));
<add> let source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates);
<add> if(chunk.hasEntryModule()) {
<add> source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash);
<add> }
<add> if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something");
<add> chunk.rendered = true;
<add> return new ConcatSource(source, ";");
<ide> }
<del> if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something");
<del> chunk.rendered = true;
<del> return new ConcatSource(source, ";");
<del>};
<ide>
<del>MainTemplate.prototype.renderRequireFunctionForModule = function(hash, chunk, varModuleId) {
<del> return this.applyPluginsWaterfall("module-require", this.requireFn, chunk, hash, varModuleId);
<del>};
<add> renderRequireFunctionForModule(hash, chunk, varModuleId) {
<add> return this.applyPluginsWaterfall("module-require", this.requireFn, chunk, hash, varModuleId);
<add> }
<ide>
<del>MainTemplate.prototype.renderAddModule = function(hash, chunk, varModuleId, varModule) {
<del> return this.applyPluginsWaterfall("add-module", "modules[" + varModuleId + "] = " + varModule + ";", chunk, hash, varModuleId, varModule);
<del>};
<add> renderAddModule(hash, chunk, varModuleId, varModule) {
<add> return this.applyPluginsWaterfall("add-module", "modules[" + varModuleId + "] = " + varModule + ";", chunk, hash, varModuleId, varModule);
<add> }
<ide>
<del>MainTemplate.prototype.renderCurrentHashCode = function(hash, length) {
<del> length = length || Infinity;
<del> return this.applyPluginsWaterfall("current-hash", JSON.stringify(hash.substr(0, length)), length);
<del>};
<add> renderCurrentHashCode(hash, length) {
<add> length = length || Infinity;
<add> return this.applyPluginsWaterfall("current-hash", JSON.stringify(hash.substr(0, length)), length);
<add> }
<ide>
<del>MainTemplate.prototype.entryPointInChildren = function(chunk) {
<del> function checkChildren(chunk, alreadyCheckedChunks) {
<del> return chunk.chunks.some(function(child) {
<del> if(alreadyCheckedChunks.indexOf(child) >= 0) return;
<del> alreadyCheckedChunks.push(child);
<del> return child.hasEntryModule() || checkChildren(child, alreadyCheckedChunks);
<del> });
<add> entryPointInChildren(chunk) {
<add> let checkChildren = (chunk, alreadyCheckedChunks) => {
<add> return chunk.chunks.some((child) => {
<add> if(alreadyCheckedChunks.indexOf(child) >= 0) return;
<add> alreadyCheckedChunks.push(child);
<add> return child.hasEntryModule() || checkChildren(child, alreadyCheckedChunks);
<add> });
<add> };
<add> return checkChildren(chunk, []);
<ide> }
<del> return checkChildren(chunk, []);
<del>};
<ide>
<del>MainTemplate.prototype.getPublicPath = function(options) {
<del> return this.applyPluginsWaterfall("asset-path", this.outputOptions.publicPath || "", options);
<del>};
<add> getPublicPath(options) {
<add> return this.applyPluginsWaterfall("asset-path", this.outputOptions.publicPath || "", options);
<add> }
<ide>
<del>MainTemplate.prototype.updateHash = function(hash) {
<del> hash.update("maintemplate");
<del> hash.update("3");
<del> hash.update(this.outputOptions.publicPath + "");
<del> this.applyPlugins("hash", hash);
<del>};
<add> updateHash(hash) {
<add> hash.update("maintemplate");
<add> hash.update("3");
<add> hash.update(this.outputOptions.publicPath + "");
<add> this.applyPlugins("hash", hash);
<add> }
<ide>
<del>MainTemplate.prototype.updateHashForChunk = function(hash, chunk) {
<del> this.updateHash(hash);
<del> this.applyPlugins("hash-for-chunk", hash, chunk);
<del>};
<add> updateHashForChunk(hash, chunk) {
<add> this.updateHash(hash);
<add> this.applyPlugins("hash-for-chunk", hash, chunk);
<add> }
<ide>
<del>MainTemplate.prototype.useChunkHash = function(chunk) {
<del> var paths = this.applyPluginsWaterfall("global-hash-paths", []);
<del> return !this.applyPluginsBailResult("global-hash", chunk, paths);
<add> useChunkHash(chunk) {
<add> let paths = this.applyPluginsWaterfall("global-hash-paths", []);
<add> return !this.applyPluginsBailResult("global-hash", chunk, paths);
<add> }
<ide> };
<ide><path>lib/Template.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var Tapable = require("tapable");
<del>var ConcatSource = require("webpack-sources").ConcatSource;
<add>"use strict";
<ide>
<del>function Template(outputOptions) {
<del> Tapable.call(this);
<del> this.outputOptions = outputOptions || {};
<del>}
<del>module.exports = Template;
<add>const Tapable = require("tapable");
<add>const ConcatSource = require("webpack-sources").ConcatSource;
<ide>
<del>Template.getFunctionContent = function(fn) {
<del> return fn.toString().replace(/^function\s?\(\)\s?\{\n?|\n?\}$/g, "").replace(/^\t/mg, "");
<del>};
<add>const START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
<add>const START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
<add>const DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
<ide>
<del>Template.toIdentifier = function(str) {
<del> if(typeof str !== "string") return "";
<del> return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_");
<del>};
<add>module.exports = class Template extends Tapable {
<add> constructor(outputOptions) {
<add> super();
<add> this.outputOptions = outputOptions || {};
<add> }
<ide>
<del>var START_LOWERCASE_ALPHABET_CODE = "a".charCodeAt(0);
<del>var START_UPPERCASE_ALPHABET_CODE = "A".charCodeAt(0);
<del>var DELTA_A_TO_Z = "z".charCodeAt(0) - START_LOWERCASE_ALPHABET_CODE + 1;
<del>// map number to a single character a-z, A-Z or <_ + number> if number is too big
<del>Template.numberToIdentifer = function numberToIdentifer(n) {
<del> // lower case
<del> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
<add> static getFunctionContent(fn) {
<add> return fn.toString().replace(/^function\s?\(\)\s?\{\n?|\n?\}$/g, "").replace(/^\t/mg, "");
<add> }
<ide>
<del> // upper case
<del> n -= DELTA_A_TO_Z;
<del> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
<add> static toIdentifier(str) {
<add> if(typeof str !== "string") return "";
<add> return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_");
<add> }
<ide>
<del> // fall back to _ + number
<del> n -= DELTA_A_TO_Z;
<del> return "_" + n;
<del>};
<add> // map number to a single character a-z, A-Z or <_ + number> if number is too big
<add> static numberToIdentifer(n) {
<add> // lower case
<add> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n);
<ide>
<del>Template.prototype = Object.create(Tapable.prototype);
<del>Template.prototype.constructor = Template;
<add> // upper case
<add> n -= DELTA_A_TO_Z;
<add> if(n < DELTA_A_TO_Z) return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n);
<ide>
<del>Template.prototype.indent = function indent(str) {
<del> if(Array.isArray(str)) {
<del> return str.map(indent).join("\n");
<del> } else {
<del> str = str.trimRight();
<del> if(!str) return "";
<del> var ind = (str[0] === "\n" ? "" : "\t");
<del> return ind + str.replace(/\n([^\n])/g, "\n\t$1");
<add> // fall back to _ + number
<add> n -= DELTA_A_TO_Z;
<add> return "_" + n;
<ide> }
<del>};
<ide>
<del>Template.prototype.prefix = function(str, prefix) {
<del> if(Array.isArray(str)) {
<del> str = str.join("\n");
<add> indent(str) {
<add> if(Array.isArray(str)) {
<add> return str.map(this.indent.bind(this)).join("\n");
<add> } else {
<add> str = str.trimRight();
<add> if(!str) return "";
<add> var ind = (str[0] === "\n" ? "" : "\t");
<add> return ind + str.replace(/\n([^\n])/g, "\n\t$1");
<add> }
<ide> }
<del> str = str.trim();
<del> if(!str) return "";
<del> var ind = (str[0] === "\n" ? "" : prefix);
<del> return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
<del>};
<ide>
<del>Template.prototype.asString = function(str) {
<del> if(Array.isArray(str)) {
<del> return str.join("\n");
<add> prefix(str, prefix) {
<add> if(Array.isArray(str)) {
<add> str = str.join("\n");
<add> }
<add> str = str.trim();
<add> if(!str) return "";
<add> let ind = (str[0] === "\n" ? "" : prefix);
<add> return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
<ide> }
<del> return str;
<del>};
<ide>
<del>function moduleIdIsNumber(module) {
<del> return typeof module.id === "number";
<del>}
<del>
<del>Template.prototype.getModulesArrayBounds = function(modules) {
<del> if(!modules.every(moduleIdIsNumber))
<del> return false;
<del> var maxId = -Infinity;
<del> var minId = Infinity;
<del> modules.forEach(function(module) {
<del> if(maxId < module.id) maxId = module.id;
<del> if(minId > module.id) minId = module.id;
<del> });
<del> if(minId < 16 + ("" + minId).length) {
<del> // add minId x ',' instead of 'Array(minId).concat(...)'
<del> minId = 0;
<add> asString(str) {
<add> if(Array.isArray(str)) {
<add> return str.join("\n");
<add> }
<add> return str;
<ide> }
<del> var objectOverhead = modules.map(function(module) {
<del> var idLength = (module.id + "").length;
<del> return idLength + 2;
<del> }).reduce(function(a, b) {
<del> return a + b;
<del> }, -1);
<del> var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
<del> return arrayOverhead < objectOverhead ? [minId, maxId] : false;
<del>};
<ide>
<del>Template.prototype.renderChunkModules = function(chunk, moduleTemplate, dependencyTemplates, prefix) {
<del> if(!prefix) prefix = "";
<del> var source = new ConcatSource();
<del> if(chunk.modules.length === 0) {
<del> source.add("[]");
<del> return source;
<del> }
<del> var removedModules = chunk.removedModules;
<del> var allModules = chunk.modules.map(function(module) {
<del> return {
<del> id: module.id,
<del> source: moduleTemplate.render(module, dependencyTemplates, chunk)
<del> };
<del> });
<del> if(removedModules && removedModules.length > 0) {
<del> removedModules.forEach(function(id) {
<del> allModules.push({
<del> id: id,
<del> source: "false"
<del> });
<add> getModulesArrayBounds(modules) {
<add> if(!modules.every(moduleIdIsNumber))
<add> return false;
<add> var maxId = -Infinity;
<add> var minId = Infinity;
<add> modules.forEach(function(module) {
<add> if(maxId < module.id) maxId = module.id;
<add> if(minId > module.id) minId = module.id;
<ide> });
<add> if(minId < 16 + ("" + minId).length) {
<add> // add minId x ',' instead of 'Array(minId).concat(...)'
<add> minId = 0;
<add> }
<add> var objectOverhead = modules.map(function(module) {
<add> var idLength = (module.id + "").length;
<add> return idLength + 2;
<add> }).reduce(function(a, b) {
<add> return a + b;
<add> }, -1);
<add> var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
<add> return arrayOverhead < objectOverhead ? [minId, maxId] : false;
<ide> }
<del> var bounds = this.getModulesArrayBounds(chunk.modules);
<ide>
<del> if(bounds) {
<del> // Render a spare array
<del> var minId = bounds[0];
<del> var maxId = bounds[1];
<del> if(minId !== 0) source.add("Array(" + minId + ").concat(");
<del> source.add("[\n");
<del> var modules = {};
<del> allModules.forEach(function(module) {
<del> modules[module.id] = module;
<add> renderChunkModules(chunk, moduleTemplate, dependencyTemplates, prefix) {
<add> if(!prefix) prefix = "";
<add> var source = new ConcatSource();
<add> if(chunk.modules.length === 0) {
<add> source.add("[]");
<add> return source;
<add> }
<add> var removedModules = chunk.removedModules;
<add> var allModules = chunk.modules.map(function(module) {
<add> return {
<add> id: module.id,
<add> source: moduleTemplate.render(module, dependencyTemplates, chunk)
<add> };
<ide> });
<del> for(var idx = minId; idx <= maxId; idx++) {
<del> var module = modules[idx];
<del> if(idx !== minId) source.add(",\n");
<del> source.add("/* " + idx + " */");
<del> if(module) {
<del> source.add("\n");
<del> source.add(module.source);
<add> if(removedModules && removedModules.length > 0) {
<add> removedModules.forEach(function(id) {
<add> allModules.push({
<add> id: id,
<add> source: "false"
<add> });
<add> });
<add> }
<add> var bounds = this.getModulesArrayBounds(chunk.modules);
<add>
<add> if(bounds) {
<add> // Render a spare array
<add> var minId = bounds[0];
<add> var maxId = bounds[1];
<add> if(minId !== 0) source.add("Array(" + minId + ").concat(");
<add> source.add("[\n");
<add> var modules = {};
<add> allModules.forEach(function(module) {
<add> modules[module.id] = module;
<add> });
<add> for(var idx = minId; idx <= maxId; idx++) {
<add> var module = modules[idx];
<add> if(idx !== minId) source.add(",\n");
<add> source.add("/* " + idx + " */");
<add> if(module) {
<add> source.add("\n");
<add> source.add(module.source);
<add> }
<ide> }
<add> source.add("\n" + prefix + "]");
<add> if(minId !== 0) source.add(")");
<add> } else {
<add> // Render an object
<add> source.add("{\n");
<add> allModules.sort(function(a, b) {
<add> var aId = a.id + "";
<add> var bId = b.id + "";
<add> if(aId < bId) return -1;
<add> if(aId > bId) return 1;
<add> return 0;
<add> }).forEach(function(module, idx) {
<add> if(idx !== 0) source.add(",\n");
<add> source.add("\n/***/ " + JSON.stringify(module.id) + ":\n");
<add> source.add(module.source);
<add> });
<add> source.add("\n\n" + prefix + "}");
<ide> }
<del> source.add("\n" + prefix + "]");
<del> if(minId !== 0) source.add(")");
<del> } else {
<del> // Render an object
<del> source.add("{\n");
<del> allModules.sort(function(a, b) {
<del> var aId = a.id + "";
<del> var bId = b.id + "";
<del> if(aId < bId) return -1;
<del> if(aId > bId) return 1;
<del> return 0;
<del> }).forEach(function(module, idx) {
<del> if(idx !== 0) source.add(",\n");
<del> source.add("\n/***/ " + JSON.stringify(module.id) + ":\n");
<del> source.add(module.source);
<del> });
<del> source.add("\n\n" + prefix + "}");
<add> return source;
<ide> }
<del> return source;
<ide> };
<add>
<add>function moduleIdIsNumber(module) {
<add> return typeof module.id === "number";
<add>} | 4 |
Ruby | Ruby | add tests for hard coded compilers in system calls | 77468fdae36ee58580a643d8bc0fdd9f8b6e61c3 | <ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> problem "\"#{m.source}\" should be \"#{match[0]}\""
<ide> end
<ide>
<del> # # Avoid hard-coding compilers
<del> # find_every_method_call_by_name(body_node, :system).each do |m|
<del> # param = parameters(m).first
<del> # if match = regex_match_group(param, %r{(/usr/bin/)?(gcc|llvm-gcc|clang)\s?})
<del> # problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{match[3]}\""
<del> # elsif match = regex_match_group(param, %r{(/usr/bin/)?((g|llvm-g|clang)\+\+)\s?})
<del> # problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{match[3]}\""
<del> # end
<del> # end
<add> # Avoid hard-coding compilers
<add> find_every_method_call_by_name(body_node, :system).each do |m|
<add> param = parameters(m).first
<add> if match = regex_match_group(param, %r{(/usr/bin/)?(gcc|llvm-gcc|clang)\s?})
<add> problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{match[2]}\""
<add> elsif match = regex_match_group(param, %r{(/usr/bin/)?((g|llvm-g|clang)\+\+)\s?})
<add> problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{match[2]}\""
<add> end
<add> end
<ide> #
<ide> # find_instance_method_call(body_node, :ENV, :[]=) do |m|
<ide> # param = parameters(m)[1]
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> def test
<ide> expect_offense(expected, actual)
<ide> end
<ide> end
<add>
<add> it "with hardcoded compiler 1 " do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> def test
<add> system "/usr/bin/gcc", "foo"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: "Use \"\#{ENV.cc}\" instead of hard-coding \"gcc\"",
<add> severity: :convention,
<add> line: 5,
<add> column: 12,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<add>
<add> it "with hardcoded compiler 2 " do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> def test
<add> system "/usr/bin/g++", "-o", "foo", "foo.cc"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: "Use \"\#{ENV.cxx}\" instead of hard-coding \"g++\"",
<add> severity: :convention,
<add> line: 5,
<add> column: 12,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<ide> end
<ide> def expect_offense(expected, actual)
<ide> expect(actual.message).to eq(expected[:message]) | 2 |
Python | Python | implement missing methods of variablespec | 583f7cd4d664f760bbab4dcf283d725ced10fcce | <ide><path>keras/distribute/parameter_server_evaluation_test.py
<ide> def element_spec(self):
<ide>
<ide> @property
<ide> def _type_spec(self):
<del> weight_specs = []
<del> for w in self.weights:
<del> weight_specs.append(
<del> resource_variable_ops.VariableSpec(
<del> w.shape, w.dtype, w.name.split(":")[0], trainable=False))
<add> weight_specs = [
<add> resource_variable_ops.VariableSpec.from_value(w) for w in self.weights]
<ide> return MeanMetricSpec(self.get_config(), weight_specs)
<ide>
<ide> | 1 |
Text | Text | add info on conventional commit messages | 16d52cbcdfa412846437d53063c6c1ab9fc20ed1 | <ide><path>docs/CONTRIBUTING.md
<ide> $ git add path/to/filename.ext
<ide>
<ide> You can also run `git add .` to add all unstaged files. Take care, though, because you can accidentally add files you don't want added. Review your `git status` first.
<ide>
<del>### Commit Your Changes
<add>### Commit Your Changes
<ide>
<del>We have a [tool](https://commitizen.github.io/cz-cli/) that helps you make standard commit messages. Execute `npm run commit` and follow the steps.
<add>We have a [tool](https://commitizen.github.io/cz-cli/) that helps you make standard commit messages. Execute `npm run commit` and follow the steps. This will generate a conventional commit message.
<add>
<add>**Note**: Your pull request will fail the Travis CI build if your commits do not have conventional messages. [Click here](https://conventionalcommits.org/#why-use-conventional-commits) to read more about conventional commit messages.
<ide>
<ide> If you want to add/remove changes to previous commit, [add the files](#making-your-changes), and use `git commit --amend` or `git commit --amend --no-edit` (to keep the same commit message).
<ide> | 1 |
PHP | PHP | fix failing tests from 2.x merge | b0a9e0d96ce2a492b124a2708b5bf21ef2193954 | <ide><path>src/Network/Response.php
<ide> public function cookie($options = null) {
<ide> * ### Whitelist of URIs
<ide> * e.g `cors($request, array('http://www.cakephp.org', '*.google.com', 'https://myproject.github.io'));`
<ide> *
<del> * @param CakeRequest $request Request object
<add> * @param Cake\Network\Request $request Request object
<ide> * @param string|array $allowedDomains List of allowed domains, see method description for more details
<ide> * @param string|array $allowedMethods List of HTTP verbs allowed
<ide> * @param string|array $allowedHeaders List of HTTP headers allowed
<ide> * @return void
<ide> */
<del> public function cors(CakeRequest $request, $allowedDomains, $allowedMethods = array(), $allowedHeaders = array()) {
<add> public function cors(Request $request, $allowedDomains, $allowedMethods = array(), $allowedHeaders = array()) {
<ide> $origin = $request->header('Origin');
<ide> if (!$origin) {
<ide> return;
<ide><path>tests/TestCase/Network/ResponseTest.php
<ide> public function testCookieSettings() {
<ide> * Test CORS
<ide> *
<ide> * @dataProvider corsData
<del> * @param CakeRequest $request
<add> * @param Request $request
<ide> * @param string $origin
<ide> * @param string|array $domains
<ide> * @param string|array $methods
<ide> public function testCookieSettings() {
<ide> * @return void
<ide> */
<ide> public function testCors($request, $origin, $domains, $methods, $headers, $expectedOrigin, $expectedMethods = false, $expectedHeaders = false) {
<del> $_SERVER['HTTP_ORIGIN'] = $origin;
<add> $request->env('HTTP_ORIGIN', $origin);
<ide>
<del> $response = $this->getMock('CakeResponse', array('header'));
<add> $response = $this->getMock('Cake\Network\Response', array('header'));
<ide>
<ide> $method = $response->expects(!$expectedOrigin ? $this->never() : $this->at(0))->method('header');
<ide> $expectedOrigin && $method->with('Access-Control-Allow-Origin', $expectedOrigin ? $expectedOrigin : $this->anything());
<ide> public function testCors($request, $origin, $domains, $methods, $headers, $expec
<ide> * @return array
<ide> */
<ide> public function corsData() {
<del> $fooRequest = new CakeRequest();
<add> $fooRequest = new Request();
<ide>
<del> $secureRequest = $this->getMock('CakeRequest', array('is'));
<add> $secureRequest = $this->getMock('Cake\Network\Request', array('is'));
<ide> $secureRequest->expects($this->any())
<ide> ->method('is')
<ide> ->with('ssl') | 2 |
Javascript | Javascript | remove literals that obscure assert messages | 246aeaca1ed47e245ee4c92084b59f5ddb31163c | <ide><path>test/addons-napi/test_buffer/test.js
<ide> assert.strictEqual(binding.newBuffer().toString(), binding.theText);
<ide> assert.strictEqual(binding.newExternalBuffer().toString(), binding.theText);
<ide> console.log('gc1');
<ide> global.gc();
<del>assert.strictEqual(binding.getDeleterCallCount(), 1, 'deleter was not called');
<add>assert.strictEqual(binding.getDeleterCallCount(), 1);
<ide> assert.strictEqual(binding.copyBuffer().toString(), binding.theText);
<ide>
<ide> let buffer = binding.staticBuffer();
<del>assert.strictEqual(binding.bufferHasInstance(buffer), true,
<del> 'buffer type checking fails');
<add>assert.strictEqual(binding.bufferHasInstance(buffer), true);
<ide> assert.strictEqual(binding.bufferInfo(buffer), true);
<ide> buffer = null;
<ide> global.gc();
<ide> console.log('gc2');
<del>assert.strictEqual(binding.getDeleterCallCount(), 2, 'deleter was not called');
<add>assert.strictEqual(binding.getDeleterCallCount(), 2); | 1 |
Python | Python | add counting sort | 35d38737168ebfe4eb54e829f98dc31296aa52dd | <ide><path>sorts/counting_sort.py
<add>"""
<add>This is pure python implementation of counting sort algorithm
<add>For doctests run following command:
<add>python -m doctest -v counting_sort.py
<add>or
<add>python3 -m doctest -v counting_sort.py
<add>For manual testing run:
<add>python counting_sort.py
<add>"""
<add>
<add>from __future__ import print_function
<add>
<add>
<add>def counting_sort(collection):
<add> """Pure implementation of counting sort algorithm in Python
<add> :param collection: some mutable ordered collection with heterogeneous
<add> comparable items inside
<add> :return: the same collection ordered by ascending
<add> Examples:
<add> >>> counting_sort([0, 5, 3, 2, 2])
<add> [0, 2, 2, 3, 5]
<add> >>> counting_sort([])
<add> []
<add> >>> counting_sort([-2, -5, -45])
<add> [-45, -5, -2]
<add> """
<add> # if the collection is empty, returns empty
<add> if collection == []:
<add> return []
<add>
<add> # get some information about the collection
<add> coll_len = len(collection)
<add> coll_max = max(collection)
<add> coll_min = min(collection)
<add>
<add> # create the counting array
<add> counting_arr_length = coll_max + 1 - coll_min
<add> counting_arr = [0] * counting_arr_length
<add>
<add> # count how much a number appears in the collection
<add> for number in collection:
<add> counting_arr[number - coll_min] += 1
<add>
<add> # sum each position with it's predecessors. now, counting_arr[i] tells
<add> # us how many elements <= i has in the collection
<add> for i in range(1, counting_arr_length):
<add> counting_arr[i] = counting_arr[i] + counting_arr[i-1]
<add>
<add> # create the output collection
<add> ordered = [0] * coll_len
<add>
<add> # place the elements in the output, respecting the original order (stable
<add> # sort) from end to begin, updating counting_arr
<add> for i in reversed(range(0, coll_len)):
<add> ordered[counting_arr[collection[i] - coll_min]-1] = collection[i]
<add> counting_arr[collection[i] - coll_min] -= 1
<add>
<add> return ordered
<add>
<add>
<add>if __name__ == '__main__':
<add> import sys
<add> # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
<add> # otherwise 2.x's input builtin function is too "smart"
<add> if sys.version_info.major < 3:
<add> input_function = raw_input
<add> else:
<add> input_function = input
<add>
<add> user_input = input_function('Enter numbers separated by a comma:\n')
<add> unsorted = [int(item) for item in user_input.split(',')]
<add> print(counting_sort(unsorted)) | 1 |
PHP | PHP | remove unused method | 0c3bb9f99d57080adc90bca2e01115d5d3478739 | <ide><path>src/Utility/Security.php
<ide> class Security
<ide> */
<ide> protected static $_instance;
<ide>
<del> /**
<del> * Generate authorization hash.
<del> *
<del> * @return string Hash
<del> */
<del> public static function generateAuthKey()
<del> {
<del> return Security::hash(Text::uuid());
<del> }
<del>
<ide> /**
<ide> * Create a hash from string using given method.
<ide> * | 1 |
Ruby | Ruby | require instances to use a subclass | 1c5ba1f6859418f5b0e0b6a0047db00f15f105ab | <ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide>
<ide> # @private
<ide> def initialize(name, path, spec, alias_path: nil, force_bottle: false)
<add> # Only allow instances of subclasses. The base class does not hold any spec information (URLs etc).
<add> raise "Do not call `Formula.new' directly without a subclass." unless self.class < Formula
<add>
<ide> @name = name
<ide> @path = path
<ide> @alias_path = alias_path | 1 |
Text | Text | remove incorrect option in docker install command | f04837cf803583dfeb4dcd8311e4e5ef8764c37c | <ide><path>docs/sources/installation/ubuntulinux.md
<ide> NetworkManager (this might slow your network).
<ide>
<ide> To install the latest version of Docker, use the standard `-N` flag with `wget`:
<ide>
<del> $ wget -N -qO- https://get.docker.com/ | sh
<add> $ wget -qO- https://get.docker.com/ | sh
<ide> | 1 |
Python | Python | fix more warnings | dc161865bf049bdc3b68df40b2a39015ef3c7ee4 | <ide><path>libcloud/compute/drivers/vcloud.py
<ide> def ex_revert_to_snapshot(self, node):
<ide> def _perform_snapshot_operation(self, node, operation, xml_data, headers):
<ide> res = self.connection.request(
<ide> '%s/action/%s' % (get_url_path(node.id), operation),
<del> data=ET.tostring(xml_data) if xml_data else None,
<add> data=ET.tostring(xml_data) if xml_data is not None else None,
<ide> method='POST',
<ide> headers=headers)
<ide> self._wait_for_task_completion(res.object.get('href'))
<ide><path>libcloud/compute/drivers/voxel.py
<ide> def __init__(self, response, connection):
<ide> def parse_body(self):
<ide> if not self.body:
<ide> return None
<del> if not self.parsed:
<add> if self.parsed is None:
<ide> self.parsed = super(VoxelResponse, self).parse_body()
<ide> return self.parsed
<ide>
<ide> def parse_error(self):
<ide> err_list = []
<ide> if not self.body:
<ide> return None
<del> if not self.parsed:
<add> if self.parsed is None:
<ide> self.parsed = super(VoxelResponse, self).parse_body()
<ide> for err in self.parsed.findall('err'):
<ide> code = err.get('code') | 2 |
Javascript | Javascript | walk expression in require.ensure if not a fn expr | bd56e8385f3ff065e47a843bd2b9cb5a438d9857 | <ide><path>lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js
<ide> module.exports = AbstractPlugin.create({
<ide> } finally {
<ide> this.state.current = old;
<ide> }
<add> if(fnExpression.type !== "FunctionExpression") {
<add> this.walkExpression(fnExpression);
<add> }
<ide> return true;
<ide> }
<ide> }
<ide><path>test/browsertest/lib/index.web.js
<ide> describe("main", function() {
<ide> require.ensure([], f);
<ide> });
<ide>
<add> it("should parse expression in require.ensure, which isn't a function expression", function(done) {
<add> require.ensure([], (function() {
<add> require("./empty?require.ensure:test").should.be.eql({});
<add> return function f() {
<add> done();
<add> }
<add> }()));
<add> });
<add>
<ide> it("should accept a require.include call", function() {
<ide> require.include("./require.include");
<ide> var value = null; | 2 |
Ruby | Ruby | fix typo in exception class name | 035d88205765c8880265115b51493a389c810849 | <ide><path>actionview/lib/action_view/helpers/tags/datetime_field.rb
<ide> def render
<ide> private
<ide>
<ide> def format_date(value)
<del> raise NoImplementedError
<add> raise NotImplementedError
<ide> end
<ide>
<ide> def datetime_value(value) | 1 |
Text | Text | fix the timing of setimmediate's execution | e9f2ec4e1e590ce0b1f4a071997688f54ea52fdd | <ide><path>doc/api/timers.md
<ide> added: v0.9.1
<ide> * `...args` {any} Optional arguments to pass when the `callback` is called.
<ide>
<ide> Schedules the "immediate" execution of the `callback` after I/O events'
<del>callbacks and before timers created using [`setTimeout()`][] and
<del>[`setInterval()`][] are triggered. Returns an `Immediate` for use with
<del>[`clearImmediate()`][].
<add>callbacks. Returns an `Immediate` for use with [`clearImmediate()`][].
<ide>
<ide> When multiple calls to `setImmediate()` are made, the `callback` functions are
<ide> queued for execution in the order in which they are created. The entire callback | 1 |
Python | Python | add test for morph analysis | 3c3259024310e3ed28bc71c8bb6fa60d608a049c | <ide><path>spacy/tests/doc/test_morphanalysis.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>import pytest
<add>import numpy
<add>from spacy.attrs import IS_ALPHA, IS_DIGIT, IS_LOWER, IS_PUNCT, IS_TITLE, IS_STOP
<add>from spacy.symbols import VERB
<add>from spacy.vocab import Vocab
<add>from spacy.tokens import Doc
<add>
<add>@pytest.fixture
<add>def i_has(en_tokenizer):
<add> doc = en_tokenizer("I has")
<add> doc[0].tag_ = "PRP"
<add> doc[1].tag_ = "VBZ"
<add> return doc
<add>
<add>def test_token_morph_id(i_has):
<add> assert i_has[0].morph.id
<add> assert i_has[1].morph.id != 0
<add> assert i_has[0].morph.id != i_has[1].morph.id
<add>
<add>def test_morph_props(i_has):
<add> assert i_has[0].morph.pron_type == i_has.vocab.strings["PronType_prs"]
<add> assert i_has[1].morph.pron_type == 0
<add>
<add>
<add>def test_morph_iter(i_has):
<add> assert list(i_has[0].morph) == ["PronType_prs"]
<add> assert list(i_has[1].morph) == ["Number_sing", "Person_three", "VerbForm_fin"] | 1 |
Javascript | Javascript | change var to let | d23a4cf7b71ae906e979d60b40cfee9bf375afb6 | <ide><path>lib/internal/repl/history.js
<ide> function setupHistory(repl, historyPath, ready) {
<ide> }
<ide> }
<ide>
<del> var timer = null;
<del> var writing = false;
<del> var pending = false;
<add> let timer = null;
<add> let writing = false;
<add> let pending = false;
<ide> repl.pause();
<ide> // History files are conventionally not readable by others:
<ide> // https://github.com/nodejs/node/issues/3392 | 1 |
Go | Go | reduce use of const for driver name | b1a6d5388dfd54f4a0674eefecb4bb7cdc3f9aed | <ide><path>libnetwork/drivers/macvlan/macvlan.go
<ide> const (
<ide> vethLen = 7
<ide> containerVethPrefix = "eth"
<ide> vethPrefix = "veth"
<del> macvlanType = "macvlan" // driver type name
<add> driverName = "macvlan" // driver type name
<ide> modePrivate = "private" // macvlan mode private
<ide> modeVepa = "vepa" // macvlan mode vepa
<ide> modeBridge = "bridge" // macvlan mode bridge
<ide> func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
<ide> return err
<ide> }
<ide>
<del> return dc.RegisterDriver(macvlanType, d, c)
<add> return dc.RegisterDriver(driverName, d, c)
<ide> }
<ide>
<ide> func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
<ide> func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, erro
<ide> }
<ide>
<ide> func (d *driver) Type() string {
<del> return macvlanType
<add> return driverName
<ide> }
<ide>
<ide> func (d *driver) IsBuiltIn() bool {
<ide><path>libnetwork/drivers/macvlan/macvlan_endpoint.go
<ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
<ide> if opt, ok := epOptions[netlabel.PortMap]; ok {
<ide> if _, ok := opt.([]types.PortBinding); ok {
<ide> if len(opt.([]types.PortBinding)) > 0 {
<del> logrus.Warnf("%s driver does not support port mappings", macvlanType)
<add> logrus.Warnf("macvlan driver does not support port mappings")
<ide> }
<ide> }
<ide> }
<ide> // disallow port exposure --expose
<ide> if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
<ide> if _, ok := opt.([]types.TransportPort); ok {
<ide> if len(opt.([]types.TransportPort)) > 0 {
<del> logrus.Warnf("%s driver does not support port exposures", macvlanType)
<add> logrus.Warnf("macvlan driver does not support port exposures")
<ide> }
<ide> }
<ide> }
<ide><path>libnetwork/drivers/macvlan/macvlan_network.go
<ide> func (d *driver) createNetwork(config *configuration) (bool, error) {
<ide> return false, err
<ide> }
<ide> config.CreatedSlaveLink = true
<add>
<ide> // notify the user in logs that they have limited communications
<del> logrus.Debugf("Empty -o parent= limit communications to other containers inside of network: %s",
<add> logrus.Debugf("Empty -o parent= flags limit communications to other containers inside of network: %s",
<ide> config.Parent)
<ide> } else {
<ide> // if the subinterface parent_iface.vlan_id checks do not pass, return err.
<ide><path>libnetwork/drivers/macvlan/macvlan_setup.go
<ide> func createMacVlan(containerIfName, parent, macvlanMode string) (string, error)
<ide> // Get the link for the master index (Example: the docker host eth iface)
<ide> parentLink, err := ns.NlHandle().LinkByName(parent)
<ide> if err != nil {
<del> return "", fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", macvlanType, parent, err)
<add> return "", fmt.Errorf("error occurred looking up the macvlan parent iface %s error: %s", parent, err)
<ide> }
<ide> // Create a macvlan link
<ide> macvlan := &netlink.Macvlan{
<ide> func createMacVlan(containerIfName, parent, macvlanMode string) (string, error)
<ide> }
<ide> if err := ns.NlHandle().LinkAdd(macvlan); err != nil {
<ide> // If a user creates a macvlan and ipvlan on same parent, only one slave iface can be active at a time.
<del> return "", fmt.Errorf("failed to create the %s port: %v", macvlanType, err)
<add> return "", fmt.Errorf("failed to create the macvlan port: %v", err)
<ide> }
<ide>
<ide> return macvlan.Attrs().Name, nil
<ide> func createDummyLink(dummyName, truncNetID string) error {
<ide> }
<ide> parentDummyLink, err := ns.NlHandle().LinkByName(dummyName)
<ide> if err != nil {
<del> return fmt.Errorf("error occurred looking up the %s parent iface %s error: %s", macvlanType, dummyName, err)
<add> return fmt.Errorf("error occurred looking up the macvlan parent iface %s error: %s", dummyName, err)
<ide> }
<ide> // bring the new netlink iface up
<ide> if err := ns.NlHandle().LinkSetUp(parentDummyLink); err != nil { | 4 |
Python | Python | update version number of trunk | b2eb92995656ae62d980506a24ba5a6faa601cc0 | <ide><path>numpy/version.py
<del>version='1.0'
<add>version='1.0.1'
<ide> release=False
<ide>
<ide> if not release: | 1 |
Ruby | Ruby | remove blank line | b4efff4bac1c66e5af24de86cdb69a058ccf4147 | <ide><path>actionpack/lib/action_dispatch/testing/assertions/response.rb
<ide> def assert_response(type, message = nil)
<ide> # assert_redirected_to @customer
<ide> #
<ide> def assert_redirected_to(options = {}, message=nil)
<del>
<ide> assert_response(:redirect, message)
<ide> return true if options == @response.location
<ide> | 1 |
Java | Java | fix permission requests on pre-m android | 4e1abdd74dc4127a86d62e7750d01d39bb781c08 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/permissions/PermissionsModule.java
<ide> public void shouldShowRequestPermissionRationale(final String permission, final
<ide> }
<ide>
<ide> /**
<del> * Request the given permission. successCallback is called with true if the permission had been
<del> * granted, false otherwise. For devices before Android M, this instead checks if the user has
<del> * the permission given or not.
<add> * Request the given permission. successCallback is called with GRANTED if the permission had been
<add> * granted, DENIED or NEVER_ASK_AGAIN otherwise. For devices before Android M, this checks if the user has
<add> * the permission given or not and resolves with GRANTED or DENIED.
<ide> * See {@link Activity#checkSelfPermission}.
<ide> */
<ide> @ReactMethod
<ide> public void requestPermission(final String permission, final Promise promise) {
<ide> Context context = getReactApplicationContext().getBaseContext();
<ide> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
<ide> promise.resolve(context.checkPermission(permission, Process.myPid(), Process.myUid()) ==
<del> PackageManager.PERMISSION_GRANTED);
<add> PackageManager.PERMISSION_GRANTED ? GRANTED : DENIED);
<ide> return;
<ide> }
<ide> if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) { | 1 |
Ruby | Ruby | remove unneeded rubocop comment | ad82cd888e9acf2fdc4c795156b3e0c0e4e88988 | <ide><path>Library/Homebrew/debrew.rb
<ide> def self.debug(e)
<ide> if e.is_a?(Ignorable)
<ide> menu.choice(:irb) do
<ide> puts "When you exit this IRB session, execution will continue."
<del> set_trace_func proc { |event, _, _, id, binding, klass| # rubocop:disable Metrics/ParameterLists
<add> set_trace_func proc { |event, _, _, id, binding, klass|
<ide> if klass == Raise && id == :raise && event == "return"
<ide> set_trace_func(nil)
<ide> synchronize { IRB.start_within(binding) } | 1 |
Python | Python | add tester for pytest | fddaa7c8cf341794a8f3ea098b028c49975d546a | <ide><path>numpy/testing/_private/pytesttester.py
<add>"""
<add>Pytest test running.
<add>
<add>This module implements the ``test()`` function for NumPy modules. The usual
<add>boiler plate for doing that is to put the following in the module
<add>``__init__.py`` file::
<add>
<add> from numpy.testing import PytestTester
<add> test = PytestTester(__name__).test
<add> del PytestTester
<add>
<add>
<add>Warnings filtering and other runtime settings should be dealt with in the
<add>``pytest.ini`` file in the numpy repo root. The behavior of the test depends on
<add>whether or not that file is found as follows:
<add>
<add>* ``pytest.ini`` is present (develop mode)
<add> All warnings except those explicily filtered out are raised as error.
<add>* ``pytest.ini`` is absent (release mode)
<add> DeprecationWarnings and PendingDeprecationWarnings are ignored, other
<add> warnings are passed through.
<add>
<add>In practice, tests run from the numpy repo are run in develop mode. That
<add>includes the standard ``python runtests.py`` invocation.
<add>
<add>"""
<add>from __future__ import division, absolute_import, print_function
<add>
<add>import sys
<add>import os
<add>
<add>__all__ = ['PytestTester']
<add>
<add>
<add>def _show_numpy_info():
<add> import numpy as np
<add>
<add> print("NumPy version %s" % np.__version__)
<add> relaxed_strides = np.ones((10, 1), order="C").flags.f_contiguous
<add> print("NumPy relaxed strides checking option:", relaxed_strides)
<add>
<add>
<add>class PytestTester(object):
<add> """
<add> Pytest test runner.
<add>
<add> This class is made available in ``numpy.testing``, and a test function
<add> is typically added to a package's __init__.py like so::
<add>
<add> from numpy.testing import PytestTester
<add> test = PytestTester(__name__).test
<add> del PytestTester
<add>
<add> Calling this test function finds and runs all tests associated with the
<add> module and all its sub-modules.
<add>
<add> Attributes
<add> ----------
<add> module_name : str
<add> Full path to the package to test.
<add>
<add> Parameters
<add> ----------
<add> module_name : module name
<add> The name of the module to test.
<add>
<add> """
<add> def __init__(self, module_name):
<add> self.module_name = module_name
<add>
<add> def test(self, label='fast', verbose=1, extra_argv=None,
<add> doctests=False, coverage=False, timer=0, tests=None):
<add> """
<add> Run tests for module using pytest.
<add>
<add> Parameters
<add> ----------
<add> label : {'fast', 'full'}, optional
<add> Identifies the tests to run. When set to 'fast', tests decorated
<add> with `pytest.mark.slow` are skipped, when 'full', the slow marker
<add> is ignored.
<add> verbose : int, optional
<add> Verbosity value for test outputs, in the range 1-3. Default is 1.
<add> extra_argv : list, optional
<add> List with any extra arguments to pass to pytests.
<add> doctests : bool, optional
<add> .. note:: Not supported
<add> coverage : bool, optional
<add> If True, report coverage of NumPy code. Default is False.
<add> Requires installation of (pip) pytest-cov.
<add> timer : int, optional
<add> If > 0, report the time of the slowest `timer` tests. Default is 0.
<add>
<add> tests : test or list of tests
<add> Tests to be executed with pytest '--pyargs'
<add>
<add> Returns
<add> -------
<add> result : bool
<add> Return True on success, false otherwise.
<add>
<add> Notes
<add> -----
<add> Each NumPy module exposes `test` in its namespace to run all tests for it.
<add> For example, to run all tests for numpy.lib:
<add>
<add> >>> np.lib.test() #doctest: +SKIP
<add>
<add> Examples
<add> --------
<add> >>> result = np.lib.test() #doctest: +SKIP
<add> Running unit tests for numpy.lib
<add> ...
<add> Ran 976 tests in 3.933s
<add>
<add> OK
<add>
<add> >>> result.errors #doctest: +SKIP
<add> []
<add> >>> result.knownfail #doctest: +SKIP
<add> []
<add>
<add> """
<add> import pytest
<add>
<add> #FIXME This is no longer needed? Assume it was for use in tests.
<add> # cap verbosity at 3, which is equivalent to the pytest '-vv' option
<add> #from . import utils
<add> #verbose = min(int(verbose), 3)
<add> #utils.verbose = verbose
<add> #
<add>
<add> module = sys.modules[self.module_name]
<add> module_path = os.path.abspath(module.__path__[0])
<add>
<add> # setup the pytest arguments
<add> pytest_args = ['-l']
<add>
<add> if doctests:
<add> raise ValueError("Doctests not supported")
<add>
<add> if extra_argv:
<add> pytest_args += list(extra_argv)
<add>
<add> if verbose > 1:
<add> pytest_args += ["-" + "v"*(verbose - 1)]
<add> else:
<add> pytest_args += ["-q"]
<add>
<add> if coverage:
<add> pytest_args += ["--cov=" + module_path]
<add>
<add> if label == "fast":
<add> pytest_args += ["-m", "not slow"]
<add> elif label != "full":
<add> pytest_args += ["-m", label]
<add>
<add> if timer > 0:
<add> pytest_args += ["--durations=%s" % timer]
<add>
<add> if tests is None:
<add> tests = [self.module_name]
<add>
<add> pytest_args += ['--pyargs'] + list(tests)
<add>
<add>
<add> # run tests.
<add> _show_numpy_info()
<add>
<add> try:
<add> code = pytest.main(pytest_args)
<add> except SystemExit as exc:
<add> code = exc.code
<add>
<add> return code == 0 | 1 |
Text | Text | update notes about gcm decryption | 193d6d1bda6bb8c768b809057774aa4bca5f5d99 | <ide><path>doc/api/crypto.md
<ide> supported), the `decipher.setAuthTag()` method is used to pass in the
<ide> received _authentication tag_. If no tag is provided, or if the cipher text
<ide> has been tampered with, [`decipher.final()`][] will throw, indicating that the
<ide> cipher text should be discarded due to failed authentication. If the tag length
<del>is invalid according to [NIST SP 800-38D][], `decipher.setAuthTag()` will throw
<del>an error.
<del>
<del>Note that this Node.js version does not verify the length of GCM authentication
<del>tags. Such a check *must* be implemented by applications and is crucial to the
<del>authenticity of the encrypted data, otherwise, an attacker can use an
<del>arbitrarily short authentication tag to increase the chances of successfully
<del>passing authentication (up to 0.39%). It is highly recommended to associate one
<del>of the values 16, 15, 14, 13, 12, 8 or 4 bytes with each key, and to only permit
<del>authentication tags of that length, see [NIST SP 800-38D][].
<add>is invalid according to [NIST SP 800-38D][] or does not match the value of the
<add>`authTagLength` option, `decipher.setAuthTag()` will throw an error.
<ide>
<ide> The `decipher.setAuthTag()` method must be called before
<ide> [`decipher.final()`][]. | 1 |
Javascript | Javascript | fix a fixer | 2caae7c4e4f338c004d77a060a7f59737306fc3b | <ide><path>threejs/lessons/resources/lesson.js
<ide> $(document).ready(function($){
<ide> const classRE = /^(\w+)$/;
<ide> $('a').each(function() {
<ide> const href = this.getAttribute('href');
<add> if (!href) {
<add> return;
<add> }
<ide> const m = methodPropertyRE.exec(href);
<ide> if (m) {
<ide> const codeKeywordLink = getKeywordLink(m[1]); | 1 |
Text | Text | update changelog for | bdb02c2b73e134bd7809bbe47cbc0e6693ec1dc1 | <ide><path>CHANGELOG.md
<ide> The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
<ide> and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
<ide> Dates are formatted as YYYY-MM-DD.
<ide>
<del><!--
<ide> ## [Unreleased]
<ide>
<del>Nothing yet
<del>-->
<add>- Optimize contructors without arguments [#1887](https://github.com/immutable-js/immutable-js/pull/1887) by [marianoguerra](https://github.com/marianoguerra)
<ide>
<ide> ## [4.0.0] - 2021-09-30
<ide> | 1 |
Text | Text | add linting instructions | 58a79e34e5d164e26436ba55793f2a14f4e5c672 | <ide><path>.github/pull_request_template.md
<ide> Choose the right checklist for the change that you're making:
<ide>
<ide> ## Documentation / Examples
<ide>
<del>- [ ] Make sure the linting passes
<add>- [ ] Make sure the linting passes by running `yarn lint`
<ide><path>contributing.md
<ide> If you would like to run the tests in headless mode (with the browser windows hi
<ide> yarn testheadless
<ide> ```
<ide>
<del>Running a specific test suite inside of the `test/integration` directory:
<add>Running a specific test suite (e.g. `production`) inside of the `test/integration` directory:
<ide>
<ide> ```sh
<ide> yarn testonly --testPathPattern "production"
<ide> Running one test in the `production` test suite:
<ide> yarn testonly --testPathPattern "production" -t "should allow etag header support"
<ide> ```
<ide>
<del>### Running the integration apps
<add>### Linting
<add>
<add>To check the formatting of your code:
<add>
<add>```sh
<add>yarn lint
<add>```
<add>
<add>If you get errors, you can fix them with:
<add>
<add>```sh
<add>yarn lint-fix
<add>```
<add>
<add>### Running the example apps
<ide>
<ide> Running examples can be done with:
<ide> | 2 |
Ruby | Ruby | remove dead testing core_ext | 8746f7cac2d9bd92f91f7371a6f6b3487bae7a3b | <ide><path>activesupport/lib/active_support/testing/core_ext/test.rb
<del>require 'active_support/testing/core_ext/test/unit/assertions'
<del>require 'active_support/testing/setup_and_teardown'
<del>
<del>class Test::Unit::TestCase #:nodoc:
<del> include ActiveSupport::Testing::SetupAndTeardown
<del>end
<ide>\ No newline at end of file
<ide><path>activesupport/lib/active_support/testing/core_ext/test/unit/assertions.rb
<del>require 'test/unit/assertions'
<del>module Test
<del> module Unit
<del> #--
<del> # FIXME: no Proc#binding in Ruby 2, must change this API
<del> #++
<del> module Assertions
<del> # Test numeric difference between the return value of an expression as a result of what is evaluated
<del> # in the yielded block.
<del> #
<del> # assert_difference 'Article.count' do
<del> # post :create, :article => {...}
<del> # end
<del> #
<del> # An arbitrary expression is passed in and evaluated.
<del> #
<del> # assert_difference 'assigns(:article).comments(:reload).size' do
<del> # post :create, :comment => {...}
<del> # end
<del> #
<del> # An arbitrary positive or negative difference can be specified. The default is +1.
<del> #
<del> # assert_difference 'Article.count', -1 do
<del> # post :delete, :id => ...
<del> # end
<del> #
<del> # An array of expressions can also be passed in and evaluated.
<del> #
<del> # assert_difference [ 'Article.count', 'Post.count' ], +2 do
<del> # post :create, :article => {...}
<del> # end
<del> #
<del> # A error message can be specified.
<del> #
<del> # assert_difference 'Article.count', -1, "An Article should be destroyed" do
<del> # post :delete, :id => ...
<del> # end
<del> def assert_difference(expressions, difference = 1, message = nil, &block)
<del> expression_evaluations = Array(expressions).map do |expression|
<del> [expression, lambda do
<del> eval(expression, block.__send__(:binding))
<del> end]
<del> end
<del>
<del> original_values = expression_evaluations.inject([]) { |memo, expression| memo << expression[1].call }
<del> yield
<del> expression_evaluations.each_with_index do |expression, i|
<del> full_message = ""
<del> full_message << "#{message}.\n" if message
<del> full_message << "<#{expression[0]}> was the expression that failed"
<del> assert_equal original_values[i] + difference, expression[1].call, full_message
<del> end
<del> end
<del>
<del> # Assertion that the numeric result of evaluating an expression is not changed before and after
<del> # invoking the passed in block.
<del> #
<del> # assert_no_difference 'Article.count' do
<del> # post :create, :article => invalid_attributes
<del> # end
<del> #
<del> # A error message can be specified.
<del> #
<del> # assert_no_difference 'Article.count', "An Article should not be destroyed" do
<del> # post :create, :article => invalid_attributes
<del> # end
<del> def assert_no_difference(expressions, message = nil, &block)
<del> assert_difference expressions, 0, message, &block
<del> end
<del> end
<del> end
<del>end | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.