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
Ruby
Ruby
remove hardcoded reference to java 11
658352ac1f515ecc3b581e801fe150658dc3df21
<ide><path>Library/Homebrew/cask/dsl/caveats.rb <ide> def eval_caveats(&block) <ide> #{@cask} requires Java. You can install the latest version with: <ide> brew install --cask adoptopenjdk <ide> EOS <del> elsif java_version.include?("11") || java_version.include?("+") <add> elsif java_version.include?("+") <ide> <<~EOS <ide> #{@cask} requires Java #{java_version}. You can install the latest version with: <ide> brew install --cask adoptopenjdk
1
PHP
PHP
fix code style 3
3a7d9ac0c9d731f9626ca707cc154af9fb3799ff
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public function qualifyColumn($column) <ide> public function qualifyColumns($columns) <ide> { <ide> $columns = is_array($columns) ? $columns : func_get_args(); <add> <ide> $qualifiedArray = []; <add> <ide> foreach ($columns as $column) { <ide> $qualifiedArray[] = $this->qualifyColumn($column); <ide> }
1
Text
Text
fix typo in redux-saga example
2684c98d04139097e630c4af55c8f8e2bdeb8c8a
<ide><path>docs/introduction/Ecosystem.md <ide> Handle async logic using synchronous-looking generator functions. Sagas return d <ide> function* fetchData(action) { <ide> const {someValue} = action; <ide> try { <del> const result = yield call(myAjaxLib.post, "/someEndpoint", {data : someValue}); <add> const response = yield call(myAjaxLib.post, "/someEndpoint", {data : someValue}); <ide> yield put({type : "REQUEST_SUCCEEDED", payload : response}); <ide> } <ide> catch(error) {
1
Go
Go
fix daemon command proxy
a594cd89919ab3e1aacefb4368c620e308ad0b5d
<ide><path>cmd/docker/daemon_none_test.go <ide> package main <ide> <ide> import ( <del> "strings" <ide> "testing" <add> <add> "github.com/docker/docker/pkg/testutil/assert" <ide> ) <ide> <del>func TestCmdDaemon(t *testing.T) { <del> proxy := NewDaemonProxy() <del> err := proxy.CmdDaemon("--help") <del> if err == nil { <del> t.Fatal("Expected CmdDaemon to fail on Windows.") <del> } <add>func TestDaemonCommand(t *testing.T) { <add> cmd := newDaemonCommand() <add> cmd.SetArgs([]string{"--help"}) <add> err := cmd.Execute() <ide> <del> if !strings.Contains(err.Error(), "Please run `dockerd`") { <del> t.Fatalf("Expected an error about running dockerd, got %s", err) <del> } <add> assert.Error(t, err, "Please run `dockerd`") <ide> } <ide><path>cmd/docker/daemon_unit_test.go <add>// +build daemon <add> <add>package main <add> <add>import ( <add> "testing" <add> <add> "github.com/docker/docker/pkg/testutil/assert" <add> "github.com/spf13/cobra" <add>) <add> <add>func stubRun(cmd *cobra.Command, args []string) error { <add> return nil <add>} <add> <add>func TestDaemonCommandHelp(t *testing.T) { <add> cmd := newDaemonCommand() <add> cmd.RunE = stubRun <add> cmd.SetArgs([]string{"--help"}) <add> err := cmd.Execute() <add> assert.NilError(t, err) <add>} <add> <add>func TestDaemonCommand(t *testing.T) { <add> cmd := newDaemonCommand() <add> cmd.RunE = stubRun <add> cmd.SetArgs([]string{"--containerd", "/foo"}) <add> err := cmd.Execute() <add> assert.NilError(t, err) <add>} <ide><path>cmd/docker/daemon_unix.go <ide> const daemonBinary = "dockerd" <ide> <ide> func newDaemonCommand() *cobra.Command { <ide> cmd := &cobra.Command{ <del> Use: "daemon", <del> Hidden: true, <add> Use: "daemon", <add> Hidden: true, <add> Args: cobra.ArbitraryArgs, <add> DisableFlagParsing: true, <ide> RunE: func(cmd *cobra.Command, args []string) error { <ide> return runDaemon() <ide> },
3
Text
Text
add article for websocket
d5d2c0633932f93442a48f2f7c7bc87ae283ef04
<ide><path>guide/english/nodejs/websocket/index.md <add>--- <add>title: WebSocket <add>--- <add> <add> <add># WebSocket <add>[WebSocket](https://www.websocket.org) is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The <add>WebSocket protocol enables interaction between a web client (such as a browser) and a web server with lower overheads, <add>facilitating real-time data transfer from and to the server. This is made possible by providing a standardized way for the <add>server to send content to the client without being first requested by the client, and allowing messages to be passed back and <add>forth while keeping the connection open. In this way, a two-way ongoing conversation can take place between the client and the <add>server. <add> <add>In [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), server can only respond to a request of client, it cannot send a response without client request. Although, WebSocket <add>and HTTP are different but WebSocket has been designed such that they both are compatible.<sup>1</sup> <add> <add> <add>## WS <add>We will be using the [`ws`](https://www.npmjs.com/package/ws) module to implement webSocket in node.js. <add> <add>### Installing <add>`npm install ws -g` <add> <add>### Usage <add>#### Server <add>Lets create a server that sends a message to client when a connection is established, and logs message sent by the client. <add>```javascript <add>var WebSocketServer = require('ws').Server; <add>var wss = new WebSocketServer({port: 8080}); <add> <add>wss.on('connection', function(ws) { <add> ws.on('message', function(message) { <add> console.log('Message received: %s', message); <add> }); <add> ws.send('Hello from server'); <add>}); <add>``` <add>`new WebSocketServer({port: 8080})` starts a server on port no. 8080. Then the lines following are the callback functions. <add>`function(ws)` is called once a connection is established with a client. `function(message)` is called when a client sends a <add>message to the server. <add>Save the code in a file named `ws_server.js`. <add> <add>#### Client <add>Use the code below to connect to the server <add>```javascript <add>var WebSocket = require('ws'); <add>var ws = new WebSocket('ws://localhost:8080/websockets/'); <add> <add>ws.on('open', function() { <add> ws.send('Msg from client'); <add>}); <add>ws.on('message', function(data, flags) { <add> console.log('Msg received in client: %s ', data); <add>}); <add>``` <add>`new WebSocket('ws://localhost:8080/websockets/')` establishes a connection with the server on port 8080, that we have created <add>above. `ws.on('open', function() ` sends message to server when connection is established. The other function logs the message <add>sent by the server. <add>Save the code in a file as `ws_client.js`. <add> <add>Now lets run our code. Go to the directory in which you saved your file and run the following commands <add> <add>**Server:** <add>`$ node ws_server.js` <add> <add>**Client:** <add>`$ node ws_client.js` <add> <add>From the output you can see that the server starts and is ready to accept connection. When the client starts it first establishes a connection with the server, then sends a message and listens for an incoming message from server. Once the connection is established between server and client, `ws.send()` is fired and messages are exchanged between both of them, and due to the asynchronous nature of `node.js`, both of them at the same time, are listening also. <add> <add> ## Reference <add> - [Wiki page](https://en.wikipedia.org/wiki/WebSocket) <add> - [Linode guide](https://www.linode.com/docs/development/introduction-to-websockets/)
1
Text
Text
fix typo on template.md
6d14499607c281c0780078adc6e40a8575c6c254
<ide><path>examples/code-splitting/template.md <ide> This example illustrates a very simple case of Code Splitting with `require.ensure`. <ide> <ide> * `a` and `b` are required normally via CommonJS <del>* `c` is depdended through the `require.ensure` array. <add>* `c` is depended through the `require.ensure` array. <ide> * This means: make it available, but don't execute it <ide> * webpack will load it on demand <ide> * `b` and `d` are required via CommonJs in the `require.ensure` callback
1
PHP
PHP
fix encryption pad handling. fixes
909e4d0e75deb95659deebde1bf7ec09563a88d6
<ide><path>src/Illuminate/Encryption/Encrypter.php <ide> public function decrypt($payload) <ide> // We'll go ahead and remove the PKCS7 padding from the encrypted value before <ide> // we decrypt it. Once we have the de-padded value, we will grab the vector <ide> // and decrypt the data, passing back the unserialized from of the value. <del> $value = $this->stripPadding(base64_decode($payload['value'])); <add> $value = base64_decode($payload['value']); <ide> <ide> $iv = base64_decode($payload['iv']); <ide> <del> return unserialize(rtrim($this->mcryptDecrypt($value, $iv))); <add> return unserialize($this->stripPadding($this->mcryptDecrypt($value, $iv))); <ide> } <ide> <ide> /** <ide> protected function stripPadding($value) <ide> { <ide> $pad = ord($value[($len = strlen($value)) - 1]); <ide> <del> return $this->paddingIsValid($pad, $value) ? substr($value, 0, -$pad) : $value; <add> return $this->paddingIsValid($pad, $value) ? substr($value, 0, strlen($value) - $pad) : $value; <ide> } <ide> <ide> /** <ide> protected function stripPadding($value) <ide> */ <ide> protected function paddingIsValid($pad, $value) <ide> { <del> return $pad and $pad <= $this->block and preg_match('/'.chr($pad).'{'.$pad.'}$/', $value); <add> $beforePad = strlen($value) - $pad; <add> <add> return substr($value, $beforePad) == str_repeat(substr($value, -1), $pad); <ide> } <ide> <ide> /**
1
PHP
PHP
use forcereconnection method
8c8eb21546b1ae949c459c244d8188308e423f69
<ide><path>src/Illuminate/Mail/Mailer.php <ide> protected function sendSwiftMessage($message) <ide> try { <ide> return $this->swift->send($message, $this->failedRecipients); <ide> } finally { <del> $this->swift->getTransport()->stop(); <add> $this->forceReconnection(); <ide> } <ide> } <ide>
1
Ruby
Ruby
add a failing test for ticket
7ba756281ac193e53cabba3ada75f1423906bb97
<ide><path>railties/test/application/routing_test.rb <ide> def foo_or_bar? <ide> assert_equal 'bar', last_response.body <ide> end <ide> <add> test "mount rack app" do <add> app_file 'config/routes.rb', <<-RUBY <add> AppTemplate::Application.routes.draw do |map| <add> mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, :at => "/blog" <add> # The line below is required because mount sometimes <add> # fails when a resource route is added. <add> resource :user <add> end <add> RUBY <add> <add> get '/blog/archives' <add> assert_equal '/archives', last_response.body <add> end <add> <ide> test "multiple controllers" do <ide> controller :foo, <<-RUBY <ide> class FooController < ApplicationController
1
Ruby
Ruby
remove few ivars from gcs_service implementation
2a738b31c538c0627a46504733fca3c914e1724e
<ide><path>lib/active_storage/service/gcs_service.rb <ide> def delete(key) <ide> <ide> def exist?(key) <ide> instrument :exist, key do |payload| <del> answer = file_for(key).present? <del> payload[:exist] = answer <del> answer <add> payload[:exist] = file_for(key).present? <ide> end <ide> end <ide> <ide> def url(key, expires_in:, disposition:, filename:) <ide> instrument :url, key do |payload| <ide> query = { "response-content-disposition" => "#{disposition}; filename=\"#{filename}\"" } <del> generated_url = file_for(key).signed_url(expires: expires_in, query: query) <del> <del> payload[:url] = generated_url <del> <del> generated_url <add> payload[:url] = file_for(key).signed_url(expires: expires_in, query: query) <ide> end <ide> end <ide>
1
Javascript
Javascript
add info about using `isfinite` to exclude `nan`
7705edc0da2138734e3792572f6f25d1ef3876a9
<ide><path>src/Angular.js <ide> function isString(value) {return typeof value === 'string';} <ide> * @description <ide> * Determines if a reference is a `Number`. <ide> * <add> * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`. <add> * <add> * If you wish to exclude these then you can use the native <add> * [`isFinite'](`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) <add> * method. <add> * <ide> * @param {*} value Reference to check. <ide> * @returns {boolean} True if `value` is a `Number`. <ide> */
1
Javascript
Javascript
improve error handling
988cf8d47a07eaa91f1bac48741e2c22b9aa9f84
<ide><path>hot/lazy-compilation-node.js <ide> if (!module.hot) { <ide> } <ide> <ide> var urlBase = decodeURIComponent(__resourceQuery.slice(1)); <del>exports.keepAlive = function (key) { <add>exports.keepAlive = function (options) { <add> var data = options.data; <add> var onError = options.onError; <ide> var response; <del> require("http") <del> .request( <del> urlBase + key, <del> { <del> agent: false, <del> headers: { accept: "text/event-stream" } <del> }, <del> function (res) { <del> response = res; <del> } <del> ) <del> .end(); <add> var request = require("http").request( <add> urlBase + data, <add> { <add> agent: false, <add> headers: { accept: "text/event-stream" } <add> }, <add> function (res) { <add> response = res; <add> response.on("error", errorHandler); <add> } <add> ); <add> function errorHandler(err) { <add> err.message = <add> "Problem communicating active modules to the server: " + err.message; <add> onError(err); <add> } <add> request.on("error", errorHandler); <add> request.end(); <ide> return function () { <ide> response.destroy(); <ide> }; <ide><path>hot/lazy-compilation-web.js <ide> if (typeof EventSource !== "function" || !module.hot) { <ide> var urlBase = decodeURIComponent(__resourceQuery.slice(1)); <ide> var activeEventSource; <ide> var activeKeys = new Map(); <add>var errorHandlers = new Set(); <ide> <ide> var updateEventSource = function updateEventSource() { <ide> if (activeEventSource) activeEventSource.close(); <del> activeEventSource = new EventSource( <del> urlBase + Array.from(activeKeys.keys()).join("@") <del> ); <add> if (activeKeys.size) { <add> activeEventSource = new EventSource( <add> urlBase + Array.from(activeKeys.keys()).join("@") <add> ); <add> activeEventSource.onerror = function (event) { <add> errorHandlers.forEach(function (onError) { <add> onError( <add> new Error( <add> "Problem communicating active modules to the server: " + <add> event.message + <add> " " + <add> event.filename + <add> ":" + <add> event.lineno + <add> ":" + <add> event.colno + <add> " " + <add> event.error <add> ) <add> ); <add> }); <add> }; <add> } else { <add> activeEventSource = undefined; <add> } <ide> }; <ide> <del>exports.keepAlive = function (key) { <del> var value = activeKeys.get(key) || 0; <del> activeKeys.set(key, value + 1); <add>exports.keepAlive = function (options) { <add> var data = options.data; <add> var onError = options.onError; <add> errorHandlers.add(onError); <add> var value = activeKeys.get(data) || 0; <add> activeKeys.set(data, value + 1); <ide> if (value === 0) { <ide> updateEventSource(); <ide> } <ide> <ide> return function () { <add> errorHandlers.delete(onError); <ide> setTimeout(function () { <del> var value = activeKeys.get(key); <add> var value = activeKeys.get(data); <ide> if (value === 1) { <del> activeKeys.delete(key); <add> activeKeys.delete(data); <ide> updateEventSource(); <ide> } else { <del> activeKeys.set(key, value - 1); <add> activeKeys.set(data, value - 1); <ide> } <ide> }, 1000); <ide> }; <ide><path>lib/hmr/LazyCompilationPlugin.js <ide> class LazyCompilationProxyModule extends Module { <ide> runtimeRequirements <ide> })}`, <ide> `var data = ${JSON.stringify(this.data)};`, <del> `var dispose = client.keepAlive(data, ${JSON.stringify( <add> `var dispose = client.keepAlive({ data, active: ${JSON.stringify( <ide> !!block <del> )}, module);` <add> )}, module, onError });` <ide> ]); <ide> let source; <ide> if (block) { <ide> class LazyCompilationProxyModule extends Module { <ide> message: "import()", <ide> runtimeRequirements <ide> })};`, <del> "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);" <add> "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", <add> "function onError() { /* ignore */ }", <add> keepActive <ide> ]); <ide> } else { <ide> source = Template.asString([ <ide> "module.hot.accept();", <del> "var resolveSelf;", <del> `module.exports = new Promise(function(resolve) { resolveSelf = resolve; });`, <add> "var resolveSelf, onError;", <add> `module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });`, <ide> "if (module.hot.data && module.hot.data.resolveSelf) module.hot.data.resolveSelf(module.exports);", <del> "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });" <add> "module.hot.dispose(function(data) { data.resolveSelf = resolveSelf; dispose(data); });", <add> keepActive <ide> ]); <ide> } <del> sources.set("javascript", new RawSource(keepActive + "\n\n" + source)); <add> sources.set("javascript", new RawSource(source)); <ide> return { <ide> sources, <ide> runtimeRequirements <ide><path>test/helpers/EventSourceForNode.js <ide> module.exports = class EventSource { <ide> constructor(url) { <ide> this.response = undefined; <del> require("http") <del> .request( <del> url, <del> { <del> agent: false, <del> headers: { accept: "text/event-stream" } <del> }, <del> res => { <del> this.response = res; <del> res.on("error", err => { <del> if (this.onerror) this.onerror(err); <del> }); <del> } <del> ) <del> .end(); <add> const request = require("http").request( <add> url, <add> { <add> agent: false, <add> headers: { accept: "text/event-stream" } <add> }, <add> res => { <add> this.response = res; <add> res.on("error", err => { <add> if (this.onerror) this.onerror(err); <add> }); <add> } <add> ); <add> request.on("error", err => { <add> if (this.onerror) this.onerror({ message: err }); <add> }); <add> request.end(); <ide> } <ide> <ide> close() { <ide><path>test/hotCases/lazy-compilation/simple/index.js <ide> it("should compile to lazy imported module", done => { <ide> require("../../update")(done, true, () => { <ide> promise.then(result => { <ide> expect(result).toHaveProperty("default", 42); <del> done(); <add> setTimeout(() => { <add> done(); <add> }, 1000); <ide> }, done); <ide> }) <ide> );
5
Go
Go
fix scaling of nanocpus on hyper-v containers
3b5af0a289d76366790092439e53d3983f342472
<ide><path>daemon/daemon_windows.go <ide> func verifyContainerResources(resources *containertypes.Resources, isHyperv bool <ide> return warnings, fmt.Errorf("range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU()) <ide> } <ide> <add> osv := system.GetOSVersion() <add> if resources.NanoCPUs > 0 && isHyperv && osv.Build < 16175 { <add> leftoverNanoCPUs := resources.NanoCPUs % 1e9 <add> if leftoverNanoCPUs != 0 && resources.NanoCPUs > 1e9 { <add> resources.NanoCPUs = ((resources.NanoCPUs + 1e9/2) / 1e9) * 1e9 <add> warningString := fmt.Sprintf("Your current OS version does not support Hyper-V containers with NanoCPUs greater than 1000000000 but not divisible by 1000000000. NanoCPUs rounded to %d", resources.NanoCPUs) <add> warnings = append(warnings, warningString) <add> logrus.Warn(warningString) <add> } <add> } <add> <ide> if len(resources.BlkioDeviceReadBps) > 0 { <ide> return warnings, fmt.Errorf("invalid option: Windows does not support BlkioDeviceReadBps") <ide> } <ide><path>daemon/oci_windows.go <ide> func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) { <ide> // @darrenstahlmsft implement these resources <ide> cpuShares := uint16(c.HostConfig.CPUShares) <ide> cpuPercent := uint8(c.HostConfig.CPUPercent) <add> cpuCount := uint64(c.HostConfig.CPUCount) <ide> if c.HostConfig.NanoCPUs > 0 { <del> cpuPercent = uint8(c.HostConfig.NanoCPUs * 100 / int64(sysinfo.NumCPU()) / 1e9) <add> if isHyperV { <add> cpuCount = uint64(c.HostConfig.NanoCPUs / 1e9) <add> leftoverNanoCPUs := c.HostConfig.NanoCPUs % 1e9 <add> if leftoverNanoCPUs != 0 { <add> cpuCount++ <add> cpuPercent = uint8(c.HostConfig.NanoCPUs * 100 / int64(cpuCount) / 1e9) <add> } <add> } else { <add> cpuPercent = uint8(c.HostConfig.NanoCPUs * 100 / int64(sysinfo.NumCPU()) / 1e9) <add> } <ide> } <del> cpuCount := uint64(c.HostConfig.CPUCount) <ide> memoryLimit := uint64(c.HostConfig.Memory) <ide> s.Windows.Resources = &specs.WindowsResources{ <ide> CPU: &specs.WindowsCPUResources{
2
Python
Python
remove stray print statements
e904075f35dde853f4f210fb4bb1ceebe781bc55
<ide><path>examples/training/train_new_entity_type.py <ide> def main(model=None, new_model_name='animal', output_dir=None): <ide> nlp.update(docs, golds, losses=losses, sgd=optimizer, <ide> drop=0.35) <ide> print(losses) <del> print(nlp.pipeline) <del> print(disabled.original_pipeline) <ide> <ide> # test the trained model <ide> test_text = 'Do you like horses?'
1
Text
Text
update todolist example to react 0.14
cfc5d08a9064b98c149cdd4530b7b195e061ec69
<ide><path>docs/basics/ExampleTodoList.md <ide> This is the complete source code of the tiny todo app we built during the [basic <ide> <ide> ```js <ide> import React from 'react'; <add>import ReactDOM from 'react-dom'; <ide> import { createStore } from 'redux'; <ide> import { Provider } from 'react-redux'; <ide> import App from './containers/App'; <ide> import todoApp from './reducers'; <ide> let store = createStore(todoApp); <ide> <ide> let rootElement = document.getElementById('root'); <del>React.render( <del> // The child must be wrapped in a function <del> // to work around an issue in React 0.13. <add>ReactDOM.render( <ide> <Provider store={store}> <del> {() => <App />} <add> <App /> <ide> </Provider>, <ide> rootElement <ide> ); <ide> export default connect(select)(App); <ide> #### `components/AddTodo.js` <ide> <ide> ```js <del>import React, { findDOMNode, Component, PropTypes } from 'react'; <add>import React, { Component, PropTypes } from 'react'; <add>import { findDOMNode } from 'react-dom'; <ide> <ide> export default class AddTodo extends Component { <ide> render() {
1
Javascript
Javascript
move updated proptypes into new transformproptypes
1c90a2dbcc476b4dc170f315891f5e441d9057d7
<ide><path>Libraries/Components/View/ViewStylePropTypes.js <ide> var ViewStylePropTypes = { <ide> ), <ide> shadowOpacity: ReactPropTypes.number, <ide> shadowRadius: ReactPropTypes.number, <del> transform: ReactPropTypes.arrayOf( <del> ReactPropTypes.oneOfType([ <del> ReactPropTypes.shape({rotate: ReactPropTypes.string}), <del> ReactPropTypes.shape({scaleX: ReactPropTypes.number}), <del> ReactPropTypes.shape({scaleY: ReactPropTypes.number}), <del> ReactPropTypes.shape({translateX: ReactPropTypes.number}), <del> ReactPropTypes.shape({translateY: ReactPropTypes.number}) <del> ]) <del> ), <del> transformMatrix: ReactPropTypes.arrayOf(ReactPropTypes.number), <del> <del> // DEPRECATED <del> rotation: ReactPropTypes.number, <del> scaleX: ReactPropTypes.number, <del> scaleY: ReactPropTypes.number, <del> translateX: ReactPropTypes.number, <del> translateY: ReactPropTypes.number, <ide> }; <ide> <ide> module.exports = ViewStylePropTypes; <ide><path>Libraries/StyleSheet/TransformPropTypes.js <ide> var ReactPropTypes = require('ReactPropTypes'); <ide> <ide> var TransformPropTypes = { <del> transform: ReactPropTypes.arrayOf(ReactPropTypes.object), <add> transform: ReactPropTypes.arrayOf( <add> ReactPropTypes.oneOfType([ <add> ReactPropTypes.shape({rotate: ReactPropTypes.string}), <add> ReactPropTypes.shape({scaleX: ReactPropTypes.number}), <add> ReactPropTypes.shape({scaleY: ReactPropTypes.number}), <add> ReactPropTypes.shape({translateX: ReactPropTypes.number}), <add> ReactPropTypes.shape({translateY: ReactPropTypes.number}) <add> ]) <add> ), <ide> transformMatrix: ReactPropTypes.arrayOf(ReactPropTypes.number), <ide> <ide> // DEPRECATED
2
Python
Python
fix broken import
d3e0ac864f8df4568fe9c0f81d64b41c9f531a02
<ide><path>rest_framework/resources.py <ide> from functools import update_wrapper <ide> import inspect <ide> from django.utils.decorators import classonlymethod <del>from djanorestframework import views, generics <add>from rest_framework import views, generics <ide> <ide> <ide> def wrapped(source, dest):
1
Ruby
Ruby
push options_constraints processing up
10c1787b30b041e0676c88df261811e8b9aa4c5d
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def initialize(scope, path, options) <ide> formatted = options.delete :format <ide> via = Array(options.delete(:via) { [] }) <ide> options_constraints = options.delete :constraints <add> <ide> @blocks = blocks(options_constraints, scope[:blocks]) <ide> <ide> path = normalize_path! path, formatted <ide> def initialize(scope, path, options) <ide> options = normalize_options!(options, formatted, path_params, ast, scope[:module]) <ide> <ide> <del> constraints = constraints(options, <del> options_constraints, <del> (scope[:constraints] || {}), <del> path_params) <add> split_constraints(path_params, scope[:constraints]) if scope[:constraints] <add> constraints = constraints(options, path_params) <ide> <del> normalize_requirements!(path_params, formatted, constraints) <add> split_constraints path_params, constraints <add> <add> if options_constraints.is_a?(Hash) <add> split_constraints path_params, options_constraints <add> options_constraints.each do |key, default| <add> if URL_OPTIONS.include?(key) && (String === default || Fixnum === default) <add> @defaults[key] ||= default <add> end <add> end <add> end <add> <add> normalize_format!(formatted) <ide> <ide> @conditions[:path_info] = path <ide> @conditions[:parsed_path_info] = ast <ide> <ide> add_request_method(via, @conditions) <del> normalize_defaults!(options, formatted, options_constraints) <add> normalize_defaults!(options, formatted) <ide> end <ide> <ide> def to_route <ide> def normalize_options!(options, formatted, path_params, path_ast, modyoule) <ide> end <ide> end <ide> <del> def normalize_requirements!(path_params, formatted, constraints) <add> def split_constraints(path_params, constraints) <ide> constraints.each_pair do |key, requirement| <ide> if path_params.include?(key) || key == :controller <ide> verify_regexp_requirement(requirement) if requirement.is_a?(Regexp) <ide> def normalize_requirements!(path_params, formatted, constraints) <ide> @conditions[key] = requirement <ide> end <ide> end <add> end <ide> <add> def normalize_format!(formatted) <ide> if formatted == true <ide> @requirements[:format] ||= /.+/ <ide> elsif Regexp === formatted <ide> def verify_regexp_requirement(requirement) <ide> end <ide> end <ide> <del> def normalize_defaults!(options, formatted, options_constraints) <add> def normalize_defaults!(options, formatted) <ide> options.each do |key, default| <ide> unless Regexp === default <ide> @defaults[key] = default <ide> end <ide> end <ide> <del> if options_constraints.is_a?(Hash) <del> options_constraints.each do |key, default| <del> if URL_OPTIONS.include?(key) && (String === default || Fixnum === default) <del> @defaults[key] ||= default <del> end <del> end <del> elsif options_constraints <del> verify_callable_constraint(options_constraints) <del> end <del> <ide> if Regexp === formatted <ide> @defaults[:format] = nil <ide> elsif String === formatted <ide> def translate_controller(controller) <ide> end <ide> <ide> def blocks(options_constraints, scope_blocks) <del> if options_constraints.present? && !options_constraints.is_a?(Hash) <add> if options_constraints && !options_constraints.is_a?(Hash) <add> verify_callable_constraint(options_constraints) <ide> [options_constraints] <ide> else <ide> scope_blocks || [] <ide> end <ide> end <ide> <del> def constraints(options, option_constraints, constraints, path_params) <add> def constraints(options, path_params) <add> constraints = {} <ide> required_defaults = [] <ide> options.each_pair do |key, option| <ide> if Regexp === option <ide> def constraints(options, option_constraints, constraints, path_params) <ide> end <ide> end <ide> @conditions[:required_defaults] = required_defaults <del> <del> constraints.merge!(option_constraints) if option_constraints.is_a?(Hash) <ide> constraints <ide> end <ide>
1
Java
Java
avoid use of repeated @scheduled in tests
14ac023e01226778b8481a54a657d3f7f6e5e36b
<ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java <ide> public void fixedRateTaskWithInitialDelay() { <ide> assertEquals(3000L, task.getInterval()); <ide> } <ide> <del> @Test <del> public void severalFixedRates() { <del> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <del> BeanDefinition targetDefinition = new RootBeanDefinition(SeveralFixedRatesTestBean.class); <del> severalFixedRates(context, processorDefinition, targetDefinition); <del> } <add> // TODO Reinstate repeated @Scheduled tests once we have full Java 8 support in the <add> // IDEs. <add> // @Test <add> // public void severalFixedRatesWithRepeatedScheduledAnnotation() { <add> // BeanDefinition processorDefinition = new <add> // RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <add> // BeanDefinition targetDefinition = new RootBeanDefinition( <add> // SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean.class); <add> // severalFixedRates(context, processorDefinition, targetDefinition); <add> // } <ide> <ide> @Test <del> public void severalFixedRatesWithSchedulesContainer() { <add> public void severalFixedRatesWithSchedulesContainerAnnotation() { <ide> BeanDefinition processorDefinition = new RootBeanDefinition( <ide> ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition( <del> SeveralFixedRatesWithSchedulesContainerTestBean.class); <add> SeveralFixedRatesWithSchedulesContainerAnnotationTestBean.class); <ide> severalFixedRates(context, processorDefinition, targetDefinition); <ide> } <ide> <ide> public void fixedRate() { <ide> } <ide> <ide> <del> static class SeveralFixedRatesWithSchedulesContainerTestBean { <add> static class SeveralFixedRatesWithSchedulesContainerAnnotationTestBean { <ide> <ide> @Schedules({ @Scheduled(fixedRate = 4000), <ide> @Scheduled(fixedRate = 4000, initialDelay = 2000) }) <ide> public void fixedRate() { <ide> } <ide> } <ide> <del> static class SeveralFixedRatesTestBean { <del> <del> @Scheduled(fixedRate=4000) <del> @Scheduled(fixedRate=4000, initialDelay=2000) <del> public void fixedRate() { <del> } <del> } <ide> <add> // TODO Reinstate repeated @Scheduled tests once we have full Java 8 support in the <add> // IDEs. <add> // static class SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean { <add> // <add> // @Scheduled(fixedRate=4000) <add> // @Scheduled(fixedRate=4000, initialDelay=2000) <add> // public void fixedRate() { <add> // } <add> // } <ide> <ide> static class CronTestBean { <ide>
1
Javascript
Javascript
escape regexp braces to sooth jslint's temper
3a0a35288304ab5289a1815055623b18de4dc9f6
<ide><path>src/data.js <ide> (function( jQuery ) { <ide> <ide> var windowData = {}, <del> rbrace = /^(?:{.*}|\[.*\])$/; <add> rbrace = /^(?:\{.*\}|\[.*\])$/; <ide> <ide> jQuery.extend({ <ide> cache: {},
1
Text
Text
fix the 1.0.6 header
cc042c42bce0817d9b9bbf6b3b3f7a2235cf27fb
<ide><path>CHANGELOG.md <ide> _Note: This release also contains all bug fixes available in [1.0.6](#1.0.6)._ <ide> <ide> <ide> <a name="1.0.6"></a> <del># 1.1.3 universal-irreversibility (2013-04-04) <add># 1.0.6 universal-irreversibility (2013-04-04) <ide> <ide> <ide> ## Bug Fixes
1
Javascript
Javascript
handle errors before calling c++ methods
ae86fa84feca482c752bf8d8541e9e13e256a4ff
<ide><path>lib/tls.js <ide> CryptoStream.prototype._write = function write(data, encoding, cb) { <ide> written = this.pair.ssl.encIn(data, 0, data.length); <ide> } <ide> <del> var self = this; <add> // Handle and report errors <add> if (this.pair.ssl && this.pair.ssl.error) { <add> return cb(this.pair.error(true)); <add> } <ide> <ide> // Force SSL_read call to cycle some states/data inside OpenSSL <ide> this.pair.cleartext.read(0); <ide> CryptoStream.prototype._write = function write(data, encoding, cb) { <ide> this.pair.encrypted.read(0); <ide> } <ide> <del> // Handle and report errors <del> if (this.pair.ssl && this.pair.ssl.error) { <del> return cb(this.pair.error()); <del> } <del> <ide> // Get NPN and Server name when ready <ide> this.pair.maybeInitFinished(); <ide> <ide> SecurePair.prototype.destroy = function() { <ide> }; <ide> <ide> <del>SecurePair.prototype.error = function() { <add>SecurePair.prototype.error = function(returnOnly) { <ide> var err = this.ssl.error; <ide> this.ssl.error = null; <ide> <ide> SecurePair.prototype.error = function() { <ide> err.code = 'ECONNRESET'; <ide> } <ide> this.destroy(); <del> this.emit('error', err); <add> if (!returnOnly) this.emit('error', err); <ide> } else if (this._isServer && <ide> this._rejectUnauthorized && <ide> /peer did not return a certificate/.test(err.message)) { <ide> // Not really an error. <ide> this.destroy(); <ide> } else { <del> this.cleartext.emit('error', err); <add> if (!returnOnly) this.cleartext.emit('error', err); <ide> } <ide> return err; <ide> }; <ide><path>test/simple/test-tls-client-abort3.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>if (!process.versions.openssl) { <add> console.error('Skipping because node compiled without OpenSSL.'); <add> process.exit(0); <add>} <add> <add>var common = require('../common'); <add>var common = require('../common'); <add>var tls = require('tls'); <add>var fs = require('fs'); <add>var assert = require('assert'); <add> <add>var options = { <add> key: fs.readFileSync(common.fixturesDir + '/test_key.pem'), <add> cert: fs.readFileSync(common.fixturesDir + '/test_cert.pem') <add>}; <add> <add>var gotError = 0, <add> gotRequest = 0, <add> connected = 0; <add> <add>var server = tls.createServer(options, function(c) { <add> gotRequest++; <add> c.on('data', function(data) { <add> console.log(data.toString()); <add> }); <add> <add> c.on('close', function() { <add> server.close(); <add> }); <add>}).listen(common.PORT, function() { <add> var c = tls.connect(common.PORT, { rejectUnauthorized: false }, function() { <add> connected++; <add> c.pair.ssl.shutdown(); <add> c.write('123'); <add> c.destroy(); <add> }); <add> <add> c.once('error', function() { <add> gotError++; <add> }); <add>}); <add> <add>process.once('exit', function() { <add> assert.equal(gotError, 1); <add> assert.equal(gotRequest, 1); <add> assert.equal(connected, 1); <add>});
2
Python
Python
add adamw experimental optimzier
56761bcbad3b214f4b5e63651aea564c340453e3
<ide><path>official/modeling/optimization/configs/optimization_config.py <ide> class OptimizerConfig(oneof.OneOfConfig): <ide> adam_experimental: opt_cfg.AdamExperimentalConfig = ( <ide> opt_cfg.AdamExperimentalConfig()) <ide> adamw: opt_cfg.AdamWeightDecayConfig = opt_cfg.AdamWeightDecayConfig() <add> adamw_experimental: opt_cfg.AdamWeightDecayExperimentalConfig = ( <add> opt_cfg.AdamWeightDecayExperimentalConfig()) <ide> lamb: opt_cfg.LAMBConfig = opt_cfg.LAMBConfig() <ide> rmsprop: opt_cfg.RMSPropConfig = opt_cfg.RMSPropConfig() <ide> lars: opt_cfg.LARSConfig = opt_cfg.LARSConfig() <ide><path>official/modeling/optimization/configs/optimizer_config.py <ide> class AdamWeightDecayConfig(BaseOptimizerConfig): <ide> gradient_clip_norm: float = 1.0 <ide> <ide> <add>@dataclasses.dataclass <add>class AdamWeightDecayExperimentalConfig(BaseOptimizerConfig): <add> """Configuration for Adam optimizer with weight decay. <add> <add> Attributes: <add> name: name of the optimizer. <add> beta_1: decay rate for 1st order moments. <add> beta_2: decay rate for 2st order moments. <add> epsilon: epsilon value used for numerical stability in the optimizer. <add> amsgrad: boolean. Whether to apply AMSGrad variant of this algorithm from <add> the paper "On the Convergence of Adam and beyond". <add> weight_decay: float. Weight decay rate. Default to 0. <add> global_clipnorm: A positive float. Clips the gradients to this maximum <add> L2-norm. Default to 1.0. <add> jit_compile: if True, jit compile will be used. <add> """ <add> name: str = "AdamWeightDecayExperimental" <add> beta_1: float = 0.9 <add> beta_2: float = 0.999 <add> epsilon: float = 1e-07 <add> amsgrad: bool = False <add> weight_decay: float = 0.0 <add> global_clipnorm: float = 1.0 <add> jit_compile: bool = False <add> <add> <ide> @dataclasses.dataclass <ide> class LAMBConfig(BaseOptimizerConfig): <ide> """Configuration for LAMB optimizer. <ide><path>official/modeling/optimization/optimizer_factory.py <ide> 'adam': tf.keras.optimizers.Adam, <ide> # TODO(chenmoneygithub): experimental.Adam <ide> 'adamw': legacy_adamw.AdamWeightDecay, <add> 'adamw_experimental': tf.keras.optimizers.experimental.AdamW, <ide> 'lamb': tfa_optimizers.LAMB, <ide> 'rmsprop': tf.keras.optimizers.RMSprop, <ide> 'lars': lars_optimizer.LARS,
3
Go
Go
remove unused funtion hasfilesystemsupport()
bb42801cdcd0924ada0ff5ccb3a84aa9a1cbd916
<ide><path>runtime.go <ide> func (runtime *Runtime) getContainerElement(id string) *list.Element { <ide> return nil <ide> } <ide> <del>func hasFilesystemSupport(fstype string) bool { <del> content, err := ioutil.ReadFile("/proc/filesystems") <del> if err != nil { <del> log.Printf("WARNING: Unable to read /proc/filesystems, assuming fs %s is not supported.", fstype) <del> return false <del> } <del> lines := strings.Split(string(content), "\n") <del> for _, line := range lines { <del> if strings.HasPrefix(line, "nodev") { <del> line = line[5:] <del> } <del> line = strings.TrimSpace(line) <del> if line == fstype { <del> return true <del> } <del> } <del> return false <del>} <del> <ide> func (runtime *Runtime) GetDeviceSet() (DeviceSet, error) { <ide> if runtime.deviceSet == nil { <ide> return nil, fmt.Errorf("No device set available")
1
Python
Python
add chroot detection
ca223a9b8cd2406caae901f0afdc9ba961362b9f
<ide><path>setup.py <ide> <ide> from setuptools import setup <ide> <add>is_chroot = os.stat('/').st_ino != 2 <add> <ide> <ide> def get_data_files(): <ide> data_files = [ <ide> def get_data_files(): <ide> ('share/man/man1', ['man/glances.1']) <ide> ] <ide> <del> if os.name == 'posix' and os.getuid() == 0: # Unix-like + root privileges <add> if hasattr(sys, 'real_prefix'): # virtualenv <add> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <add> elif os.name == 'posix' and (os.getuid() == 0 or is_chroot): <add> # Unix-like + root privileges/chroot environment <ide> if 'bsd' in sys.platform: <ide> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <ide> elif 'linux' in sys.platform: <ide> conf_path = os.path.join('/etc', 'glances') <ide> elif 'darwin' in sys.platform: <ide> conf_path = os.path.join('/usr/local', 'etc', 'glances') <del> elif hasattr(sys, 'real_prefix'): # virtualenv <del> conf_path = os.path.join(sys.prefix, 'etc', 'glances') <ide> elif 'win32' in sys.platform: # windows <ide> conf_path = os.path.join(os.environ.get('APPDATA'), 'glances') <ide> else: # Unix-like + per-user install
1
Ruby
Ruby
bring try! into parity with try
e98f2a74eb20e2b0866b66130501f8480798dd4c
<ide><path>activesupport/lib/active_support/core_ext/object/try.rb <ide> def try(*a, &b) <ide> # does not implement the tried method. <ide> def try!(*a, &b) <ide> if a.empty? && block_given? <del> yield self <add> try(*a, &b) <ide> else <ide> public_send(*a, &b) <ide> end <ide><path>activesupport/test/core_ext/object/try_test.rb <ide> def test_nonexisting_method_with_arguments_bang <ide> assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') } <ide> end <ide> <del> def test_try_only_block_bang <del> assert_equal @string.reverse, @string.try! { |s| s.reverse } <del> end <del> <ide> def test_valid_method <ide> assert_equal 5, @string.try(:size) <ide> end <ide> def test_try_only_block <ide> assert_equal @string.reverse, @string.try { |s| s.reverse } <ide> end <ide> <add> def test_try_only_block_bang <add> assert_equal @string.reverse, @string.try! { |s| s.reverse } <add> end <add> <ide> def test_try_only_block_nil <ide> ran = false <ide> nil.try { ran = true } <ide> def test_try_with_instance_eval_block <ide> assert_equal @string.reverse, @string.try { reverse } <ide> end <ide> <add> def test_try_with_instance_eval_block_bang <add> assert_equal @string.reverse, @string.try! { reverse } <add> end <add> <ide> def test_try_with_private_method_bang <ide> klass = Class.new do <ide> private
2
Text
Text
fix typo in vm.runinnewcontext() description
bb3b4d7d49d84e024f702b4840b1d3b89eac88f5
<ide><path>doc/api/vm.md <ide> added: v0.3.1 <ide> before terminating execution. If execution is terminated, an [`Error`][] <ide> will be thrown. <ide> <del>The `vm.runInContext()` first contextifies the given `sandbox` object (or <add>The `vm.runInNewContext()` first contextifies the given `sandbox` object (or <ide> creates a new `sandbox` if passed as `undefined`), compiles the `code`, runs it <ide> within the context of the created context, then returns the result. Running code <ide> does not have access to the local scope.
1
PHP
PHP
update queue service provider
eb3b10aae62d00eeed18cb069ab8dcd51a8de6bc
<ide><path>src/Illuminate/Queue/QueueServiceProvider.php <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Queue\Console\WorkCommand; <ide> use Illuminate\Queue\Console\ListenCommand; <add>use Illuminate\Queue\Connectors\SqsConnector; <ide> use Illuminate\Queue\Connectors\SyncConnector; <ide> use Illuminate\Queue\Connectors\BeanstalkdConnector; <ide> <ide> protected function registerListenCommand() <ide> */ <ide> public function registerConnectors($manager) <ide> { <del> foreach (array('Sync', 'Beanstalkd') as $connector) <add> foreach (array('Sync', 'Beanstalkd', 'Sqs') as $connector) <ide> { <ide> $this->{"register{$connector}Connector"}($manager); <ide> } <ide> protected function registerBeanstalkdConnector($manager) <ide> }); <ide> } <ide> <add> /** <add> * Register the Amazon SQS queue connector. <add> * <add> * @param Illuminate\Queue\QueueManager $manager <add> * @return void <add> */ <add> protected function registerSqsConnector($manager) <add> { <add> $manager->addConnector('sqs', function() <add> { <add> return new SqsConnector; <add> }); <add> } <add> <ide> /** <ide> * Get the services provided by the provider. <ide> *
1
Javascript
Javascript
fix typing issue in contextmodule
383b3354dd564197b39ad391af7da908e5cb6213
<ide><path>lib/ContextModule.js <ide> class ContextModule extends Module { <ide> <ide> // Info from Factory <ide> this.resolveDependencies = resolveDependencies; <del> /** @type {ContextModuleOptions} */ <add> /** @type {Omit<ContextModuleOptions, "resolveOptions">} */ <ide> this.options = { <ide> resource: resource, <ide> resourceQuery: resourceQuery,
1
Python
Python
remove deprecated elasticsearch configs
5d5c11918725772a9d13712fe5339e315e60d8fc
<ide><path>airflow/configuration.py <ide> class AirflowConfigParser(ConfigParser): # pylint: disable=too-many-ancestors <ide> # When reading new option, the old option will be checked to see if it exists. If it does a <ide> # DeprecationWarning will be issued and the old option will be used instead <ide> deprecated_options = { <del> ('elasticsearch', 'host'): ('elasticsearch', 'elasticsearch_host'), <del> ('elasticsearch', 'log_id_template'): ('elasticsearch', 'elasticsearch_log_id_template'), <del> ('elasticsearch', 'end_of_log_mark'): ('elasticsearch', 'elasticsearch_end_of_log_mark'), <del> ('elasticsearch', 'frontend'): ('elasticsearch', 'elasticsearch_frontend'), <del> ('elasticsearch', 'write_stdout'): ('elasticsearch', 'elasticsearch_write_stdout'), <del> ('elasticsearch', 'json_format'): ('elasticsearch', 'elasticsearch_json_format'), <del> ('elasticsearch', 'json_fields'): ('elasticsearch', 'elasticsearch_json_fields'), <ide> ('logging', 'base_log_folder'): ('core', 'base_log_folder'), <ide> ('logging', 'remote_logging'): ('core', 'remote_logging'), <ide> ('logging', 'remote_log_conn_id'): ('core', 'remote_log_conn_id'),
1
Python
Python
fix documentation in keras.datasets.imdb
b3d781553b8015d2cae023d584eeba2f314abaeb
<ide><path>keras/datasets/imdb.py <ide> def load_data( <ide> common words, but eliminate the top 20 most common words". <ide> <ide> As a convention, "0" does not stand for a specific word, but instead is used <del> to encode any unknown word. <add> to encode the pad token. <ide> <ide> Args: <ide> path: where to cache the data (relative to `~/.keras/dataset`). <ide> def get_word_index(path="imdb_word_index.json"): <ide> Example: <ide> <ide> ```python <add> # Use the default parameters to keras.datasets.imdb.load_data <add> start_char = 1 <add> oov_char = 2 <add> index_from = 3 <ide> # Retrieve the training sequences. <del> (x_train, _), _ = keras.datasets.imdb.load_data() <add> (x_train, _), _ = keras.datasets.imdb.load_data( <add> start_char=start_char, oov_char=oov_char, index_from=index_from <add> ) <ide> # Retrieve the word index file mapping words to indices <ide> word_index = keras.datasets.imdb.get_word_index() <ide> # Reverse the word index to obtain a dict mapping indices to words <del> inverted_word_index = dict((i, word) for (word, i) in word_index.items()) <add> # And add `index_from` to indices to sync with `x_train` <add> inverted_word_index = dict( <add> (i + index_from, word) for (word, i) in word_index.items() <add> ) <add> # Update `inverted_word_index` to include `start_char` and `oov_char` <add> inverted_word_index[start_char] = "[START]" <add> inverted_word_index[oov_char] = "[OOV]" <ide> # Decode the first sequence in the dataset <ide> decoded_sequence = " ".join(inverted_word_index[i] for i in x_train[0]) <ide> ```
1
Python
Python
specify config filename
1a779ad7ecb9e5215b6bd1cfa0153469d37e4274
<ide><path>src/transformers/hf_argparser.py <ide> def _add_dataclass_arguments(self, dtype: DataClassType): <ide> self.add_argument(field_name, **kwargs) <ide> <ide> def parse_args_into_dataclasses( <del> self, args=None, return_remaining_strings=False, look_for_args_file=True <add> self, args=None, return_remaining_strings=False, look_for_args_file=True, args_filename=None <ide> ) -> Tuple[DataClass, ...]: <ide> """ <ide> Parse command-line args into instances of the specified dataclass types. <ide> def parse_args_into_dataclasses( <ide> If true, will look for a ".args" file with the same base name <ide> as the entry point script for this process, and will append its <ide> potential content to the command line args. <add> args_filename: <add> If not None, will uses this file instead of the ".args" file <add> specified in the previous argument. <ide> <ide> Returns: <ide> Tuple consisting of: <ide> def parse_args_into_dataclasses( <ide> - The potential list of remaining argument strings. <ide> (same as argparse.ArgumentParser.parse_known_args) <ide> """ <del> if look_for_args_file and len(sys.argv): <del> args_file = Path(sys.argv[0]).with_suffix(".args") <add> if args_filename or (look_for_args_file and len(sys.argv)): <add> if args_filename: <add> args_file = Path(args_filename) <add> else: <add> args_file = Path(sys.argv[0]).with_suffix(".args") <add> <ide> if args_file.exists(): <ide> fargs = args_file.read_text().split() <ide> args = fargs + args if args is not None else fargs + sys.argv[1:]
1
PHP
PHP
refactor the lang class
7282954e27fa8b427d8b4f6485e8ffb2463693bf
<ide><path>system/lang.php <ide> public static function line($key, $replacements = array()) <ide> */ <ide> public function get($language = null, $default = null) <ide> { <del> if (is_null($language)) $language = Config::get('application.language'); <add> if (is_null($language)) <add> { <add> $language = Config::get('application.language'); <add> } <ide> <ide> list($module, $file, $line) = $this->parse($this->key, $language); <ide> <ide> private function parse($key, $language) <ide> { <ide> $module = (strpos($key, '::') !== false) ? substr($key, 0, strpos($key, ':')) : 'application'; <ide> <del> if ($module != 'application') $key = substr($key, strpos($key, ':') + 2); <add> if ($module != 'application') <add> { <add> $key = substr($key, strpos($key, ':') + 2); <add> } <ide> <del> if (count($segments = explode('.', $key)) > 1) return array($module, $segments[0], $segments[1]); <add> if (count($segments = explode('.', $key)) > 1) <add> { <add> return array($module, $segments[0], $segments[1]); <add> } <ide> <ide> throw new \Exception("Invalid language line [$key]. A specific line must be specified."); <ide> }
1
Text
Text
add missing closing parenthesis in docs
721dc7bccd0bcdd6f8d6600b0dc30192822a0f3d
<ide><path>docs/advanced-features/static-html-export.md <ide> Update your build script in `package.json` to use `next export`: <ide> <ide> Running `npm run build` will generate an `out` directory. <ide> <del>`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. <add>`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md)). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. <ide> <ide> For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated. <ide>
1
PHP
PHP
fix problem with fallback
5fda5a335bce1527e6796a91bb36ccb48d6807a8
<ide><path>src/Illuminate/Routing/RouteRegistrar.php <ide> public function __call($method, $parameters) <ide> return $this->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); <ide> } <ide> <del> return $this->attribute($method, $parameters[0] ?? true); <add> return $this->attribute($method, array_key_exists(0, $parameters) ? $parameters[0] : true); <ide> } <ide> <ide> throw new BadMethodCallException(sprintf( <ide><path>src/Illuminate/Routing/Router.php <ide> public function __call($method, $parameters) <ide> return (new RouteRegistrar($this))->attribute($method, is_array($parameters[0]) ? $parameters[0] : $parameters); <ide> } <ide> <del> return (new RouteRegistrar($this))->attribute($method, $parameters[0] ?? true); <add> return (new RouteRegistrar($this))->attribute($method, array_key_exists(0, $parameters) ? $parameters[0] : true); <ide> } <ide> }
2
Javascript
Javascript
remove horizontal scrollbar from donation page
2d780f257c15ecc254ef1d1d394d61a2942504ca
<ide><path>client/src/components/Donation/components/DonateOther.js <ide> class DonateOther extends Component { <ide> return ( <ide> <form <ide> action='https://www.paypal.com/cgi-bin/webscr' <add> key={item.defaultValueHash} <ide> method='post' <ide> onSubmit={() => <ide> ReactGA.event({ <ide> class DonateOther extends Component { <ide> <Spacer /> <ide> <Grid> <ide> <Row> <del> <Col md={6} mdOffset={3} sm={10} smOffset={1} xs={12}> <add> <Col lg={8} lgOffset={2} sm={10} smOffset={1} xs={12}> <ide> <h2 className='text-center'> <ide> Other ways you can support our nonprofit <ide> </h2> <ide><path>client/src/pages/donate.js <ide> import React, { Component, Fragment } from 'react'; <ide> import Helmet from 'react-helmet'; <ide> import { StripeProvider, Elements } from 'react-stripe-elements'; <del>import { Row, Col, Button } from '@freecodecamp/react-bootstrap'; <add>import { Grid, Row, Col, Button } from '@freecodecamp/react-bootstrap'; <ide> <ide> import { stripePublicKey } from '../../config/env.json'; <ide> <ide> class DonatePage extends Component { <ide> <Fragment> <ide> <Helmet title='Support our nonprofit | freeCodeCamp.org' /> <ide> <Spacer /> <del> <Row> <del> <Col sm={8} smOffset={2} xs={12}> <del> <h2 className='text-center'>Become a Supporter</h2> <del> <DonateText /> <del> </Col> <del> <Col sm={6} smOffset={3} xs={12}> <del> <hr /> <del> <StripeProvider stripe={stripe}> <del> <Elements> <del> <DonateForm /> <del> </Elements> <del> </StripeProvider> <del> <div className='text-center'> <del> <PoweredByStripe /> <add> <Grid> <add> <Row> <add> <Col sm={10} smOffset={1} xs={12}> <add> <h2 className='text-center'>Become a Supporter</h2> <add> <DonateText /> <add> </Col> <add> <Col md={8} mdOffset={2} sm={10} smOffset={1} xs={12}> <add> <hr /> <add> <StripeProvider stripe={stripe}> <add> <Elements> <add> <DonateForm /> <add> </Elements> <add> </StripeProvider> <add> <div className='text-center'> <add> <PoweredByStripe /> <add> <Spacer /> <add> <Button onClick={this.toggleOtherOptions}> <add> {`${ <add> showOtherOptions ? 'Hide' : 'Show' <add> } other ways to donate.`} <add> </Button> <add> </div> <ide> <Spacer /> <del> <Button onClick={this.toggleOtherOptions}> <del> {`${showOtherOptions ? 'Hide' : 'Show'} other ways to donate.`} <del> </Button> <del> </div> <del> <Spacer /> <del> </Col> <del> </Row> <add> </Col> <add> </Row> <add> </Grid> <ide> {showOtherOptions && <DonateOther />} <ide> </Fragment> <ide> );
2
Ruby
Ruby
remove warning of undefined instance variable
bad3d0f6a37ca675b8005da4c87cf15a5f54175b
<ide><path>activestorage/lib/active_storage/previewer/mupdf_previewer.rb <ide> def mutool_path <ide> end <ide> <ide> def mutool_exists? <del> return @mutool_exists unless @mutool_exists.nil? <add> return @mutool_exists if defined?(@mutool_exists) && !@mutool_exists.nil? <ide> <ide> system mutool_path, out: File::NULL, err: File::NULL <ide>
1
Ruby
Ruby
fix mocks dir
9fdd453257c3a257ad614dfe640b516c9495c503
<ide><path>railties/lib/initializer.rb <ide> def default_frameworks <ide> end <ide> <ide> def default_load_paths <del> paths = ["#{environment}/test/mocks/#{environment}"] <add> paths = ["#{RAILS_ROOT}/test/mocks/#{environment}"] <ide> <ide> # Then model subdirectories. <ide> # TODO: Don't include .rb models as load paths
1
Python
Python
improve error messages for base_layer
894501ac460723d1d7dcc1c0168876537f0be452
<ide><path>keras/engine/base_layer.py <ide> import copy <ide> import functools <ide> import itertools <add>import textwrap <ide> import threading <ide> import warnings <ide> import weakref <ide> def add_weight(self, <ide> # When `getter` is specified, it's possibly fine for `initializer` to be <ide> # None since it's up to the custom `getter` to raise error in case it <ide> # indeed needs `initializer`. <del> raise ValueError('An initializer for variable %s of type %s is required' <del> ' for layer %s' % (name, dtype.base_dtype, self.name)) <add> raise ValueError(f'An initializer for variable {name} of type ' <add> f'{dtype.base_dtype} is required for layer ' <add> f'{self.name}. Received: {initializer}.') <ide> <ide> getter = kwargs.pop('getter', base_layer_utils.make_variable) <ide> if (autocast and <ide> def get_config(self): <ide> # Check that either the only argument in the `__init__` is `self`, <ide> # or that `get_config` has been overridden: <ide> if len(extra_args) > 1 and hasattr(self.get_config, '_is_default'): <del> raise NotImplementedError(f'Layer {self.__class__.__name__} ' <del> 'has arguments in `__init__)_` and ' <del> 'therefore must override `get_config()`.') <add> raise NotImplementedError(textwrap.dedent(f""" <add> Layer {self.__class__.__name__} has arguments {extra_args} <add> in `__init__` and therefore must override `get_config()`. <add> <add> Example: <add> <add> class CustomLayer(keras.layers.Layer): <add> def __init__(self, arg1, arg2): <add> super().__init__() <add> self.arg1 = arg1 <add> self.arg2 = arg2 <add> <add> def get_config(self): <add> config = super().get_config() <add> config.update({{ <add> "arg1": self.arg1, <add> "arg2": self.arg2, <add> }}) <add> return config""")) <add> <ide> return config <ide> <ide> @classmethod <ide> def compute_output_signature(self, input_signature): <ide> """ <ide> def check_type_return_shape(s): <ide> if not isinstance(s, tf.TensorSpec): <del> raise TypeError('Only TensorSpec signature types are supported, ' <del> 'but saw signature entry: {}.'.format(s)) <add> raise TypeError('Only TensorSpec signature types are supported. ' <add> f'Received: {s}.') <ide> return s.shape <ide> input_shape = tf.nest.map_structure(check_type_return_shape, input_signature) <ide> output_shape = self.compute_output_shape(input_shape) <ide> def call(self, inputs): <ide> kwargs_keys = list(kwargs.keys()) <ide> if (len(kwargs_keys) > 1 or <ide> (len(kwargs_keys) == 1 and kwargs_keys[0] != 'aggregation')): <del> raise TypeError('Unknown keyword arguments: ', str(kwargs.keys())) <add> raise TypeError(f'Unknown keyword arguments: {kwargs.keys()}. ' <add> 'Expected `aggregation`.') <ide> <ide> from_metric_obj = hasattr(value, '_metric_obj') <ide> is_symbolic = isinstance(value, keras_tensor.KerasTensor) <ide> def set_weights(self, weights): <ide> ref_shape = param.shape <ide> if not ref_shape.is_compatible_with(weight_shape): <ide> raise ValueError( <del> 'Layer weight shape %s not compatible with provided weight ' <del> 'shape %s' % (ref_shape, weight_shape)) <add> f'Layer {self.name} weight shape {ref_shape} ' <add> 'is not compatible with provided weight ' <add> f'shape {weight_shape}.') <ide> weight_value_tuples.append((param, weight)) <ide> weight_index += 1 <ide> <ide> def input_shape(self): <ide> RuntimeError: if called in Eager mode. <ide> """ <ide> if not self._inbound_nodes: <del> raise AttributeError('The layer has never been called ' <add> raise AttributeError(f'The layer "{self.name}" has never been called ' <ide> 'and thus has no defined input shape.') <ide> all_input_shapes = set( <ide> [str(node.input_shapes) for node in self._inbound_nodes]) <ide> def count_params(self): <ide> with tf_utils.maybe_init_scope(self): <ide> self._maybe_build(self.inputs) <ide> else: <del> raise ValueError('You tried to call `count_params` on ' + self.name + <add> raise ValueError('You tried to call `count_params` ' <add> f'on layer {self.name}' <ide> ', but the layer isn\'t built. ' <del> 'You can build it manually via: `' + self.name + <del> '.build(batch_input_shape)`.') <add> 'You can build it manually via: ' <add> f'`{self.name}.build(batch_input_shape)`.') <ide> return layer_utils.count_params(self.weights) <ide> <ide> @property <ide> def output_shape(self): <ide> RuntimeError: if called in Eager mode. <ide> """ <ide> if not self._inbound_nodes: <del> raise AttributeError('The layer has never been called ' <add> raise AttributeError(f'The layer "{self.name}" has never been called ' <ide> 'and thus has no defined output shape.') <ide> all_output_shapes = set( <ide> [str(node.output_shapes) for node in self._inbound_nodes]) <ide> def _get_node_attribute_at_index(self, node_index, attr, attr_name): <ide> ValueError: If the index provided does not match any node. <ide> """ <ide> if not self._inbound_nodes: <del> raise RuntimeError('The layer has never been called ' <del> 'and thus has no defined ' + attr_name + '.') <add> raise RuntimeError(f'The layer {self.name} has never been called ' <add> 'and thus has no defined {attr_name}.') <ide> if not len(self._inbound_nodes) > node_index: <del> raise ValueError('Asked to get ' + attr_name + ' at node ' + <del> str(node_index) + ', but the layer has only ' + <del> str(len(self._inbound_nodes)) + ' inbound nodes.') <add> raise ValueError(f'Asked to get {attr_name} at node ' <add> f'{node_index}, but the layer has only ' <add> f'{len(self._inbound_nodes)} inbound nodes.') <ide> values = getattr(self._inbound_nodes[node_index], attr) <ide> if isinstance(values, list) and len(values) == 1: <ide> return values[0]
1
Javascript
Javascript
add mock for backhandler
ea7c5ab04b0e67083e2dda45f64decea1dc378eb
<ide><path>Libraries/Utilities/__mocks__/BackHandler.js <add>/** <add> * Copyright (c) 2013-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> */ <add> <add>'use strict'; <add> <add>const _backPressSubscriptions = new Set(); <add> <add>const BackHandler = { <add> exitApp: jest.fn(), <add> <add> addEventListener: function ( <add> eventName: BackPressEventName, <add> handler: Function <add> ): {remove: () => void} { <add> _backPressSubscriptions.add(handler); <add> return { <add> remove: () => BackHandler.removeEventListener(eventName, handler), <add> }; <add> }, <add> <add> removeEventListener: function( <add> eventName: BackPressEventName, <add> handler: Function <add> ): void { <add> _backPressSubscriptions.delete(handler); <add> }, <add> <add> <add> mockPressBack: function() { <add> let invokeDefault = true; <add> const subscriptions = [..._backPressSubscriptions].reverse(); <add> for (let i = 0; i < subscriptions.length; ++i) { <add> if (subscriptions[i]()) { <add> invokeDefault = false; <add> break; <add> } <add> } <add> <add> if (invokeDefault) { <add> BackHandler.exitApp(); <add> } <add> }, <add>}; <add> <add>module.exports = BackHandler;
1
Python
Python
improve example dags for cloud memorystore
8ba8a7295a31f6b44894bfcaea36fa93b8d8c0d0
<ide><path>airflow/providers/google/cloud/example_dags/example_cloud_memorystore.py <ide> <ide> # [START howto_operator_get_instance] <ide> get_instance = CloudMemorystoreGetInstanceOperator( <del> task_id="get-instance", location="europe-north1", instance=INSTANCE_NAME, project_id=GCP_PROJECT_ID <add> task_id="get-instance", <add> location="europe-north1", <add> instance=INSTANCE_NAME, <add> project_id=GCP_PROJECT_ID, <add> do_xcom_push=True, <ide> ) <ide> # [END howto_operator_get_instance] <ide> <ide> create_instance_2 >> import_instance <ide> create_instance >> list_instances >> list_instances_result <ide> list_instances >> delete_instance <add> export_instance >> update_instance <ide> update_instance >> delete_instance <ide> get_instance >> set_acl_permission >> export_instance <ide> export_instance >> import_instance
1
PHP
PHP
remove event cache command
7b06179ebab9ab506ea6fe41a18c5214c0869e32
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function getRouteCachePath() <ide> return $this['path.storage'].'/meta/routes.php'; <ide> } <ide> <del> /** <del> * Determine if the application events are cached. <del> * <del> * @return bool <del> */ <del> public function eventsAreCached() <del> { <del> return $this['files']->exists($this->getEventCachePath()); <del> } <del> <del> /** <del> * Get the path to the events cache file. <del> * <del> * @return string <del> */ <del> public function getEventCachePath() <del> { <del> return $this['path.storage'].'/meta/events.php'; <del> } <del> <ide> /** <ide> * Handle the given request and get the response. <ide> * <ide><path>src/Illuminate/Foundation/Console/EventCacheCommand.php <del><?php namespace Illuminate\Foundation\Console; <del> <del>use Illuminate\Console\Command; <del>use Illuminate\Foundation\EventCache; <del>use Illuminate\Filesystem\Filesystem; <del>use Illuminate\Filesystem\ClassFinder; <del> <del>class EventCacheCommand extends Command { <del> <del> /** <del> * The console command name. <del> * <del> * @var string <del> */ <del> protected $name = 'event:cache'; <del> <del> /** <del> * The console command description. <del> * <del> * @var string <del> */ <del> protected $description = 'Create a cache file of all @hears annotation events'; <del> <del> /** <del> * The filesystem instance. <del> * <del> * @var \Illuminate\Filesystem\Filesystem <del> */ <del> protected $files; <del> <del> /** <del> * Create a new event cache command instance. <del> * <del> * @param \Illuminate\Filesystem\Filesystem $files <del> * @return void <del> */ <del> public function __construct(Filesystem $files) <del> { <del> parent::__construct(); <del> <del> $this->files = $files; <del> } <del> <del> /** <del> * Execute the console command. <del> * <del> * @return void <del> */ <del> public function fire() <del> { <del> $cache = (new EventCache(new ClassFinder))->get( <del> $this->laravel['config']->get('app.events.scan', []) <del> ); <del> <del> $this->files->put( <del> $this->laravel['path.storage'].'/meta/events.php', $cache <del> ); <del> <del> $this->info('Events cached successfully!'); <del> } <del> <del>} <ide><path>src/Illuminate/Foundation/EventCache.php <del><?php namespace Illuminate\Foundation; <del> <del>use ReflectionClass; <del>use ReflectionMethod; <del>use Illuminate\Filesystem\ClassFinder; <del> <del>class EventCache { <del> <del> /** <del> * The class finder instance. <del> * <del> * @var \Illuminate\Filesystem\ClassFinder $finder <del> */ <del> protected $finder; <del> <del> /** <del> * The event registration stub. <del> * <del> * @var string <del> */ <del> protected $stub = '$events->listen(\'{{event}}\', \'{{handler}}\');'; <del> <del> /** <del> * Create a new event cache instance. <del> * <del> * @param \Illuminate\Filesystem\ClassFinder $finder <del> * @return void <del> */ <del> public function __construct(ClassFinder $finder) <del> { <del> $this->finder = $finder; <del> } <del> <del> /** <del> * Get the contents that should be written to a cache file. <del> * <del> * @param array $paths <del> * @return string <del> */ <del> public function get(array $paths) <del> { <del> $cache = '<?php $events = app(\'events\');'.PHP_EOL.PHP_EOL; <del> <del> foreach ($paths as $path) <del> { <del> $cache .= $this->getCacheForPath($path); <del> } <del> <del> return $cache; <del> } <del> <del> /** <del> * Get the cache contents for a given path. <del> * <del> * @param string $path <del> * @return string <del> */ <del> protected function getCacheForPath($path) <del> { <del> $cache = ''; <del> <del> foreach ($this->finder->findClasses($path) as $class) <del> { <del> $cache .= $this->getCacheForClass(new ReflectionClass($class)); <del> } <del> <del> return $cache; <del> } <del> <del> /** <del> * Get the cache for the given class reflection. <del> * <del> * @param \ReflectionClass $reflection <del> * @return string|null <del> */ <del> protected function getCacheForClass(ReflectionClass $reflection) <del> { <del> if ($reflection->isAbstract() && ! $reflection->isInterface()) <del> { <del> continue; <del> } <del> <del> foreach ($reflection->getMethods() as $method) <del> { <del> return $this->getCacheForMethod($method); <del> } <del> } <del> <del> /** <del> * Get the cache for the given method reflection. <del> * <del> * @param \ReflectionMethod $method <del> * @return string|null <del> */ <del> protected function getCacheForMethod(ReflectionMethod $method) <del> { <del> preg_match_all('/@hears(.*)/', $method->getDocComment(), $matches); <del> <del> $events = []; <del> <del> if (isset($matches[1]) && count($matches[1]) > 0) <del> { <del> $events = array_map('trim', $matches[1]); <del> } <del> <del> $cache = ''; <del> <del> foreach ($events as $event) <del> { <del> $cache .= $this->formatEventStub($method, $event); <del> } <del> <del> return $cache; <del> } <del> <del> /** <del> * Format the event listener stub for the given method and event. <del> * <del> * @param \ReflectionMethod $method <del> * @param string $event <del> * @return string <del> */ <del> protected function formatEventStub(ReflectionMethod $method, $event) <del> { <del> $event = str_replace('{{event}}', $event, $this->stub); <del> <del> return str_replace('{{handler}}', $method->class.'@'.$method->name, $event).PHP_EOL; <del> } <del> <del>} <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Foundation\Console\ChangesCommand; <ide> use Illuminate\Foundation\Console\OptimizeCommand; <ide> use Illuminate\Foundation\Console\RouteListCommand; <del>use Illuminate\Foundation\Console\EventCacheCommand; <ide> use Illuminate\Foundation\Console\RouteCacheCommand; <ide> use Illuminate\Foundation\Console\RouteClearCommand; <ide> use Illuminate\Foundation\Console\ConsoleMakeCommand; <ide> class ArtisanServiceProvider extends ServiceProvider { <ide> 'ConsoleMake', <ide> 'Down', <ide> 'Environment', <del> 'EventCache', <ide> 'KeyGenerate', <ide> 'Optimize', <ide> 'ProviderMake', <ide> protected function registerEnvironmentCommand() <ide> }); <ide> } <ide> <del> /** <del> * Register the command. <del> * <del> * @return void <del> */ <del> protected function registerEventCacheCommand() <del> { <del> $this->app->bindShared('command.event.cache', function($app) <del> { <del> return new EventCacheCommand($app['files']); <del> }); <del> } <del> <ide> /** <ide> * Register the command. <ide> *
4
Python
Python
improve math typesetting
abf238e2f7d6cbe5caaf23987ddcd8b35632b409
<ide><path>numpy/core/numeric.py <ide> def correlate(a, v, mode='valid'): <ide> Cross-correlation of two 1-dimensional sequences. <ide> <ide> This function computes the correlation as generally defined in signal <del> processing texts:: <add> processing texts: <ide> <del> .. math:: c_k = \sum_n a_{n+k} * \overline{v_n} <add> .. math:: c_k = \sum_n a_{n+k} \cdot \overline{v_n} <ide> <ide> with a and v sequences being zero-padded where necessary and <ide> :math:`\overline x` denoting complex conjugation. <ide> def correlate(a, v, mode='valid'): <ide> Notes <ide> ----- <ide> The definition of correlation above is not unique and sometimes correlation <del> may be defined differently. Another common definition is:: <add> may be defined differently. Another common definition is: <ide> <del> .. math:: c'_k = \sum_n a_{n} * \overline{v_{n+k} <add> .. math:: c'_k = \sum_n a_{n} \cdot \overline{v_{n+k}} <ide> <ide> which is related to :math:`c_k` by :math:`c'_k = c_{-k}`. <ide> <ide> def convolve(a, v, mode='full'): <ide> ----- <ide> The discrete convolution operation is defined as <ide> <del> .. math:: (a * v)[n] = \\sum_{m = -\\infty}^{\\infty} a[m] v[n - m] <add> .. math:: (a * v)_n = \\sum_{m = -\\infty}^{\\infty} a_m v_{n - m} <ide> <ide> It can be shown that a convolution :math:`x(t) * y(t)` in time/space <ide> is equivalent to the multiplication :math:`X(f) Y(f)` in the Fourier
1
Python
Python
fix tok2vec arch after refactor
165e37808229bc4d67889589cdab3b2e5ebe5bfd
<ide><path>spacy/ml/common.py <ide> def FeedForward(config): <ide> def LayerNormalizedMaxout(config): <ide> width = config["width"] <ide> pieces = config["pieces"] <del> layer = chain(Maxout(width, pieces=pieces), LayerNorm(nO=width)) <add> layer = LayerNorm(Maxout(width, pieces=pieces)) <ide> layer.nO = width <ide> return layer <ide><path>spacy/ml/tok2vec.py <ide> <ide> @register_architecture("spacy.Tok2Vec.v1") <ide> def Tok2Vec(config): <add> print(config) <ide> doc2feats = make_layer(config["@doc2feats"]) <ide> embed = make_layer(config["@embed"]) <ide> encode = make_layer(config["@encode"]) <del> tok2vec = chain(doc2feats, with_flatten(chain(embed, encode))) <add> depth = config["@encode"]["config"]["depth"] <add> tok2vec = chain(doc2feats, with_flatten(chain(embed, encode), pad=depth)) <ide> tok2vec.cfg = config <ide> tok2vec.nO = encode.nO <ide> tok2vec.embed = embed <ide> def MaxoutWindowEncoder(config): <ide> <ide> cnn = chain( <ide> ExtractWindow(nW=nW), <del> Maxout(nO, nO * ((nW * 2) + 1), pieces=nP), <del> LayerNorm(nO=nO), <add> LayerNorm(Maxout(nO, nO * ((nW * 2) + 1), pieces=nP)), <ide> ) <ide> model = clone(Residual(cnn), depth) <ide> model.nO = nO
2
Text
Text
add currency to inthewild.md
246c8f2952b451e0dac7f4c3489f2004c6c369bd
<ide><path>INTHEWILD.md <ide> Currently **officially** using Airflow: <ide> 1. [Creditas](https://www.creditas.com.br) [[@dcassiano](https://github.com/dcassiano)] <ide> 1. [CreditCards.com](https://www.creditcards.com/)[[@vmAggies](https://github.com/vmAggies) & [@jay-wallaby](https://github.com/jay-wallaby)] <ide> 1. [Cryptalizer.com](https://www.cryptalizer.com/) <add>1. [Currency](https://www.gocurrency.com/) [[@FCLI](https://github.com/FCLI) & [@alexbegg](https://github.com/alexbegg)] <ide> 1. [Custom Ink](https://www.customink.com/) [[@david-dalisay](https://github.com/david-dalisay), [@dmartin11](https://github.com/dmartin11) & [@mpeteuil](https://github.com/mpeteuil)] <ide> 1. [Cyscale](https://cyscale.com) [[@ocical](https://github.com/ocical)] <ide> 1. [Dailymotion](http://www.dailymotion.com/fr) [[@germaintanguy](https://github.com/germaintanguy) & [@hc](https://github.com/hc)]
1
Javascript
Javascript
use const where applicable in ignoreplugin
30a4e3614fc658533d42c56dbba0c36190e816d8
<ide><path>lib/IgnorePlugin.js <ide> class IgnorePlugin { <ide> } <ide> <ide> apply(compiler) { <del> let resourceRegExp = this.resourceRegExp; <del> let contextRegExp = this.contextRegExp; <add> const resourceRegExp = this.resourceRegExp; <add> const contextRegExp = this.contextRegExp; <ide> compiler.plugin("normal-module-factory", (nmf) => { <ide> nmf.plugin("before-resolve", (result, callback) => { <ide> if(!result) return callback();
1
PHP
PHP
fix a few bugs
418dfb0d387a6922285a39bedbd96c8870111074
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php <ide> protected function compileOpeningTags(string $value) <ide> (?<attributes> <ide> (?: <ide> \s+ <del> [\w\-:\.]+ <add> [^\s\=]+ <ide> ( <ide> = <ide> (?: <ide> protected function compileSelfClosingTags(string $value) <ide> (?<attributes> <ide> (?: <ide> \s+ <del> [\w\-:\.]+ <add> [^\s\=]+ <ide> ( <ide> = <ide> (?: <ide> protected function getAttributesFromAttributeString(string $attributeString) <ide> $attributeString = $this->parseBindAttributes($attributeString); <ide> <ide> $pattern = '/ <del> (?<attribute>[\w\.:-]+) <add> (?<attribute>[^\s\=]+) <ide> ( <ide> = <ide> (?<value> <ide> protected function getAttributesFromAttributeString(string $attributeString) <ide> } <ide> <ide> return collect($matches)->mapWithKeys(function ($match) { <del> $attribute = Str::camel($match['attribute']); <add> $attribute = $match['attribute']; <ide> $value = $match['value'] ?? null; <ide> <ide> if (is_null($value)) { <ide> protected function parseBindAttributes(string $attributeString) <ide> $pattern = "/ <ide> (?:^|\s+) # start of the string or whitespace between attributes <ide> : # attribute needs to start with a semicolon <del> ([\w-]+) # match the actual attribute name <add> ([^\s\=]+) # match the actual attribute name <ide> = # only match attributes that have a value <ide> /xm"; <ide>
1
Text
Text
add bfs for non-weighted graphs
b754750ae3a6ff88e76a654b55dc52e0f21a9a1f
<ide><path>guide/english/computer-science/shortest-path-on-a-graph/index.md <ide> title: Shortest Path on a Graph <ide> ## Shortest Path on a Graph <ide> <ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <del>Finding the shortest path between two points on a graph is a common problem in data structures especially when dealing with optimization. A graph is a series of nodes connected by edges. Graphs can be weighted (edges carry values) and directional (edges have direction). <del> <add>Finding the shortest path between two points on a graph is a common problem in data structures especially when dealing with optimization. A graph is a series of nodes connected by edges. <add> <add> <add>## Breadth First Search <add> <add>For unweighted graphs, the *Breadth First Search* algorithm is useful. Below is a Python 3 implementation. <add> <add>```python <add>from collections import deque <add> <add>def BFS(graph, startNode, endNode): <add># Assume graph is written as an adjacency list. <add> queue = deque() <add> queue.append([startNode]) <add> visited = set() <add> visited.add(startNode) <add> <add> while queue: <add> currentPath = queue.popleft() <add> for node in graph[currentPath[-1]]: <add> if node == endNode: <add> newPath = currentPath.append(node) <add> return newPath <add> elif node not in visited: <add> visited.add(node) <add> newPath = currentPath.append(node) <add> queue.append(newPath) <add> <add> return -1 <add>``` <add> <add>However, graphs can be weighted (edges carry values) and directional (edges have direction). <ide> <ide> Some applications of this are flight path optimization or <a href='https://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon' target='_blank' rel='nofollow'>6 degrees of Kevin Bacon</a> <ide>
1
Text
Text
update the security policy
bf7924b2160d272bfdac961e06d8aff13baca2c5
<ide><path>docs/security.md <ide> This document outlines our security policy for the codebases, platforms that we <ide> ## Reporting a Vulnerability <ide> <ide> > [!NOTE] <del>> If you think you have found a vulnerability, **please report responsibly**. Do not create GitHub issues for security issues. Instead follow this guide. <add>> If you think you have found a vulnerability, **please report it responsibly**. Do not create GitHub issues for security issues. Instead, follow this guide. <ide> <ide> ### Guidelines <ide> <del>We appreciate a responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. In the interest of saving everyone time, we encourage you to report vulnerabilities with these in mind: <add>We appreciate responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. In the interest of saving everyone time, we encourage you to report vulnerabilities with these in mind: <ide> <del>1. Ensure that you are using the **latest**, **stable** and **updated** versions of the Operating System and Web Browser(s) available to you on your machine. <del>2. We consider using tools & online utilities to report issues with SPF & DKIM configs, or SSL Server tests, etc. in the category of ["beg bounties"](https://www.troyhunt.com/beg-bounties/) and are unable to respond to these reports. <add>1. Ensure that you are using the **latest**, **stable**, and **updated** versions of the Operating System and Web Browser(s) available to you on your machine. <add>2. We consider using tools & online utilities to report issues with SPF & DKIM configs, SSL Server tests, etc., in the category of ["beg bounties"](https://www.troyhunt.com/beg-bounties) and are unable to respond to these reports. <ide> 3. While we do not offer any bounties or swags at the moment, we'll be happy to list your name in our [Hall of Fame](security-hall-of-fame.md) list, provided the reports are not low-effort. <ide> <ide> ### Reporting <ide> <del>After confirming the above guidelines, please feel free to either send an email to `possible-security-issue [at] freecodecamp.org`. You can also send us an PGP encrypted message at `flowcrypt.com/me/freecodecamp` if you prefer. <add>After confirming the above guidelines, please feel free to send an email to `possible-security-issue [at] freecodecamp.org`. You can also send us a PGP encrypted message at `flowcrypt.com/me/freecodecamp`. <ide> <del>Once you report a vulnerability, we will look into it and make sure that it is not a false positive. If we need to clarify any details, we will get back to you. You can submit separate reports for each issue you find. Please note that we will not be able to respond to any issues that we think are outside the guidelines. <add>Once you report a vulnerability, we will look into it and ensure that it is not a false positive. If we need to clarify any details, we will get back to you. You can submit separate reports for each issue you find. Please note that we will not be able to respond to any issues that we think are outside the guidelines. <ide> <ide> ## Platforms & Codebases <ide> <ide> Here is a list of the platforms and codebases we are accepting reports for: <ide> <ide> ### Other Platforms <ide> <del>Apart from the above, we are also accepting reports for repositories hosted on GitHub, under the freeCodeCamp organization. <add>Apart from the above, we are also accepting reports for repositories hosted on GitHub under the freeCodeCamp organization. <ide> <ide> ### Other Self-hosted Applications <ide> <del>We self-host some of our platforms using open-source software like Ghost & Discourse. If you are reporting a vulnerability please ensure that it is not a bug in the upstream software. <add>We self-host some of our platforms using open-source software like Ghost & Discourse. If you are reporting a vulnerability, please ensure that it is not a bug in the upstream software.
1
Text
Text
fix typo in example/text-classification readme
75b8990d9068a2c6ef448c190f2595c17fbcb993
<ide><path>examples/flax/text-classification/README.md <ide> In the Tensorboard results linked below, the random seed of each model is equal <ide> <ide> | Task | Metric | Acc (best run) | Acc (avg/5runs) | Stdev | Metrics | <ide> |-------|------------------------------|----------------|-----------------|-----------|--------------------------------------------------------------------------| <del>| CoLA | Matthew's corr | 60.57 | 59.04 | 1.06 | [tfhub.dev](https://tensorboard.dev/experiment/lfr2adVpRtmLDALKrElkzg/) | <add>| CoLA | Matthews corr | 60.57 | 59.04 | 1.06 | [tfhub.dev](https://tensorboard.dev/experiment/lfr2adVpRtmLDALKrElkzg/) | <ide> | SST-2 | Accuracy | 92.66 | 92.23 | 0.57 | [tfhub.dev](https://tensorboard.dev/experiment/jYvfv2trRHKMjoWnXVwrZA/) | <ide> | MRPC | F1/Accuracy | 89.90/85.78 | 88.97/84.36 | 0.72/1.09 | [tfhub.dev](https://tensorboard.dev/experiment/bo3W3DEoRw2Q7YXjWrJkfg/) | <ide> | STS-B | Pearson/Spearman corr. | 89.04/88.70 | 88.94/88.63 | 0.07/0.07 | [tfhub.dev](https://tensorboard.dev/experiment/fxVwbLD7QpKhbot0r9rn2w/) | <ide><path>examples/pytorch/text-classification/README.md <ide> single Titan RTX was used): <ide> <ide> | Task | Metric | Result | Training time | <ide> |-------|------------------------------|-------------|---------------| <del>| CoLA | Matthew's corr | 56.53 | 3:17 | <add>| CoLA | Matthews corr | 56.53 | 3:17 | <ide> | SST-2 | Accuracy | 92.32 | 26:06 | <ide> | MRPC | F1/Accuracy | 88.85/84.07 | 2:21 | <del>| STS-B | Person/Spearman corr. | 88.64/88.48 | 2:13 | <add>| STS-B | Pearson/Spearman corr. | 88.64/88.48 | 2:13 | <ide> | QQP | Accuracy/F1 | 90.71/87.49 | 2:22:26 | <ide> | MNLI | Matched acc./Mismatched acc. | 83.91/84.10 | 2:35:23 | <ide> | QNLI | Accuracy | 90.66 | 40:57 | <ide> Using mixed precision training usually results in 2x-speedup for training with t <ide> <ide> | Task | Metric | Result | Training time | Result (FP16) | Training time (FP16) | <ide> |-------|------------------------------|-------------|---------------|---------------|----------------------| <del>| CoLA | Matthew's corr | 56.53 | 3:17 | 56.78 | 1:41 | <add>| CoLA | Matthews corr | 56.53 | 3:17 | 56.78 | 1:41 | <ide> | SST-2 | Accuracy | 92.32 | 26:06 | 91.74 | 13:11 | <ide> | MRPC | F1/Accuracy | 88.85/84.07 | 2:21 | 88.12/83.58 | 1:10 | <del>| STS-B | Person/Spearman corr. | 88.64/88.48 | 2:13 | 88.71/88.55 | 1:08 | <add>| STS-B | Pearson/Spearman corr. | 88.64/88.48 | 2:13 | 88.71/88.55 | 1:08 | <ide> | QQP | Accuracy/F1 | 90.71/87.49 | 2:22:26 | 90.67/87.43 | 1:11:54 | <ide> | MNLI | Matched acc./Mismatched acc. | 83.91/84.10 | 2:35:23 | 84.04/84.06 | 1:17:06 | <ide> | QNLI | Accuracy | 90.66 | 40:57 | 90.96 | 20:16 |
2
Go
Go
reuse the type
d639f61ec1c80f8d8d65386ec9331dbb6e218cb0
<ide><path>api.go <ide> func makeHttpHandler(srv *Server, logging bool, localMethod string, localRoute s <ide> func createRouter(srv *Server, logging bool) (*mux.Router, error) { <ide> r := mux.NewRouter() <ide> <del> m := map[string]map[string]func(*Server, float64, http.ResponseWriter, *http.Request, map[string]string) error{ <add> m := map[string]map[string]HttpApiFunc{ <ide> "GET": { <ide> "/auth": getAuth, <ide> "/version": getVersion,
1
PHP
PHP
fix incorrect `__isset()`
d238d8c0bbf51580bdb5dbd86c912c5b85bdbe0d
<ide><path>lib/Cake/Test/Case/View/ViewTest.php <ide> public function testExtendElement() { <ide> TEXT; <ide> $this->assertEquals($expected, $content); <ide> } <add> <add>/** <add> * Test that setting arbitrary properties still works. <add> * <add> * @return void <add> */ <add> public function testPropertySetting() { <add> $this->assertFalse(isset($this->View->pageTitle)); <add> $this->View->pageTitle = 'test'; <add> $this->assertTrue(isset($this->View->pageTitle)); <add> $this->assertEquals('test', $this->View->pageTitle); <add> } <ide> } <ide><path>lib/Cake/View/View.php <ide> public function __set($name, $value) { <ide> * @return boolean <ide> */ <ide> public function __isset($name) { <del> return isset($this->name); <add> return isset($this->{$name}); <ide> } <ide> <ide> /**
2
Javascript
Javascript
convert var to let and const
ac4195992290ef6f0b62e2b218ee0dba059f2a76
<ide><path>lib/repl.js <ide> /* A repl library that you can include in your own code to get a runtime <ide> * interface to your program. <ide> * <del> * var repl = require("repl"); <add> * const repl = require("repl"); <ide> * // start repl on stdin <ide> * repl.start("prompt> "); <ide> * <ide> function REPLServer(prompt, <ide> <ide> // After executing the current expression, store the values of RegExp <ide> // predefined properties back in `savedRegExMatches` <del> for (var idx = 1; idx < savedRegExMatches.length; idx += 1) { <add> for (let idx = 1; idx < savedRegExMatches.length; idx += 1) { <ide> savedRegExMatches[idx] = RegExp[`$${idx}`]; <ide> } <ide> <ide> function REPLServer(prompt, <ide> self.emit('exit'); <ide> }); <ide> <del> var sawSIGINT = false; <del> var sawCtrlD = false; <add> let sawSIGINT = false; <add> let sawCtrlD = false; <ide> const prioritizedSigintQueue = new Set(); <ide> self.on('SIGINT', function onSigInt() { <ide> if (prioritizedSigintQueue.size > 0) { <ide> REPLServer.prototype.close = function close() { <ide> }; <ide> <ide> REPLServer.prototype.createContext = function() { <del> var context; <add> let context; <ide> if (this.useGlobal) { <ide> context = global; <ide> } else { <ide> REPLServer.prototype.resetContext = function() { <ide> }; <ide> <ide> REPLServer.prototype.displayPrompt = function(preserveCursor) { <del> var prompt = this._initialPrompt; <add> let prompt = this._initialPrompt; <ide> if (this[kBufferedCommandSymbol].length) { <ide> prompt = '...'; <ide> const len = this.lines.level.length ? this.lines.level.length - 1 : 0; <ide> function ArrayStream() { <ide> Stream.call(this); <ide> <ide> this.run = function(data) { <del> for (var n = 0; n < data.length; n++) <add> for (let n = 0; n < data.length; n++) <ide> this.emit('data', `${data[n]}\n`); <ide> }; <ide> } <ide> function isIdentifier(str) { <ide> return false; <ide> } <ide> const firstLen = first > 0xffff ? 2 : 1; <del> for (var i = firstLen; i < str.length; i += 1) { <add> for (let i = firstLen; i < str.length; i += 1) { <ide> const cp = str.codePointAt(i); <ide> if (!isIdentifierChar(cp)) { <ide> return false; <ide> REPLServer.prototype.complete = function() { <ide> // given to the readline interface for handling tab completion. <ide> // <ide> // Example: <del>// complete('var foo = util.') <add>// complete('let foo = util.') <ide> // -> [['util.print', 'util.debug', 'util.log', 'util.inspect'], <ide> // 'util.' ] <ide> // <ide> function complete(line, callback) { <ide> if (this[kBufferedCommandSymbol] !== undefined && <ide> this[kBufferedCommandSymbol].length) { <ide> // Get a new array of inputted lines <del> var tmp = this.lines.slice(); <add> const tmp = this.lines.slice(); <ide> // Kill off all function declarations to push all local variables into <ide> // global scope <del> for (var n = 0; n < this.lines.level.length; n++) { <del> var kill = this.lines.level[n]; <add> for (let n = 0; n < this.lines.level.length; n++) { <add> const kill = this.lines.level[n]; <ide> if (kill.isFunction) <ide> tmp[kill.line] = ''; <ide> } <del> var flat = new ArrayStream(); // Make a new "input" stream. <del> var magic = new REPLServer('', flat); // Make a nested REPL. <add> const flat = new ArrayStream(); // Make a new "input" stream. <add> const magic = new REPLServer('', flat); // Make a nested REPL. <ide> replMap.set(magic, replMap.get(this)); <ide> flat.run(tmp); // `eval` the flattened code. <ide> // All this is only profitable if the nested REPL does not have a <ide> function complete(line, callback) { <ide> } <ide> } <ide> <del> var completions; <ide> // List of completion lists, one for each inheritance "level" <del> var completionGroups = []; <del> var completeOn, group, c; <add> let completionGroups = []; <add> let completeOn, group; <ide> <ide> // REPL commands (e.g. ".break"). <del> var filter; <add> let filter; <ide> let match = line.match(/^\s*\.(\w*)$/); <ide> if (match) { <ide> completionGroups.push(Object.keys(this.commands)); <ide> function complete(line, callback) { <ide> } else if (match = line.match(requireRE)) { <ide> // require('...<Tab>') <ide> const exts = Object.keys(this.context.require.extensions); <del> var indexRe = new RegExp('^index(?:' + exts.map(regexpEscape).join('|') + <add> const indexRe = new RegExp('^index(?:' + exts.map(regexpEscape).join('|') + <ide> ')$'); <del> var versionedFileNamesRe = /-\d+\.\d+/; <add> const versionedFileNamesRe = /-\d+\.\d+/; <ide> <ide> completeOn = match[1]; <del> var subdir = match[2] || ''; <add> const subdir = match[2] || ''; <ide> filter = match[1]; <del> var dir, files, name, base, ext, abs, subfiles, isDirectory; <add> let dir, files, name, base, ext, abs, subfiles, isDirectory; <ide> group = []; <ide> let paths = []; <ide> <ide> function complete(line, callback) { <ide> } else if (line.length === 0 || /\w|\.|\$/.test(line[line.length - 1])) { <ide> match = simpleExpressionRE.exec(line); <ide> if (line.length === 0 || match) { <del> var expr; <add> let expr; <ide> completeOn = (match ? match[0] : ''); <ide> if (line.length === 0) { <ide> filter = ''; <ide> function complete(line, callback) { <ide> filter = ''; <ide> expr = match[0].slice(0, match[0].length - 1); <ide> } else { <del> var bits = match[0].split('.'); <add> const bits = match[0].split('.'); <ide> filter = bits.pop(); <ide> expr = bits.join('.'); <ide> } <ide> <ide> // Resolve expr and get its completions. <del> var memberGroups = []; <add> const memberGroups = []; <ide> if (!expr) { <ide> // If context is instance of vm.ScriptContext <ide> // Get global vars synchronously <ide> if (this.useGlobal || vm.isContext(this.context)) { <ide> completionGroups.push(getGlobalLexicalScopeNames(this[kContextId])); <del> var contextProto = this.context; <add> let contextProto = this.context; <ide> while (contextProto = Object.getPrototypeOf(contextProto)) { <ide> completionGroups.push( <ide> filteredOwnPropertyNames.call(this, contextProto)); <ide> function complete(line, callback) { <ide> if (filter !== '') addCommonWords(completionGroups); <ide> } else if (Array.isArray(globals[0])) { <ide> // Add grouped globals <del> for (var n = 0; n < globals.length; n++) <add> for (let n = 0; n < globals.length; n++) <ide> completionGroups.push(globals[n]); <ide> } else { <ide> completionGroups.push(globals); <ide> function complete(line, callback) { <ide> } <ide> // Works for non-objects <ide> try { <del> var sentinel = 5; <del> var p; <add> let sentinel = 5; <add> let p; <ide> if (typeof obj === 'object' || typeof obj === 'function') { <ide> p = Object.getPrototypeOf(obj); <ide> } else { <ide> function complete(line, callback) { <ide> function completionGroupsLoaded() { <ide> // Filter, sort (within each group), uniq and merge the completion groups. <ide> if (completionGroups.length && filter) { <del> var newCompletionGroups = []; <add> const newCompletionGroups = []; <ide> for (let i = 0; i < completionGroups.length; i++) { <ide> group = completionGroups[i] <ide> .filter((elem) => elem.indexOf(filter) === 0); <ide> function complete(line, callback) { <ide> completionGroups = newCompletionGroups; <ide> } <ide> <add> let completions; <add> <ide> if (completionGroups.length) { <del> var uniq = {}; // Unique completions across all groups <add> const uniq = {}; // Unique completions across all groups <ide> completions = []; <ide> // Completion group 0 is the "closest" <ide> // (least far up the inheritance chain) <ide> // so we put its completions last: to be closest in the REPL. <ide> for (let i = 0; i < completionGroups.length; i++) { <ide> group = completionGroups[i]; <ide> group.sort(); <del> for (var j = group.length - 1; j >= 0; j--) { <del> c = group[j]; <add> for (let j = group.length - 1; j >= 0; j--) { <add> const c = group[j]; <ide> if (!ObjectPrototype.hasOwnProperty(uniq, c)) { <ide> completions.unshift(c); <ide> uniq[c] = true; <ide> function longestCommonPrefix(arr = []) { <ide> <ide> const first = arr[0]; <ide> // complexity: O(m * n) <del> for (var m = 0; m < first.length; m++) { <add> for (let m = 0; m < first.length; m++) { <ide> const c = first[m]; <del> for (var n = 1; n < cnt; n++) { <add> for (let n = 1; n < cnt; n++) { <ide> const entry = arr[n]; <ide> if (m >= entry.length || c !== entry[m]) { <ide> return first.substring(0, m); <ide> function defineDefaultCommands(repl) { <ide> } <ide> }); <ide> <del> var clearMessage; <add> let clearMessage; <ide> if (repl.useGlobal) { <ide> clearMessage = 'Alias for .break'; <ide> } else { <ide> function defineDefaultCommands(repl) { <ide> (max, name) => Math.max(max, name.length), <ide> 0 <ide> ); <del> for (var n = 0; n < names.length; n++) { <del> var name = names[n]; <del> var cmd = this.commands[name]; <del> var spaces = ' '.repeat(longestNameLength - name.length + 3); <del> var line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`; <add> for (let n = 0; n < names.length; n++) { <add> const name = names[n]; <add> const cmd = this.commands[name]; <add> const spaces = ' '.repeat(longestNameLength - name.length + 3); <add> const line = `.${name}${cmd.help ? spaces + cmd.help : ''}\n`; <ide> this.outputStream.write(line); <ide> } <ide> this.outputStream.write('\nPress ^C to abort current expression, ' +
1
Go
Go
add limit to page size used by overlay2 driver
520034e35b463e8c9d69ac78b52a4e5df958bc04
<ide><path>daemon/graphdriver/overlay2/overlay.go <ide> func (d *Driver) Get(id string, mountLabel string) (s string, err error) { <ide> <ide> pageSize := syscall.Getpagesize() <ide> <add> // Go can return a larger page size than supported by the system <add> // as of go 1.7. This will be fixed in 1.8 and this block can be <add> // removed when building with 1.8. <add> // See https://github.com/golang/go/commit/1b9499b06989d2831e5b156161d6c07642926ee1 <add> // See https://github.com/docker/docker/issues/27384 <add> if pageSize > 4096 { <add> pageSize = 4096 <add> } <add> <ide> // Use relative paths and mountFrom when the mount data has exceeded <ide> // the page size. The mount syscall fails if the mount data cannot <ide> // fit within a page and relative links make the mount data much
1
Javascript
Javascript
improve node.js support
c20426efef220e5ec594e11af13a5a004246901b
<ide><path>src/display/canvas.js <ide> var CanvasGraphics = (function CanvasGraphicsClosure() { <ide> var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); <ide> <ide> var imgToPaint, tmpCanvas; <del> // instanceof HTMLElement does not work in jsdom node.js module <del> if (imgData instanceof HTMLElement || !imgData.data) { <add> // typeof check is needed due to node.js support, see issue #8489 <add> if ((typeof HTMLElement === 'function' && <add> imgData instanceof HTMLElement) || !imgData.data) { <ide> imgToPaint = imgData; <ide> } else { <ide> tmpCanvas = this.cachedCanvases.getCanvas('inlineImage',
1
Ruby
Ruby
clarify github .git error message
5157c08327f58ffdd9fe6aaf6acfa2bd08b1ba41
<ide><path>Library/Homebrew/rubocops/homepage.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> <ide> when %r{^https://github.com.*\.git} <ide> offending_node(parameters(homepage_node).first) <del> problem "GitHub URLs (`#{homepage}`) should not end with .git" <add> problem "GitHub homepages (`#{homepage}`) should not end with .git" <ide> <ide> # There's an auto-redirect here, but this mistake is incredibly common too. <ide> # Only applies to the homepage and subdomains for now, not the FTP URLs. <ide><path>Library/Homebrew/test/rubocops/homepage_spec.rb <ide> class #{name.capitalize} < Formula <ide> column: 2, <ide> source: source }] <ide> elsif homepage.match?("https://github.com/foo/bar.git") <del> expected_offenses = [{ message: "GitHub URLs (`#{homepage}`) should not end with .git", <add> expected_offenses = [{ message: "GitHub homepages (`#{homepage}`) should not end with .git", <ide> severity: :convention, <ide> line: 2, <ide> column: 11,
2
Python
Python
remove users of `numpy.compat.bytes`
8a4fafa5278c2d894cf4efd40a342b33e941e373
<ide><path>numpy/lib/_iotools.py <ide> <ide> import numpy as np <ide> import numpy.core.numeric as nx <del>from numpy.compat import asbytes, asunicode, bytes <add>from numpy.compat import asbytes, asunicode <ide> <ide> <ide> def _decode_line(line, encoding=None): <ide><path>numpy/lib/npyio.py <ide> ) <ide> <ide> from numpy.compat import ( <del> asbytes, asstr, asunicode, bytes, os_fspath, os_PathLike, <add> asbytes, asstr, asunicode, os_fspath, os_PathLike, <ide> pickle, contextlib_nullcontext <ide> ) <ide> <ide><path>numpy/lib/tests/test_io.py <ide> import numpy as np <ide> import numpy.ma as ma <ide> from numpy.lib._iotools import ConverterError, ConversionWarning <del>from numpy.compat import asbytes, bytes <add>from numpy.compat import asbytes <ide> from numpy.ma.testutils import assert_equal <ide> from numpy.testing import ( <ide> assert_warns, assert_, assert_raises_regex, assert_raises,
3
Text
Text
update 2fa information in onboarding.md
1460b31bd3a9699bed9b715f0e8c1edb4fd0aa44
<ide><path>doc/onboarding.md <ide> onboarding session. <ide> <ide> ## One week before the onboarding session <ide> <del>* Confirm that the new Collaborator is using two-factor authentication on their <del> GitHub account. Unless two-factor authentication is enabled, do not give an <del> account elevated privileges such as the ability to land code in the main <del> repository or to start continuous integration (CI) jobs. <add>* If the new Collaborator is not yet a member of the nodejs GitHub organization, <add> confirm that they are using two-factor authentication. It will not be possible <add> to add them to the organization if they are not using two-factor <add> authentication. <ide> * Announce the accepted nomination in a TSC meeting and in the TSC <ide> mailing list. <ide> <ide> ## Fifteen minutes before the onboarding session <ide> <ide> * Prior to the onboarding session, add the new Collaborator to <ide> [the Collaborators team](https://github.com/orgs/nodejs/teams/collaborators). <del> Note that this is the step that gives the account elevated privileges, so do <del> not perform this step (or any subsequent steps) unless two-factor <del> authentication is enabled on the new Collaborator's GitHub account. <ide> <ide> ## Onboarding session <ide>
1
Go
Go
optimize the log info for client test
40b8ff62431d2005e5801b88dbe1685e89baafe5
<ide><path>client/container_copy_test.go <ide> func TestContainerStatPath(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if stat.Name != "name" { <del> t.Fatalf("expected container path stat name to be 'name', was '%s'", stat.Name) <add> t.Fatalf("expected container path stat name to be 'name', got '%s'", stat.Name) <ide> } <ide> if stat.Mode != 0700 { <del> t.Fatalf("expected container path stat mode to be 0700, was '%v'", stat.Mode) <add> t.Fatalf("expected container path stat mode to be 0700, got '%v'", stat.Mode) <ide> } <ide> } <ide> <ide> func TestCopyFromContainer(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if stat.Name != "name" { <del> t.Fatalf("expected container path stat name to be 'name', was '%s'", stat.Name) <add> t.Fatalf("expected container path stat name to be 'name', got '%s'", stat.Name) <ide> } <ide> if stat.Mode != 0700 { <del> t.Fatalf("expected container path stat mode to be 0700, was '%v'", stat.Mode) <add> t.Fatalf("expected container path stat mode to be 0700, got '%v'", stat.Mode) <ide> } <ide> content, err := ioutil.ReadAll(r) <ide> if err != nil { <ide><path>client/image_search_test.go <ide> func TestImageSearchWithPrivilegedFuncNoError(t *testing.T) { <ide> }, nil <ide> } <ide> if auth != "IAmValid" { <del> return nil, fmt.Errorf("Invalid auth header : expected %s, got %s", "IAmValid", auth) <add> return nil, fmt.Errorf("Invalid auth header : expected 'IAmValid', got %s", auth) <ide> } <ide> query := req.URL.Query() <ide> term := query.Get("term") <ide> if term != "some-image" { <del> return nil, fmt.Errorf("tag not set in URL query properly. Expected '%s', got %s", "some-image", term) <add> return nil, fmt.Errorf("term not set in URL query properly. Expected 'some-image', got %s", term) <ide> } <ide> content, err := json.Marshal([]registry.SearchResult{ <ide> { <ide> func TestImageSearchWithPrivilegedFuncNoError(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> if len(results) != 1 { <del> t.Fatalf("expected a result, got %v", results) <add> t.Fatalf("expected 1 result, got %v", results) <ide> } <ide> } <ide> <ide> func TestImageSearchWithoutErrors(t *testing.T) { <ide> query := req.URL.Query() <ide> term := query.Get("term") <ide> if term != "some-image" { <del> return nil, fmt.Errorf("tag not set in URL query properly. Expected '%s', got %s", "some-image", term) <add> return nil, fmt.Errorf("term not set in URL query properly. Expected 'some-image', got %s", term) <ide> } <ide> filters := query.Get("filters") <ide> if filters != expectedFilters { <ide><path>client/plugin_push_test.go <ide> func TestPluginPush(t *testing.T) { <ide> } <ide> auth := req.Header.Get("X-Registry-Auth") <ide> if auth != "authtoken" { <del> return nil, fmt.Errorf("Invalid auth header : expected %s, got %s", "authtoken", auth) <add> return nil, fmt.Errorf("Invalid auth header : expected 'authtoken', got %s", auth) <ide> } <ide> return &http.Response{ <ide> StatusCode: http.StatusOK,
3
Python
Python
document the threads task pool in the cli
877b5f10b44bf92c99f5a3cdc50a0bb059924aaf
<ide><path>celery/bin/worker.py <ide> <ide> Pool implementation: <ide> <del> prefork (default), eventlet, gevent or solo. <add> prefork (default), eventlet, gevent, threads or solo. <ide> <ide> .. cmdoption:: -n, --hostname <ide>
1
Javascript
Javascript
expose meta counters (privately)
6eb4b1d0d330d75a3f72f6253cacad4a82259a11
<ide><path>packages/ember-metal/lib/meta.js <ide> export function meta(obj) { <ide> return newMeta; <ide> } <ide> <add>if (DEBUG) { <add> meta._counters = counters; <add>} <add> <ide> // Using `symbol()` here causes some node test to fail, presumably <ide> // because we define the CP with one copy of Ember and boot the app <ide> // with a different copy, so the random key we generate do not line
1
Javascript
Javascript
add test case for util.isdate() behavior
cafcc7e67a46fda9006cceeec516cd289c107f04
<ide><path>test/simple/test-util-inspect.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>// libuv-broken <add> <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var util = require('util'); <add> <add>// test the internal isDate implementation <add>var Date2 = require('vm').runInNewContext('Date'); <add>var d = new Date2(); <add>var orig = util.inspect(d); <add>Date2.prototype.foo = 'bar'; <add>var after = util.inspect(d); <add>assert.equal(orig, after);
1
Javascript
Javascript
draw line at edge of scales & update tests
f2899934db78ad0edcc8d61b8bd9377e078a358c
<ide><path>src/core/core.scale.js <ide> } <ide> } <ide> <del> <ide> this.ctx.translate(xLabelValue, yLabelValue); <ide> this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); <ide> this.ctx.font = labelFont; <ide> this.ctx.restore(); <ide> } <ide> } <add> <add> // Draw the line at the edge of the axis <add> this.ctx.lineWidth = this.options.gridLines.lineWidth; <add> this.ctx.strokeStyle = this.options.gridLines.color; <add> var x1 = this.left, x2 = this.right, y1 = this.top, y2 = this.bottom; <add> <add> if (this.isHorizontal()) { <add> y1 = y2 = this.options.position === 'top' ? this.bottom : this.top; <add> } else { <add> x1 = x2 = this.options.position === 'left' ? this.right : this.left; <add> } <add> <add> this.ctx.moveTo(x1, y1); <add> this.ctx.lineTo(x2, y2); <add> this.ctx.stroke(); <ide> } <ide> } <ide> }); <ide><path>test/scale.linear.tests.js <ide> describe('Linear Scale', function() { <ide> }, { <ide> "name": "restore", <ide> "args": [] <add> }, { <add> "name": "setLineWidth", <add> "args": [1] <add> }, { <add> "name": "setStrokeStyle", <add> "args": ["rgba(0, 0, 0, 0.1)"] <add> }, { <add> "name": "moveTo", <add> "args": [0, 100] <add> }, { <add> "name": "lineTo", <add> "args": [200, 100] <add> }, { <add> "name": "stroke", <add> "args": [] <ide> }]; <ide> expect(mockContext.getCalls()).toEqual(expected); <ide> <ide> describe('Linear Scale', function() { <ide> }, { <ide> "name": "fillText", <ide> "args": ["myLabel", 100, 122] <add> }, { <add> "name": "setLineWidth", <add> "args": [1] <add> }, { <add> "name": "setStrokeStyle", <add> "args": ["rgba(0, 0, 0, 0.1)"] <add> }, { <add> "name": "moveTo", <add> "args": [0, 100] <add> }, { <add> "name": "lineTo", <add> "args": [200, 100] <add> }, { <add> "name": "stroke", <add> "args": [] <ide> }]); <ide> <ide> // Turn off display <ide> describe('Linear Scale', function() { <ide> }, { <ide> "name": "restore", <ide> "args": [] <add> }, { <add> "name": "setLineWidth", <add> "args": [1] <add> }, { <add> "name": "setStrokeStyle", <add> "args": ["rgba(0, 0, 0, 0.1)"] <add> }, { <add> "name": "moveTo", <add> "args": [30, 0] <add> }, { <add> "name": "lineTo", <add> "args": [30, 300] <add> }, { <add> "name": "stroke", <add> "args": [] <ide> }]); <ide> <ide> // Turn off some drawing <ide> describe('Linear Scale', function() { <ide> }, { <ide> "name": "restore", <ide> "args": [] <add> }, { <add> "name": "setLineWidth", <add> "args": [1] <add> }, { <add> "name": "setStrokeStyle", <add> "args": ["rgba(0, 0, 0, 0.1)"] <add> }, { <add> "name": "moveTo", <add> "args": [30, 0] <add> }, { <add> "name": "lineTo", <add> "args": [30, 300] <add> }, { <add> "name": "stroke", <add> "args": [] <ide> }]); <ide> }); <ide> <ide> describe('Linear Scale', function() { <ide> }, { <ide> "name": "restore", <ide> "args": [] <add> }, { <add> "name": "setLineWidth", <add> "args": [1] <add> }, { <add> "name": "setStrokeStyle", <add> "args": ["rgba(0, 0, 0, 0.1)"] <add> }, { <add> "name": "moveTo", <add> "args": [30, 0] <add> }, { <add> "name": "lineTo", <add> "args": [30, 300] <add> }, { <add> "name": "stroke", <add> "args": [] <ide> }]) <ide> }); <ide> }); <ide>\ No newline at end of file
2
Python
Python
add more scaledfloatdtype tests
d7af8532863582395f5a64c18f7680f583916031
<ide><path>numpy/core/tests/test_custom_dtypes.py <ide> <ide> import numpy as np <ide> from numpy.testing import assert_array_equal <del> <del> <del>SF = np.core._multiarray_umath._get_sfloat_dtype() <del> <del> <del>@pytest.mark.parametrize("scaling", [1., -1., 2.]) <del>def test_scaled_float_from_floats(scaling): <del> a = np.array([1., 2., 3.], dtype=SF(scaling)) <del> <del> assert a.dtype.get_scaling() == scaling <del> assert_array_equal(scaling * a.view(np.float64), np.array([1., 2., 3.])) <del> <del> <del>@pytest.mark.parametrize("scaling", [1., -1., 2.]) <del>def test_sfloat_from_float(scaling): <del> a = np.array([1., 2., 3.]).astype(dtype=SF(scaling)) <del> <del> assert a.dtype.get_scaling() == scaling <del> assert_array_equal(scaling * a.view(np.float64), np.array([1., 2., 3.])) <del> <del> <del>def _get_array(scaling, aligned=True): <del> if not aligned: <del> a = np.empty(3*8 + 1, dtype=np.uint8)[1:] <del> a = a.view(np.float64) <del> a[:] = [1., 2., 3.] <del> else: <del> a = np.array([1., 2., 3.]) <del> <del> a *= 1./scaling # the casting code also uses the reciprocal. <del> return a.view(SF(scaling)) <del> <del> <del>@pytest.mark.parametrize("aligned", [True, False]) <del>def test_sfloat_casts(aligned): <del> a = _get_array(1., aligned) <del> <del> assert np.can_cast(a, SF(-1.), casting="equiv") <del> assert not np.can_cast(a, SF(-1.), casting="no") <del> na = a.astype(SF(-1.)) <del> assert_array_equal(-1 * na.view(np.float64), a.view(np.float64)) <del> <del> assert np.can_cast(a, SF(2.), casting="same_kind") <del> assert not np.can_cast(a, SF(2.), casting="safe") <del> a2 = a.astype(SF(2.)) <del> assert_array_equal(2 * a2.view(np.float64), a.view(np.float64)) <del> <del> <del>@pytest.mark.parametrize("aligned", [True, False]) <del>def test_sfloat_cast_internal_errors(aligned): <del> a = _get_array(2e300, aligned) <del> <del> with pytest.raises(TypeError, <del> match="error raised inside the core-loop: non-finite factor!"): <del> a.astype(SF(2e-300)) <del> <add>from numpy.core._multiarray_umath import ( <add> _discover_array_parameters as discover_array_params, _get_sfloat_dtype) <add> <add> <add>SF = _get_sfloat_dtype() <add> <add> <add>class TestSFloat: <add> def _get_array(self, scaling, aligned=True): <add> if not aligned: <add> a = np.empty(3*8 + 1, dtype=np.uint8)[1:] <add> a = a.view(np.float64) <add> a[:] = [1., 2., 3.] <add> else: <add> a = np.array([1., 2., 3.]) <add> <add> a *= 1./scaling # the casting code also uses the reciprocal. <add> return a.view(SF(scaling)) <add> <add> def test_sfloat_rescaled(self): <add> sf = SF(1.) <add> sf2 = sf.scaled_by(2.) <add> assert sf2.get_scaling() == 2. <add> sf6 = sf2.scaled_by(3.) <add> assert sf6.get_scaling() == 6. <add> <add> def test_class_discovery(self): <add> # This does not test much, since we always discover the scaling as 1. <add> # But most of NumPy (when writing) does not understand DType classes <add> dt, _ = discover_array_params([1., 2., 3.], dtype=SF) <add> assert dt == SF(1.) <add> <add> @pytest.mark.parametrize("scaling", [1., -1., 2.]) <add> def test_scaled_float_from_floats(self, scaling): <add> a = np.array([1., 2., 3.], dtype=SF(scaling)) <add> <add> assert a.dtype.get_scaling() == scaling <add> assert_array_equal(scaling * a.view(np.float64), [1., 2., 3.]) <add> <add> def test_repr(self): <add> # Check the repr, mainly to cover the code paths: <add> assert repr(SF(scaling=1.)) == "_ScaledFloatTestDType(scaling=1.0)" <add> <add> @pytest.mark.parametrize("scaling", [1., -1., 2.]) <add> def test_sfloat_from_float(self, scaling): <add> a = np.array([1., 2., 3.]).astype(dtype=SF(scaling)) <add> <add> assert a.dtype.get_scaling() == scaling <add> assert_array_equal(scaling * a.view(np.float64), [1., 2., 3.]) <add> <add> @pytest.mark.parametrize("aligned", [True, False]) <add> @pytest.mark.parametrize("scaling", [1., -1., 2.]) <add> def test_sfloat_getitem(self, aligned, scaling): <add> a = self._get_array(1., aligned) <add> assert a.tolist() == [1., 2., 3.] <add> <add> @pytest.mark.parametrize("aligned", [True, False]) <add> def test_sfloat_casts(self, aligned): <add> a = self._get_array(1., aligned) <add> <add> assert np.can_cast(a, SF(-1.), casting="equiv") <add> assert not np.can_cast(a, SF(-1.), casting="no") <add> na = a.astype(SF(-1.)) <add> assert_array_equal(-1 * na.view(np.float64), a.view(np.float64)) <add> <add> assert np.can_cast(a, SF(2.), casting="same_kind") <add> assert not np.can_cast(a, SF(2.), casting="safe") <add> a2 = a.astype(SF(2.)) <add> assert_array_equal(2 * a2.view(np.float64), a.view(np.float64)) <add> <add> @pytest.mark.parametrize("aligned", [True, False]) <add> def test_sfloat_cast_internal_errors(self, aligned): <add> a = self._get_array(2e300, aligned) <add> <add> with pytest.raises(TypeError, <add> match="error raised inside the core-loop: non-finite factor!"): <add> a.astype(SF(2e-300)) <add> <add> def test_sfloat_promotion(self): <add> assert np.result_type(SF(2.), SF(3.)) == SF(3.) <add> assert np.result_type(SF(3.), SF(2.)) == SF(3.) <add> # Float64 -> SF(1.) and then promotes normally, so both of this work: <add> assert np.result_type(SF(3.), np.float64) == SF(3.) <add> assert np.result_type(np.float64, SF(0.5)) == SF(1.) <add> <add> # Test an undefined promotion: <add> with pytest.raises(TypeError): <add> np.result_type(SF(1.), np.int64)
1
Mixed
Ruby
add support for activestorage expiring urls
209a79aeed2aab05af92687b041acc466ddcc302
<ide><path>activestorage/CHANGELOG.md <add> <add>* Add support for ActiveStorage expiring URLs. <add> <add> ```ruby <add> rails_blob_path(user.avatar, disposition: "attachment", expires_in: 30.minutes) <add> <add> <%= image_tag rails_blob_path(user.avatar.variant(resize: "100x100"), expires_in: 30.minutes) %> <add> ``` <add> <add> If you want to set default expiration time for ActiveStorage URLs throughout your application, set `config.active_storage.urls_expire_in`. <add> <add> *aki77* <add> <ide> * Allow to purge an attachment when record is not persisted for `has_many_attached` <ide> <ide> *Jacopo Beschi* <ide><path>activestorage/config/routes.rb <ide> resolve("ActiveStorage::Attachment") { |attachment, options| route_for(ActiveStorage.resolve_model_to_route, attachment.blob, options) } <ide> <ide> direct :rails_storage_proxy do |model, options| <add> expires_in = options.delete(:expires_in) { ActiveStorage.urls_expire_in } <add> <ide> if model.respond_to?(:signed_id) <ide> route_for( <ide> :rails_service_blob_proxy, <del> model.signed_id, <add> model.signed_id(expires_in: expires_in), <ide> model.filename, <ide> options <ide> ) <ide> else <del> signed_blob_id = model.blob.signed_id <add> signed_blob_id = model.blob.signed_id(expires_in: expires_in) <ide> variation_key = model.variation.key <ide> filename = model.blob.filename <ide> <ide> end <ide> <ide> direct :rails_storage_redirect do |model, options| <add> expires_in = options.delete(:expires_in) { ActiveStorage.urls_expire_in } <add> <ide> if model.respond_to?(:signed_id) <ide> route_for( <ide> :rails_service_blob, <del> model.signed_id, <add> model.signed_id(expires_in: expires_in), <ide> model.filename, <ide> options <ide> ) <ide> else <del> signed_blob_id = model.blob.signed_id <add> signed_blob_id = model.blob.signed_id(expires_in: expires_in) <ide> variation_key = model.variation.key <ide> filename = model.blob.filename <ide> <ide><path>activestorage/lib/active_storage.rb <ide> module ActiveStorage <ide> mattr_accessor :content_types_allowed_inline, default: [] <ide> <ide> mattr_accessor :service_urls_expire_in, default: 5.minutes <add> mattr_accessor :urls_expire_in <ide> <ide> mattr_accessor :routes_prefix, default: "/rails/active_storage" <ide> mattr_accessor :draw_routes, default: true <ide><path>activestorage/lib/active_storage/engine.rb <ide> class Engine < Rails::Engine # :nodoc: <ide> ActiveStorage.web_image_content_types = app.config.active_storage.web_image_content_types || [] <ide> ActiveStorage.content_types_to_serve_as_binary = app.config.active_storage.content_types_to_serve_as_binary || [] <ide> ActiveStorage.service_urls_expire_in = app.config.active_storage.service_urls_expire_in || 5.minutes <add> ActiveStorage.urls_expire_in = app.config.active_storage.urls_expire_in <ide> ActiveStorage.content_types_allowed_inline = app.config.active_storage.content_types_allowed_inline || [] <ide> ActiveStorage.binary_content_type = app.config.active_storage.binary_content_type || "application/octet-stream" <ide> <ide><path>activestorage/test/controllers/blobs/proxy_controller_test.rb <ide> class ActiveStorage::Blobs::ProxyControllerTest < ActionDispatch::IntegrationTes <ide> get rails_storage_proxy_url(create_blob(content_type: "application/zip")) <ide> assert_match(/^attachment; /, response.headers["Content-Disposition"]) <ide> end <add> <add> test "signed ID within expiration date" do <add> get rails_storage_proxy_url(create_file_blob(filename: "racecar.jpg"), expires_in: 1.minute) <add> assert_response :success <add> end <add> <add> test "Expired signed ID" do <add> url = rails_storage_proxy_url(create_file_blob(filename: "racecar.jpg"), expires_in: 1.minute) <add> travel 2.minutes <add> get url <add> assert_response :not_found <add> end <add>end <add> <add>class ActiveStorage::Blobs::ExpiringProxyControllerTest < ActionDispatch::IntegrationTest <add> setup do <add> @old_urls_expire_in = ActiveStorage.urls_expire_in <add> ActiveStorage.urls_expire_in = 1.minutes <add> end <add> <add> teardown do <add> ActiveStorage.urls_expire_in = @old_urls_expire_in <add> end <add> <add> test "signed ID within expiration date" do <add> get rails_storage_proxy_url(create_file_blob(filename: "racecar.jpg")) <add> assert_response :success <add> end <add> <add> test "Expired signed ID" do <add> url = rails_storage_proxy_url(create_file_blob(filename: "racecar.jpg")) <add> travel 2.minutes <add> get url <add> assert_response :not_found <add> end <ide> end <ide><path>activestorage/test/controllers/blobs/redirect_controller_test.rb <ide> class ActiveStorage::Blobs::RedirectControllerTest < ActionDispatch::Integration <ide> assert_redirected_to(/racecar\.jpg/) <ide> assert_equal "max-age=300, private", response.headers["Cache-Control"] <ide> end <add> <add> test "signed ID within expiration date" do <add> get rails_storage_redirect_url(@blob, expires_in: 1.minute) <add> assert_redirected_to(/racecar\.jpg/) <add> end <add> <add> test "Expired signed ID" do <add> url = rails_storage_redirect_url(@blob, expires_in: 1.minute) <add> travel 2.minutes <add> get url <add> assert_response :not_found <add> end <add>end <add> <add>class ActiveStorage::Blobs::ExpiringRedirectControllerTest < ActionDispatch::IntegrationTest <add> setup do <add> @blob = create_file_blob filename: "racecar.jpg" <add> @old_urls_expire_in = ActiveStorage.urls_expire_in <add> ActiveStorage.urls_expire_in = 1.minutes <add> end <add> <add> teardown do <add> ActiveStorage.urls_expire_in = @old_urls_expire_in <add> end <add> <add> test "signed ID within expiration date" do <add> get rails_storage_redirect_url(@blob) <add> assert_redirected_to(/racecar\.jpg/) <add> end <add> <add> test "Expired signed ID" do <add> url = rails_storage_redirect_url(@blob) <add> travel 2.minutes <add> get url <add> assert_response :not_found <add> end <ide> end <ide><path>guides/source/configuring.md <ide> text/javascript image/svg+xml application/postscript application/x-shockwave-fla <ide> <ide> The default is 5 minutes. <ide> <add>* `config.active_storage.urls_expire_in` determines the default expiry of URLs in the Rails application generated by Active Storage. The default is nil. <add> <ide> * `config.active_storage.routes_prefix` can be used to set the route prefix for the routes served by Active Storage. Accepts a string that will be prepended to the generated routes. <ide> <ide> ```ruby
7
Ruby
Ruby
handle zpython bottle
2b9c350b27888896886ffc6e75d2b6bbbdea4bcd
<ide><path>Library/Homebrew/bottle_version.rb <ide> def self._parse spec <ide> m = /-(r\d+\.?\d*)/.match(stem) <ide> return m.captures.first unless m.nil? <ide> <add> # e.g. 00-5.0.5 from zpython-00-5.0.5.mavericks.bottle.tar.gz <add> m = /(00-\d+\.\d+(\.\d+)+)/.match(stem) <add> return m.captures.first unless m.nil? <add> <ide> # e.g. 1.6.39 from pazpar2-1.6.39.mavericks.bottle.tar.gz <ide> m = /-(\d+\.\d+(\.\d+)+)/.match(stem) <ide> return m.captures.first unless m.nil? <ide><path>Library/Homebrew/test/test_bottle_versions.rb <ide> def test_disco_style <ide> assert_version_detected '0_5_0', <ide> '/usr/local/disco-0_5_0.mavericks.bottle.tar.gz' <ide> end <add> <add> def test_zpython_style <add> assert_version_detected '00-5.0.5', <add> '/usr/local/zpython-00-5.0.5.mavericks.bottle.tar.gz' <add> end <ide> end
2
Text
Text
add livecheck formula/cask reference example
0bc3d6cf4b8134120be2d1aff2af86eaf0f3aaf8
<ide><path>docs/Brew-Livecheck.md <ide> end <ide> <ide> If tags include the software name as a prefix (e.g. `example-1.2.3`), it's easy to modify the regex accordingly: `/^example[._-]v?(\d+(?:\.\d+)+)$/i` <ide> <add>### Referenced formula/cask <add> <add>A formula/cask can use the same check as another by using `formula` or `cask`. <add> <add>```ruby <add>livecheck do <add> formula "another-formula" <add>end <add>``` <add> <add>The referenced formula/cask should be in the same tap, as a reference to a formula/cask from another tap will generate an error if the user doesn't already have it tapped. <add> <ide> ### `strategy` blocks <ide> <ide> If the upstream version format needs to be manipulated to match the formula/cask format, a `strategy` block can be used instead of a `regex`.
1
Javascript
Javascript
add defaultfontsize setting
6d7322993f0055ca5201ba963624acedf835dad0
<ide><path>spec/workspace-spec.js <ide> describe('Workspace', () => { <ide> }); <ide> <ide> describe('::resetFontSize()', () => { <del> it("resets the font size to the window's starting font size", () => { <del> const originalFontSize = atom.config.get('editor.fontSize'); <add> it("resets the font size to the window's default font size", () => { <add> const defaultFontSize = atom.config.get('editor.defaultFontSize'); <ide> <ide> workspace.increaseFontSize(); <del> expect(atom.config.get('editor.fontSize')).toBe(originalFontSize + 1); <add> expect(atom.config.get('editor.fontSize')).toBe(defaultFontSize + 1); <ide> workspace.resetFontSize(); <del> expect(atom.config.get('editor.fontSize')).toBe(originalFontSize); <add> expect(atom.config.get('editor.fontSize')).toBe(defaultFontSize); <ide> workspace.decreaseFontSize(); <del> expect(atom.config.get('editor.fontSize')).toBe(originalFontSize - 1); <add> expect(atom.config.get('editor.fontSize')).toBe(defaultFontSize - 1); <ide> workspace.resetFontSize(); <del> expect(atom.config.get('editor.fontSize')).toBe(originalFontSize); <add> expect(atom.config.get('editor.fontSize')).toBe(defaultFontSize); <add> }); <add> <add> it('resets the font size the default font size when it is changed', () => { <add> const defaultFontSize = atom.config.get('editor.defaultFontSize'); <add> workspace.increaseFontSize(); <add> expect(atom.config.get('editor.fontSize')).toBe(defaultFontSize + 1); <add> atom.config.set('editor.defaultFontSize', 14); <add> workspace.resetFontSize(); <add> expect(atom.config.get('editor.fontSize')).toBe(14); <ide> }); <ide> <ide> it('does nothing if the font size has not been changed', () => { <ide><path>src/config-schema.js <ide> const configSchema = { <ide> maximum: 100, <ide> description: 'Height in pixels of editor text.' <ide> }, <add> defaultFontSize: { <add> type: 'integer', <add> default: 14, <add> minimum: 1, <add> maximum: 100, <add> description: <add> 'Default height in pixels of the editor text. Useful when resetting font size' <add> }, <ide> lineHeight: { <ide> type: ['string', 'number'], <ide> default: 1.5, <ide><path>src/workspace.js <ide> module.exports = class Workspace extends Model { <ide> <ide> initialize() { <ide> this.originalFontSize = this.config.get('editor.fontSize'); <add> this.defaultFontSize = this.config.get('editor.defaultFontSize'); <ide> this.project.onDidChangePaths(this.updateWindowTitle); <ide> this.subscribeToAddedItems(); <ide> this.subscribeToMovedItems(); <ide> this.subscribeToDockToggling(); <add> this.subscribeToFontSize(); <ide> } <ide> <ide> consumeServices({ serviceHub }) { <ide> module.exports = class Workspace extends Model { <ide> } <ide> } <ide> <del> // Restore to the window's original editor font size. <add> // Restore to the window's default editor font size. <ide> resetFontSize() { <del> if (this.originalFontSize) { <del> this.config.set('editor.fontSize', this.originalFontSize); <add> if (this.defaultFontSize) { <add> this.config.set('editor.fontSize', this.defaultFontSize); <ide> } <ide> } <ide> <add> subscribeToFontSize() { <add> return this.config.onDidChange('editor.defaultFontSize', () => { <add> this.defaultFontSize = this.config.get('editor.defaultFontSize'); <add> }); <add> } <ide> // Removes the item's uri from the list of potential items to reopen. <ide> itemOpened(item) { <ide> let uri;
3
Text
Text
update instructions to create airflow release
5bc64fb923d7afcab420a1b4a6d9f6cc13362f7a
<ide><path>dev/README_RELEASE_AIRFLOW.md <ide> - [Summarize the voting for the Apache Airflow release](#summarize-the-voting-for-the-apache-airflow-release) <ide> - [Publish release to SVN](#publish-release-to-svn) <ide> - [Prepare PyPI "release" packages](#prepare-pypi-release-packages) <del> - [Update CHANGELOG.md](#update-changelogmd) <ide> - [Manually prepare production Docker Image](#manually-prepare-production-docker-image) <ide> - [Publish documentation](#publish-documentation) <ide> - [Notify developers of release](#notify-developers-of-release) <ide> The Release Candidate artifacts we vote upon should be the exact ones we vote ag <ide> ``` <ide> <ide> - Set your version to 2.0.N in `setup.py` (without the RC tag) <add>- Replace the version in `README.md` and verify that installation instructions work fine. <add>- Add a commit that updates `CHANGELOG.md` to add changes from previous version if it has not already added. <add>For now this is done manually, example run `git log --oneline v2-2-test..HEAD --pretty='format:- %s'` and categorize them. <add>- Add section for the release in `UPDATING.md`. If no new entries exist, put "No breaking changes" (e.g. `2.1.4`). <ide> - Commit the version change. <ide> <ide> - Tag your release <ide> previously released RC candidates in "${AIRFLOW_SOURCES}/dist": <ide> <ide> - Again, confirm that the package is available here: https://pypi.python.org/pypi/apache-airflow <ide> <del>## Update CHANGELOG.md <del> <del>- Get a diff between the last version and the current version: <del> <del> ```shell script <del> git log 1.8.0..1.9.0 --pretty=oneline <del> ``` <del> <del>- Update CHANGELOG.md with the details, and commit it. <del> <ide> - Re-Tag & Push the constraints files with the final release version. <ide> <ide> ```shell script
1
Python
Python
provide ways to override the url rule
0e98a080976f39e20aa6f18e8a335aa23d9334f7
<ide><path>flask/app.py <ide> class Flask(_PackageBoundObject): <ide> 'MAX_CONTENT_LENGTH': None <ide> }) <ide> <add> #: The rule object to use for URL rules created. This is used by <add> #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`. <add> #: <add> #: .. versionadded:: 0.7 <add> url_rule_class = Rule <add> <ide> #: the test client that is used with when `test_client` is used. <ide> #: <ide> #: .. versionadded:: 0.7 <ide> def index(): <ide> if 'OPTIONS' not in methods: <ide> methods = tuple(methods) + ('OPTIONS',) <ide> provide_automatic_options = True <del> rule = Rule(rule, methods=methods, **options) <add> rule = self.url_rule_class(rule, methods=methods, **options) <ide> rule.provide_automatic_options = provide_automatic_options <ide> self.url_map.add(rule) <ide> if view_func is not None:
1
Java
Java
add missing verify() in jackson2tokenizertests
7bed4f36da61ee6d729bbd59639d5be183655700
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/Jackson2TokenizerTests.java <ide> public void testLimit() { <ide> .expectNext(expected) <ide> .verifyComplete(); <ide> <del> StepVerifier.create(decode(source, false, maxInMemorySize - 1)) <del> .expectError(DataBufferLimitException.class); <add> StepVerifier.create(decode(source, false, maxInMemorySize - 2)) <add> .verifyError(DataBufferLimitException.class); <ide> } <ide> <ide> @Test
1
Text
Text
add appregistry to imports in example
143b6493b0feb9384f2c74aa7390ba07cd49e9f2
<ide><path>docs/UsingNavigators.md <ide> Notice the `export default` in front of the component declaration. This will _ex <ide> <ide> ```javascript <ide> import React, { Component } from 'react'; <del>import { View, Text } from 'react-native'; <add>import { AppRegistry } from 'react-native'; <ide> <ide> import MyScene from './MyScene'; <ide>
1
Ruby
Ruby
use utf8mb4 in all tests and examples
9120d087e8fcc381d4e781218bd2c134dfce6423
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb <ide> def primary_key(table_name) <ide> # <ide> # ====== Add a backend specific option to the generated SQL (MySQL) <ide> # <del> # create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8') <add> # create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4') <ide> # <ide> # generates: <ide> # <ide> # CREATE TABLE suppliers ( <ide> # id bigint auto_increment PRIMARY KEY <del> # ) ENGINE=InnoDB DEFAULT CHARSET=utf8 <add> # ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 <ide> # <ide> # ====== Rename the primary key column <ide> # <ide><path>activerecord/test/cases/adapters/mysql2/case_sensitivity_test.rb <ide> class CollationTest < ActiveRecord::Base <ide> repair_validations(CollationTest) <ide> <ide> def test_columns_include_collation_different_from_table <del> assert_equal "utf8_bin", CollationTest.columns_hash["string_cs_column"].collation <del> assert_equal "utf8_general_ci", CollationTest.columns_hash["string_ci_column"].collation <add> assert_equal "utf8mb4_bin", CollationTest.columns_hash["string_cs_column"].collation <add> assert_equal "utf8mb4_general_ci", CollationTest.columns_hash["string_ci_column"].collation <ide> end <ide> <ide> def test_case_sensitive <ide><path>activerecord/test/cases/adapters/mysql2/charset_collation_test.rb <ide> class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase <ide> end <ide> <ide> test "add column with charset and collation" do <del> @connection.add_column :charset_collations, :title, :string, charset: "utf8", collation: "utf8_bin" <add> @connection.add_column :charset_collations, :title, :string, charset: "utf8mb4", collation: "utf8mb4_bin" <ide> <ide> column = @connection.columns(:charset_collations).find { |c| c.name == "title" } <ide> assert_equal :string, column.type <del> assert_equal "utf8_bin", column.collation <add> assert_equal "utf8mb4_bin", column.collation <ide> end <ide> <ide> test "change column with charset and collation" do <del> @connection.add_column :charset_collations, :description, :string, charset: "utf8", collation: "utf8_unicode_ci" <del> @connection.change_column :charset_collations, :description, :text, charset: "utf8", collation: "utf8_general_ci" <add> @connection.add_column :charset_collations, :description, :string, charset: "utf8mb4", collation: "utf8mb4_unicode_ci" <add> @connection.change_column :charset_collations, :description, :text, charset: "utf8mb4", collation: "utf8mb4_general_ci" <ide> <ide> column = @connection.columns(:charset_collations).find { |c| c.name == "description" } <ide> assert_equal :text, column.type <del> assert_equal "utf8_general_ci", column.collation <add> assert_equal "utf8mb4_general_ci", column.collation <ide> end <ide> <ide> test "schema dump includes collation" do <ide><path>activerecord/test/schema/mysql2_specific_schema.rb <ide> end <ide> <ide> create_table :collation_tests, id: false, force: true do |t| <del> t.string :string_cs_column, limit: 1, collation: "utf8_bin" <del> t.string :string_ci_column, limit: 1, collation: "utf8_general_ci" <add> t.string :string_cs_column, limit: 1, collation: "utf8mb4_bin" <add> t.string :string_ci_column, limit: 1, collation: "utf8mb4_general_ci" <ide> t.binary :binary_column, limit: 1 <ide> end <ide>
4
Javascript
Javascript
fix the getter for `navigationcontext`
7f54506f96ff44add072ea1f83fd6650ab7a750b
<ide><path>Libraries/CustomComponents/Navigator/Navigator.js <ide> var Navigator = React.createClass({ <ide> }, <ide> <ide> componentWillMount: function() { <add> // TODO(t7489503): Don't need this once ES6 Class landed. <add> this.__defineGetter__('navigationContext', this._getNavigationContext); <add> <ide> this._subRouteFocus = []; <ide> this.parentNavigator = this.props.navigator; <ide> this._handlers = {}; <ide> var Navigator = React.createClass({ <ide> ); <ide> }, <ide> <del> // Getter for `navigationContext`. <del> get navigationContext() { <add> _getNavigationContext: function() { <ide> if (!this._navigationContext) { <ide> this._navigationContext = new NavigationContext(); <ide> }
1
Python
Python
fix code-snippets in google provider
427e14b763d2a29432a999ba6b984fcccc11977a
<ide><path>airflow/providers/google/cloud/operators/dataflow.py <ide> class DataflowCreateJavaJobOperator(BaseOperator): <ide> "labels": {"foo": "bar"}, <ide> }, <ide> gcp_conn_id="airflow-conn-id", <del> dag=my - dag, <add> dag=my_dag, <ide> ) <ide> <ide> """ <ide> class DataflowTemplatedJobStartOperator(BaseOperator): <ide> "outputFile": "gs://bucket/output/my_output.txt", <ide> }, <ide> gcp_conn_id="airflow-conn-id", <del> dag=my - dag, <add> dag=my_dag, <ide> ) <ide> <ide> ``template``, ``dataflow_default_options``, ``parameters``, and ``job_name`` are <ide><path>airflow/providers/google/cloud/transfers/s3_to_gcs.py <ide> class S3ToGCSOperator(S3ListOperator): <ide> dest_gcs="gs://my.gcs.bucket/some/customers/", <ide> replace=False, <ide> gzip=True, <del> dag=my - dag, <add> dag=my_dag, <ide> ) <ide> <ide> Note that ``bucket``, ``prefix``, ``delimiter`` and ``dest_gcs`` are
2
Java
Java
remove bad perf test
ba56962b24c9c6eb0589efb5cd414af79eb8bf22
<ide><path>rxjava-core/src/perf/java/rx/usecases/PerfTransforms.java <ide> public Boolean call(Integer t1) { <ide> input.awaitCompletion(); <ide> } <ide> <del> @GenerateMicroBenchmark <del> public void flatMapAsyncNested(final UseCaseInput input) throws InterruptedException { <del> input.observable.flatMap(new Func1<Integer, Observable<Integer>>() { <del> <del> @Override <del> public Observable<Integer> call(Integer i) { <del> return input.observable.subscribeOn(Schedulers.computation()); <del> } <del> <del> }).subscribe(input.observer); <del> input.awaitCompletion(); <del> } <del> <ide> }
1
Python
Python
fix viewsets action urls with namespaces
bda84372d445471ce4291547edf36fe683143b42
<ide><path>rest_framework/viewsets.py <ide> def reverse_action(self, url_name, *args, **kwargs): <ide> Reverse the action for the given `url_name`. <ide> """ <ide> url_name = '%s-%s' % (self.basename, url_name) <add> namespace = None <add> if self.request and self.request.resolver_match: <add> namespace = self.request.resolver_match.namespace <add> if namespace: <add> url_name = namespace + ':' + url_name <ide> kwargs.setdefault('request', self.request) <ide> <ide> return reverse(url_name, *args, **kwargs)
1
Javascript
Javascript
use umd headers to detect module loading order
2f8ae38276394ee134050095f48ace2d53d82281
<ide><path>make.js <ide> target.cmaps = function () { <ide> target.bundle = function(args) { <ide> args = args || {}; <ide> var defines = args.defines || DEFINES; <del> var excludes = args.excludes || []; <ide> <ide> target.buildnumber(); <ide> <ide> cd(ROOT_DIR); <ide> echo(); <ide> echo('### Bundling files into ' + BUILD_TARGET); <ide> <del> function bundle(filename, outfilename, SRC_FILES, EXT_SRC_FILES) { <del> for (var i = 0, length = excludes.length; i < length; ++i) { <del> var exclude = excludes[i]; <del> var index = SRC_FILES.indexOf(exclude); <del> if (index >= 0) { <del> SRC_FILES.splice(index, 1); <del> } <del> } <del> <del> var bundleContent = cat(SRC_FILES), <add> function bundle(filename, outfilename, files) { <add> var bundleContent = cat(files), <ide> bundleVersion = VERSION, <ide> bundleBuild = exec('git log --format="%h" -n 1', <ide> {silent: true}).output.replace('\n', ''); <ide> <del> crlfchecker.checkIfCrlfIsPresent(SRC_FILES); <add> crlfchecker.checkIfCrlfIsPresent(files); <ide> <ide> // Prepend a newline because stripCommentHeaders only strips comments that <ide> // follow a line feed. The file where bundleContent is inserted already <ide> target.bundle = function(args) { <ide> // Removes AMD and CommonJS branches from UMD headers. <ide> bundleContent = stripUMDHeaders(bundleContent); <ide> <del> // Append external files last since we don't want to modify them. <del> bundleContent += cat(EXT_SRC_FILES); <del> <ide> // This just preprocesses the empty pdf.js file, we don't actually want to <ide> // preprocess everything yet since other build targets use this file. <ide> builder.preprocess(filename, outfilename, builder.merge(defines, <ide> target.bundle = function(args) { <ide> mkdir(BUILD_DIR); <ide> } <ide> <del> var SHARED_SRC_FILES = [ <del> 'shared/global.js', <del> 'shared/util.js' <add> var umd = require('./external/umdutils/verifier.js'); <add> var MAIN_SRC_FILES = [ <add> SRC_DIR + 'display/annotation_layer.js', <add> SRC_DIR + 'display/metadata.js', <add> SRC_DIR + 'display/text_layer.js', <add> SRC_DIR + 'display/api.js' <ide> ]; <ide> <del> var MAIN_SRC_FILES = SHARED_SRC_FILES.concat([ <del> 'display/dom_utils.js', <del> 'display/annotation_layer.js', <del> 'display/font_loader.js', <del> 'display/metadata.js', <del> 'display/text_layer.js', <del> 'display/webgl.js', <del> 'display/pattern_helper.js', <del> 'display/canvas.js', <del> 'display/api.js', <del> 'display/svg.js' <del> ]); <del> <ide> var WORKER_SRC_FILES = [ <del> 'core/network.js', <del> 'core/arithmetic_decoder.js', <del> 'core/charsets.js', <del> 'core/glyphlist.js', <del> 'core/jpg.js', <del> 'core/metrics.js', <del> 'core/bidi.js', <del> 'core/chunked_stream.js', <del> 'core/jbig2.js', <del> 'core/jpx.js', <del> 'core/murmurhash3.js', <del> 'core/primitives.js', <del> 'core/stream.js', <del> 'core/crypto.js', <del> 'core/font_renderer.js', <del> 'core/parser.js', <del> 'core/cmap.js', <del> 'core/obj.js', <del> 'core/ps_parser.js', <del> 'core/fonts.js', <del> 'core/function.js', <del> 'core/colorspace.js', <del> 'core/image.js', <del> 'core/pattern.js', <del> 'core/evaluator.js', <del> 'core/annotation.js', <del> 'core/document.js', <del> 'core/pdf_manager.js', <del> 'core/worker.js' <add> SRC_DIR + 'core/worker.js' <ide> ]; <ide> <del> if (!defines.SINGLE_FILE) { <del> // We want shared_src_files in both pdf.js and pdf.worker.js <del> // unless it's being built in singlefile mode. <del> WORKER_SRC_FILES = SHARED_SRC_FILES.concat(WORKER_SRC_FILES); <del> } else { <add> // Extension does not need svg.js and network.js files. <add> if (!defines.FIREFOX && !defines.MOZCENTRAL) { <add> MAIN_SRC_FILES.push(SRC_DIR + 'display/svg.js'); <add> WORKER_SRC_FILES.push(SRC_DIR + 'core/network.js'); <add> } <add> <add> if (defines.SINGLE_FILE) { <ide> // In singlefile mode, all of the src files will be bundled into <del> // the main pdf.js outuput. <add> // the main pdf.js output. <ide> MAIN_SRC_FILES = MAIN_SRC_FILES.concat(WORKER_SRC_FILES); <add> WORKER_SRC_FILES = null; // no need for worker file <ide> } <ide> <del> var EXT_SRC_FILES = []; <add> // Reading UMD headers and building loading orders of modules. The <add> // readDependencies returns AMD module names: removing 'pdfjs' prefix and <add> // adding '.js' extensions to the name. <add> var mainFiles = umd.readDependencies(MAIN_SRC_FILES).loadOrder.map( <add> function (name) { return name.replace('pdfjs/', '') + '.js'; }); <add> <add> var workerFiles = WORKER_SRC_FILES && <add> umd.readDependencies(WORKER_SRC_FILES).loadOrder.map( <add> function (name) { return name.replace('pdfjs/', '') + '.js'; }); <ide> <ide> cd(SRC_DIR); <ide> <del> bundle('pdf.js', ROOT_DIR + BUILD_TARGET, MAIN_SRC_FILES, []); <del> var srcCopy = ROOT_DIR + BUILD_DIR + 'pdf.worker.js.temp'; <del> cp('pdf.js', srcCopy); <del> bundle(srcCopy, ROOT_DIR + BUILD_WORKER_TARGET, WORKER_SRC_FILES, <del> EXT_SRC_FILES); <del> rm(srcCopy); <add> bundle('pdf.js', ROOT_DIR + BUILD_TARGET, mainFiles); <add> <add> if (workerFiles) { <add> var srcCopy = ROOT_DIR + BUILD_DIR + 'pdf.worker.js.temp'; <add> cp('pdf.js', srcCopy); <add> bundle(srcCopy, ROOT_DIR + BUILD_WORKER_TARGET, workerFiles); <add> rm(srcCopy); <add> } <ide> }; <ide> <ide> // <ide> target.firefox = function() { <ide> FIREFOX_AMO_EXTENSION_NAME = 'pdf.js.amo.xpi'; <ide> <ide> target.locale(); <del> target.bundle({ excludes: ['core/network.js'], defines: defines }); <add> target.bundle({ defines: defines }); <ide> cd(ROOT_DIR); <ide> <ide> // Clear out everything in the firefox extension build directory <ide> target.mozcentral = function() { <ide> ['icon.png', <ide> 'icon64.png']; <ide> <del> target.bundle({ excludes: ['core/network.js'], defines: defines }); <add> target.bundle({ defines: defines }); <ide> cd(ROOT_DIR); <ide> <ide> // Clear out everything in the firefox extension build directory
1
Text
Text
increase visibility of glitch boilerplate (#252)
222acd4f15e6a68983e78fa905e426089c2375ab
<ide><path>packages/learn/src/introductions/apis-and-microservices/basic-node-and-express/index.md <ide> superBlock: APIs and Microservices <ide> --- <ide> ## Introduction to the Basic Node and Express Challenges <ide> <del>Node.js is a JavaScript tool that allows developers to write backend (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules&mdash;small, independent programs&mdash;that help facilitate this purpose. Some of the core modules include:<br><br><ul><li>HTTP: a module that acts as a server</li><li>File System: a module that reads and modifies files</li><li>Path: a module for working with directory and file paths</li><li>Assertion Testing: a module that checks code against prescribed constraints</li></ul><br>Express, while not included with Node.js, is another module often used with it. Express runs between the server created by Node.js and the frontend pages of a web application. Express also handles an application's routing. Routing directs users to the correct page based on their interaction with the application.<br><br>While there are alternatives to using Express, its simplicity makes it a good place to begin when learning the interaction between a backend powered by Node.js and the frontend. <del>Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public Glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing.<br>Start this project on Glitch using <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-express/'>this link</a> or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe! <add>Node.js is a JavaScript runtime that allows developers to write backend (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules - small, independent programs - that help facilitate this purpose. Some of the core modules include: <ide> <add>- HTTP: a module that acts as a server <add>- File System: a module that reads and modifies files <add>- Path: a module for working with directory and file paths <add>- Assertion Testing: a module that checks code against prescribed constraints <add> <add>Express, while not included with Node.js, is another module often used with it. Express runs between the server created by Node.js and the frontend pages of a web application. Express also handles an application's routing. Routing directs users to the correct page based on their interaction with the application. While there are alternatives to using Express, its simplicity makes it a good place to begin when learning the interaction between a backend powered by Node.js and the frontend. <add> <add>Working on these challenges will involve you writing your code on Glitch on our starter project. After completing each challenge you can copy your public Glitch url (to the homepage of your app) into the challenge screen to test it! Optionally you may choose to write your project on another platform but it must be publicly visible for our testing. <add> <add>Start this project on Glitch using the **<a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-express/'>Backend Challenges Boilerplate</a>** (required if you use Glitch) or clone <a href='https://github.com/freeCodeCamp/boilerplate-express/'>this repository</a> on GitHub! If you use Glitch, remember to save the link to your project somewhere safe!
1
Ruby
Ruby
send sigterm, not sigquit
7748d64a76ae140cb80cd54d183bc1f94c192b9d
<ide><path>railties/test/application/console_test.rb <ide> def write_prompt(command, expected_output = nil) <ide> end <ide> <ide> def kill(pid) <del> Process.kill('QUIT', pid) <add> Process.kill('TERM', pid) <ide> Process.wait(pid) <ide> rescue Errno::ESRCH <ide> end
1
Text
Text
add link to file and fix typos in model card
97f24303e83dc67756c02111ec08930cd1e05bda
<ide><path>model_cards/chrisliu298/arxiv-ai-gpt2/README.md <ide> datasets: <ide> <ide> ## Model description <ide> <del>This GPT-2 (774M) model is capable of generating abstracts given paper titles. It was trained using all research papers under aritficial intelligence (AI), machine learning (LG), computation and language (CL), and computer vision and pattern recognition (CV) on arXiv. <add>This GPT-2 (774M) model is capable of generating abstracts given paper titles. It was trained using all research paper titles and abstracts under artificial intelligence (AI), machine learning (LG), computation and language (CL), and computer vision and pattern recognition (CV) on arXiv. <ide> <ide> ## Intended uses & limitations <ide> <ide> #### How to use <ide> <del>To generate paper abstracts, use the provided `generate.py`. This file is very similar to HuggingFace's `run_generation.py` [here](https://github.com/huggingface/transformers/tree/master/examples/text-generation). You can simply replace the text with with your own model path (line 89) and change the input string to your paper title (line 127). <add>To generate paper abstracts, use the provided `generate.py` [here](https://gist.github.com/chrisliu298/ccb8144888eace069da64ad3e6472d64). This is very similar to the HuggingFace's `run_generation.py` [here](https://github.com/huggingface/transformers/tree/master/examples/text-generation). You can simply replace the text with with your own model path (line 89) and change the input string to your paper title (line 127). <ide> <ide> ## Training data <ide> I selected a subset of the [arXiv Archive](https://github.com/staeiou/arxiv_archive) dataset (Geiger, 2019) as the training and evaluation data to fine-tune GPT-2. The original arXiv Archive dataset contains a full archive of metadata about papers on arxiv.org, from the start of the site in 1993 to the end of 2019. Our subset includes all the paper titles (query) and abstracts (context) under the Artificial Intelligence (cs.AI), Machine Learning (cs.LG), Computation and Language (cs.CL), and Computer Vision and Pattern Recognition (cs.CV) categories. I provide the information of the sub-dataset and the distribution of the training and evaluation dataset as follows.
1
Text
Text
add release notes for active storage [ci skip]
47aee9af25a155d86676086eb98ba96a80da259e
<ide><path>guides/source/6_0_release_notes.md <ide> Please refer to the [Changelog][active-storage] for detailed changes. <ide> <ide> ### Deprecations <ide> <add>* Deprecate `config.active_storage.queue` in favor of `config.active_storage.queues.analysis` <add> and `config.active_storage.queues.purge`. <add> ([Pull Request](https://github.com/rails/rails/pull/34838)) <add> <add>* Deprecate `ActiveStorage::Downloading` in favor of `ActiveStorage::Blob#open`. <add> ([Commit](https://github.com/rails/rails/commit/ee21b7c2eb64def8f00887a9fafbd77b85f464f1)) <add> <add>* Deprecate using `mini_magick` directly for generating image variants in favor of <add> `image_processing`. <add> ([Commit](https://github.com/rails/rails/commit/697f4a93ad386f9fb7795f0ba68f815f16ebad0f)) <add> <add>* Deprecate `:combine_options` in Active Storage's ImageProcessing transformer <add> without replacement. <add> ([Commit](https://github.com/rails/rails/commit/697f4a93ad386f9fb7795f0ba68f815f16ebad0f)) <add> <ide> ### Notable changes <ide> <del>* Updating an attached model via `update` or `update!` with, say, <del> `@user.update!(images: [ … ])` now replaces the existing images instead of merely adding to them. <add>* Add support for generating BMP image variants. <add> ([Pull Request](https://github.com/rails/rails/pull/36051)) <add> <add>* Add support for generating TIFF image variants. <add> ([Pull Request](https://github.com/rails/rails/pull/34824)) <add> <add>* Add support for generating progressive JPEG image variants. <add> ([Pull Request](https://github.com/rails/rails/pull/34455)) <add> <add>* Add `ActiveStorage.routes_prefix` for configuring the Active Storage generated routes. <add> ([Pull Request](https://github.com/rails/rails/pull/33883)) <add> <add>* Generate a 404 Not Found response on `ActiveStorage::DiskController#show` when <add> the requested file is missing from the disk service. <add> ([Pull Request](https://github.com/rails/rails/pull/33666)) <add> <add>* Raise `ActiveStorage::FileNotFoundError` when the requested file is missing for <add> `ActiveStorage::Blob#download` and `ActiveStorage::Blob#open`. <add> ([Pull Request](https://github.com/rails/rails/pull/33666)) <add> <add>* Add a generic `ActiveStorage::Error` class that Active Storage exceptions inherit from. <add> ([Commit](https://github.com/rails/rails/commit/18425b837149bc0d50f8d5349e1091a623762d6b)) <add> <add>* Persist uploaded files assigned to a record to storage when the record <add> is saved instead of immediately. <add> ([Pull Request](https://github.com/rails/rails/pull/33303)) <add> <add>* Add the ability to reflect on defined attachments using the existing <add> Active Record reflection mechanism. <add> ([Pull Request](https://github.com/rails/rails/pull/33018)) <add> <add>* Add `ActiveStorage::Blob#open`, which downloads a blob to a tempfile on disk <add> and yields the tempfile. <add> ([Commit](https://github.com/rails/rails/commit/ee21b7c2eb64def8f00887a9fafbd77b85f464f1)) <add> <add>* Support streaming downloads from Google Cloud Storage. Require version 1.11+ <add> of the `google-cloud-storage` gem. <add> ([Pull Request](https://github.com/rails/rails/pull/32788)) <add> <add>* Use the `image_processing` gem for Active Storage variants. This replaces using <add> `mini_magick` directly. <add> ([Pull Request](https://github.com/rails/rails/pull/32471) <add> <add>* Replace existing images instead of adding to them when updating an <add> attached model via `update` or `update!` with, say, `@user.update!(images: [ … ])`. <ide> ([Pull Request](https://github.com/rails/rails/pull/33303)) <ide> <ide> Active Model
1
Javascript
Javascript
fix example and add e2e test
de4b048b4914c8c5b8d4f68a6a06f713fdf1c22d
<ide><path>src/ng/directive/input.js <ide> var requiredDirective = function() { <ide> </script> <ide> <form name="myForm" ng-controller="Ctrl"> <ide> List: <input name="namesInput" ng-model="names" ng-list required> <del> <span class="error" ng-show="myForm.list.$error.required"> <add> <span class="error" ng-show="myForm.namesInput.$error.required"> <ide> Required!</span> <add> <br> <ide> <tt>names = {{names}}</tt><br/> <ide> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <ide> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <ide> var requiredDirective = function() { <ide> it('should initialize to model', function() { <ide> expect(binding('names')).toEqual('["igor","misko","vojta"]'); <ide> expect(binding('myForm.namesInput.$valid')).toEqual('true'); <add> expect(element('span.error').css('display')).toBe('none'); <ide> }); <ide> <ide> it('should be invalid if empty', function() { <ide> input('names').enter(''); <ide> expect(binding('names')).toEqual('[]'); <ide> expect(binding('myForm.namesInput.$valid')).toEqual('false'); <add> expect(element('span.error').css('display')).not().toBe('none'); <ide> }); <ide> </doc:scenario> <ide> </doc:example>
1
Ruby
Ruby
prettify config output on 6/8-core cpus (#313)
7727c7764c9941bbe78c342dbe5b3c1a57ac5cd6
<ide><path>Library/Homebrew/hardware.rb <ide> def self.cores_as_words <ide> when 1 then "single" <ide> when 2 then "dual" <ide> when 4 then "quad" <add> when 6 then "hexa" <add> when 8 then "octa" <ide> else <ide> Hardware::CPU.cores <ide> end
1
Javascript
Javascript
change .drawcalls to .groups
5a7a681011bfcbb76a3e9264f923e4b59718db38
<ide><path>src/extras/geometries/WireframeGeometry.js <ide> THREE.WireframeGeometry = function ( geometry ) { <ide> <ide> var indices = geometry.index.array; <ide> var vertices = geometry.attributes.position; <del> var drawcalls = geometry.drawcalls; <add> var groups = geometry.groups; <ide> var numEdges = 0; <ide> <del> if ( drawcalls.length === 0 ) { <add> if ( groups.length === 0 ) { <ide> <ide> geometry.addGroup( 0, indices.length ); <ide> <ide> THREE.WireframeGeometry = function ( geometry ) { <ide> // allocate maximal size <ide> var edges = new Uint32Array( 2 * indices.length ); <ide> <del> for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) { <add> for ( var o = 0, ol = groups.length; o < ol; ++ o ) { <ide> <del> var drawcall = drawcalls[ o ]; <add> var group = groups[ o ]; <ide> <del> var start = drawcall.start; <del> var count = drawcall.count; <add> var start = group.start; <add> var count = group.count; <ide> <ide> for ( var i = start, il = start + count; i < il; i += 3 ) { <ide>
1
Text
Text
add example code for worker.isdead() to cluster.md
e2d445be8f5f786a7b3b6dc1724fc6080cb37b8c
<ide><path>doc/api/cluster.md <ide> added: v0.11.14 <ide> This function returns `true` if the worker's process has terminated (either <ide> because of exiting or being signaled). Otherwise, it returns `false`. <ide> <add>```js <add>const cluster = require('cluster'); <add>const http = require('http'); <add>const numCPUs = require('os').cpus().length; <add> <add>if (cluster.isMaster) { <add> console.log(`Master ${process.pid} is running`); <add> <add> // Fork workers. <add> for (let i = 0; i < numCPUs; i++) { <add> cluster.fork(); <add> } <add> <add> cluster.on('fork', (worker) => { <add> console.log('worker is dead:', worker.isDead()); <add> }); <add> <add> cluster.on('exit', (worker, code, signal) => { <add> console.log('worker is dead:', worker.isDead()); <add> }); <add> <add>} else { <add> // Workers can share any TCP connection <add> // In this case it is an HTTP server <add> http.createServer((req, res) => { <add> res.writeHead(200); <add> res.end(`Current process\n ${process.pid}`); <add> process.kill(process.pid); <add> }).listen(8000); <add> <add> // Make http://localhost:8000 to ckeck isDead method. <add>} <add> <add>``` <add> <ide> ### worker.kill([signal='SIGTERM']) <ide> <!-- YAML <ide> added: v0.9.12
1
Mixed
Java
add timeinterval & timestamp to m/s
d5449b2fd63c73dea06fbbd5d584bab7b9cfde5d
<ide><path>docs/Operator-Matrix.md <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> <a name='defer'></a>`defer`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='delay'></a>`delay`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='delaySubscription'></a>`delaySubscription`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='dematerialize'></a>`dematerialize`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <add><a name='dematerialize'></a>`dematerialize`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='distinct'></a>`distinct`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item, always distinct.'>([39](#notes-39))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item, always distinct.'>([39](#notes-39))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='distinctUntilChanged'></a>`distinctUntilChanged`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item, always distinct.'>([39](#notes-39))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item, always distinct.'>([39](#notes-39))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='doAfterNext'></a>`doAfterNext`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Different terminology. Use doAfterSuccess().'>([40](#notes-40))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Different terminology. Use doAfterSuccess().'>([40](#notes-40))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty.'>([2](#notes-2))</sup>| <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> <a name='throttleLast'></a>`throttleLast`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='throttleLatest'></a>`throttleLatest`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='throttleWithTimeout'></a>`throttleWithTimeout`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item signaled so no subsequent items to work with.'>([36](#notes-36))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <del><a name='timeInterval'></a>`timeInterval`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)| <add><a name='timeInterval'></a>`timeInterval`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='timeout'></a>`timeout`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='timer'></a>`timer`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='timestamp'></a>`timestamp`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <add><a name='timestamp'></a>`timestamp`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to work with.'>([37](#notes-37))</sup>| <ide> <a name='to'></a>`to`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='toCompletionStage'></a>`toCompletionStage`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use firstStage.'>([98](#notes-98))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use firstStage.'>([98](#notes-98))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='toFlowable'></a>`toFlowable`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Would be no-op.'>([99](#notes-99))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> <a name='zip'></a>`zip`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use merge().'>([108](#notes-108))</sup>| <ide> <a name='zipArray'></a>`zipArray`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use mergeArray().'>([109](#notes-109))</sup>| <ide> <a name='zipWith'></a>`zipWith`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use mergeWith().'>([110](#notes-110))</sup>| <del><a name='total'></a>**237 operators** | **215** | **209** | **108** | **93** | **76** | <add><a name='total'></a>**237 operators** | **215** | **209** | **111** | **95** | **76** | <ide> <ide> #### Notes <ide> <a name='notes-1'></a><sup>1</sup> Use [`contains()`](#contains).<br/> <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> 17. Single.concatMapMaybe() <ide> 18. Maybe.concatMapSingle() <ide> 19. Single.concatMapSingle() <del>20. Maybe.dematerialize() <del>21. Maybe.doOnLifecycle() <del>22. Single.doOnLifecycle() <del>23. Completable.doOnLifecycle() <del>24. Single.mergeArray() <del>25. Single.mergeArrayDelayError() <del>26. Single.ofType() <del>27. Completable.onErrorReturn() <del>28. Completable.onErrorReturnItem() <del>29. Maybe.safeSubscribe() <del>30. Single.safeSubscribe() <del>31. Completable.safeSubscribe() <del>32. Completable.sequenceEqual() <del>33. Maybe.startWith() <del>34. Single.startWith() <del>35. Maybe.timeInterval() <del>36. Single.timeInterval() <del>37. Completable.timeInterval() <del>38. Maybe.timestamp() <del>39. Single.timestamp() <del>40. Maybe.toFuture() <del>41. Completable.toFuture() <add>20. Maybe.doOnLifecycle() <add>21. Single.doOnLifecycle() <add>22. Completable.doOnLifecycle() <add>23. Single.mergeArray() <add>24. Single.mergeArrayDelayError() <add>25. Single.ofType() <add>26. Completable.onErrorReturn() <add>27. Completable.onErrorReturnItem() <add>28. Maybe.safeSubscribe() <add>29. Single.safeSubscribe() <add>30. Completable.safeSubscribe() <add>31. Completable.sequenceEqual() <add>32. Maybe.startWith() <add>33. Single.startWith() <add>34. Maybe.toFuture() <add>35. Completable.toFuture() <ide><path>src/main/java/io/reactivex/rxjava3/core/Maybe.java <ide> import io.reactivex.rxjava3.internal.util.ErrorMode; <ide> import io.reactivex.rxjava3.observers.TestObserver; <ide> import io.reactivex.rxjava3.plugins.RxJavaPlugins; <del>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.schedulers.*; <ide> <ide> /** <ide> * The {@code Maybe} class represents a deferred computation and emission of a single value, no value at all or an exception. <ide> public final <U> Maybe<T> takeUntil(@NonNull Publisher<U> other) { <ide> return RxJavaPlugins.onAssembly(new MaybeTakeUntilPublisher<>(this, other)); <ide> } <ide> <add> /** <add> * Measures the time (in milliseconds) between the subscription and success item emission <add> * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timeInterval()}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @return the new {@code Maybe} instance <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Maybe<Timed<T>> timeInterval() { <add> return timeInterval(TimeUnit.MILLISECONDS, Schedulers.computation()); <add> } <add> <add> /** <add> * Measures the time (in milliseconds) between the subscription and success item emission <add> * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.s.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timeInterval(Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the provided {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Maybe<Timed<T>> timeInterval(@NonNull Scheduler scheduler) { <add> return timeInterval(TimeUnit.MILLISECONDS, scheduler); <add> } <add> <add> /** <add> * Measures the time between the subscription and success item emission <add> * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timeInterval(TimeUnit)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code unit} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Maybe<Timed<T>> timeInterval(@NonNull TimeUnit unit) { <add> return timeInterval(unit, Schedulers.computation()); <add> } <add> <add> /** <add> * Measures the time between the subscription and success item emission <add> * of the current {@code Maybe} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timeInterval.s.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timeInterval(TimeUnit, Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the provided {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Maybe<Timed<T>> timeInterval(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { <add> Objects.requireNonNull(unit, "unit is null"); <add> Objects.requireNonNull(scheduler, "scheduler is null"); <add> return RxJavaPlugins.onAssembly(new MaybeTimeInterval<>(this, unit, scheduler, true)); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Maybe} with the current time (in milliseconds) of <add> * its reception, using the {@code computation} {@link Scheduler} as time source, <add> * then signals them as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timestamp()}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler} <add> * for determining the current time upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @return the new {@code Maybe} instance <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Maybe<Timed<T>> timestamp() { <add> return timestamp(TimeUnit.MILLISECONDS, Schedulers.computation()); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Maybe} with the current time (in milliseconds) of <add> * its reception, using the given {@link Scheduler} as time source, <add> * then signals them as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.s.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timestamp(Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the provided {@code Scheduler} <add> * for determining the current time upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Maybe<Timed<T>> timestamp(@NonNull Scheduler scheduler) { <add> return timestamp(TimeUnit.MILLISECONDS, scheduler); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Maybe} with the current time of <add> * its reception, using the {@code computation} {@link Scheduler} as time source, <add> * then signals it as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="352" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timestamp(TimeUnit)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler}, <add> * for determining the current time upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code unit} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Maybe<Timed<T>> timestamp(@NonNull TimeUnit unit) { <add> return timestamp(unit, Schedulers.computation()); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Maybe} with the current time of <add> * its reception, using the given {@link Scheduler} as time source, <add> * then signals it as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="355" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.timestamp.s.png" alt=""> <add> * <p> <add> * If the current {@code Maybe} is empty or fails, the resulting {@code Maybe} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link Single#timestamp(TimeUnit, Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the provided {@code Scheduler}, <add> * which is used for determining the current time upon receiving the <add> * success item from the current {@code Maybe}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Maybe<Timed<T>> timestamp(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { <add> Objects.requireNonNull(unit, "unit is null"); <add> Objects.requireNonNull(scheduler, "scheduler is null"); <add> return RxJavaPlugins.onAssembly(new MaybeTimeInterval<>(this, unit, scheduler, false)); <add> } <add> <ide> /** <ide> * Returns a {@code Maybe} that mirrors the current {@code Maybe} but applies a timeout policy for each emitted <ide> * item. If the next item isn't emitted within the specified timeout duration starting from its predecessor, <ide><path>src/main/java/io/reactivex/rxjava3/core/Single.java <ide> import io.reactivex.rxjava3.internal.util.ErrorMode; <ide> import io.reactivex.rxjava3.observers.TestObserver; <ide> import io.reactivex.rxjava3.plugins.RxJavaPlugins; <del>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.schedulers.*; <ide> <ide> /** <ide> * The {@code Single} class implements the Reactive Pattern for a single value response. <ide> public final Single<T> subscribeOn(@NonNull Scheduler scheduler) { <ide> return RxJavaPlugins.onAssembly(new SingleSubscribeOn<>(this, scheduler)); <ide> } <ide> <add> /** <add> * Measures the time (in milliseconds) between the subscription and success item emission <add> * of the current {@code Single} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="466" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeInterval.png" alt=""> <add> * <p> <add> * If the current {@code Single} fails, the resulting {@code Single} will <add> * pass along the signal to the downstream. To measure the time to error, <add> * use {@link #materialize()} and apply {@link #timeInterval()}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @return the new {@code Single} instance <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Single<Timed<T>> timeInterval() { <add> return timeInterval(TimeUnit.MILLISECONDS, Schedulers.computation()); <add> } <add> <add> /** <add> * Measures the time (in milliseconds) between the subscription and success item emission <add> * of the current {@code Single} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeInterval.s.png" alt=""> <add> * <p> <add> * If the current {@code Single} fails, the resulting {@code Single} will <add> * pass along the signal to the downstream. To measure the time to error, <add> * use {@link #materialize()} and apply {@link #timeInterval(Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the provided {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Single<Timed<T>> timeInterval(@NonNull Scheduler scheduler) { <add> return timeInterval(TimeUnit.MILLISECONDS, scheduler); <add> } <add> <add> /** <add> * Measures the time between the subscription and success item emission <add> * of the current {@code Single} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="466" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeInterval.png" alt=""> <add> * <p> <add> * If the current {@code Single} fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To measure the time to error, <add> * use {@link #materialize()} and apply {@link #timeInterval(TimeUnit, Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the {@code computation} {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code unit} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Single<Timed<T>> timeInterval(@NonNull TimeUnit unit) { <add> return timeInterval(unit, Schedulers.computation()); <add> } <add> <add> /** <add> * Measures the time between the subscription and success item emission <add> * of the current {@code Single} and signals it as a tuple ({@link Timed}) <add> * success value. <add> * <p> <add> * <img width="640" height="463" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeInterval.s.png" alt=""> <add> * <p> <add> * If the current {@code Single} is empty or fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To measure the time to termination, <add> * use {@link #materialize()} and apply {@link #timeInterval(TimeUnit, Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timeInterval} uses the provided {@link Scheduler} <add> * for determining the current time upon subscription and upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Single<Timed<T>> timeInterval(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { <add> Objects.requireNonNull(unit, "unit is null"); <add> Objects.requireNonNull(scheduler, "scheduler is null"); <add> return RxJavaPlugins.onAssembly(new SingleTimeInterval<>(this, unit, scheduler, true)); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Single} with the current time (in milliseconds) of <add> * its reception, using the {@code computation} {@link Scheduler} as time source, <add> * then signals them as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="465" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timestamp.png" alt=""> <add> * <p> <add> * If the current {@code Single} is empty or fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To get the timestamp of the error, <add> * use {@link #materialize()} and apply {@link #timestamp()}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler} <add> * for determining the current time upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @return the new {@code Single} instance <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Single<Timed<T>> timestamp() { <add> return timestamp(TimeUnit.MILLISECONDS, Schedulers.computation()); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Single} with the current time (in milliseconds) of <add> * its reception, using the given {@link Scheduler} as time source, <add> * then signals them as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="465" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timestamp.s.png" alt=""> <add> * <p> <add> * If the current {@code Single} is empty or fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To get the timestamp of the error, <add> * use {@link #materialize()} and apply {@link #timestamp(Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the provided {@code Scheduler} <add> * for determining the current time upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Single<Timed<T>> timestamp(@NonNull Scheduler scheduler) { <add> return timestamp(TimeUnit.MILLISECONDS, scheduler); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Single} with the current time of <add> * its reception, using the {@code computation} {@link Scheduler} as time source, <add> * then signals it as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="465" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timestamp.png" alt=""> <add> * <p> <add> * If the current {@code Single} is empty or fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To get the timestamp of the error, <add> * use {@link #materialize()} and apply {@link #timestamp(TimeUnit)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the {@code computation} {@code Scheduler}, <add> * for determining the current time upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code unit} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.COMPUTATION) <add> public final Single<Timed<T>> timestamp(@NonNull TimeUnit unit) { <add> return timestamp(unit, Schedulers.computation()); <add> } <add> <add> /** <add> * Combines the success value from the current {@code Single} with the current time of <add> * its reception, using the given {@link Scheduler} as time source, <add> * then signals it as a {@link Timed} instance. <add> * <p> <add> * <img width="640" height="465" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timestamp.s.png" alt=""> <add> * <p> <add> * If the current {@code Single} is empty or fails, the resulting {@code Single} will <add> * pass along the signals to the downstream. To get the timestamp of the error, <add> * use {@link #materialize()} and apply {@link #timestamp(TimeUnit, Scheduler)}. <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code timestamp} uses the provided {@code Scheduler}, <add> * which is used for determining the current time upon receiving the <add> * success item from the current {@code Single}.</dd> <add> * </dl> <add> * @param unit the time unit for measurement <add> * @param scheduler the {@code Scheduler} used for providing the current time <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.CUSTOM) <add> public final Single<Timed<T>> timestamp(@NonNull TimeUnit unit, @NonNull Scheduler scheduler) { <add> Objects.requireNonNull(unit, "unit is null"); <add> Objects.requireNonNull(scheduler, "scheduler is null"); <add> return RxJavaPlugins.onAssembly(new SingleTimeInterval<>(this, unit, scheduler, false)); <add> } <add> <ide> /** <ide> * Returns a {@code Single} that emits the item emitted by the current {@code Single} until a {@link CompletableSource} terminates. Upon <ide> * termination of {@code other}, this will emit a {@link CancellationException} rather than go to <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimeInterval.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.maybe; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import io.reactivex.rxjava3.annotations.NonNull; <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.disposables.Disposable; <add>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <add>import io.reactivex.rxjava3.schedulers.Timed; <add> <add>/** <add> * Measures the time between subscription and the success item emission <add> * from the upstream and emits this as a {@link Timed} success value. <add> * @param <T> the element type of the sequence <add> * @since 3.0.0 <add> */ <add>public final class MaybeTimeInterval<T> extends Maybe<Timed<T>> { <add> <add> final MaybeSource<T> source; <add> <add> final TimeUnit unit; <add> <add> final Scheduler scheduler; <add> <add> final boolean start; <add> <add> public MaybeTimeInterval(MaybeSource<T> source, TimeUnit unit, Scheduler scheduler, boolean start) { <add> this.source = source; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> this.start = start; <add> } <add> <add> @Override <add> protected void subscribeActual(@NonNull MaybeObserver<? super @NonNull Timed<T>> observer) { <add> source.subscribe(new TimeIntervalMaybeObserver<>(observer, unit, scheduler, start)); <add> } <add> <add> static final class TimeIntervalMaybeObserver<T> implements MaybeObserver<T>, Disposable { <add> <add> final MaybeObserver<? super Timed<T>> downstream; <add> <add> final TimeUnit unit; <add> <add> final Scheduler scheduler; <add> <add> final long startTime; <add> <add> Disposable upstream; <add> <add> TimeIntervalMaybeObserver(MaybeObserver<? super Timed<T>> downstream, TimeUnit unit, Scheduler scheduler, boolean start) { <add> this.downstream = downstream; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> this.startTime = start ? scheduler.now(unit) : 0L; <add> } <add> <add> @Override <add> public void onSubscribe(@NonNull Disposable d) { <add> if (DisposableHelper.validate(this.upstream, d)) { <add> this.upstream = d; <add> <add> downstream.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onSuccess(@NonNull T t) { <add> downstream.onSuccess(new Timed<>(t, scheduler.now(unit) - startTime, unit)); <add> } <add> <add> @Override <add> public void onError(@NonNull Throwable e) { <add> downstream.onError(e); <add> } <add> <add> @Override <add> public void onComplete() { <add> downstream.onComplete(); <add> } <add> <add> @Override <add> public void dispose() { <add> upstream.dispose(); <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return upstream.isDisposed(); <add> } <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/single/SingleTimeInterval.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.single; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import io.reactivex.rxjava3.annotations.NonNull; <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.disposables.Disposable; <add>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <add>import io.reactivex.rxjava3.schedulers.Timed; <add> <add>/** <add> * Measures the time between subscription and the success item emission <add> * from the upstream and emits this as a {@link Timed} success value. <add> * @param <T> the element type of the sequence <add> * @since 3.0.0 <add> */ <add>public final class SingleTimeInterval<T> extends Single<Timed<T>> { <add> <add> final SingleSource<T> source; <add> <add> final TimeUnit unit; <add> <add> final Scheduler scheduler; <add> <add> final boolean start; <add> <add> public SingleTimeInterval(SingleSource<T> source, TimeUnit unit, Scheduler scheduler, boolean start) { <add> this.source = source; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> this.start = start; <add> } <add> <add> @Override <add> protected void subscribeActual(@NonNull SingleObserver<? super @NonNull Timed<T>> observer) { <add> source.subscribe(new TimeIntervalSingleObserver<>(observer, unit, scheduler, start)); <add> } <add> <add> static final class TimeIntervalSingleObserver<T> implements SingleObserver<T>, Disposable { <add> <add> final SingleObserver<? super Timed<T>> downstream; <add> <add> final TimeUnit unit; <add> <add> final Scheduler scheduler; <add> <add> final long startTime; <add> <add> Disposable upstream; <add> <add> TimeIntervalSingleObserver(SingleObserver<? super Timed<T>> downstream, TimeUnit unit, Scheduler scheduler, boolean start) { <add> this.downstream = downstream; <add> this.unit = unit; <add> this.scheduler = scheduler; <add> this.startTime = start ? scheduler.now(unit) : 0L; <add> } <add> <add> @Override <add> public void onSubscribe(@NonNull Disposable d) { <add> if (DisposableHelper.validate(this.upstream, d)) { <add> this.upstream = d; <add> <add> downstream.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onSuccess(@NonNull T t) { <add> downstream.onSuccess(new Timed<>(t, scheduler.now(unit) - startTime, unit)); <add> } <add> <add> @Override <add> public void onError(@NonNull Throwable e) { <add> downstream.onError(e); <add> } <add> <add> @Override <add> public void dispose() { <add> upstream.dispose(); <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return upstream.isDisposed(); <add> } <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/schedulers/Timed.java <ide> * @param value the value to hold <ide> * @param time the time to hold <ide> * @param unit the time unit, not null <del> * @throws NullPointerException if unit is {@code null} <add> * @throws NullPointerException if {@code value} or {@code unit} is {@code null} <ide> */ <ide> public Timed(@NonNull T value, long time, @NonNull TimeUnit unit) { <del> this.value = value; <add> this.value = Objects.requireNonNull(value, "value is null"); <ide> this.time = time; <ide> this.unit = Objects.requireNonNull(unit, "unit is null"); <ide> } <ide> public boolean equals(Object other) { <ide> <ide> @Override <ide> public int hashCode() { <del> int h = value != null ? value.hashCode() : 0; <add> int h = value.hashCode(); <ide> h = h * 31 + (int)((time >>> 31) ^ time); <ide> h = h * 31 + unit.hashCode(); <ide> return h; <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimeIntervalTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.maybe; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.Maybe; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.schedulers.*; <add>import io.reactivex.rxjava3.subjects.MaybeSubject; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add> <add>public class MaybeTimeIntervalTest { <add> <add> @Test <add> public void just() { <add> Maybe.just(1) <add> .timeInterval() <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void empty() { <add> Maybe.empty() <add> .timeInterval() <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void error() { <add> Maybe.error(new TestException()) <add> .timeInterval() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void justSeconds() { <add> Maybe.just(1) <add> .timeInterval(TimeUnit.SECONDS) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justScheduler() { <add> Maybe.just(1) <add> .timeInterval(Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justSecondsScheduler() { <add> Maybe.just(1) <add> .timeInterval(TimeUnit.SECONDS, Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeMaybe(m -> m.timeInterval()); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(MaybeSubject.create().timeInterval()); <add> } <add> <add> @Test <add> public void timeInfo() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> MaybeSubject<Integer> ms = MaybeSubject.create(); <add> <add> TestObserver<Timed<Integer>> to = ms <add> .timeInterval(scheduler) <add> .test(); <add> <add> scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); <add> <add> ms.onSuccess(1); <add> <add> to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS)); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimestampTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.maybe; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.Maybe; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.schedulers.*; <add>import io.reactivex.rxjava3.subjects.MaybeSubject; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add> <add>public class MaybeTimestampTest { <add> <add> @Test <add> public void just() { <add> Maybe.just(1) <add> .timestamp() <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void empty() { <add> Maybe.empty() <add> .timestamp() <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void error() { <add> Maybe.error(new TestException()) <add> .timestamp() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void justSeconds() { <add> Maybe.just(1) <add> .timestamp(TimeUnit.SECONDS) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justScheduler() { <add> Maybe.just(1) <add> .timestamp(Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justSecondsScheduler() { <add> Maybe.just(1) <add> .timestamp(TimeUnit.SECONDS, Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeMaybe(m -> m.timestamp()); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(MaybeSubject.create().timestamp()); <add> } <add> <add> @Test <add> public void timeInfo() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> MaybeSubject<Integer> ms = MaybeSubject.create(); <add> <add> TestObserver<Timed<Integer>> to = ms <add> .timestamp(scheduler) <add> .test(); <add> <add> scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); <add> <add> ms.onSuccess(1); <add> <add> to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS)); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleTimeIntervalTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.single; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.Single; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.schedulers.*; <add>import io.reactivex.rxjava3.subjects.SingleSubject; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add> <add>public class SingleTimeIntervalTest { <add> <add> @Test <add> public void just() { <add> Single.just(1) <add> .timestamp() <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void error() { <add> Single.error(new TestException()) <add> .timestamp() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void justSeconds() { <add> Single.just(1) <add> .timestamp(TimeUnit.SECONDS) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justScheduler() { <add> Single.just(1) <add> .timestamp(Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justSecondsScheduler() { <add> Single.just(1) <add> .timestamp(TimeUnit.SECONDS, Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeSingle(m -> m.timestamp()); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(SingleSubject.create().timestamp()); <add> } <add> <add> @Test <add> public void timeInfo() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> SingleSubject<Integer> ss = SingleSubject.create(); <add> <add> TestObserver<Timed<Integer>> to = ss <add> .timestamp(scheduler) <add> .test(); <add> <add> scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); <add> <add> ss.onSuccess(1); <add> <add> to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS)); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleTimestampTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. 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 distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.single; <add> <add>import java.util.concurrent.TimeUnit; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.Single; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.schedulers.*; <add>import io.reactivex.rxjava3.subjects.SingleSubject; <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add> <add>public class SingleTimestampTest { <add> <add> @Test <add> public void just() { <add> Single.just(1) <add> .timeInterval() <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void error() { <add> Single.error(new TestException()) <add> .timeInterval() <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void justSeconds() { <add> Single.just(1) <add> .timeInterval(TimeUnit.SECONDS) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justScheduler() { <add> Single.just(1) <add> .timeInterval(Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void justSecondsScheduler() { <add> Single.just(1) <add> .timeInterval(TimeUnit.SECONDS, Schedulers.single()) <add> .test() <add> .assertValueCount(1) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeSingle(m -> m.timeInterval()); <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(SingleSubject.create().timeInterval()); <add> } <add> <add> @Test <add> public void timeInfo() { <add> TestScheduler scheduler = new TestScheduler(); <add> <add> SingleSubject<Integer> ss = SingleSubject.create(); <add> <add> TestObserver<Timed<Integer>> to = ss <add> .timeInterval(scheduler) <add> .test(); <add> <add> scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); <add> <add> ss.onSuccess(1); <add> <add> to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS)); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/util/OperatorMatrixGenerator.java <ide> static String findNotes(String clazzName, String operatorName) { <ide> " C throttleLatest Always empty thus no items to work with.", <ide> " MS throttleWithTimeout At most one item signaled so no subsequent items to work with.", <ide> " C throttleWithTimeout Always empty thus no items to work with.", <add> " C timeInterval Always empty thus no items to work with.", <ide> " C timestamp Always empty thus no items to work with.", <ide> "FO toCompletionStage Use [`firstStage`](#firstStage), [`lastStage`](#lastStage) or [`singleStage`](#singleStage).", <ide> "F toFlowable Would be no-op.", <ide><path>src/test/java/io/reactivex/rxjava3/schedulers/TimedTest.java <ide> public void hashCodeOf() { <ide> <ide> assertEquals(TimeUnit.SECONDS.hashCode() + 31 * (5 + 31 * 1), t1.hashCode()); <ide> <del> Timed<Integer> t2 = new Timed<>(null, 5, TimeUnit.SECONDS); <add> Timed<Integer> t2 = new Timed<>(0, 5, TimeUnit.SECONDS); <ide> <ide> assertEquals(TimeUnit.SECONDS.hashCode() + 31 * (5 + 31 * 0), t2.hashCode()); <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/validators/JavadocWording.java <ide> public void maybeDocRefersToMaybeTypes() throws Exception { <ide> jdx = 0; <ide> for (;;) { <ide> int idx = m.javadoc.indexOf("Single", jdx); <del> if (idx >= 0) { <add> if (idx >= 0 && m.javadoc.indexOf("Single#", jdx) != idx) { <ide> int j = m.javadoc.indexOf("#toSingle", jdx); <ide> int k = m.javadoc.indexOf("{@code Single", jdx); <ide> if (!m.signature.contains("Single") && (j + 3 != idx && k + 7 != idx)) { <ide> e.append("java.lang.RuntimeException: Maybe doc mentions Single but not in the signature\r\n at io.reactivex.rxjava3.core.") <del> .append("Maybe(Maybe.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); <add> .append("Maybe.method(Maybe.java:").append(m.javadocLine + lineNumber(m.javadoc, idx) - 1).append(")\r\n\r\n"); <ide> } <ide> jdx = idx + 6; <ide> } else {
13
Java
Java
remove deprecated socketutils
2cee63491d1fbb6e21a9044715d98838fec9a51b
<ide><path>spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java <ide> import org.junit.jupiter.api.Test; <ide> <ide> import org.springframework.aop.framework.ProxyFactory; <add>import org.springframework.core.testfixture.net.TestSocketUtils; <ide> import org.springframework.jmx.AbstractMBeanServerTests; <ide> import org.springframework.jmx.IJmxTestBean; <ide> import org.springframework.jmx.JmxTestBean; <ide> void lazyConnectionToRemote() throws Exception { <ide> assumeTrue(runTests); <ide> <ide> @SuppressWarnings("deprecation") <del> final int port = org.springframework.util.SocketUtils.findAvailableTcpPort(); <add> final int port = TestSocketUtils.findAvailableTcpPort(); <ide> <ide> JMXServiceURL url = new JMXServiceURL("service:jmx:jmxmp://localhost:" + port); <ide> JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer()); <ide><path>spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java <ide> <ide> import org.junit.jupiter.api.AfterEach; <ide> <add>import org.springframework.core.testfixture.net.TestSocketUtils; <add> <ide> /** <ide> * @author Rob Harrop <ide> * @author Chris Beams <ide> class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTests { <ide> <ide> @SuppressWarnings("deprecation") <del> private final int servicePort = org.springframework.util.SocketUtils.findAvailableTcpPort(); <add> private final int servicePort = TestSocketUtils.findAvailableTcpPort(); <ide> <ide> private final String serviceUrl = "service:jmx:jmxmp://localhost:" + servicePort; <ide> <ide><path>spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java <ide> <ide> import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.core.testfixture.net.TestSocketUtils; <ide> import org.springframework.jmx.AbstractMBeanServerTests; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { <ide> private static final String OBJECT_NAME = "spring:type=connector,name=test"; <ide> <ide> @SuppressWarnings("deprecation") <del> private final String serviceUrl = "service:jmx:jmxmp://localhost:" + org.springframework.util.SocketUtils.findAvailableTcpPort(); <add> private final String serviceUrl = "service:jmx:jmxmp://localhost:" + TestSocketUtils.findAvailableTcpPort(); <ide> <ide> <ide> @Test <ide><path>spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java <ide> import org.junit.jupiter.api.Test; <ide> <ide> import org.springframework.aop.support.AopUtils; <add>import org.springframework.core.testfixture.net.TestSocketUtils; <ide> import org.springframework.jmx.AbstractMBeanServerTests; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTests { <ide> <ide> @SuppressWarnings("deprecation") <del> private final String serviceUrl = "service:jmx:jmxmp://localhost:" + org.springframework.util.SocketUtils.findAvailableTcpPort(); <add> private final String serviceUrl = "service:jmx:jmxmp://localhost:" + TestSocketUtils.findAvailableTcpPort(); <ide> <ide> <ide> @Test <ide><path>spring-core/src/main/java/org/springframework/util/SocketUtils.java <del>/* <del> * Copyright 2002-2022 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> * https://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.util; <del> <del>import java.net.DatagramSocket; <del>import java.net.InetAddress; <del>import java.net.ServerSocket; <del>import java.util.Random; <del>import java.util.SortedSet; <del>import java.util.TreeSet; <del> <del>import javax.net.ServerSocketFactory; <del> <del>/** <del> * Simple utility methods for working with network sockets &mdash; for example, <del> * for finding available ports on {@code localhost}. <del> * <del> * <p>Within this class, a TCP port refers to a port for a {@link ServerSocket}; <del> * whereas, a UDP port refers to a port for a {@link DatagramSocket}. <del> * <del> * <p>{@code SocketUtils} was introduced in Spring Framework 4.0, primarily to <del> * assist in writing integration tests which start an external server on an <del> * available random port. However, these utilities make no guarantee about the <del> * subsequent availability of a given port and are therefore unreliable. Instead <del> * of using {@code SocketUtils} to find an available local port for a server, it <del> * is recommended that you rely on a server's ability to start on a random port <del> * that it selects or is assigned by the operating system. To interact with that <del> * server, you should query the server for the port it is currently using. <del> * <del> * @author Sam Brannen <del> * @author Ben Hale <del> * @author Arjen Poutsma <del> * @author Gunnar Hillert <del> * @author Gary Russell <del> * @since 4.0 <del> * @deprecated as of Spring Framework 5.3.16, to be removed in 6.0; see <del> * {@link SocketUtils class-level Javadoc} for details. <del> */ <del>@Deprecated <del>public class SocketUtils { <del> <del> /** <del> * The default minimum value for port ranges used when finding an available <del> * socket port. <del> */ <del> public static final int PORT_RANGE_MIN = 1024; <del> <del> /** <del> * The default maximum value for port ranges used when finding an available <del> * socket port. <del> */ <del> public static final int PORT_RANGE_MAX = 65535; <del> <del> <del> private static final Random random = new Random(System.nanoTime()); <del> <del> <del> /** <del> * Although {@code SocketUtils} consists solely of static utility methods, <del> * this constructor is intentionally {@code public}. <del> * <h4>Rationale</h4> <del> * <p>Static methods from this class may be invoked from within XML <del> * configuration files using the Spring Expression Language (SpEL) and the <del> * following syntax. <del> * <pre><code>&lt;bean id="bean1" ... p:port="#{T(org.springframework.util.SocketUtils).findAvailableTcpPort(12000)}" /&gt;</code></pre> <del> * If this constructor were {@code private}, you would be required to supply <del> * the fully qualified class name to SpEL's {@code T()} function for each usage. <del> * Thus, the fact that this constructor is {@code public} allows you to reduce <del> * boilerplate configuration with SpEL as can be seen in the following example. <del> * <pre><code>&lt;bean id="socketUtils" class="org.springframework.util.SocketUtils" /&gt; <del> * &lt;bean id="bean1" ... p:port="#{socketUtils.findAvailableTcpPort(12000)}" /&gt; <del> * &lt;bean id="bean2" ... p:port="#{socketUtils.findAvailableTcpPort(30000)}" /&gt;</code></pre> <del> */ <del> public SocketUtils() { <del> } <del> <del> <del> /** <del> * Find an available TCP port randomly selected from the range <del> * [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. <del> * @return an available TCP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableTcpPort() { <del> return findAvailableTcpPort(PORT_RANGE_MIN); <del> } <del> <del> /** <del> * Find an available TCP port randomly selected from the range <del> * [{@code minPort}, {@value #PORT_RANGE_MAX}]. <del> * @param minPort the minimum port number <del> * @return an available TCP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableTcpPort(int minPort) { <del> return findAvailableTcpPort(minPort, PORT_RANGE_MAX); <del> } <del> <del> /** <del> * Find an available TCP port randomly selected from the range <del> * [{@code minPort}, {@code maxPort}]. <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return an available TCP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableTcpPort(int minPort, int maxPort) { <del> return SocketType.TCP.findAvailablePort(minPort, maxPort); <del> } <del> <del> /** <del> * Find the requested number of available TCP ports, each randomly selected <del> * from the range [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. <del> * @param numRequested the number of available ports to find <del> * @return a sorted set of available TCP port numbers <del> * @throws IllegalStateException if the requested number of available ports could not be found <del> */ <del> public static SortedSet<Integer> findAvailableTcpPorts(int numRequested) { <del> return findAvailableTcpPorts(numRequested, PORT_RANGE_MIN, PORT_RANGE_MAX); <del> } <del> <del> /** <del> * Find the requested number of available TCP ports, each randomly selected <del> * from the range [{@code minPort}, {@code maxPort}]. <del> * @param numRequested the number of available ports to find <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return a sorted set of available TCP port numbers <del> * @throws IllegalStateException if the requested number of available ports could not be found <del> */ <del> public static SortedSet<Integer> findAvailableTcpPorts(int numRequested, int minPort, int maxPort) { <del> return SocketType.TCP.findAvailablePorts(numRequested, minPort, maxPort); <del> } <del> <del> /** <del> * Find an available UDP port randomly selected from the range <del> * [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. <del> * @return an available UDP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableUdpPort() { <del> return findAvailableUdpPort(PORT_RANGE_MIN); <del> } <del> <del> /** <del> * Find an available UDP port randomly selected from the range <del> * [{@code minPort}, {@value #PORT_RANGE_MAX}]. <del> * @param minPort the minimum port number <del> * @return an available UDP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableUdpPort(int minPort) { <del> return findAvailableUdpPort(minPort, PORT_RANGE_MAX); <del> } <del> <del> /** <del> * Find an available UDP port randomly selected from the range <del> * [{@code minPort}, {@code maxPort}]. <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return an available UDP port number <del> * @throws IllegalStateException if no available port could be found <del> */ <del> public static int findAvailableUdpPort(int minPort, int maxPort) { <del> return SocketType.UDP.findAvailablePort(minPort, maxPort); <del> } <del> <del> /** <del> * Find the requested number of available UDP ports, each randomly selected <del> * from the range [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. <del> * @param numRequested the number of available ports to find <del> * @return a sorted set of available UDP port numbers <del> * @throws IllegalStateException if the requested number of available ports could not be found <del> */ <del> public static SortedSet<Integer> findAvailableUdpPorts(int numRequested) { <del> return findAvailableUdpPorts(numRequested, PORT_RANGE_MIN, PORT_RANGE_MAX); <del> } <del> <del> /** <del> * Find the requested number of available UDP ports, each randomly selected <del> * from the range [{@code minPort}, {@code maxPort}]. <del> * @param numRequested the number of available ports to find <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return a sorted set of available UDP port numbers <del> * @throws IllegalStateException if the requested number of available ports could not be found <del> */ <del> public static SortedSet<Integer> findAvailableUdpPorts(int numRequested, int minPort, int maxPort) { <del> return SocketType.UDP.findAvailablePorts(numRequested, minPort, maxPort); <del> } <del> <del> <del> private enum SocketType { <del> <del> TCP { <del> @Override <del> protected boolean isPortAvailable(int port) { <del> try { <del> ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket( <del> port, 1, InetAddress.getByName("localhost")); <del> serverSocket.close(); <del> return true; <del> } <del> catch (Exception ex) { <del> return false; <del> } <del> } <del> }, <del> <del> UDP { <del> @Override <del> protected boolean isPortAvailable(int port) { <del> try { <del> DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost")); <del> socket.close(); <del> return true; <del> } <del> catch (Exception ex) { <del> return false; <del> } <del> } <del> }; <del> <del> /** <del> * Determine if the specified port for this {@code SocketType} is <del> * currently available on {@code localhost}. <del> */ <del> protected abstract boolean isPortAvailable(int port); <del> <del> /** <del> * Find a pseudo-random port number within the range <del> * [{@code minPort}, {@code maxPort}]. <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return a random port number within the specified range <del> */ <del> private int findRandomPort(int minPort, int maxPort) { <del> int portRange = maxPort - minPort; <del> return minPort + random.nextInt(portRange + 1); <del> } <del> <del> /** <del> * Find an available port for this {@code SocketType}, randomly selected <del> * from the range [{@code minPort}, {@code maxPort}]. <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return an available port number for this socket type <del> * @throws IllegalStateException if no available port could be found <del> */ <del> int findAvailablePort(int minPort, int maxPort) { <del> Assert.isTrue(minPort > 0, "'minPort' must be greater than 0"); <del> Assert.isTrue(maxPort >= minPort, "'maxPort' must be greater than or equal to 'minPort'"); <del> Assert.isTrue(maxPort <= PORT_RANGE_MAX, "'maxPort' must be less than or equal to " + PORT_RANGE_MAX); <del> <del> int portRange = maxPort - minPort; <del> int candidatePort; <del> int searchCounter = 0; <del> do { <del> if (searchCounter > portRange) { <del> throw new IllegalStateException(String.format( <del> "Could not find an available %s port in the range [%d, %d] after %d attempts", <del> name(), minPort, maxPort, searchCounter)); <del> } <del> candidatePort = findRandomPort(minPort, maxPort); <del> searchCounter++; <del> } <del> while (!isPortAvailable(candidatePort)); <del> <del> return candidatePort; <del> } <del> <del> /** <del> * Find the requested number of available ports for this {@code SocketType}, <del> * each randomly selected from the range [{@code minPort}, {@code maxPort}]. <del> * @param numRequested the number of available ports to find <del> * @param minPort the minimum port number <del> * @param maxPort the maximum port number <del> * @return a sorted set of available port numbers for this socket type <del> * @throws IllegalStateException if the requested number of available ports could not be found <del> */ <del> SortedSet<Integer> findAvailablePorts(int numRequested, int minPort, int maxPort) { <del> Assert.isTrue(minPort > 0, "'minPort' must be greater than 0"); <del> Assert.isTrue(maxPort > minPort, "'maxPort' must be greater than 'minPort'"); <del> Assert.isTrue(maxPort <= PORT_RANGE_MAX, "'maxPort' must be less than or equal to " + PORT_RANGE_MAX); <del> Assert.isTrue(numRequested > 0, "'numRequested' must be greater than 0"); <del> Assert.isTrue((maxPort - minPort) >= numRequested, <del> "'numRequested' must not be greater than 'maxPort' - 'minPort'"); <del> <del> SortedSet<Integer> availablePorts = new TreeSet<>(); <del> int attemptCount = 0; <del> while ((++attemptCount <= numRequested + 100) && availablePorts.size() < numRequested) { <del> availablePorts.add(findAvailablePort(minPort, maxPort)); <del> } <del> <del> if (availablePorts.size() != numRequested) { <del> throw new IllegalStateException(String.format( <del> "Could not find %d available %s ports in the range [%d, %d]", <del> numRequested, name(), minPort, maxPort)); <del> } <del> <del> return availablePorts; <del> } <del> } <del> <del>} <ide><path>spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java <del>/* <del> * Copyright 2002-2022 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> * https://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.util; <del> <del>import java.net.DatagramSocket; <del>import java.net.InetAddress; <del>import java.net.ServerSocket; <del>import java.util.SortedSet; <del> <del>import javax.net.ServerSocketFactory; <del> <del>import org.junit.jupiter.api.Test; <del> <del>import static org.assertj.core.api.Assertions.assertThat; <del>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <del>import static org.assertj.core.api.Assertions.assertThatIllegalStateException; <del> <del>/** <del> * Unit tests for {@link SocketUtils}. <del> * <del> * @author Sam Brannen <del> * @author Gary Russell <del> */ <del>@SuppressWarnings("deprecation") <del>class SocketUtilsTests { <del> <del> @Test <del> void canBeInstantiated() { <del> // Just making sure somebody doesn't try to make SocketUtils abstract, <del> // since that would be a breaking change due to the intentional public <del> // constructor. <del> new org.springframework.util.SocketUtils(); <del> } <del> <del> // TCP <del> <del> @Test <del> void findAvailableTcpPortWithZeroMinPort() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableTcpPort(0)); <del> } <del> <del> @Test <del> void findAvailableTcpPortWithNegativeMinPort() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableTcpPort(-500)); <del> } <del> <del> @Test <del> void findAvailableTcpPort() { <del> int port = org.springframework.util.SocketUtils.findAvailableTcpPort(); <del> assertPortInRange(port, org.springframework.util.SocketUtils.PORT_RANGE_MIN, <del> org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> @Test <del> void findAvailableTcpPortWithMinPortEqualToMaxPort() { <del> int minMaxPort = org.springframework.util.SocketUtils.findAvailableTcpPort(); <del> int port = org.springframework.util.SocketUtils.findAvailableTcpPort(minMaxPort, minMaxPort); <del> assertThat(port).isEqualTo(minMaxPort); <del> } <del> <del> @Test <del> void findAvailableTcpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception { <del> int port = org.springframework.util.SocketUtils.findAvailableTcpPort(); <del> try (ServerSocket socket = ServerSocketFactory.getDefault().createServerSocket(port, 1, InetAddress.getByName("localhost"))) { <del> assertThat(socket).isNotNull(); <del> // will only look for the exact port <del> assertThatIllegalStateException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableTcpPort(port, port)) <del> .withMessageStartingWith("Could not find an available TCP port") <del> .withMessageEndingWith("after 1 attempts"); <del> } <del> } <del> <del> @Test <del> void findAvailableTcpPortWithMin() { <del> int port = org.springframework.util.SocketUtils.findAvailableTcpPort(50000); <del> assertPortInRange(port, 50000, org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> @Test <del> void findAvailableTcpPortInRange() { <del> int minPort = 20000; <del> int maxPort = minPort + 1000; <del> int port = org.springframework.util.SocketUtils.findAvailableTcpPort(minPort, maxPort); <del> assertPortInRange(port, minPort, maxPort); <del> } <del> <del> @Test <del> void find4AvailableTcpPorts() { <del> findAvailableTcpPorts(4); <del> } <del> <del> @Test <del> void find50AvailableTcpPorts() { <del> findAvailableTcpPorts(50); <del> } <del> <del> @Test <del> void find4AvailableTcpPortsInRange() { <del> findAvailableTcpPorts(4, 30000, 35000); <del> } <del> <del> @Test <del> void find50AvailableTcpPortsInRange() { <del> findAvailableTcpPorts(50, 40000, 45000); <del> } <del> <del> @Test <del> void findAvailableTcpPortsWithRequestedNumberGreaterThanSizeOfRange() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> findAvailableTcpPorts(50, 45000, 45010)); <del> } <del> <del> <del> // UDP <del> <del> @Test <del> void findAvailableUdpPortWithZeroMinPort() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableUdpPort(0)); <del> } <del> <del> @Test <del> void findAvailableUdpPortWithNegativeMinPort() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableUdpPort(-500)); <del> } <del> <del> @Test <del> void findAvailableUdpPort() { <del> int port = org.springframework.util.SocketUtils.findAvailableUdpPort(); <del> assertPortInRange(port, org.springframework.util.SocketUtils.PORT_RANGE_MIN, <del> org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> @Test <del> void findAvailableUdpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception { <del> int port = org.springframework.util.SocketUtils.findAvailableUdpPort(); <del> try (DatagramSocket socket = new DatagramSocket(port, InetAddress.getByName("localhost"))) { <del> assertThat(socket).isNotNull(); <del> // will only look for the exact port <del> assertThatIllegalStateException().isThrownBy(() -> <del> org.springframework.util.SocketUtils.findAvailableUdpPort(port, port)) <del> .withMessageStartingWith("Could not find an available UDP port") <del> .withMessageEndingWith("after 1 attempts"); <del> } <del> } <del> <del> @Test <del> void findAvailableUdpPortWithMin() { <del> int port = org.springframework.util.SocketUtils.findAvailableUdpPort(50000); <del> assertPortInRange(port, 50000, org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> @Test <del> void findAvailableUdpPortInRange() { <del> int minPort = 20000; <del> int maxPort = minPort + 1000; <del> int port = org.springframework.util.SocketUtils.findAvailableUdpPort(minPort, maxPort); <del> assertPortInRange(port, minPort, maxPort); <del> } <del> <del> @Test <del> void find4AvailableUdpPorts() { <del> findAvailableUdpPorts(4); <del> } <del> <del> @Test <del> void find50AvailableUdpPorts() { <del> findAvailableUdpPorts(50); <del> } <del> <del> @Test <del> void find4AvailableUdpPortsInRange() { <del> findAvailableUdpPorts(4, 30000, 35000); <del> } <del> <del> @Test <del> void find50AvailableUdpPortsInRange() { <del> findAvailableUdpPorts(50, 40000, 45000); <del> } <del> <del> @Test <del> void findAvailableUdpPortsWithRequestedNumberGreaterThanSizeOfRange() { <del> assertThatIllegalArgumentException().isThrownBy(() -> <del> findAvailableUdpPorts(50, 45000, 45010)); <del> } <del> <del> <del> // Helpers <del> <del> private void findAvailableTcpPorts(int numRequested) { <del> SortedSet<Integer> ports = org.springframework.util.SocketUtils.findAvailableTcpPorts(numRequested); <del> assertAvailablePorts(ports, numRequested, org.springframework.util.SocketUtils.PORT_RANGE_MIN, <del> org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> private void findAvailableTcpPorts(int numRequested, int minPort, int maxPort) { <del> SortedSet<Integer> ports = org.springframework.util.SocketUtils.findAvailableTcpPorts(numRequested, minPort, maxPort); <del> assertAvailablePorts(ports, numRequested, minPort, maxPort); <del> } <del> <del> private void findAvailableUdpPorts(int numRequested) { <del> SortedSet<Integer> ports = org.springframework.util.SocketUtils.findAvailableUdpPorts(numRequested); <del> assertAvailablePorts(ports, numRequested, org.springframework.util.SocketUtils.PORT_RANGE_MIN, <del> org.springframework.util.SocketUtils.PORT_RANGE_MAX); <del> } <del> <del> private void findAvailableUdpPorts(int numRequested, int minPort, int maxPort) { <del> SortedSet<Integer> ports = org.springframework.util.SocketUtils.findAvailableUdpPorts(numRequested, minPort, maxPort); <del> assertAvailablePorts(ports, numRequested, minPort, maxPort); <del> } <del> private void assertPortInRange(int port, int minPort, int maxPort) { <del> assertThat(port >= minPort).as("port [" + port + "] >= " + minPort).isTrue(); <del> assertThat(port <= maxPort).as("port [" + port + "] <= " + maxPort).isTrue(); <del> } <del> <del> private void assertAvailablePorts(SortedSet<Integer> ports, int numRequested, int minPort, int maxPort) { <del> assertThat(ports.size()).as("number of ports requested").isEqualTo(numRequested); <del> for (int port : ports) { <del> assertPortInRange(port, minPort, maxPort); <del> } <del> } <del> <del>} <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/net/TestSocketUtils.java <add>/* <add> * Copyright 2002-2022 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> * https://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.core.testfixture.net; <add> <add>import java.net.DatagramSocket; <add>import java.net.InetAddress; <add>import java.net.ServerSocket; <add>import java.util.Random; <add> <add>import javax.net.ServerSocketFactory; <add> <add>import org.springframework.util.Assert; <add> <add>/** <add> * Removed from spring-core and introduced as an internal test utility in <add> * spring-context in Spring Framework 6.0. <add> * <add> * <p>Simple utility methods for working with network sockets &mdash; for example, <add> * for finding available ports on {@code localhost}. <add> * <add> * <p>Within this class, a TCP port refers to a port for a {@link ServerSocket}; <add> * whereas, a UDP port refers to a port for a {@link DatagramSocket}. <add> * <add> * <p>{@code SocketUtils} was introduced in Spring Framework 4.0, primarily to <add> * assist in writing integration tests which start an external server on an <add> * available random port. However, these utilities make no guarantee about the <add> * subsequent availability of a given port and are therefore unreliable. Instead <add> * of using {@code SocketUtils} to find an available local port for a server, it <add> * is recommended that you rely on a server's ability to start on a random port <add> * that it selects or is assigned by the operating system. To interact with that <add> * server, you should query the server for the port it is currently using. <add> * <add> * @author Sam Brannen <add> * @author Ben Hale <add> * @author Arjen Poutsma <add> * @author Gunnar Hillert <add> * @author Gary Russell <add> * @since 4.0 <add> */ <add>public class TestSocketUtils { <add> <add> /** <add> * The default minimum value for port ranges used when finding an available <add> * socket port. <add> */ <add> private static final int PORT_RANGE_MIN = 1024; <add> <add> /** <add> * The default maximum value for port ranges used when finding an available <add> * socket port. <add> */ <add> private static final int PORT_RANGE_MAX = 65535; <add> <add> <add> private static final Random random = new Random(System.nanoTime()); <add> <add> <add> /** <add> * Find an available TCP port randomly selected from the range <add> * [{@value #PORT_RANGE_MIN}, {@value #PORT_RANGE_MAX}]. <add> * @return an available TCP port number <add> * @throws IllegalStateException if no available port could be found <add> */ <add> public static int findAvailableTcpPort() { <add> return findAvailablePort(PORT_RANGE_MIN, PORT_RANGE_MAX); <add> } <add> <add> /** <add> * Find an available port for this {@code SocketType}, randomly selected <add> * from the range [{@code minPort}, {@code maxPort}]. <add> * @param minPort the minimum port number <add> * @param maxPort the maximum port number <add> * @return an available port number for this socket type <add> * @throws IllegalStateException if no available port could be found <add> */ <add> private static int findAvailablePort(int minPort, int maxPort) { <add> Assert.isTrue(minPort > 0, "'minPort' must be greater than 0"); <add> Assert.isTrue(maxPort >= minPort, "'maxPort' must be greater than or equal to 'minPort'"); <add> Assert.isTrue(maxPort <= PORT_RANGE_MAX, "'maxPort' must be less than or equal to " + PORT_RANGE_MAX); <add> <add> int portRange = maxPort - minPort; <add> int candidatePort; <add> int searchCounter = 0; <add> do { <add> if (searchCounter > portRange) { <add> throw new IllegalStateException(String.format( <add> "Could not find an available TCP port in the range [%d, %d] after %d attempts", <add> minPort, maxPort, searchCounter)); <add> } <add> candidatePort = findRandomPort(minPort, maxPort); <add> searchCounter++; <add> } <add> while (!isPortAvailable(candidatePort)); <add> <add> return candidatePort; <add> } <add> <add> /** <add> * Find a pseudo-random port number within the range <add> * [{@code minPort}, {@code maxPort}]. <add> * @param minPort the minimum port number <add> * @param maxPort the maximum port number <add> * @return a random port number within the specified range <add> */ <add> private static int findRandomPort(int minPort, int maxPort) { <add> int portRange = maxPort - minPort; <add> return minPort + random.nextInt(portRange + 1); <add> } <add> <add> /** <add> * Determine if the specified port for this {@code SocketType} is <add> * currently available on {@code localhost}. <add> */ <add> private static boolean isPortAvailable(int port) { <add> try { <add> ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket( <add> port, 1, InetAddress.getByName("localhost")); <add> serverSocket.close(); <add> return true; <add> } <add> catch (Exception ex) { <add> return false; <add> } <add> } <add> <add>}
7
Ruby
Ruby
explain all test helpers
c859cd256fda470ad284b21b8595d75b78eebc9f
<ide><path>lib/action_mailbox/test_helper.rb <ide> <ide> module ActionMailbox <ide> module TestHelper <del> # Create an InboundEmail record using an eml fixture in the format of message/rfc822 <add> # Create an `InboundEmail` record using an eml fixture in the format of message/rfc822 <ide> # referenced with +fixture_name+ located in +test/fixtures/files/fixture_name+. <ide> def create_inbound_email_from_fixture(fixture_name, status: :processing) <ide> create_inbound_email_from_source file_fixture(fixture_name).read, status: status <ide> end <ide> <add> # Create an `InboundEmail` by specifying it using `Mail.new` options. Example: <add> # <add> # create_inbound_email_from_mail(from: "david@loudthinking.com", subject: "Hello!") <ide> def create_inbound_email_from_mail(status: :processing, **mail_options) <ide> create_inbound_email_from_source Mail.new(mail_options).to_s, status: status <ide> end <ide> def create_inbound_email_from_source(source, status: :processing) <ide> ActionMailbox::InboundEmail.create_and_extract_message_id! source, status: status <ide> end <ide> <add> <add> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_fixture` <add> # and immediately route it to processing. <ide> def receive_inbound_email_from_fixture(*args) <ide> create_inbound_email_from_fixture(*args).tap(&:route) <ide> end <ide> <add> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_mail` <add> # and immediately route it to processing. <ide> def receive_inbound_email_from_mail(**kwargs) <ide> create_inbound_email_from_mail(**kwargs).tap(&:route) <ide> end <add> <add> # Create an `InboundEmail` from fixture using the same arguments as `create_inbound_email_from_source` <add> # and immediately route it to processing. <ide> def receive_inbound_email_from_source(**kwargs) <ide> create_inbound_email_from_source(**kwargs).tap(&:route) <ide> end
1
PHP
PHP
specify method. rename conjoin
0f5337f854ecdd722e7e289ff58cc252337e7a9d
<ide><path>src/Illuminate/Support/Collection.php <ide> public function collapse() <ide> return new static(Arr::collapse($this->items)); <ide> } <ide> <del> /** <del> * Conjoin all values of a collection with those of another, regardless of keys. <del> * <del> * @param \Traversable $source <del> * @return self <del> */ <del> public function conjoin($source) <del> { <del> $joinedCollection = new static($this); <del> <del> foreach ($source as $item) { <del> $joinedCollection->push($item); <del> } <del> <del> return $joinedCollection; <del> } <del> <ide> /** <ide> * Determine if an item exists in the collection. <ide> * <ide> public function push($value) <ide> return $this; <ide> } <ide> <add> /** <add> * Push all of the given items onto the collection. <add> * <add> * @param \Traversable $source <add> * @return self <add> */ <add> public function concat($source) <add> { <add> $result = new static($this); <add> <add> foreach ($source as $item) { <add> $result->push($item); <add> } <add> <add> return $result; <add> } <add> <ide> /** <ide> * Get and remove an item from the collection. <ide> * <ide><path>tests/Database/DatabaseEloquentHasOneTest.php <ide> public function testHasOneWithArrayDefault() <ide> public function testMakeMethodDoesNotSaveNewModel() <ide> { <ide> $relation = $this->getRelation(); <del> $instance = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['newInstance', 'setAttribute'])->getMock(); <add> $instance = $this->getMockBuilder('Illuminate\Database\Eloquent\Model')->setMethods(['save', 'newInstance', 'setAttribute'])->getMock(); <ide> $relation->getRelated()->shouldReceive('newInstance')->with(['name' => 'taylor'])->andReturn($instance); <ide> $instance->expects($this->once())->method('setAttribute')->with('foreign_key', 1); <ide> $instance->expects($this->never())->method('save'); <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testCombineWithCollection() <ide> $this->assertSame($expected, $actual); <ide> } <ide> <del> public function testConJoinWithArray() <add> public function testConcatWithArray() <ide> { <ide> $expected = [ <ide> 0 => 4, <ide> public function testConJoinWithArray() <ide> ]; <ide> <ide> $collection = new Collection([4, 5, 6]); <del> $collection = $collection->conjoin(['a', 'b', 'c']); <del> $collection = $collection->conjoin(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe']); <del> $actual = $collection->conjoin(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe'])->toArray(); <add> $collection = $collection->concat(['a', 'b', 'c']); <add> $collection = $collection->concat(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe']); <add> $actual = $collection->concat(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe'])->toArray(); <ide> <ide> $this->assertSame($expected, $actual); <ide> } <ide> <del> public function testConJoinWithCollection() <add> public function testConcatWithCollection() <ide> { <ide> $expected = [ <ide> 0 => 4, <ide> public function testConJoinWithCollection() <ide> $firstCollection = new Collection([4, 5, 6]); <ide> $secondCollection = new Collection(['a', 'b', 'c']); <ide> $thirdCollection = new Collection(['who' => 'Jonny', 'preposition' => 'from', 'where' => 'Laroe']); <del> $firstCollection = $firstCollection->conjoin($secondCollection); <del> $firstCollection = $firstCollection->conjoin($thirdCollection); <del> $actual = $firstCollection->conjoin($thirdCollection)->toArray(); <add> $firstCollection = $firstCollection->concat($secondCollection); <add> $firstCollection = $firstCollection->concat($thirdCollection); <add> $actual = $firstCollection->concat($thirdCollection)->toArray(); <ide> <ide> $this->assertSame($expected, $actual); <ide> }
3
Ruby
Ruby
add macos & java versions
a8788015b69c5525efe2cd47ba67c1e6950d1526
<ide><path>Library/Homebrew/cask/lib/hbc/cli/doctor.rb <add>require "system_config" <add> <ide> module Hbc <ide> class CLI <ide> class Doctor < AbstractCommand <ide> def initialize(*) <ide> <ide> def run <ide> ohai "Homebrew-Cask Version", Hbc.full_version <add> ohai "macOS", MacOS.full_version <add> ohai "Java", SystemConfig.describe_java <ide> ohai "Homebrew-Cask Install Location", self.class.render_install_location <ide> ohai "Homebrew-Cask Staging Location", self.class.render_staging_location(Hbc.caskroom) <ide> ohai "Homebrew-Cask Cached Downloads", self.class.render_cached_downloads
1
PHP
PHP
fix doc block in test
81a82c5eae9c3a87e4bac0a9cae0bb6a309991dd
<ide><path>tests/test_app/TestApp/Controller/Component/TestAuthComponent.php <ide> class TestAuthComponent extends AuthComponent <ide> { <ide> /** <del> * @var string <add> * @var string|null <ide> */ <ide> public $authCheckCalledFrom = null; <ide> <ide> /** <ide> * @param Event $event <del> * @return \Cake\Network\Response|null|void <add> * @return \Cake\Network\Response|null <ide> */ <ide> public function authCheck(Event $event) <ide> {
1
PHP
PHP
improve code readability
813cd75f1576e72c5cfe6c6f827f495805f268df
<ide><path>src/Controller/Controller.php <ide> public function __get($name) <ide> } <ide> <ide> list($plugin, $class) = pluginSplit($this->modelClass, true); <del> if ($class !== $name) { <del> $trace = debug_backtrace(); <del> $parts = explode('\\', get_class($this)); <del> trigger_error( <del> sprintf( <del> 'Undefined property: %s::$%s in %s on line %s', <del> array_pop($parts), <del> $name, <del> $trace[0]['file'], <del> $trace[0]['line'] <del> ), <del> E_USER_NOTICE <del> ); <del> <del> return false; <del> } <add> if ($class === $name) { <add> return $this->loadModel($plugin . $class); <add> } <add> <add> $trace = debug_backtrace(); <add> $parts = explode('\\', get_class($this)); <add> trigger_error( <add> sprintf( <add> 'Undefined property: %s::$%s in %s on line %s', <add> array_pop($parts), <add> $name, <add> $trace[0]['file'], <add> $trace[0]['line'] <add> ), <add> E_USER_NOTICE <add> ); <ide> <del> return $this->loadModel($plugin . $class); <add> return false; <ide> } <ide> <ide> /**
1
Javascript
Javascript
add coverage for socket write after close
6a18c1d8dd034767f86bc496e292ecb0dddf944f
<ide><path>test/parallel/test-net-socket-write-after-close.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>{ <add> const server = net.createServer(); <add> <add> server.listen(common.mustCall(() => { <add> const port = server.address().port; <add> const client = net.connect({port}, common.mustCall(() => { <add> client.on('error', common.mustCall((err) => { <add> server.close(); <add> assert.strictEqual(err.constructor, Error); <add> assert.strictEqual(err.message, 'write EBADF'); <add> })); <add> client._handle.close(); <add> client.write('foo'); <add> })); <add> })); <add>} <add> <add>{ <add> const server = net.createServer(); <add> <add> server.listen(common.mustCall(() => { <add> const port = server.address().port; <add> const client = net.connect({port}, common.mustCall(() => { <add> client.on('error', common.mustCall((err) => { <add> server.close(); <add> assert.strictEqual(err.constructor, Error); <add> assert.strictEqual(err.message, 'This socket is closed'); <add> })); <add> client._handle.close(); <add> client._handle = null; <add> client.write('foo'); <add> })); <add> })); <add>}
1
Ruby
Ruby
move error text and helper into error class
3cbb49930c812b09c3fa8cd62fff8d722104e406
<ide><path>Library/Homebrew/utils.rb <ide> module GitHub extend self <ide> ISSUES_URI = URI.parse("https://api.github.com/search/issues") <ide> <ide> Error = Class.new(RuntimeError) <del> RateLimitExceededError = Class.new(Error) <ide> HTTPNotFoundError = Class.new(Error) <ide> AuthenticationFailedError = Class.new(Error) <ide> <add> class RateLimitExceededError < Error <add> def initialize(reset, error) <add> super <<-EOS.undent <add> GitHub #{error} <add> Try again in #{pretty_ratelimit_reset(reset)}, or create an API token: <add> https://github.com/settings/applications <add> and then set HOMEBREW_GITHUB_API_TOKEN. <add> EOS <add> end <add> <add> def pretty_ratelimit_reset(reset) <add> if (seconds = Time.at(reset) - Time.now) > 180 <add> "%d minutes %d seconds" % [seconds / 60, seconds % 60] <add> else <add> "#{seconds} seconds" <add> end <add> end <add> end <add> <ide> def open url, headers={}, &block <ide> # This is a no-op if the user is opting out of using the GitHub API. <ide> return if ENV['HOMEBREW_NO_GITHUB_API'] <ide> def open url, headers={}, &block <ide> def handle_api_error(e) <ide> if e.io.meta["x-ratelimit-remaining"].to_i <= 0 <ide> reset = e.io.meta.fetch("x-ratelimit-reset").to_i <del> <del> raise RateLimitExceededError, <<-EOS.undent, e.backtrace <del> GitHub #{Utils::JSON.load(e.io.read)['message']} <del> Try again in #{pretty_ratelimit_reset(reset)}, or create an API token: <del> https://github.com/settings/applications <del> and then set HOMEBREW_GITHUB_API_TOKEN. <del> EOS <add> error = Utils::JSON.load(e.io.read)["message"] <add> raise RateLimitExceededError.new(reset, error) <ide> end <ide> <ide> case e.io.status.first <ide> def handle_api_error(e) <ide> end <ide> end <ide> <del> def pretty_ratelimit_reset(reset) <del> if (seconds = Time.at(reset) - Time.now) > 180 <del> "%d minutes %d seconds" % [seconds / 60, seconds % 60] <del> else <del> "#{seconds} seconds" <del> end <del> end <del> <ide> def issues_matching(query, qualifiers={}) <ide> uri = ISSUES_URI.dup <ide> uri.query = build_query_string(query, qualifiers)
1
Text
Text
allow g flag on regex
1b06bb29f0fe3e656e2c4ce7f9f46049453656af
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-mixed-grouping-of-characters.english.md <ide> Then check whether the desired string groups are in the test string by using the <ide> <ide> ```js <ide> let testStr = "Pumpkin"; <del>let testRegex = /P(engu|umpk)in/g; <add>let testRegex = /P(engu|umpk)in/; <ide> testRegex.test(testStr); <ide> // Returns true <ide> ``` <ide> Then fix the code so that the regex that you have created is checked against <co <ide> ```yml <ide> tests: <ide> - text: Your regex <code>myRegex</code> should return <code>true</code> for the string <code>Franklin D. Roosevelt</code> <del> testString: assert(myRegex.test('Franklin D. Roosevelt')); <add> testString: myRegex.lastIndex = 0; assert(myRegex.test('Franklin D. Roosevelt')); <ide> - text: Your regex <code>myRegex</code> should return <code>true</code> for the string <code>Eleanor Roosevelt</code> <del> testString: assert(myRegex.test('Eleanor Roosevelt')); <add> testString: myRegex.lastIndex = 0; assert(myRegex.test('Eleanor Roosevelt')); <ide> - text: Your regex <code>myRegex</code> should return <code>false</code> for the string <code>Franklin Rosevelt</code> <del> testString: assert(!myRegex.test('Franklin Rosevelt')); <add> testString: myRegex.lastIndex = 0; assert(!myRegex.test('Franklin Rosevelt')); <ide> - text: You should use <code>.test()</code> to test the regex. <ide> testString: assert(code.match(/myRegex.test\(\s*myString\s*\)/)); <ide> - text: Your result should return <code>true</code>.
1
Python
Python
improve image processing (#45)
5d7612c63c6b8585a4cbd87093294e747f3f0b08
<ide><path>inception/inception/image_processing.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <del> <ide> import tensorflow as tf <ide> <ide> FLAGS = tf.app.flags.FLAGS <ide> tf.app.flags.DEFINE_integer('num_preprocess_threads', 4, <ide> """Number of preprocessing threads per tower. """ <ide> """Please make this a multiple of 4.""") <add>tf.app.flags.DEFINE_integer('num_readers', 4, <add> """Number of parallel readers during train.""") <ide> <ide> # Images are preprocessed asynchronously using multiple threads specifed by <ide> # --num_preprocss_threads and the resulting processed images are stored in a <ide> def inputs(dataset, batch_size=None, num_preprocess_threads=None): <ide> with tf.device('/cpu:0'): <ide> images, labels = batch_inputs( <ide> dataset, batch_size, train=False, <del> num_preprocess_threads=num_preprocess_threads) <add> num_preprocess_threads=num_preprocess_threads, <add> num_readers=1) <ide> <ide> return images, labels <ide> <ide> def distorted_inputs(dataset, batch_size=None, num_preprocess_threads=None): <ide> with tf.device('/cpu:0'): <ide> images, labels = batch_inputs( <ide> dataset, batch_size, train=True, <del> num_preprocess_threads=num_preprocess_threads) <add> num_preprocess_threads=num_preprocess_threads, <add> num_readers=FLAGS.num_readers) <ide> return images, labels <ide> <ide> <ide> def parse_example_proto(example_serialized): <ide> return features['image/encoded'], label, bbox, features['image/class/text'] <ide> <ide> <del>def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None): <add>def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None, <add> num_readers=1): <ide> """Contruct batches of training or evaluation examples from the image dataset. <ide> <ide> Args: <ide> def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None): <ide> batch_size: integer <ide> train: boolean <ide> num_preprocess_threads: integer, total number of preprocessing threads <add> num_readers: integer, number of parallel readers <ide> <ide> Returns: <ide> images: 4-D float Tensor of a batch of images <ide> def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None): <ide> data_files = dataset.data_files() <ide> if data_files is None: <ide> raise ValueError('No data files found for this dataset') <del> filename_queue = tf.train.string_input_producer(data_files, capacity=16) <ide> <add> # Create filename_queue <add> if train: <add> filename_queue = tf.train.string_input_producer(data_files, <add> shuffle=True, <add> capacity=16) <add> else: <add> filename_queue = tf.train.string_input_producer(data_files, <add> shuffle=False, <add> capacity=1) <ide> if num_preprocess_threads is None: <ide> num_preprocess_threads = FLAGS.num_preprocess_threads <ide> <ide> if num_preprocess_threads % 4: <ide> raise ValueError('Please make num_preprocess_threads a multiple ' <ide> 'of 4 (%d % 4 != 0).', num_preprocess_threads) <del> # Create a subgraph with its own reader (but sharing the <del> # filename_queue) for each preprocessing thread. <del> images_and_labels = [] <del> for thread_id in range(num_preprocess_threads): <del> reader = dataset.reader() <del> _, example_serialized = reader.read(filename_queue) <ide> <del> # Parse a serialized Example proto to extract the image and metadata. <del> image_buffer, label_index, bbox, _ = parse_example_proto( <del> example_serialized) <del> image = image_preprocessing(image_buffer, bbox, train, thread_id) <del> images_and_labels.append([image, label_index]) <add> if num_readers is None: <add> num_readers = FLAGS.num_readers <add> <add> if num_readers < 1: <add> raise ValueError('Please make num_readers at least 1') <ide> <ide> # Approximate number of examples per shard. <ide> examples_per_shard = 1024 <ide> def batch_inputs(dataset, batch_size, train, num_preprocess_threads=None): <ide> # The default input_queue_memory_factor is 16 implying a shuffling queue <ide> # size: examples_per_shard * 16 * 1MB = 17.6GB <ide> min_queue_examples = examples_per_shard * FLAGS.input_queue_memory_factor <del> <del> # Create a queue that produces the examples in batches after shuffling. <ide> if train: <del> images, label_index_batch = tf.train.shuffle_batch_join( <del> images_and_labels, <del> batch_size=batch_size, <add> examples_queue = tf.RandomShuffleQueue( <ide> capacity=min_queue_examples + 3 * batch_size, <del> min_after_dequeue=min_queue_examples) <add> min_after_dequeue=min_queue_examples, <add> dtypes=[tf.string]) <add> else: <add> examples_queue = tf.FIFOQueue( <add> capacity=examples_per_shard + 3 * batch_size, <add> dtypes=[tf.string]) <add> <add> # Create multiple readers to populate the queue of examples. <add> if num_readers > 1: <add> enqueue_ops = [] <add> for _ in range(num_readers): <add> reader = dataset.reader() <add> _, value = reader.read(filename_queue) <add> enqueue_ops.append(examples_queue.enqueue([value])) <add> <add> tf.train.queue_runner.add_queue_runner( <add> tf.train.queue_runner.QueueRunner(examples_queue, enqueue_ops)) <add> example_serialized = examples_queue.dequeue() <ide> else: <del> images, label_index_batch = tf.train.batch_join( <del> images_and_labels, <del> batch_size=batch_size, <del> capacity=min_queue_examples + 3 * batch_size) <add> reader = dataset.reader() <add> _, example_serialized = reader.read(filename_queue) <add> <add> images_and_labels = [] <add> for thread_id in range(num_preprocess_threads): <add> # Parse a serialized Example proto to extract the image and metadata. <add> image_buffer, label_index, bbox, _ = parse_example_proto( <add> example_serialized) <add> image = image_preprocessing(image_buffer, bbox, train, thread_id) <add> images_and_labels.append([image, label_index]) <add> <add> images, label_index_batch = tf.train.batch_join( <add> images_and_labels, <add> batch_size=batch_size, <add> capacity=2 * num_preprocess_threads * batch_size) <ide> <ide> # Reshape images into these desired dimensions. <ide> height = FLAGS.image_size
1
Javascript
Javascript
use helper for readability
937bbc5571073d1fbeffd2d9e18949b3b4dcf09b
<ide><path>lib/internal/js_stream_socket.js <ide> const kCurrentWriteRequest = Symbol('kCurrentWriteRequest'); <ide> const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest'); <ide> const kPendingShutdownRequest = Symbol('kPendingShutdownRequest'); <ide> <del>function isClosing() { <del> let socket = this[owner_symbol]; <add>function checkReusedHandle(self) { <add> let socket = self[owner_symbol]; <ide> <del> if (socket.constructor.name === 'ReusedHandle') { <add> if (socket.constructor.name === 'ReusedHandle') <ide> socket = socket.handle; <del> } <add> <add> return socket; <add>} <add> <add>function isClosing() { <add> const socket = checkReusedHandle(this); <ide> <ide> return socket.isClosing(); <ide> } <ide> <ide> function onreadstart() { <del> let socket = this[owner_symbol]; <del> <del> if (socket.constructor.name === 'ReusedHandle') { <del> socket = socket.handle; <del> } <add> const socket = checkReusedHandle(this); <ide> <ide> return socket.readStart(); <ide> } <ide> <ide> function onreadstop() { <del> let socket = this[owner_symbol]; <del> <del> if (socket.constructor.name === 'ReusedHandle') { <del> socket = socket.handle; <del> } <add> const socket = checkReusedHandle(this); <ide> <ide> return socket.readStop(); <ide> } <ide> <ide> function onshutdown(req) { <del> let socket = this[owner_symbol]; <del> <del> if (socket.constructor.name === 'ReusedHandle') { <del> socket = socket.handle; <del> } <add> const socket = checkReusedHandle(this); <ide> <ide> return socket.doShutdown(req); <ide> } <ide> <ide> function onwrite(req, bufs) { <del> let socket = this[owner_symbol]; <del> <del> if (socket.constructor.name === 'ReusedHandle') { <del> socket = socket.handle; <del> } <add> const socket = checkReusedHandle(this); <ide> <ide> return socket.doWrite(req, bufs); <ide> }
1
Python
Python
add a regression test for (not fixed yet)
a783074b622423b665ff8c4e7e97e1eebe9b183f
<ide><path>numpy/core/tests/test_regression.py <ide> def test_array_from_sequence_scalar_array(self): <ide> t = ((1,), np.array(1)) <ide> assert_raises(ValueError, lambda: np.array(t)) <ide> <add> @dec.knownfailureif(True, "Fix this for 1.5.0.") <add> def test_array_from_sequence_scalar_array2(self): <add> """Ticket #1081: weird array with strange input...""" <add> t = np.array([np.array([]), np.array(0, object)]) <add> assert_raises(ValueError, lambda: np.array(t)) <add> <ide> def test_array_too_big(self): <ide> """Ticket #1080.""" <ide> assert_raises(ValueError, np.zeros, [2**10]*10)
1
Text
Text
create model cards for indonesian models
72911c893ac26e201c9f88d534fc610b4639343a
<ide><path>model_cards/cahya/bert-base-indonesian-522M/README.md <add>--- <add>language: "id" <add>license: "mit" <add>datasets: <add>- Indonesian Wikipedia <add>widget: <add>- text: "Ibu ku sedang bekerja [MASK] supermarket." <add>--- <add> <add># Indonesian BERT base model (uncased) <add> <add>## Model description <add>It is BERT-base model pre-trained with indonesian Wikipedia using a masked language modeling (MLM) objective. This <add>model is uncased: it does not make a difference between indonesia and Indonesia. <add> <add>This is one of several other language models that have been pre-trained with indonesian datasets. More detail about <add>its usage on downstream tasks (text classification, text generation, etc) is available at [Transformer based Indonesian Language Models](https://github.com/cahya-wirawan/indonesian-language-models/tree/master/Transformers) <add> <add>## Intended uses & limitations <add> <add>### How to use <add>You can use this model directly with a pipeline for masked language modeling: <add>```python <add>>>> from transformers import pipeline <add>>>> unmasker = pipeline('fill-mask', model='cahya/bert-base-indonesian-522M') <add>>>> unmasker("Ibu ku sedang bekerja [MASK] supermarket") <add> <add>[{'sequence': '[CLS] ibu ku sedang bekerja di supermarket [SEP]', <add> 'score': 0.7983310222625732, <add> 'token': 1495}, <add> {'sequence': '[CLS] ibu ku sedang bekerja. supermarket [SEP]', <add> 'score': 0.090003103017807, <add> 'token': 17}, <add> {'sequence': '[CLS] ibu ku sedang bekerja sebagai supermarket [SEP]', <add> 'score': 0.025469014421105385, <add> 'token': 1600}, <add> {'sequence': '[CLS] ibu ku sedang bekerja dengan supermarket [SEP]', <add> 'score': 0.017966199666261673, <add> 'token': 1555}, <add> {'sequence': '[CLS] ibu ku sedang bekerja untuk supermarket [SEP]', <add> 'score': 0.016971781849861145, <add> 'token': 1572}] <add>``` <add>Here is how to use this model to get the features of a given text in PyTorch: <add>```python <add>from transformers import BertTokenizer, BertModel <add> <add>model_name='cahya/bert-base-indonesian-522M' <add>tokenizer = BertTokenizer.from_pretrained(model_name) <add>model = BertModel.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='pt') <add>output = model(**encoded_input) <add>``` <add>and in Tensorflow: <add>```python <add>from transformers import BertTokenizer, TFBertModel <add> <add>model_name='cahya/bert-base-indonesian-522M' <add>tokenizer = BertTokenizer.from_pretrained(model_name) <add>model = TFBertModel.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='tf') <add>output = model(encoded_input) <add>``` <add> <add>## Training data <add> <add>This model was pre-trained with 522MB of indonesian Wikipedia. <add>The texts are lowercased and tokenized using WordPiece and a vocabulary size of 32,000. The inputs of the model are <add>then of the form: <add> <add>```[CLS] Sentence A [SEP] Sentence B [SEP]``` <ide><path>model_cards/cahya/gpt2-small-indonesian-522M/README.md <add>--- <add>language: "id" <add>license: "mit" <add>datasets: <add>- Indonesian Wikipedia <add>widget: <add>- text: "Pulau Dewata sering dikunjungi" <add>--- <add> <add># Indonesian GPT2 small model <add> <add>## Model description <add>It is GPT2-small model pre-trained with indonesian Wikipedia using a causal language modeling (CLM) objective. This <add>model is uncased: it does not make a difference between indonesia and Indonesia. <add> <add>This is one of several other language models that have been pre-trained with indonesian datasets. More detail about <add>its usage on downstream tasks (text classification, text generation, etc) is available at [Transformer based Indonesian Language Models](https://github.com/cahya-wirawan/indonesian-language-models/tree/master/Transformers) <add> <add>## Intended uses & limitations <add> <add>### How to use <add>You can use this model directly with a pipeline for text generation. Since the generation relies on some randomness, <add>we set a seed for reproducibility: <add>```python <add>>>> from transformers import pipeline, set_seed <add>>>> generator = pipeline('text-generation', model='cahya/gpt2-small-indonesian-522M') <add>>>> set_seed(42) <add>>>> generator("Kerajaan Majapahit adalah", max_length=30, num_return_sequences=5, num_beams=10) <add> <add>[{'generated_text': 'Kerajaan Majapahit adalah sebuah kerajaan yang pernah berdiri di Jawa Timur pada abad ke-14 hingga abad ke-15. Kerajaan ini berdiri pada abad ke-14'}, <add>{'generated_text': 'Kerajaan Majapahit adalah sebuah kerajaan yang pernah berdiri di Jawa Timur pada abad ke-14 hingga abad ke-16. Kerajaan ini berdiri pada abad ke-14'}, <add>{'generated_text': 'Kerajaan Majapahit adalah sebuah kerajaan yang pernah berdiri di Jawa Timur pada abad ke-14 hingga abad ke-15. Kerajaan ini berdiri pada abad ke-15'}, <add>{'generated_text': 'Kerajaan Majapahit adalah sebuah kerajaan yang pernah berdiri di Jawa Timur pada abad ke-14 hingga abad ke-16. Kerajaan ini berdiri pada abad ke-15'}, <add>{'generated_text': 'Kerajaan Majapahit adalah sebuah kerajaan yang pernah berdiri di Jawa Timur pada abad ke-14 hingga abad ke-15. Kerajaan ini merupakan kelanjutan dari Kerajaan Majapahit yang'}] <add> <add>``` <add>Here is how to use this model to get the features of a given text in PyTorch: <add>```python <add>from transformers import GPT2Tokenizer, GPT2Model <add> <add>model_name='cahya/gpt2-small-indonesian-522M' <add>tokenizer = GPT2Tokenizer.from_pretrained(model_name) <add>model = GPT2Model.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='pt') <add>output = model(**encoded_input) <add>``` <add>and in Tensorflow: <add>```python <add>from transformers import GPT2Tokenizer, TFGPT2Model <add> <add>model_name='cahya/gpt2-small-indonesian-522M' <add>tokenizer = GPT2Tokenizer.from_pretrained(model_name) <add>model = TFGPT2Model.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='tf') <add>output = model(encoded_input) <add>``` <add> <add>## Training data <add> <add>This model was pre-trained with 522MB of indonesian Wikipedia. <add>The texts are tokenized using a byte-level version of Byte Pair Encoding (BPE) (for unicode characters) and <add>a vocabulary size of 52,000. The inputs are sequences of 128 consecutive tokens. <ide><path>model_cards/cahya/roberta-base-indonesian-522M/README.md <add>--- <add>language: "id" <add>license: "mit" <add>datasets: <add>- Indonesian Wikipedia <add>widget: <add>- text: "Ibu ku sedang bekerja <mask> supermarket." <add>--- <add> <add># Indonesian RoBERTa base model (uncased) <add> <add>## Model description <add>It is RoBERTa-base model pre-trained with indonesian Wikipedia using a masked language modeling (MLM) objective. This <add>model is uncased: it does not make a difference between indonesia and Indonesia. <add> <add>This is one of several other language models that have been pre-trained with indonesian datasets. More detail about <add>its usage on downstream tasks (text classification, text generation, etc) is available at [Transformer based Indonesian Language Models](https://github.com/cahya-wirawan/indonesian-language-models/tree/master/Transformers) <add> <add>## Intended uses & limitations <add> <add>### How to use <add>You can use this model directly with a pipeline for masked language modeling: <add>```python <add>>>> from transformers import pipeline <add>>>> unmasker = pipeline('fill-mask', model='cahya/roberta-base-indonesian-522M') <add>>>> unmasker("Ibu ku sedang bekerja <mask> supermarket") <add> <add>``` <add>Here is how to use this model to get the features of a given text in PyTorch: <add>```python <add>from transformers import RobertaTokenizer, RobertaModel <add> <add>model_name='cahya/roberta-base-indonesian-522M' <add>tokenizer = RobertaTokenizer.from_pretrained(model_name) <add>model = RobertaModel.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='pt') <add>output = model(**encoded_input) <add>``` <add>and in Tensorflow: <add>```python <add>from transformers import RobertaTokenizer, TFRobertaModel <add> <add>model_name='cahya/roberta-base-indonesian-522M' <add>tokenizer = RobertaTokenizer.from_pretrained(model_name) <add>model = TFRobertaModel.from_pretrained(model_name) <add>text = "Silakan diganti dengan text apa saja." <add>encoded_input = tokenizer(text, return_tensors='tf') <add>output = model(encoded_input) <add>``` <add> <add>## Training data <add> <add>This model was pre-trained with 522MB of indonesian Wikipedia. <add>The texts are lowercased and tokenized using WordPiece and a vocabulary size of 32,000. The inputs of the model are <add>then of the form: <add> <add>```<s> Sentence A </s> Sentence B </s>```
3