content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Ruby | Ruby | use options instead of @options | 875bbd58b4175a1219c5f7615946d0b89e51182d | <ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def config
<ide> end
<ide>
<ide> def database_yml
<del> template "config/databases/#{@options[:database]}.yml", "config/database.yml"
<add> template "config/databases/#{options[:database]}.yml", "config/database.yml"
<ide> end
<ide>
<ide> def db
<ide> def javascripts
<ide> empty_directory "public/javascripts"
<ide>
<ide> unless options[:skip_javascript]
<del> copy_file "public/javascripts/#{@options[:javascript]}.js"
<del> copy_file "public/javascripts/#{@options[:javascript]}_ujs.js", "public/javascripts/rails.js"
<add> copy_file "public/javascripts/#{options[:javascript]}.js"
<add> copy_file "public/javascripts/#{options[:javascript]}_ujs.js", "public/javascripts/rails.js"
<ide>
<ide> if options[:javascript] == "prototype"
<ide> copy_file "public/javascripts/controls.js" | 1 |
PHP | PHP | update exception message in test case | 559397583ce8493b675309e74df06e474608ca87 | <ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testUrlGenerationOverridingShortString(array $url)
<ide> Router::connect('/articles', 'Articles::index');
<ide>
<ide> $this->expectException(InvalidArgumentException::class);
<del> $this->expectExceptionMessage('cannot be used to override `_path` value.');
<add> $this->expectExceptionMessage('cannot be used when defining routes targets with `_path`.');
<ide>
<ide> Router::url($url);
<ide> } | 1 |
Javascript | Javascript | add stream destroy benchmark | 869460aa5826e4d61f5e35879815efc7e9f3848b | <ide><path>benchmark/streams/destroy.js
<add>'use strict';
<add>const common = require('../common.js');
<add>const {
<add> Duplex,
<add> Readable,
<add> Transform,
<add> Writable,
<add>} = require('stream');
<add>
<add>const bench = common.createBenchmark(main, {
<add> n: [1e6],
<add> kind: ['duplex', 'readable', 'transform', 'writable']
<add>});
<add>
<add>function main({ n, kind }) {
<add> switch (kind) {
<add> case 'duplex':
<add> new Duplex({});
<add> new Duplex();
<add>
<add> bench.start();
<add> for (let i = 0; i < n; ++i)
<add> new Duplex().destroy();
<add> bench.end(n);
<add> break;
<add> case 'readable':
<add> new Readable({});
<add> new Readable();
<add>
<add> bench.start();
<add> for (let i = 0; i < n; ++i)
<add> new Readable().destroy();
<add> bench.end(n);
<add> break;
<add> case 'writable':
<add> new Writable({});
<add> new Writable();
<add>
<add> bench.start();
<add> for (let i = 0; i < n; ++i)
<add> new Writable().destroy();
<add> bench.end(n);
<add> break;
<add> case 'transform':
<add> new Transform({});
<add> new Transform();
<add>
<add> bench.start();
<add> for (let i = 0; i < n; ++i)
<add> new Transform().destroy();
<add> bench.end(n);
<add> break;
<add> default:
<add> throw new Error('Invalid kind');
<add> }
<add>} | 1 |
Javascript | Javascript | add onscrolltoindexfailed support | e16b514c5f774fb9ccb5702717585c478cc1cf0c | <ide><path>Libraries/Lists/VirtualizedList.js
<ide> type OptionalProps = {
<ide> * sure to also set the `refreshing` prop correctly.
<ide> */
<ide> onRefresh?: ?Function,
<add> /**
<add> * Used to handle failures when scrolling to an index that has not been measured yet. Recommended
<add> * action is to either compute your own offset and `scrollTo` it, or scroll as far as possible and
<add> * then try again after more items have been rendered.
<add> */
<add> onScrollToIndexFailed?: ?(info: {
<add> index: number,
<add> highestMeasuredFrameIndex: number,
<add> averageItemLength: number,
<add> }) => void,
<ide> /**
<ide> * Called when the viewability of rows changes, as defined by the
<ide> * `viewabilityConfig` prop.
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> viewOffset?: number,
<ide> viewPosition?: number,
<ide> }) {
<del> const {data, horizontal, getItemCount, getItemLayout} = this.props;
<add> const {
<add> data,
<add> horizontal,
<add> getItemCount,
<add> getItemLayout,
<add> onScrollToIndexFailed,
<add> } = this.props;
<ide> const {animated, index, viewOffset, viewPosition} = params;
<ide> invariant(
<ide> index >= 0 && index < getItemCount(data),
<ide> `scrollToIndex out of range: ${index} vs ${getItemCount(data) - 1}`,
<ide> );
<del> invariant(
<del> getItemLayout || index <= this._highestMeasuredFrameIndex,
<del> 'scrollToIndex should be used in conjunction with getItemLayout, ' +
<del> 'otherwise there is no way to know the location of an arbitrary index.',
<del> );
<add> if (!getItemLayout && index > this._highestMeasuredFrameIndex) {
<add> invariant(
<add> !!onScrollToIndexFailed,
<add> 'scrollToIndex should be used in conjunction with getItemLayout or onScrollToIndexFailed, ' +
<add> 'otherwise there is no way to know the location of offscreen indices or handle failures.',
<add> );
<add> onScrollToIndexFailed({
<add> averageItemLength: this._averageCellLength,
<add> highestMeasuredFrameIndex: this._highestMeasuredFrameIndex,
<add> index,
<add> });
<add> return;
<add> }
<ide> const frame = this._getFrameMetricsApprox(index);
<ide> const offset =
<ide> Math.max( | 1 |
Python | Python | add a doctest for `getlincoef` | ff26a55e7855f24f065714253fdc5de1c0df9eab | <ide><path>numpy/f2py/crackfortran.py
<ide> def buildimplicitrules(block):
<ide>
<ide>
<ide> def myeval(e, g=None, l=None):
<add> """ Like `eval` but returns only integers and floats """
<ide> r = eval(e, g, l)
<del> if type(r) in [type(0), type(0.0)]:
<add> if type(r) in [int, float]:
<ide> return r
<ide> raise ValueError('r=%r' % (r))
<ide>
<ide> getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I)
<ide>
<ide>
<ide> def getlincoef(e, xset): # e = a*x+b ; x in xset
<add> """
<add> Obtain ``a`` and ``b`` when ``e == "a*x+b"``, where ``x`` is a symbol in
<add> xset.
<add>
<add> >>> getlincoef('2*x + 1', {'x'})
<add> (2, 1, 'x')
<add> >>> getlincoef('3*x + x*2 + 2 + 1', {'x'})
<add> (5, 3, 'x')
<add> >>> getlincoef('0', {'x'})
<add> (0, 0, None)
<add> >>> getlincoef('0*x', {'x'})
<add> (0, 0, 'x')
<add> >>> getlincoef('x*x', {'x'})
<add> (None, None, None)
<add>
<add> This can be tricked by sufficiently complex expressions
<add>
<add> >>> getlincoef('(x - 0.5)*(x - 1.5)*(x - 1)*x + 2*x + 3', {'x'})
<add> (2.0, 3.0, 'x')
<add> """
<ide> try:
<ide> c = int(myeval(e, {}, {}))
<ide> return 0, c, None | 1 |
Go | Go | fix virtual size on images | 00cf2a1fa264c167dff0dd50e296c93d4c59908f | <ide><path>api_params.go
<ide> type APIHistory struct {
<ide> }
<ide>
<ide> type APIImages struct {
<del> Repository string `json:",omitempty"`
<del> Tag string `json:",omitempty"`
<del> ID string `json:"Id"`
<del> Created int64
<del> Size int64
<del> ParentSize int64
<del>
<add> Repository string `json:",omitempty"`
<add> Tag string `json:",omitempty"`
<add> ID string `json:"Id"`
<add> Created int64
<add> Size int64
<add> VirtualSize int64
<ide> }
<ide>
<ide> type APIInfo struct {
<ide> type APIInfo struct {
<ide>
<ide> type APIContainers struct {
<ide> ID string `json:"Id"`
<del> Image string
<del> Command string
<del> Created int64
<del> Status string
<del> Ports string
<add> Image string
<add> Command string
<add> Created int64
<add> Status string
<add> Ports string
<ide> SizeRw int64
<ide> SizeRootFs int64
<ide> }
<ide><path>commands.go
<ide> func (cli *DockerCli) CmdImages(args ...string) error {
<ide> fmt.Fprintf(w, "%s\t", utils.TruncateID(out.ID))
<ide> }
<ide> fmt.Fprintf(w, "%s ago\t", utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))))
<del> if out.ParentSize > 0 {
<del> fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.ParentSize))
<add> if out.VirtualSize > 0 {
<add> fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.Size), utils.HumanSize(out.VirtualSize))
<ide> } else {
<ide> fmt.Fprintf(w, "%s\n", utils.HumanSize(out.Size))
<ide> }
<ide><path>image.go
<ide> type Image struct {
<ide> Architecture string `json:"architecture,omitempty"`
<ide> graph *Graph
<ide> Size int64
<del> ParentSize int64
<ide> }
<ide>
<ide> func LoadImage(root string) (*Image, error) {
<ide> func (img *Image) Checksum() (string, error) {
<ide> return hash, nil
<ide> }
<ide>
<del>func (img *Image) getVirtualSize(size int64) int64 {
<add>func (img *Image) getParentsSize(size int64) int64 {
<ide> parentImage, err := img.GetParent()
<ide> if err != nil || parentImage == nil {
<ide> return size
<ide> }
<ide> size += parentImage.Size
<del> return parentImage.getVirtualSize(size)
<add> return parentImage.getParentsSize(size)
<ide> }
<ide>
<ide> // Build an Image object from raw json data
<ide><path>server.go
<ide> func (srv *Server) Images(all bool, filter string) ([]APIImages, error) {
<ide> out.ID = image.ID
<ide> out.Created = image.Created.Unix()
<ide> out.Size = image.Size
<del> out.ParentSize = image.getVirtualSize(0)
<add> out.VirtualSize = image.getParentsSize(0) + image.Size
<ide> outs = append(outs, out)
<ide> }
<ide> }
<ide> func (srv *Server) Images(all bool, filter string) ([]APIImages, error) {
<ide> out.ID = image.ID
<ide> out.Created = image.Created.Unix()
<ide> out.Size = image.Size
<del> out.ParentSize = image.getVirtualSize(0)
<add> out.VirtualSize = image.getParentsSize(0) + image.Size
<ide> outs = append(outs, out)
<ide> }
<ide> } | 4 |
Javascript | Javascript | put dev-only code into dev blocks | 99443922856f74b521cb3a90360a6a5a3a695694 | <ide><path>packages/react-reconciler/src/ReactFiberHooks.js
<ide> type HookType =
<ide>
<ide> // the first instance of a hook mismatch in a component,
<ide> // represented by a portion of it's stacktrace
<del>let currentHookMismatch = null;
<add>let currentHookMismatchInDev = null;
<ide>
<ide> let didWarnAboutMismatchedHooksForComponent;
<ide> if (__DEV__) {
<ide> function flushHookMismatchWarnings() {
<ide> // and a stack trace so the dev can locate where
<ide> // the first mismatch is coming from
<ide> if (__DEV__) {
<del> if (currentHookMismatch !== null) {
<add> if (currentHookMismatchInDev !== null) {
<ide> let componentName = getComponentName(
<ide> ((currentlyRenderingFiber: any): Fiber).type,
<ide> );
<ide> function flushHookMismatchWarnings() {
<ide> hookStackHeader,
<ide> hookStackDiff.join('\n'),
<ide> hookStackFooter,
<del> currentHookMismatch,
<add> currentHookMismatchInDev,
<ide> );
<ide> }
<del> currentHookMismatch = null;
<add> currentHookMismatchInDev = null;
<ide> }
<ide> }
<ide> }
<ide> function cloneHook(hook: Hook): Hook {
<ide> };
<ide>
<ide> if (__DEV__) {
<del> if (!currentHookMismatch) {
<add> if (currentHookMismatchInDev === null) {
<ide> if (currentHookNameInDev !== ((hook: any): HookDev)._debugType) {
<del> currentHookMismatch = new Error('tracer').stack
<add> currentHookMismatchInDev = new Error('tracer').stack
<ide> .split('\n')
<ide> .slice(4)
<ide> .join('\n');
<ide> export function useReducer<S, A>(
<ide> }
<ide> let fiber = (currentlyRenderingFiber = resolveCurrentlyRenderingFiber());
<ide> workInProgressHook = createWorkInProgressHook();
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> let queue: UpdateQueue<S, A> | null = (workInProgressHook.queue: any);
<ide> if (queue !== null) {
<ide> // Already have a queue, so this is an update.
<ide> export function useRef<T>(initialValue: T): {current: T} {
<ide> currentHookNameInDev = 'useRef';
<ide> }
<ide> workInProgressHook = createWorkInProgressHook();
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> let ref;
<ide>
<ide> if (workInProgressHook.memoizedState === null) {
<ide> function useEffectImpl(fiberEffectTag, hookEffectTag, create, deps): void {
<ide> const prevDeps = prevEffect.deps;
<ide> if (areHookInputsEqual(nextDeps, prevDeps)) {
<ide> pushEffect(NoHookEffect, create, destroy, nextDeps);
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> return;
<ide> }
<ide> }
<ide> function useEffectImpl(fiberEffectTag, hookEffectTag, create, deps): void {
<ide> destroy,
<ide> nextDeps,
<ide> );
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> }
<ide>
<ide> export function useImperativeHandle<T>(
<ide> export function useCallback<T>(
<ide> }
<ide> }
<ide> workInProgressHook.memoizedState = [callback, nextDeps];
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> return callback;
<ide> }
<ide>
<ide> export function useMemo<T>(
<ide> if (nextDeps !== null) {
<ide> const prevDeps: Array<mixed> | null = prevState[1];
<ide> if (areHookInputsEqual(nextDeps, prevDeps)) {
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> return prevState[0];
<ide> }
<ide> }
<ide> export function useMemo<T>(
<ide> currentlyRenderingFiber = fiber;
<ide> unstashContextDependencies();
<ide> workInProgressHook.memoizedState = [nextValue, nextDeps];
<del> currentHookNameInDev = null;
<add> if (__DEV__) {
<add> currentHookNameInDev = null;
<add> }
<ide> return nextValue;
<ide> }
<ide> | 1 |
Java | Java | fix typos in annotationsscannertests | 116a256e817624db819c256ab086db6c1bb4a21c | <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationsScannerTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> void directStrategyOnClassHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void inheritedAnnotationsStrategyOnClassWhenNotAnnoatedScansNone() {
<add> void inheritedAnnotationsStrategyOnClassWhenNotAnnotatedScansNone() {
<ide> Class<?> source = WithNoAnnotations.class;
<ide> assertThat(scan(source, SearchStrategy.INHERITED_ANNOTATIONS)).isEmpty();
<ide> }
<ide> void inheritedAnnotationsStrategyOnClassWhenHasAnnotationOnBothClassesIncudesOnl
<ide> }
<ide>
<ide> @Test
<del> void superclassStrategyOnClassWhenNotAnnoatedScansNone() {
<add> void superclassStrategyOnClassWhenNotAnnotatedScansNone() {
<ide> Class<?> source = WithNoAnnotations.class;
<ide> assertThat(scan(source, SearchStrategy.SUPERCLASS)).isEmpty();
<ide> }
<ide> void superclassStrategyOnClassHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void typeHierarchyStrategyOnClassWhenNotAnnoatedScansNone() {
<add> void typeHierarchyStrategyOnClassWhenNotAnnotatedScansNone() {
<ide> Class<?> source = WithNoAnnotations.class;
<ide> assertThat(scan(source, SearchStrategy.TYPE_HIERARCHY)).isEmpty();
<ide> }
<ide> void typeHierarchyStrategyOnClassHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void directStrategyOnMethodWhenNotAnnoatedScansNone() {
<add> void directStrategyOnMethodWhenNotAnnotatedScansNone() {
<ide> Method source = methodFrom(WithNoAnnotations.class);
<ide> assertThat(scan(source, SearchStrategy.DIRECT)).isEmpty();
<ide> }
<ide> void directStrategyOnMethodHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void inheritedAnnotationsStrategyOnMethodWhenNotAnnoatedScansNone() {
<add> void inheritedAnnotationsStrategyOnMethodWhenNotAnnotatedScansNone() {
<ide> Method source = methodFrom(WithNoAnnotations.class);
<ide> assertThat(scan(source, SearchStrategy.INHERITED_ANNOTATIONS)).isEmpty();
<ide> }
<ide> void inheritedAnnotationsStrategyOnMethodHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void superclassStrategyOnMethodWhenNotAnnoatedScansNone() {
<add> void superclassStrategyOnMethodWhenNotAnnotatedScansNone() {
<ide> Method source = methodFrom(WithNoAnnotations.class);
<ide> assertThat(scan(source, SearchStrategy.SUPERCLASS)).isEmpty();
<ide> }
<ide> void superclassStrategyOnMethodHierarchyScansInCorrectOrder() {
<ide> }
<ide>
<ide> @Test
<del> void typeHierarchyStrategyOnMethodWhenNotAnnoatedScansNone() {
<add> void typeHierarchyStrategyOnMethodWhenNotAnnotatedScansNone() {
<ide> Method source = methodFrom(WithNoAnnotations.class);
<ide> assertThat(scan(source, SearchStrategy.TYPE_HIERARCHY)).isEmpty();
<ide> } | 1 |
Python | Python | remove connection diagnostics | cd04404a8595868053aa46f1e0946de7dc544a0b | <ide><path>celery/worker.py
<ide> def receive_message(self):
<ide> :rtype: :class:`carrot.messaging.Message` instance.
<ide>
<ide> """
<del> self.connection_diagnostics()
<add> #self.connection_diagnostics()
<ide> message = self.task_consumer.fetch()
<ide> if message is not None:
<ide> message.ack() | 1 |
PHP | PHP | fix some valdiation rules | 8b50161890a0eb697f878581cd8103f0d4470d71 | <ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateSame($attribute, $value, $parameters)
<ide>
<ide> $other = Arr::get($this->data, $parameters[0]);
<ide>
<del> return isset($other) && $value == $other;
<add> return isset($other) && $value === $other;
<ide> }
<ide>
<ide> /**
<ide> protected function validateDifferent($attribute, $value, $parameters)
<ide>
<ide> $other = Arr::get($this->data, $parameters[0]);
<ide>
<del> return isset($other) && $value != $other;
<add> return isset($other) && $value !== $other;
<ide> }
<ide>
<ide> /**
<ide><path>tests/Validation/ValidationValidatorTest.php
<ide> public function testValidateConfirmed()
<ide>
<ide> $v = new Validator($trans, ['password' => 'foo', 'password_confirmation' => 'foo'], ['password' => 'Confirmed']);
<ide> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, ['password' => '1e2', 'password_confirmation' => '100'], ['password' => 'Confirmed']);
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide> public function testValidateSame()
<ide> public function testValidateSame()
<ide>
<ide> $v = new Validator($trans, ['foo' => 'bar', 'baz' => 'bar'], ['foo' => 'Same:baz']);
<ide> $this->assertTrue($v->passes());
<add>
<add> $v = new Validator($trans, ['foo' => '1e2', 'baz' => '100'], ['foo' => 'Same:baz']);
<add> $this->assertFalse($v->passes());
<ide> }
<ide>
<ide> public function testValidateDifferent()
<ide> public function testValidateDifferent()
<ide>
<ide> $v = new Validator($trans, ['foo' => 'bar', 'baz' => 'bar'], ['foo' => 'Different:baz']);
<ide> $this->assertFalse($v->passes());
<add>
<add> $v = new Validator($trans, ['foo' => '1e2', 'baz' => '100'], ['foo' => 'Different:baz']);
<add> $this->assertTrue($v->passes());
<ide> }
<ide>
<ide> public function testValidateAccepted() | 2 |
PHP | PHP | add method to add a renderer to debugger | 6411dddf81762a639aa3aae08e202e2bc684f51f | <ide><path>src/Error/Debugger.php
<ide> use Cake\Error\Debug\ScalarNode;
<ide> use Cake\Error\Debug\SpecialNode;
<ide> use Cake\Error\Debug\TextFormatter;
<add>use Cake\Error\ErrorRendererInterface;
<ide> use Cake\Error\Renderer\HtmlRenderer;
<ide> use Cake\Error\Renderer\TextRenderer;
<ide> use Cake\Log\Log;
<ide> public static function addFormat(string $format, array $strings): array
<ide> } else {
<ide> $self->_templates[$format] = $strings;
<ide> }
<add> unset($self->renderers[$format]);
<ide>
<ide> return $self->_templates[$format];
<ide> }
<ide>
<add> /**
<add> * Add a renderer to the current instance.
<add> *
<add> * @param string $name The alias for the the renderer.
<add> * @param string $class The classname of the renderer to use.
<add> * @return void
<add> */
<add> public static function addRenderer(string $name, string $class): void
<add> {
<add> if (!in_array(ErrorRendererInterface::class, class_implements($class))) {
<add> throw new InvalidArgumentException('Invalid renderer class. $class must implement ' . ErrorRendererInterface::class);
<add> }
<add> $self = Debugger::getInstance();
<add> $self->renderers[$name] = $class;
<add> }
<add>
<ide> /**
<ide> * Takes a processed array of data from an error and displays it in the chosen format.
<ide> *
<ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> use Cake\Error\Debug\SpecialNode;
<ide> use Cake\Error\Debug\TextFormatter;
<ide> use Cake\Error\Debugger;
<add>use Cake\Error\Renderer\HtmlRenderer;
<ide> use Cake\Form\Form;
<ide> use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testOutputErrorDescriptionEncoding(): void
<ide> $this->assertStringNotContainsString('<script>', $result);
<ide> }
<ide>
<add> /**
<add> * Test setOutputFormat overwrite
<add> */
<add> public function testAddOutputFormatOverwrite(): void
<add> {
<add> Debugger::addRenderer('test', HtmlRenderer::class);
<add> Debugger::addFormat('test', [
<add> 'error' => '{:description} : {:path}, line {:line}',
<add> ]);
<add> Debugger::setOutputFormat('test');
<add>
<add> ob_start();
<add> $debugger = Debugger::getInstance();
<add> $data = [
<add> 'error' => 'Notice',
<add> 'code' => E_NOTICE,
<add> 'level' => E_NOTICE,
<add> 'description' => 'Oh no!',
<add> 'file' => __FILE__,
<add> 'line' => __LINE__,
<add> ];
<add> $debugger->outputError($data);
<add> $result = ob_get_clean();
<add> $this->assertStringContainsString('Oh no! :', $result);
<add> $this->assertStringContainsString(", line {$data['line']}", $result);
<add> }
<add>
<ide> /**
<ide> * Tests that the correct line is being highlighted.
<ide> */ | 2 |
Python | Python | add testcase for behavior described in | 5fa76f6800fb81a621b63c42725c5502e2520302 | <ide><path>tests/test_basic.py
<ide> def index():
<ide> assert rv == b'request|after'
<ide>
<ide>
<add>def test_request_preprocessing_early_return():
<add> app = flask.Flask(__name__)
<add> evts = []
<add>
<add> @app.before_request
<add> def before_request():
<add> return "hello"
<add>
<add> @app.route('/')
<add> def index():
<add> evts.append('index')
<add> return "damnit"
<add>
<add> rv = app.test_client().get('/').data.strip()
<add> assert rv == 'hello'
<add> assert not evts
<add>
<add>
<ide> def test_after_request_processing():
<ide> app = flask.Flask(__name__)
<ide> app.testing = True | 1 |
Ruby | Ruby | add the gem requirement for sqlite3 | d00e1646f7f0faaddf0f89f3051d165aadb2567b | <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
<ide> require 'active_record/connection_adapters/sqlite_adapter'
<add>
<add>gem 'sqlite3', '~> 1.3.4'
<ide> require 'sqlite3'
<ide>
<ide> module ActiveRecord | 1 |
Python | Python | add compat util for decimalvalidator | 41d1e42e9cda6bf9697c409e4e293f1c5139ea6e | <ide><path>rest_framework/compat.py
<ide> def apply_markdown(text):
<ide> else:
<ide> DurationField = duration_string = parse_duration = None
<ide>
<add>try:
<add> # DecimalValidator is unavailable in Django < 1.9
<add> from django.core.validators import DecimalValidator
<add>except ImportError:
<add> DecimalValidator = None
<ide>
<ide> def set_rollback():
<ide> if hasattr(transaction, 'set_rollback'):
<ide><path>rest_framework/utils/field_mapping.py
<ide> from django.db import models
<ide> from django.utils.text import capfirst
<ide>
<add>from rest_framework.compat import DecimalValidator
<ide> from rest_framework.validators import UniqueValidator
<ide>
<ide> NUMERIC_FIELD_TYPES = (
<ide> def get_field_kwargs(field_name, model_field):
<ide> if isinstance(model_field, models.DecimalField):
<ide> validator_kwarg = [
<ide> validator for validator in validator_kwarg
<del> if not isinstance(validator, validators.DecimalValidator)
<add> if DecimalValidator and not isinstance(validator, DecimalValidator)
<ide> ]
<ide>
<ide> # Ensure that max_length is passed explicitly as a keyword arg, | 2 |
PHP | PHP | add logger contract | 3082830437b427386870c3c52a74886646de7b26 | <ide><path>src/Illuminate/Contracts/Logging/Logger.php
<add><?php namespace Illuminate\Contracts\Logging;
<add>
<add>interface Logger {
<add>
<add> /**
<add> * Log an alert message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function alert($message, array $context = array());
<add>
<add> /**
<add> * Log a critical message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function critical($message, array $context = array());
<add>
<add> /**
<add> * Log an error message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function error($message, array $context = array());
<add>
<add> /**
<add> * Log a warning message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function warning($message, array $context = array());
<add>
<add> /**
<add> * Log a notice to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function notice($message, array $context = array());
<add>
<add> /**
<add> * Log an informational message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function info($message, array $context = array());
<add>
<add> /**
<add> * Log a debug message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function debug($message, array $context = array());
<add>
<add> /**
<add> * Log a message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function log($level, $message, array $context = array());
<add>
<add> /**
<add> * Register a file log handler.
<add> *
<add> * @param string $path
<add> * @param string $level
<add> * @return void
<add> */
<add> public function useFiles($path, $level = 'debug');
<add>
<add> /**
<add> * Register a daily file log handler.
<add> *
<add> * @param string $path
<add> * @param int $days
<add> * @param string $level
<add> * @return void
<add> */
<add> public function useDailyFiles($path, $days = 0, $level = 'debug');
<add>
<add>}
<ide><path>src/Illuminate/Log/Writer.php
<ide> use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Contracts\Support\JsonableInterface;
<ide> use Illuminate\Contracts\Support\ArrayableInterface;
<add>use Illuminate\Contracts\Logging\Logger as LoggerContract;
<ide>
<del>class Writer {
<add>class Writer implements LoggerContract {
<ide>
<ide> /**
<ide> * The Monolog logger instance.
<ide> public function __construct(MonologLogger $monolog, Dispatcher $dispatcher = nul
<ide> }
<ide>
<ide> /**
<del> * Call Monolog with the given method and parameters.
<add> * Log an alert message to the logs.
<ide> *
<del> * @param string $method
<del> * @param mixed $parameters
<del> * @return mixed
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<ide> */
<del> protected function callMonolog($method, $parameters)
<add> public function alert($message, array $context = array())
<ide> {
<del> if (is_array($parameters[0]))
<del> {
<del> $parameters[0] = json_encode($parameters[0]);
<del> }
<del>
<del> return call_user_func_array(array($this->monolog, $method), $parameters);
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<ide> }
<ide>
<ide> /**
<del> * Register a file log handler.
<add> * Log a critical message to the logs.
<ide> *
<del> * @param string $path
<del> * @param string $level
<add> * @param string $message
<add> * @param array $context
<ide> * @return void
<ide> */
<del> public function useFiles($path, $level = 'debug')
<add> public function critical($message, array $context = array())
<ide> {
<del> $level = $this->parseLevel($level);
<del>
<del> $this->monolog->pushHandler($handler = new StreamHandler($path, $level));
<del>
<del> $handler->setFormatter($this->getDefaultFormatter());
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<ide> }
<ide>
<ide> /**
<del> * Register a daily file log handler.
<add> * Log an error message to the logs.
<ide> *
<del> * @param string $path
<del> * @param int $days
<del> * @param string $level
<add> * @param string $message
<add> * @param array $context
<ide> * @return void
<ide> */
<del> public function useDailyFiles($path, $days = 0, $level = 'debug')
<add> public function error($message, array $context = array())
<ide> {
<del> $level = $this->parseLevel($level);
<del>
<del> $this->monolog->pushHandler($handler = new RotatingFileHandler($path, $days, $level));
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<add> }
<ide>
<del> $handler->setFormatter($this->getDefaultFormatter());
<add> /**
<add> * Log a warning message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function warning($message, array $context = array())
<add> {
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<ide> }
<ide>
<ide> /**
<del> * Register an error_log handler.
<add> * Log a notice to the logs.
<ide> *
<del> * @param string $level
<del> * @param integer $messageType
<add> * @param string $message
<add> * @param array $context
<ide> * @return void
<ide> */
<del> public function useErrorLog($level = 'debug', $messageType = ErrorLogHandler::OPERATING_SYSTEM)
<add> public function notice($message, array $context = array())
<ide> {
<del> $level = $this->parseLevel($level);
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<add> }
<ide>
<del> $this->monolog->pushHandler($handler = new ErrorLogHandler($messageType, $level));
<add> /**
<add> * Log an informational message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function info($message, array $context = array())
<add> {
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<add> }
<ide>
<del> $handler->setFormatter($this->getDefaultFormatter());
<add> /**
<add> * Log a debug message to the logs.
<add> *
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> public function debug($message, array $context = array())
<add> {
<add> return $this->writeLog(__FUNCTION__, $message, $context);
<ide> }
<ide>
<ide> /**
<del> * Get a defaut Monolog formatter instance.
<add> * Log a message to the logs.
<ide> *
<del> * @return \Monolog\Formatter\LineFormatter
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<ide> */
<del> protected function getDefaultFormatter()
<add> public function log($level, $message, array $context = array())
<ide> {
<del> return new LineFormatter(null, null, true);
<add> return $this->writeLog($level, $message, $context);
<ide> }
<ide>
<ide> /**
<del> * Parse the string level into a Monolog constant.
<add> * Dynamically pass log calls into the writer.
<ide> *
<ide> * @param string $level
<del> * @return int
<del> *
<del> * @throws \InvalidArgumentException
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<ide> */
<del> protected function parseLevel($level)
<add> public function write($level, $message, array $context = array())
<ide> {
<del> switch ($level)
<del> {
<del> case 'debug':
<del> return MonologLogger::DEBUG;
<add> return $this->log($level, $message, $context);
<add> }
<ide>
<del> case 'info':
<del> return MonologLogger::INFO;
<add> /**
<add> * Write a message to Monolog.
<add> *
<add> * @param string $level
<add> * @param string $message
<add> * @param array $context
<add> * @return void
<add> */
<add> protected function writeLog($level, $message, $context)
<add> {
<add> $this->fireLogEvent($level, $message = $this->formatMessage($message), $context);
<ide>
<del> case 'notice':
<del> return MonologLogger::NOTICE;
<add> $this->monolog->{$level}($message, $context);
<add> }
<ide>
<del> case 'warning':
<del> return MonologLogger::WARNING;
<add> /**
<add> * Register a file log handler.
<add> *
<add> * @param string $path
<add> * @param string $level
<add> * @return void
<add> */
<add> public function useFiles($path, $level = 'debug')
<add> {
<add> $this->monolog->pushHandler($handler = new StreamHandler($path, $this->parseLevel($level)));
<ide>
<del> case 'error':
<del> return MonologLogger::ERROR;
<add> $handler->setFormatter($this->getDefaultFormatter());
<add> }
<ide>
<del> case 'critical':
<del> return MonologLogger::CRITICAL;
<add> /**
<add> * Register a daily file log handler.
<add> *
<add> * @param string $path
<add> * @param int $days
<add> * @param string $level
<add> * @return void
<add> */
<add> public function useDailyFiles($path, $days = 0, $level = 'debug')
<add> {
<add> $this->monolog->pushHandler(
<add> $handler = new RotatingFileHandler($path, $days, $this->parseLevel($level))
<add> );
<ide>
<del> case 'alert':
<del> return MonologLogger::ALERT;
<add> $handler->setFormatter($this->getDefaultFormatter());
<add> }
<ide>
<del> case 'emergency':
<del> return MonologLogger::EMERGENCY;
<add> /**
<add> * Register an error_log handler.
<add> *
<add> * @param string $level
<add> * @param integer $messageType
<add> * @return void
<add> */
<add> public function useErrorLog($level = 'debug', $messageType = ErrorLogHandler::OPERATING_SYSTEM)
<add> {
<add> $this->monolog->pushHandler(
<add> $handler = new ErrorLogHandler($messageType, $this->parseLevel($level))
<add> );
<ide>
<del> default:
<del> throw new \InvalidArgumentException("Invalid log level.");
<del> }
<add> $handler->setFormatter($this->getDefaultFormatter());
<ide> }
<ide>
<ide> /**
<ide> protected function fireLogEvent($level, $message, array $context = array())
<ide> }
<ide>
<ide> /**
<del> * Dynamically pass log calls into the writer.
<add> * Format the parameters for the logger.
<ide> *
<del> * @param mixed (level, param, param)
<del> * @return mixed
<add> * @param mixed $parameters
<add> * @return void
<ide> */
<del> public function write()
<add> protected function formatMessage($message)
<ide> {
<del> $level = head(func_get_args());
<add> if (is_array($message))
<add> {
<add> return var_export($message, true);
<add> }
<add> elseif ($message instanceof JsonableInterface)
<add> {
<add> return $message->toJson();
<add> }
<add> elseif ($message instanceof ArrayableInterface)
<add> {
<add> return var_export($message->toArray(), true);
<add> }
<ide>
<del> return call_user_func_array(array($this, $level), array_slice(func_get_args(), 1));
<add> return $message;
<ide> }
<ide>
<ide> /**
<del> * Format the parameters for the logger.
<add> * Parse the string level into a Monolog constant.
<ide> *
<del> * @param mixed $parameters
<del> * @return void
<add> * @param string $level
<add> * @return int
<add> *
<add> * @throws \InvalidArgumentException
<ide> */
<del> protected function formatParameters(&$parameters)
<add> protected function parseLevel($level)
<ide> {
<del> if (isset($parameters[0]))
<add> switch ($level)
<ide> {
<del> if (is_array($parameters[0]))
<del> {
<del> $parameters[0] = var_export($parameters[0], true);
<del> }
<del> elseif ($parameters[0] instanceof JsonableInterface)
<del> {
<del> $parameters[0] = $parameters[0]->toJson();
<del> }
<del> elseif ($parameters[0] instanceof ArrayableInterface)
<del> {
<del> $parameters[0] = var_export($parameters[0]->toArray(), true);
<del> }
<add> case 'debug':
<add> return MonologLogger::DEBUG;
<add>
<add> case 'info':
<add> return MonologLogger::INFO;
<add>
<add> case 'notice':
<add> return MonologLogger::NOTICE;
<add>
<add> case 'warning':
<add> return MonologLogger::WARNING;
<add>
<add> case 'error':
<add> return MonologLogger::ERROR;
<add>
<add> case 'critical':
<add> return MonologLogger::CRITICAL;
<add>
<add> case 'alert':
<add> return MonologLogger::ALERT;
<add>
<add> case 'emergency':
<add> return MonologLogger::EMERGENCY;
<add>
<add> default:
<add> throw new \InvalidArgumentException("Invalid log level.");
<ide> }
<ide> }
<ide>
<ide> public function getMonolog()
<ide> return $this->monolog;
<ide> }
<ide>
<add> /**
<add> * Get a defaut Monolog formatter instance.
<add> *
<add> * @return \Monolog\Formatter\LineFormatter
<add> */
<add> protected function getDefaultFormatter()
<add> {
<add> return new LineFormatter(null, null, true);
<add> }
<add>
<ide> /**
<ide> * Get the event dispatcher instance.
<ide> *
<ide> public function setEventDispatcher(Dispatcher $dispatcher)
<ide> $this->dispatcher = $dispatcher;
<ide> }
<ide>
<del> /**
<del> * Dynamically handle error additions.
<del> *
<del> * @param string $method
<del> * @param mixed $parameters
<del> * @return mixed
<del> *
<del> * @throws \BadMethodCallException
<del> */
<del> public function __call($method, $parameters)
<del> {
<del> if (in_array($method, $this->levels))
<del> {
<del> $this->formatParameters($parameters);
<del>
<del> call_user_func_array(array($this, 'fireLogEvent'), array_merge(array($method), $parameters));
<del>
<del> $method = 'add'.ucfirst($method);
<del>
<del> return $this->callMonolog($method, $parameters);
<del> }
<del>
<del> throw new \BadMethodCallException("Method [$method] does not exist.");
<del> }
<del>
<ide> }
<ide><path>tests/Log/LogWriterTest.php
<ide> public function testErrorLogHandlerCanBeAdded()
<ide> }
<ide>
<ide>
<del> public function testMagicMethodsPassErrorAdditionsToMonolog()
<add> public function testMethodsPassErrorAdditionsToMonolog()
<ide> {
<ide> $writer = new Writer($monolog = m::mock('Monolog\Logger'));
<del> $monolog->shouldReceive('addError')->once()->with('foo')->andReturn('bar');
<add> $monolog->shouldReceive('error')->once()->with('foo', []);
<ide>
<del> $this->assertEquals('bar', $writer->error('foo'));
<add> $writer->error('foo');
<ide> }
<ide>
<ide>
<ide> public function testWriterFiresEventsDispatcher()
<ide> {
<ide> $writer = new Writer($monolog = m::mock('Monolog\Logger'), $events = new Illuminate\Events\Dispatcher);
<del> $monolog->shouldReceive('addError')->once()->with('foo');
<add> $monolog->shouldReceive('error')->once()->with('foo', array());
<ide>
<ide> $events->listen('illuminate.log', function($level, $message, array $context = array())
<ide> { | 3 |
Javascript | Javascript | apply observable bindings to new models | f3207fa9024bab3cf34cfdf064cbbea7312b5b60 | <ide><path>common/models/article.js
<del>'use strict';
<add>import { Observable } from 'rx';
<ide>
<ide> module.exports = function(Article) {
<del>
<add> Article.on('dataSourceAttached', () => {
<add> Article.findOne$ = Observable.fromNodeCallback(Article.findOne, Article);
<add> Article.findById$ = Observable.fromNodeCallback(Article.findById, Article);
<add> Article.find$ = Observable.fromNodeCallback(Article.find, Article);
<add> });
<ide> };
<ide><path>common/models/popularity.js
<del>'use strict';
<add>import { Observable } from 'rx';
<ide>
<ide> module.exports = function(Popularity) {
<del>
<add> Popularity.on('dataSourceAttached', () => {
<add> Popularity.findOne$ = Observable.fromNodeCallback(
<add> Popularity.findOne,
<add> Popularity
<add> );
<add> Popularity.findById$ = Observable.fromNodeCallback(
<add> Popularity.findById,
<add> Popularity
<add> );
<add> Popularity.find$ = Observable.fromNodeCallback(Popularity.find, Popularity);
<add> });
<ide> }; | 2 |
Text | Text | fix typo in upgrading guide | 04cced06fa6fcd463645724ecc1f92d067209961 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> Record callbacks.
<ide>
<ide> When you define a `after_rollback` or `after_commit` callback, you
<ide> will receive a deprecation warning about this upcoming change. When
<del>you are ready, you can opt into the new behvaior and remove the
<add>you are ready, you can opt into the new behavior and remove the
<ide> deprecation warning by adding following configuration to your
<ide> `config/application.rb`:
<ide> | 1 |
Text | Text | add link to ecosystem doc. | 952e232722f59b24490dfb40bf6dd2354fe28c9c | <ide><path>CONTRIBUTING.md
<ide> # Contributing to React Native
<ide>
<del>Thank you for your interest in contributing to React Native! From commenting on and triaging issues, to reviewing and sending Pull Requests, all contributions are welcome.
<add>Thank you for your interest in contributing to React Native! From commenting on and triaging issues, to reviewing and sending Pull Requests, all contributions are welcome. We aim to build a vibrant and inclusive [ecosystem of partners, core contributors, and community](ECOSYSTEM.md) that goes beyond the main React Native GitHub repository.
<ide>
<ide> The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies who want to learn how to run and contribute to an open source project. Contributors and people new to open source alike will find the following guides especially useful:
<ide>
<ide> * [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
<ide> * [Building Welcoming Communities](https://opensource.guide/building-community/)
<ide>
<add>
<ide> ### [Code of Conduct](https://code.fb.com/codeofconduct/)
<ide>
<ide> As a reminder, all contributors are expected to adhere to the [Code of Conduct](https://code.facebook.com/codeofconduct).
<ide>
<del>
<ide> ## Ways to Contribute
<ide>
<ide> If you are eager to start contributing code right away, we have a list of [good first issues](https://github.com/facebook/react-native/labels/good%20first%20issue) that contain bugs which have a relatively limited scope. As you gain more experience and demonstrate a commitment to evolving React Native, you may be granted issue management permissions in the repository.
<ide>
<ide> There are other ways you can contribute without writing a single line of code. Here are a few things you can do to help out:
<ide>
<del>
<ide> 1. **Replying and handling open issues.** We get a lot of issues every day, and some of them may lack necessary information. You can help out by guiding people through the process of filling out the issue template, asking for clarifying information, or pointing them to existing issues that match their description of the problem. We'll cover more about this process later, in [Handling Issues](http://github.com/facebook/react-native/wiki/Handling-Issues).
<ide> 2. **Reviewing pull requests for the docs.** Reviewing [documentation updates](https://github.com/facebook/react-native-website/pulls) can be as simple as checking for spelling and grammar. If you encounter situations that can be explained better in the docs, click **Edit** at the top of most docs pages to get started with your own contribution.
<ide> 3. **Help people write test plans.** Some pull requests sent to the main repository may lack a proper test plan. These help reviewers understand how the change was tested, and can speed up the time it takes for a contribution to be accepted.
<ide>
<del>
<ide> Each of these tasks is highly impactful, and maintainers will greatly appreciate your help.
<ide>
<del>
<ide> ### Our Development Process
<ide>
<ide> We use GitHub issues and pull requests to keep track of bug reports and contributions from the community. All changes from engineers at Facebook will sync to [GitHub](https://github.com/facebook/react-native) through a bridge with Facebook's internal source control. Changes from the community are handled through GitHub pull requests. Once a change made on GitHub is approved, it will first be imported into Facebook's internal source control and tested against Facebook's codebase. Once merged at Facebook, the change will eventually sync back to GitHub as a single commit once it has passed Facebook's internal tests.
<ide> There are a few other repositories you might want to familiarize yourself with:
<ide>
<ide> Browsing through these repositories should provide some insight into how the React Native open source project is managed.
<ide>
<del>
<ide> ## Handling Issues
<ide>
<ide> We use GitHub issues to track bugs exclusively. You can report an issue by filing a [Bug Report](https://github.com/facebook/react-native/issues/new/choose). Watch this space for more details on how to get involved and triage issues.
<ide> Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
<ide>
<ide> ## Helping with Documentation
<ide>
<del>The React Native documentation is hosted as part of the React Native website repository at https://github.com/facebook/react-native-website. The website itself is located at https://facebook.github.io/react-native and it is built using [Docusaurus](https://docusaurus.io/). If there's anything you'd like to change in the docs, you can get started by clicking on the "Edit" button located on the upper right of most pages in the website.
<add>The React Native documentation is hosted as part of the React Native website repository at https://github.com/facebook/react-native-website. The website itself is located at <https://facebook.github.io/react-native> and it is built using [Docusaurus](https://docusaurus.io/). If there's anything you'd like to change in the docs, you can get started by clicking on the "Edit" button located on the upper right of most pages in the website.
<ide>
<ide> If you are adding new functionality or introducing a change in behavior, we will ask you to update the documentation to reflect your changes.
<ide>
<ide> ### Contributing to the Blog
<ide>
<ide> The React Native blog is generated [from the Markdown sources for the blog](https://github.com/facebook/react-native-website/tree/master/website/blog).
<ide>
<del>Please open an issue in the `react-native-website` repository or tag us on [@ReactNative on Twitter](http://twitter.com/reactnative) and get the go-ahead from a maintainer before writing an article intended for the React Native blog. In most cases, you might want to share your article on your own blog or writing medium instead. It's worth asking, though, in case we find your article is a good fit for the blog.
<add>Please open an issue in the https://github.com/facebook/react-native-website repository or tag us on [@ReactNative on Twitter](http://twitter.com/reactnative) and get the go-ahead from a maintainer before writing an article intended for the React Native blog. In most cases, you might want to share your article on your own blog or writing medium instead. It's worth asking, though, in case we find your article is a good fit for the blog.
<ide>
<ide> We recommend referring to the [CONTRIBUTING](https://github.com/facebook/react-native-website/blob/master/CONTRIBUTING.md) document for the `react-native-website` repository to learn more about contributing to the website in general.
<ide>
<del>
<ide> ## Contributing Code
<ide>
<ide> Code-level contributions to React Native generally come in the form of [pull requests](https://help.github.com/en/articles/about-pull-requests). The process of proposing a change to React Native can be summarized as follows:
<ide> Whenever you are ready to contribute code, check out our [step-by-step guide to
<ide>
<ide> Tests help us prevent regressions from being introduced to the codebase. The GitHub repository is continuously tested using Circle and Appveyor, the results of which are available through the Checks functionality on [commits](https://github.com/facebook/react-native/commits/master) and pull requests. You can learn more about running and writing tests in the [Tests wiki](http://github.com/facebook/react-native/wiki/Tests).
<ide>
<del>
<ide> ## Community Contributions
<ide>
<ide> Contributions to React Native are not limited to GitHub. You can help others by sharing your experience using React Native, whether that is through blog posts, presenting talks at conferences, or simply sharing your thoughts on Twitter and tagging @ReactNative.
<ide>
<del>
<ide> ## Where to Get Help
<ide>
<del>As you work on React Native, it is natural that sooner or later you may require help. In addition to the resources listed in [SUPPORT](http://github.com/facebook/react-native/blob/master/.github/SUPPORT.md), people interested in contributing may take advantage of the following:
<del>
<add>As you work on React Native, it is natural that sooner or later you may require help. In addition to the resources listed in [SUPPORT](.github/SUPPORT.md), people interested in contributing may take advantage of the following:
<ide>
<ide> * **Twitter**. The React Native team at Facebook has its own account at [@reactnative](https://twitter.com/reactnative), and the React Native Community uses [@reactnativecomm](https://twitter.com/reactnativecomm). If you feel stuck, or need help contributing, please do not hesitate to reach out.
<ide> * **Proposals Repository**. If you are considering working on a feature large in scope, consider [creating a proposal first](https://github.com/react-native-community/discussions-and-proposals). The community can help you figure out the right approach, and we'd be happy to help. | 1 |
Ruby | Ruby | expand tabs and strip trailing whitespace | c91088cd135b797048f179423158713c4459e556 | <ide><path>activerecord/test/mixin_test.rb
<ide>
<ide> class ListTest < Test::Unit::TestCase
<ide> fixtures :mixins
<del>
<add>
<ide> def test_reordering
<del>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_3),
<del> mixins(:list_4)],
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_3),
<add> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> mixins(:list_2).move_lower
<del>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_3),
<del> mixins(:list_2),
<del> mixins(:list_4)],
<add>
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_3),
<add> mixins(:list_2),
<add> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> mixins(:list_2).move_higher
<ide>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_3),
<del> mixins(:list_4)],
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_3),
<add> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> mixins(:list_1).move_to_bottom
<ide>
<del> assert_equal [mixins(:list_2),
<del> mixins(:list_3),
<del> mixins(:list_4),
<del> mixins(:list_1)],
<add> assert_equal [mixins(:list_2),
<add> mixins(:list_3),
<add> mixins(:list_4),
<add> mixins(:list_1)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<ide>
<ide> mixins(:list_1).move_to_top
<ide>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_3),
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_3),
<ide> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<del>
<add>
<add>
<ide> mixins(:list_2).move_to_bottom
<del>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_3),
<del> mixins(:list_4),
<add>
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_3),
<add> mixins(:list_4),
<ide> mixins(:list_2)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<ide>
<ide> mixins(:list_4).move_to_top
<ide>
<del> assert_equal [mixins(:list_4),
<del> mixins(:list_1),
<del> mixins(:list_3),
<add> assert_equal [mixins(:list_4),
<add> mixins(:list_1),
<add> mixins(:list_3),
<ide> mixins(:list_2)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> end
<ide>
<ide> def test_move_to_bottom_with_next_to_last_item
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_3),
<del> mixins(:list_4)],
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_3),
<add> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<ide>
<ide> mixins(:list_3).move_to_bottom
<ide>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_4),
<del> mixins(:list_3)],
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_4),
<add> mixins(:list_3)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<ide> end
<del>
<add>
<ide> def test_next_prev
<ide> assert_equal mixins(:list_2), mixins(:list_1).lower_item
<ide> assert_nil mixins(:list_1).higher_item
<ide> assert_equal mixins(:list_3), mixins(:list_4).higher_item
<ide> assert_nil mixins(:list_4).lower_item
<ide> end
<del>
<del>
<add>
<add>
<ide> def test_injection
<ide> item = ListMixin.new("parent_id"=>1)
<ide> assert_equal "parent_id = 1", item.scope_condition
<ide> assert_equal "pos", item.position_column
<del> end
<del>
<add> end
<add>
<ide> def test_insert
<ide> new = ListMixin.create("parent_id"=>20)
<ide> assert_equal 1, new.pos
<ide> def test_insert
<ide> assert_equal 2, new.pos
<ide> assert !new.first?
<ide> assert new.last?
<del>
<add>
<ide> new = ListMixin.create("parent_id"=>20)
<del> assert_equal 3, new.pos
<add> assert_equal 3, new.pos
<ide> assert !new.first?
<ide> assert new.last?
<del>
<add>
<ide> new = ListMixin.create("parent_id"=>0)
<ide> assert_equal 1, new.pos
<ide> assert new.first?
<ide> assert new.last?
<del> end
<add> end
<ide>
<ide> def test_insert_at
<ide> new = ListMixin.create("parent_id" => 20)
<ide> assert_equal 1, new.pos
<ide>
<del> new = ListMixin.create("parent_id" => 20)
<del> assert_equal 2, new.pos
<del>
<del> new = ListMixin.create("parent_id" => 20)
<del> assert_equal 3, new.pos
<add> new = ListMixin.create("parent_id" => 20)
<add> assert_equal 2, new.pos
<add>
<add> new = ListMixin.create("parent_id" => 20)
<add> assert_equal 3, new.pos
<add>
<add> new4 = ListMixin.create("parent_id" => 20)
<add> assert_equal 4, new4.pos
<ide>
<del> new4 = ListMixin.create("parent_id" => 20)
<del> assert_equal 4, new4.pos
<add> new4.insert_at(3)
<add> assert_equal 3, new4.pos
<ide>
<del> new4.insert_at(3)
<del> assert_equal 3, new4.pos
<add> new.reload
<add> assert_equal 4, new.pos
<ide>
<del> new.reload
<del> assert_equal 4, new.pos
<del>
<ide> new.insert_at(2)
<ide> assert_equal 2, new.pos
<ide>
<ide> def test_insert_at
<ide> new4.reload
<ide> assert_equal 5, new4.pos
<ide> end
<del>
<add>
<ide> def test_delete_middle
<del>
<del> assert_equal [mixins(:list_1),
<del> mixins(:list_2),
<del> mixins(:list_3),
<del> mixins(:list_4)],
<add> assert_equal [mixins(:list_1),
<add> mixins(:list_2),
<add> mixins(:list_3),
<add> mixins(:list_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> mixins(:list_2).destroy
<del>
<del> assert_equal [mixins(:list_1, :reload),
<del> mixins(:list_3, :reload),
<del> mixins(:list_4, :reload)],
<add>
<add> assert_equal [mixins(:list_1, :reload),
<add> mixins(:list_3, :reload),
<add> mixins(:list_4, :reload)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> assert_equal 1, mixins(:list_1).pos
<ide> assert_equal 2, mixins(:list_3).pos
<ide> assert_equal 3, mixins(:list_4).pos
<ide>
<ide> mixins(:list_1).destroy
<ide>
<del> assert_equal [mixins(:list_3, :reload),
<del> mixins(:list_4, :reload)],
<add> assert_equal [mixins(:list_3, :reload),
<add> mixins(:list_4, :reload)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos')
<del>
<add>
<ide> assert_equal 1, mixins(:list_3).pos
<ide> assert_equal 2, mixins(:list_4).pos
<del>
<del> end
<add>
<add> end
<ide>
<ide> def test_with_string_based_scope
<ide> new = ListWithStringScopeMixin.create("parent_id"=>500)
<ide> assert_equal 1, new.pos
<ide> assert new.first?
<ide> assert new.last?
<del> end
<add> end
<ide>
<ide> def test_nil_scope
<ide> new1, new2, new3 = ListMixin.create, ListMixin.create, ListMixin.create
<ide> def test_nil_scope
<ide>
<ide> class TreeTest < Test::Unit::TestCase
<ide> fixtures :mixins
<del>
<add>
<ide> def test_has_child
<ide> assert_equal true, mixins(:tree_1).has_children?
<ide> assert_equal true, mixins(:tree_2).has_children?
<ide> def test_parent
<ide> assert_equal mixins(:tree_2).parent, mixins(:tree_4).parent
<ide> assert_nil mixins(:tree_1).parent
<ide> end
<del>
<add>
<ide> def test_delete
<ide> assert_equal 6, TreeMixin.count
<ide> mixins(:tree_1).destroy
<ide> def test_delete
<ide>
<ide> def test_insert
<ide> @extra = mixins(:tree_1).children.create
<del>
<add>
<ide> assert @extra
<del>
<add>
<ide> assert_equal @extra.parent, mixins(:tree_1)
<ide>
<ide> assert_equal 3, mixins(:tree_1).children.size
<ide> def test_ancestors
<ide> assert_equal [], mixins(:tree2_1).ancestors
<ide> assert_equal [], mixins(:tree3_1).ancestors
<ide> end
<del>
<add>
<ide> def test_root
<ide> assert_equal mixins(:tree_1), TreeMixin.root
<ide> assert_equal mixins(:tree_1), mixins(:tree_1).root
<ide> def test_root
<ide> assert_equal mixins(:tree_1), mixins(:tree_4).root
<ide> assert_equal mixins(:tree2_1), mixins(:tree2_1).root
<ide> assert_equal mixins(:tree3_1), mixins(:tree3_1).root
<del> end
<add> end
<ide>
<ide> def test_roots
<ide> assert_equal [mixins(:tree_1), mixins(:tree2_1), mixins(:tree3_1)], TreeMixin.roots
<ide> def test_self_and_siblings
<ide>
<ide> class TreeTestWithoutOrder < Test::Unit::TestCase
<ide> fixtures :mixins
<del>
<add>
<ide> def test_root
<ide> assert [mixins(:tree_without_order_1), mixins(:tree_without_order_2)].include?(TreeMixinWithoutOrder.root)
<del> end
<add> end
<ide>
<ide> def test_roots
<ide> assert_equal [], [mixins(:tree_without_order_1), mixins(:tree_without_order_2)] - TreeMixinWithoutOrder.roots
<ide> def test_roots
<ide>
<ide> class TouchTest < Test::Unit::TestCase
<ide> fixtures :mixins
<del>
<add>
<ide> def test_update
<del>
<del> stamped = Mixin.new
<del>
<add> stamped = Mixin.new
<add>
<ide> assert_nil stamped.updated_at
<ide> assert_nil stamped.created_at
<ide> stamped.save
<ide> assert_not_nil stamped.updated_at
<ide> assert_not_nil stamped.created_at
<del> end
<add> end
<ide>
<ide> def test_create
<ide> @obj = Mixin.create
<ide> assert_not_nil @obj.updated_at
<ide> assert_not_nil @obj.created_at
<del> end
<add> end
<ide>
<ide> def test_many_updates
<del>
<del> stamped = Mixin.new
<add> stamped = Mixin.new
<ide>
<ide> assert_nil stamped.updated_at
<ide> assert_nil stamped.created_at
<ide> stamped.save
<ide> assert_not_nil stamped.created_at
<ide> assert_not_nil stamped.updated_at
<del>
<add>
<ide> old_updated_at = stamped.updated_at
<ide>
<ide> sleep 1
<del> stamped.save
<add> stamped.save
<ide> assert_not_equal stamped.created_at, stamped.updated_at
<ide> assert_not_equal old_updated_at, stamped.updated_at
<ide>
<ide> def test_create_turned_off
<ide>
<ide> class ListSubTest < Test::Unit::TestCase
<ide> fixtures :mixins
<del>
<add>
<ide> def test_reordering
<del>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4)],
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> mixins(:list_sub_2).move_lower
<del>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_4)],
<add>
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> mixins(:list_sub_2).move_higher
<ide>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4)],
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> mixins(:list_sub_1).move_to_bottom
<ide>
<del> assert_equal [mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4),
<del> mixins(:list_sub_1)],
<add> assert_equal [mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4),
<add> mixins(:list_sub_1)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<ide>
<ide> mixins(:list_sub_1).move_to_top
<ide>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<ide> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<del>
<add>
<add>
<ide> mixins(:list_sub_2).move_to_bottom
<del>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4),
<add>
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4),
<ide> mixins(:list_sub_2)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<ide>
<ide> mixins(:list_sub_4).move_to_top
<ide>
<del> assert_equal [mixins(:list_sub_4),
<del> mixins(:list_sub_1),
<del> mixins(:list_sub_3),
<add> assert_equal [mixins(:list_sub_4),
<add> mixins(:list_sub_1),
<add> mixins(:list_sub_3),
<ide> mixins(:list_sub_2)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> end
<ide>
<ide> def test_move_to_bottom_with_next_to_last_item
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4)],
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<ide>
<ide> mixins(:list_sub_3).move_to_bottom
<ide>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_4),
<del> mixins(:list_sub_3)],
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_4),
<add> mixins(:list_sub_3)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<ide> end
<del>
<add>
<ide> def test_next_prev
<ide> assert_equal mixins(:list_sub_2), mixins(:list_sub_1).lower_item
<ide> assert_nil mixins(:list_sub_1).higher_item
<ide> assert_equal mixins(:list_sub_3), mixins(:list_sub_4).higher_item
<ide> assert_nil mixins(:list_sub_4).lower_item
<ide> end
<del>
<del>
<add>
<add>
<ide> def test_injection
<ide> item = ListMixin.new("parent_id"=>1)
<ide> assert_equal "parent_id = 1", item.scope_condition
<ide> assert_equal "pos", item.position_column
<del> end
<del>
<add> end
<add>
<ide>
<ide> def test_insert_at
<ide> new = ListMixin.create("parent_id" => 20)
<ide> assert_equal 1, new.pos
<ide>
<del> new = ListMixinSub1.create("parent_id" => 20)
<del> assert_equal 2, new.pos
<del>
<del> new = ListMixinSub2.create("parent_id" => 20)
<del> assert_equal 3, new.pos
<add> new = ListMixinSub1.create("parent_id" => 20)
<add> assert_equal 2, new.pos
<add>
<add> new = ListMixinSub2.create("parent_id" => 20)
<add> assert_equal 3, new.pos
<ide>
<del> new4 = ListMixin.create("parent_id" => 20)
<del> assert_equal 4, new4.pos
<add> new4 = ListMixin.create("parent_id" => 20)
<add> assert_equal 4, new4.pos
<add>
<add> new4.insert_at(3)
<add> assert_equal 3, new4.pos
<ide>
<del> new4.insert_at(3)
<del> assert_equal 3, new4.pos
<add> new.reload
<add> assert_equal 4, new.pos
<ide>
<del> new.reload
<del> assert_equal 4, new.pos
<del>
<ide> new.insert_at(2)
<ide> assert_equal 2, new.pos
<ide>
<ide> def test_insert_at
<ide> new4.reload
<ide> assert_equal 5, new4.pos
<ide> end
<del>
<add>
<ide> def test_delete_middle
<del>
<del> assert_equal [mixins(:list_sub_1),
<del> mixins(:list_sub_2),
<del> mixins(:list_sub_3),
<del> mixins(:list_sub_4)],
<add> assert_equal [mixins(:list_sub_1),
<add> mixins(:list_sub_2),
<add> mixins(:list_sub_3),
<add> mixins(:list_sub_4)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> mixins(:list_sub_2).destroy
<del>
<del> assert_equal [mixins(:list_sub_1, :reload),
<del> mixins(:list_sub_3, :reload),
<del> mixins(:list_sub_4, :reload)],
<add>
<add> assert_equal [mixins(:list_sub_1, :reload),
<add> mixins(:list_sub_3, :reload),
<add> mixins(:list_sub_4, :reload)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> assert_equal 1, mixins(:list_sub_1).pos
<ide> assert_equal 2, mixins(:list_sub_3).pos
<ide> assert_equal 3, mixins(:list_sub_4).pos
<ide>
<ide> mixins(:list_sub_1).destroy
<ide>
<del> assert_equal [mixins(:list_sub_3, :reload),
<del> mixins(:list_sub_4, :reload)],
<add> assert_equal [mixins(:list_sub_3, :reload),
<add> mixins(:list_sub_4, :reload)],
<ide> ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos')
<del>
<add>
<ide> assert_equal 1, mixins(:list_sub_3).pos
<ide> assert_equal 2, mixins(:list_sub_4).pos
<del>
<del> end
<add>
<add> end
<ide>
<ide> end
<ide> | 1 |
Go | Go | implement docker load with standalone client lib | 9073a52ea839ef224931e1105bfa9c715ee48e2c | <ide><path>api/client/lib/image_load.go
<add>package lib
<add>
<add>import (
<add> "io"
<add> "net/url"
<add>)
<add>
<add>// ImageLoad loads an image in the docker host from the client host.
<add>// It's up to the caller to close the io.ReadCloser returned by
<add>// this function.
<add>func (cli *Client) ImageLoad(input io.Reader) (io.ReadCloser, error) {
<add> resp, err := cli.POSTRaw("/images/load", url.Values{}, input, nil)
<add> if err != nil {
<add> return nil, err
<add> }
<add> return resp.body, nil
<add>}
<ide><path>api/client/load.go
<ide> func (cli *DockerCli) CmdLoad(args ...string) error {
<ide> cmd := Cli.Subcmd("load", nil, Cli.DockerCommands["load"].Description, true)
<ide> infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN")
<ide> cmd.Require(flag.Exact, 0)
<del>
<ide> cmd.ParseFlags(args, true)
<ide>
<del> var (
<del> input io.Reader = cli.in
<del> err error
<del> )
<add> var input io.Reader = cli.in
<ide> if *infile != "" {
<del> input, err = os.Open(*infile)
<add> file, err := os.Open(*infile)
<ide> if err != nil {
<ide> return err
<ide> }
<add> defer file.Close()
<add> input = file
<ide> }
<del> sopts := &streamOpts{
<del> rawTerminal: true,
<del> in: input,
<del> out: cli.out,
<del> }
<del> if _, err := cli.stream("POST", "/images/load", sopts); err != nil {
<add>
<add> responseBody, err := cli.client.ImageLoad(input)
<add> if err != nil {
<ide> return err
<ide> }
<del> return nil
<add> defer responseBody.Close()
<add>
<add> _, err = io.Copy(cli.out, responseBody)
<add> return err
<ide> } | 2 |
Javascript | Javascript | check parameter type of fs.mkdir() | fdf829eea48206d0a078dba3a0bf9f77c6acb619 | <ide><path>test/parallel/test-fs-mkdir.js
<ide> if (common.isMainThread && (common.isLinux || common.isOSX)) {
<ide> });
<ide> }
<ide>
<add>// mkdirSync and mkdir require options.recursive to be a boolean.
<add>// Anything else generates an error.
<add>{
<add> const pathname = path.join(tmpdir.path, nextdir());
<add> ['', 1, {}, [], null, Symbol('test'), () => {}].forEach((recursive) => {
<add> common.expectsError(
<add> () => fs.mkdir(pathname, { recursive }, common.mustNotCall()),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "recursive" argument must be of type boolean. Received ' +
<add> `type ${typeof recursive}`
<add> }
<add> );
<add> common.expectsError(
<add> () => fs.mkdirSync(pathname, { recursive }),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> type: TypeError,
<add> message: 'The "recursive" argument must be of type boolean. Received ' +
<add> `type ${typeof recursive}`
<add> }
<add> );
<add> });
<add>}
<add>
<ide> // Keep the event loop alive so the async mkdir() requests
<ide> // have a chance to run (since they don't ref the event loop).
<ide> process.nextTick(() => {});
<ide><path>test/parallel/test-fs-promises.js
<ide> function verifyStatObject(stat) {
<ide> assert.deepStrictEqual(list, ['baz2.js', 'dir']);
<ide> await rmdir(newdir);
<ide>
<add> // mkdir when options is number.
<add> {
<add> const dir = path.join(tmpDir, nextdir());
<add> await mkdir(dir, 777);
<add> stats = await stat(dir);
<add> assert(stats.isDirectory());
<add> }
<add>
<add> // mkdir when options is string.
<add> {
<add> const dir = path.join(tmpDir, nextdir());
<add> await mkdir(dir, '777');
<add> stats = await stat(dir);
<add> assert(stats.isDirectory());
<add> }
<add>
<ide> // mkdirp when folder does not yet exist.
<ide> {
<ide> const dir = path.join(tmpDir, nextdir(), nextdir());
<ide> function verifyStatObject(stat) {
<ide> assert(stats.isDirectory());
<ide> }
<ide>
<add> // mkdirp require recursive option to be a boolean.
<add> // Anything else generates an error.
<add> {
<add> const dir = path.join(tmpDir, nextdir(), nextdir());
<add> ['', 1, {}, [], null, Symbol('test'), () => {}].forEach((recursive) => {
<add> assert.rejects(
<add> // mkdir() expects to get a boolean value for options.recursive.
<add> async () => mkdir(dir, { recursive }),
<add> {
<add> code: 'ERR_INVALID_ARG_TYPE',
<add> name: 'TypeError [ERR_INVALID_ARG_TYPE]',
<add> message: 'The "recursive" argument must be of type boolean. ' +
<add> `Received type ${typeof recursive}`
<add> }
<add> );
<add> });
<add> }
<add>
<ide> await mkdtemp(path.resolve(tmpDir, 'FOO'));
<ide> assert.rejects(
<ide> // mkdtemp() expects to get a string prefix. | 2 |
Ruby | Ruby | use constant for encoding | b0f1cd8719c2c75ebeddb376312fa4bf8c1c9c22 | <ide><path>actionpack/lib/action_dispatch/http/parameters.rb
<ide> def normalize_encode_params(params)
<ide>
<ide> new_hash = {}
<ide> params.each do |k, v|
<del> new_key = k.is_a?(String) ? k.dup.force_encoding("UTF-8").encode! : k
<add> new_key = k.is_a?(String) ? k.dup.force_encoding(Encoding::UTF_8).encode! : k
<ide> new_hash[new_key] =
<ide> case v
<ide> when Hash | 1 |
Ruby | Ruby | remove dead abort_tests method | 9339db70c65219c2c575771e5c6a0fd58ee69316 | <ide><path>actionpack/test/active_record_unit.rb
<ide> def run(*args)
<ide> # Default so Test::Unit::TestCase doesn't complain
<ide> def test_truth
<ide> end
<del>
<del> private
<del> # If things go wrong, we don't want to run our test cases. We'll just define them to test nothing.
<del> def abort_tests
<del> $stderr.puts 'No Active Record connection, aborting tests.'
<del> self.class.public_instance_methods.grep(/^test./).each do |method|
<del> self.class.class_eval { define_method(method.to_sym){} }
<del> end
<del> end
<ide> end
<ide>
<ide> ActiveRecordTestConnector.setup | 1 |
PHP | PHP | fix cs errors | 4e52941f59b9f2b3786f16262260df96794fc1e2 | <ide><path>lib/Cake/Console/ConsoleOptionParser.php
<ide> public function addSubcommand($name, $options = array()) {
<ide> * @param string $name The subcommand name to remove.
<ide> * @return $this
<ide> */
<del> public function removeSubcommand($name) {
<del> unset($this->_subcommands[$name]);
<del> return $this;
<del> }
<add> public function removeSubcommand($name) {
<add> unset($this->_subcommands[$name]);
<add> return $this;
<add> }
<ide>
<ide> /**
<ide> * Add multiple subcommands at once.
<ide><path>lib/Cake/Test/Case/Console/ConsoleOptionParserTest.php
<ide> public function testAddSubcommandObject() {
<ide> *
<ide> * @return void
<ide> */
<del> public function testRemoveSubcommand() {
<del> $parser = new ConsoleOptionParser('test', false);
<del> $parser->addSubcommand(new ConsoleInputSubcommand('test'));
<del> $result = $parser->subcommands();
<del> $this->assertEquals(1, count($result));
<del> $parser->removeSubcommand('test');
<del> $result = $parser->subcommands();
<del> $this->assertEquals(0, count($result), 'Remove a subcommand does not work');
<del> }
<add> public function testRemoveSubcommand() {
<add> $parser = new ConsoleOptionParser('test', false);
<add> $parser->addSubcommand(new ConsoleInputSubcommand('test'));
<add> $result = $parser->subcommands();
<add> $this->assertEquals(1, count($result));
<add> $parser->removeSubcommand('test');
<add> $result = $parser->subcommands();
<add> $this->assertEquals(0, count($result), 'Remove a subcommand does not work');
<add> }
<ide>
<ide> /**
<ide> * test adding multiple subcommands | 2 |
Javascript | Javascript | integrate relayconnection with rnfeed | 09a34f4d0fdcbd428bda39d215ec0c637e3fe03a | <ide><path>Libraries/Components/ScrollResponder.js
<ide> var Dimensions = require('Dimensions');
<ide> var Platform = require('Platform');
<ide> var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<del>var React = require('React');
<ide> var ReactNative = require('ReactNative');
<ide> var Subscribable = require('Subscribable');
<ide> var TextInputState = require('TextInputState');
<ide> var UIManager = require('UIManager');
<ide> var { ScrollViewManager } = require('NativeModules');
<ide>
<ide> var invariant = require('fbjs/lib/invariant');
<del>var warning = require('fbjs/lib/warning');
<del>
<del>import type ReactComponent from 'ReactComponent';
<ide>
<ide> /**
<ide> * Mixin that can be integrated in order to handle scrolling that plays well
<ide><path>Libraries/Experimental/WindowedListView.js
<ide> type Props = {
<ide> * A simple array of data blobs that are passed to the renderRow function in
<ide> * order. Note there is no dataSource like in the standard `ListView`.
<ide> */
<del> data: Array<mixed>;
<add> data: Array<any>;
<ide> /**
<ide> * Takes a data blob from the `data` array prop plus some meta info and should
<ide> * return a row.
<ide> */
<ide> renderRow: (
<del> data: mixed, sectionIdx: number, rowIdx: number, key?: string
<add> data: any, sectionIdx: number, rowIdx: number, key?: string
<ide> ) => ?ReactElement;
<ide> /**
<ide> * Rendered when the list is scrolled faster than rows can be rendered.
<ide> type Props = {
<ide> /**
<ide> * Used to log perf events for async row rendering.
<ide> */
<del> asyncRowPerfEventName: ?string;
<add> asyncRowPerfEventName?: string;
<ide> /**
<ide> * A function that returns the scrollable component in which the list rows
<ide> * are rendered. Defaults to returning a ScrollView with the given props.
<ide> type Props = {
<ide> * Called when rows will be mounted/unmounted. Mounted rows always form a contiguous block so it is expressed as a
<ide> * range of start plus count.
<ide> */
<del> onMountedRowsWillChange: (firstIdx: number, count: number) => void;
<add> onMountedRowsWillChange?: (firstIdx: number, count: number) => void;
<add>};
<add>
<add>type State = {
<add> boundaryIndicatorHeight?: number;
<add> firstRow: number;
<add> lastRow: number;
<add> firstVisible: number;
<add> lastVisible: number;
<ide> };
<ide> class WindowedListView extends React.Component {
<ide> props: Props;
<del> state: {
<del> boundaryIndicatorHeight?: number;
<del> firstRow: number;
<del> lastRow: number;
<del> firstVisible: number;
<del> lastVisible: number;
<del> };
<add> state: State;
<ide> _scrollOffsetY: number = 0;
<ide> _frameHeight: number = 0;
<ide> _rowFrames: Array<Object> = [];
<ide> class WindowedListView extends React.Component {
<ide> const layoutPrev = this._rowFrames[rowIndex] || {};
<ide> console.log(
<ide> 'record layout for row: ',
<del> {i: rowIndex, h: layout.height, y: layout.y, hp: layoutPrev.height, yp: layoutPrev.y}
<add> {i: rowIndex, h: layout.height, y: layout.y, x: layout.x, hp: layoutPrev.height, yp: layoutPrev.y}
<ide> );
<ide> }
<ide> this._rowFrames[rowIndex] = {...layout, offscreenLayoutDone: true};
<ide> class WindowedListView extends React.Component {
<ide> this._hasCalledOnEndReached = this.state.lastRow === lastRow;
<ide> }
<ide> }
<del> if (this.state.firstRow !== firstRow || this.state.lastRow !== lastRow) {
<add> this.setState({firstRow, lastRow});
<add> }
<add> componentDidUpdate(prevProps: Props, prevState: State) {
<add> const {firstRow, lastRow} = this.state;
<add> if (firstRow !== prevState.firstRow || lastRow !== prevState.lastRow) {
<ide> this.props.onMountedRowsWillChange && this.props.onMountedRowsWillChange(firstRow, lastRow - firstRow + 1);
<ide> console.log('WLV: row render range changed:', {firstRow, lastRow});
<ide> }
<del> this.setState({firstRow, lastRow});
<add> if (this.props.onVisibleRowsChanged) {
<add> const {firstVisible, lastVisible} = this.state;
<add> if (firstVisible !== prevState.firstVisible ||
<add> lastVisible !== prevState.lastVisible) {
<add> this.props.onVisibleRowsChanged(firstVisible, lastVisible - lastVisible + 1);
<add> }
<add> }
<ide> }
<ide> _updateVisibleRows(newFirstVisible: number, newLastVisible: number) {
<ide> if (this.state.firstVisible !== newFirstVisible ||
<ide> this.state.lastVisible !== newLastVisible) {
<del> if (this.props.onVisibleRowsChanged) {
<del> this.props.onVisibleRowsChanged(
<del> newFirstVisible,
<del> newLastVisible - newFirstVisible + 1);
<del> }
<ide> this.setState({
<ide> firstVisible: newFirstVisible,
<ide> lastVisible: newLastVisible, | 2 |
Text | Text | fix broken links in readme | 293db49b7f5969d11d5599f97bd968dbe64c7f8b | <ide><path>README.md
<ide> MiniMagick supported transformation.
<ide>
<ide> ## Compared to other storage solutions
<ide>
<del>A key difference to how Active Storage works compared to other attachment solutions in Rails is through the use of built-in [Blob](https://github.com/rails/activestorage/blob/master/lib/active_storage/blob.rb) and [Attachment](https://github.com/rails/activestorage/blob/master/lib/active_storage/attachment.rb) models (backed by Active Record). This means existing application models do not need to be modified with additional columns to associate with files. Active Storage uses polymorphic associations via the join model of `Attachment`, which then connects to the actual `Blob`.
<add>A key difference to how Active Storage works compared to other attachment solutions in Rails is through the use of built-in [Blob](https://github.com/rails/activestorage/blob/master/app/models/active_storage/blob.rb) and [Attachment](https://github.com/rails/activestorage/blob/master/app/models/active_storage/attachment.rb) models (backed by Active Record). This means existing application models do not need to be modified with additional columns to associate with files. Active Storage uses polymorphic associations via the join model of `Attachment`, which then connects to the actual `Blob`.
<ide>
<ide> These `Blob` models are intended to be immutable in spirit. One file, one blob. You can associate the same blob with multiple application models as well. And if you want to do transformations of a given `Blob`, the idea is that you'll simply create a new one, rather than attempt to mutate the existing (though of course you can delete that later if you don't need it).
<ide> | 1 |
Python | Python | fix 2/3 problem for json save/load | cd33b39a04c52e288c9a6e9a1043a29f72cf6527 | <ide><path>spacy/language.py
<ide> from contextlib import contextmanager
<ide> import shutil
<ide>
<del>import ujson as json
<add>import ujson
<ide>
<ide>
<ide> try:
<ide> basestring
<ide> except NameError:
<ide> basestring = str
<ide>
<add>try:
<add> unicode
<add>except NameError:
<add> unicode = str
<ide>
<ide> from .tokenizer import Tokenizer
<ide> from .vocab import Vocab
<ide> def train(cls, path, gold_tuples, *configs):
<ide> parser_cfg['actions'] = ArcEager.get_actions(gold_parses=gold_tuples)
<ide> entity_cfg['actions'] = BiluoPushDown.get_actions(gold_parses=gold_tuples)
<ide>
<del> with (dep_model_dir / 'config.json').open('w') as file_:
<del> json.dump(parser_cfg, file_)
<del> with (ner_model_dir / 'config.json').open('w') as file_:
<del> json.dump(entity_cfg, file_)
<del> with (pos_model_dir / 'config.json').open('w') as file_:
<del> json.dump(tagger_cfg, file_)
<add> with (dep_model_dir / 'config.json').open('wb') as file_:
<add> data = ujson.dumps(parser_cfg)
<add> if isinstance(data, unicode):
<add> data = data.encode('utf8')
<add> file_.write(data)
<add> with (ner_model_dir / 'config.json').open('wb') as file_:
<add> data = ujson.dumps(entity_cfg)
<add> if isinstance(data, unicode):
<add> data = data.encode('utf8')
<add> file_.write(data)
<add> with (pos_model_dir / 'config.json').open('wb') as file_:
<add> data = ujson.dumps(tagger_cfg)
<add> if isinstance(data, unicode):
<add> data = data.encode('utf8')
<add> file_.write(data)
<ide>
<ide> self = cls(
<ide> path=path,
<ide> def end_training(self, path=None):
<ide> else:
<ide> entity_iob_freqs = []
<ide> entity_type_freqs = []
<del> with (path / 'vocab' / 'serializer.json').open('w') as file_:
<del> file_.write(
<del> json.dumps([
<del> (TAG, tagger_freqs),
<del> (DEP, dep_freqs),
<del> (ENT_IOB, entity_iob_freqs),
<del> (ENT_TYPE, entity_type_freqs),
<del> (HEAD, head_freqs)
<del> ]))
<add> with (path / 'vocab' / 'serializer.json').open('wb') as file_:
<add> data = ujson.dumps([
<add> (TAG, tagger_freqs),
<add> (DEP, dep_freqs),
<add> (ENT_IOB, entity_iob_freqs),
<add> (ENT_TYPE, entity_type_freqs),
<add> (HEAD, head_freqs)
<add> ])
<add> if isinstance(data, unicode):
<add> data = data.encode('utf8')
<add> file_.write(data) | 1 |
Go | Go | fix health test | 1f09adbe163f008e36dffa45c8f4b43605d7426e | <ide><path>integration-cli/docker_cli_health_test.go
<ide> func (s *DockerSuite) TestHealth(c *check.C) {
<ide> buildImageSuccessfully(c, "no_healthcheck", build.WithDockerfile(`FROM testhealth
<ide> HEALTHCHECK NONE`))
<ide>
<del> out, _ = dockerCmd(c, "inspect", "--format={{.ContainerConfig.Healthcheck.Test}}", "no_healthcheck")
<add> out, _ = dockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "no_healthcheck")
<ide> c.Check(out, checker.Equals, "[NONE]\n")
<ide>
<ide> // Enable the checks from the CLI | 1 |
Java | Java | remove the action0 overloads | c799e525680e95744a129b427df16791bfad02a1 | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public <TKey, TValue, TDuration> Observable<GroupedObservable<TKey, TValue>> gro
<ide> return create(new OperationGroupByUntil<T, TKey, TValue, TDuration>(this, keySelector, valueSelector, durationSelector));
<ide> }
<ide>
<del> /**
<del> * Invokes the action asynchronously, surfacing the result through an observable sequence.
<del> * <p>
<del> * Note: The action is called immediately, not during the subscription of the resulting
<del> * sequence. Multiple subscriptions to the resulting sequence can observe the
<del> * action's outcome.
<del> *
<del> * @param action
<del> * Action to run asynchronously.
<del> * @return An observable sequence exposing a null value upon completion of the action,
<del> * or an exception.
<del> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229265(v=vs.103).aspx">MSDN: Observable.Start</a>
<del> */
<del> public static Observable<Void> start(Action0 action) {
<del> return Async.toAsync(action).call();
<del> }
<del>
<del> /**
<del> * Invokes the action asynchronously on the specified scheduler, surfacing the
<del> * result through an observable sequence.
<del> * <p>
<del> * Note: The action is called immediately, not during the subscription of the resulting
<del> * sequence. Multiple subscriptions to the resulting sequence can observe the
<del> * action's outcome.
<del> *
<del> * @param action
<del> * Action to run asynchronously.
<del> * @param scheduler
<del> * Scheduler to run the function on.
<del> * @return An observable sequence exposing a null value upon completion of the action,
<del> * or an exception.
<del> * @see <a href="http://msdn.microsoft.com/en-us/library/hh211971(v=vs.103).aspx">MSDN: Observable.Start</a>
<del> */
<del> public static Observable<Void> start(Action0 action, Scheduler scheduler) {
<del> return Async.toAsync(action, scheduler).call();
<del> }
<del>
<ide> /**
<ide> * Invokes the specified function asynchronously, surfacing the result through an observable sequence.
<ide> * <p>
<ide><path>rxjava-core/src/test/java/rx/ObservableTests.java
<ide> public void testRangeWithScheduler() {
<ide> inOrder.verifyNoMoreInteractions();
<ide> }
<ide>
<del> @Test
<del> public void testStartWithAction() {
<del> Action0 action = mock(Action0.class);
<del> assertEquals(null, Observable.start(action).toBlockingObservable().single());
<del> }
<del>
<del> @Test(expected = RuntimeException.class)
<del> public void testStartWithActionError() {
<del> Action0 action = new Action0() {
<del> @Override
<del> public void call() {
<del> throw new RuntimeException("Some error");
<del> }
<del> };
<del> Observable.start(action).toBlockingObservable().single();
<del> }
<del>
<del> @Test
<del> public void testStartWhenSubscribeRunBeforeAction() {
<del> TestScheduler scheduler = new TestScheduler();
<del>
<del> Action0 action = mock(Action0.class);
<del>
<del> Observable<Void> observable = Observable.start(action, scheduler);
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Void> observer = mock(Observer.class);
<del> observable.subscribe(observer);
<del>
<del> InOrder inOrder = inOrder(observer);
<del> inOrder.verifyNoMoreInteractions();
<del>
<del> // Run action
<del> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS);
<del>
<del> inOrder.verify(observer, times(1)).onNext(null);
<del> inOrder.verify(observer, times(1)).onCompleted();
<del> inOrder.verifyNoMoreInteractions();
<del> }
<del>
<del> @Test
<del> public void testStartWhenSubscribeRunAfterAction() {
<del> TestScheduler scheduler = new TestScheduler();
<del>
<del> Action0 action = mock(Action0.class);
<del>
<del> Observable<Void> observable = Observable.start(action, scheduler);
<del>
<del> // Run action
<del> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS);
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Void> observer = mock(Observer.class);
<del> observable.subscribe(observer);
<del>
<del> InOrder inOrder = inOrder(observer);
<del> inOrder.verify(observer, times(1)).onNext(null);
<del> inOrder.verify(observer, times(1)).onCompleted();
<del> inOrder.verifyNoMoreInteractions();
<del> }
<del>
<del> @Test
<del> public void testStartWithActionAndMultipleObservers() {
<del> TestScheduler scheduler = new TestScheduler();
<del>
<del> Action0 action = mock(Action0.class);
<del>
<del> Observable<Void> observable = Observable.start(action, scheduler);
<del>
<del> scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS);
<del>
<del> @SuppressWarnings("unchecked")
<del> Observer<Void> observer1 = mock(Observer.class);
<del> @SuppressWarnings("unchecked")
<del> Observer<Void> observer2 = mock(Observer.class);
<del> @SuppressWarnings("unchecked")
<del> Observer<Void> observer3 = mock(Observer.class);
<del>
<del> observable.subscribe(observer1);
<del> observable.subscribe(observer2);
<del> observable.subscribe(observer3);
<del>
<del> InOrder inOrder;
<del> inOrder = inOrder(observer1);
<del> inOrder.verify(observer1, times(1)).onNext(null);
<del> inOrder.verify(observer1, times(1)).onCompleted();
<del> inOrder.verifyNoMoreInteractions();
<del>
<del> inOrder = inOrder(observer2);
<del> inOrder.verify(observer2, times(1)).onNext(null);
<del> inOrder.verify(observer2, times(1)).onCompleted();
<del> inOrder.verifyNoMoreInteractions();
<del>
<del> inOrder = inOrder(observer3);
<del> inOrder.verify(observer3, times(1)).onNext(null);
<del> inOrder.verify(observer3, times(1)).onCompleted();
<del> inOrder.verifyNoMoreInteractions();
<del>
<del> verify(action, times(1)).call();
<del> }
<del>
<ide> @Test
<ide> public void testStartWithFunc() {
<ide> Func0<String> func = new Func0<String>() { | 2 |
Java | Java | normalize start and end args | 2ad3bb2e2d62ffb780bab020f645626a16dd3b4a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java
<ide> public void onSelectionChanged(int start, int end) {
<ide> // Android will call us back for both the SELECTION_START span and SELECTION_END span in text
<ide> // To prevent double calling back into js we cache the result of the previous call and only
<ide> // forward it on if we have new values
<del> if (mPreviousSelectionStart != start || mPreviousSelectionEnd != end) {
<add>
<add> // Apparently Android might call this with an end value that is less than the start value
<add> // Lets normalize them. See https://github.com/facebook/react-native/issues/18579
<add> int realStart = Math.min(start, end);
<add> int realEnd = Math.max(start, end);
<add>
<add> if (mPreviousSelectionStart != realStart || mPreviousSelectionEnd != realEnd) {
<ide> mEventDispatcher.dispatchEvent(
<ide> new ReactTextInputSelectionEvent(
<ide> mReactEditText.getId(),
<del> start,
<del> end
<add> realStart,
<add> realEnd
<ide> ));
<ide>
<del> mPreviousSelectionStart = start;
<del> mPreviousSelectionEnd = end;
<add> mPreviousSelectionStart = realStart;
<add> mPreviousSelectionEnd = realEnd;
<ide> }
<ide> }
<ide> } | 1 |
Text | Text | create an article of error handling with go | b1a5c3679749c6033dc214aadd481ab45df42d3b | <ide><path>guide/english/go/go-errors/index.md
<add>---
<add>title: Go Errors
<add>---
<add># Go Errors
<add>
<add>Go has a built-in error interface that looks like:
<add>
<add>```go
<add>type error interface {
<add> Error() string
<add>}
<add>```
<add>Therefore anything that implements the `Error() string` can be used as an error.
<add>
<add># Checking errors
<add>
<add>A typical practice is to have functions return an error value. For example the `Print()` function from the fmt package is:
<add>
<add>```go
<add>func Print(a ...interface{}) (n int, err error)
<add>```
<add>
<add>It returns the number of bytes written as well as an error. If there was no error in printing then error will be nil. To check errors we'd use something like this:
<add>
<add>```go
<add>num, err := fmt.Print("Hello\n")
<add>if err != nil {
<add> log.Fatal(err)
<add>}
<add>fmt.Println(num)
<add>```
<add>We check if an error occured then handle it using `log.Fatal()` . This prints the error and exits. If no error was found we'd continue on to print the number of bytes written by `Print()`
<add>
<add># Creating Errors
<add>
<add>You can create errors of your own to use as needed:
<add>
<add>```go
<add>// common convention to use all lowercase in error messages
<add>err := errors.New("oh no something terrible went wrong")
<add>if err != nil {
<add> log.Fatal(err)
<add>}
<add>```
<add>This error could also be returned from a function if something went wrong in that function:
<add>
<add>```go
<add>// largeNumberAddThree adds three to a value only is it's larger than 100
<add>func largeNumberAddThree(arg int) (int, error) {
<add> if arg < 100 {
<add> return -1, errors.New("oh no that isn't large enough") // return an error when arg is too small
<add> }
<add> return arg + 3, nil // return a nil error
<add>}
<add>
<add>func main() {
<add> x := 99 // 99 will return an error
<add> y, err := largeNumberAddThree(x)
<add> if err != nil {
<add> log.Fatal(err)
<add> }
<add> fmt.Println(y)
<add>}
<add>```
<add># Panic
<add>
<add>Go also includes a `panic()` method. When a function reaches a panic it's operation stops to crash the program. Any message inside the `panic("message")` will be printed.
<add>There is also a `recover()` method that can be used to recover from a `panic()` if the `recover()` was defered earlier in execution.
<add>
<add>Using panic shouldn't be used for in place of error handling. panic should only be used for an unrecoverable error where the program cannot simply continue its execution. | 1 |
Javascript | Javascript | check bytelength in readuint(b|l)e | 9fea7eae9a48c6c2e8fb75204a4e5c60e700a3e2 | <ide><path>benchmark/buffers/buffer-read-with-byteLength.js
<ide> const common = require('../common.js');
<ide>
<ide> const types = [
<del> 'IntLE',
<ide> 'IntBE',
<add> 'IntLE',
<add> 'UIntBE',
<add> 'UIntLE'
<ide> ];
<ide>
<ide> const bench = common.createBenchmark(main, {
<ide><path>lib/buffer.js
<ide> Buffer.prototype.readUIntLE =
<ide> function readUIntLE(offset, byteLength, noAssert) {
<ide> offset = offset >>> 0;
<ide> byteLength = byteLength >>> 0;
<del> if (!noAssert)
<add> if (!noAssert) {
<add> checkByteLength(byteLength);
<ide> checkOffset(offset, byteLength, this.length);
<add> }
<ide>
<ide> var val = this[offset];
<ide> var mul = 1;
<ide> Buffer.prototype.readUIntBE =
<ide> function readUIntBE(offset, byteLength, noAssert) {
<ide> offset = offset >>> 0;
<ide> byteLength = byteLength >>> 0;
<del> if (!noAssert)
<add> if (!noAssert) {
<add> checkByteLength(byteLength);
<ide> checkOffset(offset, byteLength, this.length);
<add> }
<ide>
<ide> var val = this[offset + --byteLength];
<ide> var mul = 1;
<ide><path>test/parallel/test-buffer-read.js
<ide> read(buf, 'readUInt32BE', [1], 0xfd48eacf);
<ide> read(buf, 'readUInt32LE', [1], 0xcfea48fd);
<ide>
<ide> // testing basic functionality of readUIntBE() and readUIntLE()
<del>read(buf, 'readUIntBE', [2, 0], 0xfd);
<del>read(buf, 'readUIntLE', [2, 0], 0x48);
<add>read(buf, 'readUIntBE', [2, 2], 0x48ea);
<add>read(buf, 'readUIntLE', [2, 2], 0xea48);
<add>
<add>// invalid byteLength parameter for readUIntBE() and readUIntLE()
<add>common.expectsError(() => { buf.readUIntBE(2, 0); },
<add> { code: 'ERR_OUT_OF_RANGE' });
<add>common.expectsError(() => { buf.readUIntLE(2, 7); },
<add> { code: 'ERR_OUT_OF_RANGE' });
<ide>
<ide> // attempt to overflow buffers, similar to previous bug in array buffers
<ide> assert.throws(() => Buffer.allocUnsafe(8).readFloatBE(0xffffffff), | 3 |
Javascript | Javascript | continue work on user migration | 83c14cccc454419dcbfd415fa438189da89c7831 | <ide><path>models/User.js
<ide> var userSchema = new mongoose.Schema({
<ide> default: ''
<ide> }
<ide> },
<del>
<add> challengesHash: {},
<ide> portfolio: {
<ide> website1Link: {
<ide> type: String,
<ide> var userSchema = new mongoose.Schema({
<ide> longestStreak: {
<ide> type: Number,
<ide> default: 0
<del> }
<add> },
<add> needsMigration: { type: Boolean, default: true }
<ide> });
<ide>
<ide> /**
<ide><path>seed_data/userMigration.js
<ide> var mongoClient = new MongoClient(new Server('localhost', 27017), {native_parser
<ide> var mongoose = require('mongoose');
<ide> mongoose.connect(secrets.db);
<ide>
<del>User.find(function(err, users) {
<del> if (err) { console.log(err) }
<del> users.forEach(function(user) {
<del> console.log('in users');
<del> if (typeof user.challengesHash !== 'undefined') {
<del> var oldChallenges = Object.keys(user.challengesHash).filter(function (challenge) {
<del> return user.challengesHash[challenge];
<del> }).map(function (data) {
<del> return ({
<del> challengeNum: data,
<del> timeStamp: user.challengesHash[data]
<del> });
<del> });
<del> oldChallenges.forEach(function (challenge) {
<del> user.progressTimestamps.push(challenge.timeStamp);
<del> });
<del> newChallenges = newChallenges.filter(function (elem) {
<del> return elem.newId;
<del> });
<del> console.log(newChallenges);
<del> }
<del> });
<add>var stream = User.find( { needsMigration: true }).batchSize(10000).stream();
<add>stream.on('data', function(user) {
<add> console.log('test');
<add> user.needsMigration = true;
<add> user.save();
<add>}).on('error', function(err) {
<add> console.log(err);
<add>}).on('close', function() {
<add> console.log('done with set');
<ide> });
<add> //console.log(typeof(user.challengesHash));
<add> //if (user.challengesHash && typeof(user.challengesHash) === Object) {
<add> // var oldChallenges = Object.keys(user.challengesHash).filter(function (challenge) {
<add> // console.log(challenge);
<add> // return user.challengesHash[challenge];
<add> // }).map(function (data) {
<add> // return ({
<add> // challengeNum: data,
<add> // timeStamp: user.challengesHash[data]
<add> // });
<add> // });
<add> // oldChallenges.forEach(function (challenge) {
<add> // user.progressTimestamps.push(challenge.timeStamp);
<add> // });
<add> // newChallenges = newChallenges.filter(function (elem) {
<add> // return elem.newId;
<add> // });
<add> // console.log(newChallenges);
<add> //});
<add>//}); | 2 |
Text | Text | add missing example | 542343752ea588f46370cff9cc20278a102cdf7e | <ide><path>threejs/lessons/threejs-post-processing-3dlut.md
<ide> Note that Adobe LUTs are not designed for online usage. They are large files. Yo
<ide>
<ide> The sample below is just a modification of the code above. We only draw the background picture, no glTF file. That picture is the an identity lut image created from the script above. We then use the effect to apply whatever LUT file is loaded so the result is the image we'd need to reproduce the LUT file as a PNG.
<ide>
<del><script src="resources/threejs-post-processing-3dlut.js"></script>
<add>{{{example url="../threejs-postprocessing-adobe-lut-to-png-converter.html" }}}
<ide>
<ide> One thing completely skipped is how the shader itself works. Hopefully we can cover a little more GLSL in the future. For now, if you're curious, you can follow the links in the [post processing article](threejs-post-processing.html) as well as maybe [take a look at this video](https://www.youtube.com/watch?v=rfQ8rKGTVlg#t=24m30s).
<add>
<add><script src="resources/threejs-post-processing-3dlut.js"></script>
<add> | 1 |
Go | Go | remove stray import comment | 200edf803043ede28f61234ca3bd494834c65f9d | <ide><path>libcontainerd/remote/client_io_windows.go
<ide> import (
<ide> "github.com/containerd/containerd/cio"
<ide> "github.com/pkg/errors"
<ide> "github.com/sirupsen/logrus"
<del> // "golang.org/x/net/context"
<ide> )
<ide>
<ide> type delayedConnection struct { | 1 |
Text | Text | remove jscs-loader from readme as it is abandoned | dc58017ff8ddbcdc28cd0ebf17b69ab113856381 | <ide><path>README.md
<ide> or are automatically applied via regex from your webpack configuration.
<ide> |<a href="https://github.com/webpack/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|Tests with mocha (Browser/NodeJS)|
<ide> |<a href="https://github.com/MoOx/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|PreLoader for linting code using ESLint|
<ide> |<a href="https://github.com/webpack/jslint-loader"><img width="48" height="48" src="http://jshint.com/res/jshint-dark.png"></a>|![jshint-npm]|PreLoader for linting code using JSHint|
<del>|<a href="https://github.com/unindented/jscs-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/jscs.svg"></a>|![jscs-npm]|PreLoader for code style checking using JSCS|
<del>
<ide>
<ide> [mocha-npm]: https://img.shields.io/npm/v/mocha-loader.svg
<ide> [eslint-npm]: https://img.shields.io/npm/v/eslint-loader.svg | 1 |
Java | Java | fix broken test in springjunit4concurrencytests | 4e65c10272a97e063389fa8b171b80d3f873ff56 | <ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/concurrency/SpringJUnit4ConcurrencyTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.test.context.junit4.concurrency;
<ide>
<add>import java.lang.annotation.Annotation;
<add>import java.lang.reflect.Method;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.stream.IntStream;
<add>
<add>import org.junit.BeforeClass;
<add>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide> import org.junit.experimental.ParallelComputer;
<ide>
<ide> import org.springframework.test.web.servlet.samples.context.WebAppResourceTests;
<ide> import org.springframework.tests.Assume;
<ide> import org.springframework.tests.TestGroup;
<add>import org.springframework.util.ReflectionUtils;
<ide>
<del>import static org.springframework.test.context.junit4.JUnitTestingUtils.runTestsAndAssertCounters;
<add>import static java.util.stream.Collectors.*;
<add>import static org.springframework.core.annotation.AnnotatedElementUtils.*;
<add>import static org.springframework.test.context.junit4.JUnitTestingUtils.*;
<ide>
<ide> /**
<ide> * Concurrency tests for the {@link SpringRunner}, {@link SpringClassRule}, and
<ide> public class SpringJUnit4ConcurrencyTests {
<ide>
<ide> // @formatter:off
<del> private static final Class<?>[] testClasses = new Class[] {
<add> private final Class<?>[] testClasses = new Class[] {
<ide> // Basics
<del> /* 9 */ SpringJUnit4ClassRunnerAppCtxTests.class,
<del> /* 9 */ InheritedConfigSpringJUnit4ClassRunnerAppCtxTests.class,
<del> /* 2 */ SpringJUnit47ClassRunnerRuleTests.class,
<del> /* 2 */ ParameterizedSpringRuleTests.class,
<add> SpringJUnit4ClassRunnerAppCtxTests.class,
<add> InheritedConfigSpringJUnit4ClassRunnerAppCtxTests.class,
<add> SpringJUnit47ClassRunnerRuleTests.class,
<add> ParameterizedSpringRuleTests.class,
<ide> // Transactional
<del> /* 2 */ MethodLevelTransactionalSpringRunnerTests.class,
<del> /* 4 */ TimedTransactionalSpringRunnerTests.class,
<add> MethodLevelTransactionalSpringRunnerTests.class,
<add> TimedTransactionalSpringRunnerTests.class,
<ide> // Web and Scopes
<del> /* 1 */ DispatcherWacRootWacEarTests.class, /* 2 ignored */
<del> /* 3 */ BasicAnnotationConfigWacSpringRuleTests.class,
<del> /* 2 */ RequestAndSessionScopedBeansWacTests.class,
<del> /* 1 */ WebSocketServletServerContainerFactoryBeanTests.class,
<add> DispatcherWacRootWacEarTests.class,
<add> BasicAnnotationConfigWacSpringRuleTests.class,
<add> RequestAndSessionScopedBeansWacTests.class,
<add> WebSocketServletServerContainerFactoryBeanTests.class,
<ide> // Spring MVC Test
<del> /* 2 */ JavaConfigTests.class,
<del> /* 3 */ WebAppResourceTests.class,
<del> /* 4 */ SampleTests.class
<add> JavaConfigTests.class,
<add> WebAppResourceTests.class,
<add> SampleTests.class
<ide> };
<ide> // @formatter:on
<ide>
<del> /**
<del> * The number of tests in all {@link #testClasses}.
<del> *
<del> * <p>The current number of tests per test class is tracked as a comment
<del> * before each class reference above. The following constant must therefore
<del> * be the sum of those values.
<del> *
<del> * <p>This is admittedly fragile, but there's unfortunately not really a
<del> * better way to count the number of tests without re-implementing JUnit 4's
<del> * discovery algorithm. Plus, the presence of parameterized tests makes it
<del> * even more difficult to count programmatically.
<del> */
<del> private static final int TESTS = 44;
<del> private static final int FAILED = 0;
<del> private static final int IGNORED = 2;
<del> private static final int ABORTED = 0;
<del>
<add> @BeforeClass
<add> public static void abortIfLongRunningTestGroupIsNotEnabled() {
<add> Assume.group(TestGroup.LONG_RUNNING);
<add> }
<ide>
<ide> @Test
<ide> public void runAllTestsConcurrently() throws Exception {
<del>
<del> Assume.group(TestGroup.LONG_RUNNING);
<add> final int FAILED = 0;
<add> final int ABORTED = 0;
<add> final int IGNORED = countAnnotatedMethods(Ignore.class);
<add> // +1 since ParameterizedSpringRuleTests is parameterized
<add> final int TESTS = countAnnotatedMethods(Test.class) + 1 - IGNORED;
<ide>
<ide> runTestsAndAssertCounters(new ParallelComputer(true, true), TESTS, FAILED, TESTS, IGNORED, ABORTED,
<del> testClasses);
<add> this.testClasses);
<add> }
<add>
<add> private int countAnnotatedMethods(Class<? extends Annotation> annotationType) {
<add> return Arrays.stream(this.testClasses)
<add> .map(testClass -> getAnnotatedMethods(testClass, annotationType))
<add> .flatMapToInt(list -> IntStream.of(list.size()))
<add> .sum();
<add> }
<add>
<add> private List<Method> getAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotationType) {
<add> return Arrays.stream(ReflectionUtils.getUniqueDeclaredMethods(clazz))
<add> .filter(method -> hasAnnotation(method, annotationType))
<add> .collect(toList());
<ide> }
<ide>
<ide> } | 1 |
PHP | PHP | fix examples around prefix casing | 41f5cf3c4aae084453bcc65485166ec77a5d804f | <ide><path>src/Routing/RouteBuilder.php
<ide> public function namePrefix(?string $value = null): string
<ide> * Admin prefix:
<ide> *
<ide> * ```
<del> * Router::prefix('admin', function ($routes) {
<add> * Router::prefix('Admin', function ($routes) {
<ide> * $routes->resources('Articles');
<ide> * });
<ide> * ```
<ide> public function redirect(string $route, $url, array $options = []): Route
<ide> * for $params argument:
<ide> *
<ide> * ```
<del> * $route->prefix('api', function($route) {
<del> * $route->prefix('v10', ['path' => '/v1.0'], function($route) {
<add> * $route->prefix('Api', function($route) {
<add> * $route->prefix('V10', ['path' => '/v1.0'], function($route) {
<ide> * // Translates to `Controller\Api\V10\` namespace
<ide> * });
<ide> * });
<ide><path>src/Routing/Router.php
<ide> public static function scope(string $path, $params = [], $callback = null): void
<ide> * relevant prefix information.
<ide> *
<ide> * The path parameter is used to generate the routing parameter name.
<del> * For example a path of `admin` would result in `'prefix' => 'admin'` being
<add> * For example a path of `admin` would result in `'prefix' => 'Admin'` being
<ide> * applied to all connected routes.
<ide> *
<ide> * The prefix name will be inflected to the dasherized version to create
<ide> * the routing path. If you want a custom path name, use the `path` option.
<ide> *
<ide> * You can re-open a prefix as many times as necessary, as well as nest prefixes.
<del> * Nested prefixes will result in prefix values like `admin/api` which translates
<add> * Nested prefixes will result in prefix values like `Admin/Api` which translates
<ide> * to the `Controller\Admin\Api\` namespace.
<ide> *
<ide> * @param string $name The prefix name to use.
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public function testRedirectWithCustomRouteClass()
<ide> public function testPrefix()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/path', ['key' => 'value']);
<del> $res = $routes->prefix('admin', ['param' => 'value'], function ($r) {
<add> $res = $routes->prefix('admin', ['param' => 'value'], function (RouteBuilder $r) {
<ide> $this->assertInstanceOf(RouteBuilder::class, $r);
<ide> $this->assertCount(0, $this->collection->routes());
<ide> $this->assertSame('/path/admin', $r->path());
<ide> public function testPrefix()
<ide> public function testPrefixWithNoParams()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/path', ['key' => 'value']);
<del> $res = $routes->prefix('admin', function ($r) {
<add> $res = $routes->prefix('admin', function (RouteBuilder $r) {
<ide> $this->assertInstanceOf(RouteBuilder::class, $r);
<ide> $this->assertCount(0, $this->collection->routes());
<ide> $this->assertSame('/path/admin', $r->path());
<ide> public function testPrefixWithNoParams()
<ide> public function testNestedPrefix()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
<del> $res = $routes->prefix('api', ['_namePrefix' => 'api:'], function ($r) {
<add> $res = $routes->prefix('api', ['_namePrefix' => 'api:'], function (RouteBuilder $r) {
<ide> $this->assertSame('/admin/api', $r->path());
<ide> $this->assertEquals(['prefix' => 'admin/Api'], $r->params());
<ide> $this->assertSame('api:', $r->namePrefix());
<ide> public function testNestedPrefix()
<ide> */
<ide> public function testPathWithDotInPrefix()
<ide> {
<del> $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'admin']);
<del> $res = $routes->prefix('api', function ($r) {
<del> $r->prefix('v10', ['path' => '/v1.0'], function ($r2) {
<add> $routes = new RouteBuilder($this->collection, '/admin', ['prefix' => 'Admin']);
<add> $res = $routes->prefix('Api', function (RouteBuilder $r) {
<add> $r->prefix('v10', ['path' => '/v1.0'], function (RouteBuilder $r2) {
<ide> $this->assertSame('/admin/api/v1.0', $r2->path());
<del> $this->assertEquals(['prefix' => 'admin/Api/V10'], $r2->params());
<del> $r2->prefix('b1', ['path' => '/beta.1'], function ($r3) {
<add> $this->assertEquals(['prefix' => 'Admin/Api/V10'], $r2->params());
<add> $r2->prefix('b1', ['path' => '/beta.1'], function (RouteBuilder $r3) {
<ide> $this->assertSame('/admin/api/v1.0/beta.1', $r3->path());
<del> $this->assertEquals(['prefix' => 'admin/Api/V10/B1'], $r3->params());
<add> $this->assertEquals(['prefix' => 'Admin/Api/V10/B1'], $r3->params());
<ide> });
<ide> });
<ide> });
<ide> public function testPathWithDotInPrefix()
<ide> public function testNestedPlugin()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
<del> $res = $routes->plugin('Contacts', function ($r) {
<add> $res = $routes->plugin('Contacts', function (RouteBuilder $r) {
<ide> $this->assertSame('/b/contacts', $r->path());
<ide> $this->assertEquals(['plugin' => 'Contacts', 'key' => 'value'], $r->params());
<ide>
<ide> public function testNestedPlugin()
<ide> public function testNestedPluginPathOption()
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/b', ['key' => 'value']);
<del> $routes->plugin('Contacts', ['path' => '/people'], function ($r) {
<add> $routes->plugin('Contacts', ['path' => '/people'], function (RouteBuilder $r) {
<ide> $this->assertSame('/b/people', $r->path());
<ide> $this->assertEquals(['plugin' => 'Contacts', 'key' => 'value'], $r->params());
<ide> }); | 3 |
Javascript | Javascript | remove instatwatchers and use map for lookup | 8841132f30e2e35c2dcc6c724f1507aa3e1c1175 | <ide><path>lib/fs.js
<ide> StatWatcher.prototype.stop = function() {
<ide> };
<ide>
<ide>
<del>var statWatchers = {};
<del>function inStatWatchers(filename) {
<del> return Object.prototype.hasOwnProperty.call(statWatchers, filename) &&
<del> statWatchers[filename];
<del>}
<del>
<add>const statWatchers = new Map();
<ide>
<ide> fs.watchFile = function(filename) {
<ide> nullCheck(filename);
<ide> fs.watchFile = function(filename) {
<ide> throw new Error('watchFile requires a listener function');
<ide> }
<ide>
<del> if (inStatWatchers(filename)) {
<del> stat = statWatchers[filename];
<del> } else {
<del> stat = statWatchers[filename] = new StatWatcher();
<add> stat = statWatchers.get(filename);
<add>
<add> if (stat === undefined) {
<add> stat = new StatWatcher();
<ide> stat.start(filename, options.persistent, options.interval);
<add> statWatchers.set(filename, stat);
<ide> }
<add>
<ide> stat.addListener('change', listener);
<ide> return stat;
<ide> };
<ide>
<ide> fs.unwatchFile = function(filename, listener) {
<ide> nullCheck(filename);
<ide> filename = pathModule.resolve(filename);
<del> if (!inStatWatchers(filename)) return;
<add> var stat = statWatchers.get(filename);
<ide>
<del> var stat = statWatchers[filename];
<add> if (stat === undefined) return;
<ide>
<ide> if (typeof listener === 'function') {
<ide> stat.removeListener('change', listener);
<ide> fs.unwatchFile = function(filename, listener) {
<ide>
<ide> if (EventEmitter.listenerCount(stat, 'change') === 0) {
<ide> stat.stop();
<del> statWatchers[filename] = undefined;
<add> statWatchers.delete(filename);
<ide> }
<ide> };
<ide> | 1 |
Ruby | Ruby | avoid array#to_s and array(nil) | 7ad461b44dabb586fbad190493ac4ecd96104597 | <ide><path>activesupport/lib/active_support/vendor/i18n-0.1.3/lib/i18n.rb
<ide> def default_exception_handler(exception, locale, key, options)
<ide> # Merges the given locale, key and scope into a single array of keys.
<ide> # Splits keys that contain dots into multiple keys. Makes sure all
<ide> # keys are Symbols.
<del> def normalize_translation_keys(locale, key, scope)
<del> keys = [locale] + Array(scope) + [key]
<del> keys = keys.map { |k| k.to_s.split(/\./) }
<del> keys.flatten.map { |k| k.to_sym }
<add> def normalize_translation_keys(*keys)
<add> normalized = []
<add> keys.each do |key|
<add> case key
<add> when Array
<add> normalized.concat normalize_translation_keys(*key)
<add> when nil
<add> # skip
<add> else
<add> normalized.concat key.to_s.split('.').map { |sub| sub.to_sym }
<add> end
<add> end
<add> normalized
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | fix cases where cte's are not supported | 3c7e190ee8e3474e4ddf00ae0ac3a7c21d6f3d41 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def _select!(*fields) # :nodoc:
<ide>
<ide> # Add a Common Table Expression (CTE) that you can then reference within another SELECT statement.
<ide> #
<add> # Note: CTE's are only supported in MySQL for versions 8.0 and above. You will not be able to
<add> # use CTE's with MySQL 5.7.
<add> #
<ide> # Post.with(posts_with_tags: Post.where("tags_count > ?", 0))
<ide> # # => ActiveRecord::Relation
<ide> # # WITH posts_with_tags AS (
<ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> class MergingDifferentRelationsTest < ActiveRecord::TestCase
<ide> assert_equal dev.ratings, [rating_1]
<ide> end
<ide>
<del> test "merging relation with common table expression" do
<del> posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0")).from("posts_with_tags AS posts")
<del> posts_with_comments = Post.where("legacy_comments_count > 0")
<del> relation = posts_with_comments.merge(posts_with_tags).order("posts.id")
<add> if ActiveRecord::Base.connection.supports_common_table_expressions?
<add> test "merging relation with common table expression" do
<add> posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0")).from("posts_with_tags AS posts")
<add> posts_with_comments = Post.where("legacy_comments_count > 0")
<add> relation = posts_with_comments.merge(posts_with_tags).order("posts.id")
<ide>
<del> assert_equal [1, 2, 7], relation.pluck(:id)
<del> end
<add> assert_equal [1, 2, 7], relation.pluck(:id)
<add> end
<ide>
<del> test "merging multiple relations with common table expression" do
<del> posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0"))
<del> posts_with_comments = Post.with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<del> relation = posts_with_comments.merge(posts_with_tags)
<del> .joins("JOIN posts_with_tags pwt ON pwt.id = posts.id JOIN posts_with_comments pwc ON pwc.id = posts.id").order("posts.id")
<add> test "merging multiple relations with common table expression" do
<add> posts_with_tags = Post.with(posts_with_tags: Post.where("tags_count > 0"))
<add> posts_with_comments = Post.with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<add> relation = posts_with_comments.merge(posts_with_tags)
<add> .joins("JOIN posts_with_tags pwt ON pwt.id = posts.id JOIN posts_with_comments pwc ON pwc.id = posts.id").order("posts.id")
<ide>
<del> assert_equal [1, 2, 7], relation.pluck(:id)
<del> end
<add> assert_equal [1, 2, 7], relation.pluck(:id)
<add> end
<ide>
<del> test "relation merger leaves to database to decide what to do when multiple CTEs with same alias are passed" do
<del> posts_with_tags = Post.with(popular_posts: Post.where("tags_count > 0"))
<del> posts_with_comments = Post.with(popular_posts: Post.where("legacy_comments_count > 0"))
<del> relation = posts_with_tags.merge(posts_with_comments).joins("JOIN popular_posts pp ON pp.id = posts.id")
<add> test "relation merger leaves to database to decide what to do when multiple CTEs with same alias are passed" do
<add> posts_with_tags = Post.with(popular_posts: Post.where("tags_count > 0"))
<add> posts_with_comments = Post.with(popular_posts: Post.where("legacy_comments_count > 0"))
<add> relation = posts_with_tags.merge(posts_with_comments).joins("JOIN popular_posts pp ON pp.id = posts.id")
<ide>
<del> assert_raises ActiveRecord::StatementInvalid do
<del> relation.load
<add> assert_raises ActiveRecord::StatementInvalid do
<add> relation.load
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/relation/with_test.rb
<ide> class WithTest < ActiveRecord::TestCase
<ide> POSTS_WITH_TAGS_AND_COMMENTS = (POSTS_WITH_COMMENTS & POSTS_WITH_TAGS).sort.freeze
<ide> POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS = (POSTS_WITH_MULTIPLE_COMMENTS & POSTS_WITH_TAGS).sort.freeze
<ide>
<del> def test_with_when_hash_is_passed_as_an_argument
<del> relation = Post
<del> .with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<del> .from("posts_with_comments AS posts")
<add> if ActiveRecord::Base.connection.supports_common_table_expressions?
<add> def test_with_when_hash_is_passed_as_an_argument
<add> relation = Post
<add> .with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<add> .from("posts_with_comments AS posts")
<ide>
<del> assert_equal POSTS_WITH_COMMENTS, relation.order(:id).pluck(:id)
<del> end
<add> assert_equal POSTS_WITH_COMMENTS, relation.order(:id).pluck(:id)
<add> end
<ide>
<del> def test_with_when_hash_with_multiple_elements_of_different_type_is_passed_as_an_argument
<del> cte_options = {
<del> posts_with_tags: Post.arel_table.project(Arel.star).where(Post.arel_table[:tags_count].gt(0)),
<del> posts_with_tags_and_comments: Arel.sql("SELECT * FROM posts_with_tags WHERE legacy_comments_count > 0"),
<del> "posts_with_tags_and_multiple_comments" => Post.where("legacy_comments_count > 1").from("posts_with_tags_and_comments AS posts")
<del> }
<del> relation = Post.with(cte_options).from("posts_with_tags_and_multiple_comments AS posts")
<add> def test_with_when_hash_with_multiple_elements_of_different_type_is_passed_as_an_argument
<add> cte_options = {
<add> posts_with_tags: Post.arel_table.project(Arel.star).where(Post.arel_table[:tags_count].gt(0)),
<add> posts_with_tags_and_comments: Arel.sql("SELECT * FROM posts_with_tags WHERE legacy_comments_count > 0"),
<add> "posts_with_tags_and_multiple_comments" => Post.where("legacy_comments_count > 1").from("posts_with_tags_and_comments AS posts")
<add> }
<add> relation = Post.with(cte_options).from("posts_with_tags_and_multiple_comments AS posts")
<ide>
<del> assert_equal POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS, relation.order(:id).pluck(:id)
<del> end
<add> assert_equal POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS, relation.order(:id).pluck(:id)
<add> end
<ide>
<del> def test_multiple_with_calls
<del> relation = Post
<del> .with(posts_with_tags: Post.where("tags_count > 0"))
<del> .from("posts_with_tags_and_comments AS posts")
<del> .with(posts_with_tags_and_comments: Arel.sql("SELECT * FROM posts_with_tags WHERE legacy_comments_count > 0"))
<add> def test_multiple_with_calls
<add> relation = Post
<add> .with(posts_with_tags: Post.where("tags_count > 0"))
<add> .from("posts_with_tags_and_comments AS posts")
<add> .with(posts_with_tags_and_comments: Arel.sql("SELECT * FROM posts_with_tags WHERE legacy_comments_count > 0"))
<ide>
<del> assert_equal POSTS_WITH_TAGS_AND_COMMENTS, relation.order(:id).pluck(:id)
<del> end
<add> assert_equal POSTS_WITH_TAGS_AND_COMMENTS, relation.order(:id).pluck(:id)
<add> end
<ide>
<del> def test_count_after_with_call
<del> relation = Post.with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<add> def test_count_after_with_call
<add> relation = Post.with(posts_with_comments: Post.where("legacy_comments_count > 0"))
<ide>
<del> assert_equal Post.count, relation.count
<del> assert_equal POSTS_WITH_COMMENTS.size, relation.from("posts_with_comments AS posts").count
<del> assert_equal POSTS_WITH_COMMENTS.size, relation.joins("JOIN posts_with_comments ON posts_with_comments.id = posts.id").count
<del> end
<add> assert_equal Post.count, relation.count
<add> assert_equal POSTS_WITH_COMMENTS.size, relation.from("posts_with_comments AS posts").count
<add> assert_equal POSTS_WITH_COMMENTS.size, relation.joins("JOIN posts_with_comments ON posts_with_comments.id = posts.id").count
<add> end
<ide>
<del> def test_with_when_called_from_active_record_scope
<del> assert_equal POSTS_WITH_TAGS, Post.with_tags_cte.order(:id).pluck(:id)
<del> end
<add> def test_with_when_called_from_active_record_scope
<add> assert_equal POSTS_WITH_TAGS, Post.with_tags_cte.order(:id).pluck(:id)
<add> end
<ide>
<del> def test_with_when_invalid_params_are_passed
<del> assert_raise(ArgumentError) { Post.with }
<del> assert_raise(ArgumentError) { Post.with(posts_with_tags: nil).load }
<del> assert_raise(ArgumentError) { Post.with(posts_with_tags: [Post.where("tags_count > 0")]).load }
<add> def test_with_when_invalid_params_are_passed
<add> assert_raise(ArgumentError) { Post.with }
<add> assert_raise(ArgumentError) { Post.with(posts_with_tags: nil).load }
<add> assert_raise(ArgumentError) { Post.with(posts_with_tags: [Post.where("tags_count > 0")]).load }
<add> end
<add> else
<add> def test_common_table_expressions_are_unsupported
<add> assert_raises ActiveRecord::StatementInvalid do
<add> Post.with_tags_cte.order(:id).pluck(:id)
<add> end
<add> end
<ide> end
<ide> end
<ide> end | 3 |
Python | Python | add a comment | 619645e1ab37eea5b2f980f08ce2c2aa69b1183d | <ide><path>libcloud/compute/drivers/gce.py
<ide> def create_node(
<ide> ex_preemptible=None, ex_image_family=None, ex_labels=None,
<ide> ex_accelerator_type=None, ex_accelerator_count=None,
<ide> ex_disk_size=None, auth=None):
<add> # NOTE: "auth" argument is unused, but it's needed for "deploy_node()"
<add> # functionality to work
<ide> """
<ide> Create a new node and return a node object for the node.
<ide> | 1 |
Javascript | Javascript | add test for path.normalize with unc paths | a475e62a3e6bcec3be6ff03f1c4bdbf5b188065c | <ide><path>test/simple/test-path.js
<ide> if (isWindows) {
<ide> assert.equal(path.normalize('a//b//../b'), 'a\\b');
<ide> assert.equal(path.normalize('a//b//./c'), 'a\\b\\c');
<ide> assert.equal(path.normalize('a//b//.'), 'a\\b');
<add> assert.equal(path.normalize('//server/share/dir/file.ext'),
<add> '\\\\server\\share\\dir\\file.ext');
<ide> } else {
<ide> assert.equal(path.normalize('./fixtures///b/../b/c.js'),
<ide> 'fixtures/b/c.js'); | 1 |
Ruby | Ruby | remove unused field | 7c24ff19d56b73051b3e7f8f6f3fd0a8b325dcb6 | <ide><path>Library/Homebrew/cli/args.rb
<ide> def freeze_named_args!(named_args)
<ide> @resolved_formulae = nil
<ide> @formulae_paths = nil
<ide> @casks = nil
<del> @formulae_and_casks = nil
<ide> @kegs = nil
<ide>
<ide> self[:named_args] = named_args | 1 |
Ruby | Ruby | find the layout earlier | c52fa675b8784c1bcdc996a353a44922443b0b9f | <ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def initialize(*)
<ide> @context_prefix = @lookup_context.prefixes.first
<ide> end
<ide>
<del> def template_keys
<del> if @has_object || @collection
<del> @locals.keys + retrieve_variable(@path, @as)
<del> else
<del> @locals.keys
<del> end
<del> end
<del>
<ide> def render(context, options, block)
<del> @as = as_variable(options)
<del> setup(context, options, @as)
<add> as = as_variable(options)
<add> setup(context, options, as)
<ide>
<ide> if @path
<del> template = find_template(@path, template_keys)
<add> template = find_template(@path, template_keys(@path, as))
<ide> else
<ide> if options[:cached]
<ide> raise NotImplementedError, "render caching requires a template. Please specify a partial when rendering"
<ide> end
<ide> template = nil
<ide> end
<ide>
<add> if !block && (layout = @options[:layout])
<add> layout = find_template(layout.to_s, template_keys(@path, as))
<add> end
<add>
<ide> if @collection
<del> render_collection(context, template)
<add> render_collection(context, template, layout)
<ide> else
<del> render_partial(context, template, block)
<add> render_partial(context, template, layout, block)
<ide> end
<ide> end
<ide>
<ide> private
<del> def render_collection(view, template)
<add> def template_keys(path, as)
<add> if @has_object || @collection
<add> @locals.keys + retrieve_variable(path, as)
<add> else
<add> @locals.keys
<add> end
<add> end
<add>
<add> def render_collection(view, template, layout)
<ide> identifier = (template && template.identifier) || @path
<ide> instrument(:collection, identifier: identifier, count: @collection.size) do |payload|
<ide> return RenderedCollection.empty(@lookup_context.formats.first) if @collection.blank?
<ide> def render_collection(view, template)
<ide>
<ide> collection_body = if template
<ide> cache_collection_render(payload, view, template, @collection) do |collection|
<del> collection_with_template(view, template, collection)
<add> collection_with_template(view, template, layout, collection)
<ide> end
<ide> else
<del> collection_with_template(view, nil, @collection)
<add> collection_with_template(view, nil, layout, @collection)
<ide> end
<ide> build_rendered_collection(collection_body, spacer)
<ide> end
<ide> end
<ide>
<del> def render_partial(view, template, block)
<add> def render_partial(view, template, layout, block)
<ide> instrument(:partial, identifier: template.identifier) do |payload|
<ide> locals = @locals
<ide> as = template.variable
<ide> object = @object
<ide>
<del> if !block && (layout = @options[:layout])
<del> layout = find_template(layout.to_s, template_keys)
<del> end
<del>
<ide> locals[as] = object if @has_object
<ide>
<ide> content = template.render(view, locals) do |*name|
<ide> def find_template(path, locals)
<ide> @lookup_context.find_template(path, prefixes, true, locals, @details)
<ide> end
<ide>
<del> def collection_with_template(view, template, collection)
<add> def collection_with_template(view, template, layout, collection)
<ide> locals, collection_data = @locals, @collection_data
<del> cache = {}
<del>
<del> if layout = @options[:layout]
<del> layout = find_template(layout, template_keys)
<del> end
<add> cache = template || {}
<ide>
<ide> partial_iteration = PartialIteration.new(collection.size)
<ide>
<ide><path>activerecord/lib/active_record/railties/collection_cache_association_loading.rb
<ide> def relation_from_options(partial, collection)
<ide> end
<ide> end
<ide>
<del> def collection_with_template(_, _, collection)
<add> def collection_with_template(_, _, _, collection)
<ide> @relation.preload_associations(collection) if @relation
<ide> super
<ide> end | 2 |
Text | Text | fix noun vs. verb and more rewording | bfebb0013ecc27e1289c693476ed621cc76f8a95 | <ide><path>docs/recipes/reducers/PrerequisiteConcepts.md
<ide> As described in [Reducers](../../basics/Reducers.md), a Redux reducer function:
<ide> - Should be "pure", which means the reducer:
<ide> - Does not _perform side effects_ (such as calling API's or modifying non-local objects or variables).
<ide> - Does not _call non-pure functions_ (like `Date.now` or `Math.random`).
<del> - Does not _mutate_ its arguments. If the reducer updates state, it should do so in an ***"immutable"*** fashion. In other words, the reducer should return a **new** object with the updated data rather than _modifying_ the **existing** state object _in-place_. The same approach should be used for any sub-objects within state that the reducer updates.
<add> - Does not _mutate_ its arguments. If the reducer updates state, it should not _modify_ the **existing** state object in-place. Instead, it should generate a **new** object containing the necessary changes. The same approach should be used for any sub-objects within state that the reducer updates.
<ide>
<ide> >##### Note on immutability, side effects, and mutation
<ide> > Mutation is discouraged because it generally breaks time-travel debugging, and React Redux's `connect` function: | 1 |
Javascript | Javascript | prevent browser crashes with scope or window | f43c226c67ab64ee056615567e51f976c7637127 | <ide><path>src/Angular.js
<ide> function isWindow(obj) {
<ide> return obj && obj.document && obj.location && obj.alert && obj.setInterval;
<ide> }
<ide>
<add>
<add>function isScope(obj) {
<add> return obj && obj.$evalAsync && obj.$watch;
<add>}
<add>
<add>
<ide> function isBoolean(value) {return typeof value == $boolean;}
<ide> function isTextNode(node) {return nodeName_(node) == '#text';}
<ide>
<ide> function isLeafNode (node) {
<ide> * @returns {*} The copy or updated `destination`, if `destination` was specified.
<ide> */
<ide> function copy(source, destination){
<add> if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
<ide> if (!destination) {
<ide> destination = source;
<ide> if (source) {
<ide> function copy(source, destination){
<ide> * During a property comparision, properties of `function` type and properties with names
<ide> * that begin with `$` are ignored.
<ide> *
<del> * Note: This function is used to augment the Object type in Angular expressions. See
<del> * {@link angular.module.ng.$filter} for more information about Angular arrays.
<add> * Scope and DOMWindow objects are being compared only be identify (`===`).
<ide> *
<ide> * @param {*} o1 Object or value to compare.
<ide> * @param {*} o2 Object or value to compare.
<ide> function equals(o1, o2) {
<ide> return true;
<ide> }
<ide> } else {
<add> if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
<ide> keySet = {};
<ide> for(key in o1) {
<ide> if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(copy(123)).toEqual(123);
<ide> expect(copy([{key:null}])).toEqual([{key:null}]);
<ide> });
<add>
<add> it('should throw an exception if a Scope is being copied', inject(function($rootScope) {
<add> expect(function() { copy($rootScope.$new()); }).toThrow("Can't copy Window or Scope");
<add> }));
<add>
<add> it('should throw an exception if a Window is being copied', function() {
<add> expect(function() { copy(window); }).toThrow("Can't copy Window or Scope");
<add> });
<ide> });
<ide>
<ide> describe('equals', function() {
<ide> describe('angular', function() {
<ide> it('should treat two NaNs as equal', function() {
<ide> expect(equals(NaN, NaN)).toBe(true);
<ide> });
<add>
<add> it('should compare Scope instances only by identity', inject(function($rootScope) {
<add> var scope1 = $rootScope.$new(),
<add> scope2 = $rootScope.$new();
<add>
<add> expect(equals(scope1, scope1)).toBe(true);
<add> expect(equals(scope1, scope2)).toBe(false);
<add> expect(equals($rootScope, scope1)).toBe(false);
<add> expect(equals(undefined, scope1)).toBe(false);
<add> }));
<add>
<add> it('should compare Window instances only by identity', function() {
<add> expect(equals(window, window)).toBe(true);
<add> expect(equals(window, window.parent)).toBe(false);
<add> expect(equals(window, undefined)).toBe(false);
<add> });
<ide> });
<ide>
<ide> describe('size', function() { | 2 |
Go | Go | retain sandbox only if network is not available | 1452fc31d4f687d5f933efda72de8669c0c6663d | <ide><path>libnetwork/sandbox.go
<ide> func (sb *sandbox) Delete() error {
<ide> continue
<ide> }
<ide>
<del> if err := ep.Leave(sb); err != nil {
<add> // Retain the sanbdox if we can't obtain the network from store.
<add> if _, err := c.getNetworkFromStore(ep.getNetwork().ID()); err != nil {
<ide> retain = true
<add> log.Warnf("Failed getting network for ep %s during sandbox %s delete: %v", ep.ID(), sb.ID(), err)
<add> continue
<add> }
<add>
<add> if err := ep.Leave(sb); err != nil {
<ide> log.Warnf("Failed detaching sandbox %s from endpoint %s: %v\n", sb.ID(), ep.ID(), err)
<ide> }
<ide>
<ide> if err := ep.Delete(); err != nil {
<del> retain = true
<ide> log.Warnf("Failed deleting endpoint %s: %v\n", ep.ID(), err)
<ide> }
<ide> }
<ide> func (sb *sandbox) populateNetworkResources(ep *endpoint) error {
<ide> i := ep.iface
<ide> ep.Unlock()
<ide>
<del> if i.srcName != "" {
<add> if i != nil && i.srcName != "" {
<ide> var ifaceOptions []osl.IfaceOption
<ide>
<ide> ifaceOptions = append(ifaceOptions, sb.osSbox.InterfaceOptions().Address(i.addr), sb.osSbox.InterfaceOptions().Routes(i.routes))
<ide> func OptionGeneric(generic map[string]interface{}) SandboxOption {
<ide> func (eh epHeap) Len() int { return len(eh) }
<ide>
<ide> func (eh epHeap) Less(i, j int) bool {
<add> var (
<add> cip, cjp int
<add> ok bool
<add> )
<add>
<ide> ci, _ := eh[i].getSandbox()
<ide> cj, _ := eh[j].getSandbox()
<ide>
<ide> func (eh epHeap) Less(i, j int) bool {
<ide> return true
<ide> }
<ide>
<del> cip, ok := ci.epPriority[eh[i].ID()]
<del> if !ok {
<del> cip = 0
<add> if ci != nil {
<add> cip, ok = ci.epPriority[eh[i].ID()]
<add> if !ok {
<add> cip = 0
<add> }
<ide> }
<del> cjp, ok := cj.epPriority[eh[j].ID()]
<del> if !ok {
<del> cjp = 0
<add>
<add> if cj != nil {
<add> cjp, ok = cj.epPriority[eh[j].ID()]
<add> if !ok {
<add> cjp = 0
<add> }
<ide> }
<add>
<ide> if cip == cjp {
<ide> return eh[i].network.Name() < eh[j].network.Name()
<ide> } | 1 |
Python | Python | use int64 format for large integers. | becb96216025a9e030f59f7bbab4e22daa5b0e3f | <ide><path>rest_framework/schemas/openapi.py
<ide> def _map_field(self, field):
<ide> 'items': {},
<ide> }
<ide> if not isinstance(field.child, _UnvalidatedField):
<del> mapping['items'] = {
<del> "type": self._map_field(field.child).get('type')
<add> map_field = self._map_field(field.child)
<add> items = {
<add> "type": map_field.get('type')
<ide> }
<add> if 'format' in map_field:
<add> items['format'] = map_field.get('format')
<add> mapping['items'] = items
<ide> return mapping
<ide>
<ide> # DateField and DateTimeField type is string
<ide> def _map_field(self, field):
<ide> 'type': 'integer'
<ide> }
<ide> self._map_min_max(field, content)
<add> # 2147483647 is max for int32_size, so we use int64 for format
<add> if int(content.get('maximum', 0)) > 2147483647 or int(content.get('minimum', 0)) > 2147483647:
<add> content['format'] = 'int64'
<ide> return content
<ide>
<ide> if isinstance(field, serializers.FileField):
<ide><path>tests/schemas/test_openapi.py
<ide> def test_list_field_mapping(self):
<ide> (serializers.ListField(child=serializers.BooleanField()), {'items': {'type': 'boolean'}, 'type': 'array'}),
<ide> (serializers.ListField(child=serializers.FloatField()), {'items': {'type': 'number'}, 'type': 'array'}),
<ide> (serializers.ListField(child=serializers.CharField()), {'items': {'type': 'string'}, 'type': 'array'}),
<add> (serializers.ListField(child=serializers.IntegerField(max_value=4294967295)),
<add> {'items': {'type': 'integer', 'format': 'int64'}, 'type': 'array'}),
<add> (serializers.IntegerField(min_value=2147483648),
<add> {'type': 'integer', 'minimum': 2147483648, 'format': 'int64'}),
<ide> ]
<ide> for field, mapping in cases:
<ide> with self.subTest(field=field): | 2 |
Javascript | Javascript | remove defaults values to shave a few bytes | af8d49e1f613ed02972b073b3130e685b5dab8c8 | <ide><path>buildin/harmony-module.js
<ide> module.exports = function(originalModule) {
<ide> if(!module.children) module.children = [];
<ide> Object.defineProperty(module, "loaded", {
<ide> enumerable: true,
<del> configurable: false,
<ide> get: function() {
<ide> return module.l;
<ide> }
<ide> });
<ide> Object.defineProperty(module, "id", {
<ide> enumerable: true,
<del> configurable: false,
<ide> get: function() {
<ide> return module.i;
<ide> }
<ide> });
<ide> Object.defineProperty(module, "exports", {
<ide> enumerable: true,
<del> configurable: false,
<del> get: function() {
<del> return undefined;
<del> }
<ide> });
<ide> module.webpackPolyfill = 1;
<ide> }
<ide><path>buildin/module.js
<ide> module.exports = function(module) {
<ide> if(!module.children) module.children = [];
<ide> Object.defineProperty(module, "loaded", {
<ide> enumerable: true,
<del> configurable: false,
<ide> get: function() {
<ide> return module.l;
<ide> }
<ide> });
<ide> Object.defineProperty(module, "id", {
<ide> enumerable: true,
<del> configurable: false,
<ide> get: function() {
<ide> return module.i;
<ide> } | 2 |
Javascript | Javascript | remove third argument from assert.strictequal() | 8d15f69abd6502cedbc64597085bddfd9774b7a5 | <ide><path>test/parallel/test-stream-transform-final.js
<ide> The order things are called
<ide> const t = new stream.Transform({
<ide> objectMode: true,
<ide> transform: common.mustCall(function(chunk, _, next) {
<del> assert.strictEqual(++state, chunk, 'transformCallback part 1');
<add> // transformCallback part 1
<add> assert.strictEqual(++state, chunk);
<ide> this.push(state);
<del> assert.strictEqual(++state, chunk + 2, 'transformCallback part 2');
<add> // transformCallback part 2
<add> assert.strictEqual(++state, chunk + 2);
<ide> process.nextTick(next);
<ide> }, 3),
<ide> final: common.mustCall(function(done) {
<ide> state++;
<del> assert.strictEqual(state, 10, 'finalCallback part 1');
<add> // finalCallback part 1
<add> assert.strictEqual(state, 10);
<ide> setTimeout(function() {
<ide> state++;
<del> assert.strictEqual(state, 11, 'finalCallback part 2');
<add> // finalCallback part 2
<add> assert.strictEqual(state, 11);
<ide> done();
<ide> }, 100);
<ide> }, 1),
<ide> flush: common.mustCall(function(done) {
<ide> state++;
<del> assert.strictEqual(state, 12, 'flushCallback part 1');
<add> // flushCallback part 1
<add> assert.strictEqual(state, 12);
<ide> process.nextTick(function() {
<ide> state++;
<del> assert.strictEqual(state, 15, 'flushCallback part 2');
<add> // flushCallback part 2
<add> assert.strictEqual(state, 15);
<ide> done();
<ide> });
<ide> }, 1)
<ide> });
<ide> t.on('finish', common.mustCall(function() {
<ide> state++;
<del> assert.strictEqual(state, 13, 'finishListener');
<add> // finishListener
<add> assert.strictEqual(state, 13);
<ide> }, 1));
<ide> t.on('end', common.mustCall(function() {
<ide> state++;
<del> assert.strictEqual(state, 16, 'end event');
<add> // end event
<add> assert.strictEqual(state, 16);
<ide> }, 1));
<ide> t.on('data', common.mustCall(function(d) {
<del> assert.strictEqual(++state, d + 1, 'dataListener');
<add> // dataListener
<add> assert.strictEqual(++state, d + 1);
<ide> }, 3));
<ide> t.write(1);
<ide> t.write(4);
<ide> t.end(7, common.mustCall(function() {
<ide> state++;
<del> assert.strictEqual(state, 14, 'endMethodCallback');
<add> // endMethodCallback
<add> assert.strictEqual(state, 14);
<ide> }, 1)); | 1 |
PHP | PHP | add some doc blocks | a393b2093176335bf61c2901e3410715850b693c | <ide><path>lib/Cake/Log/CakeLog.php
<ide> public static function enabled($streamName) {
<ide> }
<ide>
<ide> /**
<del> * Enable stream
<add> * Enable stream. Streams that were previously disabled
<add> * can be re-enabled with this method.
<ide> *
<ide> * @param string $streamName to enable
<ide> * @return void
<ide> public static function enable($streamName) {
<ide> }
<ide>
<ide> /**
<del> * Disable stream
<add> * Disable stream. Disabling a stream will
<add> * prevent that log stream from receiving any messages until
<add> * its re-enabled.
<ide> *
<ide> * @param string $streamName to disable
<ide> * @return void | 1 |
Text | Text | adapt dnsimple logo to system appearance | 753c852eba5ebeb1c0d139a2488cb971198b00c4 | <ide><path>README.md
<ide> Flaky test detection and tracking is provided by [BuildPulse](https://buildpulse
<ide>
<ide> <https://brew.sh>'s DNS is [resolving with DNSimple](https://dnsimple.com/resolving/homebrew).
<ide>
<del>[](https://dnsimple.com/resolving/homebrew)
<add>[](https://dnsimple.com/resolving/homebrew#gh-light-mode-only)
<add>[](https://dnsimple.com/resolving/homebrew#gh-dark-mode-only)
<ide>
<ide> Homebrew is generously supported by [Substack](https://github.com/substackinc), [Randy Reddig](https://github.com/ydnar), [embark-studios](https://github.com/embark-studios), [CodeCrafters](https://github.com/codecrafters-io) and many other users and organisations via [GitHub Sponsors](https://github.com/sponsors/Homebrew).
<ide> | 1 |
Text | Text | change "bash" to "shell" in getting started guide | dda4b24beb0fe6609e566b77aca9bff0247d0d14 | <ide><path>guides/source/getting_started.md
<ide> This is very similar to the `Article` model that you saw earlier. The difference
<ide> is the line `belongs_to :article`, which sets up an Active Record _association_.
<ide> You'll learn a little about associations in the next section of this guide.
<ide>
<del>The (`:references`) keyword used in the bash command is a special data type for models.
<add>The (`:references`) keyword used in the shell command is a special data type for models.
<ide> It creates a new column on your database table with the provided model name appended with an `_id`
<ide> that can hold integer values. To get a better understanding, analyze the
<ide> `db/schema.rb` file after running the migration. | 1 |
Python | Python | use different logger to avoid duplicate log entry | 4f6d24f8658e0896c46e613aa656a853b358c321 | <ide><path>airflow/providers/amazon/aws/hooks/base_aws.py
<ide> def decorator_f(self, *args, **kwargs):
<ide> min_limit = retry_args.get('min', 1)
<ide> max_limit = retry_args.get('max', 1)
<ide> stop_after_delay = retry_args.get('stop_after_delay', 10)
<del> tenacity_logger = tenacity.before_log(self.log, logging.INFO) if self.log else None
<add> tenacity_before_logger = tenacity.before_log(self.log, logging.INFO) if self.log else None
<add> tenacity_after_logger = tenacity.after_log(self.log, logging.INFO) if self.log else None
<ide> default_kwargs = {
<ide> 'wait': tenacity.wait_exponential(multiplier=multiplier, max=max_limit, min=min_limit),
<ide> 'retry': tenacity.retry_if_exception(should_retry),
<ide> 'stop': tenacity.stop_after_delay(stop_after_delay),
<del> 'before': tenacity_logger,
<del> 'after': tenacity_logger,
<add> 'before': tenacity_before_logger,
<add> 'after': tenacity_after_logger,
<ide> }
<ide> return tenacity.retry(**default_kwargs)(fun)(self, *args, **kwargs)
<ide> | 1 |
Python | Python | support decimal types in mysql to gcs | 89aac2bbd0a8162a05bf5e71142f7b94937d2b3d | <ide><path>airflow/contrib/operators/mysql_to_gcs.py
<ide> from airflow.utils import apply_defaults
<ide> from collections import OrderedDict
<ide> from datetime import date, datetime
<add>from decimal import Decimal
<ide> from MySQLdb.constants import FIELD_TYPE
<ide> from tempfile import NamedTemporaryFile
<ide>
<ide> def _write_local_data_files(self, cursor):
<ide> tmp_file_handles = { self.filename.format(file_no): tmp_file_handle }
<ide>
<ide> for row in cursor:
<del> # Convert datetime objects to utc seconds
<del> row = map(lambda v: time.mktime(v.timetuple()) if type(v) in (datetime, date) else v, row)
<add> # Convert datetime objects to utc seconds, and decimals to floats
<add> row = map(self.convert_types, row)
<ide> row_dict = dict(zip(schema, row))
<ide>
<ide> # TODO validate that row isn't > 2MB. BQ enforces a hard row size of 2MB.
<ide> def _upload_to_gcs(self, files_to_upload):
<ide> for object, tmp_file_handle in files_to_upload.items():
<ide> hook.upload(self.bucket, object, tmp_file_handle.name, 'application/json')
<ide>
<add> @classmethod
<add> def convert_types(cls, value):
<add> """
<add> Takes a value from MySQLdb, and converts it to a value that's safe for
<add> JSON/Google cloud storage/BigQuery. Dates are converted to UTC seconds.
<add> Decimals are converted to floats.
<add> """
<add> if type(value) in (datetime, date):
<add> return time.mktime(value.timetuple())
<add> elif isinstance(value, Decimal):
<add> return float(value)
<add> else:
<add> return value
<add>
<ide> @classmethod
<ide> def type_map(cls, mysql_type):
<ide> """
<ide> def type_map(cls, mysql_type):
<ide> FIELD_TYPE.BIT: 'INTEGER',
<ide> FIELD_TYPE.DATETIME: 'TIMESTAMP',
<ide> FIELD_TYPE.DECIMAL: 'FLOAT',
<add> FIELD_TYPE.NEWDECIMAL: 'FLOAT',
<ide> FIELD_TYPE.DOUBLE: 'FLOAT',
<ide> FIELD_TYPE.FLOAT: 'FLOAT',
<ide> FIELD_TYPE.INT24: 'INTEGER', | 1 |
Ruby | Ruby | remove flaky test | 8a0e6a1603ce823eb66cc183a692f722668d9c67 | <ide><path>Library/Homebrew/test/cask/cmd/upgrade_spec.rb
<ide> end
<ide>
<ide> describe "with --greedy it checks additional Casks" do
<del> it 'includes the Casks with "auto_updates true" or "version latest"' do
<del> local_caffeine = Cask::CaskLoader.load("local-caffeine")
<del> local_caffeine_path = Cask::Config.global.appdir.join("Caffeine.app")
<del> auto_updates = Cask::CaskLoader.load("auto-updates")
<del> auto_updates_path = Cask::Config.global.appdir.join("MyFancyApp.app")
<del> local_transmission = Cask::CaskLoader.load("local-transmission")
<del> local_transmission_path = Cask::Config.global.appdir.join("Transmission.app")
<del> version_latest = Cask::CaskLoader.load("version-latest")
<del> version_latest_path_1 = Cask::Config.global.appdir.join("Caffeine Mini.app")
<del> version_latest_path_2 = Cask::Config.global.appdir.join("Caffeine Pro.app")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.2")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.57")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.60")
<del>
<del> expect(version_latest).to be_installed
<del> expect(version_latest_path_1).to be_a_directory
<del> expect(version_latest_path_2).to be_a_directory
<del> expect(version_latest.versions).to include("latest")
<del>
<del> described_class.run("--greedy")
<del>
<del> expect(local_caffeine).to be_installed
<del> expect(local_caffeine_path).to be_a_directory
<del> expect(local_caffeine.versions).to include("1.2.3")
<del>
<del> expect(auto_updates).to be_installed
<del> expect(auto_updates_path).to be_a_directory
<del> expect(auto_updates.versions).to include("2.61")
<del>
<del> expect(local_transmission).to be_installed
<del> expect(local_transmission_path).to be_a_directory
<del> expect(local_transmission.versions).to include("2.61")
<del>
<del> expect(version_latest).to be_installed
<del> expect(version_latest_path_1).to be_a_directory
<del> expect(version_latest_path_2).to be_a_directory
<del> expect(version_latest.versions).to include("latest")
<del> end
<del>
<ide> it 'does not include the Casks with "auto_updates true" when the version did not change' do
<ide> cask = Cask::CaskLoader.load("auto-updates")
<ide> cask_path = cask.config.appdir.join("MyFancyApp.app") | 1 |
PHP | PHP | restore controller section of autoloader | fe218f9b0b9763c37c44acbe07c1b1e42fea458a | <ide><path>laravel/autoloader.php
<ide> protected static function find($class)
<ide>
<ide> return $path;
<ide> }
<add>
<add> // Since not all controllers will be resolved by the controller resolver,
<add> // we will do a quick check in the controller directory for the class.
<add> // For instance, since base controllers would not be resolved by the
<add> // controller class, we will need to resolve them here.
<add> if (strpos($class, '_Controller') !== false)
<add> {
<add> $controller = str_replace(array('_Controller', '_'), array('', '/'), $class);
<add>
<add> if (file_exists($path = strtolower(CONTROLLER_PATH.$controller.EXT)))
<add> {
<add> return $path;
<add> }
<add> }
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file
<ide><path>laravel/routing/controller.php
<ide> use Laravel\Redirect;
<ide> use Laravel\Response;
<ide>
<del>/**
<del> * Register a function on the autoload stack to lazy-load controller files.
<del> * We register this function here to keep the primary autoloader smaller
<del> * since this logic is not needed for every Laravel application.
<del> */
<del>spl_autoload_register(function($controller)
<del>{
<del> if (strpos($controller, '_Controller') !== false)
<del> {
<del> $controller = str_replace(array('_Controller', '_'), array('', '/'), $controller);
<del>
<del> if (file_exists($path = strtolower(CONTROLLER_PATH.$controller.EXT)))
<del> {
<del> return $path;
<del> }
<del> }
<del>});
<del>
<ide> abstract class Controller {
<ide>
<ide> /** | 2 |
Ruby | Ruby | move urls code and add devel urls | 5ef9b8863a59356395a1bc39904083b531117c97 | <ide><path>Library/Homebrew/formula.rb
<ide> def to_hash
<ide> "head" => head&.version&.to_s,
<ide> "bottle" => !bottle_specification.checksums.empty?,
<ide> },
<del> "urls" => {
<del> "stable" => {
<del> "url" => stable.url,
<del> "tag" => stable.specs&.dig(:tag),
<del> "revision" => stable.specs&.dig(:revision),
<del> },
<del> },
<add> "urls" => {},
<ide> "revision" => revision,
<ide> "version_scheme" => version_scheme,
<ide> "bottle" => {},
<ide> def to_hash
<ide> }
<ide> end
<ide> hsh["bottle"][spec_sym] = bottle_info
<add> hsh["urls"][spec_sym] = {
<add> "url" => spec.url,
<add> "tag" => spec.specs[:tag],
<add> "revision" => spec.specs[:revision],
<add> }
<ide> end
<ide>
<ide> hsh["options"] = options.map do |opt| | 1 |
Go | Go | add other binaries to _lib.go | e60e54c12aa65c3c11c27bda3002b361f2c1e90f | <ide><path>dockerversion/version_lib.go
<ide> package dockerversion
<ide> // Default build-time variable for library-import.
<ide> // This file is overridden on build with build-time informations.
<ide> const (
<del> GitCommit string = "library-import"
<del> Version string = "library-import"
<del> BuildTime string = "library-import"
<del> IAmStatic string = "library-import"
<add> GitCommit string = "library-import"
<add> Version string = "library-import"
<add> BuildTime string = "library-import"
<add> IAmStatic string = "library-import"
<add> ContainerdCommitID string = "library-import"
<add> RuncCommitID string = "library-import"
<add> InitCommitID string = "library-import"
<ide> ) | 1 |
Python | Python | restore stderr return value of exec_command | 746fb50d01839c7f002a543424b62da43968725b | <ide><path>numpy/distutils/exec_command.py
<ide> def _exec_command(command, use_shell=None, use_tee = None, **env):
<ide> try:
<ide> proc = subprocess.Popen(command, shell=use_shell, env=env,
<ide> stdout=subprocess.PIPE,
<del> stderr=subprocess.PIPE,
<add> stderr=subprocess.STDOUT,
<ide> universal_newlines=True)
<ide> except EnvironmentError:
<ide> # Return 127, as os.spawn*() and /bin/sh do
<ide> return '', 127
<ide> text, err = proc.communicate()
<del> # Only append stderr if the command failed, as otherwise
<del> # the output may become garbled for parsing
<del> if proc.returncode:
<del> if text:
<del> text += "\n"
<del> text += err
<ide> # Another historical oddity
<ide> if text[-1:] == '\n':
<ide> text = text[:-1] | 1 |
Javascript | Javascript | lint untracked files with `yarn linc` | 158f040d5401d0b84e6cc64c75253a0c57274f5d | <ide><path>scripts/prettier/index.js
<ide>
<ide> const chalk = require('chalk');
<ide> const glob = require('glob');
<del>const execFileSync = require('child_process').execFileSync;
<ide> const prettier = require('prettier');
<ide> const fs = require('fs');
<add>const listChangedFiles = require('../shared/listChangedFiles');
<ide>
<ide> const mode = process.argv[2] || 'check';
<ide> const shouldWrite = mode === 'write' || mode === 'write-changed';
<ide> const config = {
<ide> },
<ide> };
<ide>
<del>function exec(command, args) {
<del> console.log('> ' + [command].concat(args).join(' '));
<del> var options = {
<del> cwd: process.cwd(),
<del> env: process.env,
<del> stdio: 'pipe',
<del> encoding: 'utf-8',
<del> };
<del> return execFileSync(command, args, options);
<del>}
<del>
<del>var mergeBase = exec('git', ['merge-base', 'HEAD', 'master']).trim();
<del>var changedFiles = new Set(
<del> exec('git', [
<del> 'diff',
<del> '-z',
<del> '--name-only',
<del> '--diff-filter=ACMRTUB',
<del> mergeBase,
<del> ]).match(/[^\0]+/g)
<del>);
<del>
<add>var changedFiles = listChangedFiles();
<ide> let didWarn = false;
<ide> let didError = false;
<ide> Object.keys(config).forEach(key => {
<ide><path>scripts/shared/listChangedFiles.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>'use strict';
<add>
<add>const execFileSync = require('child_process').execFileSync;
<add>
<add>const exec = (command, args) => {
<add> console.log('> ' + [command].concat(args).join(' '));
<add> var options = {
<add> cwd: process.cwd(),
<add> env: process.env,
<add> stdio: 'pipe',
<add> encoding: 'utf-8',
<add> };
<add> return execFileSync(command, args, options);
<add>};
<add>const execGitCmd = args =>
<add> exec('git', args)
<add> .trim()
<add> .toString()
<add> .split('\n');
<add>
<add>const mergeBase = execGitCmd(['merge-base', 'HEAD', 'master']);
<add>
<add>const listChangedFiles = () => {
<add> return new Set([
<add> ...execGitCmd(['diff', '--name-only', '--diff-filter=ACMRTUB', mergeBase]),
<add> ...execGitCmd(['ls-files', '--others', '--exclude-standard']),
<add> ]);
<add>};
<add>
<add>module.exports = listChangedFiles;
<ide><path>scripts/tasks/linc.js
<ide> 'use strict';
<ide>
<ide> const lintOnFiles = require('../eslint');
<del>const execFileSync = require('child_process').execFileSync;
<del>const mergeBase = execFileSync('git', ['merge-base', 'HEAD', 'master'], {
<del> stdio: 'pipe',
<del> encoding: 'utf-8',
<del>}).trim();
<del>const changedFiles = execFileSync(
<del> 'git',
<del> ['diff', '--name-only', '--diff-filter=ACMRTUB', mergeBase],
<del> {
<del> stdio: 'pipe',
<del> encoding: 'utf-8',
<del> }
<del>)
<del> .trim()
<del> .toString()
<del> .split('\n');
<add>const listChangedFiles = require('../shared/listChangedFiles');
<add>
<add>const changedFiles = [...listChangedFiles()];
<ide> const jsFiles = changedFiles.filter(file => file.match(/.js$/g));
<ide>
<ide> const report = lintOnFiles(jsFiles); | 3 |
Text | Text | add v3.28.2 to changelog.md | 375dd0f03fd38b4c13d0501742277e58714f6b13 | <ide><path>CHANGELOG.md
<ide> - [#19695](https://github.com/emberjs/ember.js/pull/19695) [CLEANUP] Remove {{partial}}
<ide> - [#19691](https://github.com/emberjs/ember.js/pull/19691) Add build assertion against `{{outlet named}}`
<ide>
<del>### v3.28.1 (August 30, 2021)
<add>## v3.28.2 (October 21, 2021)
<add>
<add>- [glimmerjs/glimmer-vm#1351](https://github.com/glimmerjs/glimmer-vm/pull/1351) Support lexical scope in loose mode
<add>
<add>## v3.28.1 (August 30, 2021)
<ide>
<ide> - [#19733](https://github.com/emberjs/ember.js/pull/19733) [BUGFIX] Ensure that using `routerService.urlFor(...)` and `routerService.recognize(...)` does not error if the router is not fully initialized
<ide> | 1 |
Ruby | Ruby | remove warning of intance variable not initialized | 7f7c09c1f353b1775899d448a00a4eb1330a780c | <ide><path>activesupport/lib/active_support/core_ext/thread.rb
<ide> def thread_variable?(key)
<ide> private
<ide>
<ide> def locals
<del> @locals || LOCK.synchronize { @locals ||= {} }
<add> if defined?(@locals)
<add> @locals
<add> else
<add> LOCK.synchronize { @locals ||= {} }
<add> end
<ide> end
<ide> end unless Thread.instance_methods.include?(:thread_variable_set) | 1 |
Python | Python | fix crash when modelcard is none | 9a50828b5c67198ed25c844955231f56a7b4f2ad | <ide><path>src/transformers/pipelines.py
<ide> def __init__(
<ide> self,
<ide> model,
<ide> tokenizer: PreTrainedTokenizer = None,
<del> modelcard: ModelCard = None,
<add> modelcard: Optional[ModelCard] = None,
<ide> framework: Optional[str] = None,
<ide> args_parser: ArgumentHandler = None,
<ide> device: int = -1,
<ide> def save_pretrained(self, save_directory):
<ide>
<ide> self.model.save_pretrained(save_directory)
<ide> self.tokenizer.save_pretrained(save_directory)
<del> self.modelcard.save_pretrained(save_directory)
<add> if self.modelcard is not None:
<add> self.modelcard.save_pretrained(save_directory)
<ide>
<ide> def transform(self, X):
<ide> """
<ide> def __init__(
<ide> self,
<ide> model,
<ide> tokenizer: PreTrainedTokenizer = None,
<del> modelcard: ModelCard = None,
<add> modelcard: Optional[ModelCard] = None,
<ide> framework: Optional[str] = None,
<ide> args_parser: ArgumentHandler = None,
<ide> device: int = -1,
<ide> def __init__(
<ide> self,
<ide> model,
<ide> tokenizer: PreTrainedTokenizer = None,
<del> modelcard: ModelCard = None,
<add> modelcard: Optional[ModelCard] = None,
<ide> framework: Optional[str] = None,
<ide> args_parser: ArgumentHandler = None,
<ide> device: int = -1,
<ide> def __init__(
<ide> self,
<ide> model,
<ide> tokenizer: PreTrainedTokenizer = None,
<del> modelcard: ModelCard = None,
<add> modelcard: Optional[ModelCard] = None,
<ide> framework: Optional[str] = None,
<ide> args_parser: ArgumentHandler = None,
<ide> device: int = -1,
<ide> def __init__(
<ide> self,
<ide> model,
<ide> tokenizer: Optional[PreTrainedTokenizer],
<del> modelcard: Optional[ModelCard],
<add> modelcard: Optional[ModelCard] = None,
<ide> framework: Optional[str] = None,
<ide> device: int = -1,
<ide> **kwargs | 1 |
Mixed | Text | provide the whole request | 32b99f9358b828daf16236695d041288e4b2f648 | <ide><path>actionpack/CHANGELOG.md
<ide> * `process_action.action_controller` notifications now include the following in their payloads:
<ide>
<del> * `:uuid` - the request's globally-unique ID (the `X-Request-Id` response header by default)
<add> * `:request` - the `ActionDispatch::Request`
<ide> * `:location` - the `Location` response header
<ide>
<ide> *George Claghorn*
<ide><path>actionpack/lib/action_controller/metal/instrumentation.rb
<ide> def process_action(*)
<ide> format: request.format.ref,
<ide> method: request.request_method,
<ide> path: request.fullpath,
<del> uuid: request.uuid
<add> request: request
<ide> }
<ide>
<ide> ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload)
<ide><path>guides/source/active_support_instrumentation.md
<ide> Action Controller
<ide> | `:format` | html/js/json/xml etc |
<ide> | `:method` | HTTP request verb |
<ide> | `:path` | Request path |
<del>| `:uuid` | Globally-unique request ID (X-Request-Id response header) |
<add>| `:request` | The `ActionDispatch::Request` |
<ide> | `:status` | HTTP status code |
<ide> | `:location` | Location response header |
<ide> | `:view_runtime` | Amount spent in view in ms |
<ide> Action Controller
<ide> format: :html,
<ide> method: "GET",
<ide> path: "/posts",
<add> request: #<ActionDispatch::Request:0x00007ff1cb9bd7b8>,
<ide> status: 200,
<ide> view_runtime: 46.848,
<ide> db_runtime: 0.157 | 3 |
Javascript | Javascript | improve error inspection | c041a2ee5bc7c89d846a53e4873dd394c19ec4c4 | <ide><path>lib/util.js
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> // Make error with message first say the error
<ide> base = formatError(value);
<ide> // Wrap the error in brackets in case it has no stack trace.
<del> if (base.indexOf('\n at') === -1) {
<add> const stackStart = base.indexOf('\n at');
<add> if (stackStart === -1) {
<ide> base = `[${base}]`;
<ide> }
<ide> // The message and the stack have to be indented as well!
<ide> function formatValue(ctx, value, recurseTimes) {
<ide> }
<ide> if (keyLength === 0)
<ide> return base;
<add>
<add> if (ctx.compact === false && stackStart !== -1) {
<add> braces[0] += `${base.slice(stackStart)}`;
<add> base = `[${base.slice(0, stackStart)}]`;
<add> }
<ide> } else if (isAnyArrayBuffer(value)) {
<ide> // Fast path for ArrayBuffer and SharedArrayBuffer.
<ide> // Can't do the same for DataView because it has a non-primitive
<ide><path>test/parallel/test-repl-underscore.js
<ide> function testError() {
<ide>
<ide> // The error, both from the original throw and the `_error` echo.
<ide> 'Error: foo',
<del> 'Error: foo',
<add> '[Error: foo]',
<ide>
<ide> // The sync error, with individual property echoes
<ide> /Error: ENOENT: no such file or directory, scandir '.*nonexistent.*'/,
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(util.inspect(-5e-324), '-5e-324');
<ide> const tmp = Error.stackTraceLimit;
<ide> Error.stackTraceLimit = 0;
<ide> const err = new Error('foo');
<del> assert.strictEqual(util.inspect(err), '[Error: foo]');
<add> const err2 = new Error('foo\nbar');
<add> assert.strictEqual(util.inspect(err, { compact: true }), '[Error: foo]');
<ide> assert(err.stack);
<ide> delete err.stack;
<ide> assert(!err.stack);
<del> assert.strictEqual(util.inspect(err), '[Error: foo]');
<add> assert.strictEqual(util.inspect(err, { compact: true }), '[Error: foo]');
<add> assert.strictEqual(
<add> util.inspect(err2, { compact: true }),
<add> '[Error: foo\nbar]'
<add> );
<add>
<add> err.bar = true;
<add> err2.bar = true;
<add>
<add> assert.strictEqual(
<add> util.inspect(err, { compact: true }),
<add> '{ [Error: foo] bar: true }'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err2, { compact: true }),
<add> '{ [Error: foo\nbar] bar: true }'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err, { compact: true, breakLength: 5 }),
<add> '{ [Error: foo]\n bar: true }'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err, { compact: true, breakLength: 1 }),
<add> '{ [Error: foo]\n bar:\n true }'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err2, { compact: true, breakLength: 5 }),
<add> '{ [Error: foo\nbar]\n bar: true }'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err, { compact: false }),
<add> '[Error: foo] {\n bar: true\n}'
<add> );
<add> assert.strictEqual(
<add> util.inspect(err2, { compact: false }),
<add> '[Error: foo\nbar] {\n bar: true\n}'
<add> );
<add>
<ide> Error.stackTraceLimit = tmp;
<ide> }
<ide> | 3 |
Text | Text | move each image to its own line | 1835febfaf9538dab97b14d1fa587bef98c4ac03 | <ide><path>next_frame_prediction/README.md
<ide> Authors: Xin Pan (Github: panyx0718), Anelia Angelova
<ide> <b>Results:</b>
<ide>
<ide> 
<add>
<ide> 
<del>
<ide>
<add>
<ide>
<ide> <b>Prerequisite:</b>
<ide> | 1 |
PHP | PHP | remove container check | b6113ebc5a23905474548a9d0eea448da2c178e3 | <ide><path>src/Illuminate/Routing/Router.php
<ide> protected function substituteImplicitBindings($route)
<ide> foreach ($route->callableParameters(Model::class) as $parameter) {
<ide> $class = $parameter->getClass();
<ide>
<del> if (array_key_exists($parameter->name, $parameters) && ! $this->container->bound($class->name)) {
<add> if (array_key_exists($parameter->name, $parameters)) {
<ide> $method = $parameter->isDefaultValueAvailable() ? 'find' : 'findOrFail';
<ide>
<ide> $route->setParameter( | 1 |
Javascript | Javascript | accept undefined mesh.primitives (for 1.0) | 69818a2b676d67150e2ee2fdcd6224836c80a148 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> if ( mesh.extras ) group.userData = mesh.extras;
<ide>
<del> var primitives = mesh.primitives;
<add> var primitives = mesh.primitives || [];
<ide>
<ide> for ( var name in primitives ) {
<ide> | 1 |
Python | Python | add __all__ to nose_tools/decorators.py | 58348a4e752fe3f951e38b445f5f11f33b53ab80 | <ide><path>numpy/testing/nose_tools/decorators.py
<ide>
<ide> from .utils import SkipTest, assert_warns
<ide>
<add>__all__ = ['slow', 'setastest', 'skipif', 'knownfailureif', 'deprecated',
<add> 'parametrize',]
<add>
<ide>
<ide> def slow(t):
<ide> """ | 1 |
Text | Text | adopt contributor covenant | 2c1e6bf619e404fd1ac464eb35eff4c09b3861b3 | <ide><path>CODE_OF_CONDUCT.md
<ide> # Code of Conduct
<ide>
<del>Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct/) so that you can understand what actions will and will not be tolerated.
<add>## Our Pledge
<add>
<add>In the interest of fostering an open and welcoming environment, we as
<add>contributors and maintainers pledge to make participation in our project and
<add>our community a harassment-free experience for everyone, regardless of age, body
<add>size, disability, ethnicity, sex characteristics, gender identity and expression,
<add>level of experience, education, socio-economic status, nationality, personal
<add>appearance, race, religion, or sexual identity and orientation.
<add>
<add>## Our Standards
<add>
<add>Examples of behavior that contributes to creating a positive environment
<add>include:
<add>
<add>* Using welcoming and inclusive language
<add>* Being respectful of differing viewpoints and experiences
<add>* Gracefully accepting constructive criticism
<add>* Focusing on what is best for the community
<add>* Showing empathy towards other community members
<add>
<add>Examples of unacceptable behavior by participants include:
<add>
<add>* The use of sexualized language or imagery and unwelcome sexual attention or
<add> advances
<add>* Trolling, insulting/derogatory comments, and personal or political attacks
<add>* Public or private harassment
<add>* Publishing others' private information, such as a physical or electronic
<add> address, without explicit permission
<add>* Other conduct which could reasonably be considered inappropriate in a
<add> professional setting
<add>
<add>## Our Responsibilities
<add>
<add>Project maintainers are responsible for clarifying the standards of acceptable
<add>behavior and are expected to take appropriate and fair corrective action in
<add>response to any instances of unacceptable behavior.
<add>
<add>Project maintainers have the right and responsibility to remove, edit, or
<add>reject comments, commits, code, wiki edits, issues, and other contributions
<add>that are not aligned to this Code of Conduct, or to ban temporarily or
<add>permanently any contributor for other behaviors that they deem inappropriate,
<add>threatening, offensive, or harmful.
<add>
<add>## Scope
<add>
<add>This Code of Conduct applies within all project spaces, and it also applies when
<add>an individual is representing the project or its community in public spaces.
<add>Examples of representing a project or community include using an official
<add>project e-mail address, posting via an official social media account, or acting
<add>as an appointed representative at an online or offline event. Representation of
<add>a project may be further defined and clarified by project maintainers.
<add>
<add>## Enforcement
<add>
<add>Instances of abusive, harassing, or otherwise unacceptable behavior may be
<add>reported by contacting the project team at <opensource-conduct@fb.com>. All
<add>complaints will be reviewed and investigated and will result in a response that
<add>is deemed necessary and appropriate to the circumstances. The project team is
<add>obligated to maintain confidentiality with regard to the reporter of an incident.
<add>Further details of specific enforcement policies may be posted separately.
<add>
<add>Project maintainers who do not follow or enforce the Code of Conduct in good
<add>faith may face temporary or permanent repercussions as determined by other
<add>members of the project's leadership.
<add>
<add>## Attribution
<add>
<add>This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
<add>available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
<add>
<add>[homepage]: https://www.contributor-covenant.org
<add>
<add>For answers to common questions about this code of conduct, see
<add>https://www.contributor-covenant.org/faq | 1 |
Ruby | Ruby | raise error instead of returning nil if `safe` | 9bf409111c29af56667cd86a390f46e0b5561c7d | <ide><path>Library/Homebrew/extend/git_repository.rb
<ide> def git_origin=(origin)
<ide> # Gets the full commit hash of the HEAD commit.
<ide> sig { params(safe: T::Boolean).returns(T.nilable(String)) }
<ide> def git_head(safe: false)
<del> return if !git? || !Utils::Git.available?
<del>
<del> Utils.popen_read(Utils::Git.git, "rev-parse", "--verify", "-q", "HEAD", safe: safe, chdir: self).chomp.presence
<add> popen_git("rev-parse", "--verify", "-q", "HEAD", safe: safe)
<ide> end
<ide>
<ide> # Gets a short commit hash of the HEAD commit.
<ide> sig { params(length: T.nilable(Integer), safe: T::Boolean).returns(T.nilable(String)) }
<ide> def git_short_head(length: nil, safe: false)
<del> return if !git? || !Utils::Git.available?
<del>
<del> git = Utils::Git.git
<del> short_arg = length&.to_s&.prepend("=")
<del> Utils.popen_read(git, "rev-parse", "--short#{short_arg}", "--verify", "-q", "HEAD", safe: safe, chdir: self)
<del> .chomp.presence
<add> short_arg = length.present? ? "--short=#{length}" : "--short"
<add> popen_git("rev-parse", short_arg, "--verify", "-q", "HEAD", safe: safe)
<ide> end
<ide>
<ide> # Gets the relative date of the last commit, e.g. "1 hour ago"
<ide> def git_commit_message(commit = "HEAD")
<ide>
<ide> Utils.popen_read(Utils::Git.git, "log", "-1", "--pretty=%B", commit, "--", chdir: self, err: :out).strip.presence
<ide> end
<add>
<add> private
<add>
<add> sig { params(args: T.untyped, safe: T::Boolean).returns(T.nilable(String)) }
<add> def popen_git(*args, safe: false)
<add> unless git?
<add> return unless safe
<add>
<add> raise "Not a Git repository: #{self}"
<add> end
<add>
<add> unless Utils::Git.available?
<add> return unless safe
<add>
<add> raise "Git is unavailable"
<add> end
<add>
<add> T.unsafe(Utils).popen_read(Utils::Git.git, *args, safe: safe, chdir: self).chomp.presence
<add> end
<ide> end
<ide><path>Library/Homebrew/test/utils/git_repository_spec.rb
<ide> let(:short_head_revision) { HOMEBREW_CACHE.cd { `git rev-parse --short HEAD`.chomp } }
<ide>
<ide> describe ".git_head" do
<del> it "returns the revision at HEAD" do
<add> it "returns the revision at HEAD if repo parameter is specified" do
<ide> expect(described_class.git_head(HOMEBREW_CACHE)).to eq(head_revision)
<ide> expect(described_class.git_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
<add> end
<add>
<add> it "returns the revision at HEAD if repo parameter is omitted" do
<ide> HOMEBREW_CACHE.cd do
<ide> expect(described_class.git_head).to eq(head_revision)
<ide> expect(described_class.git_head(length: 5)).to eq(head_revision[0...5])
<ide> end
<ide> end
<add>
<add> context "when directory is not a Git repository" do
<add> it "returns nil if `safe` parameter is `false`" do
<add> expect(described_class.git_head(TEST_TMPDIR, safe: false)).to eq(nil)
<add> end
<add>
<add> it "raises an error if `safe` parameter is `true`" do
<add> expect { described_class.git_head(TEST_TMPDIR, safe: true) }
<add> .to raise_error("Not a Git repository: #{TEST_TMPDIR}")
<add> end
<add> end
<add>
<add> context "when Git is unavailable" do
<add> before do
<add> allow(Utils::Git).to receive(:available?).and_return(false)
<add> end
<add>
<add> it "returns nil if `safe` parameter is `false`" do
<add> expect(described_class.git_head(HOMEBREW_CACHE, safe: false)).to eq(nil)
<add> end
<add>
<add> it "raises an error if `safe` parameter is `true`" do
<add> expect { described_class.git_head(HOMEBREW_CACHE, safe: true) }
<add> .to raise_error("Git is unavailable")
<add> end
<add> end
<ide> end
<ide>
<ide> describe ".git_short_head" do
<del> it "returns the short revision at HEAD" do
<add> it "returns the short revision at HEAD if repo parameter is specified" do
<ide> expect(described_class.git_short_head(HOMEBREW_CACHE)).to eq(short_head_revision)
<ide> expect(described_class.git_short_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
<add> end
<add>
<add> it "returns the short revision at HEAD if repo parameter is omitted" do
<ide> HOMEBREW_CACHE.cd do
<ide> expect(described_class.git_short_head).to eq(short_head_revision)
<ide> expect(described_class.git_short_head(length: 5)).to eq(head_revision[0...5])
<ide> end
<ide> end
<add>
<add> context "when directory is not a Git repository" do
<add> it "returns nil if `safe` parameter is `false`" do
<add> expect(described_class.git_short_head(TEST_TMPDIR, safe: false)).to eq(nil)
<add> end
<add>
<add> it "raises an error if `safe` parameter is `true`" do
<add> expect { described_class.git_short_head(TEST_TMPDIR, safe: true) }
<add> .to raise_error("Not a Git repository: #{TEST_TMPDIR}")
<add> end
<add> end
<add>
<add> context "when Git is unavailable" do
<add> before do
<add> allow(Utils::Git).to receive(:available?).and_return(false)
<add> end
<add>
<add> it "returns nil if `safe` parameter is `false`" do
<add> expect(described_class.git_short_head(HOMEBREW_CACHE, safe: false)).to eq(nil)
<add> end
<add>
<add> it "raises an error if `safe` parameter is `true`" do
<add> expect { described_class.git_short_head(HOMEBREW_CACHE, safe: true) }
<add> .to raise_error("Git is unavailable")
<add> end
<add> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/utils/git_repository.rb
<ide> module Utils
<ide> extend T::Sig
<ide>
<ide> sig do
<del> params(repo: T.any(String, Pathname), length: T.nilable(Integer), safe: T::Boolean).returns(T.nilable(String))
<add> params(
<add> repo: T.any(String, Pathname),
<add> length: T.nilable(Integer),
<add> safe: T::Boolean,
<add> ).returns(T.nilable(String))
<ide> end
<ide> def self.git_head(repo = Pathname.pwd, length: nil, safe: true)
<ide> return git_short_head(repo, length: length) if length.present?
<ide> def self.git_head(repo = Pathname.pwd, length: nil, safe: true)
<ide> end
<ide>
<ide> sig do
<del> params(repo: T.any(String, Pathname), length: T.nilable(Integer), safe: T::Boolean).returns(T.nilable(String))
<add> params(
<add> repo: T.any(String, Pathname),
<add> length: T.nilable(Integer),
<add> safe: T::Boolean,
<add> ).returns(T.nilable(String))
<ide> end
<ide> def self.git_short_head(repo = Pathname.pwd, length: nil, safe: true)
<ide> repo = Pathname(repo).extend(GitRepositoryExtension) | 3 |
Go | Go | fix unmount when host volume is removed | 39103e72a3ca4ff739a4986c4e4849339e08aaf3 | <ide><path>integration-cli/docker_cli_rm_test.go
<add>package main
<add>
<add>import (
<add> "os"
<add> "os/exec"
<add> "testing"
<add>)
<add>
<add>func TestRemoveContainerWithRemovedVolume(t *testing.T) {
<add> cmd := exec.Command(dockerBinary, "run", "--name", "losemyvolumes", "-v", "/tmp/testing:/test", "busybox", "true")
<add> if _, err := runCommand(cmd); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := os.Remove("/tmp/testing"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> cmd = exec.Command(dockerBinary, "rm", "-v", "losemyvolumes")
<add> if _, err := runCommand(cmd); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> deleteAllContainers()
<add>
<add> logDone("rm - removed volume")
<add>}
<ide><path>server/server.go
<ide> func (srv *Server) ContainerDestroy(job *engine.Job) engine.Status {
<ide> for _, bind := range container.HostConfig().Binds {
<ide> source := strings.Split(bind, ":")[0]
<ide> // TODO: refactor all volume stuff, all of it
<del> // this is very important that we eval the link
<del> // or comparing the keys to container.Volumes will not work
<add> // it is very important that we eval the link or comparing the keys to container.Volumes will not work
<add> //
<add> // eval symlink can fail, ref #5244 if we receive an is not exist error we can ignore it
<ide> p, err := filepath.EvalSymlinks(source)
<del> if err != nil {
<add> if err != nil && !os.IsNotExist(err) {
<ide> return job.Error(err)
<ide> }
<del> source = p
<add> if p != "" {
<add> source = p
<add> }
<ide> binds[source] = struct{}{}
<ide> }
<ide> | 2 |
Ruby | Ruby | remove variable and fix warning | 7133b0090e7509025bf71f22fb9f41404031dbbf | <ide><path>actionpack/lib/action_dispatch/middleware/public_exceptions.rb
<ide> def initialize(public_path)
<ide> end
<ide>
<ide> def call(env)
<del> exception = env["action_dispatch.exception"]
<ide> status = env["PATH_INFO"][1..-1]
<ide> request = ActionDispatch::Request.new(env)
<ide> content_type = request.formats.first | 1 |
Text | Text | add '-' to line 23 | d9c970c86de5da24e613c4a7c5fe628cb4f96f49 | <ide><path>guide/english/working-in-tech/index.md
<ide> title: Working in Tech & Information Technology(IT)
<ide> ---
<ide>
<ide> ## Working in Tech and IT
<del>A wide variety of technology-related fields such as web development, design, data science, infrastructure support, information security, and product management are often lumped into the catch-all term "tech" or IT.
<add>A wide variety of technology-related fields such as web development, design, data science, infrastructure support, information security, and product management are often lumped into the catch-all term "Tech" or IT.
<ide>
<ide> This section will focus on various aspects of working in tech, such as the ways in which teams cooperate, how to give talks and what code reviews are. We will discuss the additional career challenges that under-represented minorities and people from non-traditional education backgrounds face. This includes issues such as sexism and ageism that have been particularly prevalent in certain industries and organizations.
<ide>
<ide> The field of computer security is growing at a rapid rate every year. As more p
<ide> - Network Administrator
<ide> - Support Desk Engineer
<ide> - Security Engineer
<add>- Project Manager
<ide> - Ethical hackers
<ide> - Data Scientist
<ide> - Software Tester
<ide> - Infrastructure Support
<ide> - Help Desk Analyst
<del>- Project manager
<ide> - Data Analyst
<ide> - Data Scientist
<ide> - Database Manager | 1 |
PHP | PHP | change default config value to null | f6488265f251821a51738d43e2f8c70a6148737a | <ide><path>src/Controller/Component/AuthComponent.php
<ide> class AuthComponent extends Component {
<ide> */
<ide> protected $_defaultConfig = [
<ide> 'authenticate' => null,
<del> 'authorize' => false,
<add> 'authorize' => null,
<ide> 'ajaxLogin' => null,
<ide> 'flash' => null,
<ide> 'loginAction' => null, | 1 |
Text | Text | use number instead of string in application.rb | 4eda24a2e281c17565f5625df20c13d1b0bab299 | <ide><path>guides/source/upgrading_ruby_on_rails.md
<ide> The default configuration for Rails 6
<ide> ```ruby
<ide> # config/application.rb
<ide>
<del>config.load_defaults "6.0"
<add>config.load_defaults 6.0
<ide> ```
<ide>
<ide> enables `zeitwerk` autoloading mode on CRuby. In that mode, autoloading, reloading, and eager loading are managed by [Zeitwerk](https://github.com/fxn/zeitwerk). | 1 |
Javascript | Javascript | add default type in getstringwidth.js | d2683ede836d3f2449714c6309b47fb469873bb2 | <ide><path>benchmark/misc/getstringwidth.js
<ide> const bench = common.createBenchmark(main, {
<ide> });
<ide>
<ide> function main({ n, type }) {
<add> // Default value for testing purposes.
<add> type = type || 'ascii';
<ide> const { getStringWidth } = require('internal/readline/utils');
<ide>
<ide> const str = ({ | 1 |
Text | Text | use a descriptive text for the wikipedia link | e6be7d82c47a0b1c15202db1f04fcb5f867962ec | <ide><path>guide/english/algorithms/algorithm-design-patterns/structual-patterns/index.md
<ide> Examples of Structural Patterns include:
<ide> 15. **Proxy pattern**: a class functioning as an interface to another thing.
<ide>
<ide> ### Sources
<del>[https://en.wikipedia.org/wiki/Structural_pattern](https://en.wikipedia.org/wiki/Structural_pattern)
<add>[Structural patterns - Wikipedia](https://en.wikipedia.org/wiki/Structural_pattern) | 1 |
Javascript | Javascript | fix default value for divisions | d6dd44d2470c86e2b35aff1502271ecb414482b9 | <ide><path>src/extras/core/Curve.js
<ide> Curve.prototype = {
<ide>
<ide> getPoints: function ( divisions ) {
<ide>
<del> if ( ! divisions ) divisions = 5;
<add> if ( isNaN( divisions ) ) divisions = 5;
<ide>
<ide> var points = [];
<ide>
<ide> Curve.prototype = {
<ide>
<ide> getSpacedPoints: function ( divisions ) {
<ide>
<del> if ( ! divisions ) divisions = 5;
<add> if ( isNaN( divisions ) ) divisions = 5;
<ide>
<ide> var points = [];
<ide>
<ide> Curve.prototype = {
<ide>
<ide> getLengths: function ( divisions ) {
<ide>
<del> if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
<add> if ( isNaN( divisions ) ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
<ide>
<ide> if ( this.cacheArcLengths
<ide> && ( this.cacheArcLengths.length === divisions + 1 )
<ide><path>src/extras/core/CurvePath.js
<ide> CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
<ide>
<ide> getSpacedPoints: function ( divisions ) {
<ide>
<del> if ( ! divisions ) divisions = 40;
<add> if ( isNaN( divisions ) ) divisions = 40;
<ide>
<ide> var points = [];
<ide> | 2 |
Javascript | Javascript | fix lint warnings in the resolver | 0cb63bb97172e0cca4e207eed264613d6112eac4 | <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> describe('DependencyGraph', function() {
<ide> ' * @providesModule wontWork',
<ide> ' */',
<ide> 'hi();',
<del> ].join('\n')
<add> ].join('\n'),
<ide> },
<ide> },
<ide> // This part of the dep graph is meant to emulate internal facebook infra.
<ide> describe('DependencyGraph', function() {
<ide> ' */',
<ide> 'hiFromInternalPackage();',
<ide> ].join('\n'),
<del> }
<add> },
<ide> },
<ide> },
<ide> // we need to support multiple roots and using haste between them
<ide> describe('DependencyGraph', function() {
<ide> ' */',
<ide> 'wazup()',
<ide> ].join('\n'),
<del> }
<add> },
<ide> });
<ide>
<ide> var dgraph = new DependencyGraph({
<ide> describe('DependencyGraph', function() {
<ide> 'wontWork',
<ide> 'ember',
<ide> 'internalVendoredPackage',
<del> 'anotherIndex'
<add> 'anotherIndex',
<ide> ],
<ide> isAsset: false,
<ide> isAsset_DEPRECATED: false,
<ide><path>packager/react-packager/src/DependencyResolver/ModuleCache.js
<ide> class ModuleCache {
<ide> moduleCache: this,
<ide> cache: this._cache,
<ide> extractor: this._extractRequires,
<del> depGraphHelpers: this._depGraphHelpers
<add> depGraphHelpers: this._depGraphHelpers,
<ide> });
<ide> }
<ide> return this._moduleCache[filePath];
<ide><path>packager/react-packager/src/DependencyResolver/__tests__/Module-test.js
<ide> describe('Module', () => {
<ide> fastfs,
<ide> moduleCache: new ModuleCache(fastfs, cache),
<ide> cache: cache,
<del> depGraphHelpers: new DependencyGraphHelpers()
<add> depGraphHelpers: new DependencyGraphHelpers(),
<ide> });
<ide>
<ide> return module.getAsyncDependencies().then(actual =>
<ide> describe('Module', () => {
<ide> moduleCache: new ModuleCache(fastfs, cache),
<ide> cache,
<ide> extractor,
<del> depGraphHelpers: new DependencyGraphHelpers()
<add> depGraphHelpers: new DependencyGraphHelpers(),
<ide> });
<ide> });
<ide> } | 3 |
Text | Text | update image documentation for static image | 8873374963fdd116ab7a7e537c9604c7912f6a95 | <ide><path>docs/api-reference/next/image.md
<ide> description: Enable Image Optimization with the built-in Image component.
<ide> <details>
<ide> <summary><b>Version History</b></summary>
<ide>
<del>| Version | Changes |
<del>| --------- | ------------------------ |
<del>| `v10.0.5` | `loader` prop added. |
<del>| `v10.0.1` | `layout` prop added. |
<del>| `v10.0.0` | `next/image` introduced. |
<add>| Version | Changes |
<add>| --------- | ---------------------------------------------------------------------------- |
<add>| `v11.0.0` | Added static imports for `src`. Added `placeholder` and `blurDataURL` props. |
<add>| `v10.0.5` | `loader` prop added. |
<add>| `v10.0.1` | `layout` prop added. |
<add>| `v10.0.0` | `next/image` introduced. |
<ide>
<ide> </details>
<ide>
<ide> We can serve an optimized image like so:
<ide>
<ide> ```jsx
<ide> import Image from 'next/image'
<add>import profilePic from '../me.png'
<ide>
<ide> function Home() {
<ide> return (
<ide> <>
<ide> <h1>My Homepage</h1>
<del> <Image
<del> src="/me.png"
<del> alt="Picture of the author"
<del> width={500}
<del> height={500}
<del> />
<add> <Image src={profilePic} alt="Picture of the author" />
<ide> <p>Welcome to my homepage!</p>
<ide> </>
<ide> )
<ide> The `<Image />` component requires the following properties.
<ide>
<ide> ### src
<ide>
<del>The path or URL to the source image. This is required.
<add>Required and must be one of the following:
<add>
<add>1. A statically imported image file, as in the example code above, or
<add>2. A path string. This can be either an absolute external URL,
<add> or an internal path depending on the [loader](#loader).
<ide>
<ide> When using an external URL, you must add it to
<ide> [domains](/docs/basic-features/image-optimization.md#domains) in
<ide> When using an external URL, you must add it to
<ide>
<ide> The width of the image, in pixels. Must be an integer without a unit.
<ide>
<del>Required unless [`layout="fill"`](#layout).
<add>Required, except for statically imported images, or those with [`layout="fill"`](#layout).
<ide>
<ide> ### height
<ide>
<ide> The height of the image, in pixels. Must be an integer without a unit.
<ide>
<del>Required unless [`layout="fill"`](#layout).
<add>Required, except for statically imported images, or those with [`layout="fill"`](#layout).
<ide>
<ide> ## Optional Props
<ide>
<ide> When true, the image will be considered high priority and
<ide> Should only be used when the image is visible above the fold. Defaults to
<ide> `false`.
<ide>
<add>### placeholder
<add>
<add>A placeholder to use while the image is loading, possible values are `blur` or `empty`. Defaults to `empty`.
<add>When `placeholder="blur"`, the `blurDataURL` will be used as the placeholder. If the `src` is an object from a static import, then `blurDataURL` will automatically be populated. If the `src` is a string, then you must provide the [`blurDataURL` property](#blurdataurl).
<add>
<ide> ## Advanced Props
<ide>
<ide> In some cases, you may need more advanced usage. The `<Image />` component
<ide> When `eager`, load the image immediately.
<ide>
<ide> [Learn more](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading)
<ide>
<add>### blurDataURL
<add>
<add>A [Data URL](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) to
<add>be used as a placeholder image before the `src` image successfully loads. Only takes effect when combined
<add>with [`placeholder="blur"`](#placeholder).
<add>
<add>Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or
<add>less) is recommended. Including larger images as placeholders may harm your application performance.
<add>
<ide> ### unoptimized
<ide>
<ide> When true, the source image will be served as-is instead of changing quality, | 1 |
Text | Text | encourage 2fa before onboarding | cad0423ce430c11ff527a6bac01c413ef37ea5cf | <ide><path>doc/onboarding.md
<ide> This document is an outline of the things we tell new Collaborators at their
<ide> onboarding session.
<ide>
<add>## One week before the onboarding session
<add>
<add>* Ask the new Collaborator if they are using two-factor authentication on their
<add> GitHub account. If they are not, suggest that they enable it as their account
<add> will have elevated privileges in many of the Node.js repositories.
<add>
<add>## Fifteen minutes before the onboarding session
<add>
<ide> * Prior to the onboarding session, add the new Collaborators to
<ide> [the Collaborators team](https://github.com/orgs/nodejs/teams/collaborators).
<ide> | 1 |
Ruby | Ruby | add `formula` spec helper | 004e8175c6ceb58f026e79e6bbd0ddac9e8380f6 | <ide><path>Library/Homebrew/test/spec_helper.rb
<ide>
<ide> require "test/support/helper/shutup"
<ide> require "test/support/helper/fixtures"
<add>require "test/support/helper/formula"
<ide> require "test/support/helper/spec/shared_context/integration_test"
<ide>
<ide> TEST_DIRECTORIES = [
<ide> config.order = :random
<ide> config.include(Test::Helper::Shutup)
<ide> config.include(Test::Helper::Fixtures)
<add> config.include(Test::Helper::Formula)
<ide> config.before(:each) do |example|
<ide> if example.metadata[:needs_macos]
<ide> skip "Not on macOS." unless OS.mac?
<ide><path>Library/Homebrew/test/support/helper/formula.rb
<add>require "formulary"
<add>
<add>module Test
<add> module Helper
<add> module Formula
<add> def formula(name = "formula_name", path: Formulary.core_path(name), spec: :stable, alias_path: nil, &block)
<add> Class.new(::Formula, &block).new(name, path, spec, alias_path: alias_path)
<add> end
<add>
<add> # Use a stubbed {Formulary::FormulaLoader} to make a given formula be found
<add> # when loading from {Formulary} with `ref`.
<add> def stub_formula_loader(formula, ref = formula.full_name)
<add> loader = double(get_formula: formula)
<add> allow(Formulary).to receive(:loader_for).with(ref, from: :keg).and_return(loader)
<add> allow(Formulary).to receive(:loader_for).with(ref, from: nil).and_return(loader)
<add> end
<add> end
<add> end
<add>end | 2 |
Mixed | Go | add option for specifying the thin pool blocksize | 09ee269d998ad04733ef577739fa051df9d3f12e | <ide><path>daemon/graphdriver/devmapper/README.md
<ide> Here is the list of supported options:
<ide>
<ide> ``docker -d --storage-opt dm.datadev=/dev/sdb1 --storage-opt dm.metadatadev=/dev/sdc1``
<ide>
<add> * `dm.blocksize`
<add>
<add> Specifies a custom blocksize to use for the thin pool.
<add>
<add> Example use:
<add>
<add> ``docker -d --storage-opt dm.blocksize=64K``
<add>
<ide> * `dm.blkdiscard`
<ide>
<ide> Enables or disables the use of blkdiscard when removing
<ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> var (
<ide> DefaultDataLoopbackSize int64 = 100 * 1024 * 1024 * 1024
<ide> DefaultMetaDataLoopbackSize int64 = 2 * 1024 * 1024 * 1024
<ide> DefaultBaseFsSize uint64 = 10 * 1024 * 1024 * 1024
<add> DefaultThinpBlockSize uint32 = 1024 // 512K = 1024 512b sectors
<ide> )
<ide>
<ide> type DevInfo struct {
<ide> type DeviceSet struct {
<ide> dataDevice string
<ide> metadataDevice string
<ide> doBlkDiscard bool
<add> thinpBlockSize uint32
<ide> }
<ide>
<ide> type DiskUsage struct {
<ide> func (devices *DeviceSet) ResizePool(size int64) error {
<ide> }
<ide>
<ide> // Reload with the new block sizes
<del> if err := reloadPool(devices.getPoolName(), dataloopback, metadataloopback); err != nil {
<add> if err := reloadPool(devices.getPoolName(), dataloopback, metadataloopback, devices.thinpBlockSize); err != nil {
<ide> return fmt.Errorf("Unable to reload pool: %s", err)
<ide> }
<ide>
<ide> func (devices *DeviceSet) initDevmapper(doInit bool) error {
<ide> }
<ide> defer metadataFile.Close()
<ide>
<del> if err := createPool(devices.getPoolName(), dataFile, metadataFile); err != nil {
<add> if err := createPool(devices.getPoolName(), dataFile, metadataFile, devices.thinpBlockSize); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error
<ide> baseFsSize: DefaultBaseFsSize,
<ide> filesystem: "ext4",
<ide> doBlkDiscard: true,
<add> thinpBlockSize: DefaultThinpBlockSize,
<ide> }
<ide>
<ide> foundBlkDiscard := false
<ide> func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error
<ide> if err != nil {
<ide> return nil, err
<ide> }
<add> case "dm.blocksize":
<add> size, err := units.RAMInBytes(val)
<add> if err != nil {
<add> return nil, err
<add> }
<add> // convert to 512b sectors
<add> devices.thinpBlockSize = uint32(size) >> 9
<ide> default:
<ide> return nil, fmt.Errorf("Unknown option %s\n", key)
<ide> }
<ide><path>daemon/graphdriver/devmapper/devmapper.go
<ide> func BlockDeviceDiscard(path string) error {
<ide> }
<ide>
<ide> // This is the programmatic example of "dmsetup create"
<del>func createPool(poolName string, dataFile, metadataFile *os.File) error {
<add>func createPool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error {
<ide> task, err := createTask(DeviceCreate, poolName)
<ide> if task == nil {
<ide> return err
<ide> func createPool(poolName string, dataFile, metadataFile *os.File) error {
<ide> return fmt.Errorf("Can't get data size %s", err)
<ide> }
<ide>
<del> params := metadataFile.Name() + " " + dataFile.Name() + " 128 32768 1 skip_block_zeroing"
<add> params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize)
<ide> if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil {
<ide> return fmt.Errorf("Can't add target %s", err)
<ide> }
<ide> func createPool(poolName string, dataFile, metadataFile *os.File) error {
<ide> return nil
<ide> }
<ide>
<del>func reloadPool(poolName string, dataFile, metadataFile *os.File) error {
<add>func reloadPool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error {
<ide> task, err := createTask(DeviceReload, poolName)
<ide> if task == nil {
<ide> return err
<ide> func reloadPool(poolName string, dataFile, metadataFile *os.File) error {
<ide> return fmt.Errorf("Can't get data size %s", err)
<ide> }
<ide>
<del> params := metadataFile.Name() + " " + dataFile.Name() + " 128 32768 1 skip_block_zeroing"
<add> params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize)
<ide> if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil {
<ide> return fmt.Errorf("Can't add target %s", err)
<ide> } | 3 |
Ruby | Ruby | move tab creation outside of the debug loop | 47a82b036e43e7119fb52123a908b3af8e3af76a | <ide><path>Library/Homebrew/build.rb
<ide> def install
<ide>
<ide> begin
<ide> f.install
<del> stdlibs = detect_stdlibs
<del> Tab.create(f, ENV.compiler, stdlibs.first, f.build).write
<ide> rescue Exception => e
<ide> if ARGV.debug?
<ide> debrew e, f
<ide> def install
<ide> end
<ide> end
<ide>
<add> stdlibs = detect_stdlibs
<add> Tab.create(f, ENV.compiler, stdlibs.first, f.build).write
<add>
<ide> # Find and link metafiles
<ide> f.prefix.install_metafiles Pathname.pwd
<ide> end | 1 |
Ruby | Ruby | use filter_map for template_glob | e2781c2d93808031fbc4dbecaa7aac59aa90b4b8 | <ide><path>actionview/lib/action_view/template/resolver.rb
<ide> def template_glob(glob)
<ide> query = File.join(escape_entry(@path), glob)
<ide> path_with_slash = File.join(@path, "")
<ide>
<del> Dir.glob(query).reject do |filename|
<del> File.directory?(filename)
<del> end.map do |filename|
<del> File.expand_path(filename)
<del> end.select do |filename|
<del> filename.start_with?(path_with_slash)
<add> Dir.glob(query).filter_map do |filename|
<add> filename = File.expand_path(filename)
<add> next if File.directory?(filename)
<add> next unless filename.start_with?(path_with_slash)
<add>
<add> filename
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | restore original semantics | 5e622b2bfbb7c263a58c056a6f0dc66afeed216c | <ide><path>src/Http/ServerRequest.php
<ide> public function getHeaders()
<ide> $name = $key;
<ide> }
<ide> if ($name !== null) {
<del> $name = ucwords(str_replace(['_', ' '], [' ', '-'], $name));
<add> $name = ucwords(strtolower(str_replace(['_', ' '], [' ', '-'], $name)));
<ide> $headers[$name] = (array)$value;
<ide> }
<ide> } | 1 |
Ruby | Ruby | add locale option to parameterize | bc9711fb7d6dd89094ccc9c8f3147bcf3ddd63bc | <ide><path>activesupport/lib/active_support/core_ext/string/inflections.rb
<ide> def deconstantize
<ide>
<ide> # Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
<ide> #
<add> # If the optional parameter +locale+ is specified,
<add> # the word will be parameterized as a word of that language.
<add> # By default, this parameter is set to <tt>nil</tt> and it will use
<add> # configured I18n.locale
<add> #
<ide> # class Person
<ide> # def to_param
<ide> # "#{id}-#{name.parameterize}"
<ide> def deconstantize
<ide> #
<ide> # <%= link_to(@person.name, person_path) %>
<ide> # # => <a href="/person/1-Donald-E-Knuth">Donald E. Knuth</a>
<del> def parameterize(separator: "-", preserve_case: false)
<del> ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case)
<add> def parameterize(separator: "-", preserve_case: false, locale: nil)
<add> ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case, locale: locale)
<ide> end
<ide>
<ide> # Creates the name of a table like Rails does for models to table names. This method
<ide><path>activesupport/lib/active_support/inflector/transliterate.rb
<ide> module Inflector
<ide> #
<ide> # Now you can have different transliterations for each locale:
<ide> #
<del> # I18n.locale = :en
<del> # transliterate('Jürgen')
<add> # transliterate('Jürgen', locale: :en)
<ide> # # => "Jurgen"
<ide> #
<del> # I18n.locale = :de
<del> # transliterate('Jürgen')
<add> # transliterate('Jürgen', locale: :de)
<ide> # # => "Juergen"
<del> def transliterate(string, replacement = "?")
<add> def transliterate(string, replacement = "?", locale: nil)
<ide> raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String)
<ide>
<ide> I18n.transliterate(
<ide> ActiveSupport::Multibyte::Unicode.tidy_bytes(string).unicode_normalize(:nfc),
<del> replacement: replacement
<add> replacement: replacement,
<add> locale: locale
<ide> )
<ide> end
<ide>
<ide> def transliterate(string, replacement = "?")
<ide> # parameterize("^très|Jolie-- ", separator: "_") # => "tres_jolie--"
<ide> # parameterize("^très_Jolie-- ", separator: ".") # => "tres_jolie--"
<ide> #
<del> def parameterize(string, separator: "-", preserve_case: false)
<add> def parameterize(string, separator: "-", preserve_case: false, locale: nil)
<ide> # Replace accented chars with their ASCII equivalents.
<del> parameterized_string = transliterate(string)
<add> parameterized_string = transliterate(string, locale)
<ide>
<ide> # Turn unwanted chars into the separator.
<ide> parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator) | 2 |
Ruby | Ruby | add inspect method | c1688be78035b5b0ec7ccf1dbae30c5c93c4ee58 | <ide><path>Library/Homebrew/version/null.rb
<ide> def to_s
<ide> ""
<ide> end
<ide> alias_method :to_str, :to_s
<add>
<add> def inspect
<add> "#<Version::NULL>".freeze
<add> end
<ide> end.new
<ide> end | 1 |
Javascript | Javascript | add support for `oncontextmenu` in react | 1ffe2d0927a395c53215fadb78ceffee99f87574 | <ide><path>src/core/ReactEventEmitter.js
<ide> var ReactEventEmitter = merge(ReactEventEmitterMixin, {
<ide> trapBubbledEvent(topLevelTypes.topMouseOut, 'mouseout', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topClick, 'click', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topDoubleClick, 'dblclick', mountAt);
<add> trapBubbledEvent(topLevelTypes.topContextMenu, 'contextmenu', mountAt);
<ide> if (touchNotMouse) {
<ide> trapBubbledEvent(topLevelTypes.topTouchStart, 'touchstart', mountAt);
<ide> trapBubbledEvent(topLevelTypes.topTouchEnd, 'touchend', mountAt);
<ide><path>src/event/EventConstants.js
<ide> var topLevelTypes = keyMirror({
<ide> topCompositionEnd: null,
<ide> topCompositionStart: null,
<ide> topCompositionUpdate: null,
<add> topContextMenu: null,
<ide> topCopy: null,
<ide> topCut: null,
<ide> topDoubleClick: null,
<ide><path>src/eventPlugins/SimpleEventPlugin.js
<ide> var eventTypes = {
<ide> captured: keyOf({onClickCapture: true})
<ide> }
<ide> },
<add> contextMenu: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onContextMenu: true}),
<add> captured: keyOf({onContextMenuCapture: true})
<add> }
<add> },
<ide> copy: {
<ide> phasedRegistrationNames: {
<ide> bubbled: keyOf({onCopy: true}),
<ide> var eventTypes = {
<ide> var topLevelEventsToDispatchConfig = {
<ide> topBlur: eventTypes.blur,
<ide> topClick: eventTypes.click,
<add> topContextMenu: eventTypes.contextMenu,
<ide> topCopy: eventTypes.copy,
<ide> topCut: eventTypes.cut,
<ide> topDoubleClick: eventTypes.doubleClick,
<ide> var SimpleEventPlugin = {
<ide> return null;
<ide> }
<ide> /* falls through */
<add> case topLevelTypes.topContextMenu:
<ide> case topLevelTypes.topDoubleClick:
<ide> case topLevelTypes.topDrag:
<ide> case topLevelTypes.topDragEnd: | 3 |
Ruby | Ruby | use versions to access previous bottles | 19618bddd441afa0cfb55366902107bd144c1756 | <ide><path>Library/Homebrew/cmd/bottle.rb
<ide> require 'bottles'
<ide> require 'tab'
<ide> require 'keg'
<add>require 'cmd/versions'
<ide>
<ide> class BottleMerger < Formula
<ide> # This provides a URL and Version which are the only needed properties of
<ide> def bottle_formula f
<ide> return ofail "Formula not installed with '--build-bottle': #{f.name}"
<ide> end
<ide>
<del> bottle_revision = bottle_new_revision f
<del> filename = bottle_filename f, bottle_revision
<add> master_bottle_filenames = f.bottle_filenames 'origin/master'
<add> bottle_revision = -1
<add> begin
<add> bottle_revision += 1
<add> filename = bottle_filename(f, bottle_revision)
<add> end while master_bottle_filenames.include? filename
<ide>
<ide> if bottle_filename_formula_name(filename).empty?
<ide> return ofail "Add a new regex to bottle_version.rb to parse the bottle filename." | 1 |
Python | Python | use _umath_linalg for eig() | 1253d571a48f3100865e0b38895c0cceb8336aa3 | <ide><path>numpy/linalg/linalg.py
<ide> def eig(a):
<ide>
<ide> Parameters
<ide> ----------
<del> a : (M, M) array_like
<del> A square array of real or complex elements.
<add> a : (..., M, M) array
<add> Matrices for which the eigenvalues and right eigenvectors will
<add> be computed
<ide>
<ide> Returns
<ide> -------
<del> w : (M,) ndarray
<add> w : (..., M) array
<ide> The eigenvalues, each repeated according to its multiplicity.
<del> The eigenvalues are not necessarily ordered, nor are they
<del> necessarily real for real arrays (though for real arrays
<del> complex-valued eigenvalues should occur in conjugate pairs).
<del> v : (M, M) ndarray
<add> The eigenvalues are not necessarily ordered. The resulting
<add> array will be always be of complex type. When `a` is real
<add> the resulting eigenvalues will be real (0 imaginary part) or
<add> occur in conjugate pairs
<add>
<add> v : (..., M, M) array
<ide> The normalized (unit "length") eigenvectors, such that the
<ide> column ``v[:,i]`` is the eigenvector corresponding to the
<ide> eigenvalue ``w[i]``.
<ide> def eig(a):
<ide>
<ide> Notes
<ide> -----
<del> This is a simple interface to the LAPACK routines dgeev and zgeev
<del> which compute the eigenvalues and eigenvectors of, respectively,
<del> general real- and complex-valued square arrays.
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<add>
<add> This is implemented using the _geev LAPACK routines which compute
<add> the eigenvalues and eigenvectors of general square arrays.
<ide>
<ide> The number `w` is an eigenvalue of `a` if there exists a vector
<ide> `v` such that ``dot(a,v) = w * v``. Thus, the arrays `a`, `w`, and
<ide> def eig(a):
<ide>
<ide> """
<ide> a, wrap = _makearray(a)
<del> _assertRank2(a)
<del> _assertSquareness(a)
<add> _assertRankAtLeast2(a)
<add> _assertNdSquareness(a)
<ide> _assertFinite(a)
<del> a, t, result_t = _convertarray(a) # convert to double or cdouble type
<del> a = _to_native_byte_order(a)
<del> real_t = _linalgRealType(t)
<del> n = a.shape[0]
<del> dummy = zeros((1,), t)
<del> if isComplexType(t):
<del> # Complex routines take different arguments
<del> lapack_routine = lapack_lite.zgeev
<del> w = zeros((n,), t)
<del> v = zeros((n, n), t)
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> rwork = zeros((2*n,), real_t)
<del> results = lapack_routine(_N, _V, n, a, n, w,
<del> dummy, 1, v, n, work, -1, rwork, 0)
<del> lwork = int(abs(work[0]))
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(_N, _V, n, a, n, w,
<del> dummy, 1, v, n, work, lwork, rwork, 0)
<add> t, result_t = _commonType(a)
<add>
<add> extobj = get_linalg_error_extobj(
<add> _raise_linalgerror_eigenvalues_nonconvergence)
<add> w, vt = _umath_linalg.eig(a.astype(t), extobj=extobj)
<add>
<add> if not isComplexType(t) and all(w.imag == 0.0):
<add> w = w.real
<add> vt = vt.real
<add> result_t = _realType(result_t)
<ide> else:
<del> lapack_routine = lapack_lite.dgeev
<del> wr = zeros((n,), t)
<del> wi = zeros((n,), t)
<del> vr = zeros((n, n), t)
<del> lwork = 1
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(_N, _V, n, a, n, wr, wi,
<del> dummy, 1, vr, n, work, -1, 0)
<del> lwork = int(work[0])
<del> work = zeros((lwork,), t)
<del> results = lapack_routine(_N, _V, n, a, n, wr, wi,
<del> dummy, 1, vr, n, work, lwork, 0)
<del> if all(wi == 0.0):
<del> w = wr
<del> v = vr
<del> result_t = _realType(result_t)
<del> else:
<del> w = wr+1j*wi
<del> v = array(vr, w.dtype)
<del> ind = flatnonzero(wi != 0.0) # indices of complex e-vals
<del> for i in range(len(ind)//2):
<del> v[ind[2*i]] = vr[ind[2*i]] + 1j*vr[ind[2*i+1]]
<del> v[ind[2*i+1]] = vr[ind[2*i]] - 1j*vr[ind[2*i+1]]
<del> result_t = _complexType(result_t)
<add> result_t = _complexType(result_t)
<ide>
<del> if results['info'] > 0:
<del> raise LinAlgError('Eigenvalues did not converge')
<del> vt = v.transpose().astype(result_t)
<add> vt = vt.astype(result_t)
<ide> return w.astype(result_t), wrap(vt)
<ide>
<ide> | 1 |
PHP | PHP | refactor the database manager | 73065d12c26fde8638598a8ccd67da3c53279e96 | <ide><path>system/db/manager.php
<ide> class Manager {
<ide> */
<ide> public static function connection($connection = null)
<ide> {
<del> if (is_null($connection)) $connection = Config::get('db.default');
<add> if (is_null($connection))
<add> {
<add> $connection = Config::get('db.default');
<add> }
<ide>
<ide> if ( ! array_key_exists($connection, static::$connections))
<ide> { | 1 |
Text | Text | add link to sponsor | ee8669a587eec90f0a23b4374cc483d7569f2e34 | <ide><path>readme.md
<ide> We would like to extend our thanks to the following sponsors for helping fund on
<ide> - [iMi digital](https://www.imi-digital.de/)
<ide> - [Earthlink](https://www.earthlink.ro/)
<ide> - [Steadfast Collective](https://steadfastcollective.com/)
<add>- [We Are The Robots Inc.](https://watr.mx/)
<ide>
<ide> ## Contributing
<ide> | 1 |
Javascript | Javascript | remove ie8 url parsing workaround | b3acf663641fca0f7a966525a72845af7ec5fab2 | <ide><path>src/js/utils/url.js
<ide> import window from 'global/window';
<ide> * An object of url details
<ide> */
<ide> export const parseUrl = function(url) {
<add> // This entire method can be replace with URL once we are able to drop IE11
<add>
<ide> const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];
<ide>
<ide> // add the url to an anchor and let the browser parse the URL
<del> let a = document.createElement('a');
<add> const a = document.createElement('a');
<ide>
<ide> a.href = url;
<ide>
<del> // IE8 (and 9?) Fix
<del> // ie8 doesn't parse the URL correctly until the anchor is actually
<del> // added to the body, and an innerHTML is needed to trigger the parsing
<del> const addToBody = (a.host === '' && a.protocol !== 'file:');
<del> let div;
<del>
<del> if (addToBody) {
<del> div = document.createElement('div');
<del> div.innerHTML = `<a href="${url}"></a>`;
<del> a = div.firstChild;
<del> // prevent the div from affecting layout
<del> div.setAttribute('style', 'display:none; position:absolute;');
<del> document.body.appendChild(div);
<del> }
<del>
<ide> // Copy the specific URL properties to a new object
<del> // This is also needed for IE8 because the anchor loses its
<add> // This is also needed for IE because the anchor loses its
<ide> // properties when it's removed from the dom
<ide> const details = {};
<ide>
<ide> for (let i = 0; i < props.length; i++) {
<ide> details[props[i]] = a[props[i]];
<ide> }
<ide>
<del> // IE9 adds the port to the host property unlike everyone else. If
<add> // IE adds the port to the host property unlike everyone else. If
<ide> // a port identifier is added for standard ports, strip it.
<ide> if (details.protocol === 'http:') {
<ide> details.host = details.host.replace(/:80$/, '');
<ide> export const parseUrl = function(url) {
<ide> details.protocol = window.location.protocol;
<ide> }
<ide>
<del> if (addToBody) {
<del> document.body.removeChild(div);
<add> /* istanbul ignore if */
<add> if (!details.host) {
<add> details.host = window.location.host;
<ide> }
<ide>
<ide> return details;
<ide><path>test/unit/utils/url.test.js
<ide> import * as Url from '../../../src/js/utils/url.js';
<ide>
<ide> QUnit.module('url');
<ide> QUnit.test('should parse the details of a url correctly', function(assert) {
<del> assert.equal(
<del> Url.parseUrl('#').protocol,
<del> window.location.protocol,
<del> 'parsed relative url protocol'
<del> );
<add> assert.equal(Url.parseUrl('#').protocol, window.location.protocol, 'parsed relative url protocol');
<ide> assert.equal(Url.parseUrl('#').host, window.location.host, 'parsed relative url host');
<add> assert.equal(Url.parseUrl('#foo').hash, '#foo', 'parsed relative url hash');
<ide>
<ide> assert.equal(Url.parseUrl('http://example.com').protocol, 'http:', 'parsed example url protocol');
<ide> assert.equal(Url.parseUrl('http://example.com').hostname, 'example.com', 'parsed example url hostname'); | 2 |
PHP | PHP | fix empty use | 8162ba0b244fecac25fac1881f08298f846e4801 | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _debugPostTokenNotMatching(Controller $controller, $hashParts
<ide> );
<ide> $expectedUnlockedFields = Hash::get($expectedParts, 2);
<ide> $dataUnlockedFields = Hash::get($hashParts, 2) ?: [];
<del> if (!empty($dataUnlockedFields)) {
<add> if ($dataUnlockedFields) {
<ide> $dataUnlockedFields = explode('|', $dataUnlockedFields);
<ide> }
<ide> $unlockFieldsMessages = $this->_debugCheckFields( | 1 |
Python | Python | change action endpoint for success future and past | c99138b7008412246a488dbf8162e0be8dbac861 | <ide><path>airflow/www/app.py
<ide> import dateutil.parser
<ide> from functools import wraps
<ide> import inspect
<add>from itertools import product
<ide> import json
<ide> import logging
<ide> import os
<ide> def action(self):
<ide> confirmed = request.args.get('confirmed') == "true"
<ide> upstream = request.args.get('upstream') == "true"
<ide> downstream = request.args.get('downstream') == "true"
<add> future = request.args.get('future') == "true"
<add> past = request.args.get('past') == "true"
<ide>
<ide> if action == "run":
<ide> from airflow.executors import DEFAULT_EXECUTOR as executor
<ide> def action(self):
<ide> return redirect(origin)
<ide>
<ide> elif action == 'clear':
<del> future = request.args.get('future') == "true"
<del> past = request.args.get('past') == "true"
<del>
<ide> dag = dag.sub_dag(
<ide> task_regex=r"^{0}$".format(task_id),
<ide> include_downstream=downstream,
<ide> def action(self):
<ide> # Flagging tasks as successful
<ide> session = settings.Session()
<ide> task_ids = [task_id]
<add> end_date = ((dag.latest_execution_date or datetime.now())
<add> if future else execution_date)
<add> start_date = dag.default_args['start_date'] if past else execution_date
<add>
<ide> if downstream:
<ide> task_ids += [
<ide> t.task_id
<ide> def action(self):
<ide> t.task_id
<ide> for t in task.get_flat_relatives(upstream=True)]
<ide> TI = models.TaskInstance
<add> dates = utils.date_range(start_date, end_date)
<ide> tis = session.query(TI).filter(
<ide> TI.dag_id == dag_id,
<del> TI.execution_date == execution_date,
<add> TI.execution_date.in_(dates),
<ide> TI.task_id.in_(task_ids)).all()
<add> tasks = list(product(task_ids, dates))
<ide>
<ide> if confirmed:
<ide>
<del> updated_task_ids = []
<add> updated_tasks = []
<ide> for ti in tis:
<del> updated_task_ids.append(ti.task_id)
<add> updated_tasks.append((ti.task_id, ti.execution_date))
<ide> ti.state = State.SUCCESS
<ide>
<ide> session.commit()
<ide>
<del> to_insert = list(set(task_ids) - set(updated_task_ids))
<del> for task_id in to_insert:
<add> to_insert = list(set(tasks) - set(updated_tasks))
<add> for task_id, task_execution_date in to_insert:
<ide> ti = TI(
<ide> task=dag.get_task(task_id),
<del> execution_date=execution_date,
<add> execution_date=task_execution_date,
<ide> state=State.SUCCESS)
<ide> session.add(ti)
<ide> session.commit()
<ide> def action(self):
<ide> response = redirect(origin)
<ide> else:
<ide> tis = []
<del> for task_id in task_ids:
<add> for task_id, task_execution_date in tasks:
<ide> tis.append(TI(
<ide> task=dag.get_task(task_id),
<del> execution_date=execution_date,
<add> execution_date=task_execution_date,
<ide> state=State.SUCCESS))
<ide> details = "\n".join([str(t) for t in tis])
<ide> | 1 |
Python | Python | update asset logic | d6aa4cb478e9ba9c85f0c20de30f4b991a2b5432 | <ide><path>spacy/cli/project.py
<ide> def fetch_asset(
<ide> project_path: Path, url: str, dest: Path, checksum: Optional[str] = None
<ide> ) -> None:
<ide> check_asset(url)
<del> dest_path = project_path / dest
<add> dest_path = (project_path / dest).resolve()
<ide> if dest_path.exists() and checksum:
<ide> # If there's already a file, check for checksum
<del> # TODO: add support for chaches
<add> # TODO: add support for caches
<ide> if checksum == get_checksum(dest_path):
<ide> msg.good(f"Skipping download with matching checksum: {dest}")
<ide> return
<ide> def fetch_asset(
<ide> out = subprocess.check_output(dvc_cmd, stderr=subprocess.DEVNULL)
<ide> print(out)
<ide> except subprocess.CalledProcessError:
<del> # TODO: Can we read out Weak ETags error?
<ide> # TODO: replace curl
<del> run_command(["curl", url, "--output", str(dest_path)])
<add> run_command(["curl", url, "--output", str(dest_path), "--progress-bar"])
<ide> run_command(["dvc", "add", str(dest_path)])
<ide> msg.good(f"Fetched asset {dest}")
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.