content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Java
Java
make reactinstancemanager safer threading wise
b9eeaef2435b38367080b428af2ef72726b633a2
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> <ide> import com.facebook.common.logging.FLog; <ide> import com.facebook.infer.annotation.Assertions; <add>import com.facebook.infer.annotation.ThreadConfined; <add>import com.facebook.infer.annotation.ThreadSafe; <ide> import com.facebook.react.bridge.CatalystInstance; <ide> import com.facebook.react.bridge.JavaJSExecutor; <ide> import com.facebook.react.bridge.JavaScriptModule; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <ide> <add>import static com.facebook.infer.annotation.ThreadConfined.UI; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_END; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.BUILD_NATIVE_MODULE_REGISTRY_START; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_CATALYST_INSTANCE_END; <ide> * <ide> * To instantiate an instance of this class use {@link #builder}. <ide> */ <add>@ThreadSafe <ide> public class ReactInstanceManager { <ide> <ide> private static final String TAG = ReactInstanceManager.class.getSimpleName(); <ide> public interface ReactInstanceEventListener { <ide> void onReactContextInitialized(ReactContext context); <ide> } <ide> <del> /* should only be accessed from main thread (UI thread) */ <del> private final List<ReactRootView> mAttachedRootViews = new ArrayList<>(); <del> private LifecycleState mLifecycleState; <del> private @Nullable ReactContextInitParams mPendingReactContextInitParams; <del> private @Nullable ReactContextInitAsyncTask mReactContextInitAsyncTask; <del> private @Nullable Thread mCreateReactContextThread; <add> private final List<ReactRootView> mAttachedRootViews = Collections.synchronizedList( <add> new ArrayList<ReactRootView>()); <add> <add> private volatile LifecycleState mLifecycleState; <add> private @Nullable @ThreadConfined(UI) ReactContextInitParams mPendingReactContextInitParams; <add> private @Nullable @ThreadConfined(UI) ReactContextInitAsyncTask mReactContextInitAsyncTask; <add> private @Nullable @ThreadConfined(UI) Thread mCreateReactContextThread; <ide> <ide> /* accessed from any thread */ <ide> private final @Nullable JSBundleLoader mBundleLoader; /* path to JS bundle on file system */ <ide> public interface ReactInstanceEventListener { <ide> private final @Nullable NotThreadSafeBridgeIdleDebugListener mBridgeIdleDebugListener; <ide> private @Nullable volatile ReactContext mCurrentReactContext; <ide> private final Context mApplicationContext; <del> private @Nullable DefaultHardwareBackBtnHandler mDefaultBackButtonImpl; <add> private @Nullable @ThreadConfined(UI) DefaultHardwareBackBtnHandler mDefaultBackButtonImpl; <ide> private @Nullable Activity mCurrentActivity; <ide> private final Collection<ReactInstanceEventListener> mReactInstanceEventListeners = <ide> Collections.synchronizedSet(new HashSet<ReactInstanceEventListener>()); <ide> public void createReactContextInBackground() { <ide> * <ide> * Called from UI thread. <ide> */ <add> @ThreadConfined(UI) <ide> public void recreateReactContextInBackground() { <ide> Assertions.assertCondition( <ide> mHasStartedCreatingInitialContext, <ide> public void recreateReactContextInBackground() { <ide> recreateReactContextInBackgroundInner(); <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void recreateReactContextInBackgroundInner() { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> public void run() { <ide> recreateReactContextInBackgroundFromBundleLoader(); <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void recreateReactContextInBackgroundFromBundleLoader() { <ide> recreateReactContextInBackground( <ide> new JSCJavaScriptExecutor.Factory(mJSCConfig.getConfigMap()), <ide> private void invokeDefaultOnBackPressed() { <ide> /** <ide> * This method will give JS the opportunity to receive intents via Linking. <ide> */ <add> @ThreadConfined(UI) <ide> public void onNewIntent(Intent intent) { <add> UiThreadUtil.assertOnUiThread(); <ide> if (mCurrentReactContext == null) { <ide> FLog.w(ReactConstants.TAG, "Instance detached from instance manager"); <ide> } else { <ide> private void toggleElementInspector() { <ide> * <ide> * @deprecated Use {@link #onHostPause(Activity)} instead. <ide> */ <add> @ThreadConfined(UI) <ide> public void onHostPause() { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> public void onHostPause() { <ide> * <ide> * @param activity the activity being paused <ide> */ <add> @ThreadConfined(UI) <ide> public void onHostPause(Activity activity) { <ide> Assertions.assertNotNull(mCurrentActivity); <ide> Assertions.assertCondition( <ide> public void onHostPause(Activity activity) { <ide> * @param defaultBackButtonImpl a {@link DefaultHardwareBackBtnHandler} from an Activity that owns <ide> * this instance of {@link ReactInstanceManager}. <ide> */ <add> @ThreadConfined(UI) <ide> public void onHostResume(Activity activity, DefaultHardwareBackBtnHandler defaultBackButtonImpl) { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> public void onHostResume(Activity activity, DefaultHardwareBackBtnHandler defaul <ide> * <ide> * @deprecated use {@link #onHostDestroy(Activity)} instead <ide> */ <add> @ThreadConfined(UI) <ide> public void onHostDestroy() { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> public void onHostDestroy() { <ide> * <ide> * @param activity the activity being destroyed <ide> */ <add> @ThreadConfined(UI) <ide> public void onHostDestroy(Activity activity) { <ide> if (activity == mCurrentActivity) { <ide> onHostDestroy(); <ide> public void onHostDestroy(Activity activity) { <ide> /** <ide> * Destroy this React instance and the attached JS context. <ide> */ <add> @ThreadConfined(UI) <ide> public void destroy() { <ide> UiThreadUtil.assertOnUiThread(); <ide> <ide> public void destroy() { <ide> ResourceDrawableIdHelper.getInstance().clear(); <ide> } <ide> <del> private void moveToResumedLifecycleState(boolean force) { <add> private synchronized void moveToResumedLifecycleState(boolean force) { <ide> if (mCurrentReactContext != null) { <ide> // we currently don't have an onCreate callback so we call onResume for both transitions <ide> if (force || <ide> private void moveToResumedLifecycleState(boolean force) { <ide> mLifecycleState = LifecycleState.RESUMED; <ide> } <ide> <del> private void moveToBeforeResumeLifecycleState() { <add> private synchronized void moveToBeforeResumeLifecycleState() { <ide> if (mCurrentReactContext != null) { <ide> if (mLifecycleState == LifecycleState.BEFORE_CREATE) { <ide> mCurrentReactContext.onHostResume(mCurrentActivity); <ide> private void moveToBeforeResumeLifecycleState() { <ide> mLifecycleState = LifecycleState.BEFORE_RESUME; <ide> } <ide> <del> private void moveToBeforeCreateLifecycleState() { <add> private synchronized void moveToBeforeCreateLifecycleState() { <ide> if (mCurrentReactContext != null) { <ide> if (mLifecycleState == LifecycleState.RESUMED) { <ide> mCurrentReactContext.onHostPause(); <ide> private void moveToBeforeCreateLifecycleState() { <ide> mLifecycleState = LifecycleState.BEFORE_CREATE; <ide> } <ide> <add> private synchronized void moveReactContextToCurrentLifecycleState() { <add> if (mLifecycleState == LifecycleState.RESUMED) { <add> moveToResumedLifecycleState(true); <add> } <add> } <add> <add> @ThreadConfined(UI) <ide> public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { <ide> if (mCurrentReactContext != null) { <ide> mCurrentReactContext.onActivityResult(activity, requestCode, resultCode, data); <ide> } <ide> } <ide> <add> @ThreadConfined(UI) <ide> public void showDevOptionsDialog() { <ide> UiThreadUtil.assertOnUiThread(); <ide> mDevSupportManager.showDevOptionsDialog(); <ide> public void showDevOptionsDialog() { <ide> * This view will then be tracked by this manager and in case of catalyst instance restart it will <ide> * be re-attached. <ide> */ <add> @ThreadConfined(UI) <ide> public void attachMeasuredRootView(ReactRootView rootView) { <ide> UiThreadUtil.assertOnUiThread(); <ide> mAttachedRootViews.add(rootView); <ide> public void attachMeasuredRootView(ReactRootView rootView) { <ide> * multiple times on the same {@param rootView} - in that case view will be detached with the <ide> * first call. <ide> */ <add> @ThreadConfined(UI) <ide> public void detachRootView(ReactRootView rootView) { <ide> UiThreadUtil.assertOnUiThread(); <ide> if (mAttachedRootViews.remove(rootView)) { <ide> public LifecycleState getLifecycleState() { <ide> return mLifecycleState; <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) { <ide> recreateReactContextInBackground( <ide> new ProxyJavaScriptExecutor.Factory(jsExecutorFactory), <ide> private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) { <ide> mDevSupportManager.getSourceUrl())); <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void onJSBundleLoadedFromServer() { <ide> recreateReactContextInBackground( <ide> new JSCJavaScriptExecutor.Factory(mJSCConfig.getConfigMap()), <ide> private void onJSBundleLoadedFromServer() { <ide> mDevSupportManager.getDownloadedJSBundleFile())); <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void recreateReactContextInBackground( <ide> JavaScriptExecutor.Factory jsExecutorFactory, <ide> JSBundleLoader jsBundleLoader) { <ide> private void recreateReactContextInBackground( <ide> mReactContextInitAsyncTask = new ReactContextInitAsyncTask(); <ide> mReactContextInitAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, initParams); <ide> } else { <del> // Background task is currently running, queue up most recent init params to recreate context <del> // once task completes. <add> // Background task is currently running, queue up most recent init params to recreate <add> // context once task completes. <ide> mPendingReactContextInitParams = initParams; <ide> } <ide> } <ide> } <ide> <add> @ThreadConfined(UI) <ide> private void runCreateReactContextOnNewThread(final ReactContextInitParams initParams) { <add> UiThreadUtil.assertOnUiThread(); <ide> if (mCurrentReactContext != null) { <ide> tearDownReactContext(mCurrentReactContext); <ide> mCurrentReactContext = null; <ide> private void setupReactContext(ReactApplicationContext reactContext) { <ide> mMemoryPressureRouter.addMemoryPressureListener(catalystInstance); <ide> moveReactContextToCurrentLifecycleState(); <ide> <del> for (ReactRootView rootView : mAttachedRootViews) { <del> attachMeasuredRootViewToInstance(rootView, catalystInstance); <add> synchronized (mAttachedRootViews) { <add> for (ReactRootView rootView : mAttachedRootViews) { <add> attachMeasuredRootViewToInstance(rootView, catalystInstance); <add> } <ide> } <ide> <ide> ReactInstanceEventListener[] listeners = <ide> private void tearDownReactContext(ReactContext reactContext) { <ide> if (mLifecycleState == LifecycleState.RESUMED) { <ide> reactContext.onHostPause(); <ide> } <del> for (ReactRootView rootView : mAttachedRootViews) { <del> detachViewFromInstance(rootView, reactContext.getCatalystInstance()); <add> synchronized (mAttachedRootViews) { <add> for (ReactRootView rootView : mAttachedRootViews) { <add> detachViewFromInstance(rootView, reactContext.getCatalystInstance()); <add> } <ide> } <ide> reactContext.destroy(); <ide> mDevSupportManager.onReactInstanceDestroyed(reactContext); <ide> private void processPackage( <ide> } <ide> Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <del> <del> private void moveReactContextToCurrentLifecycleState() { <del> if (mLifecycleState == LifecycleState.RESUMED) { <del> moveToResumedLifecycleState(true); <del> } <del> } <ide> }
1
Text
Text
use code markup/markdown in headers
b46efa96cd8ab6ff44a4ffa0bb4f87010aa55d76
<ide><path>doc/api/wasi.md <ide> const importObject = { wasi_snapshot_preview1: wasi.wasiImport }; <ide> The `--experimental-wasi-unstable-preview1` and `--experimental-wasm-bigint` <ide> CLI arguments are needed for the previous example to run. <ide> <del>## Class: WASI <add>## Class: `WASI` <ide> <!-- YAML <ide> added: v13.3.0 <ide> --> <ide> represents a distinct sandbox environment. For security purposes, each `WASI` <ide> instance must have its command line arguments, environment variables, and <ide> sandbox directory structure configured explicitly. <ide> <del>### new WASI(\[options\]) <add>### `new WASI([options])` <ide> <!-- YAML <ide> added: v13.3.0 <ide> --> <ide> added: v13.3.0 <ide> directories within the sandbox. The corresponding values in `preopens` are <ide> the real paths to those directories on the host machine. <ide> <del>### wasi.start(instance) <add>### `wasi.start(instance)` <ide> <!-- YAML <ide> added: v13.3.0 <ide> --> <ide> is present on `instance`, then `start()` does nothing. <ide> `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named <ide> `memory`. If `instance` does not have a `memory` export an exception is thrown. <ide> <del>### wasi.wasiImport <add>### `wasi.wasiImport` <ide> <!-- YAML <ide> added: v13.3.0 <ide> -->
1
Javascript
Javascript
stub the storage folder application.json read
e35510e928b8f5a74c13c6f720905674f059c01c
<ide><path>spec/main-process/atom-application.new.test.js <ide> class LaunchScenario { <ide> ...options <ide> }) <ide> this.sinon.stub(app, 'createWindow', loadSettings => new StubWindow(this.sinon, loadSettings, options)) <add> this.sinon.stub(app.storageFolder, 'load', () => Promise.resolve( <add> (options.applicationJson || []).map(each => ({ <add> initialPaths: this.convertPaths(each.initialPaths) <add> })) <add> )) <ide> this.applications.add(app) <ide> return app <ide> }
1
Mixed
Python
reduce memory usage of lookup's bloomfilter
90c7eb0e2f51eb07582c4d9e3fcaed1fdb51c4bc
<ide><path>.github/contributors/PluieElectrique.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI GmbH](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [X] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Pluie | <add>| Company name (if applicable) | | <add>| Title or role (if applicable) | | <add>| Date | 2020-06-18 | <add>| GitHub username | PluieElectrique | <add>| Website (optional) | | <ide><path>spacy/lookups.py <ide> def from_bytes(self, bytes_data, **kwargs): <ide> """ <ide> self._tables = OrderedDict() <ide> for key, value in srsly.msgpack_loads(bytes_data).items(): <del> self._tables[key] = Table(key) <del> self._tables[key].update(value) <add> self._tables[key] = Table(key, value) <ide> return self <ide> <ide> def to_disk(self, path, filename="lookups.bin", **kwargs): <ide> def __init__(self, name=None, data=None): <ide> self.name = name <ide> # Assume a default size of 1M items <ide> self.default_size = 1e6 <del> size = len(data) if data and len(data) > 0 else self.default_size <add> size = max(len(data), 1) if data is not None else self.default_size <ide> self.bloom = BloomFilter.from_error_rate(size) <ide> if data: <ide> self.update(data)
2
Javascript
Javascript
add support for es6 object initializers
b5a0c8d2ea6d595fac18805e25c8a4797b07c7f1
<ide><path>src/ng/parse.js <ide> AST.prototype = { <ide> property = {type: AST.Property, kind: 'init'}; <ide> if (this.peek().constant) { <ide> property.key = this.constant(); <add> property.computed = false; <add> this.consume(':'); <add> property.value = this.expression(); <ide> } else if (this.peek().identifier) { <ide> property.key = this.identifier(); <add> property.computed = false; <add> if (this.peek(':')) { <add> this.consume(':'); <add> property.value = this.expression(); <add> } else { <add> property.value = property.key; <add> } <add> } else if (this.peek('[')) { <add> this.consume('['); <add> property.key = this.expression(); <add> this.consume(']'); <add> property.computed = true; <add> this.consume(':'); <add> property.value = this.expression(); <ide> } else { <ide> this.throwError("invalid key", this.peek()); <ide> } <del> this.consume(':'); <del> property.value = this.expression(); <ide> properties.push(property); <ide> } while (this.expect(',')); <ide> } <ide> function findConstantAndWatchExpressions(ast, $filter) { <ide> argsToWatch = []; <ide> forEach(ast.properties, function(property) { <ide> findConstantAndWatchExpressions(property.value, $filter); <del> allConstants = allConstants && property.value.constant; <add> allConstants = allConstants && property.value.constant && !property.computed; <ide> if (!property.value.constant) { <ide> argsToWatch.push.apply(argsToWatch, property.value.toWatch); <ide> } <ide> ASTCompiler.prototype = { <ide> }, <ide> <ide> recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { <del> var left, right, self = this, args, expression; <add> var left, right, self = this, args, expression, computed; <ide> recursionFn = recursionFn || noop; <ide> if (!skipWatchIdCheck && isDefined(ast.watchId)) { <ide> intoId = intoId || this.nextId(); <ide> ASTCompiler.prototype = { <ide> break; <ide> case AST.ObjectExpression: <ide> args = []; <add> computed = false; <ide> forEach(ast.properties, function(property) { <del> self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { <del> args.push(self.escape( <del> property.key.type === AST.Identifier ? property.key.name : <del> ('' + property.key.value)) + <del> ':' + expr); <del> }); <add> if (property.computed) { <add> computed = true; <add> } <ide> }); <del> expression = '{' + args.join(',') + '}'; <del> this.assign(intoId, expression); <add> if (computed) { <add> intoId = intoId || this.nextId(); <add> this.assign(intoId, '{}'); <add> forEach(ast.properties, function(property) { <add> if (property.computed) { <add> left = self.nextId(); <add> self.recurse(property.key, left); <add> } else { <add> left = property.key.type === AST.Identifier ? <add> property.key.name : <add> ('' + property.key.value); <add> } <add> right = self.nextId(); <add> self.recurse(property.value, right); <add> self.assign(self.member(intoId, left, property.computed), right); <add> }); <add> } else { <add> forEach(ast.properties, function(property) { <add> self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { <add> args.push(self.escape( <add> property.key.type === AST.Identifier ? property.key.name : <add> ('' + property.key.value)) + <add> ':' + expr); <add> }); <add> }); <add> expression = '{' + args.join(',') + '}'; <add> this.assign(intoId, expression); <add> } <ide> recursionFn(intoId || expression); <ide> break; <ide> case AST.ThisExpression: <ide> ASTInterpreter.prototype = { <ide> case AST.ObjectExpression: <ide> args = []; <ide> forEach(ast.properties, function(property) { <del> args.push({key: property.key.type === AST.Identifier ? <del> property.key.name : <del> ('' + property.key.value), <del> value: self.recurse(property.value) <del> }); <add> if (property.computed) { <add> args.push({key: self.recurse(property.key), <add> computed: true, <add> value: self.recurse(property.value) <add> }); <add> } else { <add> args.push({key: property.key.type === AST.Identifier ? <add> property.key.name : <add> ('' + property.key.value), <add> computed: false, <add> value: self.recurse(property.value) <add> }); <add> } <ide> }); <ide> return function(scope, locals, assign, inputs) { <ide> var value = {}; <ide> for (var i = 0; i < args.length; ++i) { <del> value[args[i].key] = args[i].value(scope, locals, assign, inputs); <add> if (args[i].computed) { <add> value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs); <add> } else { <add> value[args[i].key] = args[i].value(scope, locals, assign, inputs); <add> } <ide> } <ide> return context ? {value: value} : value; <ide> }; <ide><path>test/ng/parseSpec.js <ide> describe('parser', function() { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Identifier', name: 'foo' }, <add> computed: false, <ide> value: { type: 'Identifier', name: 'bar' } <ide> } <ide> ] <ide> describe('parser', function() { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Identifier', name: 'foo' }, <add> computed: false, <ide> value: { type: 'Identifier', name: 'bar' } <ide> } <ide> ] <ide> describe('parser', function() { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Identifier', name: 'foo' }, <add> computed: false, <ide> value: { type: 'Identifier', name: 'bar' } <ide> }, <ide> { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Literal', value: 'man' }, <add> computed: false, <ide> value: { type: 'Literal', value: 'shell' } <ide> }, <ide> { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Literal', value: 42 }, <add> computed: false, <ide> value: { type: 'Literal', value: 23 } <ide> } <ide> ] <ide> describe('parser', function() { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Identifier', name: 'foo' }, <add> computed: false, <ide> value: { type: 'Identifier', name: 'bar' } <ide> }, <ide> { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Literal', value: 'man' }, <add> computed: false, <ide> value: { type: 'Literal', value: 'shell' } <ide> }, <ide> { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Literal', value: 42 }, <add> computed: false, <ide> value: { type: 'Literal', value: 23 } <ide> } <ide> ] <ide> describe('parser', function() { <ide> ); <ide> }); <ide> <add> it('should understand ES6 object initializer', function() { <add> // Shorthand properties definitions. <add> expect(createAst('{x, y, z}')).toEqual( <add> { <add> type: 'Program', <add> body: [ <add> { <add> type: 'ExpressionStatement', <add> expression: { <add> type: 'ObjectExpression', <add> properties: [ <add> { <add> type: 'Property', <add> kind: 'init', <add> key: { type: 'Identifier', name: 'x' }, <add> computed: false, <add> value: { type: 'Identifier', name: 'x' } <add> }, <add> { <add> type: 'Property', <add> kind: 'init', <add> key: { type: 'Identifier', name: 'y' }, <add> computed: false, <add> value: { type: 'Identifier', name: 'y' } <add> }, <add> { <add> type: 'Property', <add> kind: 'init', <add> key: { type: 'Identifier', name: 'z' }, <add> computed: false, <add> value: { type: 'Identifier', name: 'z' } <add> } <add> ] <add> } <add> } <add> ] <add> } <add> ); <add> expect(function() { createAst('{"foo"}'); }).toThrow(); <add> <add> // Computed properties <add> expect(createAst('{[x]: x}')).toEqual( <add> { <add> type: 'Program', <add> body: [ <add> { <add> type: 'ExpressionStatement', <add> expression: { <add> type: 'ObjectExpression', <add> properties: [ <add> { <add> type: 'Property', <add> kind: 'init', <add> key: { type: 'Identifier', name: 'x' }, <add> computed: true, <add> value: { type: 'Identifier', name: 'x' } <add> } <add> ] <add> } <add> } <add> ] <add> } <add> ); <add> expect(createAst('{[x + 1]: x}')).toEqual( <add> { <add> type: 'Program', <add> body: [ <add> { <add> type: 'ExpressionStatement', <add> expression: { <add> type: 'ObjectExpression', <add> properties: [ <add> { <add> type: 'Property', <add> kind: 'init', <add> key: { <add> type: 'BinaryExpression', <add> operator: '+', <add> left: { type: 'Identifier', name: 'x' }, <add> right: { type: 'Literal', value: 1 } <add> }, <add> computed: true, <add> value: { type: 'Identifier', name: 'x' } <add> } <add> ] <add> } <add> } <add> ] <add> } <add> ); <add> }); <ide> <ide> it('should understand multiple expressions', function() { <ide> expect(createAst('foo = bar; man = shell')).toEqual( <ide> describe('parser', function() { <ide> type: 'Property', <ide> kind: 'init', <ide> key: { type: 'Identifier', name: 'foo' }, <add> computed: false, <ide> value: { <ide> type: 'AssignmentExpression', <ide> left: { type: 'Identifier', name: 'bar' }, <ide> describe('parser', function() { <ide> expect(scope.$eval("{false:1}")).toEqual({false:1}); <ide> expect(scope.$eval("{'false':1}")).toEqual({false:1}); <ide> expect(scope.$eval("{'':1,}")).toEqual({"":1}); <add> <add> // ES6 object initializers. <add> expect(scope.$eval('{x, y}', {x: 'foo', y: 'bar'})).toEqual({x: 'foo', y: 'bar'}); <add> expect(scope.$eval('{[x]: x}', {x: 'foo'})).toEqual({foo: 'foo'}); <add> expect(scope.$eval('{[x + "z"]: x}', {x: 'foo'})).toEqual({fooz: 'foo'}); <add> expect(scope.$eval('{x, 1: x, [x = x + 1]: x, 3: x + 1, [x = x + 2]: x, 5: x + 1}', {x: 1})) <add> .toEqual({x: 1, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5}); <ide> }); <ide> <ide> it('should throw syntax error exception for non constant/identifier JSON keys', function() { <ide> expect(function() { scope.$eval("{[:0}"); }).toThrowMinErr("$parse", "syntax", <del> "Syntax Error: Token '[' invalid key at column 2 of the expression [{[:0}] starting at [[:0}]"); <add> "Syntax Error: Token ':' not a primary expression at column 3 of the expression [{[:0}] starting at [:0}]"); <ide> expect(function() { scope.$eval("{{:0}"); }).toThrowMinErr("$parse", "syntax", <ide> "Syntax Error: Token '{' invalid key at column 2 of the expression [{{:0}] starting at [{:0}]"); <ide> expect(function() { scope.$eval("{?:0}"); }).toThrowMinErr("$parse", "syntax", <ide> describe('parser', function() { <ide> expect($parse('"foo" + "bar"').constant).toBe(true); <ide> expect($parse('5 != null').constant).toBe(true); <ide> expect($parse('{standard: 4/3, wide: 16/9}').constant).toBe(true); <add> expect($parse('{[standard]: 4/3, wide: 16/9}').constant).toBe(false); <ide> })); <ide> <ide> it('should not mark any expression involving variables or function calls as constant', inject(function($parse) {
2
Javascript
Javascript
replace callback with arrow functions
9d34a1e3c0449c46105dd7403120b482b1444205
<ide><path>test/pummel/test-keep-alive.js <ide> const http = require('http'); <ide> const url = require('url'); <ide> <ide> const body = 'hello world\n'; <del>const server = http.createServer(function(req, res) { <add>const server = http.createServer((req, res) => { <ide> res.writeHead(200, { <ide> 'Content-Length': body.length, <ide> 'Content-Type': 'text/plain' <ide> let keepAliveReqSec = 0; <ide> let normalReqSec = 0; <ide> <ide> <del>function runAb(opts, callback) { <add>const runAb = (opts, callback) => { <ide> const args = [ <ide> '-c', opts.concurrent || 100, <ide> '-t', opts.threads || 2, <ide> function runAb(opts, callback) { <ide> <ide> let stdout; <ide> <del> child.stdout.on('data', function(data) { <del> stdout += data; <del> }); <add> child.stdout.on('data', (data) => stdout += data); <ide> <del> child.on('close', function(code, signal) { <add> child.on('close', (code, signal) => { <ide> if (code) { <ide> console.error(code, signal); <ide> process.exit(code); <ide> function runAb(opts, callback) { <ide> <ide> callback(reqSec, keepAliveRequests); <ide> }); <del>} <add>}; <ide> <ide> server.listen(common.PORT, () => { <ide> runAb({ keepalive: true }, (reqSec) => { <ide> keepAliveReqSec = reqSec; <ide> <del> runAb({ keepalive: false }, function(reqSec) { <add> runAb({ keepalive: false }, (reqSec) => { <ide> normalReqSec = reqSec; <ide> server.close(); <ide> }); <ide> }); <ide> }); <ide> <del>process.on('exit', function() { <add>process.on('exit', () => { <ide> assert.strictEqual( <ide> normalReqSec > 50, <ide> true,
1
Java
Java
add marbles for single.amb operators
1aeac067ae3c9844f77d264e47de6a31f3eb1a53
<ide><path>src/main/java/io/reactivex/Single.java <ide> /** <ide> * Runs multiple SingleSources and signals the events of the first one that signals (cancelling <ide> * the rest). <add> * <p> <add> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.amb.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code amb} does not operate by default on a particular {@link Scheduler}.</dd> <ide> public static <T> Single<T> amb(final Iterable<? extends SingleSource<? extends <ide> /** <ide> * Runs multiple SingleSources and signals the events of the first one that signals (cancelling <ide> * the rest). <add> * <p> <add> * <img width="640" height="515" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.ambArray.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code ambArray} does not operate by default on a particular {@link Scheduler}.</dd>
1
Python
Python
remove unused activation dropout
9faa9f9dacf8c818ab2513da3ef92ce66f39515d
<ide><path>src/transformers/models/opt/configuration_opt.py <ide> class OPTConfig(PretrainedConfig): <ide> The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. <ide> attention_dropout (`float`, *optional*, defaults to 0.0): <ide> The dropout ratio for the attention probabilities. <del> activation_dropout (`float`, *optional*, defaults to 0.0): <del> The dropout ratio for activations inside the fully connected layer. <ide> layerdrop: (`float`, *optional*, defaults to 0.0): <ide> The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more <ide> details. <ide> def __init__( <ide> word_embed_proj_dim=None, <ide> dropout=0.1, <ide> attention_dropout=0.0, <del> activation_dropout=0.0, <ide> num_attention_heads=12, <ide> activation_function="relu", <ide> layerdrop=0.0, <ide> def __init__( <ide> self.num_hidden_layers = num_hidden_layers <ide> self.dropout = dropout <ide> self.attention_dropout = attention_dropout <del> self.activation_dropout = activation_dropout <ide> self.activation_function = activation_function <ide> self.init_std = init_std <ide> self.layerdrop = layerdrop <ide><path>src/transformers/models/opt/modeling_opt.py <ide> def __init__(self, config: OPTConfig): <ide> self.dropout = config.dropout <ide> self.activation_fn = ACT2FN[config.activation_function] <ide> <del> self.activation_dropout = config.activation_dropout <del> <ide> self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) <ide> self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim) <ide> self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim)
2
PHP
PHP
make comparison stricter
2937ea9ba5fdba316043de72c315ddffc73d8970
<ide><path>lib/Cake/Console/Command/Task/ExtractTask.php <ide> protected function _extractTokens() { <ide> <ide> $this->_tokens = array(); <ide> foreach ($allTokens as $token) { <del> if (!is_array($token) || ($token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML)) { <add> if (!is_array($token) || ($token[0] !== T_WHITESPACE && $token[0] !== T_INLINE_HTML)) { <ide> $this->_tokens[] = $token; <ide> } <ide> }
1
Java
Java
revise testaotprocessortests to rely on path apis
4e9fad7514479cdbd762635f6f70bdaf796e8981
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestAotProcessorTests.java <ide> import java.io.UncheckedIOException; <ide> import java.nio.file.Files; <ide> import java.nio.file.Path; <add>import java.util.Arrays; <add>import java.util.List; <ide> import java.util.stream.Stream; <ide> <ide> import org.junit.jupiter.api.Test; <ide> void process(@TempDir(cleanup = CleanupMode.ON_SUCCESS) Path tempDir) throws Exc <ide> TestAotProcessor processor = new TestAotProcessor(classpathRoots, sourceOutput, resourceOutput, classOutput, groupId, artifactId); <ide> processor.process(); <ide> <del> assertThat(findFiles(sourceOutput)).containsExactlyInAnyOrder(expectedSourceFiles); <add> assertThat(findFiles(sourceOutput)).containsExactlyInAnyOrderElementsOf(expectedSourceFiles()); <ide> <ide> assertThat(findFiles(resourceOutput.resolve("META-INF/native-image"))).contains( <del> "org.example/app-tests/reflect-config.json", <del> "org.example/app-tests/resource-config.json"); <add> Path.of(groupId, artifactId, "reflect-config.json"), <add> Path.of(groupId, artifactId, "resource-config.json")); <ide> } <ide> <ide> private void copy(Class<?> testClass, Path destination) { <ide> private void copy(Class<?> testClass, Path destination) { <ide> } <ide> } <ide> <del> private static Stream<String> findFiles(Path directory) throws IOException { <add> private static Stream<Path> findFiles(Path directory) throws IOException { <ide> return Files.walk(directory).filter(Files::isRegularFile) <del> .map(path -> path.subpath(directory.getNameCount(), path.getNameCount())) <del> // Convert Windows path to UNIX path since the expectedSourceFiles array is hard coded <del> .map(path -> path.toString().replace('\\', '/')); <add> .map(path -> path.subpath(directory.getNameCount(), path.getNameCount())); <add> } <add> <add> private static List<Path> expectedSourceFiles() { <add> return Arrays.stream(expectedSourceFiles).map(Path::of).toList(); <ide> } <ide> <ide> private static final String[] expectedSourceFiles = {
1
Ruby
Ruby
rewrite plists when installing from a bottle
340769443c5d2644afdb3af817ea23c0176c89d8
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def install_symlink_p src, new_basename = nil <ide> <ide> # we assume this pathname object is a file obviously <ide> def write content <del> #raise "Will not overwrite #{to_s}" if exist? and not ARGV.force? <add> raise "Will not overwrite #{to_s}" if exist? and not ARGV.force? <ide> dirname.mkpath <ide> File.open(self, 'w') {|f| f.write content } <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> def link <ide> end <ide> <ide> def install_plist <del> # Install a plist if one is defined <del> # Skip plist file exists check: https://github.com/mxcl/homebrew/issues/15849 <ide> if f.startup_plist <add> # A plist may already exist if we are installing from a bottle <add> f.plist_path.unlink if f.plist_path.exist? <ide> f.plist_path.write f.startup_plist <ide> f.plist_path.chmod 0644 <ide> end
2
Javascript
Javascript
remove reactdom from jest blacklist
1bc03871f391d4df958dd8af97c6002cdef5f943
<ide><path>packager/blacklist.js <ide> var sharedBlacklist = [ <ide> 'downstream/core/toArray.js', <ide> <ide> /website\/node_modules\/.*/, <add> <add> // TODO(jkassens, #9876132): Remove this rule when it's no longer needed. <add> 'downstream/relay/tools/relayUnstableBatchedUpdates.js', <ide> ]; <ide> <ide> var platformBlacklists = {
1
Javascript
Javascript
fix many tests for http streams2 refactor
0977638ffb016c9e1ace5a9f6299d4bd4c27688c
<ide><path>test/simple/test-cluster-http-pipe.js <ide> http.createServer(function(req, res) { <ide> }).listen(common.PIPE, function() { <ide> var self = this; <ide> http.get({ socketPath: common.PIPE, path: '/' }, function(res) { <add> res.resume(); <ide> res.on('end', function(err) { <ide> if (err) throw err; <ide> process.send('DONE'); <ide><path>test/simple/test-domain-http-server.js <ide> var disposeEmit = 0; <ide> <ide> var server = http.createServer(function(req, res) { <ide> var dom = domain.create(); <add> req.resume(); <ide> dom.add(req); <ide> dom.add(res); <ide> <ide><path>test/simple/test-http-abort-client.js <ide> server.listen(common.PORT, function() { <ide> <ide> res.on('data', function(chunk) { <ide> console.log('Read ' + chunk.length + ' bytes'); <del> console.log(chunk.toString()); <add> console.log(' chunk=%j', chunk.toString()); <ide> }); <ide> <ide> res.on('end', function() { <ide> console.log('Response ended.'); <ide> }); <ide> <add> res.on('aborted', function() { <add> console.log('Response aborted.'); <add> }); <add> <add> res.socket.on('close', function() { <add> console.log('socket closed, but not res'); <add> }) <add> <ide> // it would be nice if this worked: <ide> res.on('close', function() { <ide> console.log('Response aborted'); <ide><path>test/simple/test-http-client-agent.js <ide> function request(i) { <ide> server.close(); <ide> } <ide> }); <add> res.resume(); <ide> }); <ide> } <ide> <ide><path>test/simple/test-http-client-pipe-end.js <ide> var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var server = http.createServer(function(req, res) { <add> req.resume(); <ide> req.once('end', function() { <ide> res.writeHead(200); <ide> res.end(); <ide> server.listen(common.PIPE, function() { <ide> function sched(cb, ticks) { <ide> function fn() { <ide> if (--ticks) <del> process.nextTick(fn); <add> setImmediate(fn); <ide> else <ide> cb(); <ide> } <del> process.nextTick(fn); <add> setImmediate(fn); <ide> }
5
Python
Python
allow higher version of sqlalchemy
45b068b5a5ec51e907adca59fc37aab9eee6b91d
<ide><path>setup.py <ide> def run_tests(self): <ide> 'python-dateutil>=2.3, <3', <ide> 'requests>=2.5.1, <3', <ide> 'setproctitle>=1.1.8, <2', <del> 'sqlalchemy>=0.9.8, <0.10', <add> 'sqlalchemy>=0.9.8', <ide> 'thrift>=0.9.2, <0.10', <ide> ], <ide> extras_require={
1
Javascript
Javascript
fix rotation regression from
1bbf0e55b09e73cf794ff9f0459214e46f208aa2
<ide><path>web/page_view.js <ide> var PageView = function pageView(container, id, scale, <ide> this.rotation = 0; <ide> this.scale = scale || 1.0; <ide> this.viewport = defaultViewport; <del> this.pdfPageRotate = defaultViewport.rotate; <add> this.pdfPageRotate = defaultViewport.rotation; <ide> <ide> this.renderingState = RenderingStates.INITIAL; <ide> this.resume = null; <ide> var PageView = function pageView(container, id, scale, <ide> this.setPdfPage = function pageViewSetPdfPage(pdfPage) { <ide> this.pdfPage = pdfPage; <ide> this.pdfPageRotate = pdfPage.rotate; <del> this.updateViewport(); <add> var totalRotation = (this.rotation + this.pdfPageRotate) % 360; <add> this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS, totalRotation); <ide> this.stats = pdfPage.stats; <ide> this.reset(); <ide> }; <ide> <del> this.updateViewport = function pageViewUpdateViewport() { <del> var totalRotation = (this.rotation + this.pdfPageRotate) % 360; <del> this.viewport = this.viewport.clone({ <del> scale: this.scale * CSS_UNITS, <del> rotation: totalRotation <del> }); <del> }, <del> <ide> this.destroy = function pageViewDestroy() { <ide> this.zoomLayer = null; <ide> this.reset(); <ide> var PageView = function pageView(container, id, scale, <ide> this.rotation = rotation; <ide> } <ide> <del> this.updateViewport(); <add> var totalRotation = (this.rotation + this.pdfPageRotate) % 360; <add> this.viewport = this.viewport.clone({ <add> scale: this.scale * CSS_UNITS, <add> rotation: totalRotation <add> }); <ide> <ide> if (USE_ONLY_CSS_ZOOM && this.canvas) { <ide> this.cssTransform(this.canvas);
1
Javascript
Javascript
keep unsubscribed donors as isdonating
0a2f01c9d8873e7fd9064bd5d126367bc87772f2
<ide><path>api-server/server/utils/donation.js <ide> export async function cancelDonation(body, app) { <ide> const { <ide> resource: { id, status_update_time = new Date(Date.now()).toISOString() } <ide> } = body; <del> const { User, Donation } = app.models; <add> const { Donation } = app.models; <ide> Donation.findOne({ where: { subscriptionId: id } }, (err, donation) => { <ide> if (err || !donation) throw Error(err); <del> const userId = donation.userId; <ide> log(`Updating donation record: ${donation.subscriptionId}`); <ide> donation.updateAttributes({ <ide> endDate: new Date(status_update_time).toISOString() <ide> }); <del> <del> User.findOne({ where: { id: userId } }, (err, user) => { <del> if (err || !user || !user.donationEmails) throw Error(err); <del> log('Updating user record for donation cancellation'); <del> user.updateAttributes({ <del> isDonating: false <del> }); <del> }); <ide> }); <ide> } <ide> <ide><path>api-server/server/utils/donation.test.js <ide> describe('donation', () => { <ide> expect(updateDonationAttr).toHaveBeenCalledWith({ <ide> endDate: new Date(status_update_time).toISOString() <ide> }); <del> <del> expect(updateUserAttr).toHaveBeenCalledWith({ <del> isDonating: false <del> }); <add> expect(updateUserAttr).not.toHaveBeenCalled(); <ide> }); <ide> }); <ide> });
2
Text
Text
add model card
43eca3f878603b2e7edb375f9551b21c5e4a70ec
<ide><path>model_cards/mrm8488/spanbert-base-finetuned-squadv2/README.md <add>--- <add>language: english <add>thumbnail: <add>--- <add> <add># SpanBERT base fine-tuned on SQuAD v2 <add> <add>[SpanBERT](https://github.com/facebookresearch/SpanBERT) created by [Facebook Research](https://github.com/facebookresearch) and fine-tuned on [SQuAD 2.0](https://rajpurkar.github.io/SQuAD-explorer/) for **Q&A** downstream task ([by them](https://github.com/facebookresearch/SpanBERT#finetuned-models-squad-1120-relation-extraction-coreference-resolution)). <add> <add>## Details of SpanBERT <add> <add>[SpanBERT: Improving Pre-training by Representing and Predicting Spans](https://arxiv.org/abs/1907.10529) <add> <add>## Details of the downstream task (Q&A) - Dataset 📚 🧐 ❓ <add> <add>[SQuAD2.0](https://rajpurkar.github.io/SQuAD-explorer/) combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions written adversarially by crowdworkers to look similar to answerable ones. To do well on SQuAD2.0, systems must not only answer questions when possible, but also determine when no answer is supported by the paragraph and abstain from answering. <add> <add>| Dataset | Split | # samples | <add>| -------- | ----- | --------- | <add>| SQuAD2.0 | train | 130k | <add>| SQuAD2.0 | eval | 12.3k | <add> <add>## Model fine-tuning 🏋️‍ <add> <add>You can get the fine-tuning script [here](https://github.com/facebookresearch/SpanBERT) <add> <add>```bash <add>python code/run_squad.py \ <add> --do_train \ <add> --do_eval \ <add> --model spanbert-base-cased \ <add> --train_file train-v2.0.json \ <add> --dev_file dev-v2.0.json \ <add> --train_batch_size 32 \ <add> --eval_batch_size 32 \ <add> --learning_rate 2e-5 \ <add> --num_train_epochs 4 \ <add> --max_seq_length 512 \ <add> --doc_stride 128 \ <add> --eval_metric best_f1 \ <add> --output_dir squad2_output \ <add> --version_2_with_negative \ <add> --fp16 <add>``` <add> <add>## Results Comparison 📝 <add> <add>| | SQuAD 1.1 | SQuAD 2.0 | Coref | TACRED | <add>| ---------------------- | ------------- | --------- | ------- | ------ | <add>| | F1 | F1 | avg. F1 | F1 | <add>| BERT (base) | 88.5 | 76.5 | 73.1 | 67.7 | <add>| SpanBERT (base) | [92.4](https://huggingface.co/mrm8488/spanbert-base-finetuned-squadv1) | **83.6** (this one) | 77.4 | [68.2](https://huggingface.co/mrm8488/spanbert-base-finetuned-tacred) | <add>| BERT (large) | 91.3 | 83.3 | 77.1 | 66.4 | <add>| SpanBERT (large) | [94.6](https://huggingface.co/mrm8488/spanbert-large-finetuned-squadv1) | [88.7](https://huggingface.co/mrm8488/spanbert-large-finetuned-squadv2) | 79.6 | [70.8](https://huggingface.co/mrm8488/spanbert-large-finetuned-tacred) | <add> <add> <add>Note: The numbers marked as * are evaluated on the development sets becaus those models were not submitted to the official SQuAD leaderboard. All the other numbers are test numbers. <add> <add>## Model in action <add> <add>Fast usage with **pipelines**: <add> <add>```python <add>from transformers import pipeline <add> <add>qa_pipeline = pipeline( <add> "question-answering", <add> model="mrm8488/spanbert-base-finetuned-squadv2", <add> tokenizer="SpanBERT/spanbert-base-cased" <add>) <add> <add>qa_pipeline({ <add> 'context': "Manuel Romero has been working very hard in the repository hugginface/transformers lately", <add> 'question': "How has been working Manuel Romero lately?" <add> <add>}) <add># Output: {'answer': 'very hard', 'end': 40, 'score': 0.9052708846768347, 'start': 31} <add>``` <add> <add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488) <add> <add>> Made with <span style="color: #e25555;">&hearts;</span> in Spain
1
Text
Text
give credits to all the envolved people [ci skip]
9d6a5b44320bb4655cf7b633668fed1ab8ddcac2
<ide><path>activesupport/CHANGELOG.md <ide> These characters are legal in JSON but break the Javascript interpreter. <ide> After escaping them, the JSON is still legal and can be parsed by Javascript. <ide> <del> *Mario Caropreso* <add> *Mario Caropreso + Viktor Kelemen + zackham* <ide> <ide> * Fix skipping object callbacks using metadata fetched via callback chain <ide> inspection methods (`_*_callbacks`)
1
Ruby
Ruby
add delete_pyc_files! method
916e751596535177510f0c2043ecc16c392f12e2
<ide><path>Library/Homebrew/keg.rb <ide> def optlink <ide> from.make_relative_symlink(self) <ide> end <ide> <add> def delete_pyc_files! <add> Pathname.new(self).find do |pn| <add> next if pn.extname != '.pyc' <add> pn.delete <add> end <add> end <add> <ide> protected <ide> <ide> def resolve_any_conflicts dst
1
PHP
PHP
add support for "mail" driver
c222355edb06e01a9718c37676485ecab36f7d74
<ide><path>src/Illuminate/Mail/MailServiceProvider.php <ide> use Swift_Mailer; <ide> use Illuminate\Support\ServiceProvider; <ide> use Swift_SmtpTransport as SmtpTransport; <add>use Swift_MailTransport as MailTransport; <ide> <ide> class MailServiceProvider extends ServiceProvider { <ide> <ide> protected function registerSwiftMailer() <ide> * @return void <ide> */ <ide> protected function registerSwiftTransport($config) <add> { <add> switch ($config['driver']) <add> { <add> case 'smtp': <add> return $this->registerSmtpTransport($config); <add> <add> case 'mail': <add> return $this->registerMailTransport($config); <add> <add> default: <add> throw new \InvalidArgumentException('Invalid mail driver.'); <add> } <add> } <add> <add> /** <add> * Register the SMTP Swift Transport instance. <add> * <add> * @param array $config <add> * @return void <add> */ <add> protected function registerSmtpTransport($config) <ide> { <ide> $this->app['swift.transport'] = $this->app->share(function($app) use ($config) <ide> { <ide> protected function registerSwiftTransport($config) <ide> }); <ide> } <ide> <add> /** <add> * Register the Mail Swift Transport instance. <add> * <add> * @param array $config <add> * @return void <add> */ <add> protected function registerMailTransport($config) <add> { <add> $this->app['swift.transport'] = $this->app->share(function() <add> { <add> return MailTransport::newInstance(); <add> }); <add> } <add> <ide> /** <ide> * Get the services provided by the provider. <ide> *
1
PHP
PHP
add api docs for dynamic finder methods
223ba9b2aa08975294c7ed538a8dbfcc2b3cb494
<ide><path>Cake/ORM/Table.php <ide> * The primary way to retrieve data is using Table::find(). See that method <ide> * for more information. <ide> * <add> * ### Dynamic finders <add> * <add> * In addition to the standard find($type) finder methods, CakePHP provides dynamic <add> * finder methods. These methods allow you to easily set basic conditions up. For example <add> * to filter users by username you would call <add> * <add> * {{{ <add> * $query = $users->findByUsername('mark'); <add> * }}} <add> * <add> * You can also combine conditions on multiple fields using either `Or` or `And`: <add> * <add> * {{{ <add> * $query = $users->findByUsernameOrEmail('mark', 'mark@example.org'); <add> * }}} <add> * <ide> * ### Bulk updates/deletes <ide> * <ide> * You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes.
1
Go
Go
add namespace method conver
0446b6a04edaae1bddeb1dfdb82fd0d931fe1198
<ide><path>distribution/metadata/v1_id_service_test.go <ide> import ( <ide> "testing" <ide> <ide> "github.com/docker/docker/layer" <add> "github.com/stretchr/testify/require" <ide> ) <ide> <ide> func TestV1IDService(t *testing.T) { <ide> func TestV1IDService(t *testing.T) { <ide> } <ide> v1IDService := NewV1IDService(metadataStore) <ide> <add> ns := v1IDService.namespace() <add> <add> require.Equal(t, "v1id", ns) <add> <ide> testVectors := []struct { <ide> registry string <ide> v1ID string
1
Javascript
Javascript
remove unused default option in writestream
2b6c561040cb6528e1f23b88cd36be47448e1ccf
<ide><path>lib/fs.js <ide> function WriteStream(path, options) { <ide> <ide> // a little bit bigger buffer and water marks by default <ide> options = util._extend({ <del> bufferSize: 64 * 1024, <ide> lowWaterMark: 16 * 1024, <ide> highWaterMark: 64 * 1024 <ide> }, options || {});
1
Text
Text
fix duplicate anchor
765c432dfaa1c6472caf9d52926177c48761bd32
<ide><path>docs/axes/README.md <ide> Scales in Chart.js >v2.0 are significantly more powerful, but also different tha <ide> * Scale titles are supported. <ide> * New scale types can be extended without writing an entirely new chart type. <ide> <del># Common Configuration <add>## Common Configuration <ide> <ide> The following properties are common to all axes provided by Chart.js. <ide> <ide> The following properties are common to all axes provided by Chart.js. <ide> | `callbacks` | `object` | | Callback functions to hook into the axis lifecycle. [more...](#callbacks) <ide> | `weight` | `number` | `0` | The weight used to sort the axis. Higher weights are further away from the chart area. <ide> <del>## Callbacks <add>### Callbacks <ide> There are a number of config callbacks that can be used to change parameters in the scale at different points in the update process. <ide> <ide> | Name | Arguments | Description <ide> There are a number of config callbacks that can be used to change parameters in <ide> | `afterFit` | `axis` | Callback that runs after the scale fits to the canvas. <ide> | `afterUpdate` | `axis` | Callback that runs at the end of the update process. <ide> <del>## Updating Axis Defaults <add>### Updating Axis Defaults <ide> <ide> The default configuration for a scale can be easily changed using the scale service. All you need to do is to pass in a partial configuration that will be merged with the current scale default configuration to form the new default. <ide> <ide><path>docs/axes/cartesian/README.md <ide> Axes that follow a cartesian grid are known as 'Cartesian Axes'. Cartesian axes <ide> * [category](./category.md#category-cartesian-axis) <ide> * [time](./time.md#time-cartesian-axis) <ide> <del># Common Configuration <add>## Common Configuration <ide> <ide> All of the included cartesian axes support a number of common options. <ide> <ide> All of the included cartesian axes support a number of common options. <ide> | `scaleLabel` | `object` | | Scale title configuration. [more...](../labelling.md#scale-title-configuration) <ide> | `ticks` | `object` | | Tick configuration. [more...](#tick-configuration) <ide> <del>## Tick Configuration <add>### Tick Configuration <ide> The following options are common to all cartesian axes but do not apply to other axes. <ide> <ide> | Name | Type | Default | Description <ide> The following options are common to all cartesian axes but do not apply to other <ide> | `mirror` | `boolean` | `false` | Flips tick labels around axis, displaying the labels inside the chart instead of outside. *Note: Only applicable to vertical scales.* <ide> | `padding` | `number` | `10` | Padding between the tick label and the axis. When set on a vertical axis, this applies in the horizontal (X) direction. When set on a horizontal axis, this applies in the vertical (Y) direction. <ide> <del>## Axis ID <add>### Axis ID <ide> The properties `dataset.xAxisID` or `dataset.yAxisID` have to match the scale properties `scales.xAxes.id` or `scales.yAxes.id`. This is especially needed if multi-axes charts are used. <ide> <ide> ```javascript <ide> var myChart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del># Creating Multiple Axes <add>## Creating Multiple Axes <ide> <ide> With cartesian axes, it is possible to create multiple X and Y axes. To do so, you can add multiple configuration objects to the `xAxes` and `yAxes` properties. When adding new axes, it is important to ensure that you specify the type of the new axes as default types are **not** used in this case. <ide> <ide><path>docs/charts/bar.md <ide> You can also specify the dataset as x/y coordinates when using the [time scale]( <ide> data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}] <ide> ``` <ide> <del># Stacked Bar Chart <add>## Stacked Bar Chart <ide> <ide> Bar charts can be configured into stacked bar charts by changing the settings on the X and Y axes to enable stacking. Stacked bar charts can be used to show how one data series is made up of a number of smaller pieces. <ide> <ide> var stackedBar = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## Dataset Properties <del> <ide> The following dataset properties are specific to stacked bar charts. <ide> <ide> | Name | Type | Description <ide> | ---- | ---- | ----------- <ide> | `stack` | `string` | The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). <ide> <del># Horizontal Bar Chart <add>## Horizontal Bar Chart <ide> A horizontal bar chart is a variation on a vertical bar chart. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. <ide> {% chartjs %} <ide> { <ide> var myBarChart = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## Config Options <add>### Config Options <ide> The configuration options for the horizontal bar chart are the same as for the [bar chart](#scale-configuration). However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart. <ide> <ide> The default horizontal bar configuration is specified in `Chart.defaults.horizontalBar`. <ide><path>docs/charts/line.md <ide> data: [{ <ide> <ide> This alternate is used for sparse datasets, such as those in [scatter charts](./scatter.md#scatter-chart). Each data point is specified using an object containing `x` and `y` properties. <ide> <del># Stacked Area Chart <add>## Stacked Area Chart <ide> <ide> Line charts can be configured into stacked area charts by changing the settings on the y axis to enable stacking. Stacked area charts can be used to show how one data trend is made up of a number of smaller pieces. <ide> <ide> var stackedLine = new Chart(ctx, { <ide> }); <ide> ``` <ide> <del># High Performance Line Charts <add>## High Performance Line Charts <ide> <ide> When charting a lot of data, the chart render time may start to get quite large. In that case, the following strategies can be used to improve performance. <ide> <del>## Data Decimation <add>### Data Decimation <ide> <ide> Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. <ide> <ide> There are many approaches to data decimation and selection of an algorithm will depend on your data and the results you want to achieve. For instance, [min/max](https://digital.ni.com/public.nsf/allkb/F694FFEEA0ACF282862576020075F784) decimation will preserve peaks in your data but could require up to 4 points for each pixel. This type of decimation would work well for a very noisy signal where you need to see data peaks. <ide> <del>## Disable Bezier Curves <add>### Disable Bezier Curves <ide> <ide> If you are drawing lines on your chart, disabling bezier curves will improve render times since drawing a straight line is more performant than a bezier curve. <ide> <ide> new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## Disable Line Drawing <add>### Disable Line Drawing <ide> <ide> If you have a lot of data points, it can be more performant to disable rendering of the line for a dataset and only draw points. Doing this means that there is less to draw on the canvas which will improve render performance. <ide> <ide> new Chart(ctx, { <ide> }); <ide> ``` <ide> <del>## Disable Animations <add>### Disable Animations <ide> <ide> If your charts have long render times, it is a good idea to disable animations. Doing so will mean that the chart needs to only be rendered once during an update instead of multiple times. This will have the effect of reducing CPU usage and improving general page performance. <ide> <ide><path>docs/developers/README.md <ide> <ide> Developer features allow extending and enhancing Chart.js in many different ways. <ide> <del># Latest resources <add>## Latest resources <ide> <ide> Latest documentation and samples, including unreleased features, are available at: <ide> <ide> - https://www.chartjs.org/docs/master/ <ide> - https://www.chartjs.org/samples/master/ <ide> <del># Development releases <add>## Development releases <ide> <ide> Latest builds are available for testing at: <ide> <ide> Latest builds are available for testing at: <ide> <ide> **WARNING: Development builds MUST not be used for production purposes or as replacement for CDN.** <ide> <del># Browser support <add>## Browser support <ide> <ide> Chart.js offers support for the following browsers: <ide> * Chrome 50+ <ide> Browser support for the canvas element is available in all modern & major mobile <ide> <ide> Thanks to [BrowserStack](https://browserstack.com) for allowing our team to test on thousands of browsers. <ide> <del># Previous versions <add>## Previous versions <ide> <ide> Version 2 has a completely different API than earlier versions. <ide> <ide><path>docs/developers/contributing.md <ide> New contributions to the library are welcome, but we ask that you please follow <ide> - Avoid breaking changes unless there is an upcoming major release, which are infrequent. We encourage people to write plugins for most new advanced features, and care a lot about backwards compatibility. <ide> - We strongly prefer new methods to be added as private whenever possible. A method can be made private either by making a top-level `function` outside of a class or by prefixing it with `_` and adding `@private` JSDoc if inside a class. Public APIs take considerable time to review and become locked once implemented as we have limited ability to change them without breaking backwards compatibility. Private APIs allow the flexibility to address unforeseen cases. <ide> <del># Joining the project <add>## Joining the project <ide> <ide> Active committers and contributors are invited to introduce yourself and request commit access to this project. We have a very active Slack community that you can join [here](https://chartjs-slack.herokuapp.com/). If you think you can help, we'd love to have you! <ide> <del># Building and Testing <add>## Building and Testing <ide> <ide> Chart.js uses <a href="https://gulpjs.com/" target="_blank">gulp</a> to build the library into a single JavaScript file. <ide> <ide> The following commands are now available from the repository root: <ide> <ide> More information can be found in [gulpfile.js](https://github.com/chartjs/Chart.js/blob/master/gulpfile.js). <ide> <del># Bugs and Issues <add>## Bugs and Issues <ide> <ide> Please report these on the GitHub page - at <a href="https://github.com/chartjs/Chart.js" target="_blank">github.com/chartjs/Chart.js</a>. Please do not use issues for support requests. For help using Chart.js, please take a look at the [`chartjs`](https://stackoverflow.com/questions/tagged/chartjs) tag on Stack Overflow. <ide> <ide><path>docs/getting-started/installation.md <ide> bower install chart.js --save <ide> ``` <ide> <ide> ## CDN <add> <ide> ### CDNJS <ide> [![cdnjs](https://img.shields.io/cdnjs/v/Chart.js.svg?style=flat-square&maxAge=600)](https://cdnjs.com/libraries/Chart.js) <ide> <ide> You can download the latest version of [Chart.js on GitHub](https://github.com/c <ide> <ide> If you download or clone the repository, you must [build](../developers/contributing.md#building-and-testing) Chart.js to generate the dist files. Chart.js no longer comes with prebuilt release versions, so an alternative option to downloading the repo is **strongly** advised. <ide> <del># Selecting the Correct Build <add>## Selecting the Correct Build <ide> <ide> Chart.js provides two different builds for you to choose: **Stand-Alone Build**, **Bundled Build**. <ide> <del>## Stand-Alone Build <add>### Stand-Alone Build <ide> Files: <ide> * `dist/Chart.js` <ide> * `dist/Chart.min.js` <ide> <ide> The stand-alone build includes Chart.js as well as the color parsing library. If this version is used, you are required to include [Moment.js](https://momentjs.com/) before Chart.js for the functionality of the time axis. <ide> <del>## Bundled Build <add>### Bundled Build <ide> Files: <ide> * `dist/Chart.bundle.js` <ide> * `dist/Chart.bundle.min.js`
7
Ruby
Ruby
add addresses convenience method and a test for it
5d851664b8551942fb869c379c0332e5e5bc9f53
<ide><path>lib/action_mailbox/mail_ext/recipients.rb <ide> class Mail::Message <ide> def recipients <ide> Array(to) + Array(cc) + Array(bcc) <ide> end <add> <add> def recipients_addresses <add> convert_to_addresses recipients <add> end <add> <add> def to_addresses <add> convert_to_addresses to <add> end <add> <add> def cc_addresses <add> convert_to_addresses cc <add> end <add> <add> def bcc_addresses <add> convert_to_addresses bcc <add> end <add> <add> private <add> def convert_to_addresses(recipients) <add> recipients.collect { |recipient| Mail::Address.new recipient } <add> end <ide> end <ide><path>test/unit/mail_ext/recipients_test.rb <add>require_relative '../../test_helper' <add> <add>module MailExt <add> class RecipientsTest < ActiveSupport::TestCase <add> setup do <add> @mail = Mail.new(to: "david@basecamp.com", cc: "jason@basecamp.com", bcc: "andrea@basecamp.com") <add> end <add> <add> test "recipients include everyone from to, cc, and bcc" do <add> assert_equal %w[ david@basecamp.com jason@basecamp.com andrea@basecamp.com ], @mail.recipients <add> end <add> <add> test "recipients addresses use address objects" do <add> assert_equal "basecamp.com", @mail.recipients_addresses.first.domain <add> end <add> <add> test "to addresses use address objects" do <add> assert_equal "basecamp.com", @mail.to_addresses.first.domain <add> end <add> <add> test "cc addresses use address objects" do <add> assert_equal "basecamp.com", @mail.cc_addresses.first.domain <add> end <add> <add> test "bcc addresses use address objects" do <add> assert_equal "basecamp.com", @mail.bcc_addresses.first.domain <add> end <add> end <add>end <ide>\ No newline at end of file
2
Java
Java
add defaultlocale to acceptheaderlocaleresolver
8343ce9e441313513b1459f6f56724ad1fcead19
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolver.java <ide> public class AcceptHeaderLocaleResolver implements LocaleResolver { <ide> <ide> private final List<Locale> supportedLocales = new ArrayList<Locale>(); <ide> <add> private Locale defaultLocale; <add> <ide> <ide> /** <ide> * Configure supported locales to check against the requested locales <ide> public List<Locale> getSupportedLocales() { <ide> return this.supportedLocales; <ide> } <ide> <add> /** <add> * Configure a fixed default locale to fall back on if the request does not <add> * have an "Accept-Language" header. <add> * <p>By default this is not set in which case when there is "Accept-Lanaguage" <add> * header, the default locale for the server is used as defined in <add> * {@link HttpServletRequest#getLocale()}. <add> * @param defaultLocale the default locale to use <add> * @since 4.3 <add> */ <add> public void setDefaultLocale(Locale defaultLocale) { <add> this.defaultLocale = defaultLocale; <add> } <add> <add> /** <add> * The configured default locale. <add> */ <add> public Locale getDefaultLocale() { <add> return this.defaultLocale; <add> } <add> <ide> <ide> @Override <ide> public Locale resolveLocale(HttpServletRequest request) { <add> if (getDefaultLocale() != null && request.getHeader("Accept-Language") == null) { <add> return getDefaultLocale(); <add> } <ide> Locale locale = request.getLocale(); <ide> if (!isSupportedLocale(locale)) { <ide> locale = findSupportedLocale(request, locale); <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/i18n/AcceptHeaderLocaleResolverTests.java <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> <ide> import static java.util.Locale.CANADA; <add>import static java.util.Locale.JAPANESE; <ide> import static java.util.Locale.UK; <ide> import static java.util.Locale.US; <ide> import static org.junit.Assert.assertEquals; <ide> public void resolvePreferredNotSupported() throws Exception { <ide> assertEquals(US, this.resolver.resolveLocale(request(US, UK))); <ide> } <ide> <add> @Test <add> public void defaultLocale() throws Exception { <add> this.resolver.setDefaultLocale(JAPANESE); <add> MockHttpServletRequest request = new MockHttpServletRequest(); <add> assertEquals(JAPANESE, this.resolver.resolveLocale(request)); <add> <add> request.addHeader("Accept-Language", US.toString()); <add> request.setPreferredLocales(Collections.singletonList(US)); <add> assertEquals(US, this.resolver.resolveLocale(request)); <add> } <add> <ide> <ide> private HttpServletRequest request(Locale... locales) { <ide> MockHttpServletRequest request = new MockHttpServletRequest();
2
Javascript
Javascript
use const instead of let in amdmaintemplateplugin
1227054a9242d053bec663f7028ccea044ae3d77
<ide><path>lib/AmdMainTemplatePlugin.js <ide> class AmdMainTemplatePlugin { <ide> } <ide> <ide> apply(compilation) { <del> let mainTemplate = compilation.mainTemplate; <add> const mainTemplate = compilation.mainTemplate; <ide> <ide> compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { <del> let externals = chunk.modules.filter((m) => m.external); <del> let externalsDepsArray = JSON.stringify(externals.map((m) => <add> const externals = chunk.modules.filter((m) => m.external); <add> const externalsDepsArray = JSON.stringify(externals.map((m) => <ide> typeof m.request === "object" ? m.request.amd : m.request <ide> )); <del> let externalsArguments = externals.map((m) => <add> const externalsArguments = externals.map((m) => <ide> `__WEBPACK_EXTERNAL_MODULE_${m.id}__` <ide> ).join(", "); <ide> <ide> if(this.name) { <del> let name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, { <add> const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, { <ide> hash, <ide> chunk <ide> });
1
Python
Python
remove useless code
a5b28dc4851b4f822cd0685b9765e87336e8b588
<ide><path>celery/result.py <ide> def __init__(self, taskset_id, subtasks, app=None): <ide> self.subtasks = subtasks <ide> self.app = app_or_default(app) <ide> <del> def __reduce__(self): <del> return (self.__class__, (self.taskset_id, self.subtasks)) <del> <del> @classmethod <del> def _unpickle(cls, taskset_id, subtasks): <del> return cls(taskset_id, subtasks) <del> <ide> def itersubtasks(self): <ide> """Taskset subtask iterator. <ide>
1
Ruby
Ruby
use \a and \z when you mean \a and \z
11b463d8cbacfe2cc1662f9e314440de71806ca9
<ide><path>activemodel/test/validators/email_validator.rb <ide> class EmailValidator < ActiveModel::EachValidator <ide> def validate_each(record, attribute, value) <ide> record.errors[attribute] << (options[:message] || "is not an email") unless <del> /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.match?(value) <add> /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i.match?(value) <ide> end <ide> end
1
Ruby
Ruby
add proper fix to `mail_to` helper
9e2e24265510572a6574d38ba2af83fdf734ab54
<ide><path>actionpack/lib/action_view/helpers/url_helper.rb <ide> def mail_to(email_address, name = nil, html_options = {}) <ide> }.compact <ide> extras = extras.empty? ? '' : '?' + ERB::Util.html_escape(extras.join('&')) <ide> <del> email_address_obfuscated = email_address.dup <add> email_address_obfuscated = email_address.to_str <ide> email_address_obfuscated.gsub!(/@/, html_options.delete("replace_at")) if html_options.key?("replace_at") <ide> email_address_obfuscated.gsub!(/\./, html_options.delete("replace_dot")) if html_options.key?("replace_dot") <ide> case encode <ide> when "javascript" <ide> string = '' <ide> html = content_tag("a", name || email_address_obfuscated.html_safe, html_options.merge("href" => "mailto:#{email_address}#{extras}".html_safe)) <del> html = escape_javascript(html) <add> html = escape_javascript(html.to_str) <ide> "document.write('#{html}');".each_byte do |c| <ide> string << sprintf("%%%x", c) <ide> end
1
Ruby
Ruby
use link_tap_formula method
e50badf11c517f0be661da2050a02aa0b0554caa
<ide><path>Library/Homebrew/cmd/pull.rb <ide> <ide> require 'utils' <ide> require 'formula' <add>require 'cmd/tap' <ide> <ide> module Homebrew <ide> def tap arg <ide> def pull <ide> pull_url url <ide> <ide> changed_formulae = [] <add> changed_formulae_paths = [] <ide> <ide> if tap_dir <del> safe_system "brew", "tap", "--repair", "--debug" <ide> formula_dir = %w[Formula HomebrewFormula].find { |d| tap_dir.join(d).directory? } || "" <ide> else <ide> formula_dir = "Library/Formula" <ide> def pull <ide> "git", "diff-tree", "-r", "--name-only", <ide> "--diff-filter=AM", revision, "HEAD", "--", formula_dir <ide> ).each_line do |line| <del> name = File.basename(line.chomp, ".rb") <add> line = line.chomp <add> name = File.basename(line, ".rb") <add> changed_formulae_paths << Pathname.new("#{formula_dir}/#{line}") <ide> <ide> begin <ide> changed_formulae << Formula[name] <ide> def pull <ide> end <ide> end <ide> <add> link_tap_formula(changed_formulae_paths, false) <add> <ide> unless ARGV.include? '--bottle' <ide> changed_formulae.each do |f| <ide> next unless f.bottle
1
Java
Java
clarify the documentation for scan operators
82a218a5e0bb7f8788e4e6b0b54e4de9cd28e9ea
<ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java <ide> public final <U> Flowable<T> sample(@NonNull Publisher<U> sampler, boolean emitL <ide> } <ide> <ide> /** <del> * Returns a {@code Flowable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Flowable}, then feeds the result of that function along with the second item emitted by the current <del> * {@code Floawble} into the same function, and so on until all items have been emitted by the current {@code Flowable}, <del> * emitting the result of each of these iterations. <add> * Returns a {@code Flowable} that emits the first value emitted by the current {@code Flowable}, then emits one value <add> * for each subsequent value emitted by the current {@code Flowable}. Each emission after the first is the result of <add> * applying the specified accumulator function to the previous emission and the corresponding value from the current @{code Flowable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scan.v3.png" alt=""> <ide> * <p> <ide> public final Flowable<T> scan(@NonNull BiFunction<T, T, T> accumulator) { <ide> } <ide> <ide> /** <del> * Returns a {@code Flowable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Flowable} and a seed value, then feeds the result of that function along with the second item emitted by <del> * the current {@code Flowable} into the same function, and so on until all items have been emitted by the current <del> * {@code Flowable}, emitting the result of each of these iterations. <add> * Returns a {@code Flowable} that emits the provided initial (seed) value, then emits one value for each value emitted <add> * by the current {@code Flowable}. Each emission after the first is the result of applying the specified accumulator <add> * function to the previous emission and the corresponding value from the current @{code Flowable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scanSeed.v3.png" alt=""> <ide> * <p> <ide> public final Flowable<T> scan(@NonNull BiFunction<T, T, T> accumulator) { <ide> } <ide> <ide> /** <del> * Returns a {@code Flowable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Flowable} and a seed value, then feeds the result of that function along with the second item emitted by <del> * the current {@code Flowable} into the same function, and so on until all items have been emitted by the current <del> * {@code Flowable}, emitting the result of each of these iterations. <add> * Returns a {@code Flowable} that emits the provided initial (seed) value, then emits one value for each value emitted <add> * by the current {@code Flowable}. Each emission after the first is the result of applying the specified accumulator <add> * function to the previous emission and the corresponding value from the current @{code Flowable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scanSeed.v3.png" alt=""> <ide> * <p> <ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java <ide> public final <U> Observable<T> sample(@NonNull ObservableSource<U> sampler, bool <ide> } <ide> <ide> /** <del> * Returns an {@code Observable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Observable}, then feeds the result of that function along with the second item emitted by the current <del> * {@code Observable} into the same function, and so on until all items have been emitted by the current {@code Observable}, <del> * emitting the result of each of these iterations. <add> * Returns an {@code Observable} that emits the first value emitted by the current {@code Observable}, then emits one value <add> * for each subsequent value emitted by the current {@code Observable}. Each emission after the first is the result of <add> * applying the specified accumulator function to the previous emission and the corresponding value from the current @{code Observable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scan.v3.png" alt=""> <ide> * <p> <ide> public final Observable<T> scan(@NonNull BiFunction<T, T, T> accumulator) { <ide> } <ide> <ide> /** <del> * Returns an {@code Observable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Observable} and a seed value, then feeds the result of that function along with the second item emitted by <del> * the current {@code Observable} into the same function, and so on until all items have been emitted by the current <del> * {@code Observable}, emitting the result of each of these iterations. <add> * Returns an {@code Observable} that emits the provided initial (seed) value, then emits one value for each value emitted <add> * by the current {@code Observable}. Each emission after the first is the result of applying the specified accumulator <add> * function to the previous emission and the corresponding value from the current @{code Observable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scanSeed.v3.png" alt=""> <ide> * <p> <ide> public final <R> Observable<R> scan(@NonNull R initialValue, @NonNull BiFunction <ide> } <ide> <ide> /** <del> * Returns an {@code Observable} that applies a specified accumulator function to the first item emitted by the current <del> * {@code Observable} and a seed value, then feeds the result of that function along with the second item emitted by <del> * the current {@code Observable} into the same function, and so on until all items have been emitted by the current <del> * {@code Observable}, emitting the result of each of these iterations. <add> * Returns an {@code Observable} that emits the provided initial (seed) value, then emits one value for each value emitted <add> * by the current {@code Observable}. Each emission after the first is the result of applying the specified accumulator <add> * function to the previous emission and the corresponding value from the current @{code Observable}. <ide> * <p> <ide> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/scanSeed.v3.png" alt=""> <ide> * <p>
2
Ruby
Ruby
add missing ensure
06d772c0cea49d91eaa273469333430b317583bd
<ide><path>actionpack/test/controller/content_type_test.rb <ide> def test_render_changed_charset_default <ide> get :render_defaults <ide> assert_equal "utf-16", @response.charset <ide> assert_equal Mime::HTML, @response.content_type <add> ensure <ide> OldContentTypeController.default_charset = "utf-8" <ide> end <ide>
1
PHP
PHP
remove duplicate tests
767dbf0857db56e583e3628d3910b7bd81a1922c
<ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testAlphaNumeric() <ide> */ <ide> public function testAlphaNumericPassedAsArray() <ide> { <del> $this->assertTrue(Validation::alphaNumeric('frferrf')); <del> $this->assertTrue(Validation::alphaNumeric('12234')); <del> $this->assertTrue(Validation::alphaNumeric('1w2e2r3t4y')); <del> $this->assertTrue(Validation::alphaNumeric('0')); <del> $this->assertFalse(Validation::alphaNumeric('12 234')); <del> $this->assertFalse(Validation::alphaNumeric('dfd 234')); <del> $this->assertFalse(Validation::alphaNumeric("\n")); <del> $this->assertFalse(Validation::alphaNumeric("\t")); <del> $this->assertFalse(Validation::alphaNumeric("\r")); <del> $this->assertFalse(Validation::alphaNumeric(' ')); <del> $this->assertFalse(Validation::alphaNumeric('')); <ide> $this->assertFalse(Validation::alphaNumeric(['foo'])); <ide> } <ide>
1
Java
Java
add velocity to onscrollenddrag event
d4cda7168f1ff63962dee18ae72d5fee64f52a87
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/OnScrollDispatchHelper.java <ide> public class OnScrollDispatchHelper { <ide> <ide> private int mPrevX = Integer.MIN_VALUE; <ide> private int mPrevY = Integer.MIN_VALUE; <add> private float mXFlingVelocity = 0; <add> private float mYFlingVelocity = 0; <add> <ide> private long mLastScrollEventTimeMs = -(MIN_EVENT_SEPARATION_MS + 1); <ide> <add> private static final float THRESHOLD = 0.1f; // Threshold for end fling <add> <ide> /** <ide> * Call from a ScrollView in onScrollChanged, returns true if this onScrollChanged is legit (not a <ide> * duplicate) and should be dispatched. <ide> public boolean onScrollChanged(int x, int y) { <ide> mPrevX != x || <ide> mPrevY != y; <ide> <add> // Skip the first calculation in each scroll <add> if (Math.abs(mXFlingVelocity) < THRESHOLD && Math.abs(mYFlingVelocity) < THRESHOLD) { <add> shouldDispatch = false; <add> } <add> <add> if (eventTime - mLastScrollEventTimeMs != 0) { <add> mXFlingVelocity = (float) (x - mPrevX) / (eventTime - mLastScrollEventTimeMs); <add> mYFlingVelocity = (float) (y - mPrevY) / (eventTime - mLastScrollEventTimeMs); <add> } <add> <ide> mLastScrollEventTimeMs = eventTime; <ide> mPrevX = x; <ide> mPrevY = y; <ide> <ide> return shouldDispatch; <ide> } <add> <add> public float getXFlingVelocity() { <add> return this.mXFlingVelocity; <add> } <add> <add> public float getYFlingVelocity() { <add> return this.mYFlingVelocity; <add> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java <ide> public class ReactHorizontalScrollView extends HorizontalScrollView implements <ide> ReactClippingViewGroup { <ide> <ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper(); <add> private final VelocityHelper mVelocityHelper = new VelocityHelper(); <ide> <ide> private boolean mActivelyScrolling; <ide> private @Nullable Rect mClippingRect; <ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) { <ide> <ide> mActivelyScrolling = true; <ide> <del> ReactScrollViewHelper.emitScrollEvent(this); <add> ReactScrollViewHelper.emitScrollEvent( <add> this, <add> mOnScrollDispatchHelper.getXFlingVelocity(), <add> mOnScrollDispatchHelper.getYFlingVelocity()); <ide> } <ide> } <ide> <ide> public boolean onTouchEvent(MotionEvent ev) { <ide> return false; <ide> } <ide> <add> mVelocityHelper.calculateVelocity(ev); <ide> int action = ev.getAction() & MotionEvent.ACTION_MASK; <ide> if (action == MotionEvent.ACTION_UP && mDragging) { <del> ReactScrollViewHelper.emitScrollEndDragEvent(this); <add> ReactScrollViewHelper.emitScrollEndDragEvent( <add> this, <add> mVelocityHelper.getXVelocity(), <add> mVelocityHelper.getYVelocity()); <ide> mDragging = false; <ide> // After the touch finishes, we may need to do some scrolling afterwards either as a result <ide> // of a fling or because we need to page align the content <ide> handlePostTouchScrolling(); <ide> } <add> <ide> return super.onTouchEvent(ev); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java <ide> public class ReactScrollView extends ScrollView implements ReactClippingViewGrou <ide> <ide> private final OnScrollDispatchHelper mOnScrollDispatchHelper = new OnScrollDispatchHelper(); <ide> private final OverScroller mScroller; <add> private final VelocityHelper mVelocityHelper = new VelocityHelper(); <ide> <ide> private @Nullable Rect mClippingRect; <ide> private boolean mDoneFlinging; <ide> protected void onScrollChanged(int x, int y, int oldX, int oldY) { <ide> mDoneFlinging = false; <ide> } <ide> <del> ReactScrollViewHelper.emitScrollEvent(this); <add> ReactScrollViewHelper.emitScrollEvent( <add> this, <add> mOnScrollDispatchHelper.getXFlingVelocity(), <add> mOnScrollDispatchHelper.getYFlingVelocity()); <ide> } <ide> } <ide> <ide> public boolean onTouchEvent(MotionEvent ev) { <ide> return false; <ide> } <ide> <add> mVelocityHelper.calculateVelocity(ev); <ide> int action = ev.getAction() & MotionEvent.ACTION_MASK; <ide> if (action == MotionEvent.ACTION_UP && mDragging) { <del> ReactScrollViewHelper.emitScrollEndDragEvent(this); <add> ReactScrollViewHelper.emitScrollEndDragEvent( <add> this, <add> mVelocityHelper.getXVelocity(), <add> mVelocityHelper.getYVelocity()); <ide> mDragging = false; <ide> disableFpsListener(); <ide> } <add> <ide> return super.onTouchEvent(ev); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java <ide> public class ReactScrollViewHelper { <ide> /** <ide> * Shared by {@link ReactScrollView} and {@link ReactHorizontalScrollView}. <ide> */ <del> public static void emitScrollEvent(ViewGroup scrollView) { <del> emitScrollEvent(scrollView, ScrollEventType.SCROLL); <add> public static void emitScrollEvent(ViewGroup scrollView, float xVelocity, float yVelocity) { <add> emitScrollEvent(scrollView, ScrollEventType.SCROLL, xVelocity, yVelocity); <ide> } <ide> <ide> public static void emitScrollBeginDragEvent(ViewGroup scrollView) { <ide> emitScrollEvent(scrollView, ScrollEventType.BEGIN_DRAG); <ide> } <ide> <del> public static void emitScrollEndDragEvent(ViewGroup scrollView) { <del> emitScrollEvent(scrollView, ScrollEventType.END_DRAG); <add> public static void emitScrollEndDragEvent( <add> ViewGroup scrollView, <add> float xVelocity, <add> float yVelocity) { <add> emitScrollEvent(scrollView, ScrollEventType.END_DRAG, xVelocity, yVelocity); <ide> } <ide> <ide> public static void emitScrollMomentumBeginEvent(ViewGroup scrollView) { <ide> public static void emitScrollMomentumEndEvent(ViewGroup scrollView) { <ide> } <ide> <ide> private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scrollEventType) { <add> emitScrollEvent(scrollView, scrollEventType, 0, 0); <add> } <add> <add> private static void emitScrollEvent( <add> ViewGroup scrollView, <add> ScrollEventType scrollEventType, <add> float xVelocity, <add> float yVelocity) { <ide> View contentView = scrollView.getChildAt(0); <ide> <ide> if (contentView == null) { <ide> private static void emitScrollEvent(ViewGroup scrollView, ScrollEventType scroll <ide> scrollEventType, <ide> scrollView.getScrollX(), <ide> scrollView.getScrollY(), <add> xVelocity, <add> yVelocity, <ide> contentView.getWidth(), <ide> contentView.getHeight(), <ide> scrollView.getWidth(), <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ScrollEvent.java <ide> public class ScrollEvent extends Event<ScrollEvent> { <ide> <ide> private int mScrollX; <ide> private int mScrollY; <add> private double mXVelocity; <add> private double mYVelocity; <ide> private int mContentWidth; <ide> private int mContentHeight; <ide> private int mScrollViewWidth; <ide> public static ScrollEvent obtain( <ide> ScrollEventType scrollEventType, <ide> int scrollX, <ide> int scrollY, <add> float xVelocity, <add> float yVelocity, <ide> int contentWidth, <ide> int contentHeight, <ide> int scrollViewWidth, <ide> public static ScrollEvent obtain( <ide> scrollEventType, <ide> scrollX, <ide> scrollY, <add> xVelocity, <add> yVelocity, <ide> contentWidth, <ide> contentHeight, <ide> scrollViewWidth, <ide> private void init( <ide> ScrollEventType scrollEventType, <ide> int scrollX, <ide> int scrollY, <add> float xVelocity, <add> float yVelocity, <ide> int contentWidth, <ide> int contentHeight, <ide> int scrollViewWidth, <ide> private void init( <ide> mScrollEventType = scrollEventType; <ide> mScrollX = scrollX; <ide> mScrollY = scrollY; <add> mXVelocity = xVelocity; <add> mYVelocity = yVelocity; <ide> mContentWidth = contentWidth; <ide> mContentHeight = contentHeight; <ide> mScrollViewWidth = scrollViewWidth; <ide> private WritableMap serializeEventData() { <ide> layoutMeasurement.putDouble("width", PixelUtil.toDIPFromPixel(mScrollViewWidth)); <ide> layoutMeasurement.putDouble("height", PixelUtil.toDIPFromPixel(mScrollViewHeight)); <ide> <add> WritableMap velocity = Arguments.createMap(); <add> velocity.putDouble("x", mXVelocity); <add> velocity.putDouble("y", mYVelocity); <add> <ide> WritableMap event = Arguments.createMap(); <ide> event.putMap("contentInset", contentInset); <ide> event.putMap("contentOffset", contentOffset); <ide> event.putMap("contentSize", contentSize); <ide> event.putMap("layoutMeasurement", layoutMeasurement); <add> event.putMap("velocity", velocity); <ide> <ide> event.putInt("target", getViewTag()); <ide> event.putBoolean("responderIgnoreScroll", true); <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/VelocityHelper.java <add>/** <add> * Copyright (c) 2017-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>package com.facebook.react.views.scroll; <add> <add>import javax.annotation.Nullable; <add> <add>import android.view.MotionEvent; <add>import android.view.VelocityTracker; <add> <add>/** <add> * This Class helps to calculate the velocity for all ScrollView. The x and y velocity <add> * will later on send to ReactScrollViewHelper for further use. <add> * <add> * Created by wenjiam on 6/20/17. <add> */ <add>public class VelocityHelper { <add> <add> private @Nullable VelocityTracker mVelocityTracker; <add> private float mXVelocity; <add> private float mYVelocity; <add> <add> /** <add> * Call from a ScrollView in onTouchEvent. <add> * Calculating the velocity for END_DRAG movement and send them back to react ScrollResponder.js <add> * */ <add> public void calculateVelocity(MotionEvent ev) { <add> int action = ev.getAction() & MotionEvent.ACTION_MASK; <add> if (mVelocityTracker == null) { <add> mVelocityTracker = mVelocityTracker.obtain(); <add> } <add> <add> switch (action) { <add> case MotionEvent.ACTION_MOVE: { <add> mVelocityTracker.addMovement(ev); <add> break; <add> } <add> case MotionEvent.ACTION_UP: <add> case MotionEvent.ACTION_CANCEL: { <add> // Calculate velocity on END_DRAG <add> mVelocityTracker.computeCurrentVelocity(1); // points/millisecond <add> mXVelocity = mVelocityTracker.getXVelocity(); <add> mYVelocity = mVelocityTracker.getYVelocity(); <add> <add> mVelocityTracker.recycle(); <add> break; <add> } <add> } <add> } <add> <add> /* Needs to call ACTION_UP/CANCEL to update the mXVelocity */ <add> public float getXVelocity() { return mXVelocity; } <add> <add> /* Needs to call ACTION_UP/CANCEL to update the mYVelocity */ <add> public float getYVelocity() { return mYVelocity; } <add>} <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java <ide> public void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { <ide> ScrollEventType.SCROLL, <ide> horiz, <ide> vert, <add> 0f, // can't get x velocity <add> 0f, // can't get y velocity <ide> 0, // can't get content width <ide> 0, // can't get content height <ide> mReactEditText.getWidth(), <del> mReactEditText.getHeight() <del> ); <add> mReactEditText.getHeight()); <ide> <ide> mEventDispatcher.dispatchEvent(event); <ide>
7
Go
Go
use ocischema package instead of custom handler
e443512ce4799380941374ef64fc30edc989650e
<ide><path>distribution/oci.go <del>package distribution <del> <del>import ( <del> "fmt" <del> <del> "github.com/docker/distribution" <del> "github.com/docker/distribution/manifest/schema2" <del> digest "github.com/opencontainers/go-digest" <del> ocispec "github.com/opencontainers/image-spec/specs-go/v1" <del>) <del> <del>func init() { <del> // TODO: Remove this registration if distribution is included with OCI support <del> <del> ocischemaFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { <del> m := new(schema2.DeserializedManifest) <del> err := m.UnmarshalJSON(b) <del> if err != nil { <del> return nil, distribution.Descriptor{}, err <del> } <del> <del> dgst := digest.FromBytes(b) <del> return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: ocispec.MediaTypeImageManifest}, err <del> } <del> err := distribution.RegisterManifestSchema(ocispec.MediaTypeImageManifest, ocischemaFunc) <del> if err != nil { <del> panic(fmt.Sprintf("Unable to register manifest: %s", err)) <del> } <del>} <ide><path>distribution/pull_v2.go <ide> import ( <ide> "github.com/containerd/containerd/platforms" <ide> "github.com/docker/distribution" <ide> "github.com/docker/distribution/manifest/manifestlist" <add> "github.com/docker/distribution/manifest/ocischema" <ide> "github.com/docker/distribution/manifest/schema1" <ide> "github.com/docker/distribution/manifest/schema2" <ide> "github.com/docker/distribution/reference" <ide> func (p *v2Puller) pullV2Tag(ctx context.Context, ref reference.Named, platform <ide> if err != nil { <ide> return false, err <ide> } <add> case *ocischema.DeserializedManifest: <add> id, manifestDigest, err = p.pullOCI(ctx, ref, v, platform) <add> if err != nil { <add> return false, err <add> } <ide> case *manifestlist.DeserializedManifestList: <ide> id, manifestDigest, err = p.pullManifestList(ctx, ref, v, platform) <ide> if err != nil { <ide> func (p *v2Puller) pullSchema1(ctx context.Context, ref reference.Reference, unv <ide> return imageID, manifestDigest, nil <ide> } <ide> <del>func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *schema2.DeserializedManifest, platform *specs.Platform) (id digest.Digest, manifestDigest digest.Digest, err error) { <del> manifestDigest, err = schema2ManifestDigest(ref, mfst) <del> if err != nil { <del> return "", "", err <del> } <del> <del> target := mfst.Target() <add>func (p *v2Puller) pullSchema2Layers(ctx context.Context, target distribution.Descriptor, layers []distribution.Descriptor, platform *specs.Platform) (id digest.Digest, err error) { <ide> if _, err := p.config.ImageStore.Get(target.Digest); err == nil { <ide> // If the image already exists locally, no need to pull <ide> // anything. <del> return target.Digest, manifestDigest, nil <add> return target.Digest, nil <ide> } <ide> <ide> var descriptors []xfer.DownloadDescriptor <ide> <ide> // Note that the order of this loop is in the direction of bottom-most <ide> // to top-most, so that the downloads slice gets ordered correctly. <del> for _, d := range mfst.Layers { <add> for _, d := range layers { <ide> layerDescriptor := &v2LayerDescriptor{ <ide> digest: d.Digest, <ide> repo: p.repo, <ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s <ide> if runtime.GOOS == "windows" { <ide> configJSON, configRootFS, configPlatform, err = receiveConfig(p.config.ImageStore, configChan, configErrChan) <ide> if err != nil { <del> return "", "", err <add> return "", err <ide> } <ide> if configRootFS == nil { <del> return "", "", errRootFSInvalid <add> return "", errRootFSInvalid <ide> } <ide> if err := checkImageCompatibility(configPlatform.OS, configPlatform.OSVersion); err != nil { <del> return "", "", err <add> return "", err <ide> } <ide> <ide> if len(descriptors) != len(configRootFS.DiffIDs) { <del> return "", "", errRootFSMismatch <add> return "", errRootFSMismatch <ide> } <ide> if platform == nil { <ide> // Early bath if the requested OS doesn't match that of the configuration. <ide> // This avoids doing the download, only to potentially fail later. <ide> if !system.IsOSSupported(configPlatform.OS) { <del> return "", "", fmt.Errorf("cannot download image with operating system %q when requesting %q", configPlatform.OS, layerStoreOS) <add> return "", fmt.Errorf("cannot download image with operating system %q when requesting %q", configPlatform.OS, layerStoreOS) <ide> } <ide> layerStoreOS = configPlatform.OS <ide> } <ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s <ide> case <-downloadsDone: <ide> case <-layerErrChan: <ide> } <del> return "", "", err <add> return "", err <ide> } <ide> } <ide> <ide> select { <ide> case <-downloadsDone: <ide> case err = <-layerErrChan: <del> return "", "", err <add> return "", err <ide> } <ide> <ide> if release != nil { <ide> func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *s <ide> // Otherwise the image config could be referencing layers that aren't <ide> // included in the manifest. <ide> if len(downloadedRootFS.DiffIDs) != len(configRootFS.DiffIDs) { <del> return "", "", errRootFSMismatch <add> return "", errRootFSMismatch <ide> } <ide> <ide> for i := range downloadedRootFS.DiffIDs { <ide> if downloadedRootFS.DiffIDs[i] != configRootFS.DiffIDs[i] { <del> return "", "", errRootFSMismatch <add> return "", errRootFSMismatch <ide> } <ide> } <ide> } <ide> <ide> imageID, err := p.config.ImageStore.Put(configJSON) <add> if err != nil { <add> return "", err <add> } <add> <add> return imageID, nil <add>} <add> <add>func (p *v2Puller) pullSchema2(ctx context.Context, ref reference.Named, mfst *schema2.DeserializedManifest, platform *specs.Platform) (id digest.Digest, manifestDigest digest.Digest, err error) { <add> manifestDigest, err = schema2ManifestDigest(ref, mfst) <ide> if err != nil { <ide> return "", "", err <ide> } <add> id, err = p.pullSchema2Layers(ctx, mfst.Target(), mfst.Layers, platform) <add> return id, manifestDigest, err <add>} <ide> <del> return imageID, manifestDigest, nil <add>func (p *v2Puller) pullOCI(ctx context.Context, ref reference.Named, mfst *ocischema.DeserializedManifest, platform *specs.Platform) (id digest.Digest, manifestDigest digest.Digest, err error) { <add> manifestDigest, err = schema2ManifestDigest(ref, mfst) <add> if err != nil { <add> return "", "", err <add> } <add> id, err = p.pullSchema2Layers(ctx, mfst.Target(), mfst.Layers, platform) <add> return id, manifestDigest, err <ide> } <ide> <ide> func receiveConfig(s ImageConfigStore, configChan <-chan []byte, errChan <-chan error) ([]byte, *image.RootFS, *specs.Platform, error) { <ide> func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mf <ide> if err != nil { <ide> return "", "", err <ide> } <add> case *ocischema.DeserializedManifest: <add> platform := toOCIPlatform(manifestMatches[0].Platform) <add> id, _, err = p.pullOCI(ctx, manifestRef, v, &platform) <add> if err != nil { <add> return "", "", err <add> } <ide> default: <ide> return "", "", errors.New("unsupported manifest format") <ide> } <ide><path>vendor/github.com/docker/distribution/manifest/ocischema/builder.go <add>package ocischema <add> <add>import ( <add> "context" <add> "errors" <add> <add> "github.com/docker/distribution" <add> "github.com/docker/distribution/manifest" <add> "github.com/opencontainers/go-digest" <add> "github.com/opencontainers/image-spec/specs-go/v1" <add>) <add> <add>// Builder is a type for constructing manifests. <add>type Builder struct { <add> // bs is a BlobService used to publish the configuration blob. <add> bs distribution.BlobService <add> <add> // configJSON references <add> configJSON []byte <add> <add> // layers is a list of layer descriptors that gets built by successive <add> // calls to AppendReference. <add> layers []distribution.Descriptor <add> <add> // Annotations contains arbitrary metadata relating to the targeted content. <add> annotations map[string]string <add> <add> // For testing purposes <add> mediaType string <add>} <add> <add>// NewManifestBuilder is used to build new manifests for the current schema <add>// version. It takes a BlobService so it can publish the configuration blob <add>// as part of the Build process, and annotations. <add>func NewManifestBuilder(bs distribution.BlobService, configJSON []byte, annotations map[string]string) distribution.ManifestBuilder { <add> mb := &Builder{ <add> bs: bs, <add> configJSON: make([]byte, len(configJSON)), <add> annotations: annotations, <add> mediaType: v1.MediaTypeImageManifest, <add> } <add> copy(mb.configJSON, configJSON) <add> <add> return mb <add>} <add> <add>// SetMediaType assigns the passed mediatype or error if the mediatype is not a <add>// valid media type for oci image manifests currently: "" or "application/vnd.oci.image.manifest.v1+json" <add>func (mb *Builder) SetMediaType(mediaType string) error { <add> if mediaType != "" && mediaType != v1.MediaTypeImageManifest { <add> return errors.New("invalid media type for OCI image manifest") <add> } <add> <add> mb.mediaType = mediaType <add> return nil <add>} <add> <add>// Build produces a final manifest from the given references. <add>func (mb *Builder) Build(ctx context.Context) (distribution.Manifest, error) { <add> m := Manifest{ <add> Versioned: manifest.Versioned{ <add> SchemaVersion: 2, <add> MediaType: mb.mediaType, <add> }, <add> Layers: make([]distribution.Descriptor, len(mb.layers)), <add> Annotations: mb.annotations, <add> } <add> copy(m.Layers, mb.layers) <add> <add> configDigest := digest.FromBytes(mb.configJSON) <add> <add> var err error <add> m.Config, err = mb.bs.Stat(ctx, configDigest) <add> switch err { <add> case nil: <add> // Override MediaType, since Put always replaces the specified media <add> // type with application/octet-stream in the descriptor it returns. <add> m.Config.MediaType = v1.MediaTypeImageConfig <add> return FromStruct(m) <add> case distribution.ErrBlobUnknown: <add> // nop <add> default: <add> return nil, err <add> } <add> <add> // Add config to the blob store <add> m.Config, err = mb.bs.Put(ctx, v1.MediaTypeImageConfig, mb.configJSON) <add> // Override MediaType, since Put always replaces the specified media <add> // type with application/octet-stream in the descriptor it returns. <add> m.Config.MediaType = v1.MediaTypeImageConfig <add> if err != nil { <add> return nil, err <add> } <add> <add> return FromStruct(m) <add>} <add> <add>// AppendReference adds a reference to the current ManifestBuilder. <add>func (mb *Builder) AppendReference(d distribution.Describable) error { <add> mb.layers = append(mb.layers, d.Descriptor()) <add> return nil <add>} <add> <add>// References returns the current references added to this builder. <add>func (mb *Builder) References() []distribution.Descriptor { <add> return mb.layers <add>} <ide><path>vendor/github.com/docker/distribution/manifest/ocischema/manifest.go <add>package ocischema <add> <add>import ( <add> "encoding/json" <add> "errors" <add> "fmt" <add> <add> "github.com/docker/distribution" <add> "github.com/docker/distribution/manifest" <add> "github.com/opencontainers/go-digest" <add> "github.com/opencontainers/image-spec/specs-go/v1" <add>) <add> <add>var ( <add> // SchemaVersion provides a pre-initialized version structure for this <add> // packages version of the manifest. <add> SchemaVersion = manifest.Versioned{ <add> SchemaVersion: 2, // historical value here.. does not pertain to OCI or docker version <add> MediaType: v1.MediaTypeImageManifest, <add> } <add>) <add> <add>func init() { <add> ocischemaFunc := func(b []byte) (distribution.Manifest, distribution.Descriptor, error) { <add> m := new(DeserializedManifest) <add> err := m.UnmarshalJSON(b) <add> if err != nil { <add> return nil, distribution.Descriptor{}, err <add> } <add> <add> dgst := digest.FromBytes(b) <add> return m, distribution.Descriptor{Digest: dgst, Size: int64(len(b)), MediaType: v1.MediaTypeImageManifest}, err <add> } <add> err := distribution.RegisterManifestSchema(v1.MediaTypeImageManifest, ocischemaFunc) <add> if err != nil { <add> panic(fmt.Sprintf("Unable to register manifest: %s", err)) <add> } <add>} <add> <add>// Manifest defines a ocischema manifest. <add>type Manifest struct { <add> manifest.Versioned <add> <add> // Config references the image configuration as a blob. <add> Config distribution.Descriptor `json:"config"` <add> <add> // Layers lists descriptors for the layers referenced by the <add> // configuration. <add> Layers []distribution.Descriptor `json:"layers"` <add> <add> // Annotations contains arbitrary metadata for the image manifest. <add> Annotations map[string]string `json:"annotations,omitempty"` <add>} <add> <add>// References returns the descriptors of this manifests references. <add>func (m Manifest) References() []distribution.Descriptor { <add> references := make([]distribution.Descriptor, 0, 1+len(m.Layers)) <add> references = append(references, m.Config) <add> references = append(references, m.Layers...) <add> return references <add>} <add> <add>// Target returns the target of this manifest. <add>func (m Manifest) Target() distribution.Descriptor { <add> return m.Config <add>} <add> <add>// DeserializedManifest wraps Manifest with a copy of the original JSON. <add>// It satisfies the distribution.Manifest interface. <add>type DeserializedManifest struct { <add> Manifest <add> <add> // canonical is the canonical byte representation of the Manifest. <add> canonical []byte <add>} <add> <add>// FromStruct takes a Manifest structure, marshals it to JSON, and returns a <add>// DeserializedManifest which contains the manifest and its JSON representation. <add>func FromStruct(m Manifest) (*DeserializedManifest, error) { <add> var deserialized DeserializedManifest <add> deserialized.Manifest = m <add> <add> var err error <add> deserialized.canonical, err = json.MarshalIndent(&m, "", " ") <add> return &deserialized, err <add>} <add> <add>// UnmarshalJSON populates a new Manifest struct from JSON data. <add>func (m *DeserializedManifest) UnmarshalJSON(b []byte) error { <add> m.canonical = make([]byte, len(b)) <add> // store manifest in canonical <add> copy(m.canonical, b) <add> <add> // Unmarshal canonical JSON into Manifest object <add> var manifest Manifest <add> if err := json.Unmarshal(m.canonical, &manifest); err != nil { <add> return err <add> } <add> <add> if manifest.MediaType != "" && manifest.MediaType != v1.MediaTypeImageManifest { <add> return fmt.Errorf("if present, mediaType in manifest should be '%s' not '%s'", <add> v1.MediaTypeImageManifest, manifest.MediaType) <add> } <add> <add> m.Manifest = manifest <add> <add> return nil <add>} <add> <add>// MarshalJSON returns the contents of canonical. If canonical is empty, <add>// marshals the inner contents. <add>func (m *DeserializedManifest) MarshalJSON() ([]byte, error) { <add> if len(m.canonical) > 0 { <add> return m.canonical, nil <add> } <add> <add> return nil, errors.New("JSON representation not initialized in DeserializedManifest") <add>} <add> <add>// Payload returns the raw content of the manifest. The contents can be used to <add>// calculate the content identifier. <add>func (m DeserializedManifest) Payload() (string, []byte, error) { <add> return v1.MediaTypeImageManifest, m.canonical, nil <add>}
4
PHP
PHP
allow busfake to use custom busrepository
2407c9b86cda499eb2eedb9d19510cb4554fae1c
<ide><path>src/Illuminate/Support/Facades/Bus.php <ide> <ide> namespace Illuminate\Support\Facades; <ide> <add>use Illuminate\Bus\BatchRepository; <ide> use Illuminate\Contracts\Bus\Dispatcher as BusDispatcherContract; <ide> use Illuminate\Foundation\Bus\PendingChain; <ide> use Illuminate\Support\Testing\Fakes\BusFake; <ide> class Bus extends Facade <ide> * @param array|string $jobsToFake <ide> * @return \Illuminate\Support\Testing\Fakes\BusFake <ide> */ <del> public static function fake($jobsToFake = []) <add> public static function fake($jobsToFake = [], BatchRepository $batchRepository = null) <ide> { <del> static::swap($fake = new BusFake(static::getFacadeRoot(), $jobsToFake)); <add> static::swap($fake = new BusFake(static::getFacadeRoot(), $jobsToFake, $batchRepository)); <ide> <ide> return $fake; <ide> } <ide><path>src/Illuminate/Support/Testing/Fakes/BusFake.php <ide> namespace Illuminate\Support\Testing\Fakes; <ide> <ide> use Closure; <add>use Illuminate\Bus\BatchRepository; <ide> use Illuminate\Bus\PendingBatch; <ide> use Illuminate\Contracts\Bus\QueueingDispatcher; <ide> use Illuminate\Support\Arr; <ide> class BusFake implements QueueingDispatcher <ide> * <ide> * @param \Illuminate\Contracts\Bus\QueueingDispatcher $dispatcher <ide> * @param array|string $jobsToFake <add> * @param BatchRepository|null $jobsToFake <ide> * @return void <ide> */ <del> public function __construct(QueueingDispatcher $dispatcher, $jobsToFake = []) <add> public function __construct(QueueingDispatcher $dispatcher, $jobsToFake = [], BatchRepository $batchRepository = null) <ide> { <ide> $this->dispatcher = $dispatcher; <ide> $this->jobsToFake = Arr::wrap($jobsToFake); <del> $this->batchRepository = new BatchRepositoryFake; <add> $this->batchRepository = $batchRepository ?: new BatchRepositoryFake; <ide> } <ide> <ide> /** <ide><path>tests/Support/SupportTestingBusFakeTest.php <ide> use Illuminate\Bus\Batch; <ide> use Illuminate\Bus\Queueable; <ide> use Illuminate\Contracts\Bus\QueueingDispatcher; <add>use Illuminate\Support\Testing\Fakes\BatchRepositoryFake; <ide> use Illuminate\Support\Testing\Fakes\BusFake; <ide> use Mockery as m; <ide> use PHPUnit\Framework\Constraint\ExceptionMessage; <ide> protected function tearDown(): void <ide> m::close(); <ide> } <ide> <add> public function testItUsesCustomBusRepository() <add> { <add> $busRepository = new BatchRepositoryFake; <add> <add> $fake = new BusFake(m::mock(QueueingDispatcher::class), [], $busRepository); <add> <add> $this->assertNull($fake->findBatch('non-existent-batch')); <add> <add> $batch = $fake->batch([])->dispatch(); <add> <add> $this->assertSame($batch, $fake->findBatch($batch->id)); <add> $this->assertSame($batch, $busRepository->find($batch->id)); <add> } <add> <ide> public function testAssertDispatched() <ide> { <ide> try {
3
Javascript
Javascript
simplify default title
18cb2c03df3044848d23d5ea8f5a4920b1d92b6a
<ide><path>packages/next/client/head-manager.js <del> <del>const DEFAULT_TITLE = '' <del> <ide> const DOMAttributeNames = { <ide> acceptCharset: 'accept-charset', <ide> className: 'class', <ide> export default class HeadManager { <ide> } <ide> <ide> updateTitle (component) { <del> let title <add> let title = '' <ide> if (component) { <ide> const { children } = component.props <ide> title = typeof children === 'string' ? children : children.join('') <del> } else { <del> title = DEFAULT_TITLE <ide> } <ide> if (title !== document.title) document.title = title <ide> }
1
Go
Go
avoid alloc w/ writestring
db877d8a425a3c063eedb1908ab1b50df1a33a57
<ide><path>pkg/broadcastwriter/broadcastwriter.go <ide> func (w *BroadcastWriter) Write(p []byte) (n int, err error) { <ide> for { <ide> line, err := w.buf.ReadString('\n') <ide> if err != nil { <del> w.buf.Write([]byte(line)) <add> w.buf.WriteString(line) <ide> break <ide> } <ide> for stream, writers := range w.streams {
1
Python
Python
kill unused file
af0c674ec36e46c37ff4b2d4f0ff35a88bfad435
<ide><path>numpy/f2py/__init__.py <ide> def __getattr__(attr): <ide> <ide> # Avoid importing things that aren't needed for building <ide> # which might import the main numpy module <del> if attr == "f2py_testing": <del> import numpy.f2py.f2py_testing as f2py_testing <del> return f2py_testing <del> <del> elif attr == "test": <add> if attr == "test": <ide> from numpy._pytesttester import PytestTester <ide> test = PytestTester(__name__) <ide> return test <ide> def __getattr__(attr): <ide> "{!r}".format(__name__, attr)) <ide> <ide> def __dir__(): <del> return list(globals().keys() | {"f2py_testing", "test"}) <add> return list(globals().keys() | {"test"}) <ide> <ide> else: <del> from . import f2py_testing <del> <del> from numpy._pytesttester import PytestTester <del> test = PytestTester(__name__) <del> del PytestTester <add> raise NotImplementedError("F2PY needs Python 3.7") <ide><path>numpy/f2py/f2py_testing.py <del>import sys <del>import re <del> <del>from numpy.testing import jiffies, memusage <del> <del> <del>def cmdline(): <del> m = re.compile(r'\A\d+\Z') <del> args = [] <del> repeat = 1 <del> for a in sys.argv[1:]: <del> if m.match(a): <del> repeat = eval(a) <del> else: <del> args.append(a) <del> f2py_opts = ' '.join(args) <del> return repeat, f2py_opts <del> <del> <del>def run(runtest, test_functions, repeat=1): <del> l = [(t, repr(t.__doc__.split('\n')[1].strip())) for t in test_functions] <del> start_memusage = memusage() <del> diff_memusage = None <del> start_jiffies = jiffies() <del> i = 0 <del> while i < repeat: <del> i += 1 <del> for t, fname in l: <del> runtest(t) <del> if start_memusage is None: <del> continue <del> if diff_memusage is None: <del> diff_memusage = memusage() - start_memusage <del> else: <del> diff_memusage2 = memusage() - start_memusage <del> if diff_memusage2 != diff_memusage: <del> print('memory usage change at step %i:' % i, <del> diff_memusage2 - diff_memusage, <del> fname) <del> diff_memusage = diff_memusage2 <del> current_memusage = memusage() <del> print('run', repeat * len(test_functions), 'tests', <del> 'in %.2f seconds' % ((jiffies() - start_jiffies) / 100.0)) <del> if start_memusage: <del> print('initial virtual memory size:', start_memusage, 'bytes') <del> print('current virtual memory size:', current_memusage, 'bytes') <ide><path>numpy/tests/test_public_api.py <ide> def test_NPY_NO_EXPORT(): <ide> "f2py.crackfortran", <ide> "f2py.diagnose", <ide> "f2py.f2py2e", <del> "f2py.f2py_testing", <ide> "f2py.f90mod_rules", <ide> "f2py.func2subr", <ide> "f2py.rules",
3
Mixed
Ruby
accept a collection in fresh_when and stale?
050fda020606028acffeaaf79e65d6f595856262
<ide><path>actionpack/CHANGELOG.md <add>* Expand `ActionController::ConditionalGet#fresh_when` and `stale?` to also <add> accept a collection of records as the first argument, so that the <add> following code can be written in a shorter form. <add> <add> # Before <add> def index <add> @article = Article.all <add> fresh_when(etag: @articles, last_modified: @articles.maximum(:created_at)) <add> end <add> <add> # After <add> def index <add> @article = Article.all <add> fresh_when(@articles) <add> end <add> <add> *claudiob* <add> <ide> * Explicitly ignored wildcard verbs when searching for HEAD routes before fallback <ide> <ide> Fixes an issue where a mounted rack app at root would intercept the HEAD <ide><path>actionpack/lib/action_controller/metal/conditional_get.rb <ide> def etag(&etagger) <ide> # This will render the show template if the request isn't sending a matching ETag or <ide> # If-Modified-Since header and just a <tt>304 Not Modified</tt> response if there's a match. <ide> # <del> # You can also just pass a record where +last_modified+ will be set by calling <del> # +updated_at+ and the +etag+ by passing the object itself. <add> # You can also just pass a record. In this case +last_modified+ will be set <add> # by calling +updated_at+ and +etag+ by passing the object itself. <ide> # <ide> # def show <ide> # @article = Article.find(params[:id]) <ide> # fresh_when(@article) <ide> # end <ide> # <del> # When passing a record, you can still set whether the public header: <add> # You can also pass an object that responds to +maximum+, such as a <add> # collection of active records. In this case +last_modified+ will be set by <add> # calling +maximum(:updated_at)+ on the collection (the timestamp of the <add> # most recently updated record) and the +etag+ by passing the object itself. <add> # <add> # def index <add> # @articles = Article.all <add> # fresh_when(@articles) <add> # end <add> # <add> # When passing a record or a collection, you can still set the public header: <ide> # <ide> # def show <ide> # @article = Article.find(params[:id]) <ide> def etag(&etagger) <ide> # <ide> # before_action { fresh_when @article, template: 'widgets/show' } <ide> # <del> def fresh_when(record = nil, etag: record, last_modified: nil, public: false, template: nil) <del> last_modified ||= record.try(:updated_at) <add> def fresh_when(object = nil, etag: object, last_modified: nil, public: false, template: nil) <add> last_modified ||= object.try(:updated_at) || object.try(:maximum, :updated_at) <ide> <ide> if etag || template <ide> response.etag = combine_etags(etag: etag, last_modified: last_modified, <ide> def fresh_when(record = nil, etag: record, last_modified: nil, public: false, te <ide> # end <ide> # end <ide> # <del> # You can also just pass a record where +last_modified+ will be set by calling <del> # +updated_at+ and the +etag+ by passing the object itself. <add> # You can also just pass a record. In this case +last_modified+ will be set <add> # by calling +updated_at+ and +etag+ by passing the object itself. <ide> # <ide> # def show <ide> # @article = Article.find(params[:id]) <ide> def fresh_when(record = nil, etag: record, last_modified: nil, public: false, te <ide> # end <ide> # end <ide> # <del> # When passing a record, you can still set whether the public header: <add> # You can also pass an object that responds to +maximum+, such as a <add> # collection of active records. In this case +last_modified+ will be set by <add> # calling +maximum(:updated_at)+ on the collection (the timestamp of the <add> # most recently updated record) and the +etag+ by passing the object itself. <add> # <add> # def index <add> # @articles = Article.all <add> # <add> # if stale?(@articles) <add> # @statistics = @articles.really_expensive_call <add> # respond_to do |format| <add> # # all the supported formats <add> # end <add> # end <add> # end <add> # <add> # When passing a record or a collection, you can still set the public header: <ide> # <ide> # def show <ide> # @article = Article.find(params[:id]) <ide> def fresh_when(record = nil, etag: record, last_modified: nil, public: false, te <ide> # super if stale? @article, template: 'widgets/show' <ide> # end <ide> # <del> def stale?(record = nil, etag: record, last_modified: nil, public: nil, template: nil) <del> fresh_when(record, etag: etag, last_modified: last_modified, public: public, template: template) <add> def stale?(object = nil, etag: object, last_modified: nil, public: nil, template: nil) <add> fresh_when(object, etag: etag, last_modified: last_modified, public: public, template: template) <ide> !request.fresh?(response) <ide> end <ide> <ide><path>actionpack/test/controller/render_test.rb <ide> def conditional_hello_with_record <ide> end <ide> end <ide> <add> class Collection <add> def initialize(records) <add> @records = records <add> end <add> <add> def maximum(attribute) <add> @records.max_by(&attribute).public_send(attribute) <add> end <add> end <add> <add> def conditional_hello_with_collection_of_records <add> ts = Time.now.utc.beginning_of_day <add> <add> record = Struct.new(:updated_at, :cache_key).new(ts, "foo/123") <add> old_record = Struct.new(:updated_at, :cache_key).new(ts - 1.day, "bar/123") <add> <add> if stale?(Collection.new([record, old_record])) <add> render action: 'hello_world' <add> end <add> end <add> <ide> def conditional_hello_with_expires_in <ide> expires_in 60.1.seconds <ide> render :action => 'hello_world' <ide> def test_request_modified <ide> assert_equal @last_modified, @response.headers['Last-Modified'] <ide> end <ide> <del> <ide> def test_responds_with_last_modified_with_record <ide> get :conditional_hello_with_record <ide> assert_equal @last_modified, @response.headers['Last-Modified'] <ide> def test_request_modified_with_record <ide> assert_equal @last_modified, @response.headers['Last-Modified'] <ide> end <ide> <add> def test_responds_with_last_modified_with_collection_of_records <add> get :conditional_hello_with_collection_of_records <add> assert_equal @last_modified, @response.headers['Last-Modified'] <add> end <add> <add> def test_request_not_modified_with_collection_of_records <add> @request.if_modified_since = @last_modified <add> get :conditional_hello_with_collection_of_records <add> assert_equal 304, @response.status.to_i <add> assert @response.body.blank? <add> assert_equal @last_modified, @response.headers['Last-Modified'] <add> end <add> <add> def test_request_not_modified_but_etag_differs_with_collection_of_records <add> @request.if_modified_since = @last_modified <add> @request.if_none_match = "234" <add> get :conditional_hello_with_collection_of_records <add> assert_response :success <add> end <add> <add> def test_request_modified_with_collection_of_records <add> @request.if_modified_since = 'Thu, 16 Jul 2008 00:00:00 GMT' <add> get :conditional_hello_with_collection_of_records <add> assert_equal 200, @response.status.to_i <add> assert @response.body.present? <add> assert_equal @last_modified, @response.headers['Last-Modified'] <add> end <add> <ide> def test_request_with_bang_gets_last_modified <ide> get :conditional_hello_with_bangs <ide> assert_equal @last_modified, @response.headers['Last-Modified']
3
Javascript
Javascript
upgrade flagdependencyexportsplugin to es6
20c39015f29601c8c486b56029839cd9380d39f5
<ide><path>lib/FlagDependencyExportsPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>function FlagDependencyExportsPlugin() { <add>"use strict"; <ide> <del>} <del>module.exports = FlagDependencyExportsPlugin; <add>class FlagDependencyExportsPlugin { <ide> <del>FlagDependencyExportsPlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compilation", function(compilation) { <del> compilation.plugin("finish-modules", function(modules) { <add> apply(compiler) { <add> compiler.plugin("compilation", (compilation) => { <add> compilation.plugin("finish-modules", (modules) => { <ide> <del> var dependencies = {}; <add> const dependencies = {}; <ide> <del> var module, moduleWithExports; <del> var queue = modules.filter(function(m) { <del> return !m.providedExports; <del> }); <del> for(var i = 0; i < queue.length; i++) { <del> module = queue[i]; <add> let module; <add> let moduleWithExports; <add> const queue = modules.filter((m) => !m.providedExports); <add> for(let i = 0; i < queue.length; i++) { <add> module = queue[i]; <ide> <del> if(module.providedExports !== true) { <del> moduleWithExports = false; <del> processDependenciesBlock(module); <del> if(!moduleWithExports) { <del> module.providedExports = true; <del> notifyDependencies(); <add> if(module.providedExports !== true) { <add> moduleWithExports = false; <add> processDependenciesBlock(module); <add> if(!moduleWithExports) { <add> module.providedExports = true; <add> notifyDependencies(); <add> } <ide> } <ide> } <del> } <ide> <del> function processDependenciesBlock(depBlock) { <del> depBlock.dependencies.forEach(function(dep) { <del> processDependency(dep); <del> }); <del> depBlock.variables.forEach(function(variable) { <del> variable.dependencies.forEach(function(dep) { <del> processDependency(dep); <del> }); <del> }); <del> depBlock.blocks.forEach(function(block) { <del> processDependenciesBlock(block); <del> }); <del> } <del> <del> function processDependency(dep, usedExports) { <del> var exportDesc = dep.getExports && dep.getExports(); <del> if(!exportDesc) return; <del> moduleWithExports = true; <del> var exports = exportDesc.exports; <del> var exportDeps = exportDesc.dependencies; <del> if(exportDeps) { <del> exportDeps.forEach(function(dep) { <del> var depIdent = dep.identifier(); <del> var array = dependencies["$" + depIdent]; <del> if(!array) array = dependencies["$" + depIdent] = []; <del> if(array.indexOf(module) < 0) <del> array.push(module); <add> function processDependenciesBlock(depBlock) { <add> depBlock.dependencies.forEach((dep) => processDependency(dep)); <add> depBlock.variables.forEach((variable) => { <add> variable.dependencies.forEach((dep) => processDependency(dep)); <ide> }); <add> depBlock.blocks.forEach((block) => processDependenciesBlock(block)); <ide> } <del> var changed = false; <del> if(module.providedExports !== true) { <del> if(exports === true) { <del> module.providedExports = true; <del> changed = true; <del> } else if(Array.isArray(exports)) { <del> if(Array.isArray(module.providedExports)) { <del> changed = addToSet(module.providedExports, exports); <del> } else { <del> module.providedExports = exports.slice(); <add> <add> function processDependency(dep, usedExports) { <add> const exportDesc = dep.getExports && dep.getExports(); <add> if(!exportDesc) return; <add> moduleWithExports = true; <add> const exports = exportDesc.exports; <add> const exportDeps = exportDesc.dependencies; <add> if(exportDeps) { <add> exportDeps.forEach((dep) => { <add> const depIdent = dep.identifier(); <add> let array = dependencies["$" + depIdent]; <add> if(!array) array = dependencies["$" + depIdent] = []; <add> if(array.indexOf(module) < 0) <add> array.push(module); <add> }); <add> } <add> let changed = false; <add> if(module.providedExports !== true) { <add> if(exports === true) { <add> module.providedExports = true; <ide> changed = true; <add> } else if(Array.isArray(exports)) { <add> if(Array.isArray(module.providedExports)) { <add> changed = addToSet(module.providedExports, exports); <add> } else { <add> module.providedExports = exports.slice(); <add> changed = true; <add> } <ide> } <ide> } <add> if(changed) { <add> notifyDependencies(); <add> } <ide> } <del> if(changed) { <del> notifyDependencies(); <del> } <del> } <ide> <del> function notifyDependencies() { <del> var deps = dependencies["$" + module.identifier()]; <del> if(deps) { <del> deps.forEach(function(dep) { <del> queue.push(dep); <del> }); <add> function notifyDependencies() { <add> const deps = dependencies["$" + module.identifier()]; <add> if(deps) { <add> deps.forEach((dep) => queue.push(dep)); <add> } <ide> } <add> }); <add> <add> function addToSet(a, b) { <add> let changed = false; <add> b.forEach((item) => { <add> if(a.indexOf(item) < 0) { <add> a.push(item); <add> changed = true; <add> } <add> }); <add> return changed; <ide> } <ide> }); <add> } <add>} <ide> <del> function addToSet(a, b) { <del> var changed = false; <del> b.forEach(function(item) { <del> if(a.indexOf(item) < 0) { <del> a.push(item); <del> changed = true; <del> } <del> }); <del> return changed; <del> } <del> }); <del>}; <add>module.exports = FlagDependencyExportsPlugin;
1
Text
Text
update the list with confirmshaming
d512c927a91d5110ee7151cf5dc8dc08d9e0b40b
<ide><path>guide/english/developer-ethics/dark-patterns/index.md <ide> Examples include: <ide> <ide> * [**Disguised Ads**](https://darkpatterns.org/types-of-dark-pattern/disguised-ads) – Advertisements disguised as other kinds of content or navigation, in order to get users to click on them. <ide> <add>* [**Confirmshaming**](https://darkpatterns.org/types-of-dark-pattern/disguised-ads) – Confirmshaming is the act of guilting the user into opting in to something. The option to decline is worded in such a way as to shame the user into compliance. <add> <ide> * [**Forced Continuity**](https://darkpatterns.org/types-of-dark-pattern/forced-continuity) – Silently charging a user's credit card without warning at the end of a free trial. <ide> <ide> * [**Friend Spam**](https://darkpatterns.org/types-of-dark-pattern/friend-spam) – A website or app asks for a user's email or social media permissions under the pretense it will be used for a desirable outcome (e.g. finding friends), but then spams all the user's contacts in a message that claims to be from that user.
1
Python
Python
use running estimates in batchnormalization
3108e9194c9243e7062a81d412399adf6463c1e0
<ide><path>keras/layers/normalization.py <ide> class BatchNormalization(Layer): <ide> <ide> mode: 0 -> featurewise normalization <ide> 1 -> samplewise normalization (may sometimes outperform featurewise mode) <add> <add> momentum: momentum term in the computation of a running estimate of the mean and std of the data <ide> ''' <del> def __init__(self, input_shape, epsilon=1e-6, mode=0, weights=None): <add> def __init__(self, input_shape, epsilon=1e-6, mode=0, momentum=0.9, weights=None): <ide> super(BatchNormalization,self).__init__() <ide> self.init = initializations.get("uniform") <ide> self.input_shape = input_shape <ide> self.epsilon = epsilon <ide> self.mode = mode <add> self.momentum = momentum <ide> <ide> self.gamma = self.init((self.input_shape)) <ide> self.beta = shared_zeros(self.input_shape) <ide> <add> self.running_mean = None <add> self.running_std = None <add> <ide> self.params = [self.gamma, self.beta] <ide> if weights is not None: <ide> self.set_weights(weights) <ide> def get_output(self, train): <ide> X = self.get_input(train) <ide> <ide> if self.mode == 0: <del> m = X.mean(axis=0) <del> # manual computation of std to prevent NaNs <del> std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 <del> X_normed = (X - m) / (std + self.epsilon) <add> if train: <add> m = X.mean(axis=0) <add> # manual computation of std to prevent NaNs <add> std = T.mean((X-m)**2 + self.epsilon, axis=0) ** 0.5 <add> X_normed = (X - m) / (std + self.epsilon) <add> <add> if self.running_mean is None: <add> self.running_mean = m <add> self.running_std = std <add> else: <add> self.running_mean *= self.momentum <add> self.running_mean += (1-self.momentum) * m <add> self.running_std *= self.momentum <add> self.running_std += (1-self.momentum) * std <add> else: <add> X_normed = (X - self.running_mean) / (self.running_std + self.epsilon) <ide> <ide> elif self.mode == 1: <ide> m = X.mean(axis=-1, keepdims=True)
1
Javascript
Javascript
escape style values
a2ae42db90d626eda8f84f127068bd1f95fb5a6d
<ide><path>packages/react-dom/src/server/ReactDOMServerFormatConfig.js <ide> function pushStyle( <ide> valueChunk = stringToChunk('' + styleValue); <ide> } <ide> } else { <del> valueChunk = stringToChunk(('' + styleValue).trim()); <add> valueChunk = stringToChunk( <add> escapeTextForBrowser(('' + styleValue).trim()), <add> ); <ide> } <ide> } <ide> if (isFirst) {
1
Python
Python
ignore unexpected weights from pt conversion
88cc26dcd1e73c16feff1874ffe75c49159e4dcd
<ide><path>src/transformers/models/bert/modeling_tf_bert.py <ide> def serving_output(self, output: TFBaseModelOutputWithPooling) -> TFBaseModelOut <ide> ) <ide> class TFBertForPreTraining(TFBertPreTrainedModel, TFBertPreTrainingLoss): <ide> # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model <del> _keys_to_ignore_on_load_unexpected = [r"cls.predictions.decoder.weight"] <add> _keys_to_ignore_on_load_unexpected = [ <add> r"position_ids", <add> r"cls.predictions.decoder.weight", <add> r"cls.predictions.decoder.bias", <add> ] <ide> <ide> def __init__(self, config: BertConfig, *inputs, **kwargs): <ide> super().__init__(config, *inputs, **kwargs)
1
Python
Python
use mseloss in (m)bartforsequenceclassification
d49d3cf6d603a0c8cf742c41ce1623c34e094e83
<ide><path>src/transformers/models/bart/modeling_bart.py <ide> import torch.nn.functional as F <ide> import torch.utils.checkpoint <ide> from torch import nn <del>from torch.nn import CrossEntropyLoss <add>from torch.nn import CrossEntropyLoss, MSELoss <ide> <ide> from ...activations import ACT2FN <ide> from ...file_utils import ( <ide> def forward( <ide> <ide> loss = None <ide> if labels is not None: <del> loss_fct = CrossEntropyLoss() <del> loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1)) <add> if self.config.num_labels == 1: <add> # regression <add> loss_fct = MSELoss() <add> loss = loss_fct(logits.view(-1), labels.view(-1)) <add> else: <add> loss_fct = CrossEntropyLoss() <add> loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1)) <ide> <ide> if not return_dict: <ide> output = (logits,) + outputs[1:] <ide><path>src/transformers/models/mbart/modeling_mbart.py <ide> import torch.nn.functional as F <ide> import torch.utils.checkpoint <ide> from torch import nn <del>from torch.nn import CrossEntropyLoss <add>from torch.nn import CrossEntropyLoss, MSELoss <ide> <ide> from ...activations import ACT2FN <ide> from ...file_utils import ( <ide> def forward( <ide> <ide> loss = None <ide> if labels is not None: <del> loss_fct = CrossEntropyLoss() <del> loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1)) <add> if self.config.num_labels == 1: <add> # regression <add> loss_fct = MSELoss() <add> loss = loss_fct(logits.view(-1), labels.view(-1)) <add> else: <add> loss_fct = CrossEntropyLoss() <add> loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1)) <ide> <ide> if not return_dict: <ide> output = (logits,) + outputs[1:]
2
Javascript
Javascript
remove redundant prefixes from the css order test
e3584179fe919c59033e54f019a1511691d2c85b
<ide><path>test/unit/css.js <ide> asyncTest( "Make sure initialized display value for disconnected nodes is correc <ide> // but it's the best that we can do. <ide> (function() { <ide> var style = document.createElement( "div" ).style, <del> prefixes = [ "Webkit", "O", "Moz", "ms" ], <del> exist = "order" in style, <del> i = 0; <del> <del> if ( !exist ) { <del> for ( ; i < prefixes.length; i++ ) { <del> if ( exist = prefixes[ i ] + "Order" in style ) { <del> break; <del> } <del> } <del> } <add> exist = "order" in style || "WebkitOrder" in style; <ide> <ide> if ( exist ) { <ide> test( "Don't append px to CSS \"order\" value (#14049)", 1, function() {
1
Javascript
Javascript
remove state queue from usesyncexternalstore
8e80592a3ab2bdbd036f5af77c89fcf937b8f43b
<ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js <ide> import { <ide> } from './ReactTypeOfMode'; <ide> import { <ide> NoLane, <add> SyncLane, <ide> NoLanes, <ide> isSubsetOfLanes, <ide> mergeLanes, <ide> import { <ide> isTransitionLane, <ide> markRootEntangled, <ide> markRootMutableRead, <add> NoTimestamp, <ide> } from './ReactFiberLane.new'; <ide> import { <del> DiscreteEventPriority, <ide> ContinuousEventPriority, <ide> getCurrentUpdatePriority, <ide> setCurrentUpdatePriority, <ide> export type Hook = {| <ide> memoizedState: any, <ide> baseState: any, <ide> baseQueue: Update<any, any> | null, <del> queue: UpdateQueue<any, any> | null, <add> queue: any, <ide> next: Hook | null, <ide> |}; <ide> <ide> export type Effect = {| <ide> next: Effect, <ide> |}; <ide> <add>type StoreInstance<T> = {| <add> value: T, <add> getSnapshot: () => T, <add>|}; <add> <ide> export type FunctionComponentUpdateQueue = {|lastEffect: Effect | null|}; <ide> <ide> type BasicStateAction<S> = (S => S) | S; <ide> function mountReducer<S, I, A>( <ide> initialState = ((initialArg: any): S); <ide> } <ide> hook.memoizedState = hook.baseState = initialState; <del> const queue = (hook.queue = { <add> const queue: UpdateQueue<S, A> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> dispatch: null, <ide> lastRenderedReducer: reducer, <ide> lastRenderedState: (initialState: any), <del> }); <add> }; <add> hook.queue = queue; <ide> const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind( <ide> null, <ide> currentlyRenderingFiber, <ide> function useMutableSource<Source, Snapshot>( <ide> // So if there are interleaved updates, they get pushed to the older queue. <ide> // When this becomes current, the previous queue and dispatch method will be discarded, <ide> // including any interleaving updates that occur. <del> const newQueue = { <add> const newQueue: UpdateQueue<Snapshot, BasicStateAction<Snapshot>> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> function mountSyncExternalStore<T>( <ide> getSnapshot: () => T, <ide> ): T { <ide> const hook = mountWorkInProgressHook(); <del> return useSyncExternalStore(hook, subscribe, getSnapshot); <add> // Read the current snapshot from the store on every render. This breaks the <add> // normal rules of React, and only works because store updates are <add> // always synchronous. <add> const nextSnapshot = getSnapshot(); <add> if (__DEV__) { <add> if (!didWarnUncachedGetSnapshot) { <add> if (nextSnapshot !== getSnapshot()) { <add> console.error( <add> 'The result of getSnapshot should be cached to avoid an infinite loop', <add> ); <add> didWarnUncachedGetSnapshot = true; <add> } <add> } <add> } <add> hook.memoizedState = nextSnapshot; <add> const inst: StoreInstance<T> = { <add> value: nextSnapshot, <add> getSnapshot, <add> }; <add> hook.queue = inst; <add> return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot); <ide> } <ide> <ide> function updateSyncExternalStore<T>( <ide> subscribe: (() => void) => () => void, <ide> getSnapshot: () => T, <ide> ): T { <ide> const hook = updateWorkInProgressHook(); <del> return useSyncExternalStore(hook, subscribe, getSnapshot); <del>} <del> <del>function useSyncExternalStore<T>( <del> hook: Hook, <del> subscribe: (() => void) => () => void, <del> getSnapshot: () => T, <del>): T { <del> // TODO: This is a copy-paste of the userspace shim. We can improve the <del> // built-in implementation using lower-level APIs. We also intend to move <del> // the tearing checks to an earlier, pre-commit phase so that the layout <del> // effects always observe a consistent tree. <del> <del> const dispatcher = ReactCurrentDispatcher.current; <del> <del> // Read the current snapshot from the store on every render. Again, this <del> // breaks the rules of React, and only works here because of specific <del> // implementation details, most importantly that updates are <add> // Read the current snapshot from the store on every render. This breaks the <add> // normal rules of React, and only works because store updates are <ide> // always synchronous. <del> const value = getSnapshot(); <add> const nextSnapshot = getSnapshot(); <ide> if (__DEV__) { <ide> if (!didWarnUncachedGetSnapshot) { <del> if (value !== getSnapshot()) { <add> if (nextSnapshot !== getSnapshot()) { <ide> console.error( <ide> 'The result of getSnapshot should be cached to avoid an infinite loop', <ide> ); <ide> didWarnUncachedGetSnapshot = true; <ide> } <ide> } <ide> } <add> const prevSnapshot = hook.memoizedState; <add> if (!is(prevSnapshot, nextSnapshot)) { <add> hook.memoizedState = nextSnapshot; <add> markWorkInProgressReceivedUpdate(); <add> } <add> const inst = hook.queue; <add> return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot); <add>} <ide> <del> // Because updates are synchronous, we don't queue them. Instead we force a <del> // re-render whenever the subscribed state changes by updating an some <del> // arbitrary useState hook. Then, during render, we call getSnapshot to read <del> // the current value. <del> // <del> // Because we don't actually use the state returned by the useState hook, we <del> // can save a bit of memory by storing other stuff in that slot. <del> // <del> // To implement the early bailout, we need to track some things on a mutable <del> // object. Usually, we would put that in a useRef hook, but we can stash it in <del> // our useState hook instead. <del> // <del> // To force a re-render, we call forceUpdate({inst}). That works because the <del> // new object always fails an equality check. <del> const [{inst}, forceUpdate] = dispatcher.useState({ <del> inst: {value, getSnapshot}, <del> }); <add>function useSyncExternalStore<T>( <add> hook: Hook, <add> inst: StoreInstance<T>, <add> subscribe: (() => void) => () => void, <add> getSnapshot: () => T, <add> nextSnapshot: T, <add>): T { <add> const fiber = currentlyRenderingFiber; <add> const dispatcher = ReactCurrentDispatcher.current; <ide> <ide> // Track the latest getSnapshot function with a ref. This needs to be updated <ide> // in the layout phase so we can access it during the tearing check that <ide> // happens on subscribe. <ide> // TODO: Circumvent SSR warning <ide> dispatcher.useLayoutEffect(() => { <del> inst.value = value; <add> inst.value = nextSnapshot; <ide> inst.getSnapshot = getSnapshot; <ide> <ide> // Whenever getSnapshot or subscribe changes, we need to check in the <ide> // commit phase if there was an interleaved mutation. In concurrent mode <ide> // this can happen all the time, but even in synchronous mode, an earlier <ide> // effect may have mutated the store. <add> // TODO: Move the tearing checks to an earlier, pre-commit phase so that the <add> // layout effects always observe a consistent tree. <ide> if (checkIfSnapshotChanged(inst)) { <ide> // Force a re-render. <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> const prevPriority = getCurrentUpdatePriority(); <del> ReactCurrentBatchConfig.transition = 0; <del> setCurrentUpdatePriority(DiscreteEventPriority); <del> forceUpdate({inst}); <del> setCurrentUpdatePriority(prevPriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <add> forceStoreRerender(fiber); <ide> } <del> }, [subscribe, value, getSnapshot]); <add> }, [subscribe, nextSnapshot, getSnapshot]); <ide> <ide> dispatcher.useEffect(() => { <ide> const handleStoreChange = () => { <ide> function useSyncExternalStore<T>( <ide> // read from the store. <ide> if (checkIfSnapshotChanged(inst)) { <ide> // Force a re-render. <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> const prevPriority = getCurrentUpdatePriority(); <del> ReactCurrentBatchConfig.transition = 0; <del> setCurrentUpdatePriority(DiscreteEventPriority); <del> forceUpdate({inst}); <del> setCurrentUpdatePriority(prevPriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <add> forceStoreRerender(fiber); <ide> } <ide> }; <ide> // Check for changes right before subscribing. Subsequent changes will be <ide> function useSyncExternalStore<T>( <ide> return subscribe(handleStoreChange); <ide> }, [subscribe]); <ide> <del> return value; <add> return nextSnapshot; <ide> } <ide> <ide> function checkIfSnapshotChanged(inst) { <ide> function checkIfSnapshotChanged(inst) { <ide> } <ide> } <ide> <add>function forceStoreRerender(fiber) { <add> scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); <add>} <add> <ide> function mountState<S>( <ide> initialState: (() => S) | S, <ide> ): [S, Dispatch<BasicStateAction<S>>] { <ide> function mountState<S>( <ide> initialState = initialState(); <ide> } <ide> hook.memoizedState = hook.baseState = initialState; <del> const queue = (hook.queue = { <add> const queue: UpdateQueue<S, BasicStateAction<S>> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> dispatch: null, <ide> lastRenderedReducer: basicStateReducer, <ide> lastRenderedState: (initialState: any), <del> }); <add> }; <add> hook.queue = queue; <ide> const dispatch: Dispatch< <ide> BasicStateAction<S>, <ide> > = (queue.dispatch = (dispatchAction.bind( <ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js <ide> import { <ide> } from './ReactTypeOfMode'; <ide> import { <ide> NoLane, <add> SyncLane, <ide> NoLanes, <ide> isSubsetOfLanes, <ide> mergeLanes, <ide> import { <ide> isTransitionLane, <ide> markRootEntangled, <ide> markRootMutableRead, <add> NoTimestamp, <ide> } from './ReactFiberLane.old'; <ide> import { <del> DiscreteEventPriority, <ide> ContinuousEventPriority, <ide> getCurrentUpdatePriority, <ide> setCurrentUpdatePriority, <ide> export type Hook = {| <ide> memoizedState: any, <ide> baseState: any, <ide> baseQueue: Update<any, any> | null, <del> queue: UpdateQueue<any, any> | null, <add> queue: any, <ide> next: Hook | null, <ide> |}; <ide> <ide> export type Effect = {| <ide> next: Effect, <ide> |}; <ide> <add>type StoreInstance<T> = {| <add> value: T, <add> getSnapshot: () => T, <add>|}; <add> <ide> export type FunctionComponentUpdateQueue = {|lastEffect: Effect | null|}; <ide> <ide> type BasicStateAction<S> = (S => S) | S; <ide> function mountReducer<S, I, A>( <ide> initialState = ((initialArg: any): S); <ide> } <ide> hook.memoizedState = hook.baseState = initialState; <del> const queue = (hook.queue = { <add> const queue: UpdateQueue<S, A> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> dispatch: null, <ide> lastRenderedReducer: reducer, <ide> lastRenderedState: (initialState: any), <del> }); <add> }; <add> hook.queue = queue; <ide> const dispatch: Dispatch<A> = (queue.dispatch = (dispatchAction.bind( <ide> null, <ide> currentlyRenderingFiber, <ide> function useMutableSource<Source, Snapshot>( <ide> // So if there are interleaved updates, they get pushed to the older queue. <ide> // When this becomes current, the previous queue and dispatch method will be discarded, <ide> // including any interleaving updates that occur. <del> const newQueue = { <add> const newQueue: UpdateQueue<Snapshot, BasicStateAction<Snapshot>> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> function mountSyncExternalStore<T>( <ide> getSnapshot: () => T, <ide> ): T { <ide> const hook = mountWorkInProgressHook(); <del> return useSyncExternalStore(hook, subscribe, getSnapshot); <add> // Read the current snapshot from the store on every render. This breaks the <add> // normal rules of React, and only works because store updates are <add> // always synchronous. <add> const nextSnapshot = getSnapshot(); <add> if (__DEV__) { <add> if (!didWarnUncachedGetSnapshot) { <add> if (nextSnapshot !== getSnapshot()) { <add> console.error( <add> 'The result of getSnapshot should be cached to avoid an infinite loop', <add> ); <add> didWarnUncachedGetSnapshot = true; <add> } <add> } <add> } <add> hook.memoizedState = nextSnapshot; <add> const inst: StoreInstance<T> = { <add> value: nextSnapshot, <add> getSnapshot, <add> }; <add> hook.queue = inst; <add> return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot); <ide> } <ide> <ide> function updateSyncExternalStore<T>( <ide> subscribe: (() => void) => () => void, <ide> getSnapshot: () => T, <ide> ): T { <ide> const hook = updateWorkInProgressHook(); <del> return useSyncExternalStore(hook, subscribe, getSnapshot); <del>} <del> <del>function useSyncExternalStore<T>( <del> hook: Hook, <del> subscribe: (() => void) => () => void, <del> getSnapshot: () => T, <del>): T { <del> // TODO: This is a copy-paste of the userspace shim. We can improve the <del> // built-in implementation using lower-level APIs. We also intend to move <del> // the tearing checks to an earlier, pre-commit phase so that the layout <del> // effects always observe a consistent tree. <del> <del> const dispatcher = ReactCurrentDispatcher.current; <del> <del> // Read the current snapshot from the store on every render. Again, this <del> // breaks the rules of React, and only works here because of specific <del> // implementation details, most importantly that updates are <add> // Read the current snapshot from the store on every render. This breaks the <add> // normal rules of React, and only works because store updates are <ide> // always synchronous. <del> const value = getSnapshot(); <add> const nextSnapshot = getSnapshot(); <ide> if (__DEV__) { <ide> if (!didWarnUncachedGetSnapshot) { <del> if (value !== getSnapshot()) { <add> if (nextSnapshot !== getSnapshot()) { <ide> console.error( <ide> 'The result of getSnapshot should be cached to avoid an infinite loop', <ide> ); <ide> didWarnUncachedGetSnapshot = true; <ide> } <ide> } <ide> } <add> const prevSnapshot = hook.memoizedState; <add> if (!is(prevSnapshot, nextSnapshot)) { <add> hook.memoizedState = nextSnapshot; <add> markWorkInProgressReceivedUpdate(); <add> } <add> const inst = hook.queue; <add> return useSyncExternalStore(hook, inst, subscribe, getSnapshot, nextSnapshot); <add>} <ide> <del> // Because updates are synchronous, we don't queue them. Instead we force a <del> // re-render whenever the subscribed state changes by updating an some <del> // arbitrary useState hook. Then, during render, we call getSnapshot to read <del> // the current value. <del> // <del> // Because we don't actually use the state returned by the useState hook, we <del> // can save a bit of memory by storing other stuff in that slot. <del> // <del> // To implement the early bailout, we need to track some things on a mutable <del> // object. Usually, we would put that in a useRef hook, but we can stash it in <del> // our useState hook instead. <del> // <del> // To force a re-render, we call forceUpdate({inst}). That works because the <del> // new object always fails an equality check. <del> const [{inst}, forceUpdate] = dispatcher.useState({ <del> inst: {value, getSnapshot}, <del> }); <add>function useSyncExternalStore<T>( <add> hook: Hook, <add> inst: StoreInstance<T>, <add> subscribe: (() => void) => () => void, <add> getSnapshot: () => T, <add> nextSnapshot: T, <add>): T { <add> const fiber = currentlyRenderingFiber; <add> const dispatcher = ReactCurrentDispatcher.current; <ide> <ide> // Track the latest getSnapshot function with a ref. This needs to be updated <ide> // in the layout phase so we can access it during the tearing check that <ide> // happens on subscribe. <ide> // TODO: Circumvent SSR warning <ide> dispatcher.useLayoutEffect(() => { <del> inst.value = value; <add> inst.value = nextSnapshot; <ide> inst.getSnapshot = getSnapshot; <ide> <ide> // Whenever getSnapshot or subscribe changes, we need to check in the <ide> // commit phase if there was an interleaved mutation. In concurrent mode <ide> // this can happen all the time, but even in synchronous mode, an earlier <ide> // effect may have mutated the store. <add> // TODO: Move the tearing checks to an earlier, pre-commit phase so that the <add> // layout effects always observe a consistent tree. <ide> if (checkIfSnapshotChanged(inst)) { <ide> // Force a re-render. <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> const prevPriority = getCurrentUpdatePriority(); <del> ReactCurrentBatchConfig.transition = 0; <del> setCurrentUpdatePriority(DiscreteEventPriority); <del> forceUpdate({inst}); <del> setCurrentUpdatePriority(prevPriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <add> forceStoreRerender(fiber); <ide> } <del> }, [subscribe, value, getSnapshot]); <add> }, [subscribe, nextSnapshot, getSnapshot]); <ide> <ide> dispatcher.useEffect(() => { <ide> const handleStoreChange = () => { <ide> function useSyncExternalStore<T>( <ide> // read from the store. <ide> if (checkIfSnapshotChanged(inst)) { <ide> // Force a re-render. <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> const prevPriority = getCurrentUpdatePriority(); <del> ReactCurrentBatchConfig.transition = 0; <del> setCurrentUpdatePriority(DiscreteEventPriority); <del> forceUpdate({inst}); <del> setCurrentUpdatePriority(prevPriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <add> forceStoreRerender(fiber); <ide> } <ide> }; <ide> // Check for changes right before subscribing. Subsequent changes will be <ide> function useSyncExternalStore<T>( <ide> return subscribe(handleStoreChange); <ide> }, [subscribe]); <ide> <del> return value; <add> return nextSnapshot; <ide> } <ide> <ide> function checkIfSnapshotChanged(inst) { <ide> function checkIfSnapshotChanged(inst) { <ide> } <ide> } <ide> <add>function forceStoreRerender(fiber) { <add> scheduleUpdateOnFiber(fiber, SyncLane, NoTimestamp); <add>} <add> <ide> function mountState<S>( <ide> initialState: (() => S) | S, <ide> ): [S, Dispatch<BasicStateAction<S>>] { <ide> function mountState<S>( <ide> initialState = initialState(); <ide> } <ide> hook.memoizedState = hook.baseState = initialState; <del> const queue = (hook.queue = { <add> const queue: UpdateQueue<S, BasicStateAction<S>> = { <ide> pending: null, <ide> interleaved: null, <ide> lanes: NoLanes, <ide> dispatch: null, <ide> lastRenderedReducer: basicStateReducer, <ide> lastRenderedState: (initialState: any), <del> }); <add> }; <add> hook.queue = queue; <ide> const dispatch: Dispatch< <ide> BasicStateAction<S>, <ide> > = (queue.dispatch = (dispatchAction.bind(
2
Python
Python
expand japanese requirements warning
556895177edbc5d7dc64e0f95e36273a2fb16478
<ide><path>spacy/lang/ja/__init__.py <ide> def try_sudachi_import(split_mode="A"): <ide> return tok <ide> except ImportError: <ide> raise ImportError( <del> "Japanese support requires SudachiPy: " "https://github.com/WorksApplications/SudachiPy" <add> "Japanese support requires SudachiPy and SudachiDict-core " <add> "(https://github.com/WorksApplications/SudachiPy). " <add> "Install with `pip install sudachipy sudachidict_core` or " <add> "install spaCy with `pip install spacy[ja]`." <ide> ) <ide> <ide>
1
Go
Go
use complete port configs when plumbing mark rules
093a017f68b282513d5f02ad5ae3c84168964d9c
<ide><path>libnetwork/service_linux.go <ide> func (sb *sandbox) addLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*P <ide> } <ide> <ide> if addService { <del> var iPorts []*PortConfig <add> var filteredPorts []*PortConfig <ide> if sb.ingress { <del> iPorts = filterPortConfigs(ingressPorts, false) <del> if err := programIngress(gwIP, iPorts, false); err != nil { <add> filteredPorts = filterPortConfigs(ingressPorts, false) <add> if err := programIngress(gwIP, filteredPorts, false); err != nil { <ide> logrus.Errorf("Failed to add ingress: %v", err) <ide> return <ide> } <ide> } <ide> <del> logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v", vip, fwMark, iPorts) <del> if err := invokeFWMarker(sb.Key(), vip, fwMark, iPorts, eIP, false); err != nil { <add> logrus.Debugf("Creating service for vip %s fwMark %d ingressPorts %#v", vip, fwMark, ingressPorts) <add> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, filteredPorts, eIP, false); err != nil { <ide> logrus.Errorf("Failed to add firewall mark rule in sbox %s: %v", sb.Key(), err) <ide> return <ide> } <ide> func (sb *sandbox) rmLBBackend(ip, vip net.IP, fwMark uint32, ingressPorts []*Po <ide> logrus.Errorf("Failed to delete a new service for vip %s fwmark %d: %v", vip, fwMark, err) <ide> } <ide> <del> var iPorts []*PortConfig <add> var filteredPorts []*PortConfig <ide> if sb.ingress { <del> iPorts = filterPortConfigs(ingressPorts, true) <del> if err := programIngress(gwIP, iPorts, true); err != nil { <add> filteredPorts = filterPortConfigs(ingressPorts, true) <add> if err := programIngress(gwIP, filteredPorts, true); err != nil { <ide> logrus.Errorf("Failed to delete ingress: %v", err) <ide> } <ide> } <ide> <del> if err := invokeFWMarker(sb.Key(), vip, fwMark, iPorts, eIP, true); err != nil { <add> if err := invokeFWMarker(sb.Key(), vip, fwMark, ingressPorts, filteredPorts, eIP, true); err != nil { <ide> logrus.Errorf("Failed to add firewall mark rule in sbox %s: %v", sb.Key(), err) <ide> } <ide> } <ide> func plumbProxy(iPort *PortConfig, isDelete bool) error { <ide> return nil <ide> } <ide> <add>func writePortsToFile(ports []*PortConfig) (string, error) { <add> f, err := ioutil.TempFile("", "port_configs") <add> if err != nil { <add> return "", err <add> } <add> defer f.Close() <add> <add> buf, err := proto.Marshal(&EndpointRecord{ <add> IngressPorts: ports, <add> }) <add> <add> n, err := f.Write(buf) <add> if err != nil { <add> return "", err <add> } <add> <add> if n < len(buf) { <add> return "", io.ErrShortWrite <add> } <add> <add> return f.Name(), nil <add>} <add> <add>func readPortsFromFile(fileName string) ([]*PortConfig, error) { <add> buf, err := ioutil.ReadFile(fileName) <add> if err != nil { <add> return nil, err <add> } <add> <add> var epRec EndpointRecord <add> err = proto.Unmarshal(buf, &epRec) <add> if err != nil { <add> return nil, err <add> } <add> <add> return epRec.IngressPorts, nil <add>} <add> <ide> // Invoke fwmarker reexec routine to mark vip destined packets with <ide> // the passed firewall mark. <del>func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, eIP *net.IPNet, isDelete bool) error { <del> var ingressPortsFile string <add>func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*PortConfig, filteredPorts []*PortConfig, eIP *net.IPNet, isDelete bool) error { <add> var ( <add> ingressPortsFile string <add> filteredPortsFile string <add> ) <add> <ide> if len(ingressPorts) != 0 { <del> f, err := ioutil.TempFile("", "port_configs") <add> var err error <add> ingressPortsFile, err = writePortsToFile(ingressPorts) <ide> if err != nil { <ide> return err <ide> } <add> } <ide> <del> buf, err := proto.Marshal(&EndpointRecord{ <del> IngressPorts: ingressPorts, <del> }) <del> <del> n, err := f.Write(buf) <add> if len(filteredPorts) != 0 { <add> var err error <add> filteredPortsFile, err = writePortsToFile(filteredPorts) <ide> if err != nil { <del> f.Close() <ide> return err <ide> } <del> <del> if n < len(buf) { <del> f.Close() <del> return io.ErrShortWrite <del> } <del> <del> ingressPortsFile = f.Name() <del> f.Close() <ide> } <ide> <ide> addDelOpt := "-A" <ide> func invokeFWMarker(path string, vip net.IP, fwMark uint32, ingressPorts []*Port <ide> <ide> cmd := &exec.Cmd{ <ide> Path: reexec.Self(), <del> Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, eIP.String()), <add> Args: append([]string{"fwmarker"}, path, vip.String(), fmt.Sprintf("%d", fwMark), addDelOpt, ingressPortsFile, filteredPortsFile, eIP.String()), <ide> Stdout: os.Stdout, <ide> Stderr: os.Stderr, <ide> } <ide> func fwMarker() { <ide> runtime.LockOSThread() <ide> defer runtime.UnlockOSThread() <ide> <del> if len(os.Args) < 7 { <add> if len(os.Args) < 8 { <ide> logrus.Error("invalid number of arguments..") <ide> os.Exit(1) <ide> } <ide> <ide> var ingressPorts []*PortConfig <add> var filteredPorts []*PortConfig <ide> if os.Args[5] != "" { <del> buf, err := ioutil.ReadFile(os.Args[5]) <add> var err error <add> ingressPorts, err = readPortsFromFile(os.Args[5]) <ide> if err != nil { <del> logrus.Errorf("Failed to read ports config file: %v", err) <add> logrus.Errorf("Failed reading ingress ports file: %v", err) <ide> os.Exit(6) <ide> } <add> } <ide> <del> var epRec EndpointRecord <del> err = proto.Unmarshal(buf, &epRec) <add> if os.Args[6] != "" { <add> var err error <add> filteredPorts, err = readPortsFromFile(os.Args[6]) <ide> if err != nil { <del> logrus.Errorf("Failed to unmarshal ports config data: %v", err) <add> logrus.Errorf("Failed reading filtered ports file: %v", err) <ide> os.Exit(7) <ide> } <del> <del> ingressPorts = epRec.IngressPorts <ide> } <ide> <ide> vip := os.Args[2] <ide> func fwMarker() { <ide> addDelOpt := os.Args[4] <ide> <ide> rules := [][]string{} <del> for _, iPort := range ingressPorts { <add> for _, iPort := range filteredPorts { <ide> rule := strings.Fields(fmt.Sprintf("-t nat %s PREROUTING -p %s --dport %d -j REDIRECT --to-port %d", <ide> addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, iPort.TargetPort)) <ide> rules = append(rules, rule) <add> } <ide> <del> rule = strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d", <add> for _, iPort := range ingressPorts { <add> rule := strings.Fields(fmt.Sprintf("-t mangle %s PREROUTING -p %s --dport %d -j MARK --set-mark %d", <ide> addDelOpt, strings.ToLower(PortConfig_Protocol_name[int32(iPort.Protocol)]), iPort.PublishedPort, fwMark)) <ide> rules = append(rules, rule) <ide> } <ide> func fwMarker() { <ide> } <ide> <ide> if addDelOpt == "-A" { <del> eIP, subnet, err := net.ParseCIDR(os.Args[6]) <add> eIP, subnet, err := net.ParseCIDR(os.Args[7]) <ide> if err != nil { <del> logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[6], err) <add> logrus.Errorf("Failed to parse endpoint IP %s: %v", os.Args[7], err) <ide> os.Exit(9) <ide> } <ide>
1
Go
Go
update the test for the new struct
7790a77b6afeda6f223202288a89f4b431f033a0
<ide><path>registry/registry_test.go <ide> func spawnTestRegistry(t *testing.T) *Registry { <ide> } <ide> <ide> func TestPingRegistryEndpoint(t *testing.T) { <del> standalone, err := pingRegistryEndpoint(makeURL("/v1/")) <add> regInfo, err := pingRegistryEndpoint(makeURL("/v1/")) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> assertEqual(t, standalone, true, "Expected standalone to be true (default)") <add> assertEqual(t, regInfo.Standalone, true, "Expected standalone to be true (default)") <ide> } <ide> <ide> func TestGetRemoteHistory(t *testing.T) {
1
Go
Go
fix vet warning
c5bf2145f172a264d3d8fc63d6717826b95b5ee2
<ide><path>integration-cli/docker_api_containers_test.go <ide> func TestPostContainerBindNormalVolume(t *testing.T) { <ide> } <ide> <ide> if fooDir2 != fooDir { <del> t.Fatal("expected volume path to be %s, got: %s", fooDir, fooDir2) <add> t.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2) <ide> } <ide> <ide> logDone("container REST API - can use path from normal volume as bind-mount to overwrite another volume") <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func TestDaemonUlimitDefaults(t *testing.T) { <ide> <ide> outArr := strings.Split(out, "\n") <ide> if len(outArr) < 2 { <del> t.Fatal("got unexpected output: %s", out) <add> t.Fatalf("got unexpected output: %s", out) <ide> } <ide> nofile := strings.TrimSpace(outArr[0]) <ide> nproc := strings.TrimSpace(outArr[1]) <ide> func TestDaemonUlimitDefaults(t *testing.T) { <ide> <ide> outArr = strings.Split(out, "\n") <ide> if len(outArr) < 2 { <del> t.Fatal("got unexpected output: %s", out) <add> t.Fatalf("got unexpected output: %s", out) <ide> } <ide> nofile = strings.TrimSpace(outArr[0]) <ide> nproc = strings.TrimSpace(outArr[1]) <ide> func TestDaemonLoggingDriverDefault(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> var res struct { <del> Log string `json:log` <del> Stream string `json:stream` <del> Time time.Time `json:time` <add> Log string `json:"log"` <add> Stream string `json:"stream"` <add> Time time.Time `json:"time"` <ide> } <ide> if err := json.NewDecoder(f).Decode(&res); err != nil { <ide> t.Fatal(err) <ide> func TestDaemonLoggingDriverNoneOverride(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> var res struct { <del> Log string `json:log` <del> Stream string `json:stream` <del> Time time.Time `json:time` <add> Log string `json:"log"` <add> Stream string `json:"stream"` <add> Time time.Time `json:"time"` <ide> } <ide> if err := json.NewDecoder(f).Decode(&res); err != nil { <ide> t.Fatal(err) <ide><path>integration-cli/docker_cli_links_test.go <ide> func TestLinksInvalidContainerTarget(t *testing.T) { <ide> t.Fatal("an invalid container target should produce an error") <ide> } <ide> if !strings.Contains(out, "Could not get container") { <del> t.Fatal("error output expected 'Could not get container', but got %q instead; err: %v", out, err) <add> t.Fatalf("error output expected 'Could not get container', but got %q instead; err: %v", out, err) <ide> } <ide> <ide> logDone("links - linking to non-existent container should not work") <ide><path>integration-cli/docker_cli_pause_test.go <ide> func TestPause(t *testing.T) { <ide> t.Fatalf("error thrown while checking if containers were paused: %v", err) <ide> } <ide> if len(pausedContainers) != 1 { <del> t.Fatalf("there should be one paused container and not", len(pausedContainers)) <add> t.Fatalf("there should be one paused container and not %d", len(pausedContainers)) <ide> } <ide> <ide> dockerCmd(t, "unpause", name) <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunAttachWithDettach(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true") <ide> _, stderr, _, err := runCommandWithStdoutStderr(cmd) <ide> if err == nil { <del> t.Fatalf("Container should have exited with error code different than 0", err) <add> t.Fatal("Container should have exited with error code different than 0") <ide> } else if !strings.Contains(stderr, "Conflicting options: -a and -d") { <del> t.Fatalf("Should have been returned an error with conflicting options -a and -d") <add> t.Fatal("Should have been returned an error with conflicting options -a and -d") <ide> } <ide> <ide> logDone("run - Attach stdout with -d") <ide> func TestRunCreateVolumeEtc(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") <ide> out, _, err := runCommandWithOutput(cmd) <ide> if err != nil { <del> t.Fatal("failed to run container: %v, output: %q", err, out) <add> t.Fatalf("failed to run container: %v, output: %q", err, out) <ide> } <ide> if !strings.Contains(out, "nameserver 127.0.0.1") { <ide> t.Fatal("/etc volume mount hides /etc/resolv.conf") <ide> func TestRunCreateVolumeEtc(t *testing.T) { <ide> cmd = exec.Command(dockerBinary, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") <ide> out, _, err = runCommandWithOutput(cmd) <ide> if err != nil { <del> t.Fatal("failed to run container: %v, output: %q", err, out) <add> t.Fatalf("failed to run container: %v, output: %q", err, out) <ide> } <ide> if !strings.Contains(out, "test123") { <ide> t.Fatal("/etc volume mount hides /etc/hostname") <ide> func TestRunCreateVolumeEtc(t *testing.T) { <ide> cmd = exec.Command(dockerBinary, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") <ide> out, _, err = runCommandWithOutput(cmd) <ide> if err != nil { <del> t.Fatal("failed to run container: %v, output: %q", err, out) <add> t.Fatalf("failed to run container: %v, output: %q", err, out) <ide> } <ide> out = strings.Replace(out, "\n", " ", -1) <ide> if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { <ide> func TestRunAllowPortRangeThroughExpose(t *testing.T) { <ide> t.Fatal(err) <ide> } <ide> var ports nat.PortMap <del> err = unmarshalJSON([]byte(portstr), &ports) <add> if err = unmarshalJSON([]byte(portstr), &ports); err != nil { <add> t.Fatal(err) <add> } <ide> for port, binding := range ports { <ide> portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) <ide> if portnum < 3000 || portnum > 3003 { <del> t.Fatalf("Port is out of range ", portnum, binding, out) <add> t.Fatalf("Port %d is out of range ", portnum) <ide> } <ide> if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { <del> t.Fatal("Port is not mapped for the port "+port, out) <add> t.Fatalf("Port is not mapped for the port %d", port) <ide> } <ide> } <ide> if err := deleteContainer(id); err != nil { <ide> func TestRunAllowPortRangeThroughPublish(t *testing.T) { <ide> for port, binding := range ports { <ide> portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) <ide> if portnum < 3000 || portnum > 3003 { <del> t.Fatalf("Port is out of range ", portnum, binding, out) <add> t.Fatalf("Port %d is out of range ", portnum) <ide> } <ide> if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { <ide> t.Fatal("Port is not mapped for the port "+port, out) <ide><path>integration-cli/docker_utils.go <ide> func daemonTime(t *testing.T) time.Time { <ide> <ide> body, err := sockRequest("GET", "/info", nil) <ide> if err != nil { <del> t.Fatal("daemonTime: failed to get /info: %v", err) <add> t.Fatalf("daemonTime: failed to get /info: %v", err) <ide> } <ide> <ide> type infoJSON struct {
6
Ruby
Ruby
add application verifier
233001749cd00e147f93c17c17e49e5f6094721e
<ide><path>railties/lib/rails/application.rb <ide> def key_generator <ide> end <ide> end <ide> <add> def verifier <add> @verifier ||= begin <add> if config.respond_to?(:message_verifier_salt) <add> salt = config.message_verifier_salt <add> end <add> <add> salt = salt || 'application verifier' <add> secret = key_generator.generate_key(salt) <add> ActiveSupport::MessageVerifier.new(secret) <add> end <add> end <add> <ide> # Stores some of the Rails initial environment parameters which <ide> # will be used by middlewares and engines to configure themselves. <ide> def env_config <ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> assert_equal 'some_value', verifier.verify(last_response.body) <ide> end <ide> <add> test "application verifier can be used in the entire application" do <add> make_basic_app do |app| <add> app.config.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' <add> app.config.session_store :disabled <add> end <add> <add> class ::OmgController < ActionController::Base <add> def index <add> render text: Rails.application.verifier.generate("some_value") <add> end <add> end <add> <add> get "/" <add> <add> assert_equal 'some_value', Rails.application.verifier.verify(last_response.body) <add> <add> secret = app.key_generator.generate_key('application verifier') <add> verifier = ActiveSupport::MessageVerifier.new(secret) <add> assert_equal 'some_value', verifier.verify(last_response.body) <add> end <add> <add> test "application verifier use the configure salt" do <add> make_basic_app do |app| <add> app.config.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' <add> app.config.session_store :disabled <add> app.config.message_verifier_salt = 'another salt' <add> end <add> <add> class ::OmgController < ActionController::Base <add> def index <add> render text: Rails.application.verifier.generate("some_value") <add> end <add> end <add> <add> get "/" <add> <add> secret = app.key_generator.generate_key('another salt') <add> verifier = ActiveSupport::MessageVerifier.new(secret) <add> assert_equal 'some_value', verifier.verify(last_response.body) <add> end <add> <ide> test "protect from forgery is the default in a new app" do <ide> make_basic_app <ide>
2
Java
Java
fix typo in single + maybe defer()
f4daec6334454003ed394db1c1336af4527721f3
<ide><path>src/main/java/io/reactivex/Maybe.java <ide> public static <T> Maybe<T> create(MaybeOnSubscribe<T> onSubscribe) { <ide> <ide> /** <ide> * Calls a Callable for each individual MaybeObserver to return the actual MaybeSource source to <del> * be subscribe to. <add> * be subscribed to. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd> <ide><path>src/main/java/io/reactivex/Single.java <ide> public static <T> Single<T> create(SingleOnSubscribe<T> source) { <ide> <ide> /** <ide> * Calls a Callable for each individual SingleObserver to return the actual Single source to <del> * be subscribe to. <add> * be subscribed to. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd>
2
Ruby
Ruby
check homepage reachability
3ba3ecba9dec22a0f12533792fdfb6a9910cc81b
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_homepage <ide> %r[^http://code\.google\.com/] <ide> problem "Please use https:// for #{homepage}" <ide> end <add> <add> return unless @online <add> begin <add> nostdout { curl "--connect-timeout", "15", "-IL", "-o", "/dev/null", homepage } <add> rescue ErrorDuringExecution <add> problem "The homepage is not reachable (curl exit code #{$?.exitstatus})" <add> end <ide> end <ide> <ide> def audit_github_repository
1
Javascript
Javascript
remove unnecessary null
5170db8e72e1301205b82c8a4e69b38b019bb868
<ide><path>src/shared/utils/getComponentName.js <ide> import type { ReactInstance } from 'ReactInstanceType'; <ide> import type { Fiber } from 'ReactFiber'; <ide> <del>function getComponentName(instanceOrFiber : ReactInstance | Fiber) : string | null { <add>function getComponentName(instanceOrFiber : ReactInstance | Fiber) : string { <ide> if (typeof instanceOrFiber.getName === 'function') { <ide> // Stack reconciler <ide> const instance = ((instanceOrFiber : any) : ReactInstance); <del> return instance.getName() || 'Component' || null; <add> return instance.getName() || 'Component'; <ide> } <ide> if (typeof instanceOrFiber.tag === 'number') { <ide> // Fiber reconciler <ide> function getComponentName(instanceOrFiber : ReactInstance | Fiber) : string | nu <ide> return type; <ide> } <ide> if (typeof type === 'function') { <del> return type.displayName || type.name || null; <add> return type.displayName || type.name || 'Component'; <ide> } <ide> } <del> return null; <add> return 'Component'; <ide> } <ide> <ide> module.exports = getComponentName;
1
Text
Text
move entry from "features" to "bugs"
bb4cd4a5ce36a741dd18d203b39537a05506b298
<ide><path>CHANGELOG.md <ide> - **ngMessages:** create new scope for ngMessage, clean it up correctly <ide> ([56f33af8](https://github.com/angular/angular.js/commit/56f33af89045e2ec18d144d9d1ef73affbe51959), <ide> [#14307](https://github.com/angular/angular.js/issues/14307)) <add>- **ngMessagesInclude:** don't break on empty (or whitespace-only) templates <add> ([01b8772c](https://github.com/angular/angular.js/commit/01b8772cca55916376355a2ae58d3ab7832a4bc2), <add> [#12941](https://github.com/angular/angular.js/issues/12941), [#14726](https://github.com/angular/angular.js/issues/14726)) <ide> - **ngMock#$controller:** properly assign bindings to all types of controllers (e.g. class-based) <ide> ([db58801a](https://github.com/angular/angular.js/commit/db58801a55c91df755414387dc00fee5902bb5f3), <ide> [#14437](https://github.com/angular/angular.js/issues/14437), [#14439](https://github.com/angular/angular.js/issues/14439)) <ide> - **limitTo:** add support for array-like objects <ide> ([b03957f0](https://github.com/angular/angular.js/commit/b03957f0047fcfe996abc8efe97f9e2be2c2e13a), <ide> [#14657](https://github.com/angular/angular.js/issues/14657), [#14694](https://github.com/angular/angular.js/issues/14694)) <del>- **ngMessagesInclude:** don't break on empty (or whitespace-only) templates <del> ([01b8772c](https://github.com/angular/angular.js/commit/01b8772cca55916376355a2ae58d3ab7832a4bc2), <del> [#12941](https://github.com/angular/angular.js/issues/12941), [#14726](https://github.com/angular/angular.js/issues/14726)) <ide> - **orderBy:** add support for custom comparators <ide> ([2e33d170](https://github.com/angular/angular.js/commit/2e33d170be7eb72f40fd57a8f66631583572fbf2), <ide> [#13238](https://github.com/angular/angular.js/issues/13238), [#14455](https://github.com/angular/angular.js/issues/14455), [#5123](https://github.com/angular/angular.js/issues/5123), [#8112](https://github.com/angular/angular.js/issues/8112), [#10368](https://github.com/angular/angular.js/issues/10368), [#14468](https://github.com/angular/angular.js/issues/14468))
1
Text
Text
fix tiny typo in labelling.md
9e6a6112a436143d353115e73c974a6f6b2f7713
<ide><path>docs/axes/labelling.md <ide> The scale label configuration is nested under the scale configuration in the `sc <ide> | Name | Type | Default | Description <ide> | -----| ---- | --------| ----------- <ide> | `display` | `Boolean` | `false` | If true, display the axis title. <del>| `labelString` | `String` | `''` | The text for the title. (i.e. "# of People" or "Respone Choices"). <add>| `labelString` | `String` | `''` | The text for the title. (i.e. "# of People" or "Response Choices"). <ide> | `fontColor` | Color | `'#666'` | Font color for scale title. <ide> | `fontFamily` | `String` | `"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"` | Font family for the scale title, follows CSS font-family options. <ide> | `fontSize` | `Number` | `12` | Font size for scale title. <ide> var chart = new Chart(ctx, { <ide> } <ide> } <ide> }); <del>``` <ide>\ No newline at end of file <add>```
1
Mixed
Go
check uid ranges
72d1e40c4a3b190319cfa5cb44b5e6f1694100fc
<ide><path>docs/sources/reference/run.md <ide> but the operator can override it: <ide> <ide> -u="": Username or UID <ide> <add>> **Note:** if you pass numeric uid, it must be in range 0-2147483647. <add> <ide> ## WORKDIR <ide> <ide> The default working directory for running binaries within a container is the <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestUserByID(t *testing.T) { <ide> logDone("run - user by id") <ide> } <ide> <add>func TestUserByIDBig(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "-u", "2147483648", "busybox", "id") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err == nil { <add> t.Fatal("No error, but must be.", out) <add> } <add> if !strings.Contains(out, "Uids and gids must be in range") { <add> t.Fatalf("expected error about uids range, got %s", out) <add> } <add> deleteAllContainers() <add> <add> logDone("run - user by id, id too big") <add>} <add> <add>func TestUserByIDNegative(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "-u", "-1", "busybox", "id") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err == nil { <add> t.Fatal("No error, but must be.", out) <add> } <add> if !strings.Contains(out, "Uids and gids must be in range") { <add> t.Fatalf("expected error about uids range, got %s", out) <add> } <add> deleteAllContainers() <add> <add> logDone("run - user by id, id negative") <add>} <add> <add>func TestUserByIDZero(t *testing.T) { <add> cmd := exec.Command(dockerBinary, "run", "-u", "0", "busybox", "id") <add> <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> t.Fatal(err, out) <add> } <add> if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") { <add> t.Fatalf("expected daemon user got %s", out) <add> } <add> deleteAllContainers() <add> <add> logDone("run - user by id, zero uid") <add>} <add> <ide> func TestUserNotFound(t *testing.T) { <ide> cmd := exec.Command(dockerBinary, "run", "-u", "notme", "busybox", "id") <ide> <ide><path>pkg/user/user.go <ide> import ( <ide> "strings" <ide> ) <ide> <add>const ( <add> minId = 0 <add> maxId = 1<<31 - 1 //for 32-bit systems compatibility <add>) <add> <add>var ( <add> ErrRange = fmt.Errorf("Uids and gids must be in range %d-%d", minId, maxId) <add>) <add> <ide> type User struct { <ide> Name string <ide> Pass string <ide> func GetUserGroupSupplementary(userSpec string, defaultUid int, defaultGid int) <ide> // not numeric - we have to bail <ide> return 0, 0, nil, fmt.Errorf("Unable to find user %v", userArg) <ide> } <add> if uid < minId || uid > maxId { <add> return 0, 0, nil, ErrRange <add> } <ide> <ide> // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit <ide> } <ide> func GetUserGroupSupplementary(userSpec string, defaultUid int, defaultGid int) <ide> // not numeric - we have to bail <ide> return 0, 0, nil, fmt.Errorf("Unable to find group %v", groupArg) <ide> } <add> if gid < minId || gid > maxId { <add> return 0, 0, nil, ErrRange <add> } <ide> <ide> // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit <ide> }
3
PHP
PHP
pass notifiable email through reset link
0fd627be7d66eb053b991d22c5d5e859284c8dce
<ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php <ide> public function toMail($notifiable) <ide> return (new MailMessage) <ide> ->subject(Lang::getFromJson('Reset Password Notification')) <ide> ->line(Lang::getFromJson('You are receiving this email because we received a password reset request for your account.')) <del> ->action(Lang::getFromJson('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token], false))) <add> ->action(Lang::getFromJson('Reset Password'), url(config('app.url').route('password.reset', ['token' => $this->token, 'email' => $notifiable->email], false))) <ide> ->line(Lang::getFromJson('This password reset link will expire in :count minutes.', ['count' => config('auth.passwords.users.expire')])) <ide> ->line(Lang::getFromJson('If you did not request a password reset, no further action is required.')); <ide> }
1
Javascript
Javascript
rectangle element tests
26684b6371cca9db250edc9e7c0a056fb8081d4d
<ide><path>src/elements/element.rectangle.js <ide> }, <ide> inRange: function(mouseX, mouseY) { <ide> var vm = this._view; <del> if (vm.y < vm.base) { <del> return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base); <del> } else { <del> return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y); <del> } <add> var inRange = false; <add> <add> if (vm) { <add> if (vm.y < vm.base) { <add> inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.y && mouseY <= vm.base); <add> } else { <add> inRange = (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2) && (mouseY >= vm.base && mouseY <= vm.y); <add> } <add> } <add> <add> return inRange; <ide> }, <ide> inLabelRange: function(mouseX) { <ide> var vm = this._view; <del> return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2); <add> <add> if (vm) { <add> return (mouseX >= vm.x - vm.width / 2 && mouseX <= vm.x + vm.width / 2); <add> } else { <add> return false; <add> } <ide> }, <ide> tooltipPosition: function() { <ide> var vm = this._view; <ide><path>test/element.rectangle.tests.js <add>// Test the rectangle element <add> <add>describe('Rectangle element tests', function() { <add> it ('Should be constructed', function() { <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> expect(rectangle).not.toBe(undefined); <add> expect(rectangle._datasetIndex).toBe(2); <add> expect(rectangle._index).toBe(1); <add> }); <add> <add> it ('Should correctly identify as in range', function() { <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Safely handles if these are called before the viewmodel is instantiated <add> expect(rectangle.inRange(5)).toBe(false); <add> expect(rectangle.inLabelRange(5)).toBe(false); <add> <add> // Attach a view object as if we were the controller <add> rectangle._view = { <add> base: 0, <add> width: 4, <add> x: 10, <add> y: 15 <add> }; <add> <add> expect(rectangle.inRange(10, 15)).toBe(true); <add> expect(rectangle.inRange(10, 10)).toBe(true); <add> expect(rectangle.inRange(10, 16)).toBe(false); <add> expect(rectangle.inRange(5, 5)).toBe(false); <add> <add> expect(rectangle.inLabelRange(5)).toBe(false); <add> expect(rectangle.inLabelRange(7)).toBe(false); <add> expect(rectangle.inLabelRange(10)).toBe(true); <add> expect(rectangle.inLabelRange(12)).toBe(true); <add> expect(rectangle.inLabelRange(15)).toBe(false); <add> expect(rectangle.inLabelRange(20)).toBe(false); <add> <add> // Test when the y is below the base (negative bar) <add> var negativeRectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Attach a view object as if we were the controller <add> negativeRectangle._view = { <add> base: 0, <add> width: 4, <add> x: 10, <add> y: -15 <add> }; <add> <add> expect(negativeRectangle.inRange(10, -16)).toBe(false); <add> expect(negativeRectangle.inRange(10, 1)).toBe(false); <add> expect(negativeRectangle.inRange(10, -5)).toBe(true); <add> }); <add> <add> it ('should get the correct height', function() { <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Attach a view object as if we were the controller <add> rectangle._view = { <add> base: 0, <add> width: 4, <add> x: 10, <add> y: 15 <add> }; <add> <add> expect(rectangle.height()).toBe(-15); <add> <add> // Test when the y is below the base (negative bar) <add> var negativeRectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Attach a view object as if we were the controller <add> negativeRectangle._view = { <add> base: -10, <add> width: 4, <add> x: 10, <add> y: -15 <add> }; <add> expect(negativeRectangle.height()).toBe(5); <add> }); <add> <add> it ('should get the correct tooltip position', function() { <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Attach a view object as if we were the controller <add> rectangle._view = { <add> base: 0, <add> width: 4, <add> x: 10, <add> y: 15 <add> }; <add> <add> expect(rectangle.tooltipPosition()).toEqual({ <add> x: 10, <add> y: 0, <add> }); <add> <add> // Test when the y is below the base (negative bar) <add> var negativeRectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1 <add> }); <add> <add> // Attach a view object as if we were the controller <add> negativeRectangle._view = { <add> base: -10, <add> width: 4, <add> x: 10, <add> y: -15 <add> }; <add> <add> expect(negativeRectangle.tooltipPosition()).toEqual({ <add> x: 10, <add> y: -15, <add> }); <add> }); <add> <add> it ('should draw correctly', function() { <add> var mockContext = window.createMockContext(); <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1, <add> _chart: { <add> ctx: mockContext, <add> } <add> }); <add> <add> // Attach a view object as if we were the controller <add> rectangle._view = { <add> backgroundColor: 'rgb(255, 0, 0)', <add> base: 0, <add> borderColor: 'rgb(0, 0, 255)', <add> borderWidth: 1, <add> ctx: mockContext, <add> width: 4, <add> x: 10, <add> y: 15, <add> }; <add> <add> rectangle.draw(); <add> <add> expect(mockContext.getCalls()).toEqual([{ <add> name: 'beginPath', <add> args: [], <add> }, { <add> name: 'setFillStyle', <add> args: ['rgb(255, 0, 0)'] <add> }, { <add> name: 'setStrokeStyle', <add> args: ['rgb(0, 0, 255)'], <add> }, { <add> name: 'setLineWidth', <add> args: [1] <add> }, { <add> name: 'moveTo', <add> args: [8.5, 0] <add> }, { <add> name: 'lineTo', <add> args: [8.5, 15.5] <add> }, { <add> name: 'lineTo', <add> args: [11.5, 15.5] <add> }, { <add> name: 'lineTo', <add> args: [11.5, 0] <add> }, { <add> name: 'fill', <add> args: [], <add> }, { <add> name: 'stroke', <add> args: [] <add> }]); <add> }); <add> <add> it ('should draw correctly with no stroke', function() { <add> var mockContext = window.createMockContext(); <add> var rectangle = new Chart.elements.Rectangle({ <add> _datasetIndex: 2, <add> _index: 1, <add> _chart: { <add> ctx: mockContext, <add> } <add> }); <add> <add> // Attach a view object as if we were the controller <add> rectangle._view = { <add> backgroundColor: 'rgb(255, 0, 0)', <add> base: 0, <add> borderColor: 'rgb(0, 0, 255)', <add> ctx: mockContext, <add> width: 4, <add> x: 10, <add> y: 15, <add> }; <add> <add> rectangle.draw(); <add> <add> expect(mockContext.getCalls()).toEqual([{ <add> name: 'beginPath', <add> args: [], <add> }, { <add> name: 'setFillStyle', <add> args: ['rgb(255, 0, 0)'] <add> }, { <add> name: 'setStrokeStyle', <add> args: ['rgb(0, 0, 255)'], <add> }, { <add> name: 'setLineWidth', <add> args: [undefined] <add> }, { <add> name: 'moveTo', <add> args: [8, 0] <add> }, { <add> name: 'lineTo', <add> args: [8, 15] <add> }, { <add> name: 'lineTo', <add> args: [12, 15] <add> }, { <add> name: 'lineTo', <add> args: [12, 0] <add> }, { <add> name: 'fill', <add> args: [], <add> }]); <add> }); <add> <add> <add>}); <ide>\ No newline at end of file
2
PHP
PHP
add tests which cover additional functionality
5cd82c114dce511db580e2b2b827b75eedda80d8
<ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testTheMutatorCacheIsPopulated() <ide> } <ide> <ide> <add> public function testRouteKeyIsPrimaryKey() <add> { <add> $model = new EloquentModelStub; <add> $model->id = 'foo'; <add> $this->assertEquals('foo', $model->getRouteKey()); <add> } <add> <add> <ide> public function testRouteNameIsPrimaryKeyName() <ide> { <ide> $model = new EloquentModelStub; <ide> $this->assertEquals('id', $model->getRouteKeyName()); <ide> } <ide> <ide> <del> <ide> public function testCloneModelMakesAFreshCopyOfTheModel() <ide> { <ide> $class = new EloquentModelStub; <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> <?php <ide> <ide> use Illuminate\Routing\UrlGenerator; <add>use Illuminate\Support\Contracts\RouteableInterface; <ide> <ide> class RoutingUrlGeneratorTest extends PHPUnit_Framework_TestCase { <ide> <ide> public function testBasicRouteGeneration() <ide> <ide> } <ide> <add> public function testRouteableInterfaceRouting() <add> { <add> $url = new UrlGenerator( <add> $routes = new Illuminate\Routing\RouteCollection, <add> $request = Illuminate\Http\Request::create('http://www.foo.com/') <add> ); <add> <add> $route = new Illuminate\Routing\Route(array('GET'), 'foo/{bar}', array('as' => 'routeable')); <add> $routes->add($route); <add> <add> $model = new RouteableInterfaceStub; <add> <add> $this->assertEquals('/foo/routeable', $url->route('routeable', array($model), false)); <add> } <add> <ide> <ide> public function testRoutesMaintainRequestScheme() <ide> { <ide> public function testForceRootUrl() <ide> } <ide> <ide> } <add> <add>class RouteableInterfaceStub implements RouteableInterface { <add> public function getRouteKey() { return 'routeable'; } <add> public function getRouteKeyName() {} <add>} <ide>\ No newline at end of file
2
Ruby
Ruby
handle `frozenerror` if it is available
01efbc128d1379d02dd14acf324d011944a1c429
<ide><path>activerecord/test/cases/aggregations_test.rb <ide> def test_change_single_value_object <ide> <ide> def test_immutable_value_objects <ide> customers(:david).balance = Money.new(100) <del> assert_raise(RuntimeError) { customers(:david).balance.instance_eval { @amount = 20 } } <add> assert_raise(frozen_error_class) { customers(:david).balance.instance_eval { @amount = 20 } } <ide> end <ide> <ide> def test_inferred_mapping <ide><path>activerecord/test/cases/query_cache_test.rb <ide> def test_query_cache_does_not_allow_sql_key_mutation <ide> payload[:sql].downcase! <ide> end <ide> <del> assert_raises RuntimeError do <add> assert_raises frozen_error_class do <ide> ActiveRecord::Base.cache do <ide> assert_queries(1) { Task.find(1); Task.find(1) } <ide> end <ide><path>activerecord/test/cases/test_case.rb <ide> def has_column?(model, column_name) <ide> model.reset_column_information <ide> model.column_names.include?(column_name.to_s) <ide> end <add> <add> def frozen_error_class <add> Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError <add> end <ide> end <ide> <ide> class PostgreSQLTestCase < TestCase <ide><path>activerecord/test/cases/transactions_test.rb <ide> def test_rollback_when_commit_raises <ide> def test_rollback_when_saving_a_frozen_record <ide> topic = Topic.new(title: "test") <ide> topic.freeze <del> e = assert_raise(RuntimeError) { topic.save } <add> e = assert_raise(frozen_error_class) { topic.save } <ide> # Not good enough, but we can't do much <ide> # about it since there is no specific error <ide> # for frozen objects. <ide><path>activesupport/test/abstract_unit.rb <ide> class ActiveSupport::TestCase <ide> private def jruby_skip(message = "") <ide> skip message if defined?(JRUBY_VERSION) <ide> end <add> <add> def frozen_error_class <add> Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError <add> end <ide> end <ide><path>activesupport/test/core_ext/hash_ext_test.rb <ide> def test_except_with_original_frozen <ide> original.freeze <ide> assert_nothing_raised { original.except(:a) } <ide> <del> assert_raise(RuntimeError) { original.except!(:a) } <add> assert_raise(frozen_error_class) { original.except!(:a) } <ide> end <ide> <ide> def test_except_does_not_delete_values_in_original <ide><path>railties/test/application/middleware_test.rb <ide> def app <ide> <ide> test "can't change middleware after it's built" do <ide> boot! <del> assert_raise RuntimeError do <add> assert_raise frozen_error_class do <ide> app.config.middleware.use Rack::Config <ide> end <ide> end <ide><path>railties/test/isolation/abstract_unit.rb <ide> class ActiveSupport::TestCase <ide> include TestHelpers::Rack <ide> include TestHelpers::Generation <ide> include ActiveSupport::Testing::Stream <add> <add> def frozen_error_class <add> Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError <add> end <ide> end <ide> <ide> # Create a scope and build a fixture rails app
8
Go
Go
add break after found = true
8928677ea2b4e69ecfd96a2c951a33e46b7b7388
<ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerSuite) TestDaemonIPv6Enabled(c *check.C) { <ide> for i := range addrs { <ide> if addrs[i].String() == expected { <ide> found = true <add> break <ide> } <ide> } <ide>
1
Mixed
Ruby
handle notes in *.sass files
dd996ad394057a003ad851ff75e6242d0c5e8fa1
<ide><path>railties/CHANGELOG.md <add>* Fix `rake notes` to look into `*.sass` files <add> <add> *Yuri Artemev* <add> <ide> * Removed deprecated `Rails.application.railties.engines`. <ide> <ide> *Arun Agrawal* <ide><path>railties/lib/rails/source_annotation_extractor.rb <ide> def find_in(dir) <ide> case item <ide> when /\.(builder|rb|coffee|rake)$/ <ide> /#\s*(#{tag}):?\s*(.*)$/ <del> when /\.(css|scss|js)$/ <add> when /\.(css|scss|sass|js)$/ <ide> /\/\/\s*(#{tag}):?\s*(.*)$/ <ide> when /\.erb$/ <ide> /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/ <ide><path>railties/test/application/rake/notes_test.rb <ide> def teardown <ide> app_file "app/assets/javascripts/application.js", "// TODO: note in js" <ide> app_file "app/assets/stylesheets/application.css", "// TODO: note in css" <ide> app_file "app/assets/stylesheets/application.css.scss", "// TODO: note in scss" <add> app_file "app/assets/stylesheets/application.css.sass", "// TODO: note in sass" <ide> app_file "app/controllers/application_controller.rb", 1000.times.map { "" }.join("\n") << "# TODO: note in ruby" <ide> app_file "lib/tasks/task.rake", "# TODO: note in rake" <ide> <ide> def teardown <ide> assert_match(/note in js/, output) <ide> assert_match(/note in css/, output) <ide> assert_match(/note in scss/, output) <add> assert_match(/note in sass/, output) <ide> assert_match(/note in rake/, output) <ide> <del> assert_equal 9, lines.size <add> assert_equal 10, lines.size <ide> <ide> lines.each do |line| <ide> assert_equal 4, line[0].size
3
Text
Text
fix the readme
fa2876c7f9be06baf67c652e14bc036bc88c8dbb
<ide><path>README.md <ide> To propose a model for inclusion please submit a pull request. <ide> - [textsum](textsum) -- sequence-to-sequence with attention model for text summarization. <ide> - [transformer](transformer) -- spatial transformer network, which allows the spatial manipulation of data within the network <ide> - [im2txt](im2txt) -- image-to-text neural network for image captioning. <del>======= <add> <ide> Implementation of the Neural Programmer model described in https://openreview.net/pdf?id=ry2YOrcge <ide> <ide> Download the data from http://www-nlp.stanford.edu/software/sempre/wikitable/
1
Javascript
Javascript
modify regexp in template-common
83b0013209329f5952ac2a9554fd21a3340ef23b
<ide><path>examples/template-common.js <ide> exports.replaceBase = (template) => { <ide> }; <ide> <ide> exports.needResults = (template, prefix) => { <del> const regExp = prefix ? new RegExp(`\\{\\{${prefix}:`) : /\{\{/; <add> const regExp = prefix ? new RegExp(`_\\{\\{${prefix}:`) : /_\{\{/; <ide> return regExp.test(template); <ide> }; <ide> <ide> exports.replaceResults = (template, baseDir, stdout, prefix) => { <del> const regexp = new RegExp("\\{\\{" + (prefix ? prefix + ":" : "") + "([^:\\}]+)\\}\\}", "g"); <add> const regexp = new RegExp("_\\{\\{" + (prefix ? prefix + ":" : "") + "([^:\\}]+)\\}\\}_", "g"); <ide> <ide> return template.replace(regexp, function(match) { <del> match = match.substr(2 + (prefix ? prefix.length + 1 : 0), match.length - 4 - (prefix ? prefix.length + 1 : 0)); <add> match = match.substr(3 + (prefix ? prefix.length + 1 : 0), match.length - 6 - (prefix ? prefix.length + 1 : 0)); <ide> if(match === "stdout") <ide> return stdout; <ide> return fs.readFileSync(path.join(baseDir, match), "utf-8").replace(/[\r\n]*$/, "");
1
PHP
PHP
add a test for edge case. remove an unneeded test
19720e5151205f63eca83b2aa20b9b9aeff2739d
<ide><path>tests/TestCase/Utility/TextTest.php <ide> public function testTruncate() <ide> $this->assertSame('Vive la R' . chr(195) . chr(169) . 'pu...', $this->Text->truncate($text8, 15)); <ide> $this->assertSame('НОПРСТУ...', $this->Text->truncate($text9, 10)); <ide> $this->assertSame('http://example.com/somethin...', $this->Text->truncate($text10, 30)); <add> $this->assertSame('1 <b>2...</b>', $this->Text->truncate('1 <b>2 345</b>', 6, ['exact' => false, 'html' => true, 'ellipsis' => '...'])); <ide> <ide> $text = '<p><span style="font-size: medium;"><a>Iamatestwithnospacesandhtml</a></span></p>'; <ide> $result = $this->Text->truncate($text, 10, [ <ide> public function testSubstr() <ide> return $method->invokeArgs(null, func_get_args()); <ide> }; <ide> <del> $text = '&#x3042;&#x3044;&#x3046;&#x3048;&#x3048;'; <del> $this->assertEquals('&#x3044;&#x3046;&#x3048;', $substr($text, 1, -1, ['html' => true, 'trimWidth' => true])); <del> <ide> $text = 'データベースアクセス &amp; ORM'; <ide> $this->assertEquals('アクセス', $substr($text, 6, 4, [])); <ide> $this->assertEquals('アクセス', $substr($text, 6, 8, ['trimWidth' => true]));
1
Javascript
Javascript
add test on unhandled rejection
18cf0960eab834ed3a4ddef22a7e8b6dcecfc058
<ide><path>test/parallel/test-async-hooks-promise-enable-disable.js <ide> let p_resource = null; <ide> let p_er = null; <ide> let p_inits = 0; <ide> <add>common.crashOnUnhandledRejection(); <add> <ide> // Not useful to place common.mustCall() around 'exit' event b/c it won't be <ide> // able to check it anway. <ide> process.on('exit', (code) => {
1
Java
Java
improve resourcepatternhint documentation
b9f85627a17a55270d5ba3d3b6e7b7d267ba8817
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourceHints.java <ide> public ResourceHints registerPattern(@Nullable Consumer<ResourcePatternHints.Bui <ide> /** <ide> * Register that the resources matching the specified pattern should be <ide> * made available at runtime. <del> * @param include a pattern of the resources to include <add> * @param include a pattern of the resources to include (see {@link ResourcePatternHint} documentation) <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public ResourceHints registerPattern(String include) { <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourcePatternHint.java <ide> <ide> /** <ide> * A hint that describes resources that should be made available at runtime. <add> * <ide> * <p>The patterns may be a simple path which has a one-to-one mapping to a <ide> * resource on the classpath, or alternatively may contain the special <del> * {@code *} character to indicate a wildcard search. <add> * {@code *} character to indicate a wildcard search. For example: <add> * <ul> <add> * <li>{@code file.properties}: matches just the {@code file.properties} <add> * file at the root of the classpath.</li> <add> * <li>{@code com/example/file.properties}: matches just the <add> * {@code file.properties} file in {@code com/example/}.</li> <add> * <li>{@code *.properties}: matches all the files with a {@code .properties} <add> * extension anywhere in the classpath.</li> <add> * <li>{@code com/example/*.properties}: matches all the files with a {@code .properties} <add> * extension in {@code com/example/} and its child directories at any depth.</li> <add> * <li>{@code com/example/*}: matches all the files in {@code com/example/} <add> * and its child directories at any depth.</li> <add> * </ul> <ide> * <ide> * @author Stephane Nicoll <ide> * @author Brian Clozel <add> * @author Sebastien Deleuze <ide> * @since 6.0 <ide> */ <ide> public final class ResourcePatternHint implements ConditionalHint { <ide><path>spring-core/src/main/java/org/springframework/aot/hint/ResourcePatternHints.java <ide> public static class Builder { <ide> /** <ide> * Includes the resources matching the specified pattern. <ide> * @param reachableType the type that should be reachable for this hint to apply <del> * @param includes the include patterns <add> * @param includes the include patterns (see {@link ResourcePatternHint} documentation) <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public Builder includes(TypeReference reachableType, String... includes) { <ide> public Builder includes(TypeReference reachableType, String... includes) { <ide> <ide> /** <ide> * Includes the resources matching the specified pattern. <del> * @param includes the include patterns <add> * @param includes the include patterns (see {@link ResourcePatternHint} documentation) <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public Builder includes(String... includes) { <ide> public Builder includes(String... includes) { <ide> /** <ide> * Exclude resources matching the specified pattern. <ide> * @param reachableType the type that should be reachable for this hint to apply <del> * @param excludes the excludes pattern <add> * @param excludes the excludes pattern (see {@link ResourcePatternHint} documentation) <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public Builder excludes(TypeReference reachableType, String... excludes) { <ide> public Builder excludes(TypeReference reachableType, String... excludes) { <ide> <ide> /** <ide> * Exclude resources matching the specified pattern. <del> * @param excludes the excludes pattern <add> * @param excludes the excludes pattern (see {@link ResourcePatternHint} documentation) <ide> * @return {@code this}, to facilitate method chaining <ide> */ <ide> public Builder excludes(String... excludes) {
3
Javascript
Javascript
remove unused variable
f13f3b5b29c323162ec967b95bcc611b4e9e3ac3
<ide><path>src/layout/pie.js <ide> d3.layout.pie = function() { <ide> // Compute the arcs! <ide> // They are stored in the original data's order. <ide> var arcs = []; <del> index.forEach(function(i, j) { <add> index.forEach(function(i) { <ide> arcs[i] = { <ide> data: data[i], <ide> value: d = values[i],
1
Javascript
Javascript
remove runwithpriority internally
41e62e77191e112a7be38448e53470a6b8220611
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js <ide> import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes'; <ide> import type {Container, SuspenseInstance} from '../client/ReactDOMHostConfig'; <ide> import type {DOMEventName} from '../events/DOMEventNames'; <ide> <del>// Intentionally not named imports because Rollup would use dynamic dispatch for <del>// CommonJS interop named imports. <del>import * as Scheduler from 'scheduler'; <del> <ide> import { <ide> isReplayableDiscreteEvent, <ide> queueDiscreteEvent, <ide> const getCurrentPriorityLevel = enableNewReconciler <ide> ? getCurrentPriorityLevel_new <ide> : getCurrentPriorityLevel_old; <ide> <del>const { <del> unstable_UserBlockingPriority: UserBlockingPriority, <del> unstable_runWithPriority: runWithPriority, <del>} = Scheduler; <del> <ide> // TODO: can we stop exporting these? <ide> export let _enabled = true; <ide> <ide> function dispatchContinuousEvent( <ide> ) { <ide> const previousPriority = getCurrentUpdateLanePriority(); <ide> try { <del> // TODO: Double wrapping is necessary while we decouple Scheduler priority. <ide> setCurrentUpdateLanePriority(InputContinuousLanePriority); <del> runWithPriority( <del> UserBlockingPriority, <del> dispatchEvent.bind( <del> null, <del> domEventName, <del> eventSystemFlags, <del> container, <del> nativeEvent, <del> ), <del> ); <add> dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousPriority); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberHooks.new.js <ide> import { <ide> markWorkInProgressReceivedUpdate, <ide> checkIfWorkInProgressReceivedUpdate, <ide> } from './ReactFiberBeginWork.new'; <del>import { <del> UserBlockingPriority, <del> NormalPriority, <del> runWithPriority, <del> getCurrentPriorityLevel, <del>} from './SchedulerWithReactIntegration.new'; <ide> import {getIsHydrating} from './ReactFiberHydrationContext.new'; <ide> import { <ide> makeClientId, <ide> function rerenderDeferredValue<T>(value: T): T { <ide> } <ide> <ide> function startTransition(setPending, callback) { <del> const priorityLevel = getCurrentPriorityLevel(); <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> setCurrentUpdateLanePriority( <ide> higherLanePriority(previousLanePriority, InputContinuousLanePriority), <ide> ); <ide> <del> runWithPriority( <del> priorityLevel < UserBlockingPriority ? UserBlockingPriority : priorityLevel, <del> () => { <del> setPending(true); <del> }, <del> ); <add> setPending(true); <ide> <ide> // TODO: Can remove this. Was only necessary because we used to give <ide> // different behavior to transitions without a config object. Now they are <ide> // all treated the same. <ide> setCurrentUpdateLanePriority(DefaultLanePriority); <ide> <del> runWithPriority( <del> priorityLevel > NormalPriority ? NormalPriority : priorityLevel, <del> () => { <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> ReactCurrentBatchConfig.transition = 1; <del> try { <del> setPending(false); <del> callback(); <del> } finally { <del> setCurrentUpdateLanePriority(previousLanePriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <del> } <del> }, <del> ); <add> const prevTransition = ReactCurrentBatchConfig.transition; <add> ReactCurrentBatchConfig.transition = 1; <add> try { <add> setPending(false); <add> callback(); <add> } finally { <add> setCurrentUpdateLanePriority(previousLanePriority); <add> ReactCurrentBatchConfig.transition = prevTransition; <add> } <ide> } <ide> <ide> function mountTransition(): [(() => void) => void, boolean] { <ide><path>packages/react-reconciler/src/ReactFiberHooks.old.js <ide> import { <ide> markWorkInProgressReceivedUpdate, <ide> checkIfWorkInProgressReceivedUpdate, <ide> } from './ReactFiberBeginWork.old'; <del>import { <del> UserBlockingPriority, <del> NormalPriority, <del> runWithPriority, <del> getCurrentPriorityLevel, <del>} from './SchedulerWithReactIntegration.old'; <ide> import {getIsHydrating} from './ReactFiberHydrationContext.old'; <ide> import { <ide> makeClientId, <ide> function rerenderDeferredValue<T>(value: T): T { <ide> } <ide> <ide> function startTransition(setPending, callback) { <del> const priorityLevel = getCurrentPriorityLevel(); <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> setCurrentUpdateLanePriority( <ide> higherLanePriority(previousLanePriority, InputContinuousLanePriority), <ide> ); <ide> <del> runWithPriority( <del> priorityLevel < UserBlockingPriority ? UserBlockingPriority : priorityLevel, <del> () => { <del> setPending(true); <del> }, <del> ); <add> setPending(true); <ide> <ide> // TODO: Can remove this. Was only necessary because we used to give <ide> // different behavior to transitions without a config object. Now they are <ide> // all treated the same. <ide> setCurrentUpdateLanePriority(DefaultLanePriority); <ide> <del> runWithPriority( <del> priorityLevel > NormalPriority ? NormalPriority : priorityLevel, <del> () => { <del> const prevTransition = ReactCurrentBatchConfig.transition; <del> ReactCurrentBatchConfig.transition = 1; <del> try { <del> setPending(false); <del> callback(); <del> } finally { <del> setCurrentUpdateLanePriority(previousLanePriority); <del> ReactCurrentBatchConfig.transition = prevTransition; <del> } <del> }, <del> ); <add> const prevTransition = ReactCurrentBatchConfig.transition; <add> ReactCurrentBatchConfig.transition = 1; <add> try { <add> setPending(false); <add> callback(); <add> } finally { <add> setCurrentUpdateLanePriority(previousLanePriority); <add> ReactCurrentBatchConfig.transition = prevTransition; <add> } <ide> } <ide> <ide> function mountTransition(): [(() => void) => void, boolean] { <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> scheduleCallback, <ide> cancelCallback, <ide> getCurrentPriorityLevel, <del> runWithPriority, <ide> shouldYield, <ide> requestPaint, <ide> now, <ide> export function deferredUpdates<A>(fn: () => A): A { <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(DefaultLanePriority); <del> return runWithPriority(NormalSchedulerPriority, fn); <add> return fn(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> } <ide> export function batchedEventUpdates<A, R>(fn: A => R, a: A): R { <ide> } <ide> <ide> export function discreteUpdates<A, B, C, D, R>( <del> fn: (A, B, C) => R, <add> fn: (A, B, C, D) => R, <ide> a: A, <ide> b: B, <ide> c: C, <ide> export function discreteUpdates<A, B, C, D, R>( <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(InputDiscreteLanePriority); <del> return runWithPriority( <del> UserBlockingSchedulerPriority, <del> fn.bind(null, a, b, c, d), <del> ); <add> return fn(a, b, c, d); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> executionContext = prevExecutionContext; <ide> export function flushSync<A, R>(fn: A => R, a: A): R { <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <ide> if (fn) { <del> return runWithPriority(ImmediateSchedulerPriority, fn.bind(null, a)); <add> return fn(a); <ide> } else { <ide> return (undefined: $FlowFixMe); <ide> } <ide> export function flushControlled(fn: () => mixed): void { <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority(ImmediateSchedulerPriority, fn); <add> fn(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> <ide> function commitRoot(root) { <ide> const previousUpdateLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority( <del> ImmediateSchedulerPriority, <del> commitRootImpl.bind(null, root, previousUpdateLanePriority), <del> ); <add> commitRootImpl(root, previousUpdateLanePriority); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousUpdateLanePriority); <ide> } <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js <ide> import { <ide> scheduleCallback, <ide> cancelCallback, <ide> getCurrentPriorityLevel, <del> runWithPriority, <ide> shouldYield, <ide> requestPaint, <ide> now, <ide> export function deferredUpdates<A>(fn: () => A): A { <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(DefaultLanePriority); <del> return runWithPriority(NormalSchedulerPriority, fn); <add> return fn(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> } <ide> export function batchedEventUpdates<A, R>(fn: A => R, a: A): R { <ide> } <ide> <ide> export function discreteUpdates<A, B, C, D, R>( <del> fn: (A, B, C) => R, <add> fn: (A, B, C, D) => R, <ide> a: A, <ide> b: B, <ide> c: C, <ide> export function discreteUpdates<A, B, C, D, R>( <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(InputDiscreteLanePriority); <del> return runWithPriority( <del> UserBlockingSchedulerPriority, <del> fn.bind(null, a, b, c, d), <del> ); <add> return fn(a, b, c, d); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> executionContext = prevExecutionContext; <ide> export function flushSync<A, R>(fn: A => R, a: A): R { <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <ide> if (fn) { <del> return runWithPriority(ImmediateSchedulerPriority, fn.bind(null, a)); <add> return fn(a); <ide> } else { <ide> return (undefined: $FlowFixMe); <ide> } <ide> export function flushControlled(fn: () => mixed): void { <ide> const previousLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority(ImmediateSchedulerPriority, fn); <add> fn(); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousLanePriority); <ide> <ide> function commitRoot(root) { <ide> const previousUpdateLanePriority = getCurrentUpdateLanePriority(); <ide> try { <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority( <del> ImmediateSchedulerPriority, <del> commitRootImpl.bind(null, root, previousUpdateLanePriority), <del> ); <add> commitRootImpl(root, previousUpdateLanePriority); <ide> } finally { <ide> setCurrentUpdateLanePriority(previousUpdateLanePriority); <ide> } <ide><path>packages/react-reconciler/src/SchedulerWithReactIntegration.new.js <ide> import { <ide> import {scheduleMicrotask, supportsMicrotasks} from './ReactFiberHostConfig'; <ide> <ide> const { <del> unstable_runWithPriority: Scheduler_runWithPriority, <ide> unstable_scheduleCallback: Scheduler_scheduleCallback, <ide> unstable_cancelCallback: Scheduler_cancelCallback, <ide> unstable_shouldYield: Scheduler_shouldYield, <ide> function reactPriorityToSchedulerPriority(reactPriorityLevel) { <ide> } <ide> } <ide> <del>export function runWithPriority<T>( <del> reactPriorityLevel: ReactPriorityLevel, <del> fn: () => T, <del>): T { <del> const priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); <del> return Scheduler_runWithPriority(priorityLevel, fn); <del>} <del> <ide> export function scheduleCallback( <ide> reactPriorityLevel: ReactPriorityLevel, <ide> callback: SchedulerCallback, <ide> function flushSyncCallbackQueueImpl() { <ide> const isSync = true; <ide> const queue = syncQueue; <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority(ImmediatePriority, () => { <del> for (; i < queue.length; i++) { <del> let callback = queue[i]; <del> do { <del> callback = callback(isSync); <del> } while (callback !== null); <del> } <del> }); <add> for (; i < queue.length; i++) { <add> let callback = queue[i]; <add> do { <add> callback = callback(isSync); <add> } while (callback !== null); <add> } <ide> syncQueue = null; <ide> } catch (error) { <ide> // If something throws, leave the remaining callbacks on the queue. <ide><path>packages/react-reconciler/src/SchedulerWithReactIntegration.old.js <ide> import { <ide> import {scheduleMicrotask, supportsMicrotasks} from './ReactFiberHostConfig'; <ide> <ide> const { <del> unstable_runWithPriority: Scheduler_runWithPriority, <ide> unstable_scheduleCallback: Scheduler_scheduleCallback, <ide> unstable_cancelCallback: Scheduler_cancelCallback, <ide> unstable_shouldYield: Scheduler_shouldYield, <ide> function reactPriorityToSchedulerPriority(reactPriorityLevel) { <ide> } <ide> } <ide> <del>export function runWithPriority<T>( <del> reactPriorityLevel: ReactPriorityLevel, <del> fn: () => T, <del>): T { <del> const priorityLevel = reactPriorityToSchedulerPriority(reactPriorityLevel); <del> return Scheduler_runWithPriority(priorityLevel, fn); <del>} <del> <ide> export function scheduleCallback( <ide> reactPriorityLevel: ReactPriorityLevel, <ide> callback: SchedulerCallback, <ide> function flushSyncCallbackQueueImpl() { <ide> const isSync = true; <ide> const queue = syncQueue; <ide> setCurrentUpdateLanePriority(SyncLanePriority); <del> runWithPriority(ImmediatePriority, () => { <del> for (; i < queue.length; i++) { <del> let callback = queue[i]; <del> do { <del> callback = callback(isSync); <del> } while (callback !== null); <del> } <del> }); <add> for (; i < queue.length; i++) { <add> let callback = queue[i]; <add> do { <add> callback = callback(isSync); <add> } while (callback !== null); <add> } <ide> syncQueue = null; <ide> } catch (error) { <ide> // If something throws, leave the remaining callbacks on the queue. <ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.js <ide> describe('ReactSchedulerIntegration', () => { <ide> ); <ide> } <ide> <del> it('flush sync has correct priority', () => { <del> function ReadPriority() { <del> Scheduler.unstable_yieldValue( <del> 'Priority: ' + getCurrentPriorityAsString(), <del> ); <del> return null; <del> } <del> ReactNoop.flushSync(() => ReactNoop.render(<ReadPriority />)); <del> expect(Scheduler).toHaveYielded(['Priority: Immediate']); <del> }); <del> <ide> // TODO: Figure out what to do with these tests. I don't think most of them <ide> // make sense once we decouple Scheduler from React. Perhaps need similar <ide> // tests for React DOM. <ide> describe('ReactSchedulerIntegration', () => { <ide> ]); <ide> }); <ide> <del> it('layout effects have immediate priority', () => { <del> const {useLayoutEffect} = React; <del> function ReadPriority() { <del> Scheduler.unstable_yieldValue( <del> 'Render priority: ' + getCurrentPriorityAsString(), <del> ); <del> useLayoutEffect(() => { <del> Scheduler.unstable_yieldValue( <del> 'Layout priority: ' + getCurrentPriorityAsString(), <del> ); <del> }); <del> return null; <del> } <del> <del> ReactNoop.render(<ReadPriority />); <del> expect(Scheduler).toFlushAndYield([ <del> 'Render priority: Normal', <del> 'Layout priority: Immediate', <del> ]); <del> }); <del> <ide> it('passive effects are called before Normal-pri scheduled in layout effects', async () => { <ide> const {useEffect, useLayoutEffect} = React; <ide> function Effects({step}) {
8
Javascript
Javascript
upgrade contextdependencytemplateasid to es6
b972260ac0fe9db80d1ce80845f59c673601249d
<ide><path>lib/dependencies/ContextDependencyTemplateAsId.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>function ContextDependencyTemplateAsId() {} <del>module.exports = ContextDependencyTemplateAsId; <add>"use strict"; <add> <add>class ContextDependencyTemplateAsId { <ide> <del>ContextDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptions, requestShortener) { <del> var comment = ""; <del> if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; <del> if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { <del> if(dep.valueRange) { <del> if(Array.isArray(dep.replaces)) { <del> for(var i = 0; i < dep.replaces.length; i++) { <del> var rep = dep.replaces[i]; <del> source.replace(rep.range[0], rep.range[1] - 1, rep.value) <add> apply(dep, source, outputOptions, requestShortener) { <add> let comment = ""; <add> if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; <add> if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { <add> if(dep.valueRange) { <add> if(Array.isArray(dep.replaces)) { <add> for(let i = 0; i < dep.replaces.length; i++) { <add> const rep = dep.replaces[i]; <add> source.replace(rep.range[0], rep.range[1] - 1, rep.value) <add> } <ide> } <add> source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); <add> source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); <add> } else { <add> source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve"); <ide> } <del> source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); <del> source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); <ide> } else { <del> source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve"); <add> const content = require("./WebpackMissingModule").module(dep.request); <add> source.replace(dep.range[0], dep.range[1] - 1, content); <ide> } <del> } else { <del> var content = require("./WebpackMissingModule").module(dep.request); <del> source.replace(dep.range[0], dep.range[1] - 1, content); <ide> } <del>}; <add>} <add>module.exports = ContextDependencyTemplateAsId;
1
PHP
PHP
fix multi connection/part downloading file
ab96ed56f34b5b88c5b50f17956154bec7507a96
<ide><path>lib/Cake/Network/CakeResponse.php <ide> protected function _sendFile($file, $range) { <ide> <ide> $bufferSize = 8192; <ide> set_time_limit(0); <add> session_write_close(); <ide> while (!feof($file->handle)) { <ide> if (!$this->_isActive()) { <ide> $file->close();
1
Javascript
Javascript
fix a typo
6f735eeb0568637c7f33388bfe00390d9cb41f75
<ide><path>server/render.js <ide> export async function renderScriptError (req, res, page, error, customFields, op <ide> res.setHeader('Content-Type', 'text/javascript') <ide> res.end(` <ide> window.__NEXT_REGISTER_PAGE('${page}', function() { <del> var error = new Error('Page not exists: ${page}') <add> var error = new Error('Page does not exist: ${page}') <ide> error.statusCode = 404 <ide> <ide> return { error: error }
1
Python
Python
fix mixed precision serialization of group convs
9e3627ae6a1e1be80bdac6799b36ae7c29f5ae41
<ide><path>keras/layers/convolutional/base_conv.py <ide> def call(self, inputs): <ide> inputs = tf.pad(inputs, self._compute_causal_padding(inputs)) <ide> <ide> if self.groups > 1: <del> outputs = self._jit_compiled_convolution_op(inputs, self.kernel) <add> outputs = self._jit_compiled_convolution_op( <add> inputs, tf.convert_to_tensor(self.kernel) <add> ) <ide> else: <ide> outputs = self.convolution_op(inputs, self.kernel) <ide>
1
Java
Java
use layout width for boringlayout in nodes
9498f22439fb1b822811822146749e490d780f3f
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTText.java <ide> protected void collectState( <ide> mDrawCommand = new DrawTextLayout(new BoringLayout( <ide> mText, <ide> PAINT, <del> Integer.MAX_VALUE, // fits one line so don't care about the width <add> (int) getLayoutWidth(), <ide> mAlignment, <ide> mSpacingMult, <ide> mSpacingAdd,
1
Javascript
Javascript
use map to track round robin workers
6654c5945263a3ced718b94a89c70fdc9b061500
<ide><path>lib/internal/cluster/round_robin_handle.js <ide> const assert = require('assert'); <ide> const net = require('net'); <ide> const { sendHelper } = require('internal/cluster/utils'); <del>const getOwnPropertyNames = Object.getOwnPropertyNames; <ide> const { internalBinding } = require('internal/bootstrap/loaders'); <ide> const uv = internalBinding('uv'); <ide> <ide> module.exports = RoundRobinHandle; <ide> <ide> function RoundRobinHandle(key, address, port, addressType, fd) { <ide> this.key = key; <del> this.all = {}; <add> this.all = new Map(); <ide> this.free = []; <ide> this.handles = []; <ide> this.handle = null; <ide> function RoundRobinHandle(key, address, port, addressType, fd) { <ide> } <ide> <ide> RoundRobinHandle.prototype.add = function(worker, send) { <del> assert(worker.id in this.all === false); <del> this.all[worker.id] = worker; <add> assert(this.all.has(worker.id) === false); <add> this.all.set(worker.id, worker); <ide> <ide> const done = () => { <ide> if (this.handle.getsockname) { <ide> RoundRobinHandle.prototype.add = function(worker, send) { <ide> }; <ide> <ide> RoundRobinHandle.prototype.remove = function(worker) { <del> if (worker.id in this.all === false) <add> const existed = this.all.delete(worker.id); <add> <add> if (!existed) <ide> return false; <ide> <del> delete this.all[worker.id]; <ide> const index = this.free.indexOf(worker); <ide> <ide> if (index !== -1) <ide> this.free.splice(index, 1); <ide> <del> if (getOwnPropertyNames(this.all).length !== 0) <add> if (this.all.size !== 0) <ide> return false; <ide> <ide> for (var handle; handle = this.handles.shift(); handle.close()) <ide> RoundRobinHandle.prototype.distribute = function(err, handle) { <ide> }; <ide> <ide> RoundRobinHandle.prototype.handoff = function(worker) { <del> if (worker.id in this.all === false) { <add> if (this.all.has(worker.id) === false) { <ide> return; // Worker is closing (or has closed) the server. <ide> } <ide>
1
Javascript
Javascript
give test-net-gh-5504 more time to run
22879e749e595a730f194615874ca9710a0f5bf1
<ide><path>test/simple/test-net-GH-5504.js <ide> function parent() { <ide> setTimeout(function() { <ide> throw new Error('hang'); <ide> }); <del> }, 1000).unref(); <add> }, 4000).unref(); <ide> <ide> var s = spawn(node, [__filename, 'server'], opt); <ide> var c;
1
Ruby
Ruby
use filename when printing pending migrations
6d55eb992b11c624bb20fd6fc3cd230b8e5673a5
<ide><path>activerecord/lib/active_record/migration.rb <ide> def detailed_migration_message(pending_migrations) <ide> message += "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}\n\n" <ide> <ide> pending_migrations.each do |pending_migration| <del> message += "#{pending_migration.basename}\n" <add> message += "#{pending_migration.filename}\n" <ide> end <ide> <ide> message
1
Python
Python
add tests mistakenly left out of r9397
ad4e1a7a72136b5a6364b60ccf8a3e3ae387814a
<ide><path>tests/regressiontests/forms/fields.py <ide> >>> f.clean('.002') == Decimal("0.002") <ide> True <ide> <add>>>> f = DecimalField(max_digits=2, decimal_places=2) <add>>>> f.clean('.01') == Decimal(".01") <add>True <add>>>> f.clean('1.1') <add>Traceback (most recent call last): <add>... <add>ValidationError: [u'Ensure that there are no more than 0 digits before the decimal point.'] <add> <add> <ide> # DateField ################################################################### <ide> <ide> >>> import datetime
1
Javascript
Javascript
improve test performance
65d9d062d9e79476655c23e7508067c204405580
<ide><path>test/TestCases.template.js <ide> const describeCases = config => { <ide> "utf-8" <ide> ); <ide> const jsonStats = stats.toJson({ <del> errorDetails: true <add> errorDetails: true, <add> modules: false, <add> assets: false, <add> chunks: false <ide> }); <ide> if ( <ide> checkArrayExpectation(
1
PHP
PHP
return a collection from lists()
f1e45c60628da3340afc77b2b425870db7fb60b9
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function lists($column, $key = null) <ide> <ide> $results = new Collection($this->get($columns)); <ide> <del> return $results->lists($columns[0], array_get($columns, 1)); <add> return $results->lists($columns[0], array_get($columns, 1))->all(); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Support/Collection.php <ide> public function implode($value, $glue = null) <ide> <ide> if (is_array($first) || is_object($first)) <ide> { <del> return implode($glue, $this->lists($value)); <add> return implode($glue, $this->lists($value)->all()); <ide> } <ide> <ide> return implode($value, $this->items); <ide> public function last() <ide> * <ide> * @param string $value <ide> * @param string $key <del> * @return array <add> * @return static <ide> */ <ide> public function lists($value, $key = null) <ide> { <del> return array_pluck($this->items, $value, $key); <add> return new static(array_pluck($this->items, $value, $key)); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentCollectionTest.php <ide> public function testCollectionReturnsUniqueItems() <ide> public function testLists() <ide> { <ide> $data = new Collection(array((object) array('name' => 'taylor', 'email' => 'foo'), (object) array('name' => 'dayle', 'email' => 'bar'))); <del> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')); <del> $this->assertEquals(array('foo', 'bar'), $data->lists('email')); <add> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')->all()); <add> $this->assertEquals(array('foo', 'bar'), $data->lists('email')->all()); <ide> } <ide> <ide> <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> public function testPushManyRelation() <ide> $this->assertEquals(1, $model->id); <ide> $this->assertTrue($model->exists); <ide> $this->assertEquals(2, count($model->relationMany)); <del> $this->assertEquals([2, 3], $model->relationMany->lists('id')); <add> $this->assertEquals([2, 3], $model->relationMany->lists('id')->all()); <ide> } <ide> <ide> <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testChunk() <ide> public function testListsWithArrayAndObjectValues() <ide> { <ide> $data = new Collection(array((object) array('name' => 'taylor', 'email' => 'foo'), array('name' => 'dayle', 'email' => 'bar'))); <del> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')); <del> $this->assertEquals(array('foo', 'bar'), $data->lists('email')); <add> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')->all()); <add> $this->assertEquals(array('foo', 'bar'), $data->lists('email')->all()); <ide> } <ide> <ide> <ide> public function testListsWithArrayAccessValues() <ide> new TestArrayAccessImplementation(array('name' => 'dayle', 'email' => 'bar')) <ide> )); <ide> <del> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')); <del> $this->assertEquals(array('foo', 'bar'), $data->lists('email')); <add> $this->assertEquals(array('taylor' => 'foo', 'dayle' => 'bar'), $data->lists('email', 'name')->all()); <add> $this->assertEquals(array('foo', 'bar'), $data->lists('email')->all()); <ide> } <ide> <ide> <ide> public function testGetListValueWithAccessors() <ide> $modelTwo = new TestAccessorEloquentTestStub(array('some' => 'bar')); <ide> $data = new Collection(array($model, $modelTwo)); <ide> <del> $this->assertEquals(array('foo', 'bar'), $data->lists('some')); <add> $this->assertEquals(array('foo', 'bar'), $data->lists('some')->all()); <ide> } <ide> <ide> <ide> public function testValueRetrieverAcceptsDotNotation() <ide> )); <ide> <ide> $c = $c->sortBy('foo.bar'); <del> $this->assertEquals(array(2, 1), $c->lists('id')); <add> $this->assertEquals(array(2, 1), $c->lists('id')->all()); <ide> } <ide> <ide>
5
Ruby
Ruby
find all validators for multiple attributes
cf9324e5909e71ec0a2477338e696b6af2f17f13
<ide><path>activemodel/lib/active_model/validations.rb <ide> def validators <ide> end <ide> <ide> # List all validators that being used to validate a specific attribute. <del> def validators_on(attribute) <del> _validators[attribute.to_sym] <add> def validators_on(*attributes) <add> attributes.inject([]) do |all, attribute| <add> all |= _validators[attribute.to_sym] || [] <add> end <ide> end <ide> <ide> # Check if method is an attribute method or not. <ide><path>activemodel/test/cases/validations_test.rb <ide> def test_accessing_instance_of_validator_on_an_attribute <ide> assert_equal 10, Topic.validators_on(:title).first.options[:minimum] <ide> end <ide> <add> def test_list_of_validators_on_multiple_attributes <add> Topic.validates :title, :length => { :minimum => 10 } <add> Topic.validates :author_name, :presence => true, :format => /a/ <add> <add> validators = Topic.validators_on(:title, :author_name) <add> <add> assert_equal [ <add> ActiveModel::Validations::FormatValidator, <add> ActiveModel::Validations::LengthValidator, <add> ActiveModel::Validations::PresenceValidator <add> ], validators.map { |v| v.class }.sort_by { |c| c.to_s } <add> end <add> <add> def test_list_of_validators_will_be_empty_when_empty <add> Topic.validates :title, :length => { :minimum => 10 } <add> assert_equal [], Topic.validators_on(:author_name) <add> end <add> <ide> def test_validations_on_the_instance_level <ide> auto = Automobile.new <ide>
2
Go
Go
add network endpoint for crashtest
20c2a4f80f4171ffb59ea61bdcf57d8edc970fa8
<ide><path>contrib/crashTest.go <ide> package main <ide> <ide> import ( <add> "fmt" <ide> "io" <ide> "log" <add> "net" <ide> "os" <ide> "os/exec" <ide> "path" <ide> func crashTest() error { <ide> return err <ide> } <ide> <add> var endpoint string <add> if ep := os.Getenv("TEST_ENDPOINT"); ep == "" { <add> endpoint = "192.168.56.1:7979" <add> } else { <add> endpoint = ep <add> } <add> conn, _ := net.Dial("tcp", endpoint) <add> <add> restartCount := 0 <add> totalTestCount := 1 <ide> for { <ide> daemon, err := runDaemon() <ide> if err != nil { <ide> return err <ide> } <add> if conn != nil { <add> fmt.Fprintf(conn, "RESTART: %d\n", restartCount) <add> } <add> restartCount++ <ide> // time.Sleep(5000 * time.Millisecond) <ide> var stop bool <ide> go func() error { <ide> stop = false <ide> for i := 0; i < 100 && !stop; i++ { <ide> func() error { <add> if conn != nil { <add> fmt.Fprintf(conn, "TEST: %d\n", totalTestCount) <add> } <add> totalTestCount++ <ide> cmd := exec.Command(DOCKER_PATH, "run", "base", "echo", "hello", "world") <ide> log.Printf("%d", i) <ide> outPipe, err := cmd.StdoutPipe()
1
Ruby
Ruby
override existing bintray bottles
cfc8ac0190a21375c98d004d6e400c74413b3dc0
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def test_bot <ide> formula_packaged[formula_name] = true <ide> end <ide> <del> content_url = "https://api.bintray.com/content/homebrew/#{bintray_repo}/#{bintray_package}/#{version}/#{filename}" <del> content_url += "?publish=1&override=1" if existing_bottle <add> content_url = "https://api.bintray.com/content/homebrew" <add> content_url += "/#{bintray_repo}/#{bintray_package}/#{version}/#{filename}" <add> content_url += "?override=1" <add> content_url += "&publish=1" if existing_bottle <ide> curl "--silent", "--fail", "-u#{bintray_user}:#{bintray_key}", <ide> "-T", filename, content_url <ide> puts
1
Ruby
Ruby
push url audits down to resourceauditor
41ecce78982e9e1ca6ece946005dbd7a79c72e95
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_urls <ide> if homepage =~ %r[^http://((?:build|cloud|developer|download|extensions|git|glade|help|library|live|nagios|news|people|projects|rt|static|wiki|www)\.)?gnome\.org] <ide> problem "Gnome homepages should be https:// links (URL is #{homepage})." <ide> end <del> <del> urls = @specs.map(&:url) <del> <del> # Check GNU urls; doesn't apply to mirrors <del> urls.grep(%r[^(?:https?|ftp)://(?!alpha).+/gnu/]) do |u| <del> problem "\"http://ftpmirror.gnu.org\" is preferred for GNU software (url is #{u})." <del> end <del> <del> mirrors = @specs.map(&:mirrors).flatten <del> dupes = urls & mirrors <del> <del> dupes.each do |dupe| <del> problem "URL should not be duplicated as a mirror: #{dupe}" <del> end <del> <del> # the rest of the checks apply to mirrors as well. <del> urls += mirrors <del> <del> # Check a variety of SSL/TLS links that don't consistently auto-redirect <del> # or are overly common errors that need to be reduced & fixed over time. <del> urls.each do |p| <del> # Skip the main url link, as it can't be made SSL/TLS yet. <del> next if p =~ %r[/ftpmirror\.gnu\.org] <del> <del> case p <del> when %r[^http://ftp\.gnu\.org/] <del> problem "ftp.gnu.org urls should be https://, not http:// (url is #{p})." <del> when %r[^http://[^/]*\.apache\.org/] <del> problem "Apache urls should be https://, not http (url is #{p})." <del> when %r[^http://code\.google\.com/] <del> problem "code.google.com urls should be https://, not http (url is #{p})." <del> when %r[^http://fossies\.org/] <del> problem "Fossies urls should be https://, not http (url is #{p})." <del> when %r[^http://mirrors\.kernel\.org/] <del> problem "mirrors.kernel urls should be https://, not http (url is #{p})." <del> when %r[^http://([^/]*\.|)bintray\.com/] <del> problem "Bintray urls should be https://, not http (url is #{p})." <del> when %r[^http://tools\.ietf\.org/] <del> problem "ietf urls should be https://, not http (url is #{p})." <del> end <del> end <del> <del> # Check SourceForge urls <del> urls.each do |p| <del> # Skip if the URL looks like a SVN repo <del> next if p =~ %r[/svnroot/] <del> next if p =~ %r[svn\.sourceforge] <del> <del> # Is it a sourceforge http(s) URL? <del> next unless p =~ %r[^https?://.*\b(sourceforge|sf)\.(com|net)] <del> <del> if p =~ /(\?|&)use_mirror=/ <del> problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})." <del> end <del> <del> if p =~ /\/download$/ <del> problem "Don't use /download in SourceForge urls (url is #{p})." <del> end <del> <del> if p =~ %r[^https?://sourceforge\.] <del> problem "Use http://downloads.sourceforge.net to get geolocation (url is #{p})." <del> end <del> <del> if p =~ %r[^https?://prdownloads\.] <del> problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" + <del> "\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/" <del> end <del> <del> if p =~ %r[^http://\w+\.dl\.] <del> problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})." <del> end <del> <del> if p.start_with? "http://downloads" <del> problem "Use https:// URLs for downloads from SourceForge (url is #{p})." <del> end <del> end <del> <del> # Check for Google Code download urls, https:// is preferred <del> # Intentionally not extending this to SVN repositories due to certificate <del> # issues. <del> urls.grep(%r[^http://.*\.googlecode\.com/files.*]) do |u| <del> problem "Use https:// URLs for downloads from Google Code (url is #{u})." <del> end <del> <del> # Check for new-url Google Code download urls, https:// is preferred <del> urls.grep(%r[^http://code\.google\.com/]) do |u| <del> problem "Use https:// URLs for downloads from code.google (url is #{u})." <del> end <del> <del> # Check for git:// GitHub repo urls, https:// is preferred. <del> urls.grep(%r[^git://[^/]*github\.com/]) do |u| <del> problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." <del> end <del> <del> # Check for git:// Gitorious repo urls, https:// is preferred. <del> urls.grep(%r[^git://[^/]*gitorious\.org/]) do |u| <del> problem "Use https:// URLs for accessing Gitorious repositories (url is #{u})." <del> end <del> <del> # Check for http:// GitHub repo urls, https:// is preferred. <del> urls.grep(%r[^http://github\.com/.*\.git$]) do |u| <del> problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." <del> end <del> <del> # Use new-style archive downloads <del> urls.select { |u| u =~ %r[https://.*github.*/(?:tar|zip)ball/] && u !~ %r[\.git$] }.each do |u| <del> problem "Use /archive/ URLs for GitHub tarballs (url is #{u})." <del> end <del> <del> # Don't use GitHub .zip files <del> urls.select { |u| u =~ %r[https://.*github.*/(archive|releases)/.*\.zip$] && u !~ %r[releases/download] }.each do |u| <del> problem "Use GitHub tarballs rather than zipballs (url is #{u})." <del> end <ide> end <ide> <ide> def audit_specs <ide> def devel_only?(formula) <ide> <ide> class ResourceAuditor <ide> attr_reader :problems <del> attr_reader :version, :checksum, :using, :specs, :url, :name <add> attr_reader :version, :checksum, :using, :specs, :url, :mirrors, :name <ide> <ide> def initialize(resource) <ide> @name = resource.name <ide> @version = resource.version <ide> @checksum = resource.checksum <ide> @url = resource.url <add> @mirrors = resource.mirrors <ide> @using = resource.using <ide> @specs = resource.specs <ide> @problems = [] <ide> def audit <ide> audit_version <ide> audit_checksum <ide> audit_download_strategy <add> audit_urls <ide> self <ide> end <ide> <ide> def audit_download_strategy <ide> end <ide> end <ide> <add> def audit_urls <add> # Check GNU urls; doesn't apply to mirrors <add> if url =~ %r[^(?:https?|ftp)://(?!alpha).+/gnu/] <add> problem "\"http://ftpmirror.gnu.org\" is preferred for GNU software (url is #{url})." <add> end <add> <add> if mirrors.include?(url) <add> problem "URL should not be duplicated as a mirror: #{url}" <add> end <add> <add> urls = [url] + mirrors <add> <add> # Check a variety of SSL/TLS links that don't consistently auto-redirect <add> # or are overly common errors that need to be reduced & fixed over time. <add> urls.each do |p| <add> # Skip the main url link, as it can't be made SSL/TLS yet. <add> next if p =~ %r[/ftpmirror\.gnu\.org] <add> <add> case p <add> when %r[^http://ftp\.gnu\.org/] <add> problem "ftp.gnu.org urls should be https://, not http:// (url is #{p})." <add> when %r[^http://[^/]*\.apache\.org/] <add> problem "Apache urls should be https://, not http (url is #{p})." <add> when %r[^http://code\.google\.com/] <add> problem "code.google.com urls should be https://, not http (url is #{p})." <add> when %r[^http://fossies\.org/] <add> problem "Fossies urls should be https://, not http (url is #{p})." <add> when %r[^http://mirrors\.kernel\.org/] <add> problem "mirrors.kernel urls should be https://, not http (url is #{p})." <add> when %r[^http://([^/]*\.|)bintray\.com/] <add> problem "Bintray urls should be https://, not http (url is #{p})." <add> when %r[^http://tools\.ietf\.org/] <add> problem "ietf urls should be https://, not http (url is #{p})." <add> end <add> end <add> <add> # Check SourceForge urls <add> urls.each do |p| <add> # Skip if the URL looks like a SVN repo <add> next if p =~ %r[/svnroot/] <add> next if p =~ %r[svn\.sourceforge] <add> <add> # Is it a sourceforge http(s) URL? <add> next unless p =~ %r[^https?://.*\b(sourceforge|sf)\.(com|net)] <add> <add> if p =~ /(\?|&)use_mirror=/ <add> problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})." <add> end <add> <add> if p =~ /\/download$/ <add> problem "Don't use /download in SourceForge urls (url is #{p})." <add> end <add> <add> if p =~ %r[^https?://sourceforge\.] <add> problem "Use http://downloads.sourceforge.net to get geolocation (url is #{p})." <add> end <add> <add> if p =~ %r[^https?://prdownloads\.] <add> problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" + <add> "\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/" <add> end <add> <add> if p =~ %r[^http://\w+\.dl\.] <add> problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})." <add> end <add> <add> if p.start_with? "http://downloads" <add> problem "Use https:// URLs for downloads from SourceForge (url is #{p})." <add> end <add> end <add> <add> # Check for Google Code download urls, https:// is preferred <add> # Intentionally not extending this to SVN repositories due to certificate <add> # issues. <add> urls.grep(%r[^http://.*\.googlecode\.com/files.*]) do |u| <add> problem "Use https:// URLs for downloads from Google Code (url is #{u})." <add> end <add> <add> # Check for new-url Google Code download urls, https:// is preferred <add> urls.grep(%r[^http://code\.google\.com/]) do |u| <add> problem "Use https:// URLs for downloads from code.google (url is #{u})." <add> end <add> <add> # Check for git:// GitHub repo urls, https:// is preferred. <add> urls.grep(%r[^git://[^/]*github\.com/]) do |u| <add> problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." <add> end <add> <add> # Check for git:// Gitorious repo urls, https:// is preferred. <add> urls.grep(%r[^git://[^/]*gitorious\.org/]) do |u| <add> problem "Use https:// URLs for accessing Gitorious repositories (url is #{u})." <add> end <add> <add> # Check for http:// GitHub repo urls, https:// is preferred. <add> urls.grep(%r[^http://github\.com/.*\.git$]) do |u| <add> problem "Use https:// URLs for accessing GitHub repositories (url is #{u})." <add> end <add> <add> # Use new-style archive downloads <add> urls.select { |u| u =~ %r[https://.*github.*/(?:tar|zip)ball/] && u !~ %r[\.git$] }.each do |u| <add> problem "Use /archive/ URLs for GitHub tarballs (url is #{u})." <add> end <add> <add> # Don't use GitHub .zip files <add> urls.select { |u| u =~ %r[https://.*github.*/(archive|releases)/.*\.zip$] && u !~ %r[releases/download] }.each do |u| <add> problem "Use GitHub tarballs rather than zipballs (url is #{u})." <add> end <add> end <add> <add> <ide> def problem text <ide> @problems << text <ide> end
1
Javascript
Javascript
fix azure pipelines
fd3256f47e402c8f283a287ecce94593e329cb91
<ide><path>test/integration/api-support/pages/api/child-process.js <ide> import { execSync } from 'child_process' <ide> <ide> export default (req, res) => { <del> const output = execSync('echo "hi"') <add> const output = execSync('echo hi') <ide> .toString() <ide> .trim() <ide> res.end(output)
1
Javascript
Javascript
remove extra serialization
aa38be0f4202fddf7bd55681b2a92ef321863b71
<ide><path>lib/dependencies/AMDRequireItemDependency.js <ide> class AMDRequireItemDependency extends ModuleDependency { <ide> get type() { <ide> return "amd require"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> <del> write(this.range); <del> <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> <del> this.range = read(); <del> <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ContextElementDependency.js <ide> class ContextElementDependency extends ModuleDependency { <ide> get type() { <ide> return "context element"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> <del> write(this.userRequest); <del> <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> <del> this.userRequest = read(); <del> <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ImportEagerDependency.js <ide> class ImportEagerDependency extends ModuleDependency { <ide> get type() { <ide> return "import() eager"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> <del> write(this.range); <del> <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> <del> this.range = read(); <del> <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ImportWeakDependency.js <ide> class ImportWeakDependency extends ModuleDependency { <ide> get type() { <ide> return "import() weak"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> write(this.range); <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> this.range = read(); <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ModuleHotAcceptDependency.js <ide> class ModuleHotAcceptDependency extends ModuleDependency { <ide> get type() { <ide> return "module.hot.accept"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> write(this.range); <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> this.range = read(); <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ModuleHotDeclineDependency.js <ide> class ModuleHotDeclineDependency extends ModuleDependency { <ide> get type() { <ide> return "module.hot.decline"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> write(this.range); <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> this.range = read(); <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/ProvidedDependency.js <ide> class ProvidedDependency extends ModuleDependency { <ide> const { write } = context; <ide> write(this.identifier); <ide> write(this.path); <del> write(this.range); <ide> super.serialize(context); <ide> } <ide> <ide> deserialize(context) { <ide> const { read } = context; <ide> this.identifier = read(); <ide> this.path = read(); <del> this.range = read(); <ide> super.deserialize(context); <ide> } <ide> } <ide><path>lib/dependencies/RequireIncludeDependency.js <ide> class RequireIncludeDependency extends ModuleDependency { <ide> get type() { <ide> return "require.include"; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> <del> write(this.range); <del> <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> <del> this.range = read(); <del> <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable( <ide><path>lib/dependencies/RequireResolveDependency.js <ide> class RequireResolveDependency extends ModuleDependency { <ide> // This doesn't use any export <ide> return Dependency.NO_EXPORTS_REFERENCED; <ide> } <del> <del> serialize(context) { <del> const { write } = context; <del> <del> write(this.range); <del> <del> super.serialize(context); <del> } <del> <del> deserialize(context) { <del> const { read } = context; <del> <del> this.range = read(); <del> <del> super.deserialize(context); <del> } <ide> } <ide> <ide> makeSerializable(
9
Ruby
Ruby
pass options to `driven_by`
ec99107a2982236c726699cbbefc8839de278b93
<ide><path>actionpack/lib/action_dispatch/system_test_case.rb <ide> def self.start_application # :nodoc: <ide> # driven_by :selenium, using: :firefox <ide> # <ide> # driven_by :selenium, screen_size: [800, 800] <del> def self.driven_by(driver, using: :chrome, screen_size: [1400, 1400]) <del> @driver = SystemTesting::Driver.new(driver, using: using, screen_size: screen_size) <add> def self.driven_by(driver, using: :chrome, screen_size: [1400, 1400], options: {}) <add> @driver = SystemTesting::Driver.new(driver, using: using, screen_size: screen_size, options: options) <ide> end <ide> <ide> # Returns the driver object for the initialized system test <ide><path>actionpack/lib/action_dispatch/system_testing/driver.rb <ide> def initialize(name, **options) <ide> @name = name <ide> @browser = options[:using] <ide> @screen_size = options[:screen_size] <add> @options = options[:options] <ide> end <ide> <ide> def use <ide> def selenium? <ide> <ide> def register <ide> Capybara.register_driver @name do |app| <del> Capybara::Selenium::Driver.new(app, browser: @browser).tap do |driver| <add> Capybara::Selenium::Driver.new(app, { browser: @browser }.merge(@options)).tap do |driver| <ide> driver.browser.manage.window.size = Selenium::WebDriver::Dimension.new(*@screen_size) <ide> end <ide> end <ide><path>actionpack/test/dispatch/system_testing/driver_test.rb <ide> class DriverTest < ActiveSupport::TestCase <ide> end <ide> <ide> test "initializing the driver with a browser" do <del> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :chrome, screen_size: [1400, 1400]) <add> driver = ActionDispatch::SystemTesting::Driver.new(:selenium, using: :chrome, screen_size: [1400, 1400], options: { url: "http://example.com/wd/hub" }) <ide> assert_equal :selenium, driver.instance_variable_get(:@name) <ide> assert_equal :chrome, driver.instance_variable_get(:@browser) <ide> assert_equal [1400, 1400], driver.instance_variable_get(:@screen_size) <add> assert_equal ({ url: "http://example.com/wd/hub" }), driver.instance_variable_get(:@options) <ide> end <ide> <ide> test "selenium? returns false if driver is poltergeist" do
3
Javascript
Javascript
remove angular.noconflict feature
9faabd1ba0b1929785bcf166dc0ff60008e7c442
<ide><path>src/Angular.js <ide> var /** holds major version number for IE or NaN for real browsers */ <ide> nodeName_, <ide> uid = ['0', '0', '0']; <ide> <del>/** <del> * @ngdoc function <del> * @name angular.noConflict <del> * @function <del> * <del> * @description <del> * Restores the previous global value of angular and returns the current instance. Other libraries may already use the <del> * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to <del> * restore the previous namespace and keep a reference to angular. <del> * <del> * @return {Object} The current angular namespace <del> */ <del>function noConflict() { <del> var a = window.angular; <del> window.angular = _angular; <del> return a; <del>} <del> <ide> /** <ide> * @private <ide> * @param {*} obj <ide><path>src/AngularPublic.js <ide> function publishExternalAPI(angular){ <ide> 'isDate': isDate, <ide> 'lowercase': lowercase, <ide> 'uppercase': uppercase, <del> 'callbacks': {counter: 0}, <del> 'noConflict': noConflict <add> 'callbacks': {counter: 0} <ide> }); <ide> <ide> angularModule = setupModuleLoader(window); <ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> })); <ide> }); <ide> <del> describe('noConflict', function() { <del> var globalAngular; <del> beforeEach(function() { <del> globalAngular = angular; <del> }); <del> <del> afterEach(function() { <del> angular = globalAngular; <del> }); <del> <del> it('should return angular', function() { <del> var a = angular.noConflict(); <del> expect(a).toBe(globalAngular); <del> }); <del> <del> it('should restore original angular', function() { <del> var a = angular.noConflict(); <del> expect(angular).toBeUndefined(); <del> }); <del> <del> }); <del> <ide> });
3
Go
Go
add explicit status response to options handler
ac599d652846f6456366b8028b2c38da0565d8b1
<ide><path>api.go <ide> func createRouter(srv *Server, logging bool) (*mux.Router, error) { <ide> if srv.enableCors { <ide> writeCorsHeaders(w, r) <ide> } <add> w.WriteHeader(http.StatusOK) <ide> }) <ide> return r, nil <ide> } <ide><path>api_test.go <ide> func TestOptionsRoute(t *testing.T) { <ide> } <ide> <ide> router.ServeHTTP(r, req) <del> if r.Code != 200 { <add> if r.Code != http.StatusOK { <ide> t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code) <ide> } <ide> } <ide> func TestGetEnabledCors(t *testing.T) { <ide> } <ide> <ide> router.ServeHTTP(r, req) <del> if r.Code != 200 { <add> if r.Code != http.StatusOK { <ide> t.Errorf("Expected response for OPTIONS request to be \"200\", %v found.", r.Code) <ide> } <ide>
2
Python
Python
add util function to add vectors to vocab
dc2bb1259f3c31e1744f715e09e3449b61f03c5d
<ide><path>spacy/tests/util.py <ide> def apply_transition_sequence(parser, doc, sequence): <ide> stepwise.transition(transition) <ide> <ide> <add>def add_vecs_to_vocab(vocab, vectors): <add> """Add list of vector tuples to given vocab. All vectors need to have the <add> same length. Format: [("text", [1, 2, 3])]""" <add> length = len(vectors[0][1]) <add> vocab.resize_vectors(length) <add> for word, vec in vectors: <add> vocab[word].vector = vec <add> return vocab <add> <add> <ide> def get_cosine(vec1, vec2): <ide> """Get cosine for two given vectors""" <ide> return numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2))
1
Python
Python
mark a non-implemented test as a knownfailure
bc96ed3ed9229957631be5560389e6896c9dc6b3
<ide><path>numpy/core/tests/test_multiarray.py <ide> def test_simple_strict_within(self): <ide> <ide> if sys.version_info >= (2, 6): <ide> class TestNewBufferProtocol(object): <add> @dec.knownfailureif(True, "No tests for the new buffer interface yet.") <ide> def test_there_are_no_tests_yet_so_fail(self): <ide> raise AssertionError("Need tests for the new buffer interface! " <ide> "For arrays and scalars.")
1
Mixed
Javascript
add getcolordepth function
bb9cedb0f07c4f74cada172845f2aea197efa456
<ide><path>doc/api/assert.md <ide> AssertionError [ERR_ASSERTION]: Input A expected to deepStrictEqual input B: <ide> ] <ide> ``` <ide> <add>To deactivate the colors, use the `NODE_DISABLE_COLORS` environment variable. <add>Please note that this will also deactivate the colors in the REPL. <add> <ide> ## Legacy mode <ide> <ide> > Stability: 0 - Deprecated: Use strict mode instead. <ide><path>doc/api/tty.md <ide> added: v0.7.7 <ide> A `number` specifying the number of rows the TTY currently has. This property <ide> is updated whenever the `'resize'` event is emitted. <ide> <add>### writeStream.getColorDepth([env]) <add><!-- YAML <add>added: REPLACEME <add>--> <add> <add>* `env` {object} A object containing the environment variables to check. <add> Defaults to `process.env`. <add>* Returns: {number} <add> <add>Returns: <add>* 1 for 2, <add>* 4 for 16, <add>* 8 for 256, <add>* 24 for 16,777,216 <add>colors supported. <add> <add>Use this to determine what colors the terminal supports. Due to the nature of <add>colors in terminals it is possible to either have false positives or false <add>negatives. It depends on process information and the environment variables that <add>may lie about what terminal is used. <add>To enforce a specific behavior without relying on `process.env` it is possible <add>to pass in an object with different settings. <add> <add>Use the `NODE_DISABLE_COLORS` environment variable to enforce this function to <add>always return 1. <add> <ide> ## tty.isatty(fd) <ide> <!-- YAML <ide> added: v0.5.8 <ide><path>lib/internal/errors.js <ide> const kCode = Symbol('code'); <ide> const kInfo = Symbol('info'); <ide> const messages = new Map(); <ide> <add>var green = ''; <add>var red = ''; <add>var white = ''; <add> <ide> const { errmap } = process.binding('uv'); <ide> const { kMaxLength } = process.binding('buffer'); <ide> const { defineProperty } = Object; <ide> function createErrDiff(actual, expected, operator) { <ide> const expectedLines = util <ide> .inspect(expected, { compact: false }).split('\n'); <ide> const msg = `Input A expected to ${operator} input B:\n` + <del> '\u001b[32m+ expected\u001b[39m \u001b[31m- actual\u001b[39m'; <add> `${green}+ expected${white} ${red}- actual${white}`; <ide> const skippedMsg = ' ... Lines skipped'; <ide> <ide> // Remove all ending lines that match (this optimizes the output for <ide> function createErrDiff(actual, expected, operator) { <ide> printedLines++; <ide> } <ide> lastPos = i; <del> other += `\n\u001b[32m+\u001b[39m ${expectedLines[i]}`; <add> other += `\n${green}+${white} ${expectedLines[i]}`; <ide> printedLines++; <ide> // Only extra actual lines exist <ide> } else if (expectedLines.length < i + 1) { <ide> function createErrDiff(actual, expected, operator) { <ide> printedLines++; <ide> } <ide> lastPos = i; <del> res += `\n\u001b[31m-\u001b[39m ${actualLines[i]}`; <add> res += `\n${red}-${white} ${actualLines[i]}`; <ide> printedLines++; <ide> // Lines diverge <ide> } else if (actualLines[i] !== expectedLines[i]) { <ide> function createErrDiff(actual, expected, operator) { <ide> printedLines++; <ide> } <ide> lastPos = i; <del> res += `\n\u001b[31m-\u001b[39m ${actualLines[i]}`; <del> other += `\n\u001b[32m+\u001b[39m ${expectedLines[i]}`; <add> res += `\n${red}-${white} ${actualLines[i]}`; <add> other += `\n${green}+${white} ${expectedLines[i]}`; <ide> printedLines += 2; <ide> // Lines are identical <ide> } else { <ide> class AssertionError extends Error { <ide> if (message != null) { <ide> super(message); <ide> } else { <del> if (util === null) util = require('util'); <add> if (util === null) { <add> util = require('util'); <add> if (process.stdout.isTTY && process.stdout.getColorDepth() !== 1) { <add> green = '\u001b[32m'; <add> white = '\u001b[39m'; <add> red = '\u001b[31m'; <add> } <add> } <ide> <ide> if (actual && actual.stack && actual instanceof Error) <ide> actual = `${actual.name}: ${actual.message}`; <ide><path>lib/tty.js <ide> const { inherits } = util; <ide> const errnoException = util._errnoException; <ide> const errors = require('internal/errors'); <ide> const readline = require('readline'); <add>const { release } = require('os'); <add> <add>const OSRelease = release().split('.'); <add> <add>const COLORS_2 = 1; <add>const COLORS_16 = 4; <add>const COLORS_256 = 8; <add>const COLORS_16m = 24; <ide> <ide> function isatty(fd) { <ide> return Number.isInteger(fd) && fd >= 0 && isTTY(fd); <ide> inherits(WriteStream, net.Socket); <ide> <ide> WriteStream.prototype.isTTY = true; <ide> <add>WriteStream.prototype.getColorDepth = function(env = process.env) { <add> if (env.NODE_DISABLE_COLORS || env.TERM === 'dumb' && !env.COLORTERM) { <add> return COLORS_2; <add> } <add> <add> if (process.platform === 'win32') { <add> // Windows 10 build 10586 is the first Windows release that supports 256 <add> // colors. Windows 10 build 14931 is the first release that supports <add> // 16m/TrueColor. <add> if (+OSRelease[0] >= 10) { <add> const build = +OSRelease[2]; <add> if (build >= 14931) <add> return COLORS_16m; <add> if (build >= 10586) <add> return COLORS_256; <add> } <add> <add> return COLORS_16; <add> } <add> <add> if (env.TMUX) { <add> return COLORS_256; <add> } <add> <add> if (env.CI) { <add> if ('TRAVIS' in env || 'CIRCLECI' in env || 'APPVEYOR' in env || <add> 'GITLAB_CI' in env || env.CI_NAME === 'codeship') { <add> return COLORS_256; <add> } <add> return COLORS_2; <add> } <add> <add> if ('TEAMCITY_VERSION' in env) { <add> return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? <add> COLORS_16 : COLORS_2; <add> } <add> <add> switch (env.TERM_PROGRAM) { <add> case 'iTerm.app': <add> if (!env.TERM_PROGRAM_VERSION || <add> /^[0-2]\./.test(env.TERM_PROGRAM_VERSION)) { <add> return COLORS_256; <add> } <add> return COLORS_16m; <add> case 'HyperTerm': <add> case 'Hyper': <add> case 'MacTerm': <add> return COLORS_16m; <add> case 'Apple_Terminal': <add> return COLORS_256; <add> } <add> <add> if (env.TERM) { <add> if (/^xterm-256/.test(env.TERM)) <add> return COLORS_256; <add> if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(env.TERM)) <add> return COLORS_16; <add> } <add> <add> if (env.COLORTERM) <add> return COLORS_16; <add> <add> return COLORS_2; <add>}; <ide> <ide> WriteStream.prototype._refreshSize = function() { <ide> var oldCols = this.columns; <ide><path>test/parallel/test-assert.js <ide> common.expectsError( <ide> Error.stackTraceLimit = tmpLimit; <ide> <ide> // Test error diffs <add> const colors = process.stdout.isTTY && process.stdout.getColorDepth() > 1; <ide> const start = 'Input A expected to deepStrictEqual input B:'; <del> const actExp = '\u001b[32m+ expected\u001b[39m \u001b[31m- actual\u001b[39m'; <del> const plus = '\u001b[32m+\u001b[39m'; <del> const minus = '\u001b[31m-\u001b[39m'; <add> const actExp = colors ? <add> '\u001b[32m+ expected\u001b[39m \u001b[31m- actual\u001b[39m' : <add> '+ expected - actual'; <add> const plus = colors ? '\u001b[32m+\u001b[39m' : '+'; <add> const minus = colors ? '\u001b[31m-\u001b[39m' : '-'; <ide> let message = [ <ide> start, <ide> `${actExp} ... Lines skipped`, <ide><path>test/parallel/test-tty-get-color-depth.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert').strict; <add>/* eslint-disable no-restricted-properties */ <add>const { openSync } = require('fs'); <add>const tty = require('tty'); <add> <add>const { WriteStream } = require('tty'); <add> <add>// Do our best to grab a tty fd. <add>function getTTYfd() { <add> const ttyFd = [0, 1, 2, 4, 5].find(tty.isatty); <add> if (ttyFd === undefined) { <add> try { <add> return openSync('/dev/tty'); <add> } catch (e) { <add> // There aren't any tty fd's available to use. <add> return -1; <add> } <add> } <add> return ttyFd; <add>} <add> <add>const fd = getTTYfd(); <add> <add>// Give up if we did not find a tty <add>if (fd === -1) <add> common.skip(); <add> <add>const writeStream = new WriteStream(fd); <add> <add>let depth = writeStream.getColorDepth(); <add> <add>assert.equal(typeof depth, 'number'); <add>assert(depth >= 1 && depth <= 24); <add> <add>// If the terminal does not support colors, skip the rest <add>if (depth === 1) <add> common.skip(); <add> <add>assert.notEqual(writeStream.getColorDepth({ TERM: 'dumb' }), depth); <add> <add>// Deactivate colors <add>const tmp = process.env.NODE_DISABLE_COLORS; <add>process.env.NODE_DISABLE_COLORS = 1; <add> <add>depth = writeStream.getColorDepth(); <add> <add>assert.equal(depth, 1); <add> <add>process.env.NODE_DISABLE_COLORS = tmp;
6
Javascript
Javascript
change buffer.from to new buffer
7d142780dea3649f4ad07905e6c5f809ea9df597
<ide><path>lib/SourceMapDevToolPlugin.js <ide> class SourceMapDevToolPlugin { <ide> } else { <ide> asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment <ide> .replace(/\[map\]/g, () => JSON.stringify(sourceMap)) <del> .replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(sourceMap)).toString("base64")}`) <add> .replace(/\[url\]/g, () => `data:application/json;charset=utf-8;base64,${new Buffer(JSON.stringify(sourceMap), "utf-8").toString("base64")}`) // eslint-disable-line <ide> ); <ide> } <ide> });
1
Python
Python
keep api backwards compatible
b807f3d52a68dbf657c6437f71ecbfcba0695972
<ide><path>rest_framework/generics.py <ide> class Meta: <ide> <ide> return serializer_class <ide> <del> def get_serializer(self, instance=None, data=None, files=None, partial=False): <add> def get_serializer(self, instance=None, data=None, <add> files=None, partial=False): <ide> """ <ide> Return the serializer instance that should be used for validating and <ide> deserializing input, and for serializing output. <ide> """ <ide> serializer_class = self.get_serializer_class() <ide> context = self.get_serializer_context() <del> return serializer_class(instance, data=data, files=files, partial=partial, context=context) <add> return serializer_class(instance, data=data, files=files, <add> partial=partial, context=context) <ide> <ide> <ide> class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView): <ide> class UpdateAPIView(mixins.UpdateModelMixin, <ide> Concrete view for updating a model instance. <ide> """ <ide> def put(self, request, *args, **kwargs): <del> return self.update(request, partial=False, *args, **kwargs) <add> return self.update(request, *args, **kwargs) <ide> <ide> def patch(self, request, *args, **kwargs): <del> return self.update(request, partial=True, *args, **kwargs) <add> kwargs['partial'] = True <add> return self.update(request, *args, **kwargs) <ide> <ide> <ide> class ListCreateAPIView(mixins.ListModelMixin, <ide> def get(self, request, *args, **kwargs): <ide> return self.retrieve(request, *args, **kwargs) <ide> <ide> def put(self, request, *args, **kwargs): <del> return self.update(request, partial=False, *args, **kwargs) <add> return self.update(request, *args, **kwargs) <ide> <ide> def delete(self, request, *args, **kwargs): <ide> return self.destroy(request, *args, **kwargs) <ide> <ide> def patch(self, request, *args, **kwargs): <del> return self.update(request, partial=True, *args, **kwargs) <add> kwargs['partial'] = True <add> return self.update(request, *args, **kwargs) <ide><path>rest_framework/mixins.py <ide> class CreateModelMixin(object): <ide> """ <ide> def create(self, request, *args, **kwargs): <ide> serializer = self.get_serializer(data=request.DATA, files=request.FILES) <add> <ide> if serializer.is_valid(): <ide> self.pre_save(serializer.object) <ide> self.object = serializer.save() <ide> headers = self.get_success_headers(serializer.data) <del> return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) <add> return Response(serializer.data, status=status.HTTP_201_CREATED, <add> headers=headers) <add> <ide> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <ide> <ide> def get_success_headers(self, data): <ide> class UpdateModelMixin(object): <ide> Update a model instance. <ide> Should be mixed in with `SingleObjectBaseView`. <ide> """ <del> def update(self, request, partial=False, *args, **kwargs): <add> def update(self, request, *args, **kwargs): <add> partial = kwargs.pop('partial', False) <ide> try: <ide> self.object = self.get_object() <del> created = False <add> success_status_code = status.HTTP_200_OK <ide> except Http404: <ide> self.object = None <del> created = True <add> success_status_code = status.HTTP_201_CREATED <ide> <del> serializer = self.get_serializer(self.object, data=request.DATA, files=request.FILES, partial=partial) <add> serializer = self.get_serializer(self.object, data=request.DATA, <add> files=request.FILES, partial=partial) <ide> <ide> if serializer.is_valid(): <ide> self.pre_save(serializer.object) <ide> self.object = serializer.save() <del> status_code = created and status.HTTP_201_CREATED or status.HTTP_200_OK <del> return Response(serializer.data, status=status_code) <add> return Response(serializer.data, status=success_status_code) <ide> <ide> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <ide> <ide> def pre_save(self, obj): <ide> <ide> # Ensure we clean the attributes so that we don't eg return integer <ide> # pk using a string representation, as provided by the url conf kwarg. <del> obj.full_clean() <add> if hasattr(obj, 'full_clean'): <add> obj.full_clean() <ide> <ide> <ide> class DestroyModelMixin(object):
2
Go
Go
add dummy proxy on port map
97adea5b7703005624eaa129d45ee0ad211792db
<ide><path>libnetwork/portmapper/mapper.go <ide> func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, usePr <ide> <ide> if useProxy { <ide> m.userlandProxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port) <add> } else { <add> m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort) <ide> } <ide> case *net.UDPAddr: <ide> proto = "udp" <ide> func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, usePr <ide> <ide> if useProxy { <ide> m.userlandProxy = newProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port) <add> } else { <add> m.userlandProxy = newDummyProxy(proto, hostIP, allocatedHostPort) <ide> } <ide> default: <ide> return nil, ErrUnknownBackendAddressType <ide> func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, usePr <ide> <ide> cleanup := func() error { <ide> // need to undo the iptables rules before we return <del> if m.userlandProxy != nil { <del> m.userlandProxy.Stop() <del> } <add> m.userlandProxy.Stop() <ide> pm.forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort) <ide> if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil { <ide> return err <ide> func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, usePr <ide> return nil <ide> } <ide> <del> if m.userlandProxy != nil { <del> if err := m.userlandProxy.Start(); err != nil { <del> if err := cleanup(); err != nil { <del> return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) <del> } <del> return nil, err <add> if err := m.userlandProxy.Start(); err != nil { <add> if err := cleanup(); err != nil { <add> return nil, fmt.Errorf("Error during port allocation cleanup: %v", err) <ide> } <add> return nil, err <ide> } <ide> <ide> pm.currentMappings[key] = m <ide><path>libnetwork/portmapper/mapper_test.go <ide> package portmapper <ide> <ide> import ( <ide> "net" <add> "strings" <ide> "testing" <ide> <ide> "github.com/docker/libnetwork/iptables" <ide> func TestMapAllPortsSingleInterface(t *testing.T) { <ide> hosts = []net.Addr{} <ide> } <ide> } <add> <add>func TestMapTCPDummyListen(t *testing.T) { <add> pm := New() <add> dstIP := net.ParseIP("0.0.0.0") <add> dstAddr := &net.TCPAddr{IP: dstIP, Port: 80} <add> <add> // no-op for dummy <add> srcAddr := &net.TCPAddr{Port: 1080, IP: net.ParseIP("172.16.0.1")} <add> <add> addrEqual := func(addr1, addr2 net.Addr) bool { <add> return (addr1.Network() == addr2.Network()) && (addr1.String() == addr2.String()) <add> } <add> <add> if host, err := pm.Map(srcAddr, dstIP, 80, false); err != nil { <add> t.Fatalf("Failed to allocate port: %s", err) <add> } else if !addrEqual(dstAddr, host) { <add> t.Fatalf("Incorrect mapping result: expected %s:%s, got %s:%s", <add> dstAddr.String(), dstAddr.Network(), host.String(), host.Network()) <add> } <add> if _, err := net.Listen("tcp", "0.0.0.0:80"); err == nil { <add> t.Fatal("Listen on mapped port without proxy should fail") <add> } else { <add> if !strings.Contains(err.Error(), "address already in use") { <add> t.Fatalf("Error should be about address already in use, got %v", err) <add> } <add> } <add> if _, err := net.Listen("tcp", "0.0.0.0:81"); err != nil { <add> t.Fatal(err) <add> } <add> if host, err := pm.Map(srcAddr, dstIP, 81, false); err == nil { <add> t.Fatalf("Bound port shouldn't be allocated, but it was on: %v", host) <add> } else { <add> if !strings.Contains(err.Error(), "address already in use") { <add> t.Fatalf("Error should be about address already in use, got %v", err) <add> } <add> } <add>} <add> <add>func TestMapUDPDummyListen(t *testing.T) { <add> pm := New() <add> dstIP := net.ParseIP("0.0.0.0") <add> dstAddr := &net.UDPAddr{IP: dstIP, Port: 80} <add> <add> // no-op for dummy <add> srcAddr := &net.UDPAddr{Port: 1080, IP: net.ParseIP("172.16.0.1")} <add> <add> addrEqual := func(addr1, addr2 net.Addr) bool { <add> return (addr1.Network() == addr2.Network()) && (addr1.String() == addr2.String()) <add> } <add> <add> if host, err := pm.Map(srcAddr, dstIP, 80, false); err != nil { <add> t.Fatalf("Failed to allocate port: %s", err) <add> } else if !addrEqual(dstAddr, host) { <add> t.Fatalf("Incorrect mapping result: expected %s:%s, got %s:%s", <add> dstAddr.String(), dstAddr.Network(), host.String(), host.Network()) <add> } <add> if _, err := net.ListenUDP("udp", &net.UDPAddr{IP: dstIP, Port: 80}); err == nil { <add> t.Fatal("Listen on mapped port without proxy should fail") <add> } else { <add> if !strings.Contains(err.Error(), "address already in use") { <add> t.Fatalf("Error should be about address already in use, got %v", err) <add> } <add> } <add> if _, err := net.ListenUDP("udp", &net.UDPAddr{IP: dstIP, Port: 81}); err != nil { <add> t.Fatal(err) <add> } <add> if host, err := pm.Map(srcAddr, dstIP, 81, false); err == nil { <add> t.Fatalf("Bound port shouldn't be allocated, but it was on: %v", host) <add> } else { <add> if !strings.Contains(err.Error(), "address already in use") { <add> t.Fatalf("Error should be about address already in use, got %v", err) <add> } <add> } <add>} <ide><path>libnetwork/portmapper/proxy.go <ide> package portmapper <ide> import ( <ide> "flag" <ide> "fmt" <add> "io" <ide> "io/ioutil" <ide> "log" <ide> "net" <ide> func (p *proxyCommand) Stop() error { <ide> } <ide> return nil <ide> } <add> <add>// dummyProxy just listen on some port, it is needed to prevent accidental <add>// port allocations on bound port, because without userland proxy we using <add>// iptables rules and not net.Listen <add>type dummyProxy struct { <add> listener io.Closer <add> addr net.Addr <add>} <add> <add>func newDummyProxy(proto string, hostIP net.IP, hostPort int) userlandProxy { <add> switch proto { <add> case "tcp": <add> addr := &net.TCPAddr{IP: hostIP, Port: hostPort} <add> return &dummyProxy{addr: addr} <add> case "udp": <add> addr := &net.UDPAddr{IP: hostIP, Port: hostPort} <add> return &dummyProxy{addr: addr} <add> } <add> return nil <add>} <add> <add>func (p *dummyProxy) Start() error { <add> switch addr := p.addr.(type) { <add> case *net.TCPAddr: <add> l, err := net.ListenTCP("tcp", addr) <add> if err != nil { <add> return err <add> } <add> p.listener = l <add> case *net.UDPAddr: <add> l, err := net.ListenUDP("udp", addr) <add> if err != nil { <add> return err <add> } <add> p.listener = l <add> default: <add> return fmt.Errorf("Unknown addr type: %T", p.addr) <add> } <add> return nil <add>} <add> <add>func (p *dummyProxy) Stop() error { <add> if p.listener != nil { <add> return p.listener.Close() <add> } <add> return nil <add>}
3
Ruby
Ruby
add spdx spec
6ecef73131178459ab9aa787bd9eaaacb48a6300
<ide><path>Library/Homebrew/test/utils/spdx_spec.rb <add># frozen_string_literal: true <add> <add>require "utils/spdx" <add> <add>describe SPDX do <add> describe ".spdx_data" do <add> it "has the license list version" do <add> expect(described_class.spdx_data["licenseListVersion"]).not_to eq(nil) <add> end <add> <add> it "has the release date" do <add> expect(described_class.spdx_data["releaseDate"]).not_to eq(nil) <add> end <add> <add> it "has licenses" do <add> expect(described_class.spdx_data["licenses"].length).not_to eq(0) <add> end <add> end <add> <add> describe ".download_latest_license_data!", :needs_network do <add> let(:tmp_json_path) { Pathname.new("#{TEST_TMPDIR}/spdx.json") } <add> <add> after do <add> FileUtils.rm tmp_json_path <add> end <add> <add> it "downloads latest license data" do <add> described_class.download_latest_license_data! to: tmp_json_path <add> expect(tmp_json_path).to exist <add> end <add> end <add>end <ide><path>Library/Homebrew/utils/spdx.rb <ide> def spdx_data <ide> @spdx_data ||= JSON.parse(JSON_PATH.read) <ide> end <ide> <del> def download_latest_license_data! <add> def download_latest_license_data!(to: JSON_PATH) <ide> latest_tag = GitHub.open_api(API_URL)["tag_name"] <ide> data_url = "https://raw.githubusercontent.com/spdx/license-list-data/#{latest_tag}/json/licenses.json" <del> curl_download(data_url, to: JSON_PATH, partial: false) <add> curl_download(data_url, to: to, partial: false) <ide> end <ide> end
2