content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Text
Text
fix typo in bash_history mount example
655766ed955477299fac95a0fcd60af58f2b5be8
<ide><path>docs/userguide/dockervolumes.md <ide> Only the current container can use a private volume. <ide> The `-v` flag can also be used to mount a single file - instead of *just* <ide> directories - from the host machine. <ide> <del> $ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash <add> $ docker run --rm -it -v ~/.bash_history:/root/.bash_history ubuntu /bin/bash <ide> <ide> This will drop you into a bash shell in a new container, you will have your bash <ide> history from the host and when you exit the container, the host will have the
1
Python
Python
add view_name argument to hyperlinkedidentityfield
484ee8cc273eb9769549ee42ee574dc76c77fc02
<ide><path>rest_framework/fields.py <ide> class HyperlinkedIdentityField(Field): <ide> """ <ide> A field that represents the model's identity using a hyperlink. <ide> """ <add> def __init__(self, *args, **kwargs): <add> try: <add> self.view_name = kwargs.pop('view_name') <add> except: <add> raise ValueError("Hyperlinked field requires 'view_name' kwarg") <add> super(HyperlinkedRelatedField, self).__init__(*args, **kwargs) <add> <ide> def field_to_native(self, obj, field_name): <ide> request = self.context.get('request', None) <del> view_name = self.parent.opts.view_name <add> view_name = self.view_name or self.parent.opts.view_name <ide> view_kwargs = {'pk': obj.pk} <ide> return reverse(view_name, kwargs=view_kwargs, request=request) <ide>
1
Javascript
Javascript
remove dev timeout warnings
776dc97437fba0696217aabc638c302379a5808d
<ide><path>Libraries/Interaction/InteractionManager.js <ide> var setImmediate = require('setImmediate'); <ide> <ide> type Handle = number; <ide> <del>/** <del> * Maximum time a handle can be open before warning in DEV. <del> */ <del>var DEV_TIMEOUT = 2000; <del> <ide> var _emitter = new EventEmitter(); <ide> var _interactionSet = new Set(); <ide> var _addInteractionSet = new Set(); <ide> var InteractionManager = { <ide> scheduleUpdate(); <ide> var handle = ++_inc; <ide> _addInteractionSet.add(handle); <del> if (__DEV__) { <del> // Capture the stack trace of what created the handle. <del> var error = new Error( <del> 'InteractionManager: interaction handle not cleared within ' + <del> DEV_TIMEOUT + ' ms.' <del> ); <del> setDevTimeoutHandle(handle, error, DEV_TIMEOUT); <del> } <ide> return handle; <ide> }, <ide> <ide> function processUpdate() { <ide> _deleteInteractionSet.clear(); <ide> } <ide> <del>/** <del> * Wait until `timeout` has passed and warn if the handle has not been cleared. <del> */ <del>function setDevTimeoutHandle( <del> handle: Handle, <del> error: Error, <del> timeout: number <del>): void { <del> setTimeout(() => { <del> if (_interactionSet.has(handle)) { <del> console.warn(error.message + '\n' + error.stack); <del> } <del> }, timeout); <del>} <del> <ide> module.exports = InteractionManager;
1
Javascript
Javascript
add test for _setsimultaneousaccepts()
3235d318dce78799d244661eb72ed755e4e3fd1e
<ide><path>test/parallel/test-net-server-simultaneous-accepts-produce-warning-once.js <add>'use strict'; <add> <add>const { expectWarning } = require('../common'); <add>const net = require('net'); <add> <add>expectWarning( <add> 'DeprecationWarning', <add> 'net._setSimultaneousAccepts() is deprecated and will be removed.', <add> 'DEP0121'); <add> <add>net._setSimultaneousAccepts(); <add>net._setSimultaneousAccepts();
1
Ruby
Ruby
add test for negated build.with?
e14fedd1b35480ea3707689db044140d18662b9c
<ide><path>Library/Homebrew/rubocops/extend/formula_cop.rb <ide> def method_called_in_block?(node, method_name) <ide> end <ide> <ide> # Check if method_name is called among the direct children nodes in the given node <add> # Check if the node itself is the method <ide> def method_called?(node, method_name) <add> if node.send_type? && node.method_name == method_name <add> offending_node(node) <add> return true <add> end <ide> node.each_child_node(:send) do |call_node| <ide> next unless call_node.method_name == method_name <del> @offensive_node = call_node <del> @offense_source_range = call_node.source_range <add> offending_node(call_node) <ide> return true <ide> end <ide> false <ide><path>Library/Homebrew/rubocops/lines_cop.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> problem "Use if #{correct} instead of unless #{m.source}" <ide> end <ide> <del> # find_instance_method_call(body_node, :build, :with?) do |m| <del> # next unless negation?(m) <del> # problem "Don't negate 'build.with?': use 'build.without?'" <del> # end <del> # <add> find_instance_method_call(body_node, :build, :with?) do |m| <add> next unless method_called?(m.parent, :!) <add> problem "Don't negate 'build.with?': use 'build.without?'" <add> end <add> <ide> # find_instance_method_call(body_node, :build, :without?) do |m| <ide> # next unless negation?(m) <ide> # problem "Don't negate 'build.without?': use 'build.with?'" <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> end <ide> <ide> def unless_modifier?(node) <add> return false unless node.if_type? <ide> node.modifier_form? && node.unless? <ide> end <ide> <ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb <ide> def post_install <ide> expect_offense(expected, actual) <ide> end <ide> end <add> <add> it "with negated build.with?" do <add> source = <<-EOS.undent <add> class Foo < Formula <add> desc "foo" <add> url 'http://example.com/foo-1.0.tgz' <add> def post_install <add> return if !build.with? "bar" <add> end <add> end <add> EOS <add> <add> expected_offenses = [{ message: "Don't negate 'build.with?': use 'build.without?'", <add> severity: :convention, <add> line: 5, <add> column: 14, <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])
3
Text
Text
fix typos in vue intro
43d538ce2d203a9f21afbaca90cea953b644969c
<ide><path>guide/english/vue/index.md <ide> But on the other hand, Vue.js can also be leveraged to create powerful single pa <ide> such as `vue-router` for page routing and `vuex` for state management. <ide> <ide> Its main attributes are the following: <del>* It's approachable: if you know basic HTML, CSS & JavaScript - then you'll be writing apps in Vue.js in no time! <del>* It's versatile: you can use it as a simple library or a fully featured framework <del>* It's performant: it's extremely performant out of the box with very little to almost no optimization required. <add>* It's approachable: if you know basic HTML, CSS & JavaScript, then you'll be writing apps in Vue.js in no time! <add>* It's versatile: you can use it as a simple library or a fully featured framework. <add>* It's performant: it's extremely performant out of the box with little to no optimization required. <ide> <ide> #### More Information <ide>
1
Javascript
Javascript
fix arguments order in assert.strictequal
60743638cc0c5b70bc2fc998ab4d0e13c59a26f7
<ide><path>test/parallel/test-http-pause.js <ide> server.listen(0, function() { <ide> }); <ide> <ide> process.on('exit', () => { <del> assert.strictEqual(expectedServer, resultServer); <del> assert.strictEqual(expectedClient, resultClient); <add> assert.strictEqual(resultServer, expectedServer); <add> assert.strictEqual(resultClient, expectedClient); <ide> });
1
Mixed
Python
add comment about auto-generated file [ci skip]
8736bfc0521c63fe11034eb7ece1bc460ec0f545
<ide><path>website/setup/jinja_to_js.py <ide> def main( <ide> # fmt: on <ide> ): <ide> """Convert a jinja2 template to a JavaScript module.""" <del> compiler = JinjaToJS( <del> template_path.parent, template_path.parts[-1], js_module_format="es6" <del> ) <add> tpl_file = template_path.parts[-1] <add> compiler = JinjaToJS(template_path.parent, tpl_file, js_module_format="es6") <add> header = f"// This file was auto-generated by {__file__} based on {tpl_file}" <ide> result = compiler.get_output() <ide> if output is not None: <ide> with output.open("w") as f: <del> f.write(result) <add> f.write(f"{header}\n{result}") <ide> print(f"Updated {output.parts[-1]}") <ide> else: <ide> print(result) <ide><path>website/src/widgets/quickstart-training-generator.js <add>// This file was auto-generated by jinja_to_js.py based on quickstart_training.jinja <ide> import jinjaToJS from "jinja-to-js";export default function templateQuickstartTraining(ctx) { <ide> var __result = ""; <ide> var __tmp;
2
Javascript
Javascript
add more test coverage for nested memo()
14be29b2b97f2be6c82955acc0455fbac22ec403
<ide><path>packages/react-reconciler/src/__tests__/ReactMemo-test.internal.js <ide> describe('memo', () => { <ide> expect(ReactNoop.getChildren()).toEqual([span('1!')]); <ide> }); <ide> <add> it('supports defaultProps defined on the memo() return value', async () => { <add> function Counter({a, b, c, d, e}) { <add> return <Text text={a + b + c + d + e} />; <add> } <add> Counter.defaultProps = { <add> a: 1, <add> }; <add> // Note! We intentionally use React.memo() rather than the injected memo(). <add> // This tests a synchronous chain of React.memo() without lazy() in the middle. <add> Counter = React.memo(Counter); <add> Counter.defaultProps = { <add> b: 2, <add> }; <add> Counter = React.memo(Counter); <add> Counter = React.memo(Counter); // Layer without defaultProps <add> Counter.defaultProps = { <add> c: 3, <add> }; <add> Counter = React.memo(Counter); <add> Counter.defaultProps = { <add> d: 4, <add> }; <add> // The final layer uses memo() from test fixture (which might be lazy). <add> Counter = memo(Counter); <add> ReactNoop.render( <add> <Suspense fallback={<Text text="Loading..." />}> <add> <Counter e={5} /> <add> </Suspense>, <add> ); <add> expect(ReactNoop.flush()).toEqual(['Loading...']); <add> await Promise.resolve(); <add> expect(ReactNoop.flush()).toEqual([15]); <add> expect(ReactNoop.getChildren()).toEqual([span(15)]); <add> <add> // Should bail out because props have not changed <add> ReactNoop.render( <add> <Suspense> <add> <Counter e={5} /> <add> </Suspense>, <add> ); <add> expect(ReactNoop.flush()).toEqual([]); <add> expect(ReactNoop.getChildren()).toEqual([span(15)]); <add> <add> // Should update because count prop changed <add> ReactNoop.render( <add> <Suspense> <add> <Counter e={10} /> <add> </Suspense>, <add> ); <add> expect(ReactNoop.flush()).toEqual([20]); <add> expect(ReactNoop.getChildren()).toEqual([span(20)]); <add> }); <add> <ide> it('warns if first argument is undefined', () => { <ide> expect(() => memo()).toWarnDev( <ide> 'memo: The first argument must be a component. Instead ' +
1
Javascript
Javascript
update version to 0.27.1
7278115d96b64a24b17adef0b2e45c231e58be2a
<ide><path>d3.js <del>d3 = {version: "0.27.0"}; // semver <add>d3 = {version: "0.27.1"}; // semver <ide> if (!Date.now) Date.now = function() { <ide> return +new Date(); <ide> }; <ide><path>d3.min.js <del>(function(){var o=null;d3={version:"0.27.0"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <add>(function(){var o=null;d3={version:"0.27.1"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <ide> d3.split=function(a,b){var e=[],f=[],c,d=-1,h=a.length;if(arguments.length<2)b=aa;for(;++d<h;)if(b.call(f,c=a[d],d)){e.push(f);f=[]}else f.push(c);e.push(f);return e};function aa(a){return a==o}function E(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function ba(a,b){b=x(arguments);b[0]=this;a.apply(this,b);return this} <ide> d3.range=function(a,b,e){if(arguments.length==1){b=a;a=0}if(e==o)e=1;if((b-a)/e==Infinity)throw Error("infinite range");var f=[],c=-1,d;if(e<0)for(;(d=a+e*++c)>b;)f.push(d);else for(;(d=a+e*++c)<b;)f.push(d);return f};d3.requote=function(a){return a.replace(ca,"\\$&")};var ca=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g; <ide> d3.text=function(a,b,e){var f=new XMLHttpRequest;if(arguments.length==3)f.overrideMimeType(b);else e=b;f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)e(f.status<300&&f.responseText?f.responseText:o)};f.send(o)};d3.json=function(a,b){return d3.text(a,"application/json",function(e){b(e&&JSON.parse(e))})}; <ide><path>src/core/core.js <del>d3 = {version: "0.27.0"}; // semver <add>d3 = {version: "0.27.1"}; // semver
3
Python
Python
add depth argument for text classifier
3cdee79a0ca24d4262f1a7444050485d107a6d4a
<ide><path>spacy/_ml.py <ide> def SpacyVectors(docs, drop=0.): <ide> <ide> <ide> def build_text_classifier(nr_class, width=64, **cfg): <add> depth = cfg.get('depth', 2) <ide> nr_vector = cfg.get('nr_vector', 5000) <ide> pretrained_dims = cfg.get('pretrained_dims', 0) <ide> with Model.define_operators({'>>': chain, '+': add, '|': concatenate, <ide> def build_text_classifier(nr_class, width=64, **cfg): <ide> LN(Maxout(width, vectors_width)) <ide> >> Residual( <ide> (ExtractWindow(nW=1) >> LN(Maxout(width, width*3))) <del> ) ** 2, pad=2 <add> ) ** depth, pad=depth <ide> ) <ide> >> flatten_add_lengths <ide> >> ParametricAttention(width)
1
PHP
PHP
remove pointless code
cf16ae055f185761f3430002d23eb900b2c8884a
<ide><path>lib/Cake/Routing/Route/CakeRoute.php <ide> public function parse($url) { <ide> $route[$key] = $value; <ide> } <ide> <del> foreach ($this->keys as $key) { <del> if (isset($route[$key])) { <del> $route[$key] = $route[$key]; <del> } <del> } <del> <ide> if (isset($route['_args_'])) { <ide> list($pass, $named) = $this->_parseArgs($route['_args_'], $route); <ide> $route['pass'] = array_merge($route['pass'], $pass); <ide> protected function _parseArgs($args, $context) { <ide> $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false; <ide> if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) { <ide> list($key, $val) = explode($namedConfig['separator'], $param, 2); <del> $key = $key; <del> $val = $val; <ide> $hasRule = isset($rules[$key]); <ide> $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context)); <ide> if ($passIt) {
1
Text
Text
correct the word "remove"
4f3674cc37b1e3bc19ecf4f4e606543f2ce03d8b
<ide><path>errors/future-webpack5-moved-to-webpack5.md <ide> The `future.webpack5` option has been moved to `webpack5` in `next.config.js`. <ide> <ide> #### Possible Ways to Fix It <ide> <del>If you had the value `true` you can removed the option as webpack 5 is now the default for all Next.js apps unless opted out. <add>If you had the value `true` you can remove the option as webpack 5 is now the default for all Next.js apps unless opted out. <ide> <ide> If you had he value `false` you can update `next.config.js`: <ide>
1
Ruby
Ruby
remove unused match variables in selector
01ac925b78b695789731e79156fd8ed255564192
<ide><path>actionpack/lib/action_view/vendor/html-scanner/html/selector.rb <ide> def simple_selector(statement, values, can_negate = true) <ide> # Get identifier, class, attribute name, pseudo or negation. <ide> while true <ide> # Element identifier. <del> next if statement.sub!(/^#(\?|[\w\-]+)/) do |match| <add> next if statement.sub!(/^#(\?|[\w\-]+)/) do <ide> id = $1 <ide> if id == "?" <ide> id = values.shift <ide> def simple_selector(statement, values, can_negate = true) <ide> end <ide> <ide> # Class name. <del> next if statement.sub!(/^\.([\w\-]+)/) do |match| <add> next if statement.sub!(/^\.([\w\-]+)/) do <ide> class_name = $1 <ide> @source << ".#{class_name}" <ide> class_name = Regexp.new("(^|\s)#{Regexp.escape(class_name)}($|\s)") unless class_name.is_a?(Regexp) <ide> def simple_selector(statement, values, can_negate = true) <ide> end <ide> <ide> # Attribute value. <del> next if statement.sub!(/^\[\s*([[:alpha:]][\w\-:]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do |match| <add> next if statement.sub!(/^\[\s*([[:alpha:]][\w\-:]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do <ide> name, equality, value = $1, $2, $3 <ide> if value == "?" <ide> value = values.shift <ide> def simple_selector(statement, values, can_negate = true) <ide> end <ide> <ide> # Root element only. <del> next if statement.sub!(/^:root/) do |match| <add> next if statement.sub!(/^:root/) do <ide> pseudo << lambda do |element| <ide> element.parent.nil? || !element.parent.tag? <ide> end <ide> def simple_selector(statement, values, can_negate = true) <ide> "" # Remove <ide> end <ide> # First/last child (of type). <del> next if statement.sub!(/^:(first|last)-(child|of-type)/) do |match| <add> next if statement.sub!(/^:(first|last)-(child|of-type)/) do <ide> reverse = $1 == "last" <ide> of_type = $2 == "of-type" <ide> pseudo << nth_child(0, 1, of_type, reverse) <ide> @source << ":#{$1}-#{$2}" <ide> "" # Remove <ide> end <ide> # Only child (of type). <del> next if statement.sub!(/^:only-(child|of-type)/) do |match| <add> next if statement.sub!(/^:only-(child|of-type)/) do <ide> of_type = $1 == "of-type" <ide> pseudo << only_child(of_type) <ide> @source << ":only-#{$1}" <ide> def simple_selector(statement, values, can_negate = true) <ide> <ide> # Empty: no child elements or meaningful content (whitespaces <ide> # are ignored). <del> next if statement.sub!(/^:empty/) do |match| <add> next if statement.sub!(/^:empty/) do <ide> pseudo << lambda do |element| <ide> empty = true <ide> for child in element.children <ide> def simple_selector(statement, values, can_negate = true) <ide> end <ide> # Content: match the text content of the element, stripping <ide> # leading and trailing spaces. <del> next if statement.sub!(/^:content\(\s*(\?|'[^']*'|"[^"]*"|[^)]*)\s*\)/) do |match| <add> next if statement.sub!(/^:content\(\s*(\?|'[^']*'|"[^"]*"|[^)]*)\s*\)/) do <ide> content = $1 <ide> if content == "?" <ide> content = values.shift
1
Ruby
Ruby
add test for object conditional with scope
1d6ac2246255d33eb9e4f1b1237c3b5d59ad2bde
<ide><path>activesupport/test/callbacks_test.rb <ide> def run; run_callbacks :foo; end <ide> } <ide> end <ide> <add> # FIXME: do we really want to support classes as conditionals? There were <add> # no tests for it previous to this. <add> def test_class_conditional_with_scope <add> z = [] <add> callback = Class.new { <add> define_singleton_method(:foo) { |o| z << o } <add> } <add> klass = Class.new { <add> include ActiveSupport::Callbacks <add> define_callbacks :foo, :scope => [:name] <add> set_callback :foo, :before, :foo, :if => callback <add> def foo; end <add> def run; run_callbacks :foo; end <add> } <add> object = klass.new <add> object.run <add> assert_equal [object], z <add> end <add> <ide> # FIXME: do we really want to support classes as conditionals? There were <ide> # no tests for it previous to this. <ide> def test_class
1
Java
Java
update javadoc for publicresourceurlprovider
10e1a805403883c9bc9ed19205e6306ffb01db73
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PublicResourceUrlProvider.java <ide> <ide> <ide> /** <del> * A central component for serving static resources that is aware of Spring MVC <del> * handler mappings and provides methods to determine the public URL path that <del> * a client should use to access a static resource. <add> * A central component to use to obtain the public URL path that clients should <add> * use to access a static resource. <add> * <add> * <p>This class is aware of Spring MVC handler mappings used to serve static <add> * resources and uses the {@code ResourceResolver} chains of the configured <add> * {@code ResourceHttpRequestHandler}s to make its decisions. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.1
1
Java
Java
remove timer proxy
ed6a3a6c74e2abc3c6dc911aa354bcd38458cd32
<ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/JavaTimerManager.java <ide> public void doFrame(long frameTimeNanos) { <ide> } <ide> <ide> if (mTimersToCall != null) { <del> mJSTimers.callTimers(mTimersToCall); <add> mReactApplicationContext.getJSModule(JSTimers.class).callTimers(mTimersToCall); <ide> mTimersToCall = null; <ide> } <ide> <ide> public void run() { <ide> } <ide> <ide> if (sendIdleEvents) { <del> mJSTimers.callIdleCallbacks(absoluteFrameStartTime); <add> mReactApplicationContext <add> .getJSModule(JSTimers.class) <add> .callIdleCallbacks(absoluteFrameStartTime); <ide> } <ide> <ide> mCurrentIdleCallbackRunnable = null; <ide> public void cancel() { <ide> } <ide> <ide> private final ReactApplicationContext mReactApplicationContext; <del> private final JSTimers mJSTimers; <ide> private final ReactChoreographer mReactChoreographer; <ide> private final DevSupportManager mDevSupportManager; <ide> private final Object mTimerGuard = new Object(); <ide> public void cancel() { <ide> <ide> public JavaTimerManager( <ide> ReactApplicationContext reactContext, <del> JSTimers jsTimers, <ide> ReactChoreographer reactChoreographer, <ide> DevSupportManager devSupportManager) { <ide> mReactApplicationContext = reactContext; <del> mJSTimers = jsTimers; <ide> mReactChoreographer = reactChoreographer; <ide> mDevSupportManager = devSupportManager; <ide> <ide> public void createAndMaybeCallTimer( <ide> if (mDevSupportManager.getDevSupportEnabled()) { <ide> long driftTime = Math.abs(remoteTime - deviceTime); <ide> if (driftTime > 60000) { <del> mJSTimers.emitTimeDriftWarning( <del> "Debugger and device times have drifted by more than 60s. Please correct this by " <del> + "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine."); <add> mReactApplicationContext <add> .getJSModule(JSTimers.class) <add> .emitTimeDriftWarning( <add> "Debugger and device times have drifted by more than 60s. Please correct this by " <add> + "running adb shell \"date `date +%m%d%H%M%Y.%S`\" on your debugger machine."); <ide> } <ide> } <ide> <ide> public void createAndMaybeCallTimer( <ide> if (duration == 0 && !repeat) { <ide> WritableArray timerToCall = Arguments.createArray(); <ide> timerToCall.pushInt(callbackID); <del> mJSTimers.callTimers(timerToCall); <add> mReactApplicationContext.getJSModule(JSTimers.class).callTimers(timerToCall); <ide> return; <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/core/TimingModule.java <ide> import com.facebook.react.bridge.ReactApplicationContext; <ide> import com.facebook.react.bridge.ReactContextBaseJavaModule; <ide> import com.facebook.react.bridge.ReactMethod; <del>import com.facebook.react.bridge.WritableArray; <ide> import com.facebook.react.devsupport.interfaces.DevSupportManager; <ide> import com.facebook.react.jstasks.HeadlessJsTaskContext; <ide> import com.facebook.react.jstasks.HeadlessJsTaskEventListener; <ide> public final class TimingModule extends ReactContextBaseJavaModule <ide> public TimingModule(ReactApplicationContext reactContext, DevSupportManager devSupportManager) { <ide> super(reactContext); <ide> <del> JSTimers jsTimersProxy = <del> new JSTimers() { <del> @Override <del> public void callTimers(WritableArray timerIDs) { <del> getReactApplicationContext().getJSModule(JSTimers.class).callTimers(timerIDs); <del> } <del> <del> @Override <del> public void callIdleCallbacks(double frameTime) { <del> getReactApplicationContext().getJSModule(JSTimers.class).callIdleCallbacks(frameTime); <del> } <del> <del> @Override <del> public void emitTimeDriftWarning(String warningMessage) { <del> getReactApplicationContext() <del> .getJSModule(JSTimers.class) <del> .emitTimeDriftWarning(warningMessage); <del> } <del> }; <del> <ide> mJavaTimerManager = <del> new JavaTimerManager( <del> reactContext, jsTimersProxy, ReactChoreographer.getInstance(), devSupportManager); <add> new JavaTimerManager(reactContext, ReactChoreographer.getInstance(), devSupportManager); <ide> } <ide> <ide> @Override
2
Python
Python
move exec_command tests out of the file itself
c29a68e5a5978a1e32fefb8776974f94ab343845
<ide><path>numpy/distutils/exec_command.py <del>#!/usr/bin/env python <ide> """ <ide> exec_command <ide> <ide> def _quote_arg(arg): <ide> return '"%s"' % arg <ide> return arg <ide> <del> <del>def test_nt(**kws): <del> pythonexe = get_pythonexe() <del> echo = find_executable('echo') <del> using_cygwin_echo = echo != 'echo' <del> if using_cygwin_echo: <del> log.warn('Using cygwin echo in win32 environment is not supported') <del> <del> s, o=exec_command(pythonexe\ <del> +' -c "import os;print os.environ.get(\'AAA\',\'\')"') <del> assert s==0 and o=='', (s, o) <del> <del> s, o=exec_command(pythonexe\ <del> +' -c "import os;print os.environ.get(\'AAA\')"', <del> AAA='Tere') <del> assert s==0 and o=='Tere', (s, o) <del> <del> os.environ['BBB'] = 'Hi' <del> s, o=exec_command(pythonexe\ <del> +' -c "import os;print os.environ.get(\'BBB\',\'\')"') <del> assert s==0 and o=='Hi', (s, o) <del> <del> s, o=exec_command(pythonexe\ <del> +' -c "import os;print os.environ.get(\'BBB\',\'\')"', <del> BBB='Hey') <del> assert s==0 and o=='Hey', (s, o) <del> <del> s, o=exec_command(pythonexe\ <del> +' -c "import os;print os.environ.get(\'BBB\',\'\')"') <del> assert s==0 and o=='Hi', (s, o) <del> elif 0: <del> s, o=exec_command('echo Hello') <del> assert s==0 and o=='Hello', (s, o) <del> <del> s, o=exec_command('echo a%AAA%') <del> assert s==0 and o=='a', (s, o) <del> <del> s, o=exec_command('echo a%AAA%', AAA='Tere') <del> assert s==0 and o=='aTere', (s, o) <del> <del> os.environ['BBB'] = 'Hi' <del> s, o=exec_command('echo a%BBB%') <del> assert s==0 and o=='aHi', (s, o) <del> <del> s, o=exec_command('echo a%BBB%', BBB='Hey') <del> assert s==0 and o=='aHey', (s, o) <del> s, o=exec_command('echo a%BBB%') <del> assert s==0 and o=='aHi', (s, o) <del> <del> s, o=exec_command('this_is_not_a_command') <del> assert s and o!='', (s, o) <del> <del> s, o=exec_command('type not_existing_file') <del> assert s and o!='', (s, o) <del> <del> s, o=exec_command('echo path=%path%') <del> assert s==0 and o!='', (s, o) <del> <del> s, o=exec_command('%s -c "import sys;sys.stderr.write(sys.platform)"' \ <del> % pythonexe) <del> assert s==0 and o=='win32', (s, o) <del> <del> s, o=exec_command('%s -c "raise \'Ignore me.\'"' % pythonexe) <del> assert s==1 and o, (s, o) <del> <del> s, o=exec_command('%s -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"'\ <del> % pythonexe) <del> assert s==0 and o=='012', (s, o) <del> <del> s, o=exec_command('%s -c "import sys;sys.exit(15)"' % pythonexe) <del> assert s==15 and o=='', (s, o) <del> <del> s, o=exec_command('%s -c "print \'Heipa\'"' % pythonexe) <del> assert s==0 and o=='Heipa', (s, o) <del> <del> print ('ok') <del> <del>def test_posix(**kws): <del> s, o=exec_command("echo Hello",**kws) <del> assert s==0 and o=='Hello', (s, o) <del> <del> s, o=exec_command('echo $AAA',**kws) <del> assert s==0 and o=='', (s, o) <del> <del> s, o=exec_command('echo "$AAA"',AAA='Tere',**kws) <del> assert s==0 and o=='Tere', (s, o) <del> <del> <del> s, o=exec_command('echo "$AAA"',**kws) <del> assert s==0 and o=='', (s, o) <del> <del> os.environ['BBB'] = 'Hi' <del> s, o=exec_command('echo "$BBB"',**kws) <del> assert s==0 and o=='Hi', (s, o) <del> <del> s, o=exec_command('echo "$BBB"',BBB='Hey',**kws) <del> assert s==0 and o=='Hey', (s, o) <del> <del> s, o=exec_command('echo "$BBB"',**kws) <del> assert s==0 and o=='Hi', (s, o) <del> <del> <del> s, o=exec_command('this_is_not_a_command',**kws) <del> assert s!=0 and o!='', (s, o) <del> <del> s, o=exec_command('echo path=$PATH',**kws) <del> assert s==0 and o!='', (s, o) <del> <del> s, o=exec_command('python -c "import sys,os;sys.stderr.write(os.name)"',**kws) <del> assert s==0 and o=='posix', (s, o) <del> <del> s, o=exec_command('python -c "raise \'Ignore me.\'"',**kws) <del> assert s==1 and o, (s, o) <del> <del> s, o=exec_command('python -c "import sys;sys.stderr.write(\'0\');sys.stderr.write(\'1\');sys.stderr.write(\'2\')"',**kws) <del> assert s==0 and o=='012', (s, o) <del> <del> s, o=exec_command('python -c "import sys;sys.exit(15)"',**kws) <del> assert s==15 and o=='', (s, o) <del> <del> s, o=exec_command('python -c "print \'Heipa\'"',**kws) <del> assert s==0 and o=='Heipa', (s, o) <del> <del> print ('ok') <del> <del>def test_execute_in(**kws): <del> pythonexe = get_pythonexe() <del> tmpfile = temp_file_name() <del> fn = os.path.basename(tmpfile) <del> tmpdir = os.path.dirname(tmpfile) <del> f = open(tmpfile, 'w') <del> f.write('Hello') <del> f.close() <del> <del> s, o = exec_command('%s -c "print \'Ignore the following IOError:\','\ <del> 'open(%r,\'r\')"' % (pythonexe, fn),**kws) <del> assert s and o!='', (s, o) <del> s, o = exec_command('%s -c "print open(%r,\'r\').read()"' % (pythonexe, fn), <del> execute_in = tmpdir,**kws) <del> assert s==0 and o=='Hello', (s, o) <del> os.remove(tmpfile) <del> print ('ok') <del> <del>def test_cl(**kws): <del> if os.name=='nt': <del> s, o = exec_command(['cl', '/V'],**kws) <del> assert s, (s, o) <del> print ('cl ok') <del> <del>if os.name=='posix': <del> test = test_posix <del>elif os.name in ['nt', 'dos']: <del> test = test_nt <del>else: <del> raise NotImplementedError('exec_command tests for ', os.name) <del> <ide> ############################################################ <del> <del>if __name__ == "__main__": <del> <del> test(use_tee=0) <del> test(use_tee=1) <del> test_execute_in(use_tee=0) <del> test_execute_in(use_tee=1) <del> test_cl(use_tee=1) <ide><path>numpy/distutils/tests/test_exec_command.py <ide> from tempfile import TemporaryFile <ide> <ide> from numpy.distutils import exec_command <add>from numpy.distutils.exec_command import get_pythonexe <add>from numpy.testing import TestCase, run_module_suite, tempdir <ide> <ide> # In python 3 stdout, stderr are text (unicode compliant) devices, so to <ide> # emulate them import StringIO from the io module. <ide> def test_exec_command_stderr(): <ide> with redirect_stdout(TemporaryFile()): <ide> with redirect_stderr(StringIO()): <ide> exec_command.exec_command("cd '.'") <add> <add> <add>class TestExecCommand(TestCase): <add> def setUp(self): <add> self.pyexe = get_pythonexe() <add> <add> def check_nt(self, **kws): <add> s, o = exec_command.exec_command('echo path=%path%') <add> self.assertEqual(s, 0) <add> self.assertNotEqual(o, '') <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "import sys;sys.stderr.write(sys.platform)"' % self.pyexe) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'win32') <add> <add> def check_posix(self, **kws): <add> s, o = exec_command.exec_command("echo Hello", **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Hello') <add> <add> s, o = exec_command.exec_command('echo $AAA', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, '') <add> <add> s, o = exec_command.exec_command('echo "$AAA"', AAA='Tere', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Tere') <add> <add> s, o = exec_command.exec_command('echo "$AAA"', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, '') <add> <add> if 'BBB' not in os.environ: <add> os.environ['BBB'] = 'Hi' <add> s, o = exec_command.exec_command('echo "$BBB"', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Hi') <add> <add> s, o = exec_command.exec_command('echo "$BBB"', BBB='Hey', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Hey') <add> <add> s, o = exec_command.exec_command('echo "$BBB"', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Hi') <add> <add> del os.environ['BBB'] <add> <add> s, o = exec_command.exec_command('echo "$BBB"', **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, '') <add> <add> <add> s, o = exec_command.exec_command('this_is_not_a_command', **kws) <add> self.assertNotEqual(s, 0) <add> self.assertNotEqual(o, '') <add> <add> s, o = exec_command.exec_command('echo path=$PATH', **kws) <add> self.assertEqual(s, 0) <add> self.assertNotEqual(o, '') <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "import sys,os;sys.stderr.write(os.name)"' % <add> self.pyexe, **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'posix') <add> <add> def check_basic(self, *kws): <add> s, o = exec_command.exec_command( <add> '"%s" -c "raise \'Ignore me.\'"' % self.pyexe, **kws) <add> self.assertNotEqual(s, 0) <add> self.assertNotEqual(o, '') <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "import sys;sys.stderr.write(\'0\');' <add> 'sys.stderr.write(\'1\');sys.stderr.write(\'2\')"' % <add> self.pyexe, **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, '012') <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "import sys;sys.exit(15)"' % self.pyexe, **kws) <add> self.assertEqual(s, 15) <add> self.assertEqual(o, '') <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "print(\'Heipa\'")' % self.pyexe, **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Heipa') <add> <add> def check_execute_in(self, **kws): <add> with tempdir() as tmpdir: <add> fn = "file" <add> tmpfile = os.path.join(tmpdir, fn) <add> f = open(tmpfile, 'w') <add> f.write('Hello') <add> f.close() <add> <add> s, o = exec_command.exec_command( <add> '"%s" -c "f = open(\'%s\', \'r\'); f.close()"' % <add> (self.pyexe, fn), **kws) <add> self.assertNotEqual(s, 0) <add> self.assertNotEqual(o, '') <add> s, o = exec_command.exec_command( <add> '"%s" -c "f = open(\'%s\', \'r\'); print(f.read()); ' <add> 'f.close()"' % (self.pyexe, fn), execute_in=tmpdir, **kws) <add> self.assertEqual(s, 0) <add> self.assertEqual(o, 'Hello') <add> <add> def test_basic(self): <add> with redirect_stdout(StringIO()): <add> with redirect_stderr(StringIO()): <add> if os.name == "posix": <add> self.check_posix(use_tee=0) <add> self.check_posix(use_tee=1) <add> elif os.name == "nt": <add> self.check_nt(use_tee=0) <add> self.check_nt(use_tee=1) <add> self.check_execute_in(use_tee=0) <add> self.check_execute_in(use_tee=1) <add> <add> <add>if __name__ == "__main__": <add> run_module_suite()
2
Python
Python
fix line too long in mnist_acgan
1ef28433ba6899c31f1cc3133edc1bf1def0bd35
<ide><path>examples/mnist_acgan.py <ide> def build_discriminator(): <ide> # Salimans et al., 2016 <ide> # https://arxiv.org/pdf/1606.03498.pdf (Section 3.4) <ide> soft_zero, soft_one = 0, 0.95 <del> y = np.array([soft_one] * len(image_batch) + [soft_zero] * len(image_batch)) <add> y = np.array( <add> [soft_one] * len(image_batch) + [soft_zero] * len(image_batch)) <ide> aux_y = np.concatenate((label_batch, sampled_labels), axis=0) <ide> <ide> # we don't want the discriminator to also maximize the classification
1
Javascript
Javascript
fix wrong constructor
c35c65b4778f39c0896712fdc7bde380c4577629
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL ); <ide> var properties = new THREE.WebGLProperties(); <ide> var objects = new THREE.WebGLObjects( _gl, properties, this.info ); <del> var programCache = new THREE.WebGLPrograms( this, _gl, extensions ); <add> var programCache = new THREE.WebGLPrograms( this, capabilities ); <ide> <ide> var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender ); <ide> var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
1
Python
Python
remove sentence about usage of rmsprop for rnn
2f55055a9f053b35fa721d3eb75dd07ea5a5f1e3
<ide><path>keras/optimizers.py <ide> class RMSprop(Optimizer): <ide> at their default values <ide> (except the learning rate, which can be freely tuned). <ide> <del> This optimizer is usually a good choice for recurrent <del> neural networks. <del> <ide> # Arguments <ide> lr: float >= 0. Learning rate. <ide> rho: float >= 0.
1
Ruby
Ruby
remove unused variable
e56bdf3663339336732d391b396397c1f64433cb
<ide><path>activerecord/test/cases/relation/mutation_test.rb <ide> def relation <ide> relation.uniq! :foo <ide> end <ide> <del> e = assert_deprecated(/use distinct_value instead/) do <add> assert_deprecated(/use distinct_value instead/) do <ide> assert_equal :foo, relation.uniq_value # deprecated access <ide> end <ide>
1
Javascript
Javascript
remove clamp-to-zero from webgl morph target code
69aba65161ad30890cb882dfdcccdd5d65e529be
<ide><path>src/renderers/webgl/WebGLMorphtargets.js <ide> function WebGLMorphtargets( gl ) { <ide> <ide> } <ide> <del> var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : Math.max(0, 1 - morphInfluencesSum); <add> var morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; <ide> <ide> program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence ); <ide> program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
1
Javascript
Javascript
improve color detection
f871c80a6d4a78438d6e19ec9ef812d53fc75c92
<ide><path>lib/internal/tty.js <ide> const COLORS_16m = 24; <ide> // Copyright (C) 1996-2016 Free Software Foundation, Inc. Copying and <ide> // distribution of this file, with or without modification, are permitted <ide> // provided the copyright notice and this notice are preserved. <del>const TERM_ENVS = [ <del> 'eterm', <del> 'cons25', <del> 'console', <del> 'cygwin', <del> 'dtterm', <del> 'gnome', <del> 'hurd', <del> 'jfbterm', <del> 'konsole', <del> 'kterm', <del> 'mlterm', <del> 'putty', <del> 'st', <del> 'terminator' <del>]; <add>const TERM_ENVS = { <add> 'eterm': COLORS_16, <add> 'cons25': COLORS_16, <add> 'console': COLORS_16, <add> 'cygwin': COLORS_16, <add> 'dtterm': COLORS_16, <add> 'gnome': COLORS_16, <add> 'hurd': COLORS_16, <add> 'jfbterm': COLORS_16, <add> 'konsole': COLORS_16, <add> 'kterm': COLORS_16, <add> 'mlterm': COLORS_16, <add> 'putty': COLORS_16, <add> 'st': COLORS_16, <add> // https://github.com/da-x/rxvt-unicode/tree/v9.22-with-24bit-color <add> 'rxvt-unicode-24bit': COLORS_16m, <add> // https://gist.github.com/XVilka/8346728#gistcomment-2823421 <add> 'terminator': COLORS_16m <add>}; <ide> <ide> const TERM_ENVS_REG_EXP = [ <ide> /ansi/, <ide> const TERM_ENVS_REG_EXP = [ <ide> // https://github.com/chalk/supports-color, <ide> // https://github.com/isaacs/color-support. <ide> function getColorDepth(env = process.env) { <del> if (env.NODE_DISABLE_COLORS || env.TERM === 'dumb' && !env.COLORTERM) { <add> if (env.NODE_DISABLE_COLORS || env.TERM === 'dumb') { <ide> return COLORS_2; <ide> } <ide> <ide> function getColorDepth(env = process.env) { <ide> } <ide> return COLORS_16m; <ide> case 'HyperTerm': <del> case 'Hyper': <ide> case 'MacTerm': <ide> return COLORS_16m; <ide> case 'Apple_Terminal': <ide> function getColorDepth(env = process.env) { <ide> <ide> const termEnv = env.TERM.toLowerCase(); <ide> <del> for (const term of TERM_ENVS) { <del> if (termEnv === term) { <del> return COLORS_16; <del> } <add> if (TERM_ENVS[termEnv]) { <add> return TERM_ENVS[termEnv]; <ide> } <ide> for (const term of TERM_ENVS_REG_EXP) { <ide> if (term.test(termEnv)) { <ide> function getColorDepth(env = process.env) { <ide> } <ide> } <ide> <del> if (env.COLORTERM) <add> if (env.COLORTERM) { <add> if (env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit') <add> return COLORS_16m; <ide> return COLORS_16; <add> } <ide> <ide> return COLORS_2; <ide> } <ide><path>test/pseudo-tty/test-tty-get-color-depth.js <ide> const common = require('../common'); <ide> const assert = require('assert').strict; <ide> const { WriteStream } = require('tty'); <add>const { inspect } = require('util'); <ide> <ide> const fd = common.getTTYfd(); <ide> const writeStream = new WriteStream(fd); <ide> const writeStream = new WriteStream(fd); <ide> // Check different environment variables. <ide> [ <ide> [{ COLORTERM: '1' }, 4], <add> [{ COLORTERM: 'truecolor' }, 24], <add> [{ COLORTERM: '24bit' }, 24], <ide> [{ TMUX: '1' }, 8], <ide> [{ CI: '1' }, 1], <ide> [{ CI: '1', TRAVIS: '1' }, 8], <ide> const writeStream = new WriteStream(fd); <ide> [{ TERM_PROGRAM: 'iTerm.app', TERM_PROGRAM_VERSION: '3.0' }, 24], <ide> [{ TERM_PROGRAM: 'iTerm.app', TERM_PROGRAM_VERSION: '2.0' }, 8], <ide> [{ TERM_PROGRAM: 'HyperTerm' }, 24], <del> [{ TERM_PROGRAM: 'Hyper' }, 24], <add> [{ TERM_PROGRAM: 'Hyper' }, 1], <ide> [{ TERM_PROGRAM: 'MacTerm' }, 24], <ide> [{ TERM_PROGRAM: 'Apple_Terminal' }, 8], <ide> [{ TERM: 'xterm-256' }, 8], <ide> const writeStream = new WriteStream(fd); <ide> [{ TERM: 'fail' }, 1], <ide> [{ NODE_DISABLE_COLORS: '1' }, 1], <ide> [{ TERM: 'dumb' }, 1], <del> [{ TERM: 'dumb', COLORTERM: '1' }, 4], <add> [{ TERM: 'dumb', COLORTERM: '1' }, 1], <add> [{ TERM: 'terminator' }, 24], <add> [{ TERM: 'console' }, 4] <ide> ].forEach(([env, depth], i) => { <ide> const actual = writeStream.getColorDepth(env); <ide> assert.strictEqual( <ide> actual, <ide> depth, <del> `i: ${i}, expected: ${depth}, actual: ${actual}, env: ${env}` <add> `i: ${i}, expected: ${depth}, ` + <add> `actual: ${actual}, env: ${inspect(env)}` <ide> ); <ide> }); <ide>
2
Mixed
Javascript
hide the poster when play fires. closes
f980cdb1fbd6aba9967fb06190a7b2f37882131f
<ide><path>CHANGELOG.md <ide> CHANGELOG <ide> * @mmcc added a VERSION key to the videojs object ([view](https://github.com/videojs/video.js/pull/1798)) <ide> * @mmcc fixed an issue with text track hiding introduced in #1681 ([view](https://github.com/videojs/video.js/pull/1804)) <ide> * Export video.js as a named AMD module ([view](https://github.com/videojs/video.js/pull/1844)) <add>* Hide the poster when play fires ([view](https://github.com/videojs/video.js/pull/1834)) <ide> <ide> -------------------- <ide> <ide><path>src/js/player.js <ide> vjs.Player.prototype.onLoadStart = function() { <ide> } else { <ide> // reset the hasStarted state <ide> this.hasStarted(false); <del> this.one('play', function(){ <del> this.hasStarted(true); <del> }); <ide> } <ide> }; <ide> <ide> vjs.Player.prototype.onLoadedAllData; <ide> vjs.Player.prototype.onPlay = function(){ <ide> this.removeClass('vjs-paused'); <ide> this.addClass('vjs-playing'); <add> <add> // hide the poster when the user hits play <add> // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play <add> this.hasStarted(true); <ide> }; <ide> <ide> /** <ide><path>test/unit/mediafaker.js <ide> vjs.MediaFaker.prototype.volume = function(){ return 0; }; <ide> vjs.MediaFaker.prototype.muted = function(){ return false; }; <ide> vjs.MediaFaker.prototype.pause = function(){ return false; }; <ide> vjs.MediaFaker.prototype.paused = function(){ return true; }; <add>vjs.MediaFaker.prototype.play = function() { <add> this.player().trigger('play'); <add>}; <ide> vjs.MediaFaker.prototype.supportsFullScreen = function(){ return false; }; <ide> vjs.MediaFaker.prototype.buffered = function(){ return {}; }; <ide> vjs.MediaFaker.prototype.duration = function(){ return {}; }; <ide><path>test/unit/player.js <ide> test('should set and update the poster value', function(){ <ide> player.dispose(); <ide> }); <ide> <add>// hasStarted() is equivalent to the "show poster flag" in the <add>// standard, for the purpose of displaying the poster image <add>// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play <add>test('should hide the poster when play is called', function() { <add> var player = PlayerTest.makePlayer({ <add> poster: 'https://example.com/poster.jpg' <add> }); <add> <add> equal(player.hasStarted(), false, 'the show poster flag is true before play'); <add> player.play(); <add> equal(player.hasStarted(), true, 'the show poster flag is false after play'); <add> <add> player.trigger('loadstart'); <add> equal(player.hasStarted(), <add> false, <add> 'the resource selection algorithm sets the show poster flag to true'); <add> <add> player.play(); <add> equal(player.hasStarted(), true, 'the show poster flag is false after play'); <add>}); <add> <ide> test('should load a media controller', function(){ <ide> var player = PlayerTest.makePlayer({ <ide> preload: 'none',
4
Java
Java
fix @since typo
c7401dbe1f31fe0310d0edae3f7f9672b34b850a
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistration.java <ide> public InterceptorRegistration pathMatcher(PathMatcher pathMatcher) { <ide> <ide> /** <ide> * Specify an order position to be used. Default is 0. <del> * @since 4.23 <add> * @since 4.3.23 <ide> */ <ide> public InterceptorRegistration order(int order){ <ide> this.order = order;
1
Mixed
Python
fix merge conflicts
e2abb5ef2c12a57f973331eb7e0fb0b4e19419bf
<ide><path>docs/templates/getting-started/faq.md <ide> layer_output = get_3rd_layer_output([X, 0])[0] <ide> layer_output = get_3rd_layer_output([X, 1])[0] <ide> ``` <ide> <del>Another more flexible way of getting output from intermediate layers is to use the [functional API](/getting-started/functional-api-guide). <add>Another more flexible way of getting output from intermediate layers is to use the [functional API](/getting-started/functional-api-guide). For example, if you have created an autoencoder for MNIST: <add> <add>```python <add>inputs = Input(shape=(784,)) <add>encoded = Dense(32, activation='relu')(inputs) <add>decoded = Dense(784)(encoded) <add>model = Model(input=inputs, output=decoded) <add>``` <add> <add>After compiling and training the model, you can get the output of the data from the encoder like this: <add> <add>```python <add>encoder = Model(input=inputs, output=encoded) <add>X_encoded = encoder.predict(X) <add>``` <ide> <ide> --- <ide> <ide><path>docs/templates/getting-started/functional-api-guide.md <ide> from keras.layers import merge, Convolution2D, Input <ide> <ide> # input tensor for a 3-channel 256x256 image <ide> x = Input(shape=(3, 256, 256)) <del># 3x3 conv with 16 output channels <del>y = Convolution2D(16, 3, 3, border_mode='same') <add># 3x3 conv with 3 output channels (same as input channels) <add>y = Convolution2D(3, 3, 3, border_mode='same') <ide> # this returns x + y. <ide> z = merge([x, y], mode='sum') <ide> ``` <ide><path>examples/mnist_siamese_graph.py <ide> def euclidean_distance(vects): <ide> <ide> def eucl_dist_output_shape(shapes): <ide> shape1, shape2 = shapes <del> return shape1 <add> return (shape1[0], 1) <ide> <ide> <ide> def contrastive_loss(y_true, y_pred): <ide><path>keras/backend/theano_backend.py <ide> from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams <ide> from theano.tensor.signal import pool <ide> from theano.tensor.nnet import conv3d2d <del>from theano.sandbox import softsign as T_softsign <add>try: <add> from theano.tensor.nnet.nnet import softsign as T_softsign <add>except ImportError: <add> from theano.sandbox.softsign import softsign as T_softsign <ide> import inspect <ide> import numpy as np <ide> from .common import _FLOATX, _EPSILON <ide> def softplus(x): <ide> <ide> <ide> def softsign(x): <del> return T_softsign.softsign(x) <add> return T_softsign(x) <ide> <ide> <ide> def categorical_crossentropy(output, target, from_logits=False): <ide><path>keras/datasets/cifar.py <ide> from __future__ import absolute_import <ide> import sys <ide> from six.moves import cPickle <del>from six.moves import range <ide> <ide> <ide> def load_batch(fpath, label_key='labels'): <ide><path>keras/engine/topology.py <ide> def save_weights(self, filepath, overwrite=False): <ide> for layer in flattened_layers: <ide> g = f.create_group(layer.name) <ide> symbolic_weights = layer.trainable_weights + layer.non_trainable_weights <del> weight_values = layer.get_weights() <add> weight_values = K.batch_get_value(symbolic_weights) <ide> weight_names = [] <ide> for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)): <ide> if hasattr(w, 'name') and w.name: <ide><path>keras/layers/embeddings.py <ide> class Embedding(Layer): <ide> model = Sequential() <ide> model.add(Embedding(1000, 64, input_length=10)) <ide> # the model will take as input an integer matrix of size (batch, input_length). <del> # the largest integer (i.e. word index) in the input should be no larger than 1000 (vocabulary size). <add> # the largest integer (i.e. word index) in the input should be no larger than 999 (vocabulary size). <ide> # now model.output_shape == (None, 10, 64), where None is the batch dimension. <ide> <ide> input_array = np.random.randint(1000, size=(32, 10)) <ide> class Embedding(Layer): <ide> ``` <ide> <ide> # Arguments <del> input_dim: int >= 0. Size of the vocabulary, ie. <add> input_dim: int > 0. Size of the vocabulary, ie. <ide> 1 + maximum integer index occurring in the input data. <ide> output_dim: int >= 0. Dimension of the dense embedding. <ide> init: name of initialization function for the weights <ide> class Embedding(Layer): <ide> This is useful for [recurrent layers](recurrent.md) which may take <ide> variable length input. If this is `True` then all subsequent layers <ide> in the model need to support masking or an exception will be raised. <add> If mask_zero is set to True, as a consequence, index 0 cannot be <add> used in the vocabulary (input_dim should equal |vocabulary| + 2). <ide> input_length: Length of input sequences, when it is constant. <ide> This argument is required if you are going to connect <ide> `Flatten` then `Dense` layers upstream <ide><path>keras/layers/normalization.py <ide> def call(self, x, mask=None): <ide> std = K.mean(K.square(x - brodcast_mean) + self.epsilon, axis=reduction_axes) <ide> std = K.sqrt(std) <ide> brodcast_std = K.reshape(std, broadcast_shape) <del> mean_update = self.momentum * self.running_mean + (1-self.momentum) * mean <del> std_update = self.momentum * self.running_std + (1-self.momentum) * std <add> mean_update = self.momentum * self.running_mean + (1 - self.momentum) * mean <add> std_update = self.momentum * self.running_std + (1 - self.momentum) * std <ide> self.updates = [(self.running_mean, mean_update), <ide> (self.running_std, std_update)] <ide> x_normed = (x - brodcast_mean) / (brodcast_std + self.epsilon) <ide><path>keras/layers/recurrent.py <ide> class Recurrent(Layer): <ide> is always unrolled, so this argument does not do anything. <ide> Unrolling can speed-up a RNN, although it tends to be more memory-intensive. <ide> Unrolling is only suitable for short sequences. <del> consume_less: one of "cpu", "mem", or "gpu". <del> Note that "gpu" mode is only available for LSTM. <del> <add> consume_less: one of "cpu", "mem", or "gpu" (LSTM/GRU only). <ide> If set to "cpu", the RNN will use <ide> an implementation that uses fewer, larger matrix products, <ide> thus running faster on CPU but consuming more memory. <ide> class Recurrent(Layer): <ide> but smaller ones, thus running slower (may actually be faster on GPU) <ide> while consuming less memory. <ide> <del> If set to "gpu" (LSTM only), the LSTM will combine the input gate, <add> If set to "gpu" (LSTM/GRU only), the RNN will combine the input gate, <ide> the forget gate and the output gate into a single matrix, <ide> enabling more time-efficient parallelization on the GPU. Note: RNN <ide> dropout must be shared for all gates, resulting in a slightly <ide> def __init__(self, output_dim, <ide> <ide> def build(self, input_shape): <ide> self.input_spec = [InputSpec(shape=input_shape)] <del> input_dim = input_shape[2] <del> self.input_dim = input_dim <add> self.input_dim = input_shape[2] <add> <add> if self.stateful: <add> self.reset_states() <add> else: <add> # initial states: all-zero tensor of shape (output_dim) <add> self.states = [None] <add> <add> if self.consume_less == 'gpu': <add> <add> self.W = self.init((self.input_dim, 3 * self.output_dim), <add> name='{}_W'.format(self.name)) <add> self.U = self.inner_init((self.output_dim, 3 * self.output_dim), <add> name='{}_U'.format(self.name)) <add> <add> self.b = K.variable(np.hstack((np.zeros(self.output_dim), <add> np.zeros(self.output_dim), <add> np.zeros(self.output_dim))), <add> name='{}_b'.format(self.name)) <add> <add> self.trainable_weights = [self.W, self.U, self.b] <add> else: <ide> <del> self.W_z = self.init((input_dim, self.output_dim), <del> name='{}_W_z'.format(self.name)) <del> self.U_z = self.inner_init((self.output_dim, self.output_dim), <del> name='{}_U_z'.format(self.name)) <del> self.b_z = K.zeros((self.output_dim,), name='{}_b_z'.format(self.name)) <add> self.W_z = self.init((self.input_dim, self.output_dim), <add> name='{}_W_z'.format(self.name)) <add> self.U_z = self.inner_init((self.output_dim, self.output_dim), <add> name='{}_U_z'.format(self.name)) <add> self.b_z = K.zeros((self.output_dim,), name='{}_b_z'.format(self.name)) <ide> <del> self.W_r = self.init((input_dim, self.output_dim), <del> name='{}_W_r'.format(self.name)) <del> self.U_r = self.inner_init((self.output_dim, self.output_dim), <del> name='{}_U_r'.format(self.name)) <del> self.b_r = K.zeros((self.output_dim,), name='{}_b_r'.format(self.name)) <add> self.W_r = self.init((self.input_dim, self.output_dim), <add> name='{}_W_r'.format(self.name)) <add> self.U_r = self.inner_init((self.output_dim, self.output_dim), <add> name='{}_U_r'.format(self.name)) <add> self.b_r = K.zeros((self.output_dim,), name='{}_b_r'.format(self.name)) <ide> <del> self.W_h = self.init((input_dim, self.output_dim), <del> name='{}_W_h'.format(self.name)) <del> self.U_h = self.inner_init((self.output_dim, self.output_dim), <del> name='{}_U_h'.format(self.name)) <del> self.b_h = K.zeros((self.output_dim,), name='{}_b_h'.format(self.name)) <add> self.W_h = self.init((self.input_dim, self.output_dim), <add> name='{}_W_h'.format(self.name)) <add> self.U_h = self.inner_init((self.output_dim, self.output_dim), <add> name='{}_U_h'.format(self.name)) <add> self.b_h = K.zeros((self.output_dim,), name='{}_b_h'.format(self.name)) <add> <add> self.trainable_weights = [self.W_z, self.U_z, self.b_z, <add> self.W_r, self.U_r, self.b_r, <add> self.W_h, self.U_h, self.b_h] <add> <add> self.W = K.concatenate([self.W_z, self.W_r, self.W_h]) <add> self.U = K.concatenate([self.U_z, self.U_r, self.U_h]) <add> self.b = K.concatenate([self.b_z, self.b_r, self.b_h]) <ide> <ide> self.regularizers = [] <ide> if self.W_regularizer: <del> self.W_regularizer.set_param(K.concatenate([self.W_z, <del> self.W_r, <del> self.W_h])) <add> self.W_regularizer.set_param(self.W) <ide> self.regularizers.append(self.W_regularizer) <ide> if self.U_regularizer: <del> self.U_regularizer.set_param(K.concatenate([self.U_z, <del> self.U_r, <del> self.U_h])) <add> self.U_regularizer.set_param(self.U) <ide> self.regularizers.append(self.U_regularizer) <ide> if self.b_regularizer: <del> self.b_regularizer.set_param(K.concatenate([self.b_z, <del> self.b_r, <del> self.b_h])) <add> self.b_regularizer.set_param(self.b) <ide> self.regularizers.append(self.b_regularizer) <ide> <del> self.trainable_weights = [self.W_z, self.U_z, self.b_z, <del> self.W_r, self.U_r, self.b_r, <del> self.W_h, self.U_h, self.b_h] <del> if self.stateful: <del> self.reset_states() <del> else: <del> # initial states: all-zero tensor of shape (output_dim) <del> self.states = [None] <del> <ide> if self.initial_weights is not None: <ide> self.set_weights(self.initial_weights) <ide> del self.initial_weights <ide> def step(self, x, states): <ide> B_U = states[1] # dropout matrices for recurrent units <ide> B_W = states[2] <ide> <del> if self.consume_less == 'cpu': <del> x_z = x[:, :self.output_dim] <del> x_r = x[:, self.output_dim: 2 * self.output_dim] <del> x_h = x[:, 2 * self.output_dim:] <del> else: <del> x_z = K.dot(x * B_W[0], self.W_z) + self.b_z <del> x_r = K.dot(x * B_W[1], self.W_r) + self.b_r <del> x_h = K.dot(x * B_W[2], self.W_h) + self.b_h <add> if self.consume_less == 'gpu': <add> <add> matrix_x = K.dot(x * B_W[0], self.W) + self.b <add> matrix_inner = K.dot(h_tm1 * B_U[0], self.U[:, :2 * self.output_dim]) <add> <add> x_z = matrix_x[:, :self.output_dim] <add> x_r = matrix_x[:, self.output_dim: 2 * self.output_dim] <add> inner_z = matrix_inner[:, :self.output_dim] <add> inner_r = matrix_inner[:, self.output_dim: 2 * self.output_dim] <add> <add> z = self.inner_activation(x_z + inner_z) <add> r = self.inner_activation(x_r + inner_r) <ide> <del> z = self.inner_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z)) <del> r = self.inner_activation(x_r + K.dot(h_tm1 * B_U[1], self.U_r)) <add> x_h = matrix_x[:, 2 * self.output_dim:] <add> inner_h = K.dot(r * h_tm1 * B_U[0], self.U[:, 2 * self.output_dim:]) <add> hh = self.activation(x_h + inner_h) <add> else: <add> if self.consume_less == 'cpu': <add> x_z = x[:, :self.output_dim] <add> x_r = x[:, self.output_dim: 2 * self.output_dim] <add> x_h = x[:, 2 * self.output_dim:] <add> elif self.consume_less == 'mem': <add> x_z = K.dot(x * B_W[0], self.W_z) + self.b_z <add> x_r = K.dot(x * B_W[1], self.W_r) + self.b_r <add> x_h = K.dot(x * B_W[2], self.W_h) + self.b_h <add> else: <add> raise Exception('Unknown `consume_less` mode.') <add> z = self.inner_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z)) <add> r = self.inner_activation(x_r + K.dot(h_tm1 * B_U[1], self.U_r)) <ide> <del> hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.U_h)) <add> hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.U_h)) <ide> h = z * h_tm1 + (1 - z) * hh <ide> return h, [h] <ide> <ide><path>keras/models.py <ide> <ide> def model_from_config(config, custom_objects={}): <ide> from keras.utils.layer_utils import layer_from_config <add> if isinstance(config, list): <add> raise Exception('model_fom_config expects a dictionary.' <add> 'To load an old-style config use the appropiate' <add> '`load_config` method on Sequential or Graph') <ide> return layer_from_config(config, custom_objects=custom_objects) <ide> <ide> <ide> def predict_generator(self, generator, val_samples, max_q_size=10): <ide> <ide> def get_config(self): <ide> '''Returns the model configuration <del> as a Python dictionary. <add> as a Python list. <ide> ''' <ide> config = [] <ide> if self.layers[0].__class__.__name__ == 'Merge': <ide><path>keras/preprocessing/image.py <ide> def reset(self): <ide> self.batch_index = 0 <ide> <ide> def _flow_index(self, N, batch_size=32, shuffle=False, seed=None): <add> # ensure self.batch_index is 0 <add> self.reset() <add> <ide> while 1: <del> index_array = np.arange(N) <ide> if self.batch_index == 0: <add> index_array = np.arange(N) <ide> if shuffle: <ide> if seed is not None: <ide> np.random.seed(seed + self.total_batches_seen) <ide><path>keras/wrappers/scikit_learn.py <ide> import copy <ide> import inspect <ide> import types <del>import numpy as np <ide> <ide> from ..utils.np_utils import to_categorical <ide> from ..models import Sequential
12
Javascript
Javascript
fix require of performancenow
b01feb41d844755b235c32d3f9576a5d2e02e0e0
<ide><path>Libraries/Experimental/IncrementalExample.js <ide> const IncrementalPresenter = require('IncrementalPresenter'); <ide> const JSEventLoopWatchdog = require('JSEventLoopWatchdog'); <ide> const StaticContainer = require('StaticContainer.react'); <ide> <del>const performanceNow = require('performanceNow'); <add>const performanceNow = require('fbjs/lib/performanceNow'); <ide> <ide> InteractionManager.setDeadline(1000); <ide> JSEventLoopWatchdog.install({thresholdMS: 200}); <ide><path>Libraries/Interaction/JSEventLoopWatchdog.js <ide> */ <ide> 'use strict'; <ide> <del>const performanceNow = require('performanceNow'); <add>const performanceNow = require('fbjs/lib/performanceNow'); <ide> <ide> type Handler = { <ide> onIterate?: () => void,
2
Text
Text
update podfile documentation for rn >= 0.42.0
6336e4d41eccbe83212db88d00a73450f8353d3b
<ide><path>docs/IntegrationWithExistingApps.md <ide> target 'NumberTileGame' do <ide> 'RCTWebSocket', # needed for debugging <ide> # Add any other subspecs you want to use in your project <ide> ] <add> # Explicitly include Yoga if you are using RN >= 0.42.0 <add> pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga" <ide> <ide> end <ide> ``` <ide> target 'swift-2048' do <ide> 'RCTWebSocket', # needed for debugging <ide> # Add any other subspecs you want to use in your project <ide> ] <add> # Explicitly include Yoga if you are using RN >= 0.42.0 <add> pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga" <ide> <ide> end <ide> ```
1
Javascript
Javascript
apply suggestions from code review
05cf60677b0cdac47ce6b860cbb7b41957a2cbba
<ide><path>src/Angular.js <ide> function bindJQuery() { <ide> * @description <ide> * Restores the pre-1.8 behavior of jqLite that turns XHTML-like strings like <ide> * `<div /><span />` to `<div></div><span></span>` instead of `<div><span></span></div>`. <del> * The new behavior is a security fix so if you use this method, please try to adjust <del> * to the change & remove the call as soon as possible. <add> * The new behavior is a security fix. Thus, if you need to call this function, please try to adjust <add> * your code for this change and remove your use of this function as soon as possible. <ide> <del> * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read <add> * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the <ide> * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details <ide> * about the workarounds. <ide> */ <ide><path>src/jqLite.js <ide> * ```js <ide> * angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement(); <ide> * ``` <del> * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read <add> * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the <ide> * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details <ide> * about the workarounds. <ide> * <ide> wrapMap.th = wrapMap.td; <ide> <ide> // Support: IE <10 only <ide> // IE 9 requires an option wrapper & it needs to have the whole table structure <del>// set up up front; assigning `"<td></td>"` to `tr.innerHTML` doesn't work, etc. <add>// set up in advance; assigning `"<td></td>"` to `tr.innerHTML` doesn't work, etc. <ide> var wrapMapIE9 = { <ide> option: [1, '<select multiple="multiple">', '</select>'], <ide> _default: [0, '', '']
2
PHP
PHP
support serializable objects
1d7fa4dce39703c819e86af1fd26d685dfdf9a8b
<ide><path>src/Log/Engine/BaseLog.php <ide> use Cake\Core\InstanceConfigTrait; <ide> use JsonSerializable; <ide> use Psr\Log\AbstractLogger; <add>use Serializable; <ide> <ide> /** <ide> * Base log engine class. <ide> protected function _format(string $message, array $context = []): string <ide> continue; <ide> } <ide> <add> if ($value instanceof Serializable) { <add> $replacements['{' . $key . '}'] = $value->serialize(); <add> continue; <add> } <add> <ide> if (method_exists($value, 'toArray')) { <ide> $replacements['{' . $key . '}'] = print_r($value->toArray(), true); <ide> continue; <ide><path>tests/TestCase/Log/Engine/BaseLogTest.php <ide> */ <ide> namespace Cake\Test\TestCase\Log\Engine; <ide> <add>use ArrayObject; <ide> use Cake\ORM\Entity; <ide> use Cake\TestSuite\TestCase; <ide> use Psr\Log\LogLevel; <ide> public function testPlaceHoldersInMessage() <ide> 'bool' => true, <ide> 'json' => new Entity(['foo' => 'bar']), <ide> 'array' => ['arr'], <add> 'serializable' => new ArrayObject(['x' => 'y']), <ide> 'obj' => function () { <ide> }, <ide> ]; <ide> $this->logger->log( <ide> LogLevel::INFO, <del> '1: {string}, 2: {bool}, 3: {json}, 4: {not a placeholder}, 5: {array}, 6: {obj}, 8: {valid-ph-not-in-context}', <add> '1: {string}, 2: {bool}, 3: {json}, 4: {not a placeholder}, 5: {array}, ' <add> . '6: {serializable} 7: {obj}, 8: {valid-ph-not-in-context}', <ide> $context <ide> ); <ide> <ide> public function testPlaceHoldersInMessage() <ide> $this->assertStringContainsString("3: {\n \"foo\": \"bar\"\n}", $message); <ide> $this->assertStringContainsString('4: {not a placeholder}', $message); <ide> $this->assertStringContainsString("5: Array\n(\n [0] => arr\n)", $message); <del> $this->assertStringContainsString("6: Closure Object", $message); <add> $this->assertStringContainsString('6: x:i:0;a:1:{s:1:"x";s:1:"y";};m:a:0:{}', $message); <add> $this->assertStringContainsString("7: Closure Object", $message); <ide> $this->assertStringContainsString('8: {valid-ph-not-in-context}', $message); <ide> } <ide> }
2
Ruby
Ruby
improve performance of ar object instantiation
8fee923888192a658d8823b31e77ed0683dfd665
<ide><path>activerecord/lib/active_record/attribute_set/builder.rb <ide> def initialize(types) <ide> end <ide> <ide> def build_from_database(values = {}, additional_types = {}) <del> attributes = build_attributes_from_values(values, additional_types) <add> build_from_database_pairs(values.keys, values.values, additional_types) <add> end <add> <add> def build_from_database_pairs(columns = [], values = [], additional_types = {}) <add> attributes = build_attributes_from_values(columns, values, additional_types) <ide> add_uninitialized_attributes(attributes) <ide> AttributeSet.new(attributes) <ide> end <ide> <ide> private <ide> <del> def build_attributes_from_values(values, additional_types) <del> values.each_with_object({}) do |(name, value), hash| <add> def build_attributes_from_values(columns, values, additional_types) <add> # We are performing manual iteration here as this method is a performance <add> # hotspot <add> hash = {} <add> index = 0 <add> length = columns.length <add> <add> while index < length <add> name = columns[index] <add> value = values[index] <ide> type = additional_types.fetch(name, types[name]) <ide> hash[name] = Attribute.from_database(name, value, type) <add> index += 1 <ide> end <add> <add> hash <ide> end <ide> <ide> def add_uninitialized_attributes(attributes) <ide><path>activerecord/lib/active_record/inheritance.rb <ide> def compute_type(type_name) <ide> # record instance. For single-table inheritance, we check the record <ide> # for a +type+ column and return the corresponding class. <ide> def discriminate_class_for_record(record) <del> if using_single_table_inheritance?(record) <del> find_sti_class(record[inheritance_column]) <add> discriminate_class_for_value(record[inheritance_column]) <add> end <add> <add> def discriminate_class_for_value(value) <add> if using_single_table_inheritance?(value) <add> find_sti_class(value) <ide> else <ide> super <ide> end <ide> end <ide> <del> def using_single_table_inheritance?(record) <del> record[inheritance_column].present? && columns_hash.include?(inheritance_column) <add> def using_single_table_inheritance?(value) <add> value.present? && columns_hash.include?(inheritance_column) <ide> end <ide> <ide> def find_sti_class(type_name) <ide><path>activerecord/lib/active_record/persistence.rb <ide> def create!(attributes = nil, &block) <ide> # how this "single-table" inheritance mapping is implemented. <ide> def instantiate(attributes, column_types = {}) <ide> klass = discriminate_class_for_record(attributes) <del> attributes = klass.attributes_builder.build_from_database(attributes, column_types) <del> klass.allocate.init_with('attributes' => attributes, 'new_record' => false) <add> klass.instantiate_pairs(attributes.keys, attributes.values, column_types) <add> end <add> <add> def instantiate_pairs(columns, values, column_types = {}) # :nodoc: <add> attributes = attributes_builder.build_from_database_pairs(columns, values, column_types) <add> allocate.init_with('attributes' => attributes, 'new_record' => false) <add> end <add> <add> def instantiate_result_set(result_set, column_types = {}) # :nodoc: <add> inheritance_column_index = inheritance_column && result_set.columns.find_index(inheritance_column) <add> <add> result_set.each_pair.map do |columns, values| <add> inheritance_value = inheritance_column_index && values[inheritance_column_index] <add> klass = discriminate_class_for_value(inheritance_value) <add> klass.instantiate_pairs(columns, values, column_types) <add> end <ide> end <ide> <ide> private <ide> # Called by +instantiate+ to decide which class to use for a new <ide> # record instance. <ide> # <del> # See +ActiveRecord::Inheritance#discriminate_class_for_record+ for <add> # See +ActiveRecord::Inheritance#discriminate_class_for_value+ for <ide> # the single-table inheritance discriminator. <add> def discriminate_class_for_value(*) <add> self <add> end <add> <ide> def discriminate_class_for_record(record) <ide> self <ide> end <add> <add> def inheritance_column <add> nil <add> end <ide> end <ide> <ide> # Returns true if this object hasn't been saved yet -- that is, a record <ide><path>activerecord/lib/active_record/querying.rb <ide> def find_by_sql(sql, binds = []) <ide> } <ide> <ide> message_bus.instrument('instantiation.active_record', payload) do <del> result_set.map { |record| instantiate(record, column_types) } <add> instantiate_result_set(result_set, column_types) <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/result.rb <ide> def each <ide> end <ide> end <ide> <add> def each_pair <add> return to_enum(__method__) unless block_given? <add> <add> columns = @columns.map { |c| c.dup.freeze } <add> @rows.each do |row| <add> yield columns, row <add> end <add> end <add> <ide> def to_hash <ide> hash_rows <ide> end
5
Javascript
Javascript
fix borderexample for dynamiccolorios
f6d0f9deaccdc53114d47b8a69c49fda7cb1f8e1
<ide><path>packages/rn-tester/js/examples/Border/BorderExample.js <ide> const { <ide> StyleSheet, <ide> View, <ide> PlatformColor, <add> Platform, <ide> DynamicColorIOS, <ide> } = require('react-native'); <ide> <ide> const styles = StyleSheet.create({ <ide> }, <ide> border15: { <ide> borderWidth: 10, <del> borderColor: PlatformColor('systemGray4', 'holo_orange_dark'), <add> borderColor: PlatformColor( <add> 'systemGray4', <add> '@android:color/holo_orange_dark', <add> ), <ide> }, <ide> border16: { <ide> borderWidth: 10, <del> borderColor: DynamicColorIOS({light: 'magenta', dark: 'cyan'}), <add> borderColor: <add> Platform.OS === 'ios' <add> ? DynamicColorIOS({light: 'magenta', dark: 'cyan'}) <add> : 'black', <ide> }, <ide> }); <ide>
1
Python
Python
add pronic number implementation
076193eefa161a2030ca4b1ee60b285d4a50e4c6
<ide><path>maths/pronic_number.py <add>""" <add>== Pronic Number == <add>A number n is said to be a Proic number if <add>there exists an integer m such that n = m * (m + 1) <add> <add>Examples of Proic Numbers: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90, 110 ... <add>https://en.wikipedia.org/wiki/Pronic_number <add>""" <add> <add># Author : Akshay Dubey (https://github.com/itsAkshayDubey) <add> <add> <add>def is_pronic(number: int) -> bool: <add> """ <add> # doctest: +NORMALIZE_WHITESPACE <add> This functions takes an integer number as input. <add> returns True if the number is pronic. <add> >>> is_pronic(-1) <add> False <add> >>> is_pronic(0) <add> True <add> >>> is_pronic(2) <add> True <add> >>> is_pronic(5) <add> False <add> >>> is_pronic(6) <add> True <add> >>> is_pronic(8) <add> False <add> >>> is_pronic(30) <add> True <add> >>> is_pronic(32) <add> False <add> >>> is_pronic(2147441940) <add> True <add> >>> is_pronic(9223372033963249500) <add> True <add> >>> is_pronic(6.0) <add> Traceback (most recent call last): <add> ... <add> TypeError: Input value of [number=6.0] must be an integer <add> """ <add> if not isinstance(number, int): <add> raise TypeError(f"Input value of [number={number}] must be an integer") <add> if number < 0 or number % 2 == 1: <add> return False <add> number_sqrt = int(number**0.5) <add> return number == number_sqrt * (number_sqrt + 1) <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod()
1
PHP
PHP
remove debug code
3fac8f913402880af9578766a0a9242c6e6649ee
<ide><path>src/ORM/TableRegistry.php <ide> public static function remove($alias) <ide> static::$_fallbacked[$alias] <ide> ); <ide> } <del> <del> public static function keys() { return array_keys(static::$_instances); } <ide> }
1
Text
Text
fix image spec json example
715e78631d727ac6db9f08a8537a82aa56919f08
<ide><path>image/spec/v1.1.md <ide> Here is an example image JSON file: <ide> "/var/job-result-data": {}, <ide> "/var/log/my-app-logs": {}, <ide> }, <del> "WorkingDir": "/home/alice", <add> "WorkingDir": "/home/alice" <ide> }, <ide> "rootfs": { <ide> "diff_ids": [ <ide><path>image/spec/v1.2.md <ide> Here is an example image JSON file: <ide> "/var/job-result-data": {}, <ide> "/var/log/my-app-logs": {}, <ide> }, <del> "WorkingDir": "/home/alice", <add> "WorkingDir": "/home/alice" <ide> }, <ide> "rootfs": { <ide> "diff_ids": [ <ide><path>image/spec/v1.md <ide> Here is an example image JSON file: <ide> "/var/job-result-data": {}, <ide> "/var/log/my-app-logs": {}, <ide> }, <del> "WorkingDir": "/home/alice", <add> "WorkingDir": "/home/alice" <ide> } <ide> } <ide> ```
3
PHP
PHP
add tests for generating month selects
ed75f986b72fe371c33ed28d654842842582d050
<ide><path>src/View/Input/DateTime.php <ide> public function render(array $data) { <ide> <ide> $templateOptions = []; <ide> foreach ($this->_selects as $select) { <del> if ($data[$select] !== false) { <del> $method = $select . 'Select'; <del> $data[$select]['name'] = $data['name'] . "[" . $select . "]"; <del> $data[$select]['val'] = $selected[$select]; <del> <del> if (!isset($data[$select]['empty'])) { <del> $data[$select]['empty'] = $data['empty']; <del> } <del> if (!isset($data[$select]['disabled'])) { <del> $data[$select]['disabled'] = $data['disabled']; <del> } <add> if ($data[$select] === false || $data[$select] === null) { <add> $templateOptions[$select] = ''; <add> unset($data[$select]); <add> continue; <add> } <add> $method = $select . 'Select'; <add> $data[$select]['name'] = $data['name'] . "[" . $select . "]"; <add> $data[$select]['val'] = $selected[$select]; <ide> <del> $templateOptions[$select] = $this->{$method}($data[$select]); <add> if (!isset($data[$select]['empty'])) { <add> $data[$select]['empty'] = $data['empty']; <add> } <add> if (!isset($data[$select]['disabled'])) { <add> $data[$select]['disabled'] = $data['disabled']; <ide> } <add> $templateOptions[$select] = $this->{$method}($data[$select]); <ide> unset($data[$select]); <ide> } <ide> unset($data['name'], $data['empty'], $data['disabled'], $data['val']); <ide><path>tests/TestCase/View/Input/DateTimeTest.php <ide> public function setUp() { <ide> 'selectMultiple' => '<select name="{{name}}[]" multiple="multiple"{{attrs}}>{{content}}</select>', <ide> 'option' => '<option value="{{value}}"{{attrs}}>{{text}}</option>', <ide> 'optgroup' => '<optgroup label="{{label}}"{{attrs}}>{{content}}</optgroup>', <del> 'dateWidget' => '{{year}}-{{month}}-{{day}} {{hour}}:{{minute}}:{{second}}' <add> 'dateWidget' => '{{year}}{{month}}{{day}}{{hour}}{{minute}}{{second}}' <ide> ]; <ide> $this->templates = new StringTemplate($templates); <ide> $this->selectBox = new SelectBox($this->templates); <ide> public function testRenderYearWidgetValueOutOfBounds() { <ide> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test rendering the month widget <add> * <add> * @return void <add> */ <ide> public function testRenderMonthWidget() { <del> $this->markTestIncomplete(); <add> $now = new \DateTime('2010-09-01 12:00:00'); <add> $result = $this->DateTime->render([ <add> 'name' => 'date', <add> 'year' => false, <add> 'day' => false, <add> 'hour' => false, <add> 'minute' => false, <add> 'second' => false, <add> 'val' => $now, <add> ]); <add> $expected = [ <add> 'select' => ['name' => 'date[month]'], <add> ['option' => ['value' => '01']], '01', '/option', <add> ['option' => ['value' => '02']], '02', '/option', <add> ['option' => ['value' => '03']], '03', '/option', <add> ['option' => ['value' => '04']], '04', '/option', <add> ['option' => ['value' => '05']], '05', '/option', <add> ['option' => ['value' => '06']], '06', '/option', <add> ['option' => ['value' => '07']], '07', '/option', <add> ['option' => ['value' => '08']], '08', '/option', <add> ['option' => ['value' => '09', 'selected' => 'selected']], '09', '/option', <add> ['option' => ['value' => '10']], '10', '/option', <add> ['option' => ['value' => '11']], '11', '/option', <add> ['option' => ['value' => '12']], '12', '/option', <add> '/select', <add> ]; <add> $this->assertTags($result, $expected); <ide> } <ide> <add>/** <add> * Test rendering month widget with names. <add> * <add> * @return void <add> */ <ide> public function testRenderMonthWidgetWithNames() { <del> $this->markTestIncomplete(); <add> $now = new \DateTime('2010-09-01 12:00:00'); <add> $result = $this->DateTime->render([ <add> 'name' => 'date', <add> 'year' => false, <add> 'day' => false, <add> 'hour' => false, <add> 'minute' => false, <add> 'second' => false, <add> 'month' => ['data-foo' => 'test', 'names' => true], <add> 'val' => $now, <add> ]); <add> $expected = [ <add> 'select' => ['name' => 'date[month]', 'data-foo' => 'test'], <add> ['option' => ['value' => '01']], 'January', '/option', <add> ['option' => ['value' => '02']], 'February', '/option', <add> ['option' => ['value' => '03']], 'March', '/option', <add> ['option' => ['value' => '04']], 'April', '/option', <add> ['option' => ['value' => '05']], 'May', '/option', <add> ['option' => ['value' => '06']], 'June', '/option', <add> ['option' => ['value' => '07']], 'July', '/option', <add> ['option' => ['value' => '08']], 'August', '/option', <add> ['option' => ['value' => '09', 'selected' => 'selected']], 'September', '/option', <add> ['option' => ['value' => '10']], 'October', '/option', <add> ['option' => ['value' => '11']], 'November', '/option', <add> ['option' => ['value' => '12']], 'December', '/option', <add> '/select', <add> ]; <add> $this->assertTags($result, $expected); <ide> } <ide> <ide> public function testRenderDayWidget() {
2
Ruby
Ruby
add os.mac? and os.linux?
c511d7d2f43369773940dbb8fb8fbe8ed2153127
<ide><path>Library/Homebrew/extend/ENV/std.rb <ide> def remove_macosxsdk version=MacOS.version <ide> end <ide> <ide> def macosxsdk version=MacOS.version <del> return unless MACOS <add> return unless OS.mac? <ide> # Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS. <ide> remove_macosxsdk <ide> version = version.to_s <ide><path>Library/Homebrew/formula_installer.rb <ide> def finish <ide> link <ide> end <ide> <del> fix_install_names <add> fix_install_names if OS.mac? <ide> <ide> record_cxx_stdlib <ide> <ide><path>Library/Homebrew/global.rb <ide> require 'extend/string' <ide> require 'extend/symbol' <ide> require 'extend/enumerable' <add>require 'os' <ide> require 'utils' <ide> require 'exceptions' <ide> require 'set' <ide> def mkpath <ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <ide> MACOS_VERSION = MACOS_FULL_VERSION[/10\.\d+/].to_f <ide> OS_VERSION = "Mac OS X #{MACOS_FULL_VERSION}" <del> MACOS = true <ide> else <ide> MACOS_FULL_VERSION = MACOS_VERSION = 0 <ide> OS_VERSION = RUBY_PLATFORM <del> MACOS = false <ide> end <ide> <ide> HOMEBREW_GITHUB_API_TOKEN = ENV["HOMEBREW_GITHUB_API_TOKEN"] <ide><path>Library/Homebrew/hardware.rb <add>require 'os' <add> <ide> class Hardware <ide> module CPU extend self <ide> INTEL_32BIT_ARCHS = [:i386].freeze <ide> def is_64_bit? <ide> end <ide> end <ide> <del> case RUBY_PLATFORM.downcase <del> when /darwin/ <add> if OS.mac? <ide> require 'os/mac/hardware' <ide> CPU.extend MacCPUs <del> when /linux/ <add> elsif OS.linux? <ide> require 'os/linux/hardware' <ide> CPU.extend LinuxCPUs <ide> else <ide><path>Library/Homebrew/keg_fix_install_names.rb <ide> class Keg <ide> def fix_install_names options={} <del> return unless MACOS <ide> mach_o_files.each do |file| <ide> install_names_for(file, options) do |id, bad_names| <ide> file.ensure_writable do <ide><path>Library/Homebrew/macos.rb <ide> def app_with_bundle_id id <ide> end <ide> <ide> def mdfind id <del> return [] unless MACOS <add> return [] unless OS.mac? <ide> (@mdfind ||= {}).fetch(id.to_s) do |key| <ide> @mdfind[key] = `/usr/bin/mdfind "kMDItemCFBundleIdentifier == '#{key}'"`.split("\n") <ide> end <ide><path>Library/Homebrew/os.rb <add>module OS <add> def self.mac? <add> /darwin/i === RUBY_PLATFORM <add> end <add> <add> def self.linux? <add> /linux/i === RUBY_PLATFORM <add> end <add>end <ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def uncached_version <ide> # This is a separate function as you can't cache the value out of a block <ide> # if return is used in the middle, which we do many times in here. <ide> <del> return "0" unless MACOS <add> return "0" unless OS.mac? <ide> <ide> # this shortcut makes version work for people who don't realise you <ide> # need to install the CLI tools <ide><path>Library/Homebrew/test/testing_env.rb <ide> RUBY_BIN = Pathname.new(RbConfig::CONFIG['bindir']) <ide> RUBY_PATH = RUBY_BIN + RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'] <ide> <del>MACOS = true <ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp <ide> MACOS_VERSION = ENV.fetch('MACOS_VERSION') { MACOS_FULL_VERSION[/10\.\d+/] }.to_f <ide> <ide><path>Library/brew.rb <ide> # it may work, but I only see pain this route and don't want to support it <ide> abort "Cowardly refusing to continue at this prefix: #{HOMEBREW_PREFIX}" <ide> end <del>if MACOS and MACOS_VERSION < 10.5 <add>if OS.mac? and MacOS.version < 10.5 <ide> abort <<-EOABORT.undent <ide> Homebrew requires Leopard or higher. For Tiger support, see: <ide> https://github.com/mistydemeo/tigerbrew
10
PHP
PHP
add hasscope to the builder
d370eb18092210adadcbdd857f97d4c1dc2784c3
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public static function hasGlobalMacro($name) <ide> return isset(static::$macros[$name]); <ide> } <ide> <add> /** <add> * Determine if the given model has a scope. <add> * <add> * @param string $method <add> * @return bool <add> */ <add> public function hasScope(string $name) <add> { <add> return $this->model->hasScope($name); <add> } <add> <ide> /** <ide> * Dynamically access builder proxies. <ide> * <ide> public function __call($method, $parameters) <ide> return call_user_func_array(static::$macros[$method], $parameters); <ide> } <ide> <del> if ($this->model->hasScope($method)) { <add> if ($this->hasScope($method)) { <ide> return $this->callScope([$this->model, 'scope' . ucfirst($method)], $parameters); <ide> } <ide>
1
Python
Python
add test for ex_list_library_drives method
ec86c955469a51bfd5a732bfce811406e725f319
<ide><path>libcloud/test/compute/test_cloudsigma_v2_0.py <ide> def test_ex_close_vnc_tunnel(self): <ide> status = self.driver.ex_close_vnc_tunnel(node=node) <ide> self.assertTrue(status) <ide> <add> def test_ex_list_library_drives(self): <add> drives = self.driver.ex_list_library_drives() <add> <add> drive = drives[0] <add> self.assertEqual(drive.name, 'IPCop 2.0.2') <add> self.assertEqual(drive.size, 1000000000) <add> self.assertEqual(drive.media, 'cdrom') <add> self.assertEqual(drive.status, 'unmounted') <add> <ide> def test_ex_list_user_drives(self): <ide> drives = self.driver.ex_list_user_drives() <ide>
1
Javascript
Javascript
implement duration in http test double
98d1110721faf0a5c62f5402e863f2c203783677
<ide><path>benchmark/_http-benchmarkers.js <ide> class TestDoubleBenchmarker { <ide> } <ide> <ide> create(options) { <add> const env = Object.assign({ <add> duration: options.duration, <add> test_url: `http://127.0.0.1:${options.port}${options.path}`, <add> }, process.env); <add> <ide> const child = child_process.fork(this.executable, { <ide> silent: true, <del> env: Object.assign({}, process.env, { <del> test_url: `http://127.0.0.1:${options.port}${options.path}` <del> }) <add> env <ide> }); <ide> return child; <ide> } <ide><path>benchmark/_test-double-benchmarker.js <ide> <ide> const http = require('http'); <ide> <del>http.get(process.env.test_url, function() { <del> console.log(JSON.stringify({ throughput: 1 })); <del>}); <add>const duration = process.env.duration || 0; <add>const url = process.env.test_url; <add> <add>const start = process.hrtime(); <add>let throughput = 0; <add> <add>function request(res) { <add> res.on('data', () => {}); <add> res.on('error', () => {}); <add> res.on('end', () => { <add> throughput++; <add> const diff = process.hrtime(start); <add> if (duration > 0 && diff[0] < duration) { <add> run(); <add> } else { <add> console.log(JSON.stringify({ throughput })); <add> } <add> }); <add>} <add> <add>function run() { <add> http.get(url, request); <add>} <add> <add>run(); <ide><path>test/sequential/test-benchmark-http.js <ide> runBenchmark('http', <ide> 'res=normal', <ide> 'type=asc' <ide> ], <del> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <add> { <add> NODEJS_BENCHMARK_ZERO_ALLOWED: 1, <add> duration: 0 <add> });
3
Javascript
Javascript
add sub-reducer support to navigationstackreducer
dcb68db758dfd8bdddeddf23c81a523a8506d7af
<ide><path>Examples/UIExplorer/NavigationExperimental/NavigationAnimatedExample.js <ide> var { <ide> } = NavigationExperimental; <ide> <ide> const NavigationBasicReducer = NavigationReducer.StackReducer({ <del> initialStates: [ <del> {key: 'First Route'} <del> ], <del> matchAction: action => action.type === 'push', <del> actionStateMap: action => ({key: action.key}), <add> getPushedReducerForAction: (action) => { <add> if (action.type === 'push') { <add> return (state) => state || {key: action.key}; <add> } <add> return null; <add> }, <add> getReducerForState: (initialState) => (state) => state || initialState, <add> initialState: { <add> key: 'AnimatedExampleStackKey', <add> index: 0, <add> children: [ <add> {key: 'First Route'}, <add> ], <add> }, <ide> }); <ide> <ide> class NavigationAnimatedExample extends React.Component { <ide><path>Examples/UIExplorer/NavigationExperimental/NavigationBasicExample.js <ide> const { <ide> } = NavigationExperimental; <ide> const StackReducer = NavigationReducer.StackReducer; <ide> <del>const NavigationBasicReducer = StackReducer({ <del> initialStates: [ <del> {key: 'first_page'} <del> ], <del> matchAction: action => true, <del> actionStateMap: action => ({key: action}), <add>const NavigationBasicReducer = NavigationReducer.StackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (action.type === 'push') { <add> return (state) => state || {key: action.key}; <add> } <add> return null; <add> }, <add> getReducerForState: (initialState) => (state) => state || initialState, <add> initialState: { <add> key: 'BasicExampleStackKey', <add> index: 0, <add> children: [ <add> {key: 'First Route'}, <add> ], <add> }, <ide> }); <ide> <ide> const NavigationBasicExample = React.createClass({ <ide> const NavigationBasicExample = React.createClass({ <ide> <NavigationExampleRow <ide> text={`Push page #${navState.children.length}`} <ide> onPress={() => { <del> onNavigate('page #' + navState.children.length); <add> onNavigate({ type: 'push', key: 'page #' + navState.children.length }); <ide> }} <ide> /> <ide> <NavigationExampleRow <ide> text="pop" <ide> onPress={() => { <del> onNavigate(StackReducer.PopAction()); <add> onNavigate(NavigationRootContainer.getBackAction()); <ide> }} <ide> /> <ide> <NavigationExampleRow <ide><path>Examples/UIExplorer/NavigationExperimental/NavigationCompositionExample.js <ide> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN <ide> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN <ide> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <del>*/ <add> * <add> * @flow <add> */ <ide> 'use strict'; <ide> <ide> const React = require('react-native'); <ide> const { <ide> const NavigationExampleRow = require('./NavigationExampleRow'); <ide> const NavigationExampleTabBar = require('./NavigationExampleTabBar'); <ide> <add>import type {NavigationParentState} from 'NavigationStateUtils'; <add> <ide> const ExampleExitAction = () => ({ <ide> isExitAction: true, <ide> }); <ide> ExampleExitAction.match = (action) => ( <ide> action && action.isExitAction === true <ide> ); <ide> <del>const ExamplePageAction = (type) => ({ <add>const PageAction = (type) => ({ <ide> type, <ide> isPageAction: true, <ide> }); <del>ExamplePageAction.match = (action) => ( <add>PageAction.match = (action) => ( <ide> action && action.isPageAction === true <ide> ); <ide> <del>const ExampleSettingsPageAction = (type) => ({ <del> ...ExamplePageAction(type), <del> isSettingsPageAction: true, <add>const ExampleProfilePageAction = (type) => ({ <add> ...PageAction(type), <add> isProfilePageAction: true, <ide> }); <del>ExampleSettingsPageAction.match = (action) => ( <del> action && action.isSettingsPageAction === true <add>ExampleProfilePageAction.match = (action) => ( <add> action && action.isProfilePageAction === true <ide> ); <ide> <del>const ExampleInfoAction = () => ExamplePageAction('InfoPage'); <add>const ExampleInfoAction = () => PageAction('InfoPage'); <ide> <del>const ExampleNotifSettingsAction = () => ExampleSettingsPageAction('NotifSettingsPage'); <add>const ExampleNotifProfileAction = () => ExampleProfilePageAction('NotifProfilePage'); <ide> <ide> const _jsInstanceUniqueId = '' + Date.now(); <ide> let _uniqueIdCount = 0; <ide> function pageStateActionMap(action) { <ide> }; <ide> } <ide> <del>function getTabActionMatcher(key) { <del> return function (action) { <del> if (!ExamplePageAction.match(action)) { <del> return false; <del> } <del> if (ExampleSettingsPageAction.match(action)) { <del> return key === 'settings'; <del> } <del> return true; <del> }; <del>} <del> <del>var ExampleTabs = [ <del> { <del> label: 'Account', <del> reducer: NavigationReducer.StackReducer({ <del> initialStates: [ <del> {type: 'AccountPage', key: 'base'} <del> ], <del> key: 'account', <del> matchAction: getTabActionMatcher('account'), <del> actionStateMap: pageStateActionMap, <add>const ExampleAppReducer = NavigationReducer.TabsReducer({ <add> key: 'AppNavigationState', <add> initialIndex: 0, <add> tabReducers: [ <add> NavigationReducer.StackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (PageAction.match(action) && !ExampleProfilePageAction.match(action)) { <add> return (state) => (state || pageStateActionMap(action)); <add> } <add> return null; <add> }, <add> initialState: { <add> key: 'notifs', <add> index: 0, <add> children: [ <add> {key: 'base', type: 'NotifsPage'}, <add> ], <add> }, <ide> }), <del> }, <del> { <del> label: 'Notifications', <del> reducer: NavigationReducer.StackReducer({ <del> initialStates: [ <del> {type: 'NotifsPage', key: 'base'} <del> ], <del> key: 'notifs', <del> matchAction: getTabActionMatcher('notifs'), <del> actionStateMap: pageStateActionMap, <add> NavigationReducer.StackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (PageAction.match(action) && !ExampleProfilePageAction.match(action)) { <add> return (state) => (state || pageStateActionMap(action)); <add> } <add> return null; <add> }, <add> initialState: { <add> key: 'settings', <add> index: 0, <add> children: [ <add> {key: 'base', type: 'SettingsPage'}, <add> ], <add> }, <ide> }), <del> }, <del> { <del> label: 'Settings', <del> reducer: NavigationReducer.StackReducer({ <del> initialStates: [ <del> {type: 'SettingsPage', key: 'base'} <del> ], <del> key: 'settings', <del> matchAction: getTabActionMatcher('settings'), <del> actionStateMap: pageStateActionMap, <add> NavigationReducer.StackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (PageAction.match(action) || ExampleProfilePageAction.match(action)) { <add> return (state) => (state || pageStateActionMap(action)); <add> } <add> return null; <add> }, <add> initialState: { <add> key: 'profile', <add> index: 0, <add> children: [ <add> {key: 'base', type: 'ProfilePage'}, <add> ], <add> }, <ide> }), <del> }, <del>]; <del> <del>const ExampleAppReducer = NavigationReducer.TabsReducer({ <del> tabReducers: ExampleTabs.map(tab => tab.reducer), <add> ], <ide> }); <ide> <ide> function stateTypeTitleMap(pageState) { <ide> switch (pageState.type) { <del> case 'AccountPage': <del> return 'Account Page'; <add> case 'ProfilePage': <add> return 'Profile Page'; <ide> case 'NotifsPage': <ide> return 'Notifications'; <ide> case 'SettingsPage': <ide> return 'Settings'; <ide> case 'InfoPage': <ide> return 'Info Page'; <del> case 'NotifSettingsPage': <del> return 'Notification Settings'; <add> case 'NotifProfilePage': <add> return 'Page in Profile'; <ide> } <ide> } <ide> <ide> class ExampleTabScreen extends React.Component { <ide> }} <ide> /> <ide> <NavigationExampleRow <del> text="Open notifs settings in settings tab" <add> text="Open a page in the profile tab" <ide> onPress={() => { <del> this.props.onNavigate(ExampleNotifSettingsAction()); <add> this.props.onNavigate(ExampleNotifProfileAction()); <ide> }} <ide> /> <ide> <NavigationExampleRow <ide> class NavigationCompositionExample extends React.Component { <ide> return ( <ide> <NavigationRootContainer <ide> reducer={ExampleAppReducer} <del> persistenceKey="NavigationCompositionExampleState" <add> persistenceKey="NavigationCompositionState" <ide> ref={navRootContainer => { this.navRootContainer = navRootContainer; }} <ide> renderNavigation={this.renderApp.bind(this)} <ide> /> <ide> ); <ide> } <del> handleBackAction() { <add> handleBackAction(): boolean { <ide> return ( <ide> this.navRootContainer && <ide> this.navRootContainer.handleNavigation(NavigationRootContainer.getBackAction()) <ide> ); <ide> } <del> renderApp(navigationState, onNavigate) { <add> renderApp(navigationState: NavigationParentState, onNavigate: Function) { <ide> if (!navigationState) { <ide> return null; <ide> } <ide><path>Examples/UIExplorer/UIExplorerNavigationReducer.js <ide> export type UIExplorerNavigationState = { <ide> }; <ide> <ide> const UIExplorerStackReducer = StackReducer({ <del> key: 'UIExplorerMainStack', <del> initialStates: [ <del> {key: 'AppList'}, <del> ], <del> initialIndex: 0, <del> matchAction: action => action.openExample && !!UIExplorerList.Modules[action.openExample], <del> actionStateMap: action => ({ key: action.openExample, }), <add> getPushedReducerForAction: (action) => { <add> if (action.type === 'UIExplorerExampleAction' && UIExplorerList.Modules[action.openExample]) { <add> return (state) => state || {key: action.openExample}; <add> } <add> return null; <add> }, <add> getReducerForState: (initialState) => (state) => state || initialState, <add> initialState: { <add> key: 'UIExplorerMainStack', <add> index: 0, <add> children: [ <add> {key: 'AppList'}, <add> ], <add> }, <ide> }); <ide> <ide> function UIExplorerNavigationReducer(lastState: ?UIExplorerNavigationState, action: any): UIExplorerNavigationState { <ide> function UIExplorerNavigationReducer(lastState: ?UIExplorerNavigationState, acti <ide> if (newStack !== lastState.stack) { <ide> return { <ide> externalExample: null, <del> stack: UIExplorerStackReducer(null, action), <add> stack: newStack, <ide> } <ide> } <ide> return lastState; <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCard.js <ide> 'use strict'; <ide> <ide> const Animated = require('Animated'); <del>const NavigationReducer = require('NavigationReducer'); <add>const NavigationRootContainer = require('NavigationRootContainer'); <ide> const NavigationContainer = require('NavigationContainer'); <ide> const PanResponder = require('PanResponder'); <ide> const Platform = require('Platform'); <ide> class NavigationCard extends React.Component { <ide> const doesPop = (xRatio + vx) > 0.45; <ide> if (doesPop) { <ide> // todo: add an action which accepts velocity of the pop action/gesture, which is caught and used by NavigationAnimatedView <del> this.props.onNavigate(NavigationReducer.StackReducer.PopAction()); <add> this.props.onNavigate(NavigationRootContainer.getBackAction()); <ide> return; <ide> } <ide> Animated.spring(this.props.position, { <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationHeader.js <ide> const Animated = require('Animated'); <ide> const Image = require('Image'); <ide> const NavigationContainer = require('NavigationContainer'); <del>const NavigationReducer = require('NavigationReducer'); <add>const NavigationRootContainer = require('NavigationRootContainer'); <ide> const React = require('react-native'); <ide> const StyleSheet = require('StyleSheet'); <ide> const Text = require('Text'); <ide> class NavigationHeader extends React.Component { <ide> ); <ide> } <ide> _handleBackPress() { <del> this.props.onNavigate(NavigationReducer.StackReducer.PopAction()); <add> this.props.onNavigate(NavigationRootContainer.getBackAction()); <ide> } <ide> } <ide> <ide><path>Libraries/NavigationExperimental/NavigationStateUtils.js <ide> function indexOf(state: NavigationState, key: string): ?number { <ide> return index; <ide> } <ide> <del>function push(state: NavigationState, newChildState: NavigationState): NavigationState { <del> const parentState = getParent(state); <del> if (!parentState) { <del> return state; <del> } <del> var lastChildren: Array<NavigationState> = parentState.children; <add>function push(state: NavigationParentState, newChildState: NavigationState): NavigationParentState { <add> var lastChildren: Array<NavigationState> = state.children; <ide> return { <del> ...parentState, <add> ...state, <ide> children: [ <ide> ...lastChildren, <ide> newChildState, <ide> function push(state: NavigationState, newChildState: NavigationState): Navigatio <ide> }; <ide> } <ide> <del>function pop(state: NavigationState): NavigationState { <del> const parentState = getParent(state); <del> if (!parentState) { <del> return state; <del> } <del> const lastChildren = parentState.children; <add>function pop(state: NavigationParentState): NavigationParentState { <add> const lastChildren = state.children; <ide> return { <del> ...parentState, <add> ...state, <ide> children: lastChildren.slice(0, lastChildren.length - 1), <ide> index: lastChildren.length - 2, <ide> }; <ide><path>Libraries/NavigationExperimental/Reducer/NavigationStackReducer.js <ide> var NavigationStateUtils = require('NavigationStateUtils'); <ide> <ide> import type { <ide> NavigationState, <add> NavigationParentState, <ide> NavigationReducer, <ide> } from 'NavigationStateUtils'; <ide> <ide> export type NavigationStackReducerAction = BackAction | { <ide> type: string, <ide> }; <ide> <del>const ActionTypes = { <del> PUSH: 'react-native/NavigationExperimental/stack-push', <del> POP: 'react-native/NavigationExperimental/stack-pop', <del> JUMP_TO: 'react-native/NavigationExperimental/stack-jumpTo', <del> JUMP_TO_INDEX: 'react-native/NavigationExperimental/stack-jumpToIndex', <del> RESET: 'react-native/NavigationExperimental/stack-reset', <del>}; <del> <del>const DEFAULT_KEY = 'NAV_STACK_DEFAULT_KEY'; <del> <del>function NavigationStackPushAction(state: NavigationState): NavigationStackReducerAction { <del> return { <del> type: ActionTypes.PUSH, <del> state, <del> }; <del>} <add>export type ReducerForStateHandler = (state: NavigationState) => NavigationReducer; <ide> <del>function NavigationStackPopAction(): NavigationStackReducerAction { <del> return { <del> type: ActionTypes.POP, <del> }; <del>} <add>export type PushedReducerForActionHandler = (action: any) => ?NavigationReducer; <ide> <del>function NavigationStackJumpToAction(key: string): NavigationStackReducerAction { <del> return { <del> type: ActionTypes.JUMP_TO, <del> key, <del> }; <del>} <add>export type StackReducerConfig = { <add> /* <add> * The initialState is that the reducer will use when there is no previous state. <add> * Must be a NavigationParentState: <add> * <add> * { <add> * children: [ <add> * {key: 'subState0'}, <add> * {key: 'subState1'}, <add> * ], <add> * index: 0, <add> * key: 'navStackKey' <add> * } <add> */ <add> initialState: NavigationParentState; <ide> <del>function NavigationStackJumpToIndexAction(index: number): NavigationStackReducerAction { <del> return { <del> type: ActionTypes.JUMP_TO_INDEX, <del> index, <del> }; <del>} <add> /* <add> * Returns the sub-reducer for a particular state to handle. This will be called <add> * when we need to handle an action on a sub-state. If no reducer is returned, <add> * no action will be taken <add> */ <add> getReducerForState?: ReducerForStateHandler; <ide> <del>function NavigationStackResetAction(children: Array<NavigationState>, index: number): NavigationStackReducerAction { <del> return { <del> type: ActionTypes.RESET, <del> index, <del> children, <del> }; <del>} <del> <del>type StackReducerConfig = { <del> initialStates: Array<NavigationState>; <del> initialIndex: ?number; <del> key: ?string; <del> matchAction: (action: any) => boolean; <del> actionStateMap: (action: any) => NavigationState; <add> /* <add> * Returns a sub-reducer that will be used when pushing a new route. If a reducer <add> * is returned, it be called to get the new state that will be pushed <add> */ <add> getPushedReducerForAction: PushedReducerForActionHandler; <ide> }; <ide> <del>function NavigationStackReducer({initialStates, initialIndex, key, matchAction, actionStateMap}: StackReducerConfig): NavigationReducer { <add>const defaultGetReducerForState = (initialState) => (state) => state || initialState; <add> <add>function NavigationStackReducer({initialState, getReducerForState, getPushedReducerForAction}: StackReducerConfig): NavigationReducer { <add> const getReducerForStateWithDefault = getReducerForState || defaultGetReducerForState; <ide> return function (lastState: ?NavigationState, action: any): NavigationState { <del> if (key == null) { <del> key = DEFAULT_KEY; <del> } <del> if (initialIndex == null) { <del> initialIndex = initialStates.length - 1; <del> } <ide> if (!lastState) { <del> lastState = { <del> index: initialIndex, <del> children: initialStates, <del> key, <del> }; <add> return initialState; <ide> } <ide> const lastParentState = NavigationStateUtils.getParent(lastState); <del> if (!action || !lastParentState) { <add> if (!lastParentState) { <ide> return lastState; <ide> } <ide> switch (action.type) { <del> case ActionTypes.PUSH: <del> return NavigationStateUtils.push( <del> lastParentState, <del> action.state <del> ); <del> case ActionTypes.POP: <ide> case 'BackAction': <ide> if (lastParentState.index === 0 || lastParentState.children.length === 1) { <ide> return lastParentState; <ide> } <ide> return NavigationStateUtils.pop(lastParentState); <del> case ActionTypes.JUMP_TO: <del> return NavigationStateUtils.jumpTo( <del> lastParentState, <del> action.key <del> ); <del> case ActionTypes.JUMP_TO_INDEX: <del> return NavigationStateUtils.jumpToIndex( <del> lastParentState, <del> action.index <del> ); <del> case ActionTypes.RESET: <del> return { <del> ...lastParentState, <del> index: action.index, <del> children: action.children, <del> }; <ide> } <del> if (matchAction(action)) { <add> <add> const activeSubState = lastParentState.children[lastParentState.index]; <add> const activeSubReducer = getReducerForStateWithDefault(activeSubState); <add> const nextActiveState = activeSubReducer(activeSubState, action); <add> if (nextActiveState !== activeSubState) { <add> const nextChildren = [...lastParentState.children]; <add> nextChildren[lastParentState.index] = nextActiveState; <add> return { <add> ...lastParentState, <add> children: nextChildren, <add> }; <add> } <add> <add> const subReducerToPush = getPushedReducerForAction(action); <add> if (subReducerToPush) { <ide> return NavigationStateUtils.push( <ide> lastParentState, <del> actionStateMap(action) <add> subReducerToPush(null, action) <ide> ); <ide> } <ide> return lastParentState; <ide> }; <ide> } <ide> <del>NavigationStackReducer.PushAction = NavigationStackPushAction; <del>NavigationStackReducer.PopAction = NavigationStackPopAction; <del>NavigationStackReducer.JumpToAction = NavigationStackJumpToAction; <del>NavigationStackReducer.JumpToIndexAction = NavigationStackJumpToIndexAction; <del>NavigationStackReducer.ResetAction = NavigationStackResetAction; <del> <ide> module.exports = NavigationStackReducer; <ide><path>Libraries/NavigationExperimental/Reducer/NavigationTabsReducer.js <ide> const ActionTypes = { <ide> JUMP_TO: 'react-native/NavigationExperimental/tabs-jumpTo', <ide> }; <ide> <del>const DEFAULT_KEY = 'TABS_STATE_DEFAULT_KEY'; <del> <ide> export type JumpToAction = { <ide> type: typeof ActionTypes.JUMP_TO, <ide> index: number, <ide> type TabsReducerConfig = { <ide> }; <ide> <ide> function NavigationTabsReducer({key, initialIndex, tabReducers}: TabsReducerConfig): NavigationReducer { <del> if (key == null) { <del> key = DEFAULT_KEY; <del> } <ide> return function(lastNavState: ?NavigationState, action: ?any): NavigationState { <ide> if (!lastNavState) { <ide> lastNavState = { <ide> function NavigationTabsReducer({key, initialIndex, tabReducers}: TabsReducerConf <ide> }; <ide> }); <ide> let selectedTabReducer = subReducers.splice(lastParentNavState.index, 1)[0]; <del> subReducers.unshift(selectedTabReducer); <del> subReducers.push(function(navState: ?NavigationState, action: any): NavigationState { <add> subReducers.unshift(function(navState: ?NavigationState, action: any): NavigationState { <ide> if (navState && action.type === 'BackAction') { <ide> return NavigationStateUtils.jumpToIndex( <ide> lastParentNavState, <del> 0 <add> initialIndex || 0 <ide> ); <ide> } <ide> return lastParentNavState; <ide> }); <add> subReducers.unshift(selectedTabReducer); <ide> const findReducer = NavigationFindReducer(subReducers, lastParentNavState); <ide> return findReducer(lastParentNavState, action); <ide> }; <ide><path>Libraries/NavigationExperimental/Reducer/__tests__/NavigationStackReducer-test.js <ide> jest <ide> .mock('ErrorUtils'); <ide> <ide> const NavigationStackReducer = require('NavigationStackReducer'); <del> <del>const { <del> JumpToAction, <del> JumpToIndexAction, <del> PopAction, <del> PushAction, <del> ResetAction, <del>} = NavigationStackReducer; <add>const NavigationRootContainer = require('NavigationRootContainer'); <ide> <ide> describe('NavigationStackReducer', () => { <ide> <del> it('handles PushAction', () => { <del> const initialStates = [ <del> {key: 'route0'}, <del> {key: 'route1'}, <del> ]; <del> let reducer = NavigationStackReducer({ <del> initialStates, <del> matchAction: () => true, <del> actionStateMap: (action) => action, <del> }); <del> <del> let state = reducer(); <del> expect(state.children).toBe(initialStates); <del> expect(state.index).toBe(1); <del> expect(state.key).toBe('NAV_STACK_DEFAULT_KEY'); <del> <del> state = reducer(state, PushAction({key: 'route2'})); <del> expect(state.children[0].key).toBe('route0'); <del> expect(state.children[1].key).toBe('route1'); <del> expect(state.children[2].key).toBe('route2'); <del> expect(state.index).toBe(2); <del> }); <del> <del> it('handles PopAction', () => { <del> let reducer = NavigationStackReducer({ <del> initialStates: [ <add> it('provides default/initial state', () => { <add> const initialState = { <add> children: [ <ide> {key: 'a'}, <del> {key: 'b'}, <ide> ], <del> initialIndex: 1, <add> index: 0, <ide> key: 'myStack', <del> matchAction: () => true, <del> actionStateMap: (action) => action, <add> }; <add> const reducer = NavigationStackReducer({ <add> getPushedReducerForAction: (action) => null, <add> getReducerForState: (state) => () => state, <add> initialState, <ide> }); <del> <del> let state = reducer(); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children.length).toBe(2); <del> expect(state.index).toBe(1); <del> expect(state.key).toBe('myStack'); <del> <del> state = reducer(state, PopAction()); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children.length).toBe(1); <del> expect(state.index).toBe(0); <del> expect(state.key).toBe('myStack'); <del> <del> // make sure Pop on an single-route state is a no-op <del> state = reducer(state, PopAction()); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children.length).toBe(1); <del> expect(state.index).toBe(0); <del> expect(state.key).toBe('myStack'); <add> const dummyAction = {type: 'dummyAction'}; <add> expect(reducer(null, dummyAction)).toBe(initialState); <ide> }); <ide> <del> it('handles JumpToAction', () => { <del> let reducer = NavigationStackReducer({ <del> initialStates: [ <del> {key: 'a'}, <del> {key: 'b'}, <del> {key: 'c'}, <del> ], <del> initialIndex: 0, <del> key: 'myStack', <del> matchAction: () => true, <del> actionStateMap: (action) => action, <add> it('handles basic reducer pushing', () => { <add> const reducer = NavigationStackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (action.type === 'TestPushAction') { <add> return (state) => state || {key: action.testValue}; <add> } <add> return null; <add> }, <add> getReducerForState: (state) => () => state, <add> initialState: { <add> children: [ <add> {key: 'first'}, <add> ], <add> index: 0, <add> key: 'myStack' <add> } <ide> }); <del> <del> let state = reducer(); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children[2].key).toBe('c'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(0); <del> <del> state = reducer(state, JumpToAction('b')); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children[2].key).toBe('c'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(1); <del> <del> state = reducer(state, JumpToAction('c')); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children[2].key).toBe('c'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(2); <del> <del> state = reducer(state, JumpToAction('c')); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children[2].key).toBe('c'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(2); <del> expect(state.key).toBe('myStack'); <del> }); <del> <del> it('handles JumpToIndexAction', () => { <del> let reducer = NavigationStackReducer({ <del> initialStates: [ <del> {key: 'a'}, <del> {key: 'b'}, <del> {key: 'c'}, <del> ], <del> initialIndex: 2, <del> key: 'myStack', <del> matchAction: () => true, <del> actionStateMap: (action) => action, <del> }); <del> <del> let state = reducer(); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(2); <del> <del> state = reducer(state, JumpToIndexAction(0)); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(0); <del> <del> state = reducer(state, JumpToIndexAction(1)); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children[2].key).toBe('c'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(1); <del> expect(state.key).toBe('myStack'); <add> const state1 = reducer(null, {type: 'default'}); <add> expect(state1.children.length).toBe(1); <add> expect(state1.children[0].key).toBe('first'); <add> expect(state1.index).toBe(0); <add> <add> const action = {type: 'TestPushAction', testValue: 'second'}; <add> const state2 = reducer(state1, action); <add> expect(state2.children.length).toBe(2); <add> expect(state2.children[0].key).toBe('first'); <add> expect(state2.children[1].key).toBe('second'); <add> expect(state2.index).toBe(1); <ide> }); <ide> <del> it('handles ResetAction', () => { <del> let reducer = NavigationStackReducer({ <del> initialStates: [ <del> {key: 'a'}, <del> {key: 'b'}, <del> ], <del> initialIndex: 1, <del> key: 'myStack', <del> matchAction: () => true, <del> actionStateMap: (action) => action, <add> it('handles BackAction', () => { <add> const reducer = NavigationStackReducer({ <add> getPushedReducerForAction: (action) => { <add> if (action.type === 'TestPushAction') { <add> return (state) => state || {key: action.testValue}; <add> } <add> return null; <add> }, <add> getReducerForState: (state) => () => state, <add> initialState: { <add> children: [ <add> {key: 'a'}, <add> {key: 'b'}, <add> ], <add> index: 1, <add> key: 'myStack', <add> }, <ide> }); <ide> <del> let state = reducer(); <del> expect(state.children[0].key).toBe('a'); <del> expect(state.children[1].key).toBe('b'); <del> expect(state.children.length).toBe(2); <del> expect(state.index).toBe(1); <del> <del> state = reducer(state, ResetAction([{key: 'c'}, {key: 'd'}], 0)); <del> expect(state.children[0].key).toBe('c'); <del> expect(state.children[1].key).toBe('d'); <del> expect(state.children.length).toBe(2); <del> expect(state.index).toBe(0); <add> const state1 = reducer(null, {type: 'MyDefaultAction'}); <add> expect(state1.children[0].key).toBe('a'); <add> expect(state1.children[1].key).toBe('b'); <add> expect(state1.children.length).toBe(2); <add> expect(state1.index).toBe(1); <add> expect(state1.key).toBe('myStack'); <ide> <del> const newStates = [ <del> {key: 'e'}, <del> {key: 'f'}, <del> {key: 'g'}, <del> ]; <add> const state2 = reducer(state1, NavigationRootContainer.getBackAction()); <add> expect(state2.children[0].key).toBe('a'); <add> expect(state2.children.length).toBe(1); <add> expect(state2.index).toBe(0); <ide> <del> state = reducer(state, ResetAction(newStates, 1)); <del> expect(state.children[0].key).toBe('e'); <del> expect(state.children[1].key).toBe('f'); <del> expect(state.children[2].key).toBe('g'); <del> expect(state.children.length).toBe(3); <del> expect(state.index).toBe(1); <del> expect(state.key).toBe('myStack'); <add> const state3 = reducer(state2, NavigationRootContainer.getBackAction()); <add> expect(state3).toBe(state2); <ide> }); <ide> <del>}); <add>}); <ide>\ No newline at end of file
10
Python
Python
remove japanese from languages
04e6a6518869b1ca15beb79694049e0fb164a2aa
<ide><path>spacy/tests/conftest.py <ide> import pytest <ide> <ide> <del>LANGUAGES = [English, German, Spanish, Italian, Japanese, French, Portuguese, Dutch, <add>LANGUAGES = [English, German, Spanish, Italian, French, Portuguese, Dutch, <ide> Swedish, Hungarian, Finnish, Bengali, Norwegian] <ide> <ide>
1
Go
Go
fix data race in testlogevent
abfdaca3f86d7951693697fbd849078d6b406478
<ide><path>api.go <ide> func getEvents(srv *Server, version float64, w http.ResponseWriter, r *http.Requ <ide> wf.Flush() <ide> if since != 0 { <ide> // If since, send previous events that happened after the timestamp <del> for _, event := range srv.events { <add> for _, event := range srv.GetEvents() { <ide> if event.Time >= since { <ide> err := sendEvent(wf, &event) <ide> if err != nil && err.Error() == "JSON error" { <ide><path>server.go <ide> func (srv *Server) poolAdd(kind, key string) error { <ide> } <ide> <ide> func (srv *Server) poolRemove(kind, key string) error { <add> srv.Lock() <add> defer srv.Unlock() <ide> switch kind { <ide> case "pull": <ide> delete(srv.pullingPool, key) <ide> func NewServer(eng *engine.Engine, config *DaemonConfig) (*Server, error) { <ide> } <ide> <ide> func (srv *Server) HTTPRequestFactory(metaHeaders map[string][]string) *utils.HTTPRequestFactory { <add> srv.Lock() <add> defer srv.Unlock() <ide> if srv.reqFactory == nil { <ide> ud := utils.NewHTTPUserAgentDecorator(srv.versionInfos()...) <ide> md := &utils.HTTPMetaHeadersDecorator{ <ide> func (srv *Server) HTTPRequestFactory(metaHeaders map[string][]string) *utils.HT <ide> func (srv *Server) LogEvent(action, id, from string) *utils.JSONMessage { <ide> now := time.Now().Unix() <ide> jm := utils.JSONMessage{Status: action, ID: id, From: from, Time: now} <del> srv.events = append(srv.events, jm) <add> srv.AddEvent(jm) <ide> for _, c := range srv.listeners { <ide> select { // non blocking channel <ide> case c <- jm: <ide> func (srv *Server) LogEvent(action, id, from string) *utils.JSONMessage { <ide> return &jm <ide> } <ide> <add>func (srv *Server) AddEvent(jm utils.JSONMessage) { <add> srv.Lock() <add> defer srv.Unlock() <add> srv.events = append(srv.events, jm) <add>} <add> <add>func (srv *Server) GetEvents() []utils.JSONMessage { <add> srv.RLock() <add> defer srv.RUnlock() <add> return srv.events <add>} <add> <ide> type Server struct { <del> sync.Mutex <add> sync.RWMutex <ide> runtime *Runtime <ide> pullingPool map[string]struct{} <ide> pushingPool map[string]struct{} <ide><path>server_unit_test.go <ide> func TestLogEvent(t *testing.T) { <ide> <ide> srv.LogEvent("fakeaction2", "fakeid", "fakeimage") <ide> <del> if len(srv.events) != 2 { <del> t.Fatalf("Expected 2 events, found %d", len(srv.events)) <add> numEvents := len(srv.GetEvents()) <add> if numEvents != 2 { <add> t.Fatalf("Expected 2 events, found %d", numEvents) <ide> } <ide> go func() { <ide> time.Sleep(200 * time.Millisecond) <ide> func TestLogEvent(t *testing.T) { <ide> setTimeout(t, "Listening for events timed out", 2*time.Second, func() { <ide> for i := 2; i < 4; i++ { <ide> event := <-listener <del> if event != srv.events[i] { <add> if event != srv.GetEvents()[i] { <ide> t.Fatalf("Event received it different than expected") <ide> } <ide> }
3
Text
Text
remove clunky sentence
18e821bcd30a3907c537c0f3938238efb09773cd
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.md <ide> Assign the following three lines of text into the single variable `myStr` using <ide> <ide> You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words. <ide> <del>Here is the text with the escape sequences written out. <del> <del>"FirstLine<code>newline</code><code>tab</code><code>backslash</code>SecondLine`newline`ThirdLine" <add>**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces. <ide> <ide> # --hints-- <ide>
1
Javascript
Javascript
remove unused variable
857975d5e7e0d7bf38577db0478d9e5ede79922e
<ide><path>lib/_tls_wrap.js <ide> // USE OR OTHER DEALINGS IN THE SOFTWARE. <ide> <ide> var assert = require('assert'); <del>var constants = require('constants'); <ide> var crypto = require('crypto'); <ide> var net = require('net'); <ide> var tls = require('tls');
1
Python
Python
make dbapihook use get_uri from connection
59c450ee5425a2d23ef813dbf219cde14df7c85c
<ide><path>airflow/hooks/dbapi.py <ide> from contextlib import closing <ide> from datetime import datetime <ide> from typing import Any, Optional <del>from urllib.parse import quote_plus, urlunsplit <ide> <ide> from sqlalchemy import create_engine <ide> <ide> def get_uri(self) -> str: <ide> :return: the extracted uri. <ide> """ <ide> conn = self.get_connection(getattr(self, self.conn_name_attr)) <del> login = '' <del> if conn.login: <del> login = f'{quote_plus(conn.login)}:{quote_plus(conn.password)}@' <del> host = conn.host <del> if conn.port is not None: <del> host += f':{conn.port}' <del> schema = self.__schema or conn.schema or '' <del> return urlunsplit((conn.conn_type, f'{login}{host}', schema, '', '')) <add> conn.schema = self.__schema or conn.schema <add> return conn.get_uri() <ide> <ide> def get_sqlalchemy_engine(self, engine_kwargs=None): <ide> """ <ide><path>airflow/models/connection.py <ide> def _parse_from_uri(self, uri: str): <ide> <ide> def get_uri(self) -> str: <ide> """Return connection in URI format""" <add> if '_' in self.conn_type: <add> self.log.warning( <add> f"Connection schemes (type: {str(self.conn_type)}) " <add> f"shall not contain '_' according to RFC3986." <add> ) <add> <ide> uri = f"{str(self.conn_type).lower().replace('_', '-')}://" <ide> <ide> authority_block = '' <ide><path>airflow/providers/mysql/hooks/mysql.py <ide> def get_conn(self) -> MySQLConnectionTypes: <ide> <ide> raise ValueError('Unknown MySQL client name provided!') <ide> <del> def get_uri(self) -> str: <del> conn = self.get_connection(getattr(self, self.conn_name_attr)) <del> uri = super().get_uri() <del> if conn.extra_dejson.get('charset', False): <del> charset = conn.extra_dejson["charset"] <del> return f"{uri}?charset={charset}" <del> return uri <del> <ide> def bulk_load(self, table: str, tmp_file: str) -> None: <ide> """Loads a tab-delimited file into a database table""" <ide> conn = self.get_conn() <ide><path>airflow/providers/postgres/hooks/postgres.py <ide> def copy_expert(self, sql: str, filename: str) -> None: <ide> conn.commit() <ide> <ide> def get_uri(self) -> str: <del> conn = self.get_connection(getattr(self, self.conn_name_attr)) <add> """ <add> Extract the URI from the connection. <add> :return: the extracted uri. <add> """ <ide> uri = super().get_uri().replace("postgres://", "postgresql://") <del> if conn.extra_dejson.get('client_encoding', False): <del> charset = conn.extra_dejson["client_encoding"] <del> return f"{uri}?client_encoding={charset}" <ide> return uri <ide> <ide> def bulk_load(self, table: str, tmp_file: str) -> None: <ide><path>tests/hooks/test_dbapi.py <ide> def test_insert_rows_commit_every(self): <ide> def test_get_uri_schema_not_none(self): <ide> self.db_hook.get_connection = mock.MagicMock( <ide> return_value=Connection( <del> conn_type="conn_type", <add> conn_type="conn-type", <ide> host="host", <ide> login="login", <ide> password="password", <ide> schema="schema", <ide> port=1, <ide> ) <ide> ) <del> assert "conn_type://login:password@host:1/schema" == self.db_hook.get_uri() <add> assert "conn-type://login:password@host:1/schema" == self.db_hook.get_uri() <ide> <ide> def test_get_uri_schema_override(self): <ide> self.db_hook_schema_override.get_connection = mock.MagicMock( <ide> return_value=Connection( <del> conn_type="conn_type", <add> conn_type="conn-type", <ide> host="host", <ide> login="login", <ide> password="password", <ide> schema="schema", <ide> port=1, <ide> ) <ide> ) <del> assert "conn_type://login:password@host:1/schema-override" == self.db_hook_schema_override.get_uri() <add> assert "conn-type://login:password@host:1/schema-override" == self.db_hook_schema_override.get_uri() <ide> <ide> def test_get_uri_schema_none(self): <ide> self.db_hook.get_connection = mock.MagicMock( <ide> return_value=Connection( <del> conn_type="conn_type", host="host", login="login", password="password", schema=None, port=1 <add> conn_type="conn-type", host="host", login="login", password="password", schema=None, port=1 <ide> ) <ide> ) <del> assert "conn_type://login:password@host:1" == self.db_hook.get_uri() <add> assert "conn-type://login:password@host:1" == self.db_hook.get_uri() <ide> <ide> def test_get_uri_special_characters(self): <ide> self.db_hook.get_connection = mock.MagicMock( <ide> return_value=Connection( <del> conn_type="conn_type", <add> conn_type="conn-type", <add> host="host/", <add> login="lo/gi#! n", <add> password="pass*! word/", <add> schema="schema/", <add> port=1, <add> ) <add> ) <add> assert ( <add> "conn-type://lo%2Fgi%23%21%20n:pass%2A%21%20word%2F@host%2F:1/schema%2F" == self.db_hook.get_uri() <add> ) <add> <add> def test_get_uri_login_none(self): <add> self.db_hook.get_connection = mock.MagicMock( <add> return_value=Connection( <add> conn_type="conn-type", <add> host="host", <add> login=None, <add> password="password", <add> schema="schema", <add> port=1, <add> ) <add> ) <add> assert "conn-type://:password@host:1/schema" == self.db_hook.get_uri() <add> <add> def test_get_uri_password_none(self): <add> self.db_hook.get_connection = mock.MagicMock( <add> return_value=Connection( <add> conn_type="conn-type", <add> host="host", <add> login="login", <add> password=None, <add> schema="schema", <add> port=1, <add> ) <add> ) <add> assert "conn-type://login@host:1/schema" == self.db_hook.get_uri() <add> <add> def test_get_uri_authority_none(self): <add> self.db_hook.get_connection = mock.MagicMock( <add> return_value=Connection( <add> conn_type="conn-type", <ide> host="host", <del> login="logi#! n", <del> password="pass*! word", <add> login=None, <add> password=None, <ide> schema="schema", <ide> port=1, <ide> ) <ide> ) <del> assert "conn_type://logi%23%21+n:pass%2A%21+word@host:1/schema" == self.db_hook.get_uri() <add> assert "conn-type://host:1/schema" == self.db_hook.get_uri() <ide> <ide> def test_run_log(self): <ide> statement = 'SQL' <ide><path>tests/providers/amazon/aws/hooks/test_base_aws.py <ide> def test_get_credentials_from_gcp_credentials(self): <ide> } <ide> ) <ide> ) <add> mock_connection.conn_type = 'aws' <ide> <ide> # Store original __import__ <ide> orig_import = __import__ <ide><path>tests/providers/snowflake/hooks/test_snowflake.py <ide> <ide> BASE_CONNECTION_KWARGS: Dict = { <ide> 'login': 'user', <add> 'conn_type': 'snowflake', <ide> 'password': 'pw', <ide> 'schema': 'public', <ide> 'extra': {
7
Ruby
Ruby
add todos for rubocop migrations
8cb90595b3ff0ef66813c3d4b130027b06cc4679
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_style <ide> end <ide> <ide> def audit_file <add> # TODO: check could be in RuboCop <ide> actual_mode = formula.path.stat.mode <ide> # Check that the file is world-readable. <ide> if actual_mode & 0444 != 0444 <ide> def audit_file <ide> path: formula.path) <ide> end <ide> <add> # TODO: check could be in RuboCop <ide> problem "'DATA' was found, but no '__END__'" if text.data? && !text.end? <ide> <add> # TODO: check could be in RuboCop <ide> problem "'__END__' was found, but 'DATA' is not used" if text.end? && !text.data? <ide> <add> # TODO: check could be in RuboCop <ide> if text.to_s.match?(/inreplace [^\n]* do [^\n]*\n[^\n]*\.gsub![^\n]*\n\ *end/m) <ide> problem "'inreplace ... do' was used for a single substitution (use the non-block form instead)." <ide> end <ide> def audit_keg_only <ide> first_word = reason.split.first <ide> <ide> if reason =~ /\A[A-Z]/ && !reason.start_with?(*whitelist) <add> # TODO: check could be in RuboCop <ide> problem <<~EOS <ide> '#{first_word}' from the keg_only reason should be '#{first_word.downcase}'. <ide> EOS <ide> end <ide> <ide> return unless reason.end_with?(".") <ide> <add> # TODO: check could be in RuboCop <ide> problem "keg_only reason should not end with a period." <ide> end <ide> <ide> def audit_lines <ide> def line_problems(line, _lineno) <ide> # Check for string interpolation of single values. <ide> if line =~ /(system|inreplace|gsub!|change_make_var!).*[ ,]"#\{([\w.]+)\}"/ <add> # TODO: check could be in RuboCop <ide> problem "Don't need to interpolate \"#{Regexp.last_match(2)}\" with #{Regexp.last_match(1)}" <ide> end <ide> <ide> # Check for string concatenation; prefer interpolation <ide> if line =~ /(#\{\w+\s*\+\s*['"][^}]+\})/ <add> # TODO: check could be in RuboCop <ide> problem "Try not to concatenate paths in string interpolation:\n #{Regexp.last_match(1)}" <ide> end <ide> <ide> # Prefer formula path shortcuts in Pathname+ <ide> if line =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share|Frameworks)[/'"])} <add> # TODO: check could be in RuboCop <ide> problem( <ide> "\"(#{Regexp.last_match(1)}...#{Regexp.last_match(2)})\" should" \ <ide> " be \"(#{Regexp.last_match(3).downcase}+...)\"", <ide> ) <ide> end <ide> <add> # TODO: check could be in RuboCop <ide> problem "Use separate make calls" if line.include?("make && make") <ide> <ide> if line =~ /JAVA_HOME/i && <ide> [formula.name, *formula.deps.map(&:name)].none? { |name| name.match?(/^openjdk(@|$)/) } && <ide> formula.requirements.none? { |req| req.is_a?(JavaRequirement) } <add> # TODO: check could be in RuboCop <ide> problem "Use `depends_on :java` to set JAVA_HOME" <ide> end <ide> <ide> return unless @strict <ide> <add> # TODO: check could be in RuboCop <ide> problem "`env :userpaths` in formulae is deprecated" if line.include?("env :userpaths") <ide> <ide> if line =~ /system ((["'])[^"' ]*(?:\s[^"' ]*)+\2)/ <ide> bad_system = Regexp.last_match(1) <ide> unless %w[| < > & ; *].any? { |c| bad_system.include? c } <ide> good_system = bad_system.gsub(" ", "\", \"") <add> # TODO: check could be in RuboCop <ide> problem "Use `system #{good_system}` instead of `system #{bad_system}` " <ide> end <ide> end <ide> <add> # TODO: check could be in RuboCop <ide> problem "`#{Regexp.last_match(1)}` is now unnecessary" if line =~ /(require ["']formula["'])/ <ide> <ide> if line.match?(%r{#\{share\}/#{Regexp.escape(formula.name)}[/'"]}) <add> # TODO: check could be in RuboCop <ide> problem "Use \#{pkgshare} instead of \#{share}/#{formula.name}" <ide> end <ide> <ide> if !@core_tap && line =~ /depends_on .+ if build\.with(out)?\?\(?["']\w+["']\)?/ <add> # TODO: check could be in RuboCop <ide> problem "`Use :optional` or `:recommended` instead of `#{Regexp.last_match(0)}`" <ide> end <ide> <ide> if line =~ %r{share(\s*[/+]\s*)(['"])#{Regexp.escape(formula.name)}(?:\2|/)} <add> # TODO: check could be in RuboCop <ide> problem "Use pkgshare instead of (share#{Regexp.last_match(1)}\"#{formula.name}\")" <ide> end <ide> <ide> return unless @core_tap <ide> <add> # TODO: check could be in RuboCop <ide> problem "`env :std` in homebrew/core formulae is deprecated" if line.include?("env :std") <ide> end <ide> <ide> def audit_version <ide> if version.nil? <ide> problem "missing version" <ide> elsif version.blank? <add> # TODO: check could be in RuboCop <ide> problem "version is set to an empty string" <ide> elsif !version.detected_from_url? <ide> version_text = version <ide> def audit_version <ide> end <ide> end <ide> <add> # TODO: check could be in RuboCop <ide> problem "version #{version} should not have a leading 'v'" if version.to_s.start_with?("v") <ide> <ide> return unless version.to_s.match?(/_\d+$/) <ide> <add> # TODO: check could be in RuboCop <ide> problem "version #{version} should not end with an underline and a number" <ide> end <ide> <ide> def audit_download_strategy <ide> if url =~ %r{^(cvs|bzr|hg|fossil)://} || url =~ %r{^(svn)\+http://} <add> # TODO: check could be in RuboCop <ide> problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{Regexp.last_match(1)}` instead" <ide> end <ide> <ide> url_strategy = DownloadStrategyDetector.detect(url) <ide> <ide> if using == :git || url_strategy == GitDownloadStrategy <add> # TODO: check could be in RuboCop <ide> problem "Git should specify :revision when a :tag is specified." if specs[:tag] && !specs[:revision] <ide> end <ide>
1
PHP
PHP
improve error message
7698a812f36bcadbf846de9dc3c7c13fe1392327
<ide><path>src/Http/Uri.php <ide> public function __get(string $name) <ide> if ($name === 'base' || $name === 'webroot') { <ide> return $this->{$name}; <ide> } <del> <del> throw new Error("Cannot access attribute `{$name}`"); <add> throw new Error("Undefined property via __get('{$name}')"); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/UriTest.php <ide> public function testMagicAttributes() <ide> $this->assertSame('/base/', $uri->webroot); <ide> <ide> $this->expectException(Error::class); <add> $this->expectExceptionMessage('Undefined property via __get'); <ide> $uri->uri; <ide> } <ide>
2
Javascript
Javascript
fix react native tests
ec90ad127f3e862425732e00e68abfeb47cd88b2
<ide><path>jest/hasteImpl.js <ide> const cli = require('@react-native-community/cli'); <ide> const {haste} = (cli.loadConfig && cli.loadConfig()) || { <ide> haste: { <ide> providesModuleNodeModules: [], <del> platforms: [], <add> platforms: ['ios', 'android'], <ide> }, <ide> }; <ide>
1
Python
Python
simplify ufunc pickling
2e3de29722cc42970a31fe6843c5aa0dbcf0ee7d
<ide><path>numpy/core/__init__.py <ide> __all__ += shape_base.__all__ <ide> __all__ += einsumfunc.__all__ <ide> <del># Make it possible so that ufuncs can be pickled <del># Here are the loading and unloading functions <del># The name numpy.core._ufunc_reconstruct must be <del># available for unpickling to work. <add># We used to use `np.core._ufunc_reconstruct` to unpickle. This is unnecessary, <add># but old pickles saved before 1.20 will be using it, and there is no reason <add># to break loading them. <ide> def _ufunc_reconstruct(module, name): <ide> # The `fromlist` kwarg is required to ensure that `mod` points to the <ide> # inner-most module rather than the parent package when module name is <ide> def _ufunc_reconstruct(module, name): <ide> return getattr(mod, name) <ide> <ide> def _ufunc_reduce(func): <del> from pickle import whichmodule <del> name = func.__name__ <del> return _ufunc_reconstruct, (whichmodule(func, name), name) <add> # Report the `__name__`. pickle will try to find the module. Note that <add> # pickle supports for this `__name__` to be a `__qualname__`. It may <add> # make sense to add a `__qualname__` to ufuncs, to allow this more <add> # explicitly (Numba has ufuncs as attributes). <add> # See also: https://github.com/dask/distributed/issues/3450 <add> return func.__name__ <ide> <ide> <ide> import copyreg <ide> <del>copyreg.pickle(ufunc, _ufunc_reduce, _ufunc_reconstruct) <add>copyreg.pickle(ufunc, _ufunc_reduce) <ide> # Unclutter namespace (must keep _ufunc_reconstruct for unpickling) <ide> del copyreg <ide> del _ufunc_reduce
1
Javascript
Javascript
add test cases for path
e18ebe8354b600ca868bb3abd65d8a159e190d17
<ide><path>test/parallel/test-path.js <ide> const failures = []; <ide> // path.basename tests <ide> assert.strictEqual(path.basename(f), 'test-path.js'); <ide> assert.strictEqual(path.basename(f, '.js'), 'test-path'); <add>assert.strictEqual(path.basename('.js', '.js'), ''); <ide> assert.strictEqual(path.basename(''), ''); <ide> assert.strictEqual(path.basename('/dir/basename.ext'), 'basename.ext'); <ide> assert.strictEqual(path.basename('/basename.ext'), 'basename.ext'); <ide> assert.strictEqual(path.posix.dirname('/a'), '/'); <ide> assert.strictEqual(path.posix.dirname(''), '.'); <ide> assert.strictEqual(path.posix.dirname('/'), '/'); <ide> assert.strictEqual(path.posix.dirname('////'), '/'); <add>assert.strictEqual(path.posix.dirname('//a'), '//'); <ide> assert.strictEqual(path.posix.dirname('foo'), '.'); <ide> <ide> assert.strictEqual(path.win32.dirname('c:\\'), 'c:\\');
1
Text
Text
fix dublication in net.createserver() docs
c51d47d5df22234c34968ade0ae470ceb9343d48
<ide><path>doc/api/net.md <ide> added: v0.7.0 <ide> --> <ide> * `options` {Object} <ide> * `connectListener` {Function} <add> <ide> Alias to <ide> [`net.createConnection(options[, connectListener])`][`net.createConnection(options)`]. <ide> <ide> then returns the `net.Socket` that starts the connection. <ide> <!-- YAML <ide> added: v0.5.0 <ide> --> <del>* `options` {Object} <del>* `connectionListener` {Function} <del> <del>Creates a new TCP or [IPC][] server. <ide> <ide> * `options` {Object} <ide> * `allowHalfOpen` {boolean} Indicates whether half-opened TCP <ide> Creates a new TCP or [IPC][] server. <ide> [`'connection'`][] event. <ide> * Returns: {net.Server} <ide> <add>Creates a new TCP or [IPC][] server. <add> <ide> If `allowHalfOpen` is set to `true`, when the other end of the socket <ide> sends a FIN packet, the server will only send a FIN packet back when <ide> [`socket.end()`][] is explicitly called, until then the connection is
1
Python
Python
add version string
7856656df0c60d038f2d2c584e3bf9a5420cc801
<ide><path>djangorestframework/__init__.py <add>VERSION="0.1.1" <ide><path>djangorestframework/tests/package.py <add>"""Tests for the djangorestframework package setup.""" <add>from django.test import TestCase <add>import djangorestframework <add> <add>class TestVersion(TestCase): <add> """Simple sanity test to check the VERSION exists""" <add> <add> def test_version(self): <add> """Ensure the VERSION exists.""" <add> djangorestframework.VERSION <add>
2
Javascript
Javascript
add tests for format('zz')
d45f06de4ef873e305e32d3c74c0792595b8f533
<ide><path>test/moment/zones.js <ide> exports.zones = { <ide> test.equal(m.zone(), 13 * 60); <ide> test.equal(m.hours(), 0); <ide> test.done(); <add> }, <add> <add> "timezone format" : function (test) { <add> test.equal(moment().zone(-60).format('ZZ'), "+0100", "-60 -> +0100"); <add> test.equal(moment().zone(-90).format('ZZ'), "+0130", "-90 -> +0130"); <add> test.equal(moment().zone(-120).format('ZZ'), "+0200", "-120 -> +0200"); <add> <add> test.equal(moment().zone(+60).format('ZZ'), "-0100", "+60 -> -0100"); <add> test.equal(moment().zone(+90).format('ZZ'), "-0130", "+90 -> -0130"); <add> test.equal(moment().zone(+120).format('ZZ'), "-0200", "+120 -> -0200"); <add> test.done(); <ide> } <ide> };
1
Javascript
Javascript
ignore duplicated entries in observer
ef9ecfbcfe8a5b1e8b1c601c48afa065cbdab614
<ide><path>lib/perf_hooks.js <ide> class PerformanceObserver extends AsyncResource { <ide> for (var n = 0; n < entryTypes.length; n++) { <ide> const entryType = entryTypes[n]; <ide> const list = getObserversList(entryType); <add> if (this[kTypes][entryType]) continue; <ide> const item = { obs: this }; <ide> this[kTypes][entryType] = item; <ide> L.append(list, item); <ide><path>test/parallel/test-performanceobserver.js <ide> assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); <ide> 'for option "entryTypes"' <ide> }); <ide> }); <add> <add> const obs = new PerformanceObserver(common.mustNotCall()); <add> obs.observe({ entryTypes: ['mark', 'mark'] }); <add> obs.disconnect(); <add> performance.mark('42'); <add> assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 0); <ide> } <ide> <ide> // Test Non-Buffered
2
Javascript
Javascript
update route recognizer
cb3fb8ea50ee0d2f3fbe0211547ba121b5203fb3
<ide><path>packages/ember-routing/lib/vendor/route-recognizer.js <ide> define("route-recognizer", <ide> } <ide> for(var key in params) { <ide> if (params.hasOwnProperty(key)) { <del> if(!~allowedParams.indexOf(key)) { <add> if(allowedParams.indexOf(key) === -1) { <ide> throw 'Query param "' + key + '" is not specified as a valid param for this route'; <ide> } <ide> var value = params[key]; <ide> define("route-recognizer", <ide> pathLen, i, l, queryStart, queryParams = {}; <ide> <ide> queryStart = path.indexOf('?'); <del> if (~queryStart) { <add> if (queryStart !== -1) { <ide> var queryString = path.substr(queryStart + 1, path.length); <ide> path = path.substr(0, queryStart); <ide> queryParams = this.parseQueryString(queryString);
1
PHP
PHP
make request helper and __get consistent
a6ff272c54677a9f52718292fc0938ffb1871832
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function request($key = null, $default = null) <ide> return app('request')->only($key); <ide> } <ide> <del> return data_get(app('request')->all(), $key, $default); <add> $value = app('request')->__get($key); <add> <add> return is_null($value) ? value($default) : $value; <ide> } <ide> } <ide> <ide><path>src/Illuminate/Http/Request.php <ide> public function toArray() <ide> */ <ide> public function offsetExists($offset) <ide> { <del> return array_key_exists($offset, $this->all()); <add> return array_key_exists( <add> $offset, $this->all() + $this->route()->parameters() <add> ); <ide> } <ide> <ide> /** <ide> public function offsetExists($offset) <ide> */ <ide> public function offsetGet($offset) <ide> { <del> return data_get($this->all(), $offset); <add> return $this->__get($offset); <ide> } <ide> <ide> /** <ide> public function __isset($key) <ide> */ <ide> public function __get($key) <ide> { <del> if ($this->offsetExists($key)) { <del> return $this->offsetGet($key); <add> if (array_key_exists($key, $this->all())) { <add> return data_get($this->all(), $key); <ide> } <ide> <ide> return $this->route($key); <ide><path>tests/Http/HttpRequestTest.php <ide> public function testMagicMethods() <ide> <ide> // Parameter 'empty' is '', then it ISSET and is EMPTY. <ide> $this->assertEquals($request->empty, ''); <del> $this->assertEquals(isset($request->empty), true); <del> $this->assertEquals(empty($request->empty), true); <add> $this->assertTrue(isset($request->empty)); <add> $this->assertTrue(empty($request->empty)); <ide> <ide> // Parameter 'undefined' is undefined/null, then it NOT ISSET and is EMPTY. <ide> $this->assertEquals($request->undefined, null); <ide> public function testMagicMethods() <ide> }); <ide> <ide> // Router parameter 'foo' is 'bar', then it ISSET and is NOT EMPTY. <del> $this->assertEquals($request->foo, 'bar'); <add> $this->assertEquals('bar', $request->foo); <add> $this->assertEquals('bar', $request['foo']); <ide> $this->assertEquals(isset($request->foo), true); <ide> $this->assertEquals(empty($request->foo), false); <ide>
3
Text
Text
fix grammatical error in readme file
9c88ea8c580098c3decff945cc235a707410d39e
<ide><path>readme.md <ide> Client-side routing behaves exactly like the browser: <ide> <ide> 1. The component is fetched <ide> 2. If it defines `getInitialProps`, data is fetched. If an error occurs, `_error.js` is rendered <del>3. After 1 and 2 complete, `pushState` is performed and the new component rendered <add>3. After 1 and 2 complete, `pushState` is performed and the new component is rendered <ide> <ide> Each top-level component receives a `url` property with the following API: <ide> <ide> export default () => <ide> </div> <ide> ``` <ide> <del>##### Using a component that support `onClick` <add>##### Using a component that supports `onClick` <ide> <ide> `<Link>` supports any component that supports the `onClick` event. In case you don't provide an `<a>` tag, it will only add the `onClick` event handler and won't pass the `href` property. <ide> <ide> If you no longer want to listen to that event, you can simply unset the event li <ide> Router.onRouteChangeStart = null <ide> ``` <ide> <del>If a route load is cancelled (for example by clicking two links rapidly in succession), `routeChangeError` will fire. The passed `err` will contained a `cancelled` property set to `true`. <add>If a route load is cancelled (for example by clicking two links rapidly in succession), `routeChangeError` will fire. The passed `err` will contain a `cancelled` property set to `true`. <ide> <ide> ```js <ide> Router.onRouteChangeError = (err, url) => { <ide> module.exports = { <ide> } <ide> ``` <ide> <del>Note: Next.js will automatically use that prefix the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration). <add>Note: Next.js will automatically use that prefix in the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration). <ide> <ide> ## Production deployment <ide>
1
Text
Text
fix some casing of "on-demand isr"
455d16419fe07322188a60f6f6abba82159757a6
<ide><path>docs/api-reference/data-fetching/get-static-paths.md <ide> description: API reference for `getStaticPaths`. Learn how to fetch data and gen <ide> | Version | Changes | <ide> | ------- | ------- | <ide> <del>| `v12.1.0` | [On-demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). | <add>| `v12.1.0` | [On-Demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). | <ide> | `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) | <ide> | `v9.3.0` | `getStaticPaths` introduced. | <ide> <ide><path>docs/api-reference/data-fetching/get-static-props.md <ide> description: API reference for `getStaticProps`. Learn how to use `getStaticProp <ide> | Version | Changes | <ide> | ------- | ------- | <ide> <del>| `v12.1.0` | [On-demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). | <add>| `v12.1.0` | [On-Demand Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta) added (Beta). | <ide> | `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | <ide> | `v10.0.0` | `fallback: 'blocking'` return option added. | <ide> | `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) | <ide><path>docs/basic-features/data-fetching/incremental-static-regeneration.md <ide> description: 'Learn how to create or update static pages at runtime with Increme <ide> <ide> | Version | Changes | <ide> | --------- | --------------------------------------------------------------------------------------- | <del>| `v12.1.0` | On-demand ISR added (Beta). | <add>| `v12.1.0` | On-Demand ISR added (Beta). | <ide> | `v12.0.0` | [Bot-aware ISR fallback](https://nextjs.org/blog/next-12#bot-aware-isr-fallback) added. | <ide> | `v9.5.0` | Base Path added. | <ide> <ide> When a request is made to a path that hasn’t been generated, Next.js will serv <ide> <ide> If you set a `revalidate` time of `60`, all visitors will see the same generated version of your site for one minute. The only way to invalidate the cache is from someone visiting that page after the minute has passed. <ide> <del>Starting with `v12.1.0`, Next.js supports on-demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page. This makes it easier to update your site when: <add>Starting with `v12.1.0`, Next.js supports On-Demand Incremental Static Regeneration to manually purge the Next.js cache for a specific page. This makes it easier to update your site when: <ide> <ide> - Content from your headless CMS is created or updated <ide> - Ecommerce metadata changes (price, description, category, reviews, etc.) <ide> export default async function handler(req, res) { <ide> <ide> [View our demo](https://on-demand-isr.vercel.app) to see on-demand revalidation in action and provide feedback. <ide> <del>### Testing on-demand ISR during development <add>### Testing on-Demand ISR during development <ide> <ide> When running locally with `next dev`, `getStaticProps` is invoked on every request. To verify your on-demand ISR configuration is correct, you will need to create a [production build](/docs/api-reference/cli.md#build) and start the [production server](/docs/api-reference/cli.md#production): <ide>
3
PHP
PHP
remove unused import
b57eb65a6f499e5c32b80eccd2dd25935aba7f4d
<ide><path>src/Illuminate/Cache/CacheServiceProvider.php <ide> <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Cache\Console\ClearCommand; <del>use Illuminate\Cache\Console\CacheTableCommand; <ide> <ide> class CacheServiceProvider extends ServiceProvider <ide> { <ide><path>src/Illuminate/Database/MigrationServiceProvider.php <ide> use Illuminate\Database\Migrations\Migrator; <ide> use Illuminate\Database\Migrations\MigrationCreator; <ide> use Illuminate\Database\Console\Migrations\ResetCommand; <del>use Illuminate\Database\Console\Migrations\RefreshCommand; <add>use Illuminate\Database\Console\Migrations\StatusCommand; <ide> use Illuminate\Database\Console\Migrations\InstallCommand; <ide> use Illuminate\Database\Console\Migrations\MigrateCommand; <add>use Illuminate\Database\Console\Migrations\RefreshCommand; <ide> use Illuminate\Database\Console\Migrations\RollbackCommand; <del>use Illuminate\Database\Console\Migrations\MigrateMakeCommand; <del>use Illuminate\Database\Console\Migrations\StatusCommand; <ide> use Illuminate\Database\Migrations\DatabaseMigrationRepository; <ide> <ide> class MigrationServiceProvider extends ServiceProvider <ide><path>src/Illuminate/Database/SeedServiceProvider.php <ide> <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Database\Console\Seeds\SeedCommand; <del>use Illuminate\Database\Console\Seeds\SeederMakeCommand; <ide> <ide> class SeedServiceProvider extends ServiceProvider <ide> {
3
PHP
PHP
add type hints
43c62439315bbf91b7c70c8fe202a869efdf3de4
<ide><path>src/Mailer/Email.php <ide> use Cake\Core\StaticConfigTrait; <ide> use Cake\Log\Log; <ide> use Cake\Utility\Text; <add>use Cake\View\ViewBuilder; <ide> use InvalidArgumentException; <ide> use JsonSerializable; <ide> use LogicException; <ide> public function __clone() <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> public function setFrom($email, $name = null) <add> public function setFrom($email, ?string $name = null): self <ide> { <ide> return $this->_setEmailSingle('_from', $email, $name, 'From requires only 1 email address.'); <ide> } <ide> public function setFrom($email, $name = null) <ide> * <ide> * @return array <ide> */ <del> public function getFrom() <add> public function getFrom(): array <ide> { <ide> return $this->_from; <ide> } <ide> public function getFrom() <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> public function setSender($email, $name = null) <add> public function setSender($email, ?string $name = null): self <ide> { <ide> return $this->_setEmailSingle('_sender', $email, $name, 'Sender requires only 1 email address.'); <ide> } <ide> public function setSender($email, $name = null) <ide> * <ide> * @return array <ide> */ <del> public function getSender() <add> public function getSender(): array <ide> { <ide> return $this->_sender; <ide> } <ide> public function getSender() <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> public function setReplyTo($email, $name = null) <add> public function setReplyTo($email, ?string $name = null): self <ide> { <ide> return $this->_setEmailSingle('_replyTo', $email, $name, 'Reply-To requires only 1 email address.'); <ide> } <ide> public function setReplyTo($email, $name = null) <ide> * <ide> * @return array <ide> */ <del> public function getReplyTo() <add> public function getReplyTo(): array <ide> { <ide> return $this->_replyTo; <ide> } <ide> public function setTo($email, ?string $name = null): self <ide> * <ide> * @return array <ide> */ <del> public function getTo() <add> public function getTo(): array <ide> { <ide> return $this->_to; <ide> } <ide> public function getEmailPattern(): ?string <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> protected function _setEmail($varName, $email, $name) <add> protected function _setEmail(string $varName, $email, ?string $name): self <ide> { <ide> if (!is_array($email)) { <ide> $this->_validateEmail($email, $varName); <ide> protected function _setEmail($varName, $email, $name) <ide> * @return void <ide> * @throws \InvalidArgumentException If email address does not validate <ide> */ <del> protected function _validateEmail($email, $context) <add> protected function _validateEmail(string $email, string $context): void <ide> { <ide> if ($this->_emailPattern === null) { <ide> if (filter_var($email, FILTER_VALIDATE_EMAIL)) { <ide> protected function _validateEmail($email, $context) <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> protected function _setEmailSingle($varName, $email, $name, $throwMessage) <add> protected function _setEmailSingle(string $varName, $email, ?string $name, string $throwMessage): self <ide> { <ide> if ($email === []) { <ide> $this->{$varName} = $email; <ide> protected function _setEmailSingle($varName, $email, $name, $throwMessage) <ide> * @return $this <ide> * @throws \InvalidArgumentException <ide> */ <del> protected function _addEmail($varName, $email, $name) <add> protected function _addEmail(string $varName, $email, ?string $name): self <ide> { <ide> if (!is_array($email)) { <ide> $this->_validateEmail($email, $varName); <ide> public function getHeaders(array $include = []): array <ide> * @param array $address Addresses to format. <ide> * @return array <ide> */ <del> protected function _formatAddress($address) <add> protected function _formatAddress(array $address): array <ide> { <ide> $return = []; <ide> foreach ($address as $email => $alias) { <ide> public function send($content = null): array <ide> * @param string|null $content Content array or string <ide> * @return void <ide> */ <del> public function render(?string $content = null) <add> public function render(?string $content = null): void <ide> { <ide> list($this->_message, <ide> $this->_boundary, <ide> public function render(?string $content = null) <ide> ) = $this->getRenderer()->render($this, $content); <ide> } <ide> <del> public function viewBuilder() <add> public function viewBuilder(): ViewBuilder <ide> { <ide> return $this->getRenderer()->viewBuilder(); <ide> } <ide> <del> protected function getRenderer() <add> protected function getRenderer(): Renderer <ide> { <ide> if ($this->renderer === null) { <ide> $this->renderer = new Renderer(); <ide> protected function getRenderer() <ide> return $this->renderer; <ide> } <ide> <del> protected function setRenderer(Renderer $renderer) <add> protected function setRenderer(Renderer $renderer): self <ide> { <ide> $this->renderer = $renderer; <ide> <ide> protected function setRenderer(Renderer $renderer) <ide> * @param array $contents The content with 'headers' and 'message' keys. <ide> * @return void <ide> */ <del> protected function _logDelivery($contents) <add> protected function _logDelivery($contents): void <ide> { <ide> if (empty($this->_profile['log'])) { <ide> return; <ide> protected function _logDelivery($contents) <ide> * @param string|array $value The value to convert <ide> * @return string <ide> */ <del> protected function flatten($value) <add> protected function flatten($value): string <ide> { <ide> return is_array($value) ? implode(';', $value) : $value; <ide> } <ide> public static function deliver( <ide> * @return void <ide> * @throws \InvalidArgumentException When using a configuration that doesn't exist. <ide> */ <del> protected function _applyConfig($config) <add> protected function _applyConfig($config): void <ide> { <ide> if (is_string($config)) { <ide> $name = $config; <ide> public function reset(): self <ide> * @param string $text String to encode <ide> * @return string Encoded string <ide> */ <del> protected function _encode($text) <add> protected function _encode(string $text): string <ide> { <ide> $restore = mb_internal_encoding(); <ide> mb_internal_encoding($this->_appCharset); <ide> protected function _encode($text) <ide> * @param string $text String to decode <ide> * @return string Decoded string <ide> */ <del> protected function _decode($text) <add> protected function _decode(string $text): string <ide> { <ide> $restore = mb_internal_encoding(); <ide> mb_internal_encoding($this->_appCharset); <ide> protected function _decode($text) <ide> * @param string $path The absolute path to the file to read. <ide> * @return string File contents in base64 encoding <ide> */ <del> protected function _readFile($path) <add> protected function _readFile(string $path): string <ide> { <ide> return chunk_split(base64_encode((string)file_get_contents($path))); <ide> } <ide> protected function _readFile($path) <ide> * <ide> * @return string <ide> */ <del> public function getContentTransferEncoding() <add> public function getContentTransferEncoding(): string <ide> { <ide> if ($this->transferEncoding) { <ide> return $this->transferEncoding; <ide> public function getContentTransferEncoding() <ide> * <ide> * @return string <ide> */ <del> public function getContentTypeCharset() <add> public function getContentTypeCharset(): string <ide> { <ide> $charset = strtoupper($this->charset); <ide> if (array_key_exists($charset, $this->_contentTypeCharset)) { <ide><path>tests/TestCase/Mailer/EmailTest.php <ide> public function testToUnderscoreDomain() <ide> public static function invalidEmails() <ide> { <ide> return [ <del> [1.0], <ide> [''], <ide> ['string'], <ide> ['<tag>'], <del> [['ok@cakephp.org', 1.0, '', 'string']], <add> [['ok@cakephp.org', '1.0', '', 'string']], <ide> ]; <ide> } <ide>
2
PHP
PHP
add a testplugin.comment for the new testcases
8fc94e2ad91890e64c8acd6cc2af6dbd9f05c45a
<ide><path>tests/test_app/Plugin/TestPlugin/src/Model/Entity/Comment.php <add><?php <add> <add>namespace TestPlugin\Model\Entity; <add> <add>use Cake\ORM\Entity; <add> <add>/** <add> * Tests entity class used for asserting correct loading in plugins <add> * <add> */ <add>class Comment extends Entity { <add> <add>}
1
Python
Python
update convert_to_threejs.py
6c12df36047a7066ee6e29fa5ef942f71a165c7a
<ide><path>utils/converters/fbx/convert_to_threejs.py <ide> def generate_material_object(material): <ide> } <ide> <ide> else: <del> print "Unknown type of Material", getMaterialName(material) <add> print ("Unknown type of Material"), getMaterialName(material) <ide> <ide> # default to Lambert Material if the current Material type cannot be handeled <ide> if not material_type: <ide> def copy_textures(textures): <ide> shutil.copyfile(url, saveFilename) <ide> texture_dict[url] = True <ide> except IOError as e: <del> print "I/O error({0}): {1} {2}".format(e.errno, e.strerror, url) <add> print ("I/O error({0}): {1} {2}").format(e.errno, e.strerror, url) <ide> <ide> def findFilesWithExt(directory, ext, include_path = True): <ide> ext = ext.lower()
1
PHP
PHP
remove unused var
42d4f20a31bb9a0fd01d55b9cf175e3e94f909b3
<ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> public function testBeforeRedirectCallbackWithArrayUrl() <ide> $RequestHandler->response = $this->Controller->response; <ide> <ide> ob_start(); <del> $response = $RequestHandler->beforeRedirect( <add> $RequestHandler->beforeRedirect( <ide> $event, <ide> ['controller' => 'RequestHandlerTest', 'action' => 'param_method', 'first', 'second'], <ide> $this->Controller->response
1
Ruby
Ruby
link tmp kegs during rescue
096a5bdfb431b366d9a67340366195e805efc748
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install_dependency(dep, inherited_options) <ide> oh1 "Installing #{formula.full_name} dependency: #{Formatter.identifier(dep.name)}" <ide> fi.install <ide> fi.finish <del> rescue FormulaInstallationAlreadyAttemptedError <del> # We already attempted to install f as part of the dependency tree of <del> # another formula. In that case, don't generate an error, just move on. <del> nil <del> rescue Exception # rubocop:disable Lint/RescueException <add> rescue Exception => e # rubocop:disable Lint/RescueException <ide> ignore_interrupts do <ide> tmp_keg.rename(installed_keg) if tmp_keg && !installed_keg.directory? <ide> linked_keg.link if keg_was_linked <ide> end <del> raise <add> raise unless e.is_a? FormulaInstallationAlreadyAttemptedError <add> <add> # We already attempted to install f as part of another formula's <add> # dependency tree. In that case, don't generate an error, just move on. <add> nil <ide> else <ide> ignore_interrupts { tmp_keg.rmtree if tmp_keg&.directory? } <ide> end
1
Ruby
Ruby
remove unnecessary arguments. references
c2ea2874475f4f93fe087ef63cdeee020dc98cdd
<ide><path>actionpack/lib/action_view/partials.rb <ide> def render_partial_collection(partial_path, collection, partial_spacer_template <ide> spacer = partial_spacer_template ? render(:partial => partial_spacer_template) : '' <ide> <ide> if partial_path.nil? <del> render_partial_collection_with_unknown_partial_path(collection, local_assigns, spacer) <add> render_partial_collection_with_unknown_partial_path(collection, local_assigns) <ide> else <del> render_partial_collection_with_known_partial_path(collection, partial_path, local_assigns, spacer) <add> render_partial_collection_with_known_partial_path(collection, partial_path, local_assigns) <ide> end.join(spacer) <ide> end <ide> <del> def render_partial_collection_with_known_partial_path(collection, partial_path, local_assigns, spacer) <add> def render_partial_collection_with_known_partial_path(collection, partial_path, local_assigns) <ide> template = ActionView::PartialTemplate.new(self, partial_path, nil, local_assigns) <ide> collection.map do |element| <ide> template.render_member(element) <ide> end <ide> end <ide> <del> def render_partial_collection_with_unknown_partial_path(collection, local_assigns, spacer) <add> def render_partial_collection_with_unknown_partial_path(collection, local_assigns) <ide> templates = Hash.new <ide> i = 0 <ide> collection.map do |element|
1
PHP
PHP
ignore error reported by phpstan
7f2322c88cca8c60c06fc464ae25e80d46b15e11
<ide><path>src/Database/Expression/WhenThenExpression.php <ide> public function when($when, $type = null) <ide> 'The `$when` argument must be either a non-empty array, a scalar value, an object, ' . <ide> 'or an instance of `\%s`, `%s` given.', <ide> ExpressionInterface::class, <del> is_array($when) ? '[]' : getTypeName($when) <add> is_array($when) ? '[]' : getTypeName($when) // @phpstan-ignore-line <ide> )); <ide> } <ide>
1
Python
Python
fix dummy provider nodelocation ids; libcloud-70
c2c1c71e8555b05aaa535cd83130fb9bbbbb580c
<ide><path>libcloud/drivers/dummy.py <ide> def list_locations(self): <ide> name="Paul's Room", <ide> country='US', <ide> driver=self), <del> NodeLocation(id=1, <add> NodeLocation(id=2, <ide> name="London Loft", <ide> country='GB', <ide> driver=self), <del> NodeLocation(id=1, <add> NodeLocation(id=3, <ide> name="Island Datacenter", <ide> country='FJ', <ide> driver=self),
1
PHP
PHP
use strict checks
62c6aeb6f7e1e3d1a6e94f22a1d219ff7c1f50cc
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function testEmptyPaginationResult() <ide> <ide> $this->Paginator->paginate($table); <ide> <del> $this->assertEquals( <add> $this->assertSame( <ide> 0, <ide> $this->request->params['paging']['PaginatorPosts']['count'], <ide> 'Count should be 0' <ide> ); <del> $this->assertEquals( <add> $this->assertSame( <ide> 1, <ide> $this->request->params['paging']['PaginatorPosts']['page'], <ide> 'Page number should not be 0' <ide> ); <del> $this->assertEquals( <add> $this->assertSame( <ide> 1, <ide> $this->request->params['paging']['PaginatorPosts']['pageCount'], <ide> 'Page count number should not be 0'
1
Javascript
Javascript
add additional test case for variable leaking
4f7e2da365ac10e4e718c05430bbedab64fe31f5
<ide><path>test/cases/entry-inline/no-var-leak-strict/index.js <add>var localVar = 42; <add> <add>it("should not leak localVar to other modules", () => { <add> expect(localVar).toBe(42); <add> import(/* webpackMode: "eager" */ "./module").then(module => { <add> expect(module.default).toBe("undefined"); <add> }); <add>}); <add> <add>export {}; <ide><path>test/cases/entry-inline/no-var-leak-strict/module.js <add>export default typeof localVar; <ide><path>test/cases/entry-inline/no-var-leak/index.js <add>var localVar = 42; <add> <add>it("should not leak localVar to other modules", () => { <add> expect(localVar).toBe(42); <add> expect(require("./module")).toBe("undefined"); <add>}); <ide><path>test/cases/entry-inline/no-var-leak/module.js <add>module.exports = typeof localVar;
4
Java
Java
use taskexecutor instead of threadpooltaskexecutor
e09c5fd9e567d6e9058205789e7bb3ecf54a87fb
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.event.SmartApplicationListener; <add>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.MessageHandler; <ide> import org.springframework.messaging.converter.ByteArrayMessageConverter; <ide> public AbstractSubscribableChannel clientInboundChannel() { <ide> } <ide> <ide> @Bean <del> public ThreadPoolTaskExecutor clientInboundChannelExecutor() { <add> public TaskExecutor clientInboundChannelExecutor() { <ide> TaskExecutorRegistration reg = getClientInboundChannelRegistration().taskExecutor(); <ide> ThreadPoolTaskExecutor executor = reg.getTaskExecutor(); <ide> executor.setThreadNamePrefix("clientInboundChannel-"); <ide> public AbstractSubscribableChannel clientOutboundChannel() { <ide> } <ide> <ide> @Bean <del> public ThreadPoolTaskExecutor clientOutboundChannelExecutor() { <add> public TaskExecutor clientOutboundChannelExecutor() { <ide> TaskExecutorRegistration reg = getClientOutboundChannelRegistration().taskExecutor(); <ide> ThreadPoolTaskExecutor executor = reg.getTaskExecutor(); <ide> executor.setThreadNamePrefix("clientOutboundChannel-"); <ide> public AbstractSubscribableChannel brokerChannel() { <ide> } <ide> <ide> @Bean <del> public ThreadPoolTaskExecutor brokerChannelExecutor() { <add> public TaskExecutor brokerChannelExecutor() { <ide> ChannelRegistration reg = getBrokerRegistry().getBrokerChannelRegistration(); <ide> ThreadPoolTaskExecutor executor; <ide> if (reg.hasTaskExecutor()) { <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketMessageBrokerStats.java <ide> import java.time.Instant; <ide> import java.util.concurrent.Executor; <ide> import java.util.concurrent.ScheduledFuture; <del>import java.util.concurrent.ThreadPoolExecutor; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> <add>import org.springframework.core.task.TaskExecutor; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler; <ide> import org.springframework.scheduling.TaskScheduler; <ide> public class WebSocketMessageBrokerStats { <ide> private StompBrokerRelayMessageHandler stompBrokerRelay; <ide> <ide> @Nullable <del> private ThreadPoolExecutor inboundChannelExecutor; <add> private TaskExecutor inboundChannelExecutor; <ide> <ide> @Nullable <del> private ThreadPoolExecutor outboundChannelExecutor; <add> private TaskExecutor outboundChannelExecutor; <ide> <ide> @Nullable <ide> private TaskScheduler sockJsTaskScheduler; <ide> public void setStompBrokerRelay(StompBrokerRelayMessageHandler stompBrokerRelay) <ide> this.stompBrokerRelay = stompBrokerRelay; <ide> } <ide> <del> public void setInboundChannelExecutor(ThreadPoolTaskExecutor inboundChannelExecutor) { <del> this.inboundChannelExecutor = inboundChannelExecutor.getThreadPoolExecutor(); <add> public void setInboundChannelExecutor(TaskExecutor inboundChannelExecutor) { <add> this.inboundChannelExecutor = inboundChannelExecutor; <ide> } <ide> <del> public void setOutboundChannelExecutor(ThreadPoolTaskExecutor outboundChannelExecutor) { <del> this.outboundChannelExecutor = outboundChannelExecutor.getThreadPoolExecutor(); <add> public void setOutboundChannelExecutor(TaskExecutor outboundChannelExecutor) { <add> this.outboundChannelExecutor = outboundChannelExecutor; <ide> } <ide> <ide> public void setSockJsTaskScheduler(TaskScheduler sockJsTaskScheduler) { <ide> public String getStompBrokerRelayStatsInfo() { <ide> * Get stats about the executor processing incoming messages from WebSocket clients. <ide> */ <ide> public String getClientInboundExecutorStatsInfo() { <del> return (this.inboundChannelExecutor != null ? getExecutorStatsInfo(this.inboundChannelExecutor) : "null"); <add> return (this.inboundChannelExecutor != null ? <add> getExecutorStatsInfo(this.inboundChannelExecutor) : "null"); <ide> } <ide> <ide> /** <ide> * Get stats about the executor processing outgoing messages to WebSocket clients. <ide> */ <ide> public String getClientOutboundExecutorStatsInfo() { <del> return (this.outboundChannelExecutor != null ? getExecutorStatsInfo(this.outboundChannelExecutor) : "null"); <add> return (this.outboundChannelExecutor != null ? <add> getExecutorStatsInfo(this.outboundChannelExecutor) : "null"); <ide> } <ide> <ide> /** <ide> public String getSockJsTaskSchedulerStatsInfo() { <ide> } <ide> <ide> private String getExecutorStatsInfo(Executor executor) { <add> executor = executor instanceof ThreadPoolTaskExecutor ? <add> ((ThreadPoolTaskExecutor) executor).getThreadPoolExecutor() : executor; <ide> String str = executor.toString(); <ide> return str.substring(str.indexOf("pool"), str.length() - 1); <ide> }
2
Python
Python
add learning_rate to the summary
ee760015b4748488380c4a7b3d36fa6099e558ea
<ide><path>official/nlp/bert/model_training_utils.py <ide> def _run_evaluation(current_training_step, test_iterator): <ide> summary_writer = tf.summary.create_noop_writer() <ide> <ide> with summary_writer.as_default(): <add> if callable(optimizer.learning_rate): <add> tf.summary.scalar( <add> 'learning_rate', <add> optimizer.learning_rate(current_step), <add> step=current_step) <ide> tf.summary.scalar( <ide> train_loss_metric.name, train_loss, step=current_step) <ide> for metric in train_metrics + model.metrics:
1
Java
Java
add support for resolving message headers
8ae88c20d1e8808d852e37908da2a5fc6b5e077a
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/core/DestinationResolutionException.java <ide> import org.springframework.messaging.MessagingException; <ide> <ide> /** <del> * Thrown by a ChannelResolver when it cannot resolve a channel name. <add> * Thrown by a {@link DestinationResolver} when it cannot resolve a destination. <ide> * <ide> * @author Mark Fisher <add> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> @SuppressWarnings("serial") <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Header.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation; <add> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.ElementType; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.RetentionPolicy; <add>import java.lang.annotation.Target; <add> <add> <add>/** <add> * Annotation which indicates that a method parameter should be bound to a message header. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>@Target(ElementType.PARAMETER) <add>@Retention(RetentionPolicy.RUNTIME) <add>@Documented <add>public @interface Header { <add> <add> /** <add> * The name of the request header to bind to. <add> */ <add> String value() default ""; <add> <add> /** <add> * Whether the header is required. <add> * <p> <add> * Default is {@code true}, leading to an exception if the header missing. Switch this <add> * to {@code false} if you prefer a {@code null} in case of the header missing. <add> */ <add> boolean required() default true; <add> <add> /** <add> * The default value to use as a fallback. Supplying a default value implicitly <add> * sets {@link #required} to {@code false}. <add> */ <add> String defaultValue() default ValueConstants.DEFAULT_NONE; <add> <add>} <add><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Headers.java <del><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageBody.java <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <del>import org.springframework.messaging.Message; <del> <ide> <ide> /** <del> * Annotation indicating a method parameter should be bound to the body of a <del> * {@link Message}. <add> * Annotation which indicates that a method parameter should be bound to the headers of a <add> * message. The annotated parameter must be assignable to {@link java.util.Map} with <add> * String keys and Object values. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <ide> @Target(ElementType.PARAMETER) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Documented <del>public @interface MessageBody { <del> <del> /** <del> * Whether body content is required. <del> * <p>Default is {@code true}, leading to an exception thrown in case <del> * there is no body content. Switch this to {@code false} if you prefer <del> * {@code null} to be passed when the body content is {@code null}. <del> */ <del> boolean required() default true; <add>public @interface Headers { <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation; <add> <add>import java.lang.annotation.Documented; <add>import java.lang.annotation.ElementType; <add>import java.lang.annotation.Retention; <add>import java.lang.annotation.RetentionPolicy; <add>import java.lang.annotation.Target; <add> <add>import org.springframework.messaging.support.converter.MessageConverter; <add> <add> <add>/** <add> * Annotation that binds a method parameter to the payload of a message. The payload may <add> * be passed through a {@link MessageConverter} to convert it from serialized form with a <add> * specific MIME type to an Object matching the target method parameter. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>@Target(ElementType.PARAMETER) <add>@Retention(RetentionPolicy.RUNTIME) <add>@Documented <add>public @interface Payload { <add> <add> /** <add> * Whether payload content is required. <add> * <p> <add> * Default is {@code true}, leading to an exception if there is no payload. Switch to <add> * {@code false} to have {@code null} passed when there is no payload. <add> */ <add> boolean required() default true; <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/ValueConstants.java <add>/* <add> * Copyright 2002-2012 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation; <add> <add>/** <add> * Common annotation value constants. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public interface ValueConstants { <add> <add> /** <add> * Constant defining a value for no default - as a replacement for {@code null} which <add> * we cannot use in annotation attributes. <add> * <p> <add> * This is an artificial arrangement of 16 unicode characters, with its sole purpose <add> * being to never match user-declared values. <add> * <add> * @see Header#defaultValue() <add> */ <add> String DEFAULT_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n"; <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/AbstractNamedValueMethodArgumentResolver.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import java.util.Map; <add>import java.util.concurrent.ConcurrentHashMap; <add> <add>import org.springframework.beans.factory.config.BeanExpressionContext; <add>import org.springframework.beans.factory.config.BeanExpressionResolver; <add>import org.springframework.beans.factory.config.ConfigurableBeanFactory; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.core.convert.TypeDescriptor; <add>import org.springframework.core.convert.support.DefaultConversionService; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.handler.annotation.ValueConstants; <add>import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver; <add>import org.springframework.util.Assert; <add>import org.springframework.util.ClassUtils; <add> <add> <add>/** <add> * Abstract base class for resolving method arguments from a named value. Message headers, <add> * and path variables are examples of named values. Each may have a name, a required flag, <add> * and a default value. <add> * <p> <add> * Subclasses define how to do the following: <add> * <ul> <add> * <li>Obtain named value information for a method parameter <add> * <li>Resolve names into argument values <add> * <li>Handle missing argument values when argument values are required <add> * <li>Optionally handle a resolved value <add> * </ul> <add> * <p> <add> * A default value string can contain ${...} placeholders and Spring Expression Language <add> * #{...} expressions. For this to work a {@link ConfigurableBeanFactory} must be supplied <add> * to the class constructor. <add> * <p> <add> * A {@link ConversionService} may be used to apply type conversion to the resolved <add> * argument value if it doesn't match the method parameter type. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver { <add> <add> private final ConfigurableBeanFactory configurableBeanFactory; <add> <add> private final BeanExpressionContext expressionContext; <add> <add> private Map<MethodParameter, NamedValueInfo> namedValueInfoCache = <add> new ConcurrentHashMap<MethodParameter, NamedValueInfo>(256); <add> <add> private ConversionService conversionService; <add> <add> <add> /** <add> * Constructor with a {@link ConversionService} and a {@link BeanFactory}. <add> * <add> * @param cs conversion service for converting values to match the <add> * target method parameter type <add> * @param beanFactory a bean factory to use for resolving ${...} placeholder and <add> * #{...} SpEL expressions in default values, or {@code null} if default values <add> * are not expected to contain expressions <add> */ <add> protected AbstractNamedValueMethodArgumentResolver(ConversionService cs, ConfigurableBeanFactory beanFactory) { <add> this.conversionService = (cs != null) ? cs : new DefaultConversionService(); <add> this.configurableBeanFactory = beanFactory; <add> this.expressionContext = (beanFactory != null) ? new BeanExpressionContext(beanFactory, null) : null; <add> } <add> <add> <add> @Override <add> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <add> <add> Class<?> paramType = parameter.getParameterType(); <add> NamedValueInfo namedValueInfo = getNamedValueInfo(parameter); <add> <add> Object value = resolveArgumentInternal(parameter, message, namedValueInfo.name); <add> if (value == null) { <add> if (namedValueInfo.defaultValue != null) { <add> value = resolveDefaultValue(namedValueInfo.defaultValue); <add> } <add> else if (namedValueInfo.required) { <add> handleMissingValue(namedValueInfo.name, parameter, message); <add> } <add> value = handleNullValue(namedValueInfo.name, value, paramType); <add> } <add> else if ("".equals(value) && (namedValueInfo.defaultValue != null)) { <add> value = resolveDefaultValue(namedValueInfo.defaultValue); <add> } <add> <add> if (!ClassUtils.isAssignableValue(paramType, value)) { <add> value = this.conversionService.convert(value, <add> TypeDescriptor.valueOf(value.getClass()), new TypeDescriptor(parameter)); <add> } <add> <add> handleResolvedValue(value, namedValueInfo.name, parameter, message); <add> <add> return value; <add> } <add> <add> /** <add> * Obtain the named value for the given method parameter. <add> */ <add> private NamedValueInfo getNamedValueInfo(MethodParameter parameter) { <add> NamedValueInfo namedValueInfo = this.namedValueInfoCache.get(parameter); <add> if (namedValueInfo == null) { <add> namedValueInfo = createNamedValueInfo(parameter); <add> namedValueInfo = updateNamedValueInfo(parameter, namedValueInfo); <add> this.namedValueInfoCache.put(parameter, namedValueInfo); <add> } <add> return namedValueInfo; <add> } <add> <add> /** <add> * Create the {@link NamedValueInfo} object for the given method parameter. Implementations typically <add> * retrieve the method annotation by means of {@link MethodParameter#getParameterAnnotation(Class)}. <add> * @param parameter the method parameter <add> * @return the named value information <add> */ <add> protected abstract NamedValueInfo createNamedValueInfo(MethodParameter parameter); <add> <add> /** <add> * Create a new NamedValueInfo based on the given NamedValueInfo with sanitized values. <add> */ <add> private NamedValueInfo updateNamedValueInfo(MethodParameter parameter, NamedValueInfo info) { <add> String name = info.name; <add> if (info.name.length() == 0) { <add> name = parameter.getParameterName(); <add> Assert.notNull(name, "Name for argument type [" + parameter.getParameterType().getName() <add> + "] not available, and parameter name information not found in class file either."); <add> } <add> String defaultValue = ValueConstants.DEFAULT_NONE.equals(info.defaultValue) ? null : info.defaultValue; <add> return new NamedValueInfo(name, info.required, defaultValue); <add> } <add> <add> /** <add> * Resolves the given parameter type and value name into an argument value. <add> * @param parameter the method parameter to resolve to an argument value <add> * @param message the current request <add> * @param name the name of the value being resolved <add> * <add> * @return the resolved argument. May be {@code null} <add> * @throws Exception in case of errors <add> */ <add> protected abstract Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) <add> throws Exception; <add> <add> /** <add> * Resolves the given default value into an argument value. <add> */ <add> private Object resolveDefaultValue(String defaultValue) { <add> if (this.configurableBeanFactory == null) { <add> return defaultValue; <add> } <add> String placeholdersResolved = this.configurableBeanFactory.resolveEmbeddedValue(defaultValue); <add> BeanExpressionResolver exprResolver = this.configurableBeanFactory.getBeanExpressionResolver(); <add> if (exprResolver == null) { <add> return defaultValue; <add> } <add> return exprResolver.evaluate(placeholdersResolved, this.expressionContext); <add> } <add> <add> /** <add> * Invoked when a named value is required, but <add> * {@link #resolveArgumentInternal(MethodParameter, Message, String)} returned {@code null} and <add> * there is no default value. Subclasses typically throw an exception in this case. <add> * <add> * @param name the name for the value <add> * @param parameter the method parameter <add> * @param message the message being processed <add> */ <add> protected abstract void handleMissingValue(String name, MethodParameter parameter, Message<?> message); <add> <add> /** <add> * A {@code null} results in a {@code false} value for {@code boolean}s or an <add> * exception for other primitives. <add> */ <add> private Object handleNullValue(String name, Object value, Class<?> paramType) { <add> if (value == null) { <add> if (Boolean.TYPE.equals(paramType)) { <add> return Boolean.FALSE; <add> } <add> else if (paramType.isPrimitive()) { <add> throw new IllegalStateException("Optional " + paramType + " parameter '" + name + <add> "' is present but cannot be translated into a null value due to being " + <add> "declared as a primitive type. Consider declaring it as object wrapper " + <add> "for the corresponding primitive type."); <add> } <add> } <add> return value; <add> } <add> <add> /** <add> * Invoked after a value is resolved. <add> * <add> * @param arg the resolved argument value <add> * @param name the argument name <add> * @param parameter the argument parameter type <add> * @param message the message <add> */ <add> protected void handleResolvedValue(Object arg, String name, MethodParameter parameter, Message<?> message) { <add> } <add> <add> <add> /** <add> * Represents the information about a named value, including name, whether it's <add> * required and a default value. <add> */ <add> protected static class NamedValueInfo { <add> <add> private final String name; <add> <add> private final boolean required; <add> <add> private final String defaultValue; <add> <add> protected NamedValueInfo(String name, boolean required, String defaultValue) { <add> this.name = name; <add> this.required = required; <add> this.defaultValue = defaultValue; <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolver.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import org.springframework.beans.factory.config.ConfigurableBeanFactory; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.handler.annotation.Header; <add> <add> <add>/** <add> * Resolves method parameters annotated with {@link Header @Header}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class HeaderMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver { <add> <add> <add> public HeaderMethodArgumentResolver(ConversionService cs, ConfigurableBeanFactory beanFactory) { <add> super(cs, beanFactory); <add> } <add> <add> @Override <add> public boolean supportsParameter(MethodParameter parameter) { <add> return parameter.hasParameterAnnotation(Header.class); <add> } <add> <add> @Override <add> protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { <add> Header annotation = parameter.getParameterAnnotation(Header.class); <add> return new HeaderNamedValueInfo(annotation); <add> } <add> <add> @Override <add> protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, <add> String name) throws Exception { <add> <add> return message.getHeaders().get(name); <add> } <add> <add> @Override <add> protected void handleMissingValue(String headerName, MethodParameter parameter, Message<?> message) { <add> throw new MessageHandlingException(message, "Missing header '" + headerName + <add> "' for method parameter type [" + parameter.getParameterType() + "]"); <add> } <add> <add> <add> private static class HeaderNamedValueInfo extends NamedValueInfo { <add> <add> private HeaderNamedValueInfo(Header annotation) { <add> super(annotation.value(), annotation.required(), annotation.defaultValue()); <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolver.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import java.lang.reflect.Method; <add>import java.util.Map; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.handler.annotation.Header; <add>import org.springframework.messaging.handler.annotation.Headers; <add>import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver; <add>import org.springframework.messaging.support.MessageHeaderAccessor; <add>import org.springframework.util.ClassUtils; <add>import org.springframework.util.ReflectionUtils; <add> <add> <add>/** <add> * Resolves the following method parameters: <add> * <ul> <add> * <li>Parameters assignable to {@link Map} annotated with {@link Header @Headers} <add> * <li>Parameters of type {@link MessageHeaders} <add> * <li>Parameters assignable to {@link MessageHeaderAccessor} <add> * </ul> <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class HeadersMethodArgumentResolver implements HandlerMethodArgumentResolver { <add> <add> <add> @Override <add> public boolean supportsParameter(MethodParameter parameter) { <add> Class<?> paramType = parameter.getParameterType(); <add> return ((parameter.hasParameterAnnotation(Headers.class) && Map.class.isAssignableFrom(paramType)) || <add> MessageHeaders.class.equals(paramType) || <add> MessageHeaderAccessor.class.isAssignableFrom(paramType)); <add> } <add> <add> @Override <add> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <add> <add> Class<?> paramType = parameter.getParameterType(); <add> <add> if (Map.class.isAssignableFrom(paramType)) { <add> return message.getHeaders(); <add> } <add> else if (MessageHeaderAccessor.class.equals(paramType)) { <add> return new MessageHeaderAccessor(message); <add> } <add> else if (MessageHeaderAccessor.class.isAssignableFrom(paramType)) { <add> Method factoryMethod = ClassUtils.getMethod(paramType, "wrap", Message.class); <add> return ReflectionUtils.invokeMethod(factoryMethod, null, message); <add> } <add> else { <add> throw new IllegalStateException("Unexpected method parameter type " <add> + paramType + "in method " + parameter.getMethod() + ". " <add> + "@Headers method arguments must be assignable to java.util.Map."); <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/MessageBodyMethodArgumentResolver.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.messaging.handler.annotation.support; <del> <del>import org.springframework.core.MethodParameter; <del>import org.springframework.messaging.Message; <del>import org.springframework.messaging.handler.annotation.MessageBody; <del>import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver; <del>import org.springframework.messaging.support.converter.MessageConverter; <del>import org.springframework.util.Assert; <del> <del> <del>/** <del> * A resolver for extracting the body of a message. <del> * <del> * <p>This {@link HandlerMethodArgumentResolver} should be ordered last as it supports all <del> * types and does not require the {@link MessageBody} annotation. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>public class MessageBodyMethodArgumentResolver implements HandlerMethodArgumentResolver { <del> <del> private final MessageConverter converter; <del> <del> <del> public MessageBodyMethodArgumentResolver(MessageConverter converter) { <del> Assert.notNull(converter, "converter is required"); <del> this.converter = converter; <del> } <del> <del> @Override <del> public boolean supportsParameter(MethodParameter parameter) { <del> return true; <del> } <del> <del> @Override <del> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <del> <del> Object arg = null; <del> <del> MessageBody annot = parameter.getParameterAnnotation(MessageBody.class); <del> <del> if (annot == null || annot.required()) { <del> Class<?> sourceClass = message.getPayload().getClass(); <del> Class<?> targetClass = parameter.getParameterType(); <del> if (targetClass.isAssignableFrom(sourceClass)) { <del> return message.getPayload(); <del> } <del> else { <del> return this.converter.fromMessage(message, targetClass); <del> } <del> } <del> <del> return arg; <del> } <del> <del>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/MessageHandlingException.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessagingException; <add> <add> <add>/** <add> * Thrown when the handling of a message results in an unrecoverable exception. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class MessageHandlingException extends MessagingException { <add> <add> <add> public MessageHandlingException(Message<?> message, String description, Throwable cause) { <add> super(message, description, cause); <add> } <add> <add> public MessageHandlingException(Message<?> message, String description) { <add> super(message, description); <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolver.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.handler.annotation.Payload; <add>import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver; <add>import org.springframework.messaging.support.converter.MessageConverter; <add>import org.springframework.util.Assert; <add>import org.springframework.util.ClassUtils; <add> <add> <add>/** <add> * A resolver to extract and convert the payload of a message using a <add> * {@link MessageConverter}. <add> * <add> * <p> <add> * This {@link HandlerMethodArgumentResolver} should be ordered last as it supports all <add> * types and does not require the {@link Payload} annotation. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class PayloadArgumentResolver implements HandlerMethodArgumentResolver { <add> <add> private final MessageConverter converter; <add> <add> <add> public PayloadArgumentResolver(MessageConverter messageConverter) { <add> Assert.notNull(messageConverter, "converter is required"); <add> this.converter = messageConverter; <add> } <add> <add> @Override <add> public boolean supportsParameter(MethodParameter parameter) { <add> return true; <add> } <add> <add> @Override <add> public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { <add> <add> Class<?> sourceClass = message.getPayload().getClass(); <add> Class<?> targetClass = parameter.getParameterType(); <add> <add> if (ClassUtils.isAssignable(targetClass,sourceClass)) { <add> return message.getPayload(); <add> } <add> <add> Payload annot = parameter.getParameterAnnotation(Payload.class); <add> <add> if (isEmptyPayload(message)) { <add> if ((annot != null) && !annot.required()) { <add> return null; <add> } <add> } <add> <add> return this.converter.fromMessage(message, targetClass); <add> } <add> <add> protected boolean isEmptyPayload(Message<?> message) { <add> Object payload = message.getPayload(); <add> if (payload instanceof byte[]) { <add> return ((byte[]) message.getPayload()).length == 0; <add> } <add> else if (payload instanceof String) { <add> return ((String) payload).trim().equals(""); <add> } <add> else { <add> return false; <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandler.java <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <add>import org.springframework.context.ConfigurableApplicationContext; <ide> import org.springframework.core.MethodParameter; <ide> import org.springframework.core.annotation.AnnotationUtils; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.format.support.DefaultFormattingConversionService; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageChannel; <ide> import org.springframework.messaging.MessageHandler; <ide> import org.springframework.messaging.MessagingException; <ide> import org.springframework.messaging.core.AbstractMessageSendingTemplate; <ide> import org.springframework.messaging.handler.annotation.MessageMapping; <ide> import org.springframework.messaging.handler.annotation.support.ExceptionHandlerMethodResolver; <del>import org.springframework.messaging.handler.annotation.support.MessageBodyMethodArgumentResolver; <add>import org.springframework.messaging.handler.annotation.support.HeaderMethodArgumentResolver; <add>import org.springframework.messaging.handler.annotation.support.HeadersMethodArgumentResolver; <ide> import org.springframework.messaging.handler.annotation.support.MessageMethodArgumentResolver; <add>import org.springframework.messaging.handler.annotation.support.PayloadArgumentResolver; <ide> import org.springframework.messaging.handler.method.HandlerMethod; <ide> import org.springframework.messaging.handler.method.HandlerMethodArgumentResolver; <ide> import org.springframework.messaging.handler.method.HandlerMethodArgumentResolverComposite; <ide> import org.springframework.messaging.simp.annotation.support.SendToMethodReturnValueHandler; <ide> import org.springframework.messaging.simp.annotation.support.SubscriptionMethodReturnValueHandler; <ide> import org.springframework.messaging.support.MessageBuilder; <add>import org.springframework.messaging.support.converter.ByteArrayMessageConverter; <add>import org.springframework.messaging.support.converter.CompositeMessageConverter; <ide> import org.springframework.messaging.support.converter.MessageConverter; <add>import org.springframework.messaging.support.converter.StringMessageConverter; <ide> import org.springframework.stereotype.Controller; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> public class AnnotationMethodMessageHandler implements MessageHandler, Applicati <ide> <ide> private MessageConverter messageConverter; <ide> <add> private ConversionService conversionService = new DefaultFormattingConversionService(); <add> <ide> private ApplicationContext applicationContext; <ide> <ide> private Map<MappingInfo, HandlerMethod> messageMethods = new HashMap<MappingInfo, HandlerMethod>(); <ide> public AnnotationMethodMessageHandler(SimpMessageSendingOperations brokerTemplat <ide> Assert.notNull(webSocketResponseChannel, "webSocketReplyChannel is required"); <ide> this.brokerTemplate = brokerTemplate; <ide> this.webSocketResponseTemplate = new SimpMessagingTemplate(webSocketResponseChannel); <add> <add> Collection<MessageConverter> converters = new ArrayList<MessageConverter>(); <add> converters.add(new StringMessageConverter()); <add> converters.add(new ByteArrayMessageConverter()); <add> this.messageConverter = new CompositeMessageConverter(converters); <ide> } <ide> <ide> /** <ide> public Collection<String> getDestinationPrefixes() { <ide> return this.destinationPrefixes; <ide> } <ide> <add> /** <add> * Configure a {@link MessageConverter} to use to convert the payload of a message <add> * from serialize form with a specific MIME type to an Object matching the target <add> * method parameter. The converter is also used when sending message to the message <add> * broker. <add> * <add> * @see CompositeMessageConverter <add> */ <ide> public void setMessageConverter(MessageConverter converter) { <ide> this.messageConverter = converter; <ide> if (converter != null) { <ide> ((AbstractMessageSendingTemplate<?>) this.webSocketResponseTemplate).setMessageConverter(converter); <ide> } <ide> } <ide> <add> /** <add> * Return the configured {@link MessageConverter}. <add> */ <add> public MessageConverter getMessageConverter() { <add> return this.messageConverter; <add> } <add> <add> /** <add> * Configure a {@link ConversionService} to use when resolving method arguments, for <add> * example message header values. <add> * <p> <add> * By default an instance of {@link DefaultFormattingConversionService} is used. <add> */ <add> public void setConversionService(ConversionService conversionService) { <add> this.conversionService = conversionService; <add> } <add> <add> /** <add> * The configured {@link ConversionService}. <add> */ <add> public ConversionService getConversionService() { <add> return this.conversionService; <add> } <add> <ide> /** <ide> * Sets the list of custom {@code HandlerMethodArgumentResolver}s that will be used <ide> * after resolvers for supported argument type. <ide> public void setCustomReturnValueHandlers(List<HandlerMethodReturnValueHandler> c <ide> this.customReturnValueHandlers = customReturnValueHandlers; <ide> } <ide> <del> public MessageConverter getMessageConverter() { <del> return this.messageConverter; <del> } <del> <ide> @Override <ide> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <ide> this.applicationContext = applicationContext; <ide> } <ide> <add> <ide> @Override <ide> public void afterPropertiesSet() { <ide> <ide> initHandlerMethods(); <ide> <add> ConfigurableBeanFactory beanFactory = <add> (ClassUtils.isAssignableValue(ConfigurableApplicationContext.class, this.applicationContext)) ? <add> ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory() : null; <add> <add> // Annotation-based argument resolution <add> this.argumentResolvers.addResolver(new HeaderMethodArgumentResolver(this.conversionService, beanFactory)); <add> this.argumentResolvers.addResolver(new HeadersMethodArgumentResolver()); <add> <ide> // Type-based argument resolution <ide> this.argumentResolvers.addResolver(new PrincipalMethodArgumentResolver()); <ide> this.argumentResolvers.addResolver(new MessageMethodArgumentResolver()); <ide> public void afterPropertiesSet() { <ide> this.argumentResolvers.addResolvers(this.customArgumentResolvers); <ide> <ide> // catch-all argument resolver <del> this.argumentResolvers.addResolver(new MessageBodyMethodArgumentResolver(this.messageConverter)); <add> this.argumentResolvers.addResolver(new PayloadArgumentResolver(this.messageConverter)); <ide> <ide> // Annotation-based return value types <ide> this.returnValueHandlers.addHandler(new SendToMethodReturnValueHandler(this.brokerTemplate, true)); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java <ide> public class NativeMessageHeaderAccessor extends MessageHeaderAccessor { <ide> /** <ide> * A constructor for creating new headers, accepting an optional native header map. <ide> */ <del> public NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) { <add> protected NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) { <ide> this.originalNativeHeaders = nativeHeaders; <ide> } <ide> <ide> /** <ide> * A constructor for accessing and modifying existing message headers. <ide> */ <del> public NativeMessageHeaderAccessor(Message<?> message) { <add> protected NativeMessageHeaderAccessor(Message<?> message) { <ide> super(message); <ide> this.originalNativeHeaders = initNativeHeaders(message); <ide> } <ide> <del> <ide> private static Map<String, List<String>> initNativeHeaders(Message<?> message) { <ide> if (message != null) { <ide> @SuppressWarnings("unchecked") <ide> private static Map<String, List<String>> initNativeHeaders(Message<?> message) { <ide> return null; <ide> } <ide> <add> /** <add> * Create {@link NativeMessageHeaderAccessor} from the headers of an existing message. <add> */ <add> public static NativeMessageHeaderAccessor wrap(Message<?> message) { <add> return new NativeMessageHeaderAccessor(message); <add> } <add> <ide> <ide> @Override <ide> public Map<String, Object> toMap() { <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import java.lang.reflect.Method; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.context.support.GenericApplicationContext; <add>import org.springframework.core.DefaultParameterNameDiscoverer; <add>import org.springframework.core.GenericTypeResolver; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.support.DefaultConversionService; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.handler.annotation.Header; <add>import org.springframework.messaging.support.MessageBuilder; <add> <add>import static org.junit.Assert.*; <add> <add> <add>/** <add> * Test fixture for {@link HeaderMethodArgumentResolver} tests. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class HeaderMethodArgumentResolverTests { <add> <add> private HeaderMethodArgumentResolver resolver; <add> <add> private MethodParameter paramRequired; <add> private MethodParameter paramNamedDefaultValueStringHeader; <add> private MethodParameter paramSystemProperty; <add> private MethodParameter paramNotAnnotated; <add> <add> <add> @Before <add> public void setup() throws Exception { <add> @SuppressWarnings("resource") <add> GenericApplicationContext cxt = new GenericApplicationContext(); <add> cxt.refresh(); <add> this.resolver = new HeaderMethodArgumentResolver(new DefaultConversionService(), cxt.getBeanFactory()); <add> <add> Method method = getClass().getDeclaredMethod("handleMessage", <add> String.class, String.class, String.class, String.class); <add> this.paramRequired = new MethodParameter(method, 0); <add> this.paramNamedDefaultValueStringHeader = new MethodParameter(method, 1); <add> this.paramSystemProperty = new MethodParameter(method, 2); <add> this.paramNotAnnotated = new MethodParameter(method, 3); <add> <add> this.paramRequired.initParameterNameDiscovery(new DefaultParameterNameDiscoverer()); <add> GenericTypeResolver.resolveParameterType(this.paramRequired, HeaderMethodArgumentResolver.class); <add> } <add> <add> @Test <add> public void supportsParameter() { <add> assertTrue(resolver.supportsParameter(paramNamedDefaultValueStringHeader)); <add> assertFalse(resolver.supportsParameter(paramNotAnnotated)); <add> } <add> <add> @Test <add> public void resolveArgument() throws Exception { <add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeader("param1", "foo").build(); <add> this.resolver.resolveArgument(this.paramRequired, message); <add> } <add> <add> @Test(expected = MessageHandlingException.class) <add> public void resolveArgumentNotFound() throws Exception { <add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).build(); <add> this.resolver.resolveArgument(this.paramRequired, message); <add> } <add> <add> @Test <add> public void resolveArgumentDefaultValue() throws Exception { <add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).build(); <add> Object result = this.resolver.resolveArgument(this.paramNamedDefaultValueStringHeader, message); <add> <add> assertEquals("bar", result); <add> } <add> <add> @Test <add> public void resolveDefaultValueSystemProperty() throws Exception { <add> System.setProperty("systemProperty", "sysbar"); <add> try { <add> Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).build(); <add> Object result = resolver.resolveArgument(paramSystemProperty, message); <add> assertEquals("sysbar", result); <add> } <add> finally { <add> System.clearProperty("systemProperty"); <add> } <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private void handleMessage( <add> @Header String param1, <add> @Header(value = "name", defaultValue = "bar") String param2, <add> @Header(value = "name", defaultValue="#{systemProperties.systemProperty}") String param3, <add> String param4) { <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeadersMethodArgumentResolverTests.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import java.lang.reflect.Method; <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageHeaders; <add>import org.springframework.messaging.handler.annotation.Headers; <add>import org.springframework.messaging.support.MessageBuilder; <add>import org.springframework.messaging.support.MessageHeaderAccessor; <add>import org.springframework.messaging.support.NativeMessageHeaderAccessor; <add> <add>import static org.junit.Assert.*; <add> <add> <add>/** <add> * Test fixture for {@link HeadersMethodArgumentResolver} tests. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class HeadersMethodArgumentResolverTests { <add> <add> private HeadersMethodArgumentResolver resolver; <add> <add> private MethodParameter paramAnnotated; <add> private MethodParameter paramAnnotatedNotMap; <add> private MethodParameter paramMessageHeaders; <add> private MethodParameter paramMessageHeaderAccessor; <add> private MethodParameter paramMessageHeaderAccessorSubclass; <add> <add> private Message<byte[]> message; <add> <add> <add> @Before <add> public void setup() throws Exception { <add> this.resolver = new HeadersMethodArgumentResolver(); <add> <add> Method method = getClass().getDeclaredMethod("handleMessage", Map.class, String.class, <add> MessageHeaders.class, MessageHeaderAccessor.class, TestMessageHeaderAccessor.class); <add> <add> this.paramAnnotated = new MethodParameter(method, 0); <add> this.paramAnnotatedNotMap = new MethodParameter(method, 1); <add> this.paramMessageHeaders = new MethodParameter(method, 2); <add> this.paramMessageHeaderAccessor = new MethodParameter(method, 3); <add> this.paramMessageHeaderAccessorSubclass = new MethodParameter(method, 4); <add> <add> Map<String, Object> headers = new HashMap<String, Object>(); <add> headers.put("foo", "bar"); <add> this.message = MessageBuilder.withPayload(new byte[0]).copyHeaders(headers).build(); <add> } <add> <add> @Test <add> public void supportsParameter() { <add> assertTrue(this.resolver.supportsParameter(this.paramAnnotated)); <add> assertFalse(this.resolver.supportsParameter(this.paramAnnotatedNotMap)); <add> assertTrue(this.resolver.supportsParameter(this.paramMessageHeaders)); <add> assertTrue(this.resolver.supportsParameter(this.paramMessageHeaderAccessor)); <add> assertTrue(this.resolver.supportsParameter(this.paramMessageHeaderAccessorSubclass)); <add> } <add> <add> @Test <add> public void resolveArgumentAnnotated() throws Exception { <add> Object resolved = this.resolver.resolveArgument(this.paramAnnotated, this.message); <add> <add> assertTrue(resolved instanceof Map); <add> @SuppressWarnings("unchecked") <add> Map<String, Object> headers = (Map<String, Object>) resolved; <add> assertEquals("bar", headers.get("foo")); <add> } <add> <add> @Test(expected=IllegalStateException.class) <add> public void resolveArgumentAnnotatedNotMap() throws Exception { <add> this.resolver.resolveArgument(this.paramAnnotatedNotMap, this.message); <add> } <add> <add> @Test <add> public void resolveArgumentMessageHeaders() throws Exception { <add> Object resolved = this.resolver.resolveArgument(this.paramMessageHeaders, this.message); <add> <add> assertTrue(resolved instanceof MessageHeaders); <add> MessageHeaders headers = (MessageHeaders) resolved; <add> assertEquals("bar", headers.get("foo")); <add> } <add> <add> @Test <add> public void resolveArgumentMessageHeaderAccessor() throws Exception { <add> Object resolved = this.resolver.resolveArgument(this.paramMessageHeaderAccessor, this.message); <add> <add> assertTrue(resolved instanceof MessageHeaderAccessor); <add> MessageHeaderAccessor headers = (MessageHeaderAccessor) resolved; <add> assertEquals("bar", headers.getHeader("foo")); <add> } <add> <add> @Test <add> public void resolveArgumentMessageHeaderAccessorSubclass() throws Exception { <add> Object resolved = this.resolver.resolveArgument(this.paramMessageHeaderAccessorSubclass, this.message); <add> <add> assertTrue(resolved instanceof TestMessageHeaderAccessor); <add> TestMessageHeaderAccessor headers = (TestMessageHeaderAccessor) resolved; <add> assertEquals("bar", headers.getHeader("foo")); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private void handleMessage( <add> @Headers Map<String, ?> param1, <add> @Headers String param2, <add> MessageHeaders param3, <add> MessageHeaderAccessor param4, <add> TestMessageHeaderAccessor param5) { <add> } <add> <add> <add> public static class TestMessageHeaderAccessor extends NativeMessageHeaderAccessor { <add> <add> protected TestMessageHeaderAccessor(Message<?> message) { <add> super(message); <add> } <add> <add> public static TestMessageHeaderAccessor wrap(Message<?> message) { <add> return new TestMessageHeaderAccessor(message); <add> } <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolverTests.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.annotation.support; <add> <add>import java.lang.reflect.Method; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.handler.annotation.Payload; <add>import org.springframework.messaging.support.MessageBuilder; <add>import org.springframework.messaging.support.converter.MessageConverter; <add>import org.springframework.messaging.support.converter.StringMessageConverter; <add> <add>import static org.junit.Assert.*; <add> <add> <add>/** <add> * Test fixture for {@link PayloadArgumentResolver}. <add> * <add> * @author Rossen Stoyanchev <add> */ <add>public class PayloadArgumentResolverTests { <add> <add> private PayloadArgumentResolver resolver; <add> <add> private MethodParameter param; <add> private MethodParameter paramNotRequired; <add> <add> <add> @Before <add> public void setup() throws Exception { <add> <add> MessageConverter messageConverter = new StringMessageConverter(); <add> this.resolver = new PayloadArgumentResolver(messageConverter ); <add> <add> Method method = PayloadArgumentResolverTests.class.getDeclaredMethod("handleMessage", <add> String.class, String.class); <add> <add> this.param = new MethodParameter(method , 0); <add> this.paramNotRequired = new MethodParameter(method , 1); <add> } <add> <add> <add> @Test <add> public void resolveRequired() throws Exception { <add> Message<?> message = MessageBuilder.withPayload("ABC".getBytes()).build(); <add> Object actual = this.resolver.resolveArgument(this.param, message); <add> <add> assertEquals("ABC", actual); <add> } <add> <add> @Test <add> public void resolveNotRequired() throws Exception { <add> <add> Message<?> emptyByteArrayMessage = MessageBuilder.withPayload(new byte[0]).build(); <add> assertNull(this.resolver.resolveArgument(this.paramNotRequired, emptyByteArrayMessage)); <add> <add> Message<?> notEmptyMessage = MessageBuilder.withPayload("ABC".getBytes()).build(); <add> assertEquals("ABC", this.resolver.resolveArgument(this.paramNotRequired, notEmptyMessage)); <add> } <add> <add> <add> @SuppressWarnings("unused") <add> private void handleMessage( <add> @Payload String param, <add> @Payload(required=false) String paramNotRequired) { <add> } <add> <add>} <ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandlerTests.java <ide> <ide> package org.springframework.messaging.simp.handler; <ide> <add>import java.util.LinkedHashMap; <add>import java.util.Map; <add> <add>import org.junit.Before; <ide> import org.junit.Test; <ide> import org.mockito.Mockito; <ide> import org.springframework.context.support.StaticApplicationContext; <add>import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageChannel; <add>import org.springframework.messaging.handler.annotation.Header; <add>import org.springframework.messaging.handler.annotation.Headers; <ide> import org.springframework.messaging.handler.annotation.MessageMapping; <add>import org.springframework.messaging.simp.SimpMessageHeaderAccessor; <ide> import org.springframework.messaging.simp.SimpMessageSendingOperations; <ide> import org.springframework.messaging.simp.SimpMessagingTemplate; <add>import org.springframework.messaging.support.MessageBuilder; <ide> import org.springframework.stereotype.Controller; <ide> <add>import static org.junit.Assert.*; <add> <ide> <ide> /** <ide> * Test fixture for {@link AnnotationMethodMessageHandler}. <ide> * @author Rossen Stoyanchev <ide> */ <ide> public class AnnotationMethodMessageHandlerTests { <ide> <add> private TestAnnotationMethodMessageHandler messageHandler; <ide> <del> @Test(expected=IllegalStateException.class) <del> public void duplicateMappings() { <add> private TestController testController; <ide> <del> StaticApplicationContext cxt = new StaticApplicationContext(); <del> cxt.registerSingleton("d", DuplicateMappingController.class); <del> cxt.refresh(); <ide> <add> @Before <add> public void setup() { <ide> MessageChannel channel = Mockito.mock(MessageChannel.class); <ide> SimpMessageSendingOperations brokerTemplate = new SimpMessagingTemplate(channel); <del> AnnotationMethodMessageHandler mh = new AnnotationMethodMessageHandler(brokerTemplate, channel); <del> mh.setApplicationContext(cxt); <del> mh.afterPropertiesSet(); <add> this.messageHandler = new TestAnnotationMethodMessageHandler(brokerTemplate, channel); <add> this.messageHandler.setApplicationContext(new StaticApplicationContext()); <add> this.messageHandler.afterPropertiesSet(); <add> <add> testController = new TestController(); <add> this.messageHandler.registerHandler(testController); <add> } <add> <add> <add> @SuppressWarnings("unchecked") <add> @Test <add> public void headerArgumentResolution() { <add> SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(); <add> headers.setDestination("/headers"); <add> headers.setHeader("foo", "bar"); <add> Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build(); <add> this.messageHandler.handleMessage(message); <add> <add> assertEquals("headers", this.testController.method); <add> assertEquals("bar", this.testController.arguments.get("foo")); <add> assertEquals("bar", ((Map<String, Object>) this.testController.arguments.get("headers")).get("foo")); <add> } <add> <add> @Test(expected=IllegalStateException.class) <add> public void duplicateMappings() { <add> this.messageHandler.registerHandler(new DuplicateMappingController()); <ide> } <ide> <ide> <add> private static class TestAnnotationMethodMessageHandler extends AnnotationMethodMessageHandler { <add> <add> public TestAnnotationMethodMessageHandler(SimpMessageSendingOperations brokerTemplate, <add> MessageChannel webSocketResponseChannel) { <add> <add> super(brokerTemplate, webSocketResponseChannel); <add> } <add> <add> public void registerHandler(Object handler) { <add> super.detectHandlerMethods(handler); <add> } <add> } <add> <add> <add> @Controller <add> private static class TestController { <add> <add> private String method; <add> <add> private Map<String, Object> arguments = new LinkedHashMap<String, Object>(); <add> <add> <add> @MessageMapping("/headers") <add> public void headers(@Header String foo, @Headers Map<String, Object> headers) { <add> this.method = "headers"; <add> this.arguments.put("foo", foo); <add> this.arguments.put("headers", headers); <add> } <add> } <add> <ide> @Controller <del> static class DuplicateMappingController { <add> private static class DuplicateMappingController { <ide> <ide> @MessageMapping(value="/duplicate") <ide> public void handle1() { } <ide><path>spring-web/src/test/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolverTests.java <ide> <ide> package org.springframework.web.method.annotation; <ide> <del>import static org.junit.Assert.assertArrayEquals; <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertTrue; <del>import static org.junit.Assert.fail; <del> <ide> import java.lang.reflect.Method; <ide> import java.util.Map; <ide> <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> import org.springframework.web.context.support.GenericWebApplicationContext; <del>import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver; <add> <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Test fixture with {@link org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver}. <ide> public void resolveDefaultValueFromRequest() throws Exception { <ide> @Test(expected = ServletRequestBindingException.class) <ide> public void notFound() throws Exception { <ide> resolver.resolveArgument(paramNamedValueStringArray, null, webRequest, null); <del> fail("Expected exception"); <ide> } <ide> <ide> public void params(@RequestHeader(value = "name", defaultValue = "bar") String param1,
18
Ruby
Ruby
move asset tests to assets_test file
e767cda6ea171cf888c8e46b0c62e3c7df801a38
<ide><path>railties/test/application/assets_test.rb <add># -*- coding: utf-8 -*- <ide> require 'isolation/abstract_unit' <ide> require 'active_support/core_ext/kernel/reporting' <ide> require 'rack/test' <ide> class ::PostsController < ActionController::Base ; end <ide> assert_match(/\/assets\/rails-([0-z]+)\.png/, File.read(file)) <ide> end <ide> <add> test "precompile ignore asset_host" do <add> app_file "app/assets/javascripts/application.css.erb", "<%= asset_path 'rails.png' %>" <add> add_to_config "config.action_controller.asset_host = Proc.new { |source, request| 'http://www.example.com/' }" <add> <add> capture(:stdout) do <add> Dir.chdir(app_path){ `bundle exec rake assets:precompile` } <add> end <add> <add> file = Dir["#{app_path}/public/assets/application.css"].first <add> content = File.read(file) <add> assert_match(/\/assets\/rails-([0-z]+)\.png/, content) <add> assert_no_match(/www\.example\.com/, content) <add> end <add> <add> test "precompile should handle utf8 filenames" do <add> app_file "app/assets/images/レイルズ.png", "not a image really" <add> add_to_config "config.assets.precompile = [ /\.png$$/, /application.(css|js)$/ ]" <add> <add> capture(:stdout) do <add> Dir.chdir(app_path){ `bundle exec rake assets:precompile` } <add> end <add> <add> assert File.exists?("#{app_path}/public/assets/レイルズ.png") <add> <add> manifest = "#{app_path}/public/assets/manifest.yml" <add> <add> assets = YAML.load_file(manifest) <add> assert_equal "レイルズ.png", assets["レイルズ.png"] <add> end <add> <ide> test "assets are cleaned up properly" do <ide> app_file "public/assets/application.js", "alert();" <ide> app_file "public/assets/application.css", "a { color: green; }" <ide><path>railties/test/application/rake_test.rb <ide> def test_scaffold_tests_pass_by_default <ide> <ide> assert_match(/7 tests, 10 assertions, 0 failures, 0 errors/, content) <ide> end <del> <del> def test_assets_precompile_with_utf8_filename <del> add_to_config <<-RUBY <del> config.assets.precompile = [ /\.png$$/, /application.(css|js)$/ ] <del> RUBY <del> <del> Dir.chdir(app_path) do <del> `cp app/assets/images/rails.png app/assets/images/レイルズ.png` <del> `rake assets:precompile` <del> open("public/assets/manifest.yml") do |f| <del> assert_match(/レイルズ.png/, f.read) <del> end <del> end <del> end <del> <del> def test_assets_precompile_ignore_asset_host <del> add_to_config <<-RUBY <del> config.action_controller.asset_host = Proc.new { |source, request| "http://www.example.com/" } <del> RUBY <del> <del> app_file "app/assets/javascripts/test.js.erb", <<-RUBY <del> alert("<%= asset_path "rails.png" %>"); <del> RUBY <del> <del> Dir.chdir(app_path) do <del> `rake assets:precompile` <del> open("public/assets/application.js") do |f| <del> assert_match(/\"\/assets\/rails.png\"/, f.read) <del> end <del> end <del> end <ide> end <ide> end
2
Ruby
Ruby
run slowest checks last
a64e9e542f04b845f12f18f644d6d33a170e3ada
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def doctor <ide> checks.methods.sort << "check_for_linked_keg_only_brews" << "check_for_outdated_homebrew" <ide> else <ide> ARGV.named <del> end.select{ |method| method =~ /^check_/ }.uniq <add> end.select{ |method| method =~ /^check_/ }.reverse.uniq.reverse <ide> <ide> methods.each do |method| <ide> out = checks.send(method)
1
Javascript
Javascript
fix memory leak with hmr
6172d3c2ebddceedec1c28e0e92fe3b2a3dc0c38
<ide><path>lib/HotModuleReplacementPlugin.js <ide> module.exports = class HotModuleReplacementPlugin { <ide> return callback(); <ide> } <ide> ); <add> <add> const addParserPlugins = (parser, parserOptions) => { <add> parser.hooks.expression <add> .for("__webpack_hash__") <add> .tap( <add> "HotModuleReplacementPlugin", <add> ParserHelpers.toConstantDependencyWithWebpackRequire( <add> parser, <add> "__webpack_require__.h()" <add> ) <add> ); <add> parser.hooks.evaluateTypeof <add> .for("__webpack_hash__") <add> .tap( <add> "HotModuleReplacementPlugin", <add> ParserHelpers.evaluateToString("string") <add> ); <add> parser.hooks.evaluateIdentifier.for("module.hot").tap( <add> { <add> name: "HotModuleReplacementPlugin", <add> before: "NodeStuffPlugin" <add> }, <add> expr => { <add> return ParserHelpers.evaluateToIdentifier( <add> "module.hot", <add> !!parser.state.compilation.hotUpdateChunkTemplate <add> )(expr); <add> } <add> ); <add> // TODO webpack 5: refactor this, no custom hooks <add> if (!parser.hooks.hotAcceptCallback) { <add> parser.hooks.hotAcceptCallback = new SyncBailHook([ <add> "expression", <add> "requests" <add> ]); <add> } <add> if (!parser.hooks.hotAcceptWithoutCallback) { <add> parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ <add> "expression", <add> "requests" <add> ]); <add> } <add> parser.hooks.call <add> .for("module.hot.accept") <add> .tap("HotModuleReplacementPlugin", expr => { <add> if (!parser.state.compilation.hotUpdateChunkTemplate) { <add> return false; <add> } <add> if (expr.arguments.length >= 1) { <add> const arg = parser.evaluateExpression(expr.arguments[0]); <add> let params = []; <add> let requests = []; <add> if (arg.isString()) { <add> params = [arg]; <add> } else if (arg.isArray()) { <add> params = arg.items.filter(param => param.isString()); <add> } <add> if (params.length > 0) { <add> params.forEach((param, idx) => { <add> const request = param.string; <add> const dep = new ModuleHotAcceptDependency(request, param.range); <add> dep.optional = true; <add> dep.loc = Object.create(expr.loc); <add> dep.loc.index = idx; <add> parser.state.module.addDependency(dep); <add> requests.push(request); <add> }); <add> if (expr.arguments.length > 1) { <add> parser.hooks.hotAcceptCallback.call( <add> expr.arguments[1], <add> requests <add> ); <add> parser.walkExpression(expr.arguments[1]); // other args are ignored <add> return true; <add> } else { <add> parser.hooks.hotAcceptWithoutCallback.call(expr, requests); <add> return true; <add> } <add> } <add> } <add> }); <add> parser.hooks.call <add> .for("module.hot.decline") <add> .tap("HotModuleReplacementPlugin", expr => { <add> if (!parser.state.compilation.hotUpdateChunkTemplate) { <add> return false; <add> } <add> if (expr.arguments.length === 1) { <add> const arg = parser.evaluateExpression(expr.arguments[0]); <add> let params = []; <add> if (arg.isString()) { <add> params = [arg]; <add> } else if (arg.isArray()) { <add> params = arg.items.filter(param => param.isString()); <add> } <add> params.forEach((param, idx) => { <add> const dep = new ModuleHotDeclineDependency( <add> param.string, <add> param.range <add> ); <add> dep.optional = true; <add> dep.loc = Object.create(expr.loc); <add> dep.loc.index = idx; <add> parser.state.module.addDependency(dep); <add> }); <add> } <add> }); <add> parser.hooks.expression <add> .for("module.hot") <add> .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); <add> }; <add> <ide> compiler.hooks.compilation.tap( <ide> "HotModuleReplacementPlugin", <ide> (compilation, { normalModuleFactory }) => { <ide> module.exports = class HotModuleReplacementPlugin { <ide> } <ide> ); <ide> <del> const handler = (parser, parserOptions) => { <del> parser.hooks.expression <del> .for("__webpack_hash__") <del> .tap( <del> "HotModuleReplacementPlugin", <del> ParserHelpers.toConstantDependencyWithWebpackRequire( <del> parser, <del> "__webpack_require__.h()" <del> ) <del> ); <del> parser.hooks.evaluateTypeof <del> .for("__webpack_hash__") <del> .tap( <del> "HotModuleReplacementPlugin", <del> ParserHelpers.evaluateToString("string") <del> ); <del> parser.hooks.evaluateIdentifier.for("module.hot").tap( <del> { <del> name: "HotModuleReplacementPlugin", <del> before: "NodeStuffPlugin" <del> }, <del> expr => { <del> return ParserHelpers.evaluateToIdentifier( <del> "module.hot", <del> !!parser.state.compilation.hotUpdateChunkTemplate <del> )(expr); <del> } <del> ); <del> // TODO webpack 5: refactor this, no custom hooks <del> if (!parser.hooks.hotAcceptCallback) { <del> parser.hooks.hotAcceptCallback = new SyncBailHook([ <del> "expression", <del> "requests" <del> ]); <del> } <del> if (!parser.hooks.hotAcceptWithoutCallback) { <del> parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ <del> "expression", <del> "requests" <del> ]); <del> } <del> parser.hooks.call <del> .for("module.hot.accept") <del> .tap("HotModuleReplacementPlugin", expr => { <del> if (!parser.state.compilation.hotUpdateChunkTemplate) { <del> return false; <del> } <del> if (expr.arguments.length >= 1) { <del> const arg = parser.evaluateExpression(expr.arguments[0]); <del> let params = []; <del> let requests = []; <del> if (arg.isString()) { <del> params = [arg]; <del> } else if (arg.isArray()) { <del> params = arg.items.filter(param => param.isString()); <del> } <del> if (params.length > 0) { <del> params.forEach((param, idx) => { <del> const request = param.string; <del> const dep = new ModuleHotAcceptDependency( <del> request, <del> param.range <del> ); <del> dep.optional = true; <del> dep.loc = Object.create(expr.loc); <del> dep.loc.index = idx; <del> parser.state.module.addDependency(dep); <del> requests.push(request); <del> }); <del> if (expr.arguments.length > 1) { <del> parser.hooks.hotAcceptCallback.call( <del> expr.arguments[1], <del> requests <del> ); <del> parser.walkExpression(expr.arguments[1]); // other args are ignored <del> return true; <del> } else { <del> parser.hooks.hotAcceptWithoutCallback.call(expr, requests); <del> return true; <del> } <del> } <del> } <del> }); <del> parser.hooks.call <del> .for("module.hot.decline") <del> .tap("HotModuleReplacementPlugin", expr => { <del> if (!parser.state.compilation.hotUpdateChunkTemplate) { <del> return false; <del> } <del> if (expr.arguments.length === 1) { <del> const arg = parser.evaluateExpression(expr.arguments[0]); <del> let params = []; <del> if (arg.isString()) { <del> params = [arg]; <del> } else if (arg.isArray()) { <del> params = arg.items.filter(param => param.isString()); <del> } <del> params.forEach((param, idx) => { <del> const dep = new ModuleHotDeclineDependency( <del> param.string, <del> param.range <del> ); <del> dep.optional = true; <del> dep.loc = Object.create(expr.loc); <del> dep.loc.index = idx; <del> parser.state.module.addDependency(dep); <del> }); <del> } <del> }); <del> parser.hooks.expression <del> .for("module.hot") <del> .tap("HotModuleReplacementPlugin", ParserHelpers.skipTraversal); <del> }; <del> <ide> // TODO add HMR support for javascript/esm <ide> normalModuleFactory.hooks.parser <ide> .for("javascript/auto") <del> .tap("HotModuleReplacementPlugin", handler); <add> .tap("HotModuleReplacementPlugin", addParserPlugins); <ide> normalModuleFactory.hooks.parser <ide> .for("javascript/dynamic") <del> .tap("HotModuleReplacementPlugin", handler); <add> .tap("HotModuleReplacementPlugin", addParserPlugins); <ide> <ide> compilation.hooks.normalModuleLoader.tap( <ide> "HotModuleReplacementPlugin",
1
Python
Python
fix evaluate for non-gpu
f24c2e3a8af785dd11b8d0a994732174290d688b
<ide><path>spacy/cli/evaluate.py <ide> def evaluate(cmd, model, data_path, gpu_id=-1, gold_preproc=False): <ide> Train a model. Expects data in spaCy's JSON format. <ide> """ <ide> util.use_gpu(gpu_id) <del> util.set_env_log(True) <add> util.set_env_log(False) <ide> data_path = util.ensure_path(data_path) <ide> if not data_path.exists(): <ide> prints(data_path, title="Evaluation data not found", exits=1) <ide><path>spacy/util.py <ide> def minify_html(html): <ide> <ide> <ide> def use_gpu(gpu_id): <del> import cupy.cuda.device <add> try: <add> import cupy.cuda.device <add> except ImportError: <add> return None <ide> from thinc.neural.ops import CupyOps <ide> device = cupy.cuda.device.Device(gpu_id) <ide> device.use()
2
Java
Java
shorten returnvaluetype name in handlerresult
dffd6d674ab9415caed1b82755634f52383cd7ba
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerResult.java <ide> public class HandlerResult { <ide> <ide> private final Optional<Object> returnValue; <ide> <del> private final ResolvableType returnValueType; <add> private final ResolvableType returnType; <ide> <ide> private final ModelMap model; <ide> <ide> public class HandlerResult { <ide> * Create a new {@code HandlerResult}. <ide> * @param handler the handler that handled the request <ide> * @param returnValue the return value from the handler possibly {@code null} <del> * @param returnValueType the return value type <add> * @param returnType the return value type <ide> */ <del> public HandlerResult(Object handler, Object returnValue, ResolvableType returnValueType) { <del> this(handler, returnValue, returnValueType, null); <add> public HandlerResult(Object handler, Object returnValue, ResolvableType returnType) { <add> this(handler, returnValue, returnType, null); <ide> } <ide> <ide> /** <ide> * Create a new {@code HandlerResult}. <ide> * @param handler the handler that handled the request <ide> * @param returnValue the return value from the handler possibly {@code null} <del> * @param returnValueType the return value type <add> * @param returnType the return value type <ide> * @param model the model used for request handling <ide> */ <del> public HandlerResult(Object handler, Object returnValue, ResolvableType returnValueType, ModelMap model) { <add> public HandlerResult(Object handler, Object returnValue, ResolvableType returnType, ModelMap model) { <ide> Assert.notNull(handler, "'handler' is required"); <del> Assert.notNull(returnValueType, "'returnValueType' is required"); <add> Assert.notNull(returnType, "'returnType' is required"); <ide> this.handler = handler; <ide> this.returnValue = Optional.ofNullable(returnValue); <del> this.returnValueType = returnValueType; <add> this.returnType = returnType; <ide> this.model = (model != null ? model : new ExtendedModelMap()); <ide> } <ide> <ide> public Optional<Object> getReturnValue() { <ide> /** <ide> * Return the type of the value returned from the handler. <ide> */ <del> public ResolvableType getReturnValueType() { <del> return this.returnValueType; <add> public ResolvableType getReturnType() { <add> return this.returnType; <ide> } <ide> <ide> /** <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/SimpleResultHandler.java <ide> <ide> import java.util.Optional; <ide> <del>import org.reactivestreams.Publisher; <ide> import reactor.core.publisher.Flux; <ide> import reactor.core.publisher.Mono; <ide> <ide> public int getOrder() { <ide> <ide> @Override <ide> public boolean supports(HandlerResult result) { <del> ResolvableType type = result.getReturnValueType(); <add> ResolvableType type = result.getReturnType(); <ide> if (Void.TYPE.equals(type.getRawClass())) { <ide> return true; <ide> } <ide> if (getConversionService().canConvert(type.getRawClass(), Mono.class) || <ide> getConversionService().canConvert(type.getRawClass(), Flux.class)) { <del> Class<?> clazz = result.getReturnValueType().getGeneric(0).getRawClass(); <add> Class<?> clazz = result.getReturnType().getGeneric(0).getRawClass(); <ide> return Void.class.equals(clazz); <ide> } <ide> return false; <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) <ide> return (Mono<Void>) returnValue; <ide> } <ide> <del> ResolvableType returnType = result.getReturnValueType(); <add> ResolvableType returnType = result.getReturnType(); <ide> if (getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <ide> return this.conversionService.convert(returnValue, Mono.class); <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandler.java <ide> public ResponseBodyResultHandler(List<HttpMessageConverter<?>> converters, <ide> <ide> @Override <ide> public boolean supports(HandlerResult result) { <del> ResolvableType returnType = result.getReturnValueType(); <add> ResolvableType returnType = result.getReturnType(); <ide> if (returnType.getSource() instanceof MethodParameter) { <ide> MethodParameter parameter = (MethodParameter) returnType.getSource(); <ide> if (hasResponseBodyAnnotation(parameter) && !isHttpEntityType(returnType)) { <ide> else if (getConversionService().canConvert(returnType.getRawClass(), Mono.class) <ide> @Override <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <ide> Object body = result.getReturnValue().orElse(null); <del> ResolvableType bodyType = result.getReturnValueType(); <add> ResolvableType bodyType = result.getReturnType(); <ide> return writeBody(exchange, body, bodyType); <ide> } <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java <ide> public ResponseEntityResultHandler(List<HttpMessageConverter<?>> converters, <ide> <ide> @Override <ide> public boolean supports(HandlerResult result) { <del> ResolvableType returnType = result.getReturnValueType(); <add> ResolvableType returnType = result.getReturnType(); <ide> if (isSupportedType(returnType)) { <ide> return true; <ide> } <ide> else if (getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <del> ResolvableType genericType = result.getReturnValueType().getGeneric(0); <add> ResolvableType genericType = result.getReturnType().getGeneric(0); <ide> return isSupportedType(genericType); <ide> <ide> } <ide> private boolean isSupportedType(ResolvableType returnType) { <ide> @Override <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) { <ide> <del> ResolvableType returnType = result.getReturnValueType(); <add> ResolvableType returnType = result.getReturnType(); <ide> Mono<?> returnValueMono; <ide> ResolvableType bodyType; <ide> <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java <ide> public List<View> getDefaultViews() { <ide> <ide> @Override <ide> public boolean supports(HandlerResult result) { <del> Class<?> clazz = result.getReturnValueType().getRawClass(); <add> Class<?> clazz = result.getReturnType().getRawClass(); <ide> if (hasModelAttributeAnnotation(result)) { <ide> return true; <ide> } <ide> if (isSupportedType(clazz)) { <ide> return true; <ide> } <ide> if (getConversionService().canConvert(clazz, Mono.class)) { <del> clazz = result.getReturnValueType().getGeneric(0).getRawClass(); <add> clazz = result.getReturnType().getGeneric(0).getRawClass(); <ide> return isSupportedType(clazz); <ide> } <ide> return false; <ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) <ide> <ide> Mono<Object> valueMono; <ide> ResolvableType elementType; <del> ResolvableType returnType = result.getReturnValueType(); <add> ResolvableType returnType = result.getReturnType(); <ide> <ide> if (getConversionService().canConvert(returnType.getRawClass(), Mono.class)) { <ide> Optional<Object> optionalValue = result.getReturnValue();
5
Ruby
Ruby
remove override of activemodel#attribute_names
322e62842ce656e4bb7b6562efc2a7f314fe5d43
<ide><path>activemodel/lib/active_model/serialization.rb <ide> module Serialization <ide> # user.serializable_hash(include: { notes: { only: 'title' }}) <ide> # # => {"name" => "Napoleon", "notes" => [{"title"=>"Battle of Austerlitz"}]} <ide> def serializable_hash(options = nil) <del> attribute_names = self.attribute_names <add> attribute_names = attribute_names_for_serialization <ide> <ide> return serializable_attributes(attribute_names) if options.blank? <ide> <ide> def serializable_hash(options = nil) <ide> hash <ide> end <ide> <del> # Returns an array of attribute names as strings <del> def attribute_names # :nodoc: <del> attributes.keys <del> end <del> <ide> private <add> def attribute_names_for_serialization <add> attributes.keys <add> end <add> <ide> # Hook method defining how an attribute value should be retrieved for <ide> # serialization. By default this is assumed to be an instance named after <ide> # the attribute. Override this method in subclasses should you need to <ide><path>activerecord/lib/active_record/serialization.rb <ide> def serializable_hash(options = nil) <ide> <ide> super(options) <ide> end <add> <add> private <add> def attribute_names_for_serialization <add> attribute_names <add> end <ide> end <ide> end
2
Python
Python
fix dpr<>bart config for rag
a7d46a060930242cd1de7ead8821f6eeebb0cd06
<ide><path>src/transformers/models/albert/modeling_albert.py <ide> def __init__(self, config): <ide> <ide> # position_ids (1, len position emb) is contiguous in memory and exported when serialized <ide> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> <ide> # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward <ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): <ide> def __init__(self, config): <ide> self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) <ide> self.pruned_heads = set() <ide> <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) <ide><path>src/transformers/models/bert/modeling_bert.py <ide> def __init__(self, config): <ide> <ide> # position_ids (1, len position emb) is contiguous in memory and exported when serialized <ide> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> <ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): <ide> if input_ids is not None: <ide> def __init__(self, config): <ide> self.value = nn.Linear(config.hidden_size, self.all_head_size) <ide> <ide> self.dropout = nn.Dropout(config.attention_probs_dropout_prob) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) <ide><path>src/transformers/models/dpr/configuration_dpr.py <ide> class DPRConfig(PretrainedConfig): <ide> The epsilon used by the layer normalization layers. <ide> gradient_checkpointing (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> If True, use gradient checkpointing to save memory at the expense of slower backward pass. <add> position_embedding_type (:obj:`str`, `optional`, defaults to :obj:`"absolute"`): <add> Type of position embedding. Choose one of :obj:`"absolute"`, :obj:`"relative_key"`, <add> :obj:`"relative_key_query"`. For positional embeddings use :obj:`"absolute"`. For more information on <add> :obj:`"relative_key"`, please refer to `Self-Attention with Relative Position Representations (Shaw et al.) <add> <https://arxiv.org/abs/1803.02155>`__. For more information on :obj:`"relative_key_query"`, please refer to <add> `Method 4` in `Improve Transformer Models with Better Relative Position Embeddings (Huang et al.) <add> <https://arxiv.org/abs/2009.13658>`__. <ide> projection_dim (:obj:`int`, `optional`, defaults to 0): <ide> Dimension of the projection for the context and question encoders. If it is set to zero (default), then no <ide> projection is done. <ide> def __init__( <ide> layer_norm_eps=1e-12, <ide> pad_token_id=0, <ide> gradient_checkpointing=False, <add> position_embedding_type="absolute", <ide> projection_dim: int = 0, <ide> **kwargs <ide> ): <ide> def __init__( <ide> self.layer_norm_eps = layer_norm_eps <ide> self.gradient_checkpointing = gradient_checkpointing <ide> self.projection_dim = projection_dim <add> self.position_embedding_type = position_embedding_type <ide><path>src/transformers/models/electra/modeling_electra.py <ide> def __init__(self, config): <ide> <ide> # position_ids (1, len position emb) is contiguous in memory and exported when serialized <ide> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> <ide> # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.forward <ide> def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): <ide> def __init__(self, config): <ide> self.value = nn.Linear(config.hidden_size, self.all_head_size) <ide> <ide> self.dropout = nn.Dropout(config.attention_probs_dropout_prob) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) <ide><path>src/transformers/models/layoutlm/modeling_layoutlm.py <ide> def __init__(self, config): <ide> self.value = nn.Linear(config.hidden_size, self.all_head_size) <ide> <ide> self.dropout = nn.Dropout(config.attention_probs_dropout_prob) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) <ide><path>src/transformers/models/roberta/modeling_roberta.py <ide> def __init__(self, config): <ide> <ide> # position_ids (1, len position emb) is contiguous in memory and exported when serialized <ide> self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> <ide> # End copy <ide> self.padding_idx = config.pad_token_id <ide> def __init__(self, config): <ide> self.value = nn.Linear(config.hidden_size, self.all_head_size) <ide> <ide> self.dropout = nn.Dropout(config.attention_probs_dropout_prob) <del> self.position_embedding_type = config.position_embedding_type <add> self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") <ide> if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": <ide> self.max_position_embeddings = config.max_position_embeddings <ide> self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) <ide><path>tests/test_modeling_dpr.py <ide> if is_torch_available(): <ide> import torch <ide> <del> from transformers import BertConfig, DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader <add> from transformers import DPRConfig, DPRContextEncoder, DPRQuestionEncoder, DPRReader <ide> from transformers.models.dpr.modeling_dpr import ( <ide> DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, <ide> DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, <ide> def prepare_config_and_inputs(self): <ide> token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) <ide> choice_labels = ids_tensor([self.batch_size], self.num_choices) <ide> <del> config = BertConfig( <add> config = DPRConfig( <add> projection_dim=self.projection_dim, <ide> vocab_size=self.vocab_size, <ide> hidden_size=self.hidden_size, <ide> num_hidden_layers=self.num_hidden_layers, <ide> def prepare_config_and_inputs(self): <ide> attention_probs_dropout_prob=self.attention_probs_dropout_prob, <ide> max_position_embeddings=self.max_position_embeddings, <ide> type_vocab_size=self.type_vocab_size, <del> is_decoder=False, <ide> initializer_range=self.initializer_range, <ide> ) <del> config = DPRConfig(projection_dim=self.projection_dim, **config.to_dict()) <ide> <ide> return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels <ide> <del> def create_and_check_dpr_context_encoder( <add> def create_and_check_context_encoder( <ide> self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels <ide> ): <ide> model = DPRContextEncoder(config=config) <ide> def create_and_check_dpr_context_encoder( <ide> result = model(input_ids) <ide> self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size)) <ide> <del> def create_and_check_dpr_question_encoder( <add> def create_and_check_question_encoder( <ide> self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels <ide> ): <ide> model = DPRQuestionEncoder(config=config) <ide> def create_and_check_dpr_question_encoder( <ide> result = model(input_ids) <ide> self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size)) <ide> <del> def create_and_check_dpr_reader( <add> def create_and_check_reader( <ide> self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels <ide> ): <ide> model = DPRReader(config=config) <ide> def setUp(self): <ide> def test_config(self): <ide> self.config_tester.run_common_tests() <ide> <del> def test_dpr_context_encoder_model(self): <add> def test_context_encoder_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <del> self.model_tester.create_and_check_dpr_context_encoder(*config_and_inputs) <add> self.model_tester.create_and_check_context_encoder(*config_and_inputs) <ide> <del> def test_dpr_question_encoder_model(self): <add> def test_question_encoder_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <del> self.model_tester.create_and_check_dpr_question_encoder(*config_and_inputs) <add> self.model_tester.create_and_check_question_encoder(*config_and_inputs) <ide> <del> def test_dpr_reader_model(self): <add> def test_reader_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <del> self.model_tester.create_and_check_dpr_reader(*config_and_inputs) <add> self.model_tester.create_and_check_reader(*config_and_inputs) <ide> <ide> @slow <ide> def test_model_from_pretrained(self):
7
Text
Text
fix validate_my_field signature
69f605f30e271b5ca8efbf0638143fdf88877969
<ide><path>docs/api-guide/serializers.md <ide> Similar to Django forms, you can extend and reuse serializers through inheritanc <ide> class MyBaseSerializer(Serializer): <ide> my_field = serializers.CharField() <ide> <del> def validate_my_field(self): <add> def validate_my_field(self, value): <ide> ... <ide> <ide> class MySerializer(MyBaseSerializer):
1
PHP
PHP
use single quotes
c21c87defcf412c48c8b0cfe3eb8af89c8132ad5
<ide><path>src/Illuminate/Database/Console/Factories/FactoryMakeCommand.php <ide> protected function buildClass($name) <ide> $model = $this->qualifyClass($this->argument('name')); <ide> <ide> if ($this->argument('model')) { <del> $model = $this->qualifyClass($this->argument("model")); <add> $model = $this->qualifyClass($this->argument('model')); <ide> } <ide> <ide> return str_replace(
1
Ruby
Ruby
teach commands to work with revisions
17032a600c374f76d8571cf643b4f9a861d26758
<ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_cellar <ide> <ide> def cleanup_formula f <ide> if f.installed? <del> eligible_kegs = f.rack.subdirs.map { |d| Keg.new(d) }.select { |k| f.version > k.version } <add> eligible_kegs = f.rack.subdirs.map { |d| Keg.new(d) }.select { |k| f.pkg_version > k.version } <ide> eligible_kegs.each do |keg| <ide> if f.can_cleanup? <ide> cleanup_keg(keg) <ide><path>Library/Homebrew/cmd/outdated.rb <ide> module Homebrew extend self <ide> def outdated <ide> outdated_brews do |f, versions| <ide> if $stdout.tty? and not ARGV.flag? '--quiet' <del> puts "#{f.name} (#{versions*', '} < #{f.version})" <add> puts "#{f.name} (#{versions*', '} < #{f.pkg_version})" <ide> else <ide> puts f.name <ide> end <ide> def outdated <ide> def outdated_brews <ide> Formula.installed.map do |f| <ide> versions = f.rack.subdirs.map { |d| Keg.new(d).version }.sort! <del> if versions.all? { |version| f.version > version } <add> if versions.all? { |version| f.pkg_version > version } <ide> yield f, versions if block_given? <ide> f <ide> end <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> <ide> unless outdated.empty? <ide> oh1 "Upgrading #{outdated.length} outdated package#{outdated.length.plural_s}, with result:" <del> puts outdated.map{ |f| "#{f.name} #{f.version}" } * ", " <add> puts outdated.map{ |f| "#{f.name} #{f.pkg_version}" } * ", " <ide> else <ide> oh1 "No packages to upgrade" <ide> end <ide> <ide> unless upgrade_pinned? || pinned.empty? <ide> oh1 "Not upgrading #{pinned.length} pinned package#{pinned.length.plural_s}:" <del> puts pinned.map{ |f| "#{f.name} #{f.version}" } * ", " <add> puts pinned.map{ |f| "#{f.name} #{f.pkg_version}" } * ", " <ide> end <ide> <ide> outdated.each { |f| upgrade_formula(f) }
3
PHP
PHP
fix issue
73e63ed88ab1fdd39d24f3f2a2b5d32d9eb3b30d
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function whereDay($column, $operator, $value = null, $boolean = 'and') <ide> $value = $value->format('d'); <ide> } <ide> <add> $value = str_pad($value, 2, '0', STR_PAD_LEFT); <add> <ide> return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean); <ide> } <ide> <ide> public function whereMonth($column, $operator, $value = null, $boolean = 'and') <ide> $value = $value->format('m'); <ide> } <ide> <add> $value = str_pad($value, 2, '0', STR_PAD_LEFT); <add> <ide> return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean); <ide> } <ide>
1
Javascript
Javascript
fix typo in test name
d8b99791ab6c32d6cc864812fa88a1efddf39510
<ide><path>packages/ember-metal/tests/computed_test.js <ide> testBoth('circular keys should not blow up', function(get, set) { <ide> equal(get(obj, 'foo'), 'foo 3', 'cached retrieve'); <ide> }); <ide> <del>testBoth('redefining a property should undo old depenent keys', function(get ,set) { <add>testBoth('redefining a property should undo old dependent keys', function(get ,set) { <ide> <ide> equal(isWatching(obj, 'bar'), false, 'precond not watching dependent key'); <ide> equal(get(obj, 'foo'), 'bar 1');
1
Java
Java
allow use of jsoninclude.value
e881d4b1441b4ade35806b6f06d5b7ebe1828e92
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java <ide> public class Jackson2ObjectMapperBuilder { <ide> private TypeResolverBuilder<?> defaultTyping; <ide> <ide> @Nullable <del> private JsonInclude.Include serializationInclusion; <add> private JsonInclude.Value serializationInclusion; <ide> <ide> @Nullable <ide> private FilterProvider filters; <ide> public Jackson2ObjectMapperBuilder defaultTyping(TypeResolverBuilder<?> typeReso <ide> * Set a custom inclusion strategy for serialization. <ide> * @see com.fasterxml.jackson.annotation.JsonInclude.Include <ide> */ <del> public Jackson2ObjectMapperBuilder serializationInclusion(JsonInclude.Include serializationInclusion) { <add> public Jackson2ObjectMapperBuilder serializationInclusion(JsonInclude.Include inclusion) { <add> return serializationInclusion(JsonInclude.Value.construct(inclusion, inclusion)); <add> } <add> <add> /** <add> * Set a custom inclusion strategy for serialization. <add> * @since 5.3 <add> * @see com.fasterxml.jackson.annotation.JsonInclude.Value <add> */ <add> public Jackson2ObjectMapperBuilder serializationInclusion(JsonInclude.Value serializationInclusion) { <ide> this.serializationInclusion = serializationInclusion; <ide> return this; <ide> } <ide> else if (this.findWellKnownModules) { <ide> objectMapper.setDefaultTyping(this.defaultTyping); <ide> } <ide> if (this.serializationInclusion != null) { <del> objectMapper.setSerializationInclusion(this.serializationInclusion); <add> objectMapper.setDefaultPropertyInclusion(this.serializationInclusion); <ide> } <ide> <ide> if (this.filters != null) {
1
Javascript
Javascript
improve norwegian bokmål. fixes
42dfe2fb5ea9853c2defbf539f2b872aedb5403d
<ide><path>locale/nb.js <ide> }(function (moment) { <ide> return moment.defineLocale('nb', { <ide> months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), <del> monthsShort : 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), <add> monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), <ide> weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), <del> weekdaysShort : 'sø._ma._ti._on._to._fr._lø.'.split('_'), <add> weekdaysShort : 'søn_man_tirs_ons_tors_fre_lør'.split('_'), <ide> weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), <ide> longDateFormat : { <ide> LT : 'H.mm', <ide><path>test/locale/nb.js <ide> exports['locale:nb'] = { <ide> }, <ide> <ide> 'parse' : function (test) { <del> var tests = 'januar jan_februar feb_mars mars_april april_mai mai_juni juni_juli juli_august aug_september sep_oktober okt_november nov_desember des'.split('_'), <add> var tests = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), <ide> i; <ide> function equalTest(input, mmm, i) { <ide> test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); <ide> exports['locale:nb'] = { <ide> 'format' : function (test) { <ide> var a = [ <ide> ['dddd, MMMM Do YYYY, h:mm:ss a', 'søndag, februar 14. 2010, 3:25:50 pm'], <del> ['ddd, hA', 'sø., 3PM'], <del> ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], <add> ['ddd, hA', 'søn, 3PM'], <add> ['M Mo MM MMMM MMM', '2 2. 02 februar feb'], <ide> ['YYYY YY', '2010 10'], <ide> ['D Do DD', '14 14. 14'], <del> ['d do dddd ddd dd', '0 0. søndag sø. sø'], <add> ['d do dddd ddd dd', '0 0. søndag søn sø'], <ide> ['DDD DDDo DDDD', '45 45. 045'], <ide> ['w wo ww', '6 6. 06'], <ide> ['h hh', '3 03'], <ide> exports['locale:nb'] = { <ide> ['LLL', '14. februar 2010 kl. 15.25'], <ide> ['LLLL', 'søndag 14. februar 2010 kl. 15.25'], <ide> ['l', '14.2.2010'], <del> ['ll', '14. feb. 2010'], <del> ['lll', '14. feb. 2010 kl. 15.25'], <del> ['llll', 'sø. 14. feb. 2010 kl. 15.25'] <add> ['ll', '14. feb 2010'], <add> ['lll', '14. feb 2010 kl. 15.25'], <add> ['llll', 'søn 14. feb 2010 kl. 15.25'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> exports['locale:nb'] = { <ide> }, <ide> <ide> 'format month' : function (test) { <del> var expected = 'januar jan._februar feb._mars mars_april april_mai mai_juni juni_juli juli_august aug._september sep._oktober okt._november nov._desember des.'.split('_'), i; <add> var expected = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; <ide> for (i = 0; i < expected.length; i++) { <ide> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); <ide> } <ide> test.done(); <ide> }, <ide> <ide> 'format week' : function (test) { <del> var expected = 'søndag sø. sø_mandag ma. ma_tirsdag ti. ti_onsdag on. on_torsdag to. to_fredag fr. fr_lørdag lø. lø'.split('_'), i; <add> var expected = 'søndag søn sø_mandag man ma_tirsdag tirs ti_onsdag ons on_torsdag tors to_fredag fre fr_lørdag lør lø'.split('_'), i; <ide> for (i = 0; i < expected.length; i++) { <ide> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); <ide> }
2
Javascript
Javascript
increase code coverage of cjs loader
6ef4d9ef116f616ccaf189e651f83184a922379c
<ide><path>test/fixtures/cjs-module-wrap.js <add>'use strict'; <ide> const assert = require('assert'); <ide> const m = require('module'); <ide> <ide><path>test/fixtures/cjs-module-wrapper.js <add>'use strict'; <add>const assert = require('assert'); <add>const m = require('module'); <add> <add>global.mwc = 0; <add> <add>const originalWrapper = m.wrapper; <add>const patchedWrapper = {...m.wrapper}; <add> <add>patchedWrapper[0] += 'global.mwc = (global.mwc || 0 ) + 1'; <add> <add>// Storing original version of wrapper function <add>m.wrapper = patchedWrapper; <add> <add>require('./not-main-module.js'); <add> <add>assert.strictEqual(mwc, 1); <add> <add>// Restoring original wrapper function <add>m.wrapper = originalWrapper; <add>// Cleaning require cache <add>delete require.cache[require.resolve('./not-main-module.js')]; <add>delete global.mwc; <ide><path>test/parallel/test-module-wrap.js <ide> const fixtures = require('../common/fixtures'); <ide> const { execFileSync } = require('child_process'); <ide> <ide> const cjsModuleWrapTest = fixtures.path('cjs-module-wrap.js'); <del>const node = process.argv[0]; <add>const node = process.execPath; <ide> <ide> execFileSync(node, [cjsModuleWrapTest], { stdio: 'pipe' }); <ide><path>test/parallel/test-module-wrapper.js <add>'use strict'; <add>require('../common'); <add>const fixtures = require('../common/fixtures'); <add>const { execFileSync } = require('child_process'); <add> <add>const cjsModuleWrapTest = fixtures.path('cjs-module-wrapper.js'); <add>const node = process.execPath; <add> <add>execFileSync(node, [cjsModuleWrapTest], { stdio: 'pipe' });
4
Javascript
Javascript
use stripe checkout on donate page
d74d72446d9705ae4f1ba765d65735ebd766fa11
<ide><path>client/src/components/Donation/DonateForm.js <ide> import PropTypes from 'prop-types'; <ide> import { connect } from 'react-redux'; <ide> import { createSelector } from 'reselect'; <ide> import { <del> Tabs, <del> Tab, <del> Row, <add> Button, <ide> Col, <del> ToggleButtonGroup, <add> Row, <add> Tab, <add> Tabs, <ide> ToggleButton, <del> Button <add> ToggleButtonGroup <ide> } from '@freecodecamp/react-bootstrap'; <ide> // import { StripeProvider, Elements } from 'react-stripe-elements'; <ide> <ide> import { <ide> amountsConfig, <ide> durationsConfig, <ide> defaultAmount, <del> defaultStateConfig <add> defaultStateConfig, <add> onetimeSKUConfig <ide> } from '../../../../config/donation-settings'; <add>import { deploymentEnv } from '../../../config/env.json'; <ide> import Spacer from '../helpers/Spacer'; <ide> // import DonateFormChildViewForHOC from './DonateFormChildViewForHOC'; <ide> import PaypalButton from './PaypalButton'; <ide> const propTypes = { <ide> navigate: PropTypes.func.isRequired, <ide> showLoading: PropTypes.bool.isRequired, <ide> stripe: PropTypes.shape({ <del> createToken: PropTypes.func.isRequired <add> createToken: PropTypes.func.isRequired, <add> redirectToCheckout: PropTypes.func.isRequired <ide> }) <ide> }; <ide> <ide> class DonateForm extends Component { <ide> this.getDonationButtonLabel = this.getDonationButtonLabel.bind(this); <ide> this.handleSelectAmount = this.handleSelectAmount.bind(this); <ide> this.handleSelectDuration = this.handleSelectDuration.bind(this); <add> this.handleStripeCheckoutRedirect = this.handleStripeCheckoutRedirect.bind( <add> this <add> ); <ide> this.hideAmountOptionsCB = this.hideAmountOptionsCB.bind(this); <ide> this.resetDonation = this.resetDonation.bind(this); <ide> } <ide> class DonateForm extends Component { <ide> this.setState({ donationAmount }); <ide> } <ide> <add> async handleStripeCheckoutRedirect(e) { <add> const { stripe } = this.props; <add> const { donationAmount, donationDuration } = this.state; <add> <add> const isOneTime = donationDuration === 'onetime'; <add> const getSKUId = () => { <add> const { id } = onetimeSKUConfig[deploymentEnv || 'staging'].find( <add> skuConfig => skuConfig.amount === `${donationAmount}` <add> ); <add> return id; <add> }; <add> <add> e.preventDefault(); <add> const item = isOneTime <add> ? { <add> sku: getSKUId(), <add> quantity: 1 <add> } <add> : { <add> plan: `${this.durations[donationDuration]}-donation-${donationAmount}`, <add> quantity: 1 <add> }; <add> const { error } = await stripe.redirectToCheckout({ <add> items: [item], <add> successUrl: 'https://www.freecodecamp.org/news/thank-you-for-donating/', <add> cancelUrl: 'https://freecodecamp.org/donate' <add> }); <add> console.error(error); <add> } <add> <ide> renderAmountButtons(duration) { <ide> return this.amounts[duration].map(amount => ( <ide> <ToggleButton <ide> class DonateForm extends Component { <ide> } <ide> <ide> renderDonationOptions() { <del> // const { stripe, handleProcessing, isSignedIn } = this.props; <ide> const { handleProcessing, isSignedIn } = this.props; <ide> const { donationAmount, donationDuration } = this.state; <add> <ide> const isOneTime = donationDuration === 'onetime'; <add> <ide> return ( <ide> <div> <ide> {isOneTime ? ( <ide> class DonateForm extends Component { <ide> </b> <ide> )} <ide> <Spacer /> <add> <Button <add> block={true} <add> bsStyle='primary' <add> className='btn-cta' <add> id='confirm-donation-btn' <add> onClick={this.handleStripeCheckoutRedirect} <add> > <add> Pay with Apple Pay <add> </Button> <add> <Spacer /> <add> <Button <add> block={true} <add> bsStyle='primary' <add> className='btn-cta' <add> id='confirm-donation-btn' <add> onClick={this.handleStripeCheckoutRedirect} <add> > <add> Pay with Google Pay <add> </Button> <add> <Spacer /> <add> <Button <add> block={true} <add> bsStyle='primary' <add> className='btn-cta' <add> id='confirm-donation-btn' <add> onClick={this.handleStripeCheckoutRedirect} <add> > <add> Pay with Card <add> </Button> <add> <Spacer /> <ide> {isOneTime ? ( <ide> this.renderPayPalMeLink(donationAmount) <ide> ) : ( <ide> class DonateForm extends Component { <ide> skipAddDonation={!isSignedIn} <ide> /> <ide> )} <del> <Spacer /> <del> <ide> <Spacer size={2} /> <ide> </div> <ide> ); <ide><path>config/donation-settings.js <ide> const modalDefaultStateConfig = { <ide> donationDuration: 'month' <ide> }; <ide> <add>const onetimeSKUConfig = { <add> live: [ <add> { amount: '100000', id: 'sku_GwHogRRJrCYGms' }, <add> { amount: '25000', id: 'sku_GwHnCde23uDH5R' }, <add> { amount: '6000', id: 'sku_H5mjFgpayAzJzT' } <add> ], <add> staging: [ <add> { amount: '100000', id: 'sku_GvAeUdWLsmGO9O' }, <add> { amount: '25000', id: 'sku_GvAdXbsotjFi7G' }, <add> { amount: '6000', id: 'sku_GvAeJDgwjnGAdy' } <add> ] <add>}; <add> <ide> // Configuration for server side <ide> const durationKeysConfig = ['year', 'month', 'onetime']; <ide> const donationOneTimeConfig = [100000, 25000, 6000]; <ide> module.exports = { <ide> donationOneTimeConfig, <ide> donationSubscriptionConfig, <ide> modalDefaultStateConfig, <add> onetimeSKUConfig, <ide> paypalConfigTypes, <ide> paypalConfigurator <ide> };
2
Text
Text
add changelogs for path
fb395975eff589fb1d8d7badd08ef0eb14077555
<ide><path>doc/api/path.md <ide> path.posix.basename('/tmp/myfile.html'); <ide> ## path.basename(path[, ext]) <ide> <!-- YAML <ide> added: v0.1.25 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5348 <add> description: Passing a non-string as the `path` argument will throw now. <ide> --> <ide> <ide> * `path` {String} <ide> process.env.PATH.split(path.delimiter) <ide> ## path.dirname(path) <ide> <!-- YAML <ide> added: v0.1.16 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5348 <add> description: Passing a non-string as the `path` argument will throw now. <ide> --> <ide> <ide> * `path` {String} <ide> A [`TypeError`][] is thrown if `path` is not a string. <ide> ## path.extname(path) <ide> <!-- YAML <ide> added: v0.1.25 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5348 <add> description: Passing a non-string as the `path` argument will throw now. <ide> --> <ide> <ide> * `path` {String} <ide> of the `path` methods. <ide> ## path.relative(from, to) <ide> <!-- YAML <ide> added: v0.5.0 <add>changes: <add> - version: v6.8.0 <add> pr-url: https://github.com/nodejs/node/pull/8523 <add> description: On Windows, the leading slashes for UNC paths are now included <add> in the return value. <ide> --> <ide> <ide> * `from` {String}
1
Mixed
Javascript
accept regular expressions to validate
cf7be86cd927c99547f4774d79ea6d12d621033f
<ide><path>doc/api/assert.md <ide> changes: <ide> Expects the function `block` to throw an error. <ide> <ide> If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function, <del>an object where each property will be tested for, or an instance of error where <del>each property will be tested for including the non-enumerable `message` and <del>`name` properties. <add>a validation object where each property will be tested for strict deep equality, <add>or an instance of error where each property will be tested for strict deep <add>equality including the non-enumerable `message` and `name` properties. When <add>using an object, it is also possible to use a regular expression, when <add>validating against a string property. See below for examples. <ide> <ide> If specified, `message` will be the message provided by the `AssertionError` if <ide> the block fails to throw. <ide> <del>Custom error object / error instance: <add>Custom validation object / error instance: <ide> <ide> ```js <ide> const err = new TypeError('Wrong value'); <ide> err.code = 404; <add>err.foo = 'bar'; <add>err.info = { <add> nested: true, <add> baz: 'text' <add>}; <add>err.reg = /abc/i; <ide> <ide> assert.throws( <ide> () => { <ide> throw err; <ide> }, <ide> { <ide> name: 'TypeError', <del> message: 'Wrong value' <del> // Note that only properties on the error object will be tested! <add> message: 'Wrong value', <add> info: { <add> nested: true, <add> baz: 'text' <add> } <add> // Note that only properties on the validation object will be tested for. <add> // Using nested objects requires all properties to be present. Otherwise <add> // the validation is going to fail. <add> } <add>); <add> <add>// Using regular expressions to validate error properties: <add>assert.throws( <add> () => { <add> throw err; <add> }, <add> { <add> // The `name` and `message` properties are strings and using regular <add> // expressions on those will match against the string. If they fail, an <add> // error is thrown. <add> name: /^TypeError$/, <add> message: /Wrong/, <add> foo: 'bar', <add> info: { <add> nested: true, <add> // It is not possible to use regular expressions for nested properties! <add> baz: 'text' <add> }, <add> // The `reg` property contains a regular expression and only if the <add> // validation object contains an identical regular expression, it is going <add> // to pass. <add> reg: /abc/i <ide> } <ide> ); <ide> <ide><path>lib/assert.js <ide> const { <ide> } <ide> } = require('internal/errors'); <ide> const { openSync, closeSync, readSync } = require('fs'); <del>const { inspect, types: { isPromise } } = require('util'); <add>const { inspect, types: { isPromise, isRegExp } } = require('util'); <ide> const { EOL } = require('os'); <ide> const { NativeModule } = require('internal/bootstrap/loaders'); <ide> <ide> assert.notStrictEqual = function notStrictEqual(actual, expected, message) { <ide> }; <ide> <ide> class Comparison { <del> constructor(obj, keys) { <add> constructor(obj, keys, actual) { <ide> for (const key of keys) { <del> if (key in obj) <del> this[key] = obj[key]; <add> if (key in obj) { <add> if (actual !== undefined && <add> typeof actual[key] === 'string' && <add> isRegExp(obj[key]) && <add> obj[key].test(actual[key])) { <add> this[key] = actual[key]; <add> } else { <add> this[key] = obj[key]; <add> } <add> } <ide> } <ide> } <ide> } <ide> function compareExceptionKey(actual, expected, key, message, keys) { <ide> if (!message) { <ide> // Create placeholder objects to create a nice output. <ide> const a = new Comparison(actual, keys); <del> const b = new Comparison(expected, keys); <add> const b = new Comparison(expected, keys, actual); <ide> <ide> const tmpLimit = Error.stackTraceLimit; <ide> Error.stackTraceLimit = 0; <ide> function expectedException(actual, expected, msg) { <ide> keys.push('name', 'message'); <ide> } <ide> for (const key of keys) { <add> if (typeof actual[key] === 'string' && <add> isRegExp(expected[key]) && <add> expected[key].test(actual[key])) { <add> continue; <add> } <ide> compareExceptionKey(actual, expected, key, msg, keys); <ide> } <ide> return true; <ide><path>test/parallel/test-assert.js <ide> assert.throws( <ide> } <ide> ); <ide> } <add> <add>assert.throws( <add> () => { throw new TypeError('foobar'); }, <add> { <add> message: /foo/, <add> name: /^TypeError$/ <add> } <add>); <add> <add>assert.throws( <add> () => assert.throws( <add> () => { throw new TypeError('foobar'); }, <add> { <add> message: /fooa/, <add> name: /^TypeError$/ <add> } <add> ), <add> { <add> message: `${start}\n${actExp}\n\n` + <add> ' Comparison {\n' + <add> "- message: 'foobar',\n" + <add> '+ message: /fooa/,\n' + <add> " name: 'TypeError'\n" + <add> ' }' <add> } <add>);
3
PHP
PHP
fix doc of dbosource->$_querycache
bb2286bc4303b17686e5e404d5e3ba1af7bafd06
<ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> class DboSource extends DataSource { <ide> /** <ide> * Caches serialized results of executed queries <ide> * <del> * @var array Maximum number of queries in the queries log. <add> * @var array Cache of results from executed sql queries. <ide> */ <ide> protected $_queryCache = array(); <ide>
1
PHP
PHP
add stub file i missed earlier
b7c1163ca69d9250362d31e88daa6f12a146b2c9
<ide><path>tests/test_app/TestApp/Shell/AppShell.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.6.5 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace TestApp\Shell; <add> <add>use Cake\Console\Shell; <add> <add>/** <add> * Stub class to ensure inclusion in command list. <add> */ <add>class AppShell extends Shell <add>{ <add>}
1
Javascript
Javascript
match the transitionto apis
8e8a7b950198c1407ab8f78bb34671eb8ed6dd2c
<ide><path>packages/ember-views/lib/views/states/in_buffer.js <ide> Ember.merge(inBuffer, { <ide> destroyElement: function(view) { <ide> view.clearBuffer(); <ide> var viewCollection = view._notifyWillDestroyElement(); <del> viewCollection.transitionTo('preRender'); <add> viewCollection.transitionTo('preRender', false); <ide> <ide> return view; <ide> }, <ide><path>packages/ember-views/lib/views/states/pre_render.js <ide> Ember.merge(preRender, { <ide> viewCollection.trigger('willInsertElement'); <ide> // after createElement, the view will be in the hasElement state. <ide> fn.call(view); <del> viewCollection.transitionTo('inDOM'); <add> viewCollection.transitionTo('inDOM', false); <ide> viewCollection.trigger('didInsertElement'); <ide> }, <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> ViewCollection.prototype = { <ide> } <ide> }, <ide> <del> transitionTo: function(state) { <add> transitionTo: function(state, children) { <ide> var views = this.views; <ide> for (var i = 0, l = views.length; i < l; i++) { <del> views[i].transitionTo(state, false); <add> views[i].transitionTo(state, children); <ide> } <ide> }, <ide>
3
Javascript
Javascript
fix old redirect in courseware.js
2b0428fe51c498f2b2af90c1605f8b5107fe72c1
<ide><path>controllers/courseware.js <ide> exports.coursewareNames = function(req, res) { <ide> <ide> exports.returnNextCourseware = function(req, res) { <ide> if (!req.user) { <del> return res.redirect('coursewares/intro'); <add> return res.redirect('coursewares/start-our-challenges'); <ide> } <ide> var completed = req.user.completedCoursewares.map(function (elem) { <ide> return elem._id; <ide> exports.returnNextCourseware = function(req, res) { <ide> req.flash('errors', { <ide> msg: "It looks like you've completed all the courses we have available. Good job!" <ide> }) <del> return res.redirect('../coursewares/intro'); <add> return res.redirect('../coursewares/start-our-challenges'); <ide> } <ide> nameString = courseware.name.toLowerCase().replace(/\s/g, '-'); <ide> return res.redirect('../coursewares/' + nameString);
1
PHP
PHP
remove unnecessary code
b4e6777ce18b2372d19569ca1314ef3d14a76cdf
<ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php <ide> public function dispatched($command, $callback = null) <ide> return true; <ide> }; <ide> <del> if (is_null($callback)) { <del> return collect($this->commands[$command]); <del> } <del> <ide> return collect($this->commands[$command])->filter(function ($command) use ($callback) { <ide> return $callback($command); <ide> }); <ide><path>src/Illuminate/Support/Testing/Fakes/EventFake.php <ide> public function fired($event, $callback = null) <ide> return true; <ide> }; <ide> <del> if (is_null($callback)) { <del> return collect($this->events[$event]); <del> } <del> <ide> return collect($this->events[$event])->filter(function ($arguments) use ($callback) { <ide> return $callback(...$arguments); <ide> })->flatMap(function ($arguments) { <ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php <ide> public function sent($mailable, $callback = null) <ide> return true; <ide> }; <ide> <del> if (is_null($callback)) { <del> return collect($this->mailables[$mailable]); <del> } <del> <ide> return $this->mailablesOf($mailable)->filter(function ($mailable) use ($callback) { <ide> return $callback($mailable->mailable, ...array_values($mailable->getRecipients())); <ide> }); <ide><path>src/Illuminate/Support/Testing/Fakes/NotificationFake.php <ide> public function sent($notifiable, $notification, $callback = null) <ide> <ide> $notifications = collect($this->notificationsFor($notifiable, $notification)); <ide> <del> if (is_null($callback)) { <del> return $notifications; <del> } <del> <ide> return $notifications->filter(function ($arguments) use ($callback) { <ide> return $callback(...array_values($arguments)); <ide> })->pluck('notification'); <ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php <ide> public function pushed($job, $callback = null) <ide> return true; <ide> }; <ide> <del> if (is_null($callback)) { <del> return collect($this->jobs[$job]); <del> } <del> <ide> return collect($this->jobs[$job])->filter(function ($data) use ($callback) { <ide> return $callback($data['job'], $data['queue']); <ide> })->pluck('job');
5
Python
Python
set action for head requests
908f91d8ef13649b6d658981e28ff52296b19f9f
<ide><path>rest_framework/viewsets.py <ide> def as_view(cls, actions=None, **initkwargs): <ide> <ide> def view(request, *args, **kwargs): <ide> self = cls(**initkwargs) <add> <add> if 'get' in actions and 'head' not in actions: <add> actions['head'] = actions['get'] <add> <ide> # We also store the mapping of request methods to actions, <ide> # so that we can later set the action attribute. <ide> # eg. `self.action = 'list'` on an incoming GET request. <ide> def view(request, *args, **kwargs): <ide> handler = getattr(self, action) <ide> setattr(self, method, handler) <ide> <del> if hasattr(self, 'get') and not hasattr(self, 'head'): <del> self.head = self.get <del> <ide> self.request = request <ide> self.args = args <ide> self.kwargs = kwargs <ide><path>tests/test_viewsets.py <ide> class ActionViewSet(GenericViewSet): <ide> queryset = Action.objects.all() <ide> <ide> def list(self, request, *args, **kwargs): <del> return Response() <add> response = Response() <add> response.view = self <add> return response <ide> <ide> def retrieve(self, request, *args, **kwargs): <ide> return Response() <ide> <ide> @action(detail=False) <ide> def list_action(self, request, *args, **kwargs): <del> raise NotImplementedError <add> response = Response() <add> response.view = self <add> return response <ide> <ide> @action(detail=False, url_name='list-custom') <ide> def custom_list_action(self, request, *args, **kwargs): <ide> def test_args_kwargs_request_action_map_on_self(self): <ide> self.assertNotIn(attribute, dir(bare_view)) <ide> self.assertIn(attribute, dir(view)) <ide> <add> def test_viewset_action_attr(self): <add> view = ActionViewSet.as_view(actions={'get': 'list'}) <add> <add> get = view(factory.get('/')) <add> head = view(factory.head('/')) <add> assert get.view.action == 'list' <add> assert head.view.action == 'list' <add> <add> def test_viewset_action_attr_for_extra_action(self): <add> view = ActionViewSet.as_view(actions=dict(ActionViewSet.list_action.mapping)) <add> <add> get = view(factory.get('/')) <add> head = view(factory.head('/')) <add> assert get.view.action == 'list_action' <add> assert head.view.action == 'list_action' <add> <ide> <ide> class GetExtraActionsTests(TestCase): <ide>
2
PHP
PHP
add eloquent alias
7dc60a86dc66a92d5046e811cb4fb325250c7a3b
<ide><path>config/app.php <ide> 'Cookie' => 'Illuminate\Support\Facades\Cookie', <ide> 'Crypt' => 'Illuminate\Support\Facades\Crypt', <ide> 'DB' => 'Illuminate\Support\Facades\DB', <add> 'Eloquent' => 'Illuminate\Database\Eloquent\Model', <ide> 'Event' => 'Illuminate\Support\Facades\Event', <ide> 'File' => 'Illuminate\Support\Facades\File', <ide> 'Hash' => 'Illuminate\Support\Facades\Hash',
1
Javascript
Javascript
fix unbalanced chaining
ac10de2953edf070d12f229070a857b8bbb11a5d
<ide><path>packages/ember-metal/lib/watch_path.js <ide> export function unwatchPath(obj, keyPath, meta) { <ide> <ide> if (counter === 1) { <ide> m.writeWatching(keyPath, 0); <del> m.readableChains().remove(keyPath); <add> m.writableChains(makeChainNode).remove(keyPath); <ide> } else if (counter > 1) { <ide> m.writeWatching(keyPath, counter - 1); <ide> }
1