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
Mixed
Javascript
add onhovermove support
4e59d4f5d26a620a2c6e8804a589b227481a80aa
<ide><path>packages/react-events/README.md <ide> const TextField = (props) => ( <ide> <ide> ```js <ide> // Types <del>type FocusEvent = {} <add>type FocusEvent = { <add> type: 'blur' | 'focus' | 'focuschange' <add>} <ide> ``` <ide> <ide> ### disabled: boolean <ide> const Link = (props) => ( <ide> <ide> ```js <ide> // Types <del>type HoverEvent = {} <add>type HoverEvent = { <add> pointerType: 'mouse', <add> type: 'hoverstart' | 'hoverend' | 'hovermove' | 'hoverchange' <add>} <ide> ``` <ide> <ide> ### delayHoverEnd: number <ide> Called when the element changes hover state (i.e., after `onHoverStart` and <ide> Called once the element is no longer hovered. It will be cancelled if the <ide> pointer leaves the element before the `delayHoverStart` threshold is exceeded. <ide> <add>### onHoverMove: (e: HoverEvent) => void <add> <add>Called when the pointer moves within the hit bounds of the element. `onHoverMove` is <add>called immediately and doesn't wait for delayed `onHoverStart`. <add> <ide> ### onHoverStart: (e: HoverEvent) => void <ide> <ide> Called once the element is hovered. It will not be called if the pointer leaves <ide> the element before the `delayHoverStart` threshold is exceeded. And it will not <ide> be called more than once before `onHoverEnd` is called. <ide> <add>### preventDefault: boolean = true <add> <add>Whether to `preventDefault()` native events. <add> <add>### stopPropagation: boolean = true <add> <add>Whether to `stopPropagation()` native events. <add> <ide> <ide> ## Press <ide> <ide> const Button = (props) => ( <ide> <ide> ```js <ide> // Types <del>type PressEvent = {} <add>type PressEvent = { <add> pointerType: 'mouse' | 'touch' | 'pen' | 'keyboard', <add> type: 'press' | 'pressstart' | 'pressend' | 'presschange' | 'pressmove' | 'longpress' | 'longpresschange' <add>} <ide> <ide> type PressOffset = { <ide> top: number, <ide> called during a press. <ide> <ide> ### onPressMove: (e: PressEvent) => void <ide> <del>Called when an active press moves within the hit bounds of the element. Never <del>called for keyboard-initiated press events. <add>Called when a press moves within the hit bounds of the element. `onPressMove` is <add>called immediately and doesn't wait for delayed `onPressStart`. Never called for <add>keyboard-initiated press events. <ide> <ide> ### onPressStart: (e: PressEvent) => void <ide> <ide> Defines how far the pointer (while held down) may move outside the bounds of the <ide> element before it is deactivated. Once deactivated, the pointer (still held <ide> down) can be moved back within the bounds of the element to reactivate it. <ide> Ensure you pass in a constant to reduce memory allocations. <add> <add>### preventDefault: boolean = true <add> <add>Whether to `preventDefault()` native events. <add> <add>### stopPropagation: boolean = true <add> <add>Whether to `stopPropagation()` native events. <ide><path>packages/react-events/src/Hover.js <ide> type HoverProps = { <ide> delayHoverStart: number, <ide> onHoverChange: boolean => void, <ide> onHoverEnd: (e: HoverEvent) => void, <add> onHoverMove: (e: HoverEvent) => void, <ide> onHoverStart: (e: HoverEvent) => void, <ide> }; <ide> <ide> type HoverState = { <ide> isTouched: boolean, <ide> hoverStartTimeout: null | Symbol, <ide> hoverEndTimeout: null | Symbol, <add> skipMouseAfterPointer: boolean, <ide> }; <ide> <del>type HoverEventType = 'hoverstart' | 'hoverend' | 'hoverchange'; <add>type HoverEventType = 'hoverstart' | 'hoverend' | 'hoverchange' | 'hovermove'; <ide> <ide> type HoverEvent = {| <ide> listener: HoverEvent => void, <ide> const targetEventTypes = [ <ide> <ide> // If PointerEvents is not supported (e.g., Safari), also listen to touch and mouse events. <ide> if (typeof window !== 'undefined' && window.PointerEvent === undefined) { <del> targetEventTypes.push('touchstart', 'mouseover', 'mouseout'); <add> targetEventTypes.push('touchstart', 'mouseover', 'mousemove', 'mouseout'); <ide> } <ide> <ide> function createHoverEvent( <ide> const HoverResponder = { <ide> isTouched: false, <ide> hoverStartTimeout: null, <ide> hoverEndTimeout: null, <add> skipMouseAfterPointer: false, <ide> }; <ide> }, <ide> onEvent( <ide> const HoverResponder = { <ide> state.isTouched = true; <ide> return; <ide> } <add> if (type === 'pointerover') { <add> state.skipMouseAfterPointer = true; <add> } <ide> if ( <ide> context.isPositionWithinTouchHitTarget( <ide> target.ownerDocument, <ide> const HoverResponder = { <ide> } <ide> state.isInHitSlop = false; <ide> state.isTouched = false; <add> state.skipMouseAfterPointer = false; <ide> break; <ide> } <ide> <del> case 'pointermove': { <add> case 'pointermove': <add> case 'mousemove': { <add> if (type === 'mousemove' && state.skipMouseAfterPointer === true) { <add> return; <add> } <add> <ide> if (state.isHovered && !state.isTouched) { <ide> if (state.isInHitSlop) { <ide> if ( <ide> const HoverResponder = { <ide> dispatchHoverStartEvents(event, context, props, state); <ide> state.isInHitSlop = false; <ide> } <del> } else if ( <del> state.isHovered && <del> context.isPositionWithinTouchHitTarget( <del> target.ownerDocument, <del> (nativeEvent: any).x, <del> (nativeEvent: any).y, <del> ) <del> ) { <del> dispatchHoverEndEvents(event, context, props, state); <del> state.isInHitSlop = true; <add> } else if (state.isHovered) { <add> if ( <add> context.isPositionWithinTouchHitTarget( <add> target.ownerDocument, <add> (nativeEvent: any).x, <add> (nativeEvent: any).y, <add> ) <add> ) { <add> dispatchHoverEndEvents(event, context, props, state); <add> state.isInHitSlop = true; <add> } else { <add> if (props.onHoverMove) { <add> const syntheticEvent = createHoverEvent( <add> 'hovermove', <add> event.target, <add> props.onHoverMove, <add> ); <add> context.dispatchEvent(syntheticEvent, {discrete: false}); <add> } <add> } <ide> } <ide> } <ide> break; <ide><path>packages/react-events/src/Press.js <ide> import type { <ide> ReactResponderEvent, <ide> ReactResponderContext, <add> ReactResponderDispatchEventOptions, <ide> } from 'shared/ReactTypes'; <ide> import {REACT_EVENT_COMPONENT_TYPE} from 'shared/ReactSymbols'; <ide> <ide> function dispatchEvent( <ide> state: PressState, <ide> name: PressEventType, <ide> listener: (e: Object) => void, <add> options?: ReactResponderDispatchEventOptions, <ide> ): void { <ide> const target = ((state.pressTarget: any): Element | Document); <ide> const pointerType = state.pointerType; <ide> const syntheticEvent = createPressEvent(name, target, listener, pointerType); <del> context.dispatchEvent(syntheticEvent, { <del> discrete: true, <del> }); <add> context.dispatchEvent( <add> syntheticEvent, <add> options || { <add> discrete: true, <add> }, <add> ); <ide> state.didDispatchEvent = true; <ide> } <ide> <ide> const PressResponder = { <ide> if (isPressWithinResponderRegion(nativeEvent, state)) { <ide> state.isPressWithinResponderRegion = true; <ide> if (props.onPressMove) { <del> dispatchEvent(context, state, 'pressmove', props.onPressMove); <add> dispatchEvent(context, state, 'pressmove', props.onPressMove, { <add> discrete: false, <add> }); <ide> } <ide> } else { <ide> state.isPressWithinResponderRegion = false; <ide><path>packages/react-events/src/__tests__/Hover-test.internal.js <ide> describe('Hover event responder', () => { <ide> }); <ide> }); <ide> <add> describe('onHoverMove', () => { <add> it('is called after "pointermove"', () => { <add> const onHoverMove = jest.fn(); <add> const ref = React.createRef(); <add> const element = ( <add> <Hover onHoverMove={onHoverMove}> <add> <div ref={ref} /> <add> </Hover> <add> ); <add> ReactDOM.render(element, container); <add> <add> ref.current.getBoundingClientRect = () => ({ <add> top: 50, <add> left: 50, <add> bottom: 500, <add> right: 500, <add> }); <add> ref.current.dispatchEvent(createPointerEvent('pointerover')); <add> ref.current.dispatchEvent( <add> createPointerEvent('pointermove', {pointerType: 'mouse'}), <add> ); <add> ref.current.dispatchEvent(createPointerEvent('touchmove')); <add> ref.current.dispatchEvent(createPointerEvent('mousemove')); <add> expect(onHoverMove).toHaveBeenCalledTimes(1); <add> expect(onHoverMove).toHaveBeenCalledWith( <add> expect.objectContaining({type: 'hovermove'}), <add> ); <add> }); <add> }); <add> <ide> it('expect displayName to show up for event component', () => { <ide> expect(Hover.displayName).toBe('Hover'); <ide> });
4
PHP
PHP
fix issue with case in authorizeresource
3f693da808f4cc77e15c9932ee1019f00c627ada
<ide><path>src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php <ide> protected function normalizeGuessedAbilityName($ability) <ide> */ <ide> public function authorizeResource($model, $parameter = null, array $options = [], $request = null) <ide> { <del> $parameter = $parameter ?: strtolower(class_basename($model)); <add> $parameter = $parameter ?: lcfirst(class_basename($model)); <ide> <ide> $middleware = []; <ide>
1
Ruby
Ruby
use const_get to get validator classes
f2695d2dc08fa739be9277adfe10386126f1a9b1
<ide><path>activemodel/lib/active_model/validations/validates.rb <ide> def validates(*attributes) <ide> key = "#{key.to_s.camelize}Validator" <ide> <ide> begin <del> validator = key.include?("::") ? key.constantize : const_get(key) <add> validator = const_get(key) <ide> rescue NameError <ide> raise ArgumentError, "Unknown validator: '#{key}'" <ide> end
1
Python
Python
take care of global vectors in multiprocessing
d307e9ca58c84dc24e6717fccafe7b55c604ee7c
<ide><path>spacy/_ml.py <ide> def link_vectors_to_models(vocab): <ide> key = (ops.device, vectors.name) <ide> if key in thinc.extra.load_nlp.VECTORS: <ide> if thinc.extra.load_nlp.VECTORS[key].shape != data.shape: <del> # This is a hack to avoid the problem in #3853. Maybe we should <del> # print a warning as well? <add> # This is a hack to avoid the problem in #3853. <ide> old_name = vectors.name <ide> new_name = vectors.name + "_%d" % data.shape[0] <ide> user_warning(Warnings.W019.format(old=old_name, new=new_name)) <ide><path>spacy/language.py <ide> <ide> import random <ide> import itertools <add> <add>from thinc.extra import load_nlp <add> <ide> from spacy.util import minibatch <ide> import weakref <ide> import functools <ide> def _multiprocessing_pipe(self, texts, pipes, n_process, batch_size): <ide> procs = [ <ide> mp.Process( <ide> target=_apply_pipes, <del> args=(self.make_doc, pipes, rch, sch, Underscore.get_state()), <add> args=(self.make_doc, pipes, rch, sch, Underscore.get_state(), load_nlp.VECTORS), <ide> ) <ide> for rch, sch in zip(texts_q, bytedocs_send_ch) <ide> ] <ide> def _pipe(docs, proc, kwargs): <ide> yield doc <ide> <ide> <del>def _apply_pipes(make_doc, pipes, receiver, sender, underscore_state): <add>def _apply_pipes(make_doc, pipes, receiver, sender, underscore_state, vectors): <ide> """Worker for Language.pipe <ide> <ide> receiver (multiprocessing.Connection): Pipe to receive text. Usually <ide> created by `multiprocessing.Pipe()` <ide> sender (multiprocessing.Connection): Pipe to send doc. Usually created by <ide> `multiprocessing.Pipe()` <ide> underscore_state (tuple): The data in the Underscore class of the parent <add> vectors (dict): The global vectors data, copied from the parent <ide> """ <ide> Underscore.load_state(underscore_state) <add> load_nlp.VECTORS = vectors <ide> while True: <ide> texts = receiver.get() <ide> docs = (make_doc(text) for text in texts) <ide><path>spacy/tests/regression/test_issue4725.py <add># coding: utf8 <add>from __future__ import unicode_literals <add> <add>import numpy <add> <add>from spacy.lang.en import English <add>from spacy.vocab import Vocab <add> <add> <add>def test_issue4725(): <add> # ensures that this runs correctly and doesn't hang or crash because of the global vectors <add> vocab = Vocab(vectors_name="test_vocab_add_vector") <add> data = numpy.ndarray((5, 3), dtype="f") <add> data[0] = 1.0 <add> data[1] = 2.0 <add> vocab.set_vector("cat", data[0]) <add> vocab.set_vector("dog", data[1]) <add> <add> nlp = English(vocab=vocab) <add> ner = nlp.create_pipe("ner") <add> nlp.add_pipe(ner) <add> nlp.begin_training() <add> docs = ["Kurt is in London."] * 10 <add> for _ in nlp.pipe(docs, batch_size=2, n_process=2): <add> pass <add> <ide><path>spacy/tests/regression/test_issue4849.py <ide> <ide> from spacy.lang.en import English <ide> from spacy.pipeline import EntityRuler <del>from spacy.tokens.underscore import Underscore <ide> <ide> <ide> def test_issue4849(): <ide><path>spacy/tests/regression/test_issue4903.py <ide> # coding: utf8 <ide> from __future__ import unicode_literals <ide> <del>import spacy <ide> from spacy.lang.en import English <ide> from spacy.tokens import Span, Doc <del>from spacy.tokens.underscore import Underscore <ide> <ide> <ide> class CustomPipe:
5
Python
Python
add coverage for blueprint.add_app_template_global
7ce01ab9b4aac9e559cd6cb2e309381cfc3cc71b
<ide><path>tests/test_blueprints.py <ide> def app_page(): <ide> <ide> assert b'42' in answer_page_bytes <ide> assert b'43' in answer_page_bytes <add> <add>def test_template_global(): <add> app = flask.Flask(__name__) <add> bp = flask.Blueprint('bp', __name__) <add> @bp.app_template_global() <add> def get_answer(): <add> return 42 <add> # Make sure the function is not in the jinja_env already <add> assert 'get_answer' not in app.jinja_env.globals.keys() <add> app.register_blueprint(bp) <add> <add> # Tests <add> assert 'get_answer' in app.jinja_env.globals.keys() <add> assert app.jinja_env.globals['get_answer'] is get_answer <add> assert app.jinja_env.globals['get_answer']() == 42 <add> <add> with app.app_context(): <add> rv = flask.render_template_string('{{ get_answer() }}') <add> assert rv == '42'
1
Text
Text
update license text to include guide
1e631c3b256797e0584fbd4deecebb909c0625ad
<ide><path>README.md <ide> Copyright © 2019 freeCodeCamp.org <ide> <ide> The content of this repository is bound by the following licenses: <ide> <del>- The computer software is licensed under the [BSD-3-Clause](LICENSE.md) License. <del>- The [curricular content](https://www.npmjs.com/package/@freecodecamp/curriculum) in the [`/curriculum`](/curriculum) folder and its subdirectories are licensed under the [CC-BY-SA-4.0](/curriculum/LICENSE.md) License. <add>- The computer software is licensed under the [BSD-3-Clause](LICENSE.md) license. <add>- The learning resources in the [`/curriculum`](/curriculum) and [`/guide`](/guide) directories including their subdirectories thereon are licensed under the [CC-BY-SA-4.0](/curriculum/LICENSE.md) license.
1
PHP
PHP
add failing unit test for
a280ddbbb1de5a3fc676b03b19c8ee8b81ba1f0d
<ide><path>tests/Routing/RoutingRouteTest.php <ide> public function testNonGreedyMatches() <ide> $this->assertEquals('bar', $route->parameter('foo', 'bar')); <ide> } <ide> <add> public function testRouteParametersDefaultValue() <add> { <add> $router = $this->getRouter(); <add> $router->get('foo/{bar?}', ['uses' => 'RouteTestControllerWithParameterStub@returnParameter'])->defaults('bar', 'foo'); <add> $this->assertEquals('foo', $router->dispatch(Request::create('foo', 'GET'))->getContent()); <add> <add> $router->get('foo/{bar?}', function ($bar = '') { return $bar; })->defaults('bar', 'foo'); <add> $this->assertEquals('foo', $router->dispatch(Request::create('foo', 'GET'))->getContent()); <add> } <add> <ide> /** <ide> * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException <ide> */ <ide> public function index() <ide> } <ide> } <ide> <add>class RouteTestControllerWithParameterStub extends Illuminate\Routing\Controller <add>{ <add> public function returnParameter($bar = '') <add> { <add> return $bar; <add> } <add>} <add> <ide> class RouteTestControllerMiddleware <ide> { <ide> public function handle($request, $next)
1
Ruby
Ruby
remove useless status set
11ccdc8f171e8de87ef94e91a5305d73595c7dbf
<ide><path>actionpack/lib/action_controller/metal/head.rb <ide> def head(status, options = {}) <ide> headers[key.to_s.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s <ide> end <ide> <del> response.status = Rack::Utils.status_code(status) <del> <ide> self.status = status <ide> self.location = url_for(location) if location <ide>
1
Ruby
Ruby
fix code style
8b7f38faf0e770c8446f328364e639e78307f062
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> def latest_version(formula_or_cask, json: false, full_name: false, verbose: fals <ide> livecheck_strategy: livecheck_strategy, <ide> url_provided: livecheck_url.present?, <ide> regex_provided: livecheck_regex.present?, <del> block_provided: livecheck.strategy_block.present?, <add> block_provided: livecheck.strategy_block.present?, <ide> ) <ide> strategy = Strategy.from_symbol(livecheck_strategy) <ide> strategy ||= strategies.first <ide><path>Library/Homebrew/livecheck/strategy.rb <ide> def from_url(url, livecheck_strategy: nil, url_provided: nil, regex_provided: ni <ide> if strategy == PageMatch <ide> # Only treat the `PageMatch` strategy as usable if a regex is <ide> # present in the `livecheck` block <del> next unless (regex_provided || block_provided) <add> next unless regex_provided || block_provided <ide> elsif strategy == Sparkle && (livecheck_strategy || !url_provided) <ide> # Skip the `Sparkle` strategy if a strategy is specified explicitly <ide> # or if the URL is not specified explicitly.
2
PHP
PHP
add accessor for pivot timestamp informaiton
cbe8123a479e81779cd85251eb4a5cf861e93ea3
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> class BelongsToMany extends Relation <ide> */ <ide> protected $pivotWhereIns = []; <ide> <add> /** <add> * Indicates if timestamps are available on the pivot table. <add> * <add> * @var bool <add> */ <add> public $withTimestamps = false; <add> <ide> /** <ide> * The custom pivot table column for the created_at timestamp. <ide> * <ide> public function getRelationCountHash() <ide> */ <ide> public function withTimestamps($createdAt = null, $updatedAt = null) <ide> { <add> $this->withTimestamps = true; <add> <ide> $this->pivotCreatedAt = $createdAt; <ide> $this->pivotUpdatedAt = $updatedAt; <ide>
1
Python
Python
use correct class to indicate present deprecation
2de50818296b1b4bae68787626c0236752e35101
<ide><path>rest_framework/__init__.py <ide> default_app_config = 'rest_framework.apps.RestFrameworkConfig' <ide> <ide> <del>class RemovedInDRF315Warning(PendingDeprecationWarning): <add>class RemovedInDRF315Warning(DeprecationWarning): <ide> pass
1
Python
Python
support extra argument in python 2.4
d0e984b8b4bb4423b97bc2b1cf180b3991f874ab
<ide><path>celery/utils/compat.py <ide> def __init__(self, logger, extra): <ide> self.logger = logger <ide> self.extra = extra <ide> <add> def setLevel(self, level): <add> self.level = logging._checkLevel(level) <add> <ide> def process(self, msg, kwargs): <ide> kwargs["extra"] = self.extra <ide> return msg, kwargs <ide> <ide> def debug(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.debug(msg, *args, **kwargs) <add> self.log(logging.DEBUG, msg, args, **kwargs) <ide> <ide> def info(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.info(msg, *args, **kwargs) <add> self.log(logging.INFO, msg, *args, **kwargs) <ide> <ide> def warning(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.warning(msg, *args, **kwargs) <del> <del> def warn(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.warn(msg, *args, **kwargs) <add> self.log(logging.WARNING, msg, *args, **kwargs) <add> warn = warning <ide> <ide> def error(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.error(msg, *args, **kwargs) <add> self.log(logging.ERROR, msg, *args, **kwargs) <ide> <ide> def exception(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> kwargs["exc_info"] = 1 <del> self.logger.error(msg, *args, **kwargs) <add> kwargs.setdefault("exc_info", 1) <add> self.error(msg, *args, **kwargs) <ide> <ide> def critical(self, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.critical(msg, *args, **kwargs) <add> self.log(logging.CRITICAL, msg, *args, **kwargs) <add> fatal = critical <ide> <ide> def log(self, level, msg, *args, **kwargs): <del> msg, kwargs = self.process(msg, kwargs) <del> self.logger.log(level, msg, *args, **kwargs) <add> if self.logger.isEnabledFor(level): <add> msg, kwargs = self.process(msg, kwargs) <add> self._log(level, msg, *args, **kwargs) <add> <add> def makeRecord(self, name, level, fn, lno, msg, args, exc_info, <add> func=None, extra=None): <add> rv = logging.LogRecord(name, level, fn, lno, <add> msg, args, exc_info, func) <add> if extra is not None: <add> for key, value in extra.items(): <add> if key in ("message", "asctime") or key in rv.__dict__: <add> raise KeyError( <add> "Attempt to override %r in LogRecord" % key) <add> rv.__dict__[key] = value <add> return rv <add> <add> def _log(self, level, msg, args, exc_info=None, extra=None): <add> defcaller = "(unknown file)", 0, "(unknown function)" <add> if logging._srcfile: <add> # IronPython doesn't track Python frames, so findCaller <add> # throws an exception on some versions of IronPython. <add> # We trap it here so that IronPython can use logging. <add> try: <add> fn, lno, func = self.logger.findCaller() <add> except ValueError: <add> fn, lno, func = defcaller <add> else: <add> fn, lno, func = defcaller <add> if exc_info: <add> if not isinstance(exc_info, tuple): <add> exc_info = sys.exc_info() <add> record = self.makeRecord(self.logger.name, level, fn, lno, msg, <add> args, exc_info, func, extra) <add> self.logger.handle(record) <ide> <ide> def isEnabledFor(self, level, *args, **kwargs): <ide> return self.logger.isEnabledFor(level, *args, **kwargs) <ide> <add> def addHandler(self, hdlr): <add> self.logger.addHandler(hdlr) <add> <add> def removeHandler(self, hdlr): <add> self.logger.removeHandler(hdlr) <add> <add> <add> <ide> ############## itertools.izip_longest ####################################### <ide> <ide> try:
1
Ruby
Ruby
make abstractadapter#lock thread local by default
6253874326b0c4f0b03dbe2d85d8ddf6ccb3354c
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def lock_thread=(lock_thread) <ide> end <ide> <ide> if (active_connection = @thread_cached_conns[connection_cache_key(current_thread)]) <del> active_connection.synchronized = lock_thread <add> active_connection.lock_thread = @lock_thread <ide> end <ide> end <ide> <ide> def clear_reloadable_connections! <ide> # - ActiveRecord::ConnectionTimeoutError no connection can be obtained from the pool. <ide> def checkout(checkout_timeout = @checkout_timeout) <ide> connection = checkout_and_verify(acquire_connection(checkout_timeout)) <del> connection.synchronized = @lock_thread <add> connection.lock_thread = @lock_thread <ide> connection <ide> end <ide> <ide> def checkin(conn) <ide> conn.expire <ide> end <ide> <add> conn.lock_thread = nil <ide> @available.add conn <ide> end <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def initialize(config_or_deprecated_connection, deprecated_logger = nil, depreca <ide> @idle_since = Process.clock_gettime(Process::CLOCK_MONOTONIC) <ide> @visitor = arel_visitor <ide> @statements = build_statement_pool <del> self.synchronized = false <add> self.lock_thread = nil <ide> <ide> @prepared_statements = self.class.type_cast_config_to_boolean( <ide> @config.fetch(:prepared_statements) { default_prepared_statements } <ide> def initialize(config_or_deprecated_connection, deprecated_logger = nil, depreca <ide> @verified = false <ide> end <ide> <del> def synchronized=(synchronized) # :nodoc: <del> @lock = if synchronized <add> def lock_thread=(lock_thread) # :nodoc: <add> @lock = <add> case lock_thread <add> when Thread <add> ActiveSupport::Concurrency::ThreadLoadInterlockAwareMonitor.new <add> when Fiber <ide> ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new <ide> else <ide> ActiveSupport::Concurrency::NullLock <ide><path>activerecord/test/cases/connection_pool_test.rb <ide> def setup <ide> @connection_test_model_class = ThreadConnectionTestModel <ide> end <ide> <add> def test_lock_thread_allow_fiber_reentrency <add> @pool.lock_thread = true <add> connection = @pool.checkout <add> connection.transaction do <add> enumerator = Enumerator.new do |yielder| <add> connection.transaction do <add> yielder.yield 1 <add> end <add> end <add> assert_equal 1, enumerator.next <add> end <add> end <add> <ide> private <ide> def new_thread(...) <ide> Thread.new(...) <ide><path>activesupport/lib/active_support/concurrency/load_interlock_aware_monitor.rb <ide> <ide> module ActiveSupport <ide> module Concurrency <del> # A monitor that will permit dependency loading while blocked waiting for <del> # the lock. <del> class LoadInterlockAwareMonitor < Monitor <add> module LoadInterlockAwareMonitorMixin # :nodoc: <ide> EXCEPTION_NEVER = { Exception => :never }.freeze <ide> EXCEPTION_IMMEDIATE = { Exception => :immediate }.freeze <ide> private_constant :EXCEPTION_NEVER, :EXCEPTION_IMMEDIATE <ide> def synchronize(&block) <ide> end <ide> end <ide> end <add> # A monitor that will permit dependency loading while blocked waiting for <add> # the lock. <add> class LoadInterlockAwareMonitor < Monitor <add> include LoadInterlockAwareMonitorMixin <add> end <add> <add> class ThreadLoadInterlockAwareMonitor # :nodoc: <add> prepend LoadInterlockAwareMonitorMixin <add> <add> def initialize <add> @owner = nil <add> @count = 0 <add> @mutex = Mutex.new <add> end <add> <add> private <add> def mon_try_enter <add> if @owner != Thread.current <add> return false unless @mutex.try_lock <add> @owner = Thread.current <add> end <add> @count += 1 <add> end <add> <add> def mon_enter <add> @mutex.lock if @owner != Thread.current <add> @owner = Thread.current <add> @count += 1 <add> end <add> <add> def mon_exit <add> unless @owner == Thread.current <add> raise ThreadError, "current thread not owner" <add> end <add> <add> @count -= 1 <add> return unless @count == 0 <add> @owner = nil <add> @mutex.unlock <add> end <add> end <ide> end <ide> end <ide><path>activesupport/test/concurrency/load_interlock_aware_monitor_test.rb <ide> <ide> module ActiveSupport <ide> module Concurrency <del> class LoadInterlockAwareMonitorTest < ActiveSupport::TestCase <del> def setup <del> @monitor = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new <del> end <del> <add> module LoadInterlockAwareMonitorTests <ide> def test_entering_with_no_blocking <ide> assert @monitor.mon_enter <ide> end <ide> def test_entering_with_blocking <ide> assert able_to_load <ide> end <ide> end <add> <add> class LoadInterlockAwareMonitorTest < ActiveSupport::TestCase <add> include LoadInterlockAwareMonitorTests <add> <add> def setup <add> @monitor = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new <add> end <add> end <add> <add> class ThreadLoadInterlockAwareMonitorTest < ActiveSupport::TestCase <add> include LoadInterlockAwareMonitorTests <add> <add> def setup <add> @monitor = ActiveSupport::Concurrency::ThreadLoadInterlockAwareMonitor.new <add> end <add> <add> def test_lock_owned_by_thread <add> @monitor.synchronize do <add> enumerator = Enumerator.new do |yielder| <add> @monitor.synchronize do <add> yielder.yield 42 <add> end <add> end <add> assert_equal 42, enumerator.next <add> end <add> end <add> end <ide> end <ide> end
5
Text
Text
update contributing instructions for new template
26c9b3c16b16671a87cb48913b883545796e866c
<ide><path>docs/how-to-help-with-video-challenges.md <ide> id: Unique identifier (alphanumerical, MongoDB_id) <ide> title: Challenge Title <ide> challengeType: 11 <ide> videoId: 'YouTube videoId for video challenge' <add>forumTopicId: 12345 <ide> --- <ide> <del>## Description <add># --description-- <ide> <del><section id='description'> <del>An optional description with helpful information related to the video. <del></section> <add>Challenge description text, in markdown <ide> <del>## Tests <add>```html <add><div> <add> example code <add></div> <add>``` <ide> <del><section id='tests'> <add># --question-- <ide> <del>```yml <del>question: <del> text: 'Question' <del> answers: <del> - 'Answer One' <del> - 'Answer Two' <del> - 'Answer Three' <del> solution: 3 <del>``` <add>These fields are currently used for the multiple choice Python challenges. <add> <add>## --text-- <add> <add>The question text goes here. <add> <add>## --answers-- <add> <add>Answer 1 <add> <add>--- <add> <add>Answer 2 <add> <add>--- <add> <add>More answers <add> <add>## --video-solution-- <add> <add>The number for the correct answer goes here. <ide> <del></section> <ide> ```` <ide> <ide> ## Creating questions for video challenges <ide> You can add the question locally or directly throught the GitHub interface. To a <ide> <ide> If a question has not yet been added to a particular video challenge, it will have the following default question: <ide> <del>```yml <del>question: <del> text: | <del> Question <del> answers: <del> - | <del> one <del> - | <del> two <del> - | <del> three <del> solution: 3 <del>``` <add>```md <add># --question-- <add> <add>## --text-- <add> <add>Question text <add> <add>## --answers-- <add> <add>Answer 1 <add> <add>--- <ide> <del>Update the word “Question” with your question. Update the “one”, “two”, and “three” with the possible answers. Make sure to update the solution number with which answer is correct. You can add more possible answers using the same format. The question and answers can be surrounded with quotation marks. <add>Answer 2 <ide> <del>#### Use markdown to format your question <add>--- <add> <add>More answers <ide> <del>The text in the question is parsed as markdown. The simplest way to ensure that it is formatted correctly is to start the question with `text: |`, like this: <add>## --video-solution-- <ide> <del>```yml <del>question: <del> text: | <del> Question <add>1 <ide> ``` <ide> <del>Then you need to make sure that your question is on a new line and indented one level more than `text: |`. <del> <del>The same approach can be used for the answers, so the entire question becomes <del> <del>```yml <del>question: <del> text: | <del> Question <del> answers: <del> - | <del> First answer <del> - | <del> Second <del> - | <del> Third <del> solution: 2 <add>Update the “Question Text” with your question. Update the `Answer 1`, `Answer 2`, and so on with the possible answers. Make sure to update the video-solution number with the correct answer number. You can add more possible answers using the same format. The question and answers can be surrounded with quotation marks. <add> <add>### Question examples <add> <add>````md <add># --question-- <add> <add>## --text-- <add>What does this JavaScript code log to the console? <add>```js <add>console.log('hello world'); <ide> ``` <ide> <del>Make sure each answer is plausible but there is only one correct answer. <add>## --answers-- <ide> <del>#### Use of HTML <add>hello *world* <ide> <del>Questions and answers can contain certain HTML tags like `<br>` for a new line. HTML tags should be used sparingly, when questions cannot be expressed without them. <add>--- <ide> <del>### Question examples <add>**hello** world <ide> <del>#### Examples without HTML <del> <del>````yml <del>question: <del> text: | <del> What does this JavaScript code log to the console? <del> ```js <del> console.log('hello world'); <del> ``` <del> <del> Select an answer! <del> answers: <del> - | <del> hello *world* <del> - | <del> **hello** world <del> - | <del> hello world <del> solution: 3 <del>```` <add>--- <add> <add>hello world <add> <add>--- <ide> <del>````yml <del>question: <del> text: | <del> What will print out after running this code: <del> ```py <del> width = 15 <del> height = 12.0 <del> print(height/3) <del> ``` <del> answers: <del> - | <del> 39 <del> - | <del> 4 <del> - | <del> 4.0 <del> - | <del> 5.0 <del> - | <del> 5 <del> solution: 3 <add>## --video-solution-- <add>3 <ide> ```` <ide> <del>#### Example with HTML <del> <del>```yml <del>question: <del> text: | <del> What will print out after running this code: <del> <pre><code>width = 15<br>height = 12.0<br>print(height/3)<code></pre> <del> answers: <del> - | <del> 39 <del> - | <del> 4 <del> - | <del> 4.0 <del> - | <del> 5.0 <del> - | <del> 5 <del> solution: 3 <add>````md <add> <add># --question-- <add> <add>## --text-- <add> <add>What will print out after running this code: <add> <add>```py <add>width = 15 <add>height = 12.0 <add>print(height/3) <ide> ``` <ide> <del>The final example demonstrates that HTML can be used, but that it is not as readable as the version without it. <add>## --answers-- <add> <add>39 <add> <add>--- <add> <add>4 <add> <add>--- <add> <add>4.0 <add> <add>--- <add> <add>5.0 <add> <add>--- <add> <add>5 <add> <add>## --video-solution-- <add> <add>3 <add>```` <ide> <ide> For more examples, you can look at the markdown files for the following video course. All the challenges already have questions: [Python for Everybody Course](https://github.com/freeCodeCamp/freeCodeCamp/tree/master/curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody) <ide> <ide><path>docs/how-to-work-on-coding-challenges.md <ide> Before you work on the curriculum, you would need to set up some tooling to help <ide> <ide> ## Challenge Template <ide> <del>Below is a template of what the challenge markdown files look like currently. To see the streamlined template we will be adopting see [below](#upcoming-challenge-template). <del> <ide> ````md <add> <ide> --- <ide> id: Unique identifier (alphanumerical, MongoDB_id) <del>title: Challenge Title <del>challengeType: 0 <add>title: 'Challenge Title' <add>challengeType: Integer, defined in `client/utils/challengeTypes.js` <ide> videoUrl: 'url of video explanation' <add>forumTopicId: 12345 <ide> --- <ide> <del>## Description <add># --description-- <ide> <del><section id='description'> <del>A Description of the challenge and what is required to pass <del></section> <add>Challenge description text, in markdown <ide> <del>## Instructions <add>```html <add><div> <add> example code <add></div> <add>``` <ide> <del><section id='instructions'> <del>Instructions about what exactly needs to be done. <del></section> <add># --instructions-- <ide> <del>## Tests <add>Challenge instruction text, in markdown <ide> <del><section id='tests'> <add># --hints-- <ide> <del>```yml <del>tests: <del> - text: Should return "foo" <del> testString: 'A stringified function possibly using Chai asserts' <add>Tests to run against user code, in pairs of markdown text and codeblock test code. <add> <add>```js <add>Code for test one <ide> ``` <ide> <del></section> <add>More instructions in markdown syntax <add> <add>```js <add>More code <add>``` <ide> <del>## Challenge Seed <add># --seed-- <ide> <del><section id='challengeSeed'> <add>## --before-user-code-- <ide> <del><div id='{ext}-seed'> <add>```lang <add>Code evaluated before the user’s code. <add>``` <ide> <del>```{ext} <del>Code displayed in the editor by default. <add>## --after-user-code-- <ide> <del>This is a required section for the challenge. <add>```lang <add>Code evaluated after the user’s code, and just before the tests <ide> ``` <ide> <del></div> <add>## --seed-contents-- <ide> <del>### Before Test <add>Boilerplate code to render to the editor. This section should only contain code inside backticks, like the following: <ide> <del><div id='{ext}-setup'> <add>```html <add><body> <add> <p class="main-text"> <add> Hello world! <add> </p> <add></body> <add>``` <ide> <del>```{ext} <del>Optional Test setup code. <add>```css <add>body { <add> margin: 0; <add> background-color: #3a3240; <add>} <add> <add>.main-text { <add> color: #aea8d3; <add>} <ide> ``` <ide> <del></div> <add>```js <add>console.log('freeCodeCamp is awesome!'); <add>``` <ide> <del>### After Test <add># --solutions-- <ide> <del><div id='{ext}-teardown'> <add>Solutions are used for the CI tests to ensure that changes to the hints will still pass as intended <ide> <del>```{ext} <del>Optional Test tear down code. <add>```js <add>// first solution - the language(s) should match the seed. <ide> ``` <ide> <del></div> <del> <del></section> <add>--- <ide> <del>## Solution <add>```js <add>// second solution - so if the seed is written in HTML... <add>``` <ide> <del><section id='solution'> <add>--- <ide> <del>```{ext} <del>// solution required <add>```js <add>// third solution etc. - Your solutions should be in HTML. <ide> ``` <ide> <del></section> <add># --question-- <add> <add>These fields are currently used for the multiple choice Python challenges. <add> <add>## --text-- <add> <add>The question text goes here. <add> <add>## --answers-- <add> <add>Answer 1 <add> <add>--- <add> <add>Answer 2 <add> <add>--- <add> <add>More answers <add> <add>## --video-solution-- <add> <add>The number for the correct answer goes here. <add> <add> <ide> ```` <ide> <ide> > [!NOTE] <ide> > <del>> 1. In the above sections, examples of `{ext}` are: <add>> 1. In the above sections, examples of `lang` are: <ide> > <ide> > - `html` - HTML/CSS <ide> > - `js` - JavaScript <ide> > - `jsx` - JSX <del>> <del>> 2. For the `Tests` section above, `text` and `testString` should be valid YAML strings. `testString` can be a stringified function or expression using which could use Chai asserts. <ide> <ide> ## Numbering Challenges <ide> <ide> Our goal is to have thousands of 2-minute challenges. These can flow together an <ide> <ide> Here are specific formatting guidelines for challenge text and examples: <ide> <del>- Language keywords go in `<code>` tags. For example, HTML tag names or CSS property names <del>- The first instance of a keyword when it's being defined, or general keywords (e.g. "object" or "immutable") go in `<dfn>` tags <del>- References to code parts (i.e. function, method or variable names) should be wrapped in `<code>` tags. See example below: <add>- Language keywords go in `\`` backticks. For example, HTML tag names or CSS property names. <add>- References to code parts (i.e. function, method or variable names) should be wrapped in `\`` backticks. See example below: <ide> ```md <del>Use <code>parseInt</code> to convert the variable <code>realNumber</code> into an integer. <add>Use `parseInt` to convert the variable `realNumber` into an integer. <ide> ``` <del>- References to file names and path directories (e.g. `package.json`, `src/components`) should be wrapped in `<code>` tags. <add>- References to file names and path directories (e.g. `package.json`, `src/components`) should be wrapped in `\`` backticks. <ide> - Multi-line code blocks **must be preceded by an empty line**. The next line must start with three backticks followed immediately by one of the [supported languages](https://prismjs.com/#supported-languages). To complete the code block, you must start a newline which only has three backticks and **another empty line**. See example below: <ide> - Whitespace matters in Markdown, so we recommend that you make it visible in your editor. <ide> <ide> The following is an example of code: <ide> ``` <ide> ```` <ide> <del>- Additional information in the form of a note should be formatted `<strong>Note:</strong> Rest of note text...` <del>- If multiple notes are needed, then list all of the notes in separate sentences using the format `<strong>Notes:</strong> First note text. Second note text.`. <add>- Additional information in the form of a note should be formatted `**Note:** Rest of note text...` <add>- If multiple notes are needed, then list all of the notes in separate sentences using the format `**Notes:** First note text. Second note text.`. <ide> - Use single-quotes where applicable <ide> <del>**Note:** The equivalent _Markdown_ should be used, where applicable, in place of _HTML_ tags. <add>**Note:** The equivalent _Markdown_ should be used in place of _HTML_ tags. <ide> <ide> ## Writing tests <ide> <ide> Example of valid single line JavaScript comment: <ide> <ide> Example of a valid CSS comment: <ide> <del>```js <add>```css <ide> /* Only change code above this line */ <ide> ``` <ide> <ide> Once you have verified that each challenge you've worked on passes the tests, [p <ide> > <ide> > The currently accepted values are `english` and `chinese`, with `english` being set by default. <ide> <del>## Upcoming Challenge Template <del> <del>The challenge template in the process of being updated to a cleaner, less nested structure. <del> <del>````md <del> <del>--- <del>id: Unique identifier (alphanumerical, MongoDB_id) <del>title: 'Challenge Title' <del>challengeType: Integer, defined in `client/utils/challengeTypes.js` <del>videoUrl: 'url of video explanation' <del>forumTopicId: 12345 <del>--- <del> <del>::import{component="Script" from="./script.md" } <del> <del># --description-- <del> <del>Description text, in markdown <del> <del>```html <del><div> <del> example code <del></div> <del>``` <del> <del># --hints-- <del> <del>There will be an arbitrary number of pairs of instructions (in markdown) and code blocks. <del> <del>```js <del>Code for test one <del>``` <del> <del>More instructions in markdown syntax <del> <del>```js <del>More code <del>``` <del> <del># --seed-- <del> <del>## --before-user-code-- <del> <del>```lang <del>Code evaluated before the user’s <del>``` <del> <del>## --after-user-code-- <del> <del>```lang <del>Code evaluated after the user’s, and just before the tests <del>``` <del> <del>## --seed-contents-- <del> <del>::id{#index-html} <del> <del>```html <del>Some html <del>``` <del> <del>```css <del>Some css <del>``` <del> <del>```js <del>Some js <del>``` <del> <del>::id{#index-js} <del> <del>::use{component="Script"} <del> <del> <del># --solutions-- <del> <del>Exactly the same as the seeds section <del> <del>--- <del> <del>second solution <del> <del>--- <del> <del>third solution etc. <del> <del># --question-- <del> <del>## --text-- <del> <del>The question would go here (only used for video challenges) <del> <del>## --answers-- <del> <del>Answer 1 <del> <del>--- <del> <del>Answer 2 <del> <del>--- <del> <del>More answers <del> <del>## --video-solution-- <del> <del>\<number of correct answer\> <del> <del> <del>```` <del> <ide> ### Useful Links <ide> <ide> Creating and Editing Challenges:
2
Python
Python
allow `replace` flag in gcs_to_gcs operator.
ed5004cca753650dc222fbb8e67573938c6c16d9
<ide><path>airflow/providers/google/cloud/transfers/gcs_to_gcs.py <ide> class GCSToGCSOperator(BaseOperator): <ide> of copied to the new location. This is the equivalent of a mv command <ide> as opposed to a cp command. <ide> :type move_object: bool <add> :param replace: Whether you want to replace existing destination files or not. <add> :type replace: bool <ide> :param delimiter: This is used to restrict the result to only the 'files' in a given 'folder'. <ide> If source_objects = ['foo/bah/'] and delimiter = '.avro', then only the 'files' in the <ide> folder 'foo/bah/' with '.avro' delimiter will be copied to the destination object. <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> destination_object=None, <ide> delimiter=None, <ide> move_object=False, <add> replace=True, <ide> gcp_conn_id='google_cloud_default', <ide> google_cloud_storage_conn_id=None, <ide> delegate_to=None, <ide> def __init__(self, # pylint: disable=too-many-arguments <ide> self.destination_object = destination_object <ide> self.delimiter = delimiter <ide> self.move_object = move_object <add> self.replace = replace <ide> self.gcp_conn_id = gcp_conn_id <ide> self.delegate_to = delegate_to <ide> self.last_modified_time = last_modified_time <ide> def _copy_source_with_wildcard(self, hook, prefix): <ide> self.log.info('Delimiter ignored because wildcard is in prefix') <ide> prefix_, delimiter = prefix.split(WILDCARD, 1) <ide> objects = hook.list(self.source_bucket, prefix=prefix_, delimiter=delimiter) <add> if not self.replace: <add> # If we are not replacing, list all files in the Destination GCS bucket <add> # and only keep those files which are present in <add> # Source GCS bucket and not in Destination GCS bucket <add> <add> existing_objects = hook.list(self.destination_bucket, prefix=prefix_, delimiter=delimiter) <add> <add> objects = set(objects) - set(existing_objects) <add> if len(objects) > 0: <add> self.log.info( <add> '%s files are going to be synced: %s.', len(objects), objects <add> ) <add> else: <add> self.log.info( <add> 'There are no new files to sync. Have a nice day!') <ide> for source_object in objects: <ide> if self.destination_object is None: <ide> destination_object = source_object <ide><path>tests/providers/google/cloud/transfers/test_gcs_to_gcs.py <ide> def test_execute_no_suffix(self, mock_hook): <ide> TEST_BUCKET, prefix="test_object", delimiter="" <ide> ) <ide> <add> @mock.patch('airflow.providers.google.cloud.transfers.gcs_to_gcs.GCSHook') <add> def test_execute_wildcard_with_replace_flag_false(self, mock_hook): <add> operator = GCSToGCSOperator( <add> task_id=TASK_ID, source_bucket=TEST_BUCKET, <add> source_object=SOURCE_OBJECT_WILDCARD_SUFFIX, <add> destination_bucket=DESTINATION_BUCKET, <add> replace=False) <add> <add> operator.execute(None) <add> mock_calls = [ <add> mock.call(TEST_BUCKET, prefix="test_object", delimiter=""), <add> mock.call(DESTINATION_BUCKET, prefix="test_object", delimiter=""), <add> ] <add> mock_hook.return_value.list.assert_has_calls(mock_calls) <add> <ide> @mock.patch('airflow.providers.google.cloud.transfers.gcs_to_gcs.GCSHook') <ide> def test_execute_prefix_and_suffix(self, mock_hook): <ide> operator = GCSToGCSOperator(
2
Python
Python
keep shape of the initial (dummy) state
41741c38e5f29ebf69fe9bd82a604eba3c0b97e5
<ide><path>keras/backend/tensorflow_backend.py <ide> def _step(input, state): <ide> new_state = new_states[0] <ide> else: <ide> # return dummy state, otherwise _dynamic_rnn_loop breaks <del> new_state = output <add> new_state = state <ide> return output, new_state <ide> <ide> _step.state_size = state_size * nb_states
1
Text
Text
fix mistake made in renamespacing
8618e230995193a740277b53ae3edbcc24702a37
<ide><path>README.md <ide> MyApp.president = Ember.Object.create({ <ide> name: "Barack Obama" <ide> }); <ide> <del>MyApp.country = Ember({ <add>MyApp.country = Ember.Object.create({ <ide> // Ending a property with 'Binding' tells Ember.js to <ide> // create a binding to the presidentName property. <ide> presidentNameBinding: 'MyApp.president.name'
1
Ruby
Ruby
use method provided by minitest
64d5373981674575684af25c038900434ed2dbb6
<ide><path>railties/lib/rails/test_unit/reporter.rb <ide> def record(result) <ide> if output_inline? && result.failure && (!result.skipped? || options[:verbose]) <ide> io.puts <ide> io.puts <del> io.puts format_failures(result).map { |line| color_output(line, by: result) } <add> io.puts color_output(result, by: result) <ide> io.puts <ide> io.puts format_rerun_snippet(result) <ide> io.puts <ide> def format_line(result) <ide> "%s#%s = %.2f s = %s" % [result.class, result.name, result.time, result.result_code] <ide> end <ide> <del> def format_failures(result) <del> result.failures.map do |failure| <del> "#{failure.result_label}:\n#{result.location}:\n#{failure.message}\n" <del> end <del> end <del> <ide> def format_rerun_snippet(result) <ide> location, line = result.method(result.name).source_location <ide> "#{self.executable} #{relative_path_for(location)}:#{line}"
1
Python
Python
get mtime in utc
bf6910a639fffc6896c5aefe362edaf6f6b704fe
<ide><path>tests/test_helpers.py <ide> def index(): <ide> assert rv.status_code == 416 <ide> rv.close() <ide> <del> last_modified = datetime.datetime.fromtimestamp(os.path.getmtime( <add> last_modified = datetime.datetime.utcfromtimestamp(os.path.getmtime( <ide> os.path.join(app.root_path, 'static/index.html'))).replace( <ide> microsecond=0) <ide>
1
Javascript
Javascript
fix valid id range on chown, lchown, fchown
0a539ddc0ad53c609199465dcb85008811e57bd2
<ide><path>lib/fs.js <ide> const { <ide> parseFileMode, <ide> validateBuffer, <ide> validateInteger, <del> validateInt32, <del> validateUint32 <add> validateInt32 <ide> } = require('internal/validators'); <add>// 2 ** 32 - 1 <add>const kMaxUserId = 4294967295; <ide> <ide> let truncateWarn = true; <ide> let fs; <ide> function chmodSync(path, mode) { <ide> function lchown(path, uid, gid, callback) { <ide> callback = makeCallback(callback); <ide> path = getValidatedPath(path); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> binding.lchown(pathModule.toNamespacedPath(path), uid, gid, req); <ide> } <ide> <ide> function lchownSync(path, uid, gid) { <ide> path = getValidatedPath(path); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> const ctx = { path }; <ide> binding.lchown(pathModule.toNamespacedPath(path), uid, gid, undefined, ctx); <ide> handleErrorFromBinding(ctx); <ide> } <ide> <ide> function fchown(fd, uid, gid, callback) { <ide> validateInt32(fd, 'fd', 0); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> <ide> const req = new FSReqCallback(); <ide> req.oncomplete = makeCallback(callback); <ide> function fchown(fd, uid, gid, callback) { <ide> <ide> function fchownSync(fd, uid, gid) { <ide> validateInt32(fd, 'fd', 0); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> <ide> const ctx = {}; <ide> binding.fchown(fd, uid, gid, undefined, ctx); <ide> function fchownSync(fd, uid, gid) { <ide> function chown(path, uid, gid, callback) { <ide> callback = makeCallback(callback); <ide> path = getValidatedPath(path); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> <ide> const req = new FSReqCallback(); <ide> req.oncomplete = callback; <ide> function chown(path, uid, gid, callback) { <ide> <ide> function chownSync(path, uid, gid) { <ide> path = getValidatedPath(path); <del> validateUint32(uid, 'uid'); <del> validateUint32(gid, 'gid'); <add> validateInteger(uid, 'uid', -1, kMaxUserId); <add> validateInteger(gid, 'gid', -1, kMaxUserId); <ide> const ctx = { path }; <ide> binding.chown(pathModule.toNamespacedPath(path), uid, gid, undefined, ctx); <ide> handleErrorFromBinding(ctx); <ide><path>test/parallel/test-fs-fchown.js <ide> function testGid(input, errObj) { <ide> testGid(input, errObj); <ide> }); <ide> <del>[-1, 2 ** 32].forEach((input) => { <add>[-2, 2 ** 32].forEach((input) => { <ide> const errObj = { <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError', <ide> message: 'The value of "fd" is out of range. It must be ' + <ide> `>= 0 && <= 2147483647. Received ${input}` <ide> }; <ide> testFd(input, errObj); <del> errObj.message = 'The value of "uid" is out of range. It must be >= 0 && ' + <del> `< 4294967296. Received ${input}`; <add> errObj.message = 'The value of "uid" is out of range. It must be >= -1 && ' + <add> `<= 4294967295. Received ${input}`; <ide> testUid(input, errObj); <ide> errObj.message = errObj.message.replace('uid', 'gid'); <ide> testGid(input, errObj);
2
Go
Go
handle host-gateway with extra hosts
521b8c02cc8912dc05cf178f83ea73b1b77698bd
<ide><path>builder/builder-next/builder.go <ide> import ( <ide> "github.com/docker/docker/daemon/config" <ide> "github.com/docker/docker/daemon/images" <ide> "github.com/docker/docker/libnetwork" <add> "github.com/docker/docker/opts" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/streamformatter" <ide> "github.com/docker/go-units" <ide> type Opt struct { <ide> // Builder can build using BuildKit backend <ide> type Builder struct { <ide> controller *control.Controller <add> dnsconfig config.DNSConfig <ide> reqBodyHandler *reqBodyHandler <ide> <ide> mu sync.Mutex <ide> func New(opt Opt) (*Builder, error) { <ide> } <ide> b := &Builder{ <ide> controller: c, <add> dnsconfig: opt.DNSConfig, <ide> reqBodyHandler: reqHandler, <ide> jobs: map[string]*buildJob{}, <ide> } <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder. <ide> return nil, errors.Errorf("network mode %q not supported by buildkit", opt.Options.NetworkMode) <ide> } <ide> <del> extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts) <add> extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts, b.dnsconfig.HostGatewayIP) <ide> if err != nil { <ide> return nil, err <ide> } <ide> func (j *buildJob) SetUpload(ctx context.Context, rc io.ReadCloser) error { <ide> } <ide> <ide> // toBuildkitExtraHosts converts hosts from docker key:value format to buildkit's csv format <del>func toBuildkitExtraHosts(inp []string) (string, error) { <add>func toBuildkitExtraHosts(inp []string, hostGatewayIP net.IP) (string, error) { <ide> if len(inp) == 0 { <ide> return "", nil <ide> } <ide> hosts := make([]string, 0, len(inp)) <ide> for _, h := range inp { <del> parts := strings.Split(h, ":") <del> <del> if len(parts) != 2 || parts[0] == "" || net.ParseIP(parts[1]) == nil { <add> host, ip, ok := strings.Cut(h, ":") <add> if !ok || host == "" || ip == "" { <ide> return "", errors.Errorf("invalid host %s", h) <ide> } <del> hosts = append(hosts, parts[0]+"="+parts[1]) <add> // If the IP Address is a "host-gateway", replace this value with the <add> // IP address stored in the daemon level HostGatewayIP config variable. <add> if ip == opts.HostGatewayName { <add> gateway := hostGatewayIP.String() <add> if gateway == "" { <add> return "", fmt.Errorf("unable to derive the IP value for host-gateway") <add> } <add> ip = gateway <add> } else if net.ParseIP(ip) == nil { <add> return "", fmt.Errorf("invalid host %s", h) <add> } <add> hosts = append(hosts, host+"="+ip) <ide> } <ide> return strings.Join(hosts, ","), nil <ide> }
1
Javascript
Javascript
specify es6 in the parser
9a4c54d3509a24d90ed8775222c7fe3aedb1c3a8
<ide><path>lib/Parser.js <ide> Parser.prototype.parseCalculatedString = function parseCalculatedString(expressi <ide> }); <ide> <ide> Parser.prototype.parse = function parse(source, initialState) { <del> var ast = acorn.parse(source, {ranges: true, locations: true}); <add> var ast = acorn.parse(source, {ranges: true, locations: true, ecmaVersion: 6}); <ide> if(!ast || typeof ast !== "object") <ide> throw new Error("Source couldn't be parsed"); <ide> var oldScope = this.scope; <ide> Parser.prototype.parse = function parse(source, initialState) { <ide> }; <ide> <ide> Parser.prototype.evaluate = function evaluate(source) { <del> var ast = acorn.parse("("+source+")", {ranges: true, locations: true}); <add> var ast = acorn.parse("("+source+")", {ranges: true, locations: true, ecmaVersion: 6}); <ide> if(!ast || typeof ast !== "object" || ast.type !== "Program") <ide> throw new Error("evaluate: Source couldn't be parsed"); <ide> if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement")
1
Javascript
Javascript
expose totalpages to the webpack decorator
7e756ee5d94c0c483432bc7e0d05eb0093c81f4f
<ide><path>server/build/webpack.js <ide> export default async function getBaseWebpackConfig (dir, {dev = false, isServer <ide> } <ide> <ide> if (typeof config.webpack === 'function') { <del> webpackConfig = config.webpack(webpackConfig, {dir, dev, isServer, buildId, config, defaultLoaders}) <add> webpackConfig = config.webpack(webpackConfig, {dir, dev, isServer, buildId, config, defaultLoaders, totalPages}) <ide> } <ide> <ide> return webpackConfig
1
Java
Java
revert observable.range to support 0 for count
648a9564f7eaadba37983ee0ecb8bc87e10e7bdf
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public final static <T> Observable<Observable<T>> parallelMerge(Observable<Obser <ide> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229460.aspx">MSDN: Observable.Range</a> <ide> */ <ide> public final static Observable<Integer> range(int start, int count) { <del> if (count < 1) { <del> throw new IllegalArgumentException("Count must be positive"); <add> if (count < 0) { <add> throw new IllegalArgumentException("Count can not be negative"); <ide> } <ide> if ((start + count) > Integer.MAX_VALUE) { <ide> throw new IllegalArgumentException("start + count can not exceed Integer.MAX_VALUE");
1
PHP
PHP
add serializer option to memcached cache engine
bd3f005ab69189ab5cfec9e70d1391efccd83785
<ide><path>lib/Cake/Cache/Engine/MemcachedEngine.php <ide> class MemcachedEngine extends CacheEngine { <ide> */ <ide> public $settings = array(); <ide> <add>/** <add> * List of available serializer engine <add> * <add> * Memcached must be compiled with json and igbinary support to use these engines <add> * <add> * @var array <add> */ <add> public static $serializer = array( <add> 'igbinary' => Memcached::SERIALIZER_IGBINARY, <add> 'json' => Memcached::SERIALIZER_JSON, <add> 'php' => Memcached::SERIALIZER_PHP <add> ); <add> <ide> /** <ide> * Initialize the Cache Engine <ide> * <ide> public function init($settings = array()) { <ide> 'persistent' => false, <ide> 'login' => null, <ide> 'password' => null, <add> 'serializer' => 'php' <ide> ); <ide> parent::init($settings); <ide> <ide> public function init($settings = array()) { <ide> /** <ide> * Settings the memcached instance <ide> * <add> * @throws CacheException when the Memcached extension is not built with the desired serializer engine <ide> */ <ide> protected function _setOptions() { <ide> $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); <ide> <del> if (Memcached::HAVE_IGBINARY) { <del> $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY); <add> if (!array_key_exists($this->settings['serializer'], self::$serializer)) { <add> throw new CacheException( <add> __d('cake_dev', sprintf('%s is not a valid serializer engine for Memcached', $this->settings['serializer'])) <add> ); <ide> } <ide> <add> $serializer = self::$serializer['php']; <add> switch($this->settings['serializer']) { <add> case 'igbinary': <add> if (Memcached::HAVE_IGBINARY) { <add> $serializer = self::$serializer['igbinary']; <add> } <add> break; <add> case 'json': <add> if (Memcached::HAVE_JSON) { <add> $serializer = self::$serializer['json']; <add> } <add> break; <add> } <add> <add> $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $serializer); <add> <ide> // Check for Amazon ElastiCache instance <ide> if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) { <ide> $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE); <ide><path>lib/Cake/Test/Case/Cache/Engine/MemcachedEngineTest.php <ide> public function testSettings() { <ide> 'engine' => 'Memcached', <ide> 'login' => null, <ide> 'password' => null, <del> 'groups' => array() <add> 'groups' => array(), <add> 'serializer' => 'php' <ide> ); <ide> $this->assertEquals($expecting, $settings); <ide> } <ide> public function testCompressionSetting() { <ide> $this->assertTrue($MemcachedCompressed->getMemcached()->getOption(Memcached::OPT_COMPRESSION)); <ide> } <ide> <add>/** <add> * test accepts only valid serializer engine <add> * <add> * @return void <add> */ <add> public function testInvalidSerializerSetting() { <add> $Memcached = new TestMemcachedEngine(); <add> $settings = array( <add> 'engine' => 'Memcached', <add> 'servers' => array('127.0.0.1:11211'), <add> 'persistent' => false, <add> 'serializer' => 'invalid_serializer' <add> ); <add> <add> $this->setExpectedException( <add> 'CacheException', 'invalid_serializer is not a valid serializer engine for Memcached' <add> ); <add> $Memcached->init($settings); <add> } <add> <add>/** <add> * testPhpSerializerSetting method <add> * <add> * @return void <add> */ <add> public function testPhpSerializerSetting() { <add> $Memcached = new TestMemcachedEngine(); <add> $settings = array( <add> 'engine' => 'Memcached', <add> 'servers' => array('127.0.0.1:11211'), <add> 'persistent' => false, <add> 'serializer' => 'php' <add> ); <add> <add> $Memcached->init($settings); <add> $this->assertEquals(Memcached::SERIALIZER_PHP, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER)); <add> } <add> <add>/** <add> * testPhpSerializerSetting method <add> * <add> * @return void <add> */ <add> public function testJsonSerializerSetting() { <add> $this->skipIf( <add> !Memcached::HAVE_JSON, <add> 'Memcached extension is not compiled with json support' <add> ); <add> <add> $Memcached = new TestMemcachedEngine(); <add> $settings = array( <add> 'engine' => 'Memcached', <add> 'servers' => array('127.0.0.1:11211'), <add> 'persistent' => false, <add> 'serializer' => 'json' <add> ); <add> <add> $Memcached->init($settings); <add> $this->assertEquals(Memcached::SERIALIZER_JSON, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER)); <add> } <add> <add>/** <add> * testPhpSerializerSetting method <add> * <add> * @return void <add> */ <add> public function testIgbinarySerializerSetting() { <add> $this->skipIf( <add> !Memcached::HAVE_IGBINARY, <add> 'Memcached extension is not compiled with igbinary support' <add> ); <add> <add> $Memcached = new TestMemcachedEngine(); <add> $settings = array( <add> 'engine' => 'Memcached', <add> 'servers' => array('127.0.0.1:11211'), <add> 'persistent' => false, <add> 'serializer' => 'igbinary' <add> ); <add> <add> $Memcached->init($settings); <add> $this->assertEquals(Memcached::SERIALIZER_IGBINARY, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER)); <add> } <add> <ide> /** <ide> * test using authentication without memcached installed with SASL support <ide> * throw an exception
2
Python
Python
remove unnecessary itertools call
fba219f73765725afb7468c3c1b114df3e1a27f4
<ide><path>spacy/language.py <ide> def pipe( <ide> <ide> DOCS: https://spacy.io/api/language#pipe <ide> """ <del> # raw_texts will be used later to stop iterator. <del> texts, raw_texts = itertools.tee(texts) <ide> if n_threads != -1: <ide> warnings.warn(Warnings.W016, DeprecationWarning) <ide> if n_process == -1:
1
Python
Python
pass exc explicitly to the inner context
cb54c462b809e36d12af571fa36affb4af3f7e96
<ide><path>flask/ctx.py <ide> def pop(self, exc=None): <ide> <ide> # Get rid of the app as well if necessary. <ide> if self._pushed_application_context: <del> self._pushed_application_context.pop() <add> self._pushed_application_context.pop(exc) <ide> self._pushed_application_context = None <ide> <ide> def __enter__(self):
1
Text
Text
add special cases where bubble sort is reasonable
8c4ead7998ea7def4ace03e6641071f2678fe2cb
<ide><path>guide/english/algorithms/sorting-algorithms/bubble-sort/index.md <ide> title: Bubble Sort <ide> <ide> Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. <ide> <del>This is a very slow sorting algorithm compared to algorithms like quicksort, with worst-case complexity O(n^2). However, the tradeoff is that bubble sort is one of the easiest sorting algorithms to implement from scratch. <add>This is a very slow sorting algorithm compared to algorithms like quicksort, with worst-case complexity O(n^2). However, the tradeoff is that bubble sort is one of the easiest sorting algorithms to implement from scratch. As a result, bubble sort algorithm is commonly taught as the first sorting algorthim in Algorithm and Data structure classes. From technical perspective, bubble sort is reasonable for sorting small-sized arrays or specially when executing sort algorithms on computers with remarkably limited memory resources. <ide> <ide> ### Example: <ide>
1
Javascript
Javascript
skip non-pot texture fallback on webgl2
533ff0ec9caa98639de8bb3f2c9b9a639ff428b8
<ide><path>src/renderers/webgl/WebGLTextures.js <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> } <ide> <del> function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) { <add> function textureNeedsGenerateMipmaps( texture, supportsMips ) { <ide> <del> return texture.generateMipmaps && isPowerOfTwo && <add> return texture.generateMipmaps && supportsMips && <ide> texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; <ide> <ide> } <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> } <ide> <ide> var image = cubeImage[ 0 ], <del> isPowerOfTwoImage = isPowerOfTwo( image ), <add> supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2, <ide> glFormat = utils.convert( texture.format ), <ide> glType = utils.convert( texture.type ), <ide> glInternalFormat = getInternalFormat( glFormat, glType ); <ide> <del> setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage ); <add> setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips ); <ide> <ide> for ( var i = 0; i < 6; i ++ ) { <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> } <ide> <del> if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) { <add> if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { <ide> <ide> // We assume images for cube map have the same size. <ide> generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height ); <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> } <ide> <del> function setTextureParameters( textureType, texture, isPowerOfTwoImage ) { <add> function setTextureParameters( textureType, texture, supportsMips ) { <ide> <ide> var extension; <ide> <del> if ( isPowerOfTwoImage ) { <add> if ( supportsMips ) { <ide> <ide> _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) ); <ide> _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) ); <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> var needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false; <ide> var image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize ); <ide> <del> var isPowerOfTwoImage = isPowerOfTwo( image ), <add> var supportsMips = isPowerOfTwo( image ) || capabilities.isWebGL2, <ide> glFormat = utils.convert( texture.format ), <ide> glType = utils.convert( texture.type ), <ide> glInternalFormat = getInternalFormat( glFormat, glType ); <ide> <del> setTextureParameters( textureType, texture, isPowerOfTwoImage ); <add> setTextureParameters( textureType, texture, supportsMips ); <ide> <ide> var mipmap, mipmaps = texture.mipmaps; <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> // if there are no manual mipmaps <ide> // set 0 level mipmap and then use GL to generate other mipmap levels <ide> <del> if ( mipmaps.length > 0 && isPowerOfTwoImage ) { <add> if ( mipmaps.length > 0 && supportsMips ) { <ide> <ide> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> // if there are no manual mipmaps <ide> // set 0 level mipmap and then use GL to generate other mipmap levels <ide> <del> if ( mipmaps.length > 0 && isPowerOfTwoImage ) { <add> if ( mipmaps.length > 0 && supportsMips ) { <ide> <ide> for ( var i = 0, il = mipmaps.length; i < il; i ++ ) { <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> } <ide> <del> if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) { <add> if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { <ide> <ide> generateMipmap( _gl.TEXTURE_2D, texture, image.width, image.height ); <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> <ide> var isCube = ( renderTarget.isWebGLRenderTargetCube === true ); <ide> var isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true ); <del> var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); <add> var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2; <ide> <ide> // Setup framebuffer <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> if ( isCube ) { <ide> <ide> state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture ); <del> setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo ); <add> setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, supportsMips ); <ide> <ide> for ( var i = 0; i < 6; i ++ ) { <ide> <ide> setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i ); <ide> <ide> } <ide> <del> if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) { <add> if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { <ide> <ide> generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height ); <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> } else { <ide> <ide> state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture ); <del> setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo ); <add> setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, supportsMips ); <ide> setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D ); <ide> <del> if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) { <add> if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) { <ide> <ide> generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height ); <ide> <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, <ide> function updateRenderTargetMipmap( renderTarget ) { <ide> <ide> var texture = renderTarget.texture; <del> var isTargetPowerOfTwo = isPowerOfTwo( renderTarget ); <add> var supportsMips = isPowerOfTwo( renderTarget ) || capabilities.isWebGL2; <ide> <del> if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) { <add> if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) { <ide> <ide> var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D; <ide> var webglTexture = properties.get( texture ).__webglTexture;
1
Javascript
Javascript
replace var with const
e4507e545240809bd78031df5e965a5362f7987e
<ide><path>test/parallel/test-util-inspect.js <ide> assert.strictEqual(util.inspect(-5e-324), '-5e-324'); <ide> { <ide> let obj = vm.runInNewContext('(function(){return {}})()', {}); <ide> assert.strictEqual(util.inspect(obj), '{}'); <del> obj = vm.runInNewContext('var m=new Map();m.set(1,2);m', {}); <add> obj = vm.runInNewContext('const m=new Map();m.set(1,2);m', {}); <ide> assert.strictEqual(util.inspect(obj), 'Map(1) { 1 => 2 }'); <del> obj = vm.runInNewContext('var s=new Set();s.add(1);s.add(2);s', {}); <add> obj = vm.runInNewContext('const s=new Set();s.add(1);s.add(2);s', {}); <ide> assert.strictEqual(util.inspect(obj), 'Set(2) { 1, 2 }'); <ide> obj = vm.runInNewContext('fn=function(){};new Promise(fn,fn)', {}); <ide> assert.strictEqual(util.inspect(obj), 'Promise { <pending> }');
1
Python
Python
add broadcast command for starting actors
0ac876041ae686cb69240eb26b0f6d95299edbfc
<ide><path>celery/app/control.py <ide> def ping(self, destination=None, timeout=1, **kwargs): <ide> return self.broadcast('ping', reply=True, destination=destination, <ide> timeout=timeout, **kwargs) <ide> <del> def start_actor(self, actor_name, destination = None, timeout = 1, **kwargs): <del> return self.broadcast('start_actor', name = actor_name, reply=True, destination=destination, <add> def start_actor(self, actor_name, actor_id = None, <add> destination = None, timeout = 1, **kwargs): <add> return self.broadcast('start_actor', name = actor_name, <add> actor_id = actor_id, <add> reply=True, destination=destination, <ide> timeout=timeout, **kwargs) <ide> <ide> def rate_limit(self, task_name, rate_limit, destination=None, **kwargs):
1
Ruby
Ruby
fix postgresql tests on travis
c5989cc4837b5f814e14332a0b90a44dfa806b4e
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def supports_explain? <ide> true <ide> end <ide> <add> # Range datatypes weren't introduced until PostgreSQL 9.2 <add> def supports_ranges? <add> postgresql_version >= 90200 <add> end <add> <ide> # Returns the configured supported identifier length supported by PostgreSQL <ide> def table_alias_length <ide> @table_alias_length ||= query('SHOW max_identifier_length', 'SCHEMA')[0][0].to_i <ide><path>activerecord/test/cases/adapters/postgresql/datatype_test.rb <ide> def setup <ide> @connection.execute("INSERT INTO postgresql_arrays (id, commission_by_quarter, nicknames) VALUES (1, '{35000,21000,18000,17000}', '{foo,bar,baz}')") <ide> @first_array = PostgresqlArray.find(1) <ide> <del> @connection.execute <<_SQL <add> @connection.execute <<_SQL if @connection.supports_ranges? <ide> INSERT INTO postgresql_ranges ( <ide> date_range, <ide> num_range, <ide> def setup <ide> ) <ide> _SQL <ide> <del> @connection.execute <<_SQL <add> @connection.execute <<_SQL if @connection.supports_ranges? <ide> INSERT INTO postgresql_ranges ( <ide> date_range, <ide> num_range, <ide> def setup <ide> ) <ide> _SQL <ide> <del> @connection.execute <<_SQL <add> @connection.execute <<_SQL if @connection.supports_ranges? <ide> INSERT INTO postgresql_ranges ( <ide> date_range, <ide> num_range, <ide> def setup <ide> ) <ide> _SQL <ide> <del> @connection.execute <<_SQL <add> @connection.execute <<_SQL if @connection.supports_ranges? <ide> INSERT INTO postgresql_ranges ( <ide> date_range, <ide> num_range, <ide> def setup <ide> ) <ide> _SQL <ide> <del> @connection.execute <<_SQL <add> @connection.execute <<_SQL if @connection.supports_ranges? <ide> INSERT INTO postgresql_ranges ( <ide> date_range, <ide> num_range, <ide> def setup <ide> ) <ide> _SQL <ide> <del> @first_range = PostgresqlRange.find(1) <del> @second_range = PostgresqlRange.find(2) <del> @third_range = PostgresqlRange.find(3) <del> @fourth_range = PostgresqlRange.find(4) <del> @empty_range = PostgresqlRange.find(5) <add> if @connection.supports_ranges? <add> @first_range = PostgresqlRange.find(1) <add> @second_range = PostgresqlRange.find(2) <add> @third_range = PostgresqlRange.find(3) <add> @fourth_range = PostgresqlRange.find(4) <add> @empty_range = PostgresqlRange.find(5) <add> end <ide> <ide> @connection.execute("INSERT INTO postgresql_tsvectors (id, text_vector) VALUES (1, ' ''text'' ''vector'' ')") <ide> <ide> def test_data_type_of_array_types <ide> end <ide> <ide> def test_data_type_of_range_types <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal :daterange, @first_range.column_for_attribute(:date_range).type <ide> assert_equal :numrange, @first_range.column_for_attribute(:num_range).type <ide> assert_equal :tsrange, @first_range.column_for_attribute(:ts_range).type <ide> def test_tsvector_values <ide> end <ide> <ide> def test_int4range_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal 1...11, @first_range.int4_range <ide> assert_equal 2...10, @second_range.int4_range <ide> assert_equal 2...Float::INFINITY, @third_range.int4_range <ide> def test_int4range_values <ide> end <ide> <ide> def test_int8range_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal 10...101, @first_range.int8_range <ide> assert_equal 11...100, @second_range.int8_range <ide> assert_equal 11...Float::INFINITY, @third_range.int8_range <ide> def test_int8range_values <ide> end <ide> <ide> def test_daterange_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal Date.new(2012, 1, 2)...Date.new(2012, 1, 5), @first_range.date_range <ide> assert_equal Date.new(2012, 1, 3)...Date.new(2012, 1, 4), @second_range.date_range <ide> assert_equal Date.new(2012, 1, 3)...Float::INFINITY, @third_range.date_range <ide> def test_daterange_values <ide> end <ide> <ide> def test_numrange_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal BigDecimal.new('0.1')..BigDecimal.new('0.2'), @first_range.num_range <ide> assert_equal BigDecimal.new('0.1')...BigDecimal.new('0.2'), @second_range.num_range <ide> assert_equal BigDecimal.new('0.1')...BigDecimal.new('Infinity'), @third_range.num_range <ide> def test_numrange_values <ide> end <ide> <ide> def test_tsrange_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> tz = ::ActiveRecord::Base.default_timezone <ide> assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 0)..Time.send(tz, 2011, 1, 1, 14, 30, 0), @first_range.ts_range <ide> assert_equal Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 1, 1, 14, 30, 0), @second_range.ts_range <ide> def test_tsrange_values <ide> end <ide> <ide> def test_tstzrange_values <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> assert_equal Time.parse('2010-01-01 09:30:00 UTC')..Time.parse('2011-01-01 17:30:00 UTC'), @first_range.tstz_range <ide> assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Time.parse('2011-01-01 17:30:00 UTC'), @second_range.tstz_range <ide> assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Float::INFINITY, @third_range.tstz_range <ide> def test_money_values <ide> end <ide> <ide> def test_create_tstzrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> tstzrange = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2011-02-02 14:30:00 CDT') <ide> range = PostgresqlRange.new(:tstz_range => tstzrange) <ide> assert range.save <ide> def test_create_tstzrange <ide> end <ide> <ide> def test_update_tstzrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> new_tstzrange = Time.parse('2010-01-01 14:30:00 CDT')...Time.parse('2011-02-02 14:30:00 CET') <ide> assert @first_range.tstz_range = new_tstzrange <ide> assert @first_range.save <ide> def test_update_tstzrange <ide> end <ide> <ide> def test_create_tsrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> tz = ::ActiveRecord::Base.default_timezone <ide> tsrange = Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 2, 2, 14, 30, 0) <ide> range = PostgresqlRange.new(:ts_range => tsrange) <ide> def test_create_tsrange <ide> end <ide> <ide> def test_update_tsrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> tz = ::ActiveRecord::Base.default_timezone <ide> new_tsrange = Time.send(tz, 2010, 1, 1, 14, 30, 0)...Time.send(tz, 2011, 2, 2, 14, 30, 0) <ide> assert @first_range.ts_range = new_tsrange <ide> def test_update_tsrange <ide> end <ide> <ide> def test_create_numrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> numrange = BigDecimal.new('0.5')...BigDecimal.new('1') <ide> range = PostgresqlRange.new(:num_range => numrange) <ide> assert range.save <ide> def test_create_numrange <ide> end <ide> <ide> def test_update_numrange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> new_numrange = BigDecimal.new('0.5')...BigDecimal.new('1') <ide> assert @first_range.num_range = new_numrange <ide> assert @first_range.save <ide> def test_update_numrange <ide> end <ide> <ide> def test_create_daterange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> daterange = Range.new(Date.new(2012, 1, 1), Date.new(2013, 1, 1), true) <ide> range = PostgresqlRange.new(:date_range => daterange) <ide> assert range.save <ide> def test_create_daterange <ide> end <ide> <ide> def test_update_daterange <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> new_daterange = Date.new(2012, 2, 3)...Date.new(2012, 2, 10) <ide> assert @first_range.date_range = new_daterange <ide> assert @first_range.save <ide> def test_update_daterange <ide> end <ide> <ide> def test_create_int4range <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> int4range = Range.new(3, 50, true) <ide> range = PostgresqlRange.new(:int4_range => int4range) <ide> assert range.save <ide> def test_create_int4range <ide> end <ide> <ide> def test_update_int4range <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> new_int4range = 6...10 <ide> assert @first_range.int4_range = new_int4range <ide> assert @first_range.save <ide> def test_update_int4range <ide> end <ide> <ide> def test_create_int8range <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> int8range = Range.new(30, 50, true) <ide> range = PostgresqlRange.new(:int8_range => int8range) <ide> assert range.save <ide> def test_create_int8range <ide> end <ide> <ide> def test_update_int8range <add> skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges? <ide> new_int8range = 60000...10000000 <ide> assert @first_range.int8_range = new_int8range <ide> assert @first_range.save <ide><path>activerecord/test/schema/postgresql_specific_schema.rb <ide> ); <ide> _SQL <ide> <del> execute <<_SQL <add> execute <<_SQL if supports_ranges? <ide> CREATE TABLE postgresql_ranges ( <ide> id SERIAL PRIMARY KEY, <ide> date_range daterange,
3
Python
Python
add text_file_b fixture using bytesio
4bb5b89ee4bfbc75f070c7bd3a899a73a6fe3e87
<ide><path>spacy/tests/conftest.py <ide> from ..attrs import ORTH, TAG, HEAD, DEP <ide> from ..util import match_best_version, get_data_path <ide> <del>from io import StringIO <add>from io import StringIO, BytesIO <ide> from pathlib import Path <ide> import os <ide> import pytest <ide> def lemmatizer(path): <ide> def text_file(): <ide> return StringIO() <ide> <add>@pytest.fixture <add>def text_file_b(): <add> return BytesIO() <add> <ide> <ide> @pytest.fixture <ide> def path():
1
Go
Go
remove unnecessary windows-only code
6cc644abef088e04b5b416921f203f5edb733ad1
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerCLIRunSuite) TestRunCidFileCleanupIfEmpty(c *testing.T) { <ide> defer os.RemoveAll(tmpDir) <ide> tmpCidFile := path.Join(tmpDir, "cid") <ide> <add> // This must be an image that has no CMD or ENTRYPOINT set <ide> image := "emptyfs" <del> if testEnv.OSType == "windows" { <del> // Windows can't support an emptyfs image. Just use the regular Windows image <del> image = testEnv.PlatformDefaults.BaseImage <del> } <ide> out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image) <ide> if err == nil { <ide> c.Fatalf("Run without command must fail. out=%s", out)
1
Ruby
Ruby
fix typo in form_helper.rb
065d3e061dcefde7fa48037555bf23ac7f3ae440
<ide><path>actionview/lib/action_view/helpers/form_helper.rb <ide> def default_form_builder <ide> # methods in the +FormHelper+ module. This class, however, allows you to <ide> # call methods with the model object you are building the form for. <ide> # <del> # You can create your own custom FormBuilder templates by subclasses this <add> # You can create your own custom FormBuilder templates by subclassing this <ide> # class. For example: <ide> # <ide> # class MyFormBuilder < ActionView::Helpers::FormBuilder
1
Javascript
Javascript
convert `runloopassert` to es6 class
5b3a341d2d53223775d7e09ab11819a5d433290f
<ide><path>packages/internal-test-helpers/lib/ember-dev/run-loop.js <ide> import { cancelTimers, end, getCurrentRunLoop, hasScheduledTimers } from '@ember/runloop'; <ide> <del>function RunLoopAssertion(env) { <del> this.env = env; <del>} <add>export default class RunLoopAssertion { <add> constructor(env) { <add> this.env = env; <add> } <add> <add> reset() {} <ide> <del>RunLoopAssertion.prototype = { <del> reset: function() {}, <del> inject: function() {}, <del> assert: function() { <add> inject() {} <add> <add> assert() { <ide> let { assert } = QUnit.config.current; <ide> <ide> if (getCurrentRunLoop()) { <ide> RunLoopAssertion.prototype = { <ide> assert.ok(false, 'Ember run should not have scheduled timers at end of test'); <ide> cancelTimers(); <ide> } <del> }, <del> restore: function() {}, <del>}; <add> } <ide> <del>export default RunLoopAssertion; <add> restore() {} <add>}
1
Text
Text
give definitions for back-ground size properties
193bb311330bce7386bec0ba658b6258991a816d
<ide><path>guide/english/css/background-size/index.md <ide> title: Background Size <ide> The `background-size` property specifies the size of the background images. You can set a length or a percentage, with the first value being the width and the second one being the height. You can also use one of the 5 keyword values: <ide> <ide> ```css <del>/* Background size property values that can be used */ <add>/* Background size property values that can be used: */ <add> <ide> .auto {background-size: auto;} <add>/* auto uses the default size of the background image*/ <add> <ide> .cover {background-size: cover;} <add>/* scales the image as much as possible without changing its aspect ratio it to cover the entire element, cropping when necessary to ensure no empty space remains.*/ <add> <ide> .contain {background-size: contain;} <add>/* Scales the image to its largest size without changing its aspect ratio such that both its width and height can fit inside the element.*/ <add> <ide> .initial {background-size: initial;} <add>/* uses the initially or default size of the background image*/ <add> <ide> .inherit {background-size: inherit;} <del> /* Percentage, pixel, and viewport units can also be used */ <add>/* inherits the properties of its parent element*/ <add> <ide> .pixel {background-size: 50px 50px;} <add>/* specifies the exact height and width of the image*/ <add> <ide> .percentage {background-size: 50% 50%;} <add>/* changes the width and height based on the percentage specified*/ <add> <ide> .view {background-size: 50vw 50vh;} <ide> ``` <add> <ide> Note: If using pixel or percentage for length and you only specify one value, <ide> the second one will be set to auto by default. <ide>
1
Javascript
Javascript
add spec for platformconstants
7fd08e146184432731ec5d5ba210e352690dc569
<ide><path>Libraries/Animated/src/__tests__/Animated-test.js <ide> <ide> jest.mock('../../../BatchedBridge/NativeModules', () => ({ <ide> NativeAnimatedModule: {}, <add> PlatformConstants: { <add> getConstants() { <add> return {}; <add> }, <add> }, <ide> })); <ide> <ide> let Animated = require('../Animated'); <ide><path>Libraries/Animated/src/__tests__/AnimatedNative-test.js <ide> jest <ide> .setMock('react', {Component: class {}}) <ide> .mock('../../../BatchedBridge/NativeModules', () => ({ <ide> NativeAnimatedModule: {}, <add> PlatformConstants: { <add> getConstants() { <add> return {}; <add> }, <add> }, <ide> })) <ide> .mock('../NativeAnimatedModule') <ide> .mock('../../../EventEmitter/NativeEventEmitter') <ide><path>Libraries/Core/ReactNativeVersionCheck.js <ide> */ <ide> 'use strict'; <ide> <del>const {PlatformConstants} = require('../BatchedBridge/NativeModules'); <add>import Platform from '../Utilities/Platform'; <ide> const ReactNativeVersion = require('./ReactNativeVersion'); <ide> <ide> /** <ide> const ReactNativeVersion = require('./ReactNativeVersion'); <ide> * and rely on its existence as a separate module. <ide> */ <ide> exports.checkVersions = function checkVersions(): void { <del> if (!PlatformConstants) { <del> return; <del> } <del> <del> const nativeVersion = PlatformConstants.reactNativeVersion; <add> const nativeVersion = Platform.constants.reactNativeVersion; <ide> if ( <ide> ReactNativeVersion.version.major !== nativeVersion.major || <ide> ReactNativeVersion.version.minor !== nativeVersion.minor <ide> exports.checkVersions = function checkVersions(): void { <ide> function _formatVersion(version): string { <ide> return ( <ide> `${version.major}.${version.minor}.${version.patch}` + <del> (version.prerelease !== null ? `-${version.prerelease}` : '') <add> // eslint-disable-next-line eqeqeq <add> (version.prerelease != undefined ? `-${version.prerelease}` : '') <ide> ); <ide> } <ide><path>Libraries/Core/__tests__/ReactNativeVersionCheck-test.js <ide> function _mockNativeVersion( <ide> patch = 0, <ide> prerelease = null, <ide> ) { <del> jest.doMock('../../BatchedBridge/NativeModules', () => ({ <del> PlatformConstants: { <add> jest.doMock('../../Utilities/NativePlatformConstantsAndroid', () => ({ <add> getConstants: () => ({ <ide> reactNativeVersion: {major, minor, patch, prerelease}, <del> }, <add> }), <add> })); <add> jest.doMock('../../Utilities/NativePlatformConstantsIOS', () => ({ <add> getConstants: () => ({ <add> reactNativeVersion: {major, minor, patch, prerelease}, <add> }), <ide> })); <ide> } <ide><path>Libraries/Network/__tests__/XMLHttpRequest-test.js <ide> jest <ide> }, <ide> abortRequest: function() {}, <ide> }, <add> PlatformConstants: { <add> getConstants() { <add> return {}; <add> }, <add> }, <ide> }); <ide> <ide> const XMLHttpRequest = require('../XMLHttpRequest'); <ide><path>Libraries/Utilities/NativePlatformConstantsAndroid.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <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> * @flow strict-local <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from '../TurboModule/RCTExport'; <add>import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> +getConstants: () => {| <add> isTesting: boolean, <add> reactNativeVersion: {| <add> major: number, <add> minor: number, <add> patch: number, <add> prerelease: ?number, <add> |}, <add> Version: number, <add> Release: string, <add> Serial: string, <add> Fingerprint: string, <add> Model: string, <add> ServerHost: string, <add> uiMode: string, <add> |}; <add> +getAndroidID: () => string; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('PlatformConstants'); <ide><path>Libraries/Utilities/NativePlatformConstantsIOS.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <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> * @flow strict-local <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from '../TurboModule/RCTExport'; <add>import * as TurboModuleRegistry from '../TurboModule/TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> +getConstants: () => {| <add> isTesting: boolean, <add> reactNativeVersion: {| <add> major: number, <add> minor: number, <add> patch: number, <add> prerelease: ?number, <add> |}, <add> forceTouchAvailable: boolean, <add> osVersion: string, <add> systemName: string, <add> interfaceIdiom: string, <add> |}; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('PlatformConstants'); <ide><path>Libraries/Utilities/Platform.android.js <ide> <ide> 'use strict'; <ide> <del>const NativeModules = require('../BatchedBridge/NativeModules'); <add>import NativePlatformConstantsAndroid from './NativePlatformConstantsAndroid'; <ide> <ide> export type PlatformSelectSpec<A, D> = { <ide> android?: A, <ide> export type PlatformSelectSpec<A, D> = { <ide> const Platform = { <ide> OS: 'android', <ide> get Version() { <del> const constants = NativeModules.PlatformConstants; <del> return constants && constants.Version; <add> return NativePlatformConstantsAndroid.getConstants().Version; <add> }, <add> get constants() { <add> return NativePlatformConstantsAndroid.getConstants(); <ide> }, <ide> get isTesting(): boolean { <ide> if (__DEV__) { <del> const constants = NativeModules.PlatformConstants; <del> return constants && constants.isTesting; <add> return NativePlatformConstantsAndroid.getConstants().isTesting; <ide> } <ide> return false; <ide> }, <ide> get isTV(): boolean { <del> const constants = NativeModules.PlatformConstants; <del> return constants && constants.uiMode === 'tv'; <add> return NativePlatformConstantsAndroid.getConstants().uiMode === 'tv'; <ide> }, <ide> select: <A, D>(spec: PlatformSelectSpec<A, D>): A | D => <ide> 'android' in spec ? spec.android : spec.default, <ide><path>Libraries/Utilities/Platform.ios.js <ide> <ide> 'use strict'; <ide> <del>const NativeModules = require('../BatchedBridge/NativeModules'); <add>import NativePlatformConstantsIOS from './NativePlatformConstantsIOS'; <ide> <ide> export type PlatformSelectSpec<D, I> = { <ide> default?: D, <ide> export type PlatformSelectSpec<D, I> = { <ide> const Platform = { <ide> OS: 'ios', <ide> get Version() { <del> const constants = NativeModules.PlatformConstants; <del> return constants && constants.osVersion; <add> return NativePlatformConstantsIOS.getConstants().osVersion; <add> }, <add> get constants() { <add> return NativePlatformConstantsIOS.getConstants(); <ide> }, <ide> get isPad() { <del> const constants = NativeModules.PlatformConstants; <del> return constants ? constants.interfaceIdiom === 'pad' : false; <add> return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'pad'; <ide> }, <ide> /** <ide> * Deprecated, use `isTV` instead. <ide> const Platform = { <ide> return Platform.isTV; <ide> }, <ide> get isTV() { <del> const constants = NativeModules.PlatformConstants; <del> return constants ? constants.interfaceIdiom === 'tv' : false; <add> return NativePlatformConstantsIOS.getConstants().interfaceIdiom === 'tv'; <ide> }, <ide> get isTesting(): boolean { <ide> if (__DEV__) { <del> const constants = NativeModules.PlatformConstants; <del> return constants && constants.isTesting; <add> return NativePlatformConstantsIOS.getConstants().isTesting; <ide> } <ide> return false; <ide> }, <ide><path>RNTester/js/examples/Touchable/TouchableExample.js <ide> const { <ide> Text, <ide> TouchableHighlight, <ide> TouchableOpacity, <del> NativeModules, <ide> Platform, <ide> TouchableNativeFeedback, <ide> TouchableWithoutFeedback, <ide> View, <ide> } = require('react-native'); <ide> <ide> const forceTouchAvailable = <del> (NativeModules.PlatformConstants && <del> NativeModules.PlatformConstants.forceTouchAvailable) || <del> false; <add> (Platform.OS === 'ios' && Platform.constants.forceTouchAvailable) || false; <ide> <ide> class TouchableHighlightBox extends React.Component<{}, $FlowFixMeState> { <ide> state = { <ide><path>jest/setup.js <ide> const mockNativeModules = { <ide> addListener: jest.fn(), <ide> removeListeners: jest.fn(), <ide> }, <add> PlatformConstants: { <add> getConstants() { <add> return {}; <add> }, <add> }, <ide> PushNotificationManager: { <ide> presentLocalNotification: jest.fn(), <ide> scheduleLocalNotification: jest.fn(),
11
Python
Python
add qa_dropout and seq_classif_dropout
74d78beeb418f29cade9d6a0aeb63eeee697a4e2
<ide><path>pytorch_transformers/modeling_dilbert.py <ide> def __init__(self, <ide> activation='gelu', <ide> initializer_range=0.02, <ide> tie_weights_=True, <add> qa_dropout=0.1, <add> seq_classif_dropout=0.2, <ide> **kwargs): <ide> super(DilBertConfig, self).__init__(**kwargs) <ide> <ide> def __init__(self, <ide> self.activation = activation <ide> self.initializer_range = initializer_range <ide> self.tie_weights_ = tie_weights_ <add> self.qa_dropout = qa_dropout <add> self.seq_classif_dropout = seq_classif_dropout <ide> else: <ide> raise ValueError("First argument must be either a vocabulary size (int)" <ide> " or the path to a pretrained model config file (str)")
1
PHP
PHP
add temporary_url when creating flysystem
a22794263e85607bbf897c74dfde5f7172ce8910
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> protected function createFlysystem(AdapterInterface $adapter, array $config) <ide> { <ide> $cache = Arr::pull($config, 'cache'); <ide> <del> $config = Arr::only($config, ['visibility', 'disable_asserts', 'url']); <add> $config = Arr::only($config, ['visibility', 'disable_asserts', 'url', 'temporary_url']); <ide> <ide> if ($cache) { <ide> $adapter = new CachedAdapter($adapter, $this->createCacheStore($cache));
1
PHP
PHP
avoid unneeded function call
d44c091acf6c01dbd202e39a21a8a2f2724b2441
<ide><path>src/Illuminate/Support/Str.php <ide> public static function kebab($value) <ide> */ <ide> public static function length($value, $encoding = null) <ide> { <del> return mb_strlen($value, $encoding ?: mb_internal_encoding()); <add> if ($encoding) { <add> return mb_strlen($value, $encoding); <add> } <add> <add> return mb_strlen($value); <ide> } <ide> <ide> /**
1
Text
Text
stop false positives in test for array hard coding
ae0d34359a966a370bb7d7632caaa3f56c2382ad
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.md <ide> assert( <ide> `nonMutatingSort(globalArray)` should not be hard coded. <ide> <ide> ```js <del>assert(!nonMutatingSort.toString().match(/[23569]/g)); <add>assert(!nonMutatingSort.toString().match(/\[.*?[23569].*?\]/gs)); <ide> ``` <ide> <ide> The function should return a new array, not the array passed to it.
1
Java
Java
fix bindingreflectionhintsregistrar enum support
fb1aa4f5d5601ddd1fe7928b39c6408a3003a59a
<ide><path>spring-core/src/main/java/org/springframework/aot/hint/support/BindingReflectionHintsRegistrar.java <ide> private void registerReflectionHints(ReflectionHints hints, Set<Type> seen, Type <ide> PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); <ide> for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { <ide> Method writeMethod = propertyDescriptor.getWriteMethod(); <del> if (writeMethod != null && writeMethod.getDeclaringClass() != Object.class) { <add> if (writeMethod != null && writeMethod.getDeclaringClass() != Object.class <add> && writeMethod.getDeclaringClass() != Enum.class) { <ide> hints.registerMethod(writeMethod, INVOKE); <ide> MethodParameter methodParameter = MethodParameter.forExecutable(writeMethod, 0); <ide> Type methodParameterType = methodParameter.getGenericParameterType(); <ide> private void registerReflectionHints(ReflectionHints hints, Set<Type> seen, Type <ide> } <ide> } <ide> Method readMethod = propertyDescriptor.getReadMethod(); <del> if (readMethod != null && readMethod.getDeclaringClass() != Object.class) { <add> if (readMethod != null && readMethod.getDeclaringClass() != Object.class <add> && readMethod.getDeclaringClass() != Enum.class) { <ide> hints.registerMethod(readMethod, INVOKE); <ide> MethodParameter methodParameter = MethodParameter.forExecutable(readMethod, -1); <ide> Type methodParameterType = methodParameter.getGenericParameterType(); <ide> private void collectReferencedTypes(Set<Type> seen, Set<Class<?>> types, @Nullab <ide> } <ide> ResolvableType resolvableType = ResolvableType.forType(type); <ide> Class<?> clazz = resolvableType.resolve(); <del> if (clazz != null) { <add> if (clazz != null && !types.contains(clazz)) { <ide> types.add(clazz); <ide> for (ResolvableType genericResolvableType : resolvableType.getGenerics()) { <ide> collectReferencedTypes(seen, types, genericResolvableType.getType()); <ide><path>spring-core/src/test/java/org/springframework/aot/hint/support/BindingReflectionHintsRegistrarTests.java <ide> void registerTypeForSerializationWithMultipleLevelsAndCollection() { <ide> typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(Set.class))); <ide> } <ide> <add> @Test <add> void registerTypeForSerializationWithEnum() { <add> bindingRegistrar.registerReflectionHints(this.hints.reflection(), SampleEnum.class); <add> assertThat(this.hints.reflection().typeHints()).singleElement() <add> .satisfies(typeHint -> assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleEnum.class))); <add> } <add> <ide> <ide> static class SampleEmptyClass { <ide> } <ide> public String getString() { <ide> } <ide> } <ide> <add> enum SampleEnum { <add> value1, value2 <add> } <add> <ide> }
2
Python
Python
set version to v2.0.18.dev0
24d52876e1a09cf8041da282b93e688a1d2c5a6d
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy' <del>__version__ = '2.0.17' <add>__version__ = '2.0.18.dev0' <ide> __summary__ = 'Industrial-strength Natural Language Processing (NLP) with Python and Cython' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Explosion AI' <ide> __email__ = 'contact@explosion.ai' <ide> __license__ = 'MIT' <del>__release__ = True <add>__release__ = False <ide> <ide> __download_url__ = 'https://github.com/explosion/spacy-models/releases/download' <ide> __compatibility__ = 'https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json'
1
Javascript
Javascript
add type checking for hostname
85a4e257759d0da3dbebb501069a8a1f7130a392
<ide><path>lib/_http_client.js <ide> function isInvalidPath(s) { <ide> return false; <ide> } <ide> <add>function validateHost(host, name) { <add> if (host != null && typeof host !== 'string') { <add> throw new TypeError( <add> `"options.${name}" must either be a string, undefined or null`); <add> } <add> return host; <add>} <add> <ide> function ClientRequest(options, cb) { <ide> OutgoingMessage.call(this); <ide> <ide> function ClientRequest(options, cb) { <ide> this.agent && this.agent.defaultPort; <ide> <ide> var port = options.port = options.port || defaultPort || 80; <del> var host = options.host = options.hostname || options.host || 'localhost'; <add> var host = options.host = validateHost(options.hostname, 'hostname') || <add> validateHost(options.host, 'host') || 'localhost'; <ide> <ide> var setHost = (options.setHost === undefined); <ide> <ide><path>test/parallel/test-http-hostname-typechecking.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const http = require('http'); <add> <add>// All of these values should cause http.request() to throw synchronously <add>// when passed as the value of either options.hostname or options.host <add>const vals = [{}, [], NaN, Infinity, -Infinity, true, false, 1, 0, new Date()]; <add> <add>function errCheck(name) { <add> return new RegExp(`^TypeError: "options\\.${name}" must either be a ` + <add> 'string, undefined or null$'); <add>} <add> <add>vals.forEach((v) => { <add> assert.throws(() => http.request({hostname: v}), errCheck('hostname')); <add> assert.throws(() => http.request({host: v}), errCheck('host')); <add>}); <add> <add>// These values are OK and should not throw synchronously <add>['', undefined, null].forEach((v) => { <add> assert.doesNotThrow(() => { <add> http.request({hostname: v}).on('error', common.noop); <add> http.request({host: v}).on('error', common.noop); <add> }); <add>});
2
Go
Go
add test for pull verified
614e09a8c7990e05509edb4c335c4b59001cea61
<ide><path>integration-cli/docker_cli_pull_test.go <ide> func TestPullImageWithAliases(t *testing.T) { <ide> logDone("pull - image with aliases") <ide> } <ide> <add>// pulling busybox should show verified message <add>func TestPullVerified(t *testing.T) { <add> defer setupRegistry(t)() <add> <add> repo := fmt.Sprintf("%v/dockercli/busybox:verified", privateRegistryURL) <add> defer deleteImages(repo) <add> <add> // tag the image <add> if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "tag", "busybox", repo)); err != nil { <add> t.Fatalf("Failed to tag image verifiedTest: error %v, output %q", err, out) <add> } <add> <add> // push it <add> if out, err := exec.Command(dockerBinary, "push", repo).CombinedOutput(); err != nil { <add> t.Fatalf("Failed to push image %v: error %v, output %q", err, string(out)) <add> } <add> <add> // remove it locally <add> if out, err := exec.Command(dockerBinary, "rmi", repo).CombinedOutput(); err != nil { <add> t.Fatalf("Failed to clean images: error %v, output %q", err, string(out)) <add> } <add> <add> // pull it <add> expected := "The image you are pulling has been verified" <add> pullCmd := exec.Command(dockerBinary, "pull", repo) <add> if out, _, err := runCommandWithOutput(pullCmd); err != nil || !strings.Contains(out, expected) { <add> t.Fatalf("pulling a verified image failed. expected: %s\ngot: %s, %v", expected, out, err) <add> } <add> <add> // pull it again <add> pullCmd = exec.Command(dockerBinary, "pull", repo) <add> if out, _, err := runCommandWithOutput(pullCmd); err != nil || !strings.Contains(out, expected) { <add> t.Fatalf("pulling a verified image failed. expected: %s\ngot: %s, %v", expected, out, err) <add> } <add> <add> logDone("pull - pull verified") <add>} <add> <ide> // pulling an image from the central registry should work <ide> func TestPullImageFromCentralRegistry(t *testing.T) { <ide> pullCmd := exec.Command(dockerBinary, "pull", "hello-world")
1
Go
Go
add image size to -tree
b7d1d35c278c57ad4732dc23e529cf771158ee96
<ide><path>commands.go <ide> func PrintTreeNode(cli *DockerCli, noTrunc *bool, image APIImages, prefix string <ide> imageID = utils.TruncateID(image.ID) <ide> } <ide> <add> fmt.Fprintf(cli.out, "%s%s Size: %s (virtual %s)", prefix, imageID, utils.HumanSize(image.Size), utils.HumanSize(image.VirtualSize)) <ide> if image.RepoTags[0] != "<none>:<none>" { <del> fmt.Fprintf(cli.out, "%s%s Tags: %s\n", prefix, imageID, strings.Join(image.RepoTags, ",")) <add> fmt.Fprintf(cli.out, " Tags: %s\n", strings.Join(image.RepoTags, ",")) <ide> } else { <del> fmt.Fprintf(cli.out, "%s%s\n", prefix, imageID) <add> fmt.Fprint(cli.out, "\n") <ide> } <ide> } <ide> <ide><path>commands_test.go <ide> func TestImagesTree(t *testing.T) { <ide> cmdOutput := string(cmdOutputBytes) <ide> <ide> regexpStrings := []string{ <del> fmt.Sprintf("└─%s Tags: %s:latest", unitTestImageIDShort, unitTestImageName), <add> fmt.Sprintf("└─%s Size: (\\d+.\\d+ MB) \\(virtual \\d+.\\d+ MB\\) Tags: %s:latest", unitTestImageIDShort, unitTestImageName), <ide> "(?m)^ └─[0-9a-f]+", <ide> "(?m)^ └─[0-9a-f]+", <ide> "(?m)^ └─[0-9a-f]+", <del> fmt.Sprintf(" └─%s Tags: test:latest", utils.TruncateID(image.ID)), <add> fmt.Sprintf(" └─%s Size: \\d+.\\d+ kB \\(virtual \\d+.\\d+ MB\\) Tags: test:latest", utils.TruncateID(image.ID)), <ide> } <ide> <ide> compiledRegexps := []*regexp.Regexp{}
2
Python
Python
correct io counter and max cpu/mem
9a40395efb7d32c22c6adfb3efa9bb933cdce057
<ide><path>glances/plugins/glances_processlist.py <ide> def get_process_curses_data(self, p, first, args): <ide> msg = '{:>10}'.format('?') <ide> ret.append(self.curse_add_line(msg, optional=True)) <ide> # IO read/write <del> if 'io_counters' in p: <add> if 'io_counters' in p and p['io_counters'][4] == 1: <add> # Display rate if stats is available and io_tag ([4]) == 1 <ide> # IO read <ide> io_rs = int((p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update']) <ide> if io_rs == 0: <ide><path>glances/processes.py <ide> def update(self): <ide> if self.disable_tag: <ide> return <ide> <del> # Get the time since last update <del> time_since_update = getTimeSinceLastUpdate('process_disk') <del> <del> # Reset the max dict <del> self.reset_max_values() <del> <del> # Update the maximum process ID (pid) number <del> self.processcount['pid_max'] = self.pid_max <del> <del> # Only work whith PsUtil <add> # Grab the stats <ide> mandatories_attr = ['cmdline', 'cpu_percent', 'cpu_times', <ide> 'io_counters', 'memory_info', 'memory_percent', <ide> 'name', 'nice', 'pid', <ide> 'ppid', 'status', 'username'] <add> # and build the processes stats list <ide> self.processlist = [p.info for p in sorted(psutil.process_iter(attrs=mandatories_attr, <ide> ad_value=None), <ide> key=lambda p: p.info['cpu_percent'])] <ide> <del> # Add metadata <add> # Update the maximum process ID (pid) number <add> self.processcount['pid_max'] = self.pid_max <add> <add> # Compute the maximum value for keys in self._max_values_list <add> # Reset the max dict <add> self.reset_max_values() <add> # Compute max <add> for k in self._max_values_list: <add> self.set_max_values(k, max(i[k] for i in self.processlist)) <add> <add> # Loop over processes and add metadata <ide> for proc in self.processlist: <del> proc['time_since_update'] = time_since_update <del> # Status <add> # Time since last update (for disk_io rate computation) <add> proc['time_since_update'] = getTimeSinceLastUpdate('process_disk') <add> <add> # Process status (only keep the first char) <ide> proc['status'] = str(proc['status'])[:1].upper() <add> <ide> # Process IO <ide> # procstat['io_counters'] is a list: <ide> # [read_bytes, write_bytes, read_bytes_old, write_bytes_old, io_tag] <ide> # If io_tag = 0 > Access denied (display "?") <ide> # If io_tag = 1 > No access denied (display the IO rate) <ide> # Availability: all platforms except macOS and Illumos/Solaris <ide> if proc['io_counters'] is not None: <del> proc_io = proc['io_counters'] <del> io_new = [proc_io.read_bytes, proc_io.write_bytes] <add> io_new = [proc['io_counters'].read_bytes, <add> proc['io_counters'].write_bytes] <ide> # For IO rate computation <ide> # Append saved IO r/w bytes <ide> try: <ide> proc['io_counters'] = io_new + self.io_old[proc['pid']] <add> io_tag = 1 <ide> except KeyError: <ide> proc['io_counters'] = io_new + [0, 0] <add> io_tag = 0 <ide> # then save the IO r/w bytes <ide> self.io_old[proc['pid']] = io_new <del> io_tag = 1 <ide> else: <ide> proc['io_counters'] = [0, 0] + [0, 0] <ide> io_tag = 0
2
Go
Go
remove leading/trailing spaces in builder/parser
3859c485317a395de1e8eb48270d0e3b1207a204
<ide><path>builder/parser/utils.go <ide> func fullDispatch(cmd, args string) (*Node, map[string]bool, error) { <ide> // splitCommand takes a single line of text and parses out the cmd and args, <ide> // which are used for dispatching to more exact parsing functions. <ide> func splitCommand(line string) (string, string, error) { <del> cmdline := TOKEN_WHITESPACE.Split(line, 2) <add> // Make sure we get the same results irrespective of leading/trailing spaces <add> cmdline := TOKEN_WHITESPACE.Split(strings.TrimSpace(line), 2) <ide> <ide> if len(cmdline) != 2 { <ide> return "", "", fmt.Errorf("We do not understand this file. Please ensure it is a valid Dockerfile. Parser error at %q", line) <ide><path>integration-cli/docker_cli_build_test.go <ide> func TestBuildDockerfileOutsideContext(t *testing.T) { <ide> <ide> logDone("build - Dockerfile outside context") <ide> } <add> <add>func TestBuildSpaces(t *testing.T) { <add> // Test to make sure that leading/trailing spaces on a command <add> // doesn't change the error msg we get <add> var ( <add> err1 error <add> err2 error <add> ) <add> <add> name := "testspaces" <add> defer deleteImages(name) <add> ctx, err := fakeContext("FROM busybox\nRUN\n", <add> map[string]string{ <add> "Dockerfile": "FROM busybox\nRUN\n", <add> }) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer ctx.Close() <add> <add> if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil { <add> t.Fatal("Build 1 was supposed to fail, but didn't") <add> } <add> <add> ctx.Add("Dockerfile", "FROM busybox\nRUN ") <add> if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { <add> t.Fatal("Build 2 was supposed to fail, but didn't") <add> } <add> <add> // Skip over the times <add> e1 := err1.Error()[strings.Index(err1.Error(), `level="`):] <add> e2 := err2.Error()[strings.Index(err1.Error(), `level="`):] <add> <add> // Ignore whitespace since that's what were verifying doesn't change stuff <add> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { <add> t.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2) <add> } <add> <add> ctx.Add("Dockerfile", "FROM busybox\n RUN") <add> if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { <add> t.Fatal("Build 3 was supposed to fail, but didn't") <add> } <add> <add> // Skip over the times <add> e1 = err1.Error()[strings.Index(err1.Error(), `level="`):] <add> e2 = err2.Error()[strings.Index(err1.Error(), `level="`):] <add> <add> // Ignore whitespace since that's what were verifying doesn't change stuff <add> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { <add> t.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2) <add> } <add> <add> ctx.Add("Dockerfile", "FROM busybox\n RUN ") <add> if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { <add> t.Fatal("Build 4 was supposed to fail, but didn't") <add> } <add> <add> // Skip over the times <add> e1 = err1.Error()[strings.Index(err1.Error(), `level="`):] <add> e2 = err2.Error()[strings.Index(err1.Error(), `level="`):] <add> <add> // Ignore whitespace since that's what were verifying doesn't change stuff <add> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { <add> t.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2) <add> } <add> <add> logDone("build - test spaces") <add>} <add> <add>func TestBuildSpacesWithQuotes(t *testing.T) { <add> // Test to make sure that spaces in quotes aren't lost <add> name := "testspacesquotes" <add> defer deleteImages(name) <add> <add> dockerfile := `FROM busybox <add>RUN echo " \ <add> foo "` <add> <add> _, out, err := buildImageWithOut(name, dockerfile, false) <add> if err != nil { <add> t.Fatal("Build failed:", err) <add> } <add> <add> expecting := "\n foo \n" <add> if !strings.Contains(out, expecting) { <add> t.Fatalf("Bad output: %q expecting to contian %q", out, expecting) <add> } <add> <add> logDone("build - test spaces with quotes") <add>}
2
PHP
PHP
apply fixes from styleci
50176732d66b197de62d5567b79fc77f63e2cfbd
<ide><path>database/factories/UserFactory.php <ide> <?php <ide> <ide> /** @var \Illuminate\Database\Eloquent\Factory $factory */ <del> <ide> use App\User; <ide> use Illuminate\Support\Str; <ide> use Faker\Generator as Faker;
1
PHP
PHP
raise an exception in insertbefore()
33bbf8424ec6769ba75c2547395c71405c10cdcc
<ide><path>src/Http/MiddlewareStack.php <ide> namespace Cake\Http; <ide> <ide> use Countable; <add>use LogicException; <ide> <ide> /** <ide> * Provides methods for creating and manipulating a 'stack' of <ide> public function insertBefore($class, $callable) <ide> if ($found) { <ide> return $this->insertAt($i, $callable); <ide> } <del> return $this->push($callable); <add> throw new LogicException(sprintf("No middleware matching '%s' could be found.", $class)); <ide> } <ide> <ide> /** <ide><path>tests/TestCase/Http/MiddlewareStackTest.php <ide> public function testInsertBefore() <ide> /** <ide> * Test insertBefore an invalid classname <ide> * <add> * @expectedException LogicException <add> * @expectedExceptionMessage No middleware matching 'InvalidClassName' could be found. <ide> * @return void <ide> */ <ide> public function testInsertBeforeInvalid() <ide> public function testInsertBeforeInvalid() <ide> }; <ide> $stack = new MiddlewareStack(); <ide> $stack->push($one)->push($two)->insertBefore('InvalidClassName', $three); <del> <del> $this->assertCount(3, $stack); <del> $this->assertSame($one, $stack->get(0)); <del> $this->assertSame($two, $stack->get(1)); <del> $this->assertSame($three, $stack->get(2)); <ide> } <ide> <ide> /**
2
Ruby
Ruby
reduce calls to `named_host?`
21c626133adc4b5060df1081d9423024b6b7479d
<ide><path>actionpack/lib/action_dispatch/http/url.rb <ide> module URL <ide> <ide> class << self <ide> def extract_domain(host, tld_length) <del> host.split('.').last(1 + tld_length).join('.') if named_host?(host) <add> extract_domain_from(host, tld_length) if named_host?(host) <ide> end <ide> <ide> def extract_subdomains(host, tld_length) <ide> def url_for(options) <ide> <ide> private <ide> <add> def extract_domain_from(host, tld_length) <add> host.split('.').last(1 + tld_length).join('.') <add> end <add> <ide> def add_trailing_slash(path) <ide> # includes querysting <ide> if path.include?('?') <ide> def normalize_host(_host, options) <ide> host << subdomain.to_param <ide> end <ide> host << "." unless host.empty? <del> host << (options[:domain] || extract_domain(_host, tld_length)) <add> host << (options[:domain] || extract_domain_from(_host, tld_length)) <ide> host <ide> end <ide>
1
PHP
PHP
use unset() as per code review
8415060987feed159fdd3b9b92f563af3896beba
<ide><path>src/Auth/BaseAuthenticate.php <ide> protected function _findUser(string $username, ?string $password = null) <ide> } <ide> <ide> $this->_needsPasswordRehash = $hasher->needsRehash($hashedPassword); <del> $result->unsetField($passwordField); <add> $result->unset($passwordField); <ide> } <ide> $hidden = $result->getHidden(); <ide> if ($password === null && in_array($passwordField, $hidden)) { <ide><path>src/Datasource/EntityInterface.php <ide> public function has($field); <ide> * @param string|array $field The field to unset. <ide> * @return \Cake\Datasource\EntityInterface <ide> */ <del> public function unsetField($field); <add> public function unset($field); <ide> <ide> /** <ide> * Get the list of visible fields. <ide><path>src/Datasource/EntityTrait.php <ide> public function __isset($field) <ide> */ <ide> public function __unset($field) <ide> { <del> $this->unsetField($field); <add> $this->unset($field); <ide> } <ide> <ide> /** <ide> public function getOriginal($field) <ide> * <ide> * @return array <ide> */ <del> public function getOriginalValues() <add> public function getOriginalValues(): array <ide> { <ide> $originals = $this->_original; <ide> $originalKeys = array_keys($originals); <ide> public function getOriginalValues() <ide> * @param string|array $field The field or fields to check. <ide> * @return bool <ide> */ <del> public function has($field) <add> public function has($field): bool <ide> { <ide> foreach ((array)$field as $prop) { <ide> if ($this->get($prop) === null) { <ide> public function has($field) <ide> * @param string $field The field to check. <ide> * @return bool <ide> */ <del> public function isEmpty($field) <add> public function isEmpty($field): bool <ide> { <ide> $value = $this->get($field); <ide> if ($value === null <ide> public function isEmpty($field) <ide> * @param string $field The field to check. <ide> * @return bool <ide> */ <del> public function hasValue($field) <add> public function hasValue($field): bool <ide> { <ide> return !$this->isEmpty($field); <ide> } <ide> public function hasValue($field) <ide> * ### Examples: <ide> * <ide> * ``` <del> * $entity->unsetField('name'); <del> * $entity->unsetField(['name', 'last_name']); <add> * $entity->unset('name'); <add> * $entity->unset(['name', 'last_name']); <ide> * ``` <ide> * <ide> * @param string|array $field The field to unset. <ide> * @return $this <ide> */ <del> public function unsetField($field) <add> public function unset($field) <ide> { <ide> $field = (array)$field; <ide> foreach ($field as $p) { <ide> public function unsetField($field) <ide> /** <ide> * Removes a field or list of fields from this entity <ide> * <del> * @deprecated 4.0.0 Use unsetField() instead. <add> * @deprecated 4.0.0 Use unset() instead. Will be removed in 5.0. <ide> * @param string|array $field The field to unset. <ide> * @return $this <ide> */ <ide> public function unsetProperty($field) <ide> { <del> return $this->unsetField($field); <add> return $this->unset($field); <ide> } <ide> <ide> /** <ide> public function getVisible(): array <ide> /** <ide> * Gets the list of visible fields. <ide> * <del> * @deprecated 4.0.0 Use getVisible() instead. <add> * @deprecated 4.0.0 Use getVisible() instead. Will be removed in 5.0. <ide> * @return array <ide> */ <ide> public function visibleProperties(): array <ide> public function visibleProperties(): array <ide> * <ide> * @return array <ide> */ <del> public function toArray() <add> public function toArray(): array <ide> { <ide> $result = []; <ide> foreach ($this->getVisible() as $field) { <ide> public function toArray() <ide> * <ide> * @return array <ide> */ <del> public function jsonSerialize() <add> public function jsonSerialize(): array <ide> { <ide> return $this->extract($this->getVisible()); <ide> } <ide> <ide> /** <ide> * Implements isset($entity); <ide> * <del> * @param mixed $offset The offset to check. <add> * @param string $offset The offset to check. <ide> * @return bool Success <ide> */ <del> public function offsetExists($offset) <add> public function offsetExists($offset): bool <ide> { <ide> return $this->has($offset); <ide> } <ide> <ide> /** <ide> * Implements $entity[$offset]; <ide> * <del> * @param mixed $offset The offset to get. <add> * @param string $offset The offset to get. <ide> * @return mixed <ide> */ <ide> public function &offsetGet($offset) <ide> public function &offsetGet($offset) <ide> /** <ide> * Implements $entity[$offset] = $value; <ide> * <del> * @param mixed $offset The offset to set. <add> * @param string $offset The offset to set. <ide> * @param mixed $value The value to set. <ide> * @return void <ide> */ <ide> public function offsetSet($offset, $value) <ide> /** <ide> * Implements unset($result[$offset]); <ide> * <del> * @param mixed $offset The offset to remove. <add> * @param string $offset The offset to remove. <ide> * @return void <ide> */ <ide> public function offsetUnset($offset) <ide> { <del> $this->unsetField($offset); <add> $this->unset($offset); <ide> } <ide> <ide> /** <ide><path>src/ORM/Association/BelongsToMany.php <ide> protected function _saveLinks(EntityInterface $sourceEntity, array $targetEntiti <ide> // or if we are updating an existing link. <ide> if ($changedKeys) { <ide> $joint->isNew(true); <del> $joint->unsetField($junction->getPrimaryKey()) <add> $joint->unset($junction->getPrimaryKey()) <ide> ->set(array_merge($sourceKeys, $targetKeys), ['guard' => false]); <ide> } <ide> $saved = $junction->save($joint, $options); <ide><path>src/ORM/Association/HasOne.php <ide> public function saveAssociated(EntityInterface $entity, array $options = []) <ide> $targetEntity->set($properties, ['guard' => false]); <ide> <ide> if (!$this->getTarget()->save($targetEntity, $options)) { <del> $targetEntity->unsetField(array_keys($properties)); <add> $targetEntity->unset(array_keys($properties)); <ide> <ide> return false; <ide> } <ide><path>src/ORM/Behavior/Translate/TranslateStrategyTrait.php <ide> protected function unsetEmptyFields($entity) <ide> $fields = $translation->extract($this->_config['fields'], false); <ide> foreach ($fields as $field => $value) { <ide> if (strlen($value) === 0) { <del> $translation->unsetField($field); <add> $translation->unset($field); <ide> } <ide> } <ide> <ide> protected function unsetEmptyFields($entity) <ide> // If now, the whole _translations property is empty, <ide> // unset it completely and return <ide> if (empty($entity->get('_translations'))) { <del> $entity->unsetField('_translations'); <add> $entity->unset('_translations'); <ide> } <ide> } <ide> <ide> public function buildMarshalMap(Marshaller $marshaller, array $map, array $optio <ide> */ <ide> public function afterSave(EventInterface $event, EntityInterface $entity) <ide> { <del> $entity->unsetField('_i18n'); <add> $entity->unset('_i18n'); <ide> } <ide> } <ide><path>src/ORM/Marshaller.php <ide> protected function _mergeJoinData(array $original, BelongsToMany $assoc, array $ <ide> <ide> // Scalar data can't be handled <ide> if (!is_array($value)) { <del> $record->unsetField('_joinData'); <add> $record->unset('_joinData'); <ide> continue; <ide> } <ide> <ide><path>src/ORM/Table.php <ide> protected function _processSave(EntityInterface $entity, ArrayObject $options) <ide> } <ide> <ide> if (!$success && $isNew) { <del> $entity->unsetField($this->getPrimaryKey()); <add> $entity->unset($this->getPrimaryKey()); <ide> $entity->isNew(true); <ide> } <ide> <ide> public function saveMany(iterable $entities, $options = []) <ide> /** @var \Cake\Datasource\EntityInterface[] $entities */ <ide> foreach ($entities as $key => $entity) { <ide> if (isset($isNew[$key]) && $isNew[$key]) { <del> $entity->unsetField($this->getPrimaryKey()); <add> $entity->unset($this->getPrimaryKey()); <ide> $entity->isNew(true); <ide> } <ide> } <ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php <ide> class TreeBehaviorTest extends TestCase <ide> 'core.NumberTrees', <ide> ]; <ide> <add> /** <add> * @var \Cake\ORM\Table|\Cake\ORM\Behavior\TreeBehavior <add> */ <add> protected $table; <add> <add> /** <add> * @return void <add> */ <ide> public function setUp() <ide> { <ide> parent::setUp(); <ide> public function setUp() <ide> $this->table->addBehavior('Tree'); <ide> } <ide> <add> /** <add> * @return void <add> */ <ide> public function tearDown() <ide> { <ide> parent::tearDown(); <ide> public function testChildCountNoTreeColumns() <ide> { <ide> $table = $this->table; <ide> $node = $table->get(6); <del> $node->unsetField('lft'); <del> $node->unsetField('rght'); <add> $node->unset('lft'); <add> $node->unset('rght'); <ide> $count = $this->table->childCount($node, false); <ide> $this->assertEquals(4, $count); <ide> } <ide> public function testMoveNoTreeColumns() <ide> $table = $this->getTableLocator()->get('MenuLinkTrees'); <ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); <ide> $node = $table->get(8); <del> $node->unsetField('lft'); <del> $node->unsetField('rght'); <add> $node->unset('lft'); <add> $node->unset('rght'); <ide> $node = $table->moveUp($node, true); <ide> $this->assertEquals(['lft' => 1, 'rght' => 2], $node->extract(['lft', 'rght'])); <ide> $expected = [ <ide> public function testMoveDownNoTreeColumns() <ide> $table = $this->getTableLocator()->get('MenuLinkTrees'); <ide> $table->addBehavior('Tree', ['scope' => ['menu' => 'main-menu']]); <ide> $node = $table->get(1); <del> $node->unsetField('lft'); <del> $node->unsetField('rght'); <add> $node->unset('lft'); <add> $node->unset('rght'); <ide> $node = $table->moveDown($node, true); <ide> $this->assertEquals(['lft' => 7, 'rght' => 16], $node->extract(['lft', 'rght'])); <ide> $expected = [ <ide> public function testReParentNoTreeColumns() <ide> { <ide> $table = $this->table; <ide> $entity = $table->get(6); <del> $entity->unsetField('lft'); <del> $entity->unsetField('rght'); <add> $entity->unset('lft'); <add> $entity->unset('rght'); <ide> $entity->parent_id = 2; <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertEquals(9, $entity->lft); <ide> public function testRootingNoTreeColumns() <ide> { <ide> $table = $this->table; <ide> $entity = $table->get(2); <del> $entity->unsetField('lft'); <del> $entity->unsetField('rght'); <add> $entity->unset('lft'); <add> $entity->unset('rght'); <ide> $entity->parent_id = null; <ide> $this->assertSame($entity, $table->save($entity)); <ide> $this->assertEquals(15, $entity->lft); <ide> public function testDeleteRootNoTreeColumns() <ide> { <ide> $table = $this->table; <ide> $entity = $table->get(1); <del> $entity->unsetField('lft'); <del> $entity->unsetField('rght'); <add> $entity->unset('lft'); <add> $entity->unset('rght'); <ide> $this->assertTrue($table->delete($entity)); <ide> <ide> $expected = [ <ide><path>tests/TestCase/ORM/EntityTest.php <ide> public function testGetCacheClearedByUnset() <ide> $entity->set('name', 'Jones'); <ide> $this->assertEquals('Dr. Jones', $entity->get('name')); <ide> <del> $entity->unsetField('name'); <add> $entity->unset('name'); <ide> $this->assertEquals('Dr. ', $entity->get('name')); <ide> } <ide> <ide> public function testHas() <ide> public function testUnset() <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'bar']); <del> $entity->unsetField('id'); <add> $entity->unset('id'); <ide> $this->assertFalse($entity->has('id')); <ide> $this->assertTrue($entity->has('name')); <del> $entity->unsetField('name'); <add> $entity->unset('name'); <ide> $this->assertFalse($entity->has('id')); <ide> } <ide> <ide> public function testUnsetMakesClean() <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'bar']); <ide> $this->assertTrue($entity->isDirty('name')); <del> $entity->unsetField('name'); <add> $entity->unset('name'); <ide> $this->assertFalse($entity->isDirty('name'), 'Removed properties are not dirty.'); <ide> } <ide> <ide> public function testUnsetMakesClean() <ide> public function testUnsetMultiple() <ide> { <ide> $entity = new Entity(['id' => 1, 'name' => 'bar', 'thing' => 2]); <del> $entity->unsetField(['id', 'thing']); <add> $entity->unset(['id', 'thing']); <ide> $this->assertFalse($entity->has('id')); <ide> $this->assertTrue($entity->has('name')); <ide> $this->assertFalse($entity->has('thing')); <ide> public function testMagicIsset() <ide> public function testMagicUnset() <ide> { <ide> $entity = $this->getMockBuilder('Cake\ORM\Entity') <del> ->setMethods(['unsetField']) <add> ->setMethods(['unset']) <ide> ->getMock(); <ide> $entity->expects($this->at(0)) <del> ->method('unsetField') <add> ->method('unset') <ide> ->with('foo'); <ide> unset($entity->foo); <ide> } <ide> <add> /** <add> * Tests the deprecated unsetProperty() method <add> * <add> * @return void <add> */ <add> public function testUnsetDeprecated() <add> { <add> $entity = new Entity(); <add> $entity->foo = 'foo'; <add> <add> $entity->unsetProperty('foo'); <add> $this->assertNull($entity->foo); <add> } <add> <ide> /** <ide> * Tests isset with array access <ide> * <ide> public function testSetArrayAccess() <ide> public function testUnsetArrayAccess() <ide> { <ide> $entity = $this->getMockBuilder('Cake\ORM\Entity') <del> ->setMethods(['unsetField']) <add> ->setMethods(['unset']) <ide> ->getMock(); <ide> $entity->expects($this->at(0)) <del> ->method('unsetField') <add> ->method('unset') <ide> ->with('foo'); <ide> unset($entity['foo']); <ide> } <ide> public function testToArrayVirtualProperties() <ide> $this->assertEquals(['name'], $entity->getHidden()); <ide> } <ide> <add> /** <add> * Tests the getVisible() method <add> * <add> * @return void <add> */ <add> public function testGetVisible() <add> { <add> $entity = new Entity(); <add> $entity->foo = 'foo'; <add> $entity->bar = 'bar'; <add> <add> $expected = $entity->getVisible(); <add> $this->assertSame(['foo', 'bar'], $expected); <add> } <add> <add> /** <add> * Tests the deprecated visibleProperties() method <add> * <add> * @return void <add> */ <add> public function testVisiblePropertiesDeprecated() <add> { <add> $entity = new Entity(); <add> $entity->foo = 'foo'; <add> $entity->bar = 'bar'; <add> <add> $expected = $entity->visibleProperties(); <add> $this->assertSame(['foo', 'bar'], $expected); <add> } <add> <ide> /** <ide> * Tests setting virtual properties with merging. <ide> * <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveEntityOnlySchemaFields() <ide> $this->assertEquals($entity->id, self::$nextUserId); <ide> <ide> $row = $table->find('all')->where(['id' => self::$nextUserId])->first(); <del> $entity->unsetField('crazyness'); <add> $entity->unset('crazyness'); <ide> $this->assertEquals($entity->toArray(), $row->toArray()); <ide> } <ide> <ide> public function testSaveWithClonedEntity() <ide> $article = $table->get(1); <ide> <ide> $cloned = clone $article; <del> $cloned->unsetField('id'); <add> $cloned->unset('id'); <ide> $cloned->isNew(true); <ide> $this->assertSame($cloned, $table->save($cloned)); <ide> $this->assertEquals(
11
PHP
PHP
get model associations only when needed
60a8f0900b8286c0c8b821788ab445aa8507574e
<ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function read(Model $Model, $queryData = array(), $recursive = null) { <ide> } <ide> <ide> if ($recursive !== null) { <del> $_recursive = $Model->recursive; <add> $modelRecursive = $Model->recursive; <ide> $Model->recursive = $recursive; <ide> } <ide> <ide> public function read(Model $Model, $queryData = array(), $recursive = null) { <ide> $queryData['fields'] = $this->fields($Model); <ide> } <ide> <del> $_associations = $Model->associations(); <add> if ($Model->recursive === -1) { <add> // Primary model data only, no joins. <add> $associations = array(); <ide> <del> if ($Model->recursive == -1) { <del> $_associations = array(); <del> } elseif ($Model->recursive === 0) { <del> unset($_associations[2], $_associations[3]); <add> } else { <add> $associations = $Model->associations(); <add> <add> if ($Model->recursive === 0) { <add> // Primary model data and its domain. <add> unset($associations[2], $associations[3]); <add> } <ide> } <ide> <ide> // Generate hasOne and belongsTo associations inside $queryData <ide> $linkedModels = array(); <del> foreach ($_associations as $type) { <add> foreach ($associations as $type) { <ide> if ($type !== 'hasOne' && $type !== 'belongsTo') { <ide> continue; <ide> } <ide> public function read(Model $Model, $queryData = array(), $recursive = null) { <ide> $joined[$Model->alias] = (array)Hash::extract($queryData['joins'], '{n}.alias'); <ide> } <ide> <del> foreach ($_associations as $type) { <add> foreach ($associations as $type) { <ide> foreach ($Model->{$type} as $assoc => $assocData) { <ide> $LinkModel = $Model->{$assoc}; <ide> <ide> public function read(Model $Model, $queryData = array(), $recursive = null) { <ide> } <ide> <ide> if ($recursive !== null) { <del> $Model->recursive = $_recursive; <add> $Model->recursive = $modelRecursive; <ide> } <ide> <ide> return $resultSet;
1
Python
Python
fix pid check
26c9768e44315e08c298776e0d7fb400b442bf96
<ide><path>airflow/jobs/local_task_job.py <ide> def heartbeat_callback(self, session=None): <ide> recorded_pid = ti.pid <ide> same_process = recorded_pid == current_pid <ide> <del> if ti.run_as_user or self.task_runner.run_as_user: <add> if recorded_pid is not None and (ti.run_as_user or self.task_runner.run_as_user): <add> # when running as another user, compare the task runner pid to the parent of <add> # the recorded pid because user delegation becomes an extra process level. <add> # However, if recorded_pid is None, pass that through as it signals the task <add> # runner process has already completed and been cleared out. `psutil.Process` <add> # uses the current process if the parameter is None, which is not what is intended <add> # for comparison. <ide> recorded_pid = psutil.Process(ti.pid).ppid() <ide> same_process = recorded_pid == current_pid <ide> <ide><path>tests/jobs/test_local_task_job.py <ide> def test_localtaskjob_heartbeat(self, dag_maker): <ide> with pytest.raises(AirflowException): <ide> job1.heartbeat_callback() <ide> <add> # Now, set the ti.pid to None and test that no error <add> # is raised. <add> ti.pid = None <add> session.merge(ti) <add> session.commit() <add> assert ti.pid != job1.task_runner.process.pid <add> assert not ti.run_as_user <add> assert not job1.task_runner.run_as_user <add> job1.heartbeat_callback() <add> <ide> @mock.patch('subprocess.check_call') <ide> @mock.patch('airflow.jobs.local_task_job.psutil') <ide> def test_localtaskjob_heartbeat_with_run_as_user(self, psutil_mock, _, dag_maker): <ide> def test_localtaskjob_heartbeat_with_run_as_user(self, psutil_mock, _, dag_maker <ide> with pytest.raises(AirflowException, match='PID of job runner does not match'): <ide> job1.heartbeat_callback() <ide> <add> # Here we set the ti.pid to None and test that no error is <add> # raised <add> ti.pid = None <add> session.merge(ti) <add> session.commit() <add> assert ti.run_as_user <add> assert job1.task_runner.run_as_user == ti.run_as_user <add> assert ti.pid != job1.task_runner.process.pid <add> job1.heartbeat_callback() <add> <ide> @conf_vars({('core', 'default_impersonation'): 'testuser'}) <ide> @mock.patch('subprocess.check_call') <ide> @mock.patch('airflow.jobs.local_task_job.psutil') <ide> def test_localtaskjob_heartbeat_with_default_impersonation(self, psutil_mock, _, <ide> with pytest.raises(AirflowException, match='PID of job runner does not match'): <ide> job1.heartbeat_callback() <ide> <add> # Now, set the ti.pid to None and test that no error <add> # is raised. <add> ti.pid = None <add> session.merge(ti) <add> session.commit() <add> assert job1.task_runner.run_as_user == 'testuser' <add> assert ti.run_as_user is None <add> assert ti.pid != job1.task_runner.process.pid <add> job1.heartbeat_callback() <add> <ide> def test_heartbeat_failed_fast(self): <ide> """ <ide> Test that task heartbeat will sleep when it fails fast
2
Javascript
Javascript
update code style
16d17ab3230c7358e771c1a50932ac3a4d5cb7be
<ide><path>editor/js/Sidebar.Geometry.LatheGeometry.js <ide> * @author rfm1201 <ide> */ <ide> <del>Sidebar.Geometry.LatheGeometry = function( editor, object ) { <add>Sidebar.Geometry.LatheGeometry = function ( editor, object ) { <ide> <ide> var strings = editor.strings; <ide> <ide> Sidebar.Geometry.LatheGeometry = function( editor, object ) { <ide> var pointsRow = new UI.Row(); <ide> pointsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/lathe_geometry/points' ) ).setWidth( '90px' ) ); <ide> <del> var points = new UI.Points2().setValue(parameters.points).onChange(update); <del> pointsRow.add(points); <add> var points = new UI.Points2().setValue( parameters.points ).onChange( update ); <add> pointsRow.add( points ); <ide> <ide> container.add( pointsRow ); <ide> <ide><path>editor/js/Sidebar.Geometry.TubeGeometry.js <ide> Sidebar.Geometry.TubeGeometry = function ( editor, object ) { <ide> var pointsRow = new UI.Row(); <ide> pointsRow.add( new UI.Text( strings.getKey( 'sidebar/geometry/tube_geometry/path' ) ).setWidth( '90px' ) ); <ide> <del> var points = new UI.Points3().setValue(parameters.path.points).onChange(update); <del> pointsRow.add(points); <add> var points = new UI.Points3().setValue( parameters.path.points ).onChange( update ); <add> pointsRow.add( points ); <ide> <ide> container.add( pointsRow ); <ide> <ide><path>editor/js/libs/ui.three.js <ide> UI.Texture = function ( mapping ) { <ide> reader.addEventListener( 'load', function ( event ) { <ide> <ide> var image = document.createElement( 'img' ); <del> image.addEventListener( 'load', function( event ) { <add> image.addEventListener( 'load', function ( event ) { <ide> <ide> var texture = new THREE.Texture( this, mapping ); <ide> texture.sourceFile = file.name; <ide> UI.Outliner = function ( editor ) { <ide> dom.addEventListener( 'keydown', function ( event ) { <ide> <ide> switch ( event.keyCode ) { <add> <ide> case 38: // up <ide> case 40: // down <ide> event.preventDefault(); <ide> event.stopPropagation(); <ide> break; <add> <ide> } <ide> <ide> }, false ); <ide> UI.Outliner = function ( editor ) { <ide> dom.addEventListener( 'keyup', function ( event ) { <ide> <ide> switch ( event.keyCode ) { <add> <ide> case 38: // up <ide> scope.selectIndex( scope.selectedIndex - 1 ); <ide> break; <ide> case 40: // down <ide> scope.selectIndex( scope.selectedIndex + 1 ); <ide> break; <add> <ide> } <ide> <ide> }, false ); <ide> var Points = function ( onAddClicked ) { <ide> <ide> } <ide> <del> }.bind(this); <add> }.bind( this ); <ide> <ide> this.dom = span.dom; <ide> this.pointsUI = []; <ide> Points.prototype.deletePointRow = function ( idx, dontUpdate ) { <ide> <ide> }; <ide> <del>UI.Points2 = function(){ <del> Points.call( this, UI.Points2.addRow.bind(this)); <add>UI.Points2 = function () { <add> <add> Points.call( this, UI.Points2.addRow.bind( this ) ); <ide> <ide> return this; <del>} <add> <add>}; <ide> <ide> UI.Points2.prototype = Object.create( Points.prototype ); <ide> UI.Points2.prototype.constructor = UI.Points2; <ide> UI.Points2.addRow = function () { <ide> <ide> this.update(); <ide> <del>} <add>}; <ide> <ide> UI.Points2.prototype.getValue = function () { <add> <ide> var points = []; <ide> var count = 0; <ide> <ide> UI.Points2.prototype.getValue = function () { <ide> } <ide> <ide> return points; <del>} <add> <add>}; <ide> <ide> UI.Points2.prototype.setValue = function ( points ) { <ide> <ide> UI.Points2.prototype.createPointRow = function ( x, y ) { <ide> <ide> } ); <ide> <del> this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY } ); <add> this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY } ); <ide> ++ this.lastPointIdx; <ide> pointRow.add( lbl, txtX, txtY, btn ); <ide> <ide> return pointRow; <ide> <ide> }; <ide> <del>UI.Points3 = function(){ <del> Points.call( this, UI.Points3.addRow.bind(this)); <add>UI.Points3 = function () { <add> <add> Points.call( this, UI.Points3.addRow.bind( this ) ); <ide> <ide> return this; <del>} <add> <add>}; <ide> <ide> UI.Points3.prototype = Object.create( Points.prototype ); <ide> UI.Points3.prototype.constructor = UI.Points3; <ide> UI.Points3.addRow = function () { <ide> <ide> this.update(); <ide> <del>} <add>}; <ide> <ide> UI.Points3.prototype.getValue = function () { <add> <ide> var points = []; <ide> var count = 0; <ide> <ide> UI.Points3.prototype.getValue = function () { <ide> } <ide> <ide> return points; <del>} <add> <add>}; <ide> <ide> UI.Points3.prototype.setValue = function ( points ) { <ide> <ide> UI.Points3.prototype.createPointRow = function ( x, y, z ) { <ide> <ide> } ); <ide> <del> this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY, z : txtZ } ); <add> this.pointsUI.push( { row: pointRow, lbl: lbl, x: txtX, y: txtY, z: txtZ } ); <ide> ++ this.lastPointIdx; <ide> pointRow.add( lbl, txtX, txtY, txtZ, btn ); <ide>
3
Javascript
Javascript
remove workarounds for ie8
9b2a4c6851b783bdf15507201c213ac5dc91cae1
<ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> $rootScope.$digest(); <ide> <ide> <del> expect(sortedHtml(element)).toBeOneOf( <del> '<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>', <del> '<div><b class="i-hello"></b><span class="i-cau" i-cau="">Cau!</span></div>' //ie8 <del> ); <add> expect(sortedHtml(element)).toBe('<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>'); <ide> <ide> $httpBackend.flush(); <del> expect(sortedHtml(element)).toBeOneOf( <del> '<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>', <del> '<div><span class="i-hello" i-hello="">Hello!</span><span class="i-cau" i-cau="">Cau!</span></div>' //ie8 <del> ); <add> expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>'); <ide> } <ide> )); <ide> <ide> describe('$compile', function() { <ide> <ide> $rootScope.$digest(); <ide> <del> expect(sortedHtml(element)).toBeOneOf( <del> '<div><span class="i-hello">Hello, Elvis!</span></div>', <del> '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8 <del> ); <add> expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>'); <ide> } <ide> )); <ide> <ide> describe('$compile', function() { <ide> element = template($rootScope); <ide> $rootScope.$digest(); <ide> <del> expect(sortedHtml(element)).toBeOneOf( <del> '<div><span class="i-hello">Hello, Elvis!</span></div>', <del> '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8 <del> ); <add> expect(sortedHtml(element)).toBe('<div><span class="i-hello">Hello, Elvis!</span></div>'); <ide> } <ide> )); <ide> <ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> <ide> expect(inputElm.val()).toBe('2013-01'); <ide> <del> try { <del> //set to text for browsers with datetime-local validation. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) { <del> //for IE8 <del> } <add> //set to text for browsers with datetime-local validation. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('stuff'); <ide> expect(inputElm.val()).toBe('stuff'); <ide> describe('input', function() { <ide> <ide> expect(inputElm.val()).toBe('2013-W02'); <ide> <del> try { <del> //set to text for browsers with datetime-local validation. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) { <del> //for IE8 <del> } <add> //set to text for browsers with datetime-local validation. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('stuff'); <ide> expect(inputElm.val()).toBe('stuff'); <ide> describe('input', function() { <ide> <ide> expect(inputElm.val()).toBe('2009-01-06T16:25:00.000'); <ide> <del> try { <del> //set to text for browsers with datetime-local validation. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) { <del> //for IE8 <del> } <add> //set to text for browsers with datetime-local validation. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('stuff'); <ide> expect(inputElm.val()).toBe('stuff'); <ide> describe('input', function() { <ide> <ide> expect(inputElm.val()).toBe('16:25:00.000'); <ide> <del> try { <del> //set to text for browsers with time validation. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) { <del> //for IE8 <del> } <add> //set to text for browsers with time validation. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('stuff'); <ide> expect(inputElm.val()).toBe('stuff'); <ide> describe('input', function() { <ide> <ide> expect(inputElm.val()).toBe('2014-09-14'); <ide> <del> try { <del> //set to text for browsers with date validation. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) { <del> //for IE8 <del> } <add> //set to text for browsers with date validation. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('1-2-3'); <ide> expect(inputElm.val()).toBe('1-2-3'); <ide> describe('input', function() { <ide> $rootScope.$apply('age = 123'); <ide> expect(inputElm.val()).toBe('123'); <ide> <del> try { <del> // to allow non-number values, we have to change type so that <del> // the browser which have number validation will not interfere with <del> // this test. IE8 won't allow it hence the catch. <del> inputElm[0].setAttribute('type', 'text'); <del> } catch (e) {} <add> // to allow non-number values, we have to change type so that <add> // the browser which have number validation will not interfere with <add> // this test. <add> inputElm[0].setAttribute('type', 'text'); <ide> <ide> helper.changeInputValueTo('123X'); <ide> expect(inputElm.val()).toBe('123X'); <ide><path>test/ng/directive/ngIncludeSpec.js <ide> describe('ngInclude', function() { <ide> <ide> expect(window._ngIncludeCausesScriptToRun).toBe(true); <ide> <del> // IE8 doesn't like deleting properties of window <del> window._ngIncludeCausesScriptToRun = undefined; <del> try { <del> delete window._ngIncludeCausesScriptToRun; <del> } catch (e) {} <add> delete window._ngIncludeCausesScriptToRun; <ide> })); <ide> <ide> <ide><path>test/ng/directive/styleSpec.js <ide> describe('style', function() { <ide> $compile(element)($rootScope); <ide> $rootScope.$digest(); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.header{font-size:1.5em; h3{font-size:1.5em}}'); <add> expect(element[0].innerHTML).toBe('.header{font-size:1.5em; h3{font-size:1.5em}}'); <ide> })); <ide> <ide> <ide> describe('style', function() { <ide> $compile(element)($rootScope); <ide> $rootScope.$digest(); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.some-container{ width: px; }'); <add> expect(element[0].innerHTML).toBe('.some-container{ width: px; }'); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.elementWidth = 200; <ide> }); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.some-container{ width: 200px; }'); <add> expect(element[0].innerHTML).toBe('.some-container{ width: 200px; }'); <ide> })); <ide> <ide> <ide> describe('style', function() { <ide> $compile(element)($rootScope); <ide> $rootScope.$digest(); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: em }}'); <add> expect(element[0].innerHTML).toBe('.header{ h3 { font-size: em }}'); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.fontSize = 1.5; <ide> }); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: 1.5em }}'); <add> expect(element[0].innerHTML).toBe('.header{ h3 { font-size: 1.5em }}'); <ide> })); <ide> <ide> <ide> describe('style', function() { <ide> $compile(element)($rootScope); <ide> $rootScope.$digest(); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: }}'); <add> expect(element[0].innerHTML).toBe('.header{ h3 { font-size: }}'); <ide> <ide> $rootScope.$apply(function() { <ide> $rootScope.fontSize = 1.5; <ide> $rootScope.unit = 'em'; <ide> }); <ide> <del> // read innerHTML and trim to pass on IE8 <del> expect(trim(element[0].innerHTML)).toBe('.header{ h3 { font-size: 1.5em }}'); <add> expect(element[0].innerHTML).toBe('.header{ h3 { font-size: 1.5em }}'); <ide> })); <ide> <ide>
4
Text
Text
update jsfiddle templates for react 16
e7a2ac959a9fbba1b4c1de3cfdef5a5eae701313
<ide><path>.github/ISSUE_TEMPLATE.md <ide> <ide> **What is the current behavior?** <ide> <del>**If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template: https://jsfiddle.net/ebsrpraL/).** <add>**If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template for React 16: https://jsfiddle.net/Luktwrdm/, template for React 15: https://jsfiddle.net/hmbg7e9w/).** <ide> <ide> **What is the expected behavior?** <ide>
1
Ruby
Ruby
expand paths in i18n initializer tests
3971d972c304272dbbd88d5d5df14b5739e801a2
<ide><path>railties/test/initializer/initialize_i18n_test.rb <ide> def setup <ide> #{RAILS_FRAMEWORK_ROOT}/actionpack/lib/action_view/locale/en.yml <ide> #{RAILS_FRAMEWORK_ROOT}/railties/tmp/app/config/locales/en.yml <ide> my/other/locale.yml <del> ), I18n.load_path <add> ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) } <ide> end <ide> <ide> test "i18n finds locale files in engines" do <ide> def setup <ide> #{app_path}/config/locales/en.yml <ide> my/other/locale.yml <ide> #{app_path}/vendor/plugins/engine/config/locales/en.yml <del> ), I18n.load_path <add> ).map { |path| File.expand_path(path) }, I18n.load_path.map { |path| File.expand_path(path) } <ide> end <ide> end <ide> end <ide>\ No newline at end of file
1
Text
Text
fix a typo'd line
f6e5bf526386dc7982cadeb4ad9fe0b44edac296
<ide><path>docs/JavaScriptEnvironment.md <ide> ES6 <ide> * [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of): `for (var num of [1, 2, 3]) {}` <ide> * [Modules](http://babeljs.io/docs/learn-es2015/#modules): `import React, { Component } from 'react';` <ide> * [Computed Properties](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var key = 'abc'; var obj = {[key]: 10};` <del>* Object Consise Method: `var obj = { method() { return 10; } };` <add>* [Object Concise Method](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var obj = { method() { return 10; } };` <ide> * [Object Short Notation](http://babeljs.io/docs/learn-es2015/#enhanced-object-literals): `var name = 'vjeux'; var obj = { name };` <ide> * [Rest Params](https://github.com/sebmarkbage/ecmascript-rest-spread): `function(type, ...args) { }` <ide> * [Template Literals](http://babeljs.io/docs/learn-es2015/#template-strings): ``var who = 'world'; var str = `Hello ${who}`;``
1
Text
Text
use correct placeholder for policy docs
ecf693697b097c2cd75df303e71d9cfa859b72c0
<ide><path>doc/api/cli.md <ide> Enable experimental ES module support and caching modules. <ide> <ide> ### `--experimental-policy` <ide> <!-- YAML <del>added: TODO <add>added: REPLACEME <ide> --> <ide> <ide> Use the specified file as a security policy. <ide><path>doc/api/policy.md <ide> # Policies <ide> <del><!--introduced_in=TODO--> <add><!--introduced_in=REPLACEME--> <ide> <!-- type=misc --> <ide> <ide> > Stability: 1 - Experimental
2
Ruby
Ruby
fix rubocop warnings
1174264d47b03bbcdb6900896b2a512c05686549
<ide><path>Library/Homebrew/cmd/uses.rb <ide> def uses <ide> raise FormulaUnspecifiedError if ARGV.named.empty? <ide> <ide> used_formulae = ARGV.formulae <del> formulae = (ARGV.include? "--installed") ? Formula.installed : Formula <add> formulae = ARGV.include?("--installed") ? Formula.installed : Formula <ide> recursive = ARGV.flag? "--recursive" <ide> includes = [] <ide> ignores = [] <ide> def uses <ide> Requirement.prune unless includes.include?("build?") <ide> end <ide> end <del> deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } || <del> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } <ide> else <ide> deps = f.deps.reject do |dep| <ide> ignores.any? { |ignore| dep.send(ignore) } && !includes.any? { |include| dep.send(include) } <ide> end <ide> reqs = f.requirements.reject do |req| <ide> ignores.any? { |ignore| req.send(ignore) } && !includes.any? { |include| req.send(include) } <ide> end <del> deps.any? { |dep| dep.to_formula.full_name == ff.full_name rescue dep.name == ff.name } || <del> reqs.any? { |req| req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) } <add> end <add> next true if deps.any? do |dep| <add> begin <add> dep.to_formula.full_name == ff.full_name <add> rescue <add> dep.name == ff.name <add> end <add> end <add> <add> reqs.any? do |req| <add> req.name == ff.name || [ff.name, ff.full_name].include?(req.default_formula) <ide> end <ide> rescue FormulaUnavailableError <ide> # Silently ignore this case as we don't care about things used in
1
Javascript
Javascript
remove redundant code
a532b006a10b9efd47b76498eb17746bf0998945
<ide><path>examples/jsm/loaders/3DMLoader.js <ide> Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), { <ide> <ide> var _object = this._createObject( obj, material ); <ide> <del> if ( ! this.materials.includes( material ) ) { <del> <del> this.materials.push( material ); <del> <del> } <del> <ide> if ( _object === undefined ) { <ide> <ide> continue;
1
PHP
PHP
check extension before passing to addtestfile()
2598d176702ca8ab934ca377cec369577d4a5213
<ide><path>lib/Cake/Test/Case/Console/AllConsoleLibsTest.php <ide> public static function suite() { <ide> if (!$file->isFile() || strpos($file, 'All') === 0) { <ide> continue; <ide> } <del> $suite->addTestFile($file->getRealPath()); <add> $fileName = $file->getRealPath(); <add> if (substr($fileName, -4) === '.php') { <add> $suite->addTestFile($file->getRealPath()); <add> } <ide> } <ide> return $suite; <ide> }
1
Java
Java
remove the few remaining usages of uritemplate
b44daa8b71a60b46da90c9fcd5b7ad13d2047167
<ide><path>spring-web/src/main/java/org/springframework/http/RequestEntity.java <ide> * </pre> <ide> * <ide> * <p>If you would like to provide a URI template with variables, consider using <del> * {@link org.springframework.web.util.UriTemplate}: <add> * {@link org.springframework.web.util.DefaultUriBuilderFactory DefaultUriBuilderFactory}: <ide> * <pre class="code"> <del> * URI uri = new UriTemplate(&quot;https://example.com/{foo}&quot;).expand(&quot;bar&quot;); <add> * // Create shared factory <add> * UriBuilderFactory factory = new DefaultUriBuilderFactory(); <add> * <add> * // Use factory to create URL from template <add> * URI uri = factory.uriString(&quot;https://example.com/{foo}&quot;).build(&quot;bar&quot;); <ide> * RequestEntity&lt;MyRequest&gt; request = RequestEntity.post(uri).accept(MediaType.APPLICATION_JSON).body(body); <ide> * </pre> <ide> * <ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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> import org.springframework.util.Assert; <ide> <ide> /** <del> * Represents a URI template. A URI template is a URI-like String that contains variables <del> * enclosed by braces ({@code {}}) which can be expanded to produce an actual URI. <add> * Representation of a URI template that can be expanded with URI variables via <add> * {@link #expand(Map)}, {@link #expand(Object[])}, or matched to a URL via <add> * {@link #match(String)}. This class is designed to be thread-safe and <add> * reusable, and allows any number of expand or match calls. <ide> * <del> * <p>See {@link #expand(Map)}, {@link #expand(Object[])}, and {@link #match(String)} <del> * for example usages. <del> * <del> * <p>This class is designed to be thread-safe and reusable, allowing for any number <del> * of expand or match calls. <add> * <p><strong>Note:</strong> this class uses {@link UriComponentsBuilder} <add> * internally to expand URI templates, and is merely a shortcut for already <add> * prepared URI templates. For more dynamic preparation and extra flexibility, <add> * e.g. around URI encoding, consider using {@code UriComponentsBuilder} or the <add> * higher level {@link DefaultUriBuilderFactory} which adds several encoding <add> * modes on top of {@code UriComponentsBuilder}. See the <add> * <a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-uri-building">reference docs</a> <add> * for further details. <ide> * <ide> * @author Arjen Poutsma <ide> * @author Juergen Hoeller <ide><path>spring-web/src/test/java/org/springframework/http/RequestEntityTests.java <ide> import org.junit.jupiter.api.Test; <ide> <ide> import org.springframework.core.ParameterizedTypeReference; <del>import org.springframework.web.util.UriTemplate; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <ide> <ide> public void normal() throws URISyntaxException { <ide> <ide> @Test <ide> public void uriVariablesExpansion() throws URISyntaxException { <del> URI uri = new UriTemplate("https://example.com/{foo}").expand("bar"); <add> URI uri = UriComponentsBuilder.fromUriString("https://example.com/{foo}").buildAndExpand("bar").toUri(); <ide> RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build(); <ide> <ide> String url = "https://www.{host}.com/{path}"; <ide> String host = "example"; <ide> String path = "foo/bar"; <ide> URI expected = new URI("https://www.example.com/foo/bar"); <ide> <del> uri = new UriTemplate(url).expand(host, path); <add> uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(host, path).toUri(); <ide> RequestEntity<?> entity = RequestEntity.get(uri).build(); <ide> assertThat(entity.getUrl()).isEqualTo(expected); <ide> <ide> Map<String, String> uriVariables = new HashMap<>(2); <ide> uriVariables.put("host", host); <ide> uriVariables.put("path", path); <ide> <del> uri = new UriTemplate(url).expand(uriVariables); <add> uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(uriVariables).toUri(); <ide> entity = RequestEntity.get(uri).build(); <ide> assertThat(entity.getUrl()).isEqualTo(expected); <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RequestContext.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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> import org.springframework.web.bind.EscapedErrors; <ide> import org.springframework.web.server.ServerWebExchange; <ide> import org.springframework.web.util.HtmlUtils; <del>import org.springframework.web.util.UriTemplate; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> /** <ide> * Context holder for request-specific state, like the {@link MessageSource} to <ide> public String getContextUrl(String relativeUrl) { <ide> */ <ide> public String getContextUrl(String relativeUrl, Map<String, ?> params) { <ide> String url = StringUtils.applyRelativePath(getContextPath() + "/", relativeUrl); <del> UriTemplate template = new UriTemplate(url); <del> url = template.expand(params).toASCIIString(); <add> url = UriComponentsBuilder.fromUriString(url).buildAndExpand(params).encode().toUri().toASCIIString(); <ide> return getExchange().transformUrl(url); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/view/DummyMacroRequestContext.java <ide> import org.springframework.context.support.GenericApplicationContext; <ide> import org.springframework.ui.ModelMap; <ide> import org.springframework.web.server.ServerWebExchange; <del>import org.springframework.web.util.UriTemplate; <add>import org.springframework.web.util.UriComponents; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> /** <ide> * Dummy request context used for FreeMarker macro tests. <ide> public String getContextUrl(String relativeUrl) { <ide> * @see org.springframework.web.reactive.result.view.RequestContext#getContextUrl(String, Map) <ide> */ <ide> public String getContextUrl(String relativeUrl, Map<String,String> params) { <del> UriTemplate template = new UriTemplate(relativeUrl); <del> return getContextPath() + template.expand(params).toASCIIString(); <add> UriComponents uric = UriComponentsBuilder.fromUriString(relativeUrl).buildAndExpand(params); <add> return getContextPath() + uric.toUri().toASCIIString(); <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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> import org.springframework.web.servlet.LocaleResolver; <ide> import org.springframework.web.servlet.ThemeResolver; <ide> import org.springframework.web.util.HtmlUtils; <del>import org.springframework.web.util.UriTemplate; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> import org.springframework.web.util.UrlPathHelper; <ide> import org.springframework.web.util.WebUtils; <ide> <ide> public String getContextUrl(String relativeUrl) { <ide> */ <ide> public String getContextUrl(String relativeUrl, Map<String, ?> params) { <ide> String url = getContextPath() + relativeUrl; <del> UriTemplate template = new UriTemplate(url); <del> url = template.expand(params).toASCIIString(); <add> url = UriComponentsBuilder.fromUriString(url).buildAndExpand(params).encode().toUri().toASCIIString(); <ide> if (this.response != null) { <ide> url = this.response.encodeURL(url); <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/view/DummyMacroRequestContext.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 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> import org.springframework.web.servlet.support.BindStatus; <ide> import org.springframework.web.servlet.support.RequestContext; <del>import org.springframework.web.util.UriTemplate; <add>import org.springframework.web.util.UriComponents; <add>import org.springframework.web.util.UriComponentsBuilder; <ide> <ide> /** <ide> * Dummy request context used for FreeMarker macro tests. <ide> public String getContextUrl(String relativeUrl) { <ide> * @see org.springframework.web.servlet.support.RequestContext#getContextUrl(String, Map) <ide> */ <ide> public String getContextUrl(String relativeUrl, Map<String,String> params) { <del> UriTemplate template = new UriTemplate(relativeUrl); <del> return getContextPath() + template.expand(params).toASCIIString(); <add> UriComponents uric = UriComponentsBuilder.fromUriString(relativeUrl).buildAndExpand(params); <add> return getContextPath() + uric.toUri().toASCIIString(); <ide> } <ide> <ide> /**
7
Javascript
Javascript
use redirecturl at onheadersreceived if available
ae32f31eb4c4d27b2e9230a6fa62f0a64d967b3a
<ide><path>extensions/chromium/feature-detect.js <ide> var Features = { <ide> featureDetectLastUA: '', <ide> // Whether ftp: in XMLHttpRequest is allowed <ide> extensionSupportsFTP: false, <add> // Whether redirectUrl at onHeadersReceived is supported. <add> webRequestRedirectUrl: false, <ide> }; <ide> <ide> chrome.storage.local.get(Features, function(features) { <ide> chrome.storage.local.get(Features, function(features) { <ide> // Browser not upgraded, so the features did probably not change. <ide> return; <ide> } <add> var inconclusiveTestCount = 0; <ide> <ide> if (!features.extensionSupportsFTP) { <ide> features.extensionSupportsFTP = featureTestFTP(); <ide> } <ide> <del> Features.featureDetectLastUA = navigator.userAgent; <del> chrome.storage.local.set(Features); <add> if (!features.webRequestRedirectUrl) { <add> ++inconclusiveTestCount; <add> // Relatively expensive (and asynchronous) test: <add> featureTestRedirectOnHeadersReceived(function(result) { <add> // result = 'yes', 'no' or 'maybe'. <add> if (result !== 'maybe') { <add> --inconclusiveTestCount; <add> } <add> features.webRequestRedirectUrl = result === 'yes'; <add> checkTestCompletion(); <add> }); <add> } <add> <add> checkTestCompletion(); <add> <add> function checkTestCompletion() { <add> // Only stamp the feature detection results when all tests have finished. <add> if (inconclusiveTestCount === 0) { <add> Features.featureDetectLastUA = navigator.userAgent; <add> } <add> chrome.storage.local.set(Features); <add> } <ide> }); <ide> <ide> // Tests whether the extension can perform a FTP request. <ide> function featureTestFTP() { <ide> return false; <ide> } <ide> } <add> <add>// Tests whether redirectUrl at the onHeadersReceived stage is functional. <add>// Feature is supported since Chromium 35.0.1911.0 (r259546). <add>function featureTestRedirectOnHeadersReceived(callback) { <add> // The following URL is really going to be accessed via the network. <add> // It is the only way to feature-detect this feature, because the <add> // onHeadersReceived event is only triggered for http(s) requests. <add> var url = 'http://example.com/?feature-detect-' + chrome.runtime.id; <add> function onHeadersReceived(details) { <add> // If supported, the request is redirected. <add> // If not supported, the return value is ignored. <add> return { <add> redirectUrl: chrome.runtime.getURL('/manifest.json') <add> }; <add> } <add> chrome.webRequest.onHeadersReceived.addListener(onHeadersReceived, { <add> types: ['xmlhttprequest'], <add> urls: [url] <add> }, ['blocking']); <add> <add> var x = new XMLHttpRequest(); <add> x.open('get', url); <add> x.onloadend = function() { <add> chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived); <add> if (!x.responseText) { <add> // Network error? Anyway, can't tell with certainty whether the feature <add> // is supported. <add> callback('maybe'); <add> } else if (/^\s*\{/.test(x.responseText)) { <add> // If the response starts with "{", assume that the redirection to the <add> // manifest file succeeded, so the feature is supported. <add> callback('yes'); <add> } else { <add> // Did not get the content of manifest.json, so the redirect seems not to <add> // be followed. The feature is not supported. <add> callback('no'); <add> } <add> }; <add> x.send(); <add>} <ide><path>extensions/chromium/pdfHandler.js <ide> chrome.webRequest.onHeadersReceived.addListener( <ide> var viewerUrl = getViewerURL(details.url); <ide> <ide> // Replace frame with viewer <del> // TODO: When http://crbug.com/280464 is fixed, use <del> // return { redirectUrl: viewerUrl }; <add> if (Features.webRequestRedirectUrl) { <add> return { redirectUrl: viewerUrl }; <add> } <add> // Aww.. redirectUrl is not yet supported, so we have to use a different <add> // method as fallback (Chromium <35). <ide> <ide> if (details.frameId === 0) { <ide> // Main frame. Just replace the tab and be done!
2
Text
Text
fix typo s/only_up/up_only/ [ci skip]
ca68f1cf49a3689c276d502105aaa68fa106502d
<ide><path>activerecord/CHANGELOG.md <del>* Add `#only_up` to database migrations for code that is only relevant when <add>* Add `#up_only` to database migrations for code that is only relevant when <ide> migrating up, e.g. populating a new column. <ide> <ide> *Rich Daley*
1
Text
Text
update build instructions for os x
153b796d68655e892ce331d9fc7f0477f83db07d
<ide><path>BUILDING.md <ide> If you consistently can reproduce a test failure, search for it in the <ide> file a new issue. <ide> <ide> <del>### Unix / Macintosh <add>### Unix / OS X <ide> <ide> Prerequisites: <ide> <ide> * `gcc` and `g++` 4.8 or newer, or <ide> * `clang` and `clang++` 3.4 or newer <ide> * Python 2.6 or 2.7 <ide> * GNU Make 3.81 or newer <add> <add>On OS X, you will also need: <add>* [Xcode](https://developer.apple.com/xcode/download/) <add> * You also need to install the `Command Line Tools` via Xcode. You can find <add> this under the menu `Xcode -> Preferences -> Downloads` <add> * This step will install `gcc` and the related toolchain containing `make` <add> <add>On FreeBSD and OpenBSD, you may also need: <ide> * libexecinfo (FreeBSD and OpenBSD only) <ide> <add> <ide> ```text <ide> $ ./configure <ide> $ make <ide> This option will build with "small" (English only) support, but <ide> the full `Intl` (ECMA-402) APIs. With `--download=all` it will <ide> download the ICU library as needed. <ide> <del>##### Unix / Macintosh: <add>##### Unix / OS X: <ide> <ide> ```text <ide> $ ./configure --with-intl=small-icu --download=all <ide> data at runtime. <ide> With the `--download=all`, this may download ICU if you don't have an <ide> ICU in `deps/icu`. <ide> <del>##### Unix / Macintosh: <add>##### Unix / OS X: <ide> <ide> ```text <ide> $ ./configure --with-intl=full-icu --download=all <ide> $ ./configure --with-intl=full-icu --download=all <ide> The `Intl` object will not be available. This is the default at <ide> present, so this option is not normally needed. <ide> <del>##### Unix / Macintosh: <add>##### Unix / OS X: <ide> <ide> ```text <ide> $ ./configure --with-intl=none <ide> $ ./configure --with-intl=none <ide> > vcbuild intl-none <ide> ``` <ide> <del>#### Use existing installed ICU (Unix / Macintosh only): <add>#### Use existing installed ICU (Unix / OS X only): <ide> <ide> ```text <ide> $ pkg-config --modversion icu-i18n && ./configure --with-intl=system-icu <ide> You can find other ICU releases at <ide> Download the file named something like `icu4c-**##.#**-src.tgz` (or <ide> `.zip`). <ide> <del>##### Unix / Macintosh <add>##### Unix / OS X <ide> <ide> ```text <ide> # from an already-unpacked ICU:
1
Ruby
Ruby
move macos.xcode43_without_clt? into xcode module
755c786040e4c83735c8468c6bea4644e3b31aa4
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def outdated? <ide> version < latest_version <ide> end <ide> <add> def without_clt? <add> version >= "4.3" and not MacOS::CLT.installed? <add> end <add> <ide> def prefix <ide> @prefix ||= begin <ide> path = Pathname.new(folder) <ide><path>Library/Homebrew/superenv.rb <ide> # 7) Simpler formula that *just work* <ide> # 8) Build-system agnostic configuration of the tool-chain <ide> <del>module MacOS <del> def xcode43_without_clt? <del> MacOS::Xcode.version >= "4.3" and not MacOS::CLT.installed? <del> end <del>end <del> <ide> def superbin <ide> @bin ||= (HOMEBREW_REPOSITORY/"Library/ENV").children.reject{|d| d.basename.to_s > MacOS::Xcode.version }.max <ide> end <ide> <ide> def superenv? <del> return false if MacOS.xcode43_without_clt? && MacOS.sdk_path.nil? <add> return false if MacOS::Xcode.without_clt? && MacOS.sdk_path.nil? <ide> return false unless superbin && superbin.directory? <ide> return false if ARGV.include? "--env=std" <ide> true <ide> def setup_build_environment <ide> ENV['HOMEBREW_CC'] = determine_cc <ide> ENV['HOMEBREW_CCCFG'] = determine_cccfg <ide> ENV['HOMEBREW_BREW_FILE'] = HOMEBREW_BREW_FILE <del> ENV['HOMEBREW_SDKROOT'] = "#{MacOS.sdk_path}" if MacOS.xcode43_without_clt? <add> ENV['HOMEBREW_SDKROOT'] = "#{MacOS.sdk_path}" if MacOS::Xcode.without_clt? <ide> ENV['HOMEBREW_DEVELOPER_DIR'] = determine_developer_dir # used by our xcrun shim <ide> ENV['CMAKE_PREFIX_PATH'] = determine_cmake_prefix_path <ide> ENV['CMAKE_FRAMEWORK_PATH'] = determine_cmake_frameworks_path <ide> def default_cc <ide> <ide> def determine_path <ide> paths = [superbin] <del> if MacOS.xcode43_without_clt? <add> if MacOS::Xcode.without_clt? <ide> paths << "#{MacOS::Xcode.prefix}/usr/bin" <ide> paths << "#{MacOS::Xcode.prefix}/Toolchains/XcodeDefault.xctoolchain/usr/bin" <ide> end <ide> def determine_pkg_config_libdir <ide> def determine_cmake_prefix_path <ide> paths = keg_only_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}" } <ide> paths << HOMEBREW_PREFIX.to_s # put ourselves ahead of everything else <del> paths << "#{MacOS.sdk_path}/usr" if MacOS.xcode43_without_clt? <add> paths << "#{MacOS.sdk_path}/usr" if MacOS::Xcode.without_clt? <ide> paths.to_path_s <ide> end <ide> <ide> def determine_cmake_frameworks_path <ide> # XXX: keg_only_deps perhaps? but Qt does not link its Frameworks because of Ruby's Find.find ignoring symlinks!! <ide> paths = deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/Frameworks" } <del> paths << "#{MacOS.sdk_path}/System/Library/Frameworks" if MacOS.xcode43_without_clt? <add> paths << "#{MacOS.sdk_path}/System/Library/Frameworks" if MacOS::Xcode.without_clt? <ide> paths.to_path_s <ide> end <ide> <ide> def determine_cmake_include_path <del> sdk = MacOS.sdk_path if MacOS.xcode43_without_clt? <add> sdk = MacOS.sdk_path if MacOS::Xcode.without_clt? <ide> paths = [] <ide> paths << "#{MacOS::X11.include}/freetype2" if x11? <ide> paths << "#{sdk}/usr/include/libxml2" unless deps.include? 'libxml2' <del> if MacOS.xcode43_without_clt? <del> paths << "#{sdk}/usr/include/apache2" <del> end <add> paths << "#{sdk}/usr/include/apache2" if MacOS::Xcode.without_clt? <ide> paths << "#{sdk}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Headers/" unless x11? <ide> paths << MacOS::X11.include if x11? <ide> paths.to_path_s <ide> end <ide> <ide> def determine_cmake_library_path <del> sdk = MacOS.sdk_path if MacOS.xcode43_without_clt? <add> sdk = MacOS.sdk_path if MacOS::Xcode.without_clt? <ide> paths = [] <ide> # things expect to find GL headers since X11 used to be a default, so we add them <ide> paths << "#{sdk}/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries" unless x11?
2
Mixed
Javascript
add support for mirror option
0c6f37fff744e8f00c57c51407136cc39d506409
<ide><path>docs/00-Getting-Started.md <ide> the following options. <ide> labels: { <ide> // Boolean - if true show labels <ide> show: true, <add> <add> // Boolean - if true the chart will mirror the axis labels. If the labels are on the left, mirroring the axis will render them to the right <add> mirror: false, <add> <add> // Number - controls the padding between the label and the axis <add> padding: 10, <ide> <ide> // String - template string for labels <ide> template: "<%=value%>", <ide><path>src/scales/scale.linear.js <ide> // label settings <ide> labels: { <ide> show: true, <add> mirror: false, <add> padding: 10, <ide> template: "<%=value.toLocaleString()%>", <ide> fontSize: 12, <ide> fontStyle: "normal", <ide> fontColor: "#666", <del> fontFamily: "Helvetica Neue", <add> fontFamily: "Helvetica Neue" <ide> } <ide> }; <ide> <ide> var labelStartX; <ide> <ide> if (this.options.position == "left") { <del> labelStartX = this.right - 10; <del> this.ctx.textAlign = "right"; <add> if (this.options.labels.mirror) { <add> labelStartX = this.right + this.options.labels.padding; <add> this.ctx.textAlign = "left"; <add> } else { <add> labelStartX = this.right - this.options.labels.padding; <add> this.ctx.textAlign = "right"; <add> } <ide> } else { <ide> // right side <del> labelStartX = this.left + 5; <del> this.ctx.textAlign = "left"; <add> if (this.options.labels.mirror) { <add> labelStartX = this.left - this.options.labels.padding; <add> this.ctx.textAlign = "right"; <add> } else { <add> labelStartX = this.left + this.options.labels.padding; <add> this.ctx.textAlign = "left"; <add> } <ide> } <ide> <ide> this.ctx.textBaseline = "middle";
2
Python
Python
set version to v2.2.0.dev14
6189959adbd0a0aa53ad3e3857d4f6db2dd0b2b3
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.0.dev13" <add>__version__ = "2.2.0.dev14" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) in Python" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion"
1
Text
Text
remove needless entry [ci skip]
d03c90e8aa011cbf4244bfc5e622492dcdb52ee2
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Hyonjee Joo* <ide> <del>* Deprecate passing of `start` value to `find_in_batches` and `find_each` <del> in favour of `begin_at` value. <del> <del> *Vipul A M* <del> <ide> * Add `foreign_key_exists?` method. <ide> <ide> *Tõnis Simo* <ide><path>guides/source/5_0_release_notes.md <ide> Please refer to the [Changelog][active-record] for detailed changes. <ide> * Deprecated `ActiveRecord::Base.errors_in_transactional_callbacks=`. <ide> ([commit](https://github.com/rails/rails/commit/07d3d402341e81ada0214f2cb2be1da69eadfe72)) <ide> <del>* Deprecated passing of `start` value to `find_in_batches` and `find_each` <del> in favour of `begin_at` value. <del> ([Pull Request](https://github.com/rails/rails/pull/18961)) <del> <ide> * Deprecated `Relation#uniq` use `Relation#distinct` instead. <ide> ([commit](https://github.com/rails/rails/commit/adfab2dcf4003ca564d78d4425566dd2d9cd8b4f)) <ide>
2
Java
Java
fix the extra retention problem in replaysubject
2edea6b8c8349dc06355d9c0182ba537978d6191
<ide><path>src/main/java/io/reactivex/subjects/ReplaySubject.java <ide> <ide> package io.reactivex.subjects; <ide> <del>import io.reactivex.annotations.Nullable; <ide> import java.lang.reflect.Array; <ide> import java.util.*; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.Scheduler; <del>import io.reactivex.annotations.CheckReturnValue; <add>import io.reactivex.annotations.*; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.internal.functions.ObjectHelper; <ide> import io.reactivex.internal.util.NotificationLite; <ide> * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()}, <ide> * {@link #getValues()} or {@link #getValues(Object[])}. <ide> * <p> <del> * Note that due to concurrency requirements, a size-bounded {@code ReplaySubject} may hold strong references to more <del> * source emissions than specified. <add> * Note that due to concurrency requirements, a size- and time-bounded {@code ReplaySubject} may hold strong references to more <add> * source emissions than specified while it isn't terminated yet. Use the {@link #cleanupBuffer()} to allow <add> * such inaccessible items to be cleaned up by GC once no consumer references it anymore. <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code ReplaySubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and <ide> public T getValue() { <ide> return buffer.getValue(); <ide> } <ide> <add> /** <add> * Makes sure the item cached by the head node in a bounded <add> * ReplaySubject is released (as it is never part of a replay). <add> * <p> <add> * By default, live bounded buffers will remember one item before <add> * the currently receivable one to ensure subscribers can always <add> * receive a continuous sequence of items. A terminated ReplaySubject <add> * automatically releases this inaccessible item. <add> * <p> <add> * The method must be called sequentially, similar to the standard <add> * {@code onXXX} methods. <add> * @since 2.1.11 - experimental <add> */ <add> @Experimental <add> public void cleanupBuffer() { <add> buffer.trimHead(); <add> } <add> <ide> /** An empty array to avoid allocation in getValues(). */ <ide> private static final Object[] EMPTY_ARRAY = new Object[0]; <ide> <ide> ReplayDisposable<T>[] terminate(Object terminalValue) { <ide> * @return true if successful <ide> */ <ide> boolean compareAndSet(Object expected, Object next); <add> <add> /** <add> * Make sure an old inaccessible head value is released <add> * in a bounded buffer. <add> */ <add> void trimHead(); <ide> } <ide> <ide> static final class ReplayDisposable<T> extends AtomicInteger implements Disposable { <ide> public void add(T value) { <ide> @Override <ide> public void addFinal(Object notificationLite) { <ide> buffer.add(notificationLite); <add> trimHead(); <ide> size++; <ide> done = true; <ide> } <ide> <add> @Override <add> public void trimHead() { <add> // no-op in this type of buffer <add> } <add> <ide> @Override <ide> @Nullable <ide> @SuppressWarnings("unchecked") <ide> public void addFinal(Object notificationLite) { <ide> size++; <ide> t.lazySet(n); // releases both the tail and size <ide> <add> trimHead(); <ide> done = true; <ide> } <ide> <add> /** <add> * Replace a non-empty head node with an empty one to <add> * allow the GC of the inaccessible old value. <add> */ <add> @Override <add> public void trimHead() { <add> Node<Object> h = head; <add> if (h.value != null) { <add> Node<Object> n = new Node<Object>(null); <add> n.lazySet(h.get()); <add> head = n; <add> } <add> } <add> <ide> @Override <ide> @Nullable <ide> @SuppressWarnings("unchecked") <ide> void trimFinal() { <ide> for (;;) { <ide> TimedNode<Object> next = h.get(); <ide> if (next.get() == null) { <del> head = h; <add> if (h.value != null) { <add> TimedNode<Object> lasth = new TimedNode<Object>(null, 0L); <add> lasth.lazySet(h.get()); <add> head = lasth; <add> } else { <add> head = h; <add> } <ide> break; <ide> } <ide> <ide> if (next.time > limit) { <del> head = h; <add> if (h.value != null) { <add> TimedNode<Object> lasth = new TimedNode<Object>(null, 0L); <add> lasth.lazySet(h.get()); <add> head = lasth; <add> } else { <add> head = h; <add> } <ide> break; <ide> } <ide> <ide> public void addFinal(Object notificationLite) { <ide> done = true; <ide> } <ide> <add> /** <add> * Replace a non-empty head node with an empty one to <add> * allow the GC of the inaccessible old value. <add> */ <add> @Override <add> public void trimHead() { <add> TimedNode<Object> h = head; <add> if (h.value != null) { <add> TimedNode<Object> n = new TimedNode<Object>(null, 0); <add> n.lazySet(h.get()); <add> head = n; <add> } <add> } <add> <ide> @Override <ide> @Nullable <ide> @SuppressWarnings("unchecked") <ide><path>src/test/java/io/reactivex/subjects/ReplaySubjectTest.java <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.observers.*; <ide> import io.reactivex.schedulers.*; <add>import io.reactivex.subjects.ReplaySubject.*; <ide> <ide> public class ReplaySubjectTest extends SubjectTest<Integer> { <ide> <ide> public void timedNoOutdatedData() { <ide> <ide> source.test().assertResult(); <ide> } <add> <add> @Test <add> public void noHeadRetentionCompleteSize() { <add> ReplaySubject<Integer> source = ReplaySubject.createWithSize(1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onComplete(); <add> <add> SizeBoundReplayBuffer<Integer> buf = (SizeBoundReplayBuffer<Integer>)source.buffer; <add> <add> assertNull(buf.head.value); <add> <add> Object o = buf.head; <add> <add> source.cleanupBuffer(); <add> <add> assertSame(o, buf.head); <add> } <add> <add> <add> @Test <add> public void noHeadRetentionSize() { <add> ReplaySubject<Integer> source = ReplaySubject.createWithSize(1); <add> <add> source.onNext(1); <add> source.onNext(2); <add> <add> SizeBoundReplayBuffer<Integer> buf = (SizeBoundReplayBuffer<Integer>)source.buffer; <add> <add> assertNotNull(buf.head.value); <add> <add> source.cleanupBuffer(); <add> <add> assertNull(buf.head.value); <add> <add> Object o = buf.head; <add> <add> source.cleanupBuffer(); <add> <add> assertSame(o, buf.head); <add> } <add> <add> @Test <add> public void noHeadRetentionCompleteTime() { <add> ReplaySubject<Integer> source = ReplaySubject.createWithTime(1, TimeUnit.MINUTES, Schedulers.computation()); <add> <add> source.onNext(1); <add> source.onNext(2); <add> source.onComplete(); <add> <add> SizeAndTimeBoundReplayBuffer<Integer> buf = (SizeAndTimeBoundReplayBuffer<Integer>)source.buffer; <add> <add> assertNull(buf.head.value); <add> <add> Object o = buf.head; <add> <add> source.cleanupBuffer(); <add> <add> assertSame(o, buf.head); <add> } <add> <add> @Test <add> public void noHeadRetentionTime() { <add> TestScheduler sch = new TestScheduler(); <add> <add> ReplaySubject<Integer> source = ReplaySubject.createWithTime(1, TimeUnit.MILLISECONDS, sch); <add> <add> source.onNext(1); <add> <add> sch.advanceTimeBy(2, TimeUnit.MILLISECONDS); <add> <add> source.onNext(2); <add> <add> SizeAndTimeBoundReplayBuffer<Integer> buf = (SizeAndTimeBoundReplayBuffer<Integer>)source.buffer; <add> <add> assertNotNull(buf.head.value); <add> <add> source.cleanupBuffer(); <add> <add> assertNull(buf.head.value); <add> <add> Object o = buf.head; <add> <add> source.cleanupBuffer(); <add> <add> assertSame(o, buf.head); <add> } <ide> }
2
Python
Python
add small additional tests for converters/usecols
1e6b72b42292e62c1c86e4f77e30324e43aaa218
<ide><path>numpy/lib/tests/test_io.py <ide> def test_max_rows_larger(self): <ide> # Same as above, but do not skip any lines: <ide> (0, ["-1,0\n", "1,2\n", "\n", "3,4\n"]), <ide> (0, ["-1,0", "1,2", "", "3,4"]), <del> (0, StringIO("-1,0\n1,2\n\n3,4")),]) <add> (0, StringIO("-1,0\n1,2\n\n3,4"))]) <ide> def test_max_rows_empty_lines(self, skip, data): <ide> with pytest.warns(UserWarning, <ide> match=f"Input line 3.*max_rows={3-skip}"): <ide><path>numpy/lib/tests/test_loadtxt.py <ide> def test_converters_negative_indices_with_usecols(): <ide> ) <ide> assert_equal(res, expected) <ide> <add> # Second test with variable number of rows: <add> res = np.loadtxt(StringIO('''0,1,2\n0,1,2,3,4'''), delimiter=",", <add> usecols=[0, -1], converters={-1: (lambda x: -1)}) <add> assert_array_equal(res, [[0, -1], [0, -1]]) <ide> <ide> def test_ragged_usecols(): <ide> # usecols, and negative ones, work even with varying number of columns. <ide> def test_converter_with_structured_dtype(): <ide> <ide> def test_converter_with_unicode_dtype(): <ide> """ <del> With the default 'bytes' encoding, tokens are encoded prior to being passed <del> to the converter. This means that the output of the converter may be bytes <del> instead of unicode as expected by `read_rows`. <add> With the default 'bytes' encoding, tokens are encoded prior to being <add> passed to the converter. This means that the output of the converter may <add> be bytes instead of unicode as expected by `read_rows`. <ide> <ide> This test checks that outputs from the above scenario are properly decoded <ide> prior to parsing by `read_rows`. <ide> """ <ide> txt = StringIO('abc,def\nrst,xyz') <ide> conv = bytes.upper <del> res = np.loadtxt(txt, dtype=np.dtype("U3"), converters=conv, delimiter=",") <add> res = np.loadtxt( <add> txt, dtype=np.dtype("U3"), converters=conv, delimiter=",") <ide> expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']]) <ide> assert_equal(res, expected) <ide> <ide> def test_string_no_length_given(given_dtype, expected_dtype): <ide> <ide> def test_float_conversion(): <ide> """ <del> Some tests that the conversion to float64 works as accurately as the Python <del> built-in `float` function. In a naive version of the float parser, these <del> strings resulted in values that were off by an ULP or two. <add> Some tests that the conversion to float64 works as accurately as the <add> Python built-in `float` function. In a naive version of the float parser, <add> these strings resulted in values that were off by an ULP or two. <ide> """ <ide> strings = [ <ide> '0.9999999999999999', <ide> def gen(): <ide> yield entry <ide> <ide> with pytest.raises( <del> TypeError, match=r"non-string returned while reading data" <del> ): <add> TypeError, match=r"non-string returned while reading data"): <ide> np.loadtxt(gen(), dtype="i, i", delimiter=",") <ide> <ide> <ide> @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts") <ide> def test_object_cleanup_on_read_error(): <ide> sentinel = object() <del> <ide> already_read = 0 <add> <ide> def conv(x): <ide> nonlocal already_read <ide> if already_read > 4999: <ide> def test_converters_dict_raises_non_col_key(bad_col_ind): <ide> <ide> <ide> def test_converters_dict_raises_val_not_callable(): <del> with pytest.raises( <del> TypeError, match="values of the converters dictionary must be callable" <del> ): <add> with pytest.raises(TypeError, <add> match="values of the converters dictionary must be callable"): <ide> np.loadtxt(StringIO("1 2\n3 4"), converters={0: 1}) <ide> <ide> <ide> def test_unicode_whitespace_stripping(dtype): <ide> <ide> @pytest.mark.parametrize("dtype", "FD") <ide> def test_unicode_whitespace_stripping_complex(dtype): <del> # Complex has a few extra cases since it has two components and parentheses <add> # Complex has a few extra cases since it has two components and <add> # parentheses <ide> line = " 1 , 2+3j , ( 4+5j ), ( 6+-7j ) , 8j , ( 9j ) \n" <ide> data = [line, line.replace(" ", "\u202F")] <ide> res = np.loadtxt(data, dtype=dtype, delimiter=',') <ide> def test_no_thousands_support(dtype): <ide> if dtype == "e": <ide> pytest.skip("half assignment currently uses Python float converter") <ide> if dtype in "eG": <del> pytest.xfail("clongdouble assignment is buggy (uses `complex` always).") <add> pytest.xfail("clongdouble assignment is buggy (uses `complex`?).") <ide> <ide> assert int("1_1") == float("1_1") == complex("1_1") == 11 <ide> with pytest.raises(ValueError): <ide> def test_bad_newline_in_iterator(data): <ide> # In NumPy <=1.22 this was accepted, because newlines were completely <ide> # ignored when the input was an iterable. This could be changed, but right <ide> # now, we raise an error. <del> with pytest.raises(ValueError, <del> match="Found an unquoted embedded newline within a single line"): <add> msg = "Found an unquoted embedded newline within a single line" <add> with pytest.raises(ValueError, match=msg): <ide> np.loadtxt(data, delimiter=",") <ide> <ide> <ide> def test_filelike_read_fails(self): <ide> # the current "DataClass" backing). <ide> class BadFileLike: <ide> counter = 0 <add> <ide> def read(self, size): <ide> self.counter += 1 <ide> if self.counter > 20: <ide> def test_filelike_bad_read(self): <ide> # Can only be reached if loadtxt opens the file, so it is hard to do <ide> # via the public interface (although maybe not impossible considering <ide> # the current "DataClass" backing). <add> <ide> class BadFileLike: <ide> counter = 0 <add> <ide> def read(self, size): <ide> return 1234 # not a string! <ide> <ide> with pytest.raises(TypeError, <del> match="non-string returned while reading data"): <add> match="non-string returned while reading data"): <ide> np.core._multiarray_umath._load_from_filelike( <ide> BadFileLike(), dtype=np.dtype("i"), filelike=True) <ide> <ide> def test_not_an_iter(self): <ide> with pytest.raises(TypeError, <del> match="error reading from object, expected an iterable"): <add> match="error reading from object, expected an iterable"): <ide> np.core._multiarray_umath._load_from_filelike( <ide> object(), dtype=np.dtype("i"), filelike=False) <ide>
2
Mixed
Python
fix reloading model for evaluation in examples
087798b7fa6dc82f34a7462fddd313d38b251bda
<ide><path>README.md <ide> python -m pytest -sv tests/ <ide> <ide> This package comprises the following classes that can be imported in Python and are detailed in the [Doc](#doc) section of this readme: <ide> <del>- Seven PyTorch models (`torch.nn.Module`) for Bert with pre-trained weights (in the [`modeling.py`](./pytorch_pretrained_bert/modeling.py) file): <add>- Eight PyTorch models (`torch.nn.Module`) for Bert with pre-trained weights (in the [`modeling.py`](./pytorch_pretrained_bert/modeling.py) file): <ide> - [`BertModel`](./pytorch_pretrained_bert/modeling.py#L537) - raw BERT Transformer model (**fully pre-trained**), <ide> - [`BertForMaskedLM`](./pytorch_pretrained_bert/modeling.py#L691) - BERT Transformer with the pre-trained masked language modeling head on top (**fully pre-trained**), <ide> - [`BertForNextSentencePrediction`](./pytorch_pretrained_bert/modeling.py#L752) - BERT Transformer with the pre-trained next sentence prediction classifier on top (**fully pre-trained**), <ide> - [`BertForPreTraining`](./pytorch_pretrained_bert/modeling.py#L620) - BERT Transformer with masked language modeling head and next sentence prediction classifier on top (**fully pre-trained**), <ide> - [`BertForSequenceClassification`](./pytorch_pretrained_bert/modeling.py#L814) - BERT Transformer with a sequence classification head on top (BERT Transformer is **pre-trained**, the sequence classification head **is only initialized and has to be trained**), <del> - [`BertForMultipleChoice`](./pytorch_pretrained_bert/modeling.py#L880) - BERT Transformer with a multiple choice head on top (used for task like Swag) (BERT Transformer is **pre-trained**, the sequence classification head **is only initialized and has to be trained**), <add> - [`BertForMultipleChoice`](./pytorch_pretrained_bert/modeling.py#L880) - BERT Transformer with a multiple choice head on top (used for task like Swag) (BERT Transformer is **pre-trained**, the multiple choice classification head **is only initialized and has to be trained**), <ide> - [`BertForTokenClassification`](./pytorch_pretrained_bert/modeling.py#L949) - BERT Transformer with a token classification head on top (BERT Transformer is **pre-trained**, the token classification head **is only initialized and has to be trained**), <ide> - [`BertForQuestionAnswering`](./pytorch_pretrained_bert/modeling.py#L1015) - BERT Transformer with a token classification head on top (BERT Transformer is **pre-trained**, the token classification head **is only initialized and has to be trained**). <ide> <ide> Here is a detailed documentation of the classes in the package and how to use th <ide> | Sub-section | Description | <ide> |-|-| <ide> | [Loading Google AI's pre-trained weigths](#Loading-Google-AIs-pre-trained-weigths-and-PyTorch-dump) | How to load Google AI's pre-trained weight or a PyTorch saved instance | <del>| [PyTorch models](#PyTorch-models) | API of the seven PyTorch model classes: `BertModel`, `BertForMaskedLM`, `BertForNextSentencePrediction`, `BertForPreTraining`, `BertForSequenceClassification` or `BertForQuestionAnswering` | <add>| [PyTorch models](#PyTorch-models) | API of the eight PyTorch model classes: `BertModel`, `BertForMaskedLM`, `BertForNextSentencePrediction`, `BertForPreTraining`, `BertForSequenceClassification`, `BertForMultipleChoice` or `BertForQuestionAnswering` | <ide> | [Tokenizer: `BertTokenizer`](#Tokenizer-BertTokenizer) | API of the `BertTokenizer` class| <ide> | [Optimizer: `BertAdam`](#Optimizer-BertAdam) | API of the `BertAdam` class | <ide> <ide> model = BERT_CLASS.from_pretrain(PRE_TRAINED_MODEL_NAME_OR_PATH, cache_dir=None) <ide> <ide> where <ide> <del>- `BERT_CLASS` is either the `BertTokenizer` class (to load the vocabulary) or one of the seven PyTorch model classes (to load the pre-trained weights): `BertModel`, `BertForMaskedLM`, `BertForNextSentencePrediction`, `BertForPreTraining`, `BertForSequenceClassification`, `BertForTokenClassification` or `BertForQuestionAnswering`, and <add>- `BERT_CLASS` is either the `BertTokenizer` class (to load the vocabulary) or one of the eight PyTorch model classes (to load the pre-trained weights): `BertModel`, `BertForMaskedLM`, `BertForNextSentencePrediction`, `BertForPreTraining`, `BertForSequenceClassification`, `BertForTokenClassification`, `BertForMultipleChoice` or `BertForQuestionAnswering`, and <ide> - `PRE_TRAINED_MODEL_NAME_OR_PATH` is either: <ide> <ide> - the shortcut name of a Google AI's pre-trained model selected in the list: <ide> The optimizer accepts the following arguments: <ide> <ide> BERT-base and BERT-large are respectively 110M and 340M parameters models and it can be difficult to fine-tune them on a single GPU with the recommended batch size for good performance (in most case a batch size of 32). <ide> <del>To help with fine-tuning these models, we have included five techniques that you can activate in the fine-tuning scripts [`run_classifier.py`](./examples/run_classifier.py) and [`run_squad.py`](./examples/run_squad.py): gradient-accumulation, multi-gpu training, distributed training, optimize on CPU and 16-bits training . For more details on how to use these techniques you can read [the tips on training large batches in PyTorch](https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255) that I published earlier this month. <add>To help with fine-tuning these models, we have included several techniques that you can activate in the fine-tuning scripts [`run_classifier.py`](./examples/run_classifier.py) and [`run_squad.py`](./examples/run_squad.py): gradient-accumulation, multi-gpu training, distributed training and 16-bits training . For more details on how to use these techniques you can read [the tips on training large batches in PyTorch](https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255) that I published earlier this month. <ide> <ide> Here is how to use these techniques in our scripts: <ide> <ide> - **Gradient Accumulation**: Gradient accumulation can be used by supplying a integer greater than 1 to the `--gradient_accumulation_steps` argument. The batch at each step will be divided by this integer and gradient will be accumulated over `gradient_accumulation_steps` steps. <ide> - **Multi-GPU**: Multi-GPU is automatically activated when several GPUs are detected and the batches are splitted over the GPUs. <ide> - **Distributed training**: Distributed training can be activated by supplying an integer greater or equal to 0 to the `--local_rank` argument (see below). <del>- **Optimize on CPU**: The Adam optimizer stores 2 moving average of the weights of the model. If you keep them on GPU 1 (typical behavior), your first GPU will have to store 3-times the size of the model. This is not optimal for large models like `BERT-large` and means your batch size is a lot lower than it could be. This option will perform the optimization and store the averages on the CPU/RAM to free more room on the GPU(s). As the most computational intensive operation is usually the backward pass, this doesn't have a significant impact on the training time. Activate this option with `--optimize_on_cpu` on the [`run_squad.py`](./examples/run_squad.py) script. <ide> - **16-bits training**: 16-bits training, also called mixed-precision training, can reduce the memory requirement of your model on the GPU by using half-precision training, basically allowing to double the batch size. If you have a recent GPU (starting from NVIDIA Volta architecture) you should see no decrease in speed. A good introduction to Mixed precision training can be found [here](https://devblogs.nvidia.com/mixed-precision-training-deep-neural-networks/) and a full documentation is [here](https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html). In our scripts, this option can be activated by setting the `--fp16` flag and you can play with loss scaling using the `--loss_scaling` flag (see the previously linked documentation for details on loss scaling). If the loss scaling is too high (`Nan` in the gradients) it will be automatically scaled down until the value is acceptable. The default loss scaling is 128 which behaved nicely in our tests. <ide> <ide> Note: To use *Distributed Training*, you will need to run one training script on each of your machines. This can be done for example by running the following command on each server (see [the above mentioned blog post]((https://medium.com/huggingface/training-larger-batches-practical-tips-on-1-gpu-multi-gpu-distributed-setups-ec88c3e51255)) for more details): <ide> Where `$THIS_MACHINE_INDEX` is an sequential index assigned to each of your mach <ide> <ide> ### Fine-tuning with BERT: running the examples <ide> <del>We showcase the same examples as [the original implementation](https://github.com/google-research/bert/): fine-tuning a sequence-level classifier on the MRPC classification corpus and a token-level classifier on the question answering dataset SQuAD. <add>We showcase several fine-tuning examples based on (and extended from) [the original implementation](https://github.com/google-research/bert/): <ide> <del>Before running these examples you should download the <add>- a sequence-level classifier on the MRPC classification corpus, <add>- a token-level classifier on the question answering dataset SQuAD, and <add>- a sequence-level multiple-choice classifier on the SWAG classification corpus. <add> <add>#### MRPC <add> <add>This example code fine-tunes BERT on the Microsoft Research Paraphrase <add>Corpus (MRPC) corpus and runs in less than 10 minutes on a single K-80 and in 27 seconds (!) on single tesla V100 16GB with apex installed. <add> <add>Before running this example you should download the <ide> [GLUE data](https://gluebenchmark.com/tasks) by running <ide> [this script](https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e) <del>and unpack it to some directory `$GLUE_DIR`. Please also download the `BERT-Base` <del>checkpoint, unzip it to some directory `$BERT_BASE_DIR`, and convert it to its PyTorch version as explained in the previous section. <del> <del>This example code fine-tunes `BERT-Base` on the Microsoft Research Paraphrase <del>Corpus (MRPC) corpus and runs in less than 10 minutes on a single K-80. <add>and unpack it to some directory `$GLUE_DIR`. <ide> <ide> ```shell <ide> export GLUE_DIR=/path/to/glue <ide> python run_classifier.py \ <ide> <ide> Our test ran on a few seeds with [the original implementation hyper-parameters](https://github.com/google-research/bert#sentence-and-sentence-pair-classification-tasks) gave evaluation results between 84% and 88%. <ide> <del>The second example fine-tunes `BERT-Base` on the SQuAD question answering task. <add>**Fast run with apex and 16 bit precision: fine-tuning on MRPC in 27 seconds!** <add>First install apex as indicated [here](https://github.com/NVIDIA/apex). <add>Then run <add>```shell <add>export GLUE_DIR=/path/to/glue <add> <add>python run_classifier.py \ <add> --task_name MRPC \ <add> --do_train \ <add> --do_eval \ <add> --do_lower_case \ <add> --data_dir $GLUE_DIR/MRPC/ \ <add> --bert_model bert-base-uncased \ <add> --max_seq_length 128 \ <add> --train_batch_size 32 \ <add> --learning_rate 2e-5 \ <add> --num_train_epochs 3.0 \ <add> --output_dir /tmp/mrpc_output/ <add>``` <add> <add>#### SQuAD <add> <add>This example code fine-tunes BERT on the SQuAD dataset. It runs in 24 min (with BERT-base) or 68 min (with BERT-large) on single tesla V100 16GB. <ide> <ide> The data for SQuAD can be downloaded with the following links and should be saved in a `$SQUAD_DIR` directory. <ide> <ide> python run_swag.py \ <ide> --gradient_accumulation_steps 4 <ide> ``` <ide> <del>Training with the previous hyper-parameters gave us the following results: <add>Training with the previous hyper-parameters on a single GPU gave us the following results: <ide> ``` <ide> eval_accuracy = 0.8062081375587323 <ide> eval_loss = 0.5966546792367169 <ide><path>examples/run_classifier.py <ide> def main(): <ide> # Load a trained model that you have fine-tuned <ide> model_state_dict = torch.load(output_model_file) <ide> model = BertForSequenceClassification.from_pretrained(args.bert_model, state_dict=model_state_dict) <add> if args.fp16: <add> model.half() <add> model.to(device) <ide> <ide> if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0): <ide> eval_examples = processor.get_dev_examples(args.data_dir) <ide><path>examples/run_squad.py <ide> def main(): <ide> # Load a trained model that you have fine-tuned <ide> model_state_dict = torch.load(output_model_file) <ide> model = BertForQuestionAnswering.from_pretrained(args.bert_model, state_dict=model_state_dict) <add> if args.fp16: <add> model.half() <add> model.to(device) <ide> <ide> if args.do_predict and (args.local_rank == -1 or torch.distributed.get_rank() == 0): <ide> eval_examples = read_squad_examples( <ide><path>examples/run_swag.py <ide> def main(): <ide> # Prepare model <ide> model = BertForMultipleChoice.from_pretrained(args.bert_model, <ide> cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank), <del> num_choices = 4 <del> ) <add> num_choices=4) <ide> if args.fp16: <ide> model.half() <ide> model.to(device) <ide> def main(): <ide> loss = loss * args.loss_scale <ide> if args.gradient_accumulation_steps > 1: <ide> loss = loss / args.gradient_accumulation_steps <add> tr_loss += loss.item() <add> nb_tr_examples += input_ids.size(0) <add> nb_tr_steps += 1 <ide> <ide> if args.fp16: <ide> optimizer.backward(loss) <ide> def main(): <ide> optimizer.zero_grad() <ide> global_step += 1 <ide> <add> # Save a trained model <add> model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self <add> output_model_file = os.path.join(args.output_dir, "pytorch_model.bin") <add> torch.save(model_to_save.state_dict(), output_model_file) <add> <add> # Load a trained model that you have fine-tuned <add> model_state_dict = torch.load(output_model_file) <add> model = BertForMultipleChoice.from_pretrained(args.bert_model, <add> state_dict=model_state_dict, <add> num_choices=4) <add> if args.fp16: <add> model.half() <add> model.to(device) <add> <ide> if args.do_eval and (args.local_rank == -1 or torch.distributed.get_rank() == 0): <ide> eval_examples = read_swag_examples(os.path.join(args.data_dir, 'val.csv'), is_training = True) <ide> eval_features = convert_examples_to_features(
4
Ruby
Ruby
fix regression caused by a01d164b
1b4399dfe7eaa8dd2a75f35815ea429962c51a29
<ide><path>activerecord/lib/active_record/relation/merger.rb <ide> def merge_preloads <ide> return if other.preload_values.empty? && other.includes_values.empty? <ide> <ide> if other.klass == relation.klass <del> relation.preload! other.preload_values unless other.preload_values.empty? <del> relation.includes! other.includes_values unless other.includes_values.empty? <add> relation.preload!(*other.preload_values) unless other.preload_values.empty? <add> relation.includes!(other.includes_values) unless other.includes_values.empty? <ide> else <ide> reflection = relation.klass.reflect_on_all_associations.find do |r| <ide> r.class_name == other.klass.name <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_preloading_with_associations_and_merges <ide> end <ide> end <ide> <add> def test_preloading_with_associations_default_scopes_and_merges <add> post = Post.create! title: 'Uhuu', body: 'body' <add> reader = Reader.create! post_id: post.id, person_id: 1 <add> <add> post_rel = PostWithPreloadDefaultScope.preload(:readers).joins(:readers).where(title: 'Uhuu') <add> result_post = PostWithPreloadDefaultScope.all.merge(post_rel).to_a.first <add> <add> assert_no_queries do <add> assert_equal [reader], result_post.readers.to_a <add> end <add> <add> post_rel = PostWithIncludesDefaultScope.includes(:readers).where(title: 'Uhuu') <add> result_post = PostWithIncludesDefaultScope.all.merge(post_rel).to_a.first <add> <add> assert_no_queries do <add> assert_equal [reader], result_post.readers.to_a <add> end <add> end <add> <ide> def test_loading_with_one_association <ide> posts = Post.preload(:comments) <ide> post = posts.find { |p| p.id == 1 } <ide><path>activerecord/test/models/post.rb <ide> class PostWithDefaultScope < ActiveRecord::Base <ide> default_scope { order(:title) } <ide> end <ide> <add>class PostWithPreloadDefaultScope < ActiveRecord::Base <add> self.table_name = 'posts' <add> <add> has_many :readers, foreign_key: 'post_id' <add> <add> default_scope { preload(:readers) } <add>end <add> <add>class PostWithIncludesDefaultScope < ActiveRecord::Base <add> self.table_name = 'posts' <add> <add> has_many :readers, foreign_key: 'post_id' <add> <add> default_scope { includes(:readers) } <add>end <add> <ide> class SpecialPostWithDefaultScope < ActiveRecord::Base <ide> self.table_name = 'posts' <ide> default_scope { where(:id => [1, 5,6]) }
3
Ruby
Ruby
fix a warning
2198a9fc0d2e27f828d452129ce47ad90e16fab7
<ide><path>activejob/lib/active_job/arguments.rb <ide> class DeserializationError < StandardError <ide> attr_reader :original_exception <ide> <ide> def initialize(e) #:nodoc: <del> super ("Error while trying to deserialize arguments: #{e.message}") <add> super("Error while trying to deserialize arguments: #{e.message}") <ide> @original_exception = e <ide> set_backtrace e.backtrace <ide> end
1
PHP
PHP
add ability to remove columns from schema objects
2b0f9039b1699aea317a4998b2774b6af94cb9f7
<ide><path>src/Database/Schema/TableSchema.php <ide> public function addColumn($name, $attrs) <ide> return $this; <ide> } <ide> <add> /** <add> * Remove a column from the table schema. <add> * <add> * If the column is not defined in the table, no error will be raised. <add> * <add> * @param string $name The name of the column <add> * @return $this <add> */ <add> public function removeColumn($name) <add> { <add> unset($this->_columns[$name], $this->_typeMap[$name]); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Get the column names in the table. <ide> * <ide><path>tests/TestCase/Database/Schema/TableTest.php <ide> public function testAddColumn() <ide> $this->assertEquals(['title', 'body'], $table->columns()); <ide> } <ide> <add> /** <add> * Test removing columns. <add> * <add> * @return void <add> */ <add> public function testRemoveColumn() <add> { <add> $table = new Table('articles'); <add> $result = $table->addColumn('title', [ <add> 'type' => 'string', <add> 'length' => 25, <add> 'null' => false <add> ])->removeColumn('title') <add> ->removeColumn('unknown'); <add> <add> $this->assertSame($table, $result); <add> $this->assertEquals([], $table->columns()); <add> $this->assertNull($table->column('title')); <add> $this->assertSame([], $table->typeMap()); <add> } <add> <ide> /** <ide> * Test isNullable method <ide> *
2
Go
Go
add volumes back to inspect
996133b9babbe4c4dfb42ee0d5aea9566568af14
<ide><path>daemon/inspect.go <ide> func (daemon *Daemon) ContainerInspect(job *engine.Job) engine.Status { <ide> out.Set("ExecDriver", container.ExecDriver) <ide> out.Set("MountLabel", container.MountLabel) <ide> out.Set("ProcessLabel", container.ProcessLabel) <add> out.SetJson("Volumes", container.Volumes) <ide> out.SetJson("VolumesRW", container.VolumesRW) <ide> out.SetJson("HostConfig", container.hostConfig) <ide> if _, err := out.WriteTo(job.Stdout); err != nil {
1
Python
Python
add safeguard before looking in folders
47e1676255e5dd86b9541f734cd4f4bdcbb50f4a
<ide><path>src/transformers/utils/hub.py <ide> def get_cached_models(cache_dir: Union[str, Path] = None) -> List[Tuple]: <ide> cache_dir = TRANSFORMERS_CACHE <ide> elif isinstance(cache_dir, Path): <ide> cache_dir = str(cache_dir) <add> if not os.path.isdir(cache_dir): <add> return [] <ide> <ide> cached_models = [] <ide> for file in os.listdir(cache_dir): <ide> def try_to_load_from_cache(cache_dir, repo_id, filename, revision=None): <ide> if not os.path.isdir(model_cache): <ide> # No cache for this model <ide> return None <add> for subfolder in ["refs", "snapshots"]: <add> if not os.path.isdir(os.path.join(model_cache, subfolder)): <add> return None <ide> <ide> # Resolve refs (for instance to convert main to the associated commit sha) <ide> cached_refs = os.listdir(os.path.join(model_cache, "refs")) <ide> def get_all_cached_files(cache_dir=None): <ide> cache_dir = TRANSFORMERS_CACHE <ide> else: <ide> cache_dir = str(cache_dir) <add> if not os.path.isdir(cache_dir): <add> return [] <ide> <ide> cached_files = [] <ide> for file in os.listdir(cache_dir):
1
Text
Text
remove duplicate content from readline doc
3c23db4d8a8cc51205f1999e5646d386322fb774
<ide><path>doc/api/readline.md <ide> added: v0.1.98 <ide> The `rl.close()` method closes the `readline.Interface` instance and <ide> relinquishes control over the `input` and `output` streams. When called, <ide> the `'close'` event will be emitted. <del>Closes the `Interface` instance, relinquishing control on the `input` and <del>`output` streams. The `'close'` event will also be emitted. <ide> <ide> ### rl.pause() <ide> <!-- YAML
1
Go
Go
fix golint warnings
270e8cf64dee586240968900fb1cf8e36ed641a5
<ide><path>graph/history.go <ide> func (graph *Graph) depth(img *image.Image) (int, error) { <ide> return count, nil <ide> } <ide> <del>// Set the max depth to the aufs default that most <del>// kernels are compiled with <add>// Set the max depth to the aufs default that most kernels are compiled with. <ide> // For more information see: http://sourceforge.net/p/aufs/aufs3-standalone/ci/aufs3.12/tree/config.mk <del>const MaxImageDepth = 127 <add>const maxImageDepth = 127 <ide> <ide> // CheckDepth returns an error if the depth of an image, as returned <ide> // by ImageDepth, is too large to support creating a container from it <ide> func (graph *Graph) CheckDepth(img *image.Image) error { <ide> if err != nil { <ide> return err <ide> } <del> if depth+2 >= MaxImageDepth { <del> return fmt.Errorf("Cannot create container with more than %d parents", MaxImageDepth) <add> if depth+2 >= maxImageDepth { <add> return fmt.Errorf("Cannot create container with more than %d parents", maxImageDepth) <ide> } <ide> return nil <ide> } <ide><path>pkg/devicemapper/devmapper_wrapper_deferred_remove.go <ide> package devicemapper <ide> */ <ide> import "C" <ide> <del>// LibraryDeferredRemovalsupport is supported when statically linked. <add>// LibraryDeferredRemovalSupport is supported when statically linked. <ide> const LibraryDeferredRemovalSupport = true <ide> <ide> func dmTaskDeferredRemoveFct(task *cdmTask) int { <ide><path>pkg/mflag/flag.go <ide> var Usage = func() { <ide> PrintDefaults() <ide> } <ide> <del>// Usage prints to standard error a usage message documenting the standard command layout <add>// ShortUsage prints to standard error a usage message documenting the standard command layout <ide> // The function is a variable that may be changed to point to a custom function. <ide> var ShortUsage = func() { <ide> fmt.Fprintf(CommandLine.output, "Usage of %s:\n", os.Args[0]) <ide><path>pkg/stringid/stringid.go <ide> func TruncateID(id string) string { <ide> <ide> func generateID(crypto bool) string { <ide> b := make([]byte, 32) <del> var r io.Reader = random.Reader <add> r := random.Reader <ide> if crypto { <ide> r = rand.Reader <ide> } <ide><path>pkg/tarsum/tarsum.go <ide> var ( <ide> } <ide> ) <ide> <del>// TarSum default is "sha256" <add>// DefaultTHash is default TarSum hashing algoritm - "sha256". <ide> var DefaultTHash = NewTHash("sha256", sha256.New) <ide> <ide> type simpleTHash struct { <ide><path>pkg/tlsconfig/config.go <ide> var clientCipherSuites = []uint16{ <ide> tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, <ide> } <ide> <del>// For use by code which already has a crypto/tls options struct but wants to <del>// use a commonly accepted set of TLS cipher suites, with known weak algorithms removed <add>// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls <add>// options struct but wants to use a commonly accepted set of TLS cipher suites, with <add>// known weak algorithms removed. <ide> var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...) <ide> <ide> // ServerDefault is a secure-enough TLS configuration for the server TLS configuration.
6
Text
Text
use an easier word
6308238498b6b5a95510d6346436fc7b0febd0d1
<ide><path>docs/docs/introducing-jsx.md <ide> ReactDOM.render( <ide> <ide> [Try it on CodePen.](http://codepen.io/gaearon/pen/PGEjdG?editors=0010) <ide> <del>We split JSX over multiple lines for readability. While it isn't mandatory, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of [automatic semicolon insertion](http://stackoverflow.com/q/2846283). <add>We split JSX over multiple lines for readability. While it isn't required, when doing this, we also recommend wrapping it in parentheses to avoid the pitfalls of [automatic semicolon insertion](http://stackoverflow.com/q/2846283). <ide> <ide> ### JSX is an Expression Too <ide>
1
Mixed
Python
add more settings to settings.py
c707034649fa9e24f0c6c3c0580dc06f90eac373
<ide><path>djangorestframework/settings.py <ide> 'djangorestframework.parsers.JSONParser', <ide> 'djangorestframework.parsers.FormParser' <ide> ), <add> 'DEFAULT_AUTHENTICATION': ( <add> 'djangorestframework.authentication.SessionAuthentication', <add> 'djangorestframework.authentication.UserBasicAuthentication' <add> ), <add> 'DEFAULT_PERMISSIONS': (), <add> 'DEFAULT_THROTTLES': (), <ide> 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser', <ide> 'UNAUTHENTICATED_TOKEN': None <ide> } <ide> # List of settings that may be in string import notation. <ide> IMPORT_STRINGS = ( <ide> 'DEFAULT_RENDERERS', <add> 'DEFAULT_PARSERS', <add> 'DEFAULT_AUTHENTICATION', <add> 'DEFAULT_PERMISSIONS', <add> 'DEFAULT_THROTTLES', <ide> 'UNAUTHENTICATED_USER', <ide> 'UNAUTHENTICATED_TOKEN' <ide> ) <ide> def perform_import(val, setting): <ide> if val is None or setting not in IMPORT_STRINGS: <ide> return val <ide> <del> try: <del> if isinstance(val, basestring): <del> return import_from_string(val) <del> elif isinstance(val, (list, tuple)): <del> return [import_from_string(item) for item in val] <del> return val <del> except: <del> msg = "Could not import '%s' for API setting '%s'" % (val, setting) <del> raise ImportError(msg) <add> if isinstance(val, basestring): <add> return import_from_string(val, setting) <add> elif isinstance(val, (list, tuple)): <add> return [import_from_string(item, setting) for item in val] <add> return val <ide> <ide> <del>def import_from_string(val): <add>def import_from_string(val, setting): <ide> """ <ide> Attempt to import a class from a string representation. <ide> """ <del> # Nod to tastypie's use of importlib. <del> parts = val.split('.') <del> module_path, class_name = '.'.join(parts[:-1]), parts[-1] <del> module = importlib.import_module(module_path) <del> return getattr(module, class_name) <add> try: <add> # Nod to tastypie's use of importlib. <add> parts = val.split('.') <add> module_path, class_name = '.'.join(parts[:-1]), parts[-1] <add> module = importlib.import_module(module_path) <add> return getattr(module, class_name) <add> except: <add> msg = "Could not import '%s' for API setting '%s'" % (val, setting) <add> raise ImportError(msg) <ide> <ide> <ide> class APISettings(object): <ide><path>docs/api-guide/settings.md <ide> Default: <ide> <ide> A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties. <ide> <del>Default if `DEBUG` is `True`: <add>Default: <ide> <ide> ( <ide> 'djangorestframework.authentication.SessionAuthentication', <ide> 'djangorestframework.authentication.UserBasicAuthentication' <ide> ) <ide> <del>Default if `DEBUG` is `False`: <del> <del> ( <del> 'djangorestframework.authentication.SessionAuthentication', <del> ) <del> <ide> ## DEFAULT_PERMISSIONS <ide> <ide> A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
2
Javascript
Javascript
remove useless statement
8900a4663f45d047894b98875f58529f6026746e
<ide><path>lib/internal/streams/from.js <ide> function from(Readable, iterable, opts) { <ide> }); <ide> } <ide> <del> let isAsync = false; <add> let isAsync; <ide> if (iterable && iterable[SymbolAsyncIterator]) { <ide> isAsync = true; <ide> iterator = iterable[SymbolAsyncIterator]();
1
Ruby
Ruby
remove more uses of deprecated loggers
c056787d5de2f3fb5c050c432d3eff3cdade09a3
<ide><path>activerecord/test/cases/base_test.rb <ide> def test_silence_sets_log_level_back_to_level_before_yield <ide> def test_benchmark_with_log_level <ide> original_logger = ActiveRecord::Base.logger <ide> log = StringIO.new <del> ActiveRecord::Base.logger = Logger.new(log) <add> ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) <ide> ActiveRecord::Base.logger.level = Logger::WARN <ide> ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count } <ide> ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count } <ide> def test_benchmark_with_log_level <ide> def test_benchmark_with_use_silence <ide> original_logger = ActiveRecord::Base.logger <ide> log = StringIO.new <del> ActiveRecord::Base.logger = Logger.new(log) <add> ActiveRecord::Base.logger = ActiveSupport::Logger.new(log) <ide> ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" } <ide> assert_match(/Quiet/, log.string) <ide> ensure
1
Javascript
Javascript
remove debug code
bf2c5257880410637b113c1e29bf8bee50e8e479
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> <ide> var fn = sh.get("Function"); <ide> fn = this.xref.fetchIfRef(fn); <del>/* <del> console.log("x0: "+ x0, "y0: "+ y0, "x1: "+ x1, "y1: "+ y1); <del> console.log("size: "+ fn.dict.get("Size")); <del> console.log("BPS: "+ fn.dict.get("BitsPerSample")); <del> console.log(fn.dict.get("Encode")); <del> console.log(fn.dict.get("Range")); <del> console.log(fn.dict.get("Decode")); <del>*/ <add> <ide> var gradient = this.ctx.createLinearGradient(x0, y0, x1, y1); <ide> <ide> gradient.addColorStop(0, 'rgb(0,0,255)');
1
Ruby
Ruby
fix leaky chain on polymorphic association
51660f0191a7c71ce298c71e7366ebab55be729c
<ide><path>activerecord/lib/active_record/reflection.rb <ide> def through_reflection <ide> def chain <ide> @chain ||= begin <ide> a = source_reflection.chain <del> b = through_reflection.chain <add> b = through_reflection.chain.map(&:dup) <ide> <ide> if options[:source_type] <ide> b[0] = PolymorphicReflection.new(b[0], self) <ide><path>activerecord/test/cases/reflection_test.rb <ide> require 'models/department' <ide> require 'models/cake_designer' <ide> require 'models/drink_designer' <add>require 'models/recipe' <ide> <ide> class ReflectionTest < ActiveRecord::TestCase <ide> include ActiveRecord::Reflection <ide> def test_scope_chain_does_not_interfere_with_hmt_with_polymorphic_case <ide> assert_equal 2, @hotel.chefs.size <ide> end <ide> <add> def test_scope_chain_of_polymorphic_association_does_not_leak_into_other_hmt_associations <add> hotel = Hotel.create! <add> department = hotel.departments.create! <add> drink = department.chefs.create!(employable: DrinkDesigner.create!) <add> recipe = Recipe.create!(chef_id: drink.id, hotel_id: hotel.id) <add> <add> hotel.drink_designers.to_a <add> assert_sql(/^(?!.*employable_type).*$/) { hotel.recipes.to_a } <add> end <add> <ide> def test_nested? <ide> assert !Author.reflect_on_association(:comments).nested? <ide> assert Author.reflect_on_association(:tags).nested? <ide><path>activerecord/test/models/chef.rb <ide> class Chef < ActiveRecord::Base <ide> belongs_to :employable, polymorphic: true <add> has_many :recipes <ide> end <ide><path>activerecord/test/models/hotel.rb <ide> class Hotel < ActiveRecord::Base <ide> has_many :chefs, through: :departments <ide> has_many :cake_designers, source_type: 'CakeDesigner', source: :employable, through: :chefs <ide> has_many :drink_designers, source_type: 'DrinkDesigner', source: :employable, through: :chefs <add> has_many :recipes, through: :chefs <ide> end <ide><path>activerecord/test/models/recipe.rb <add>class Recipe < ActiveRecord::Base <add> belongs_to :chef <add>end <ide><path>activerecord/test/schema/schema.rb <ide> def except(adapter_names_to_exclude) <ide> t.string :employable_type <ide> t.integer :department_id <ide> end <add> create_table :recipes, force: true do |t| <add> t.integer :chef_id <add> t.integer :hotel_id <add> end <ide> <ide> create_table :records, force: true do |t| <ide> end
6
PHP
PHP
fix another typo
a853c0f93ab7031a0558f03c8f6ad5ccc21699e6
<ide><path>lib/Cake/Model/Model.php <ide> class Model extends Object { <ide> * <ide> * ### Valid keys in validations <ide> * <del> * - `role`: String with method name, regular expression (started by slash) or array with method and parameters <add> * - `rule`: String with method name, regular expression (started by slash) or array with method and parameters <ide> * - `message`: String with the message or array if have multiple parameters. See http://php.net/sprintf <ide> * - `last`: Boolean value to indicate if continue validating the others rules if the current fail [Default: true] <ide> * - `required`: Boolean value to indicate if the field must be present on save
1
Ruby
Ruby
suggest url with full_index=1
b37c3e9cb252a7f83db2b58e3cf2e020523d1d51
<ide><path>Library/Homebrew/rubocops/patches.rb <ide> def patch_problems(patch) <ide> if match_obj = regex_match_group(patch, gh_patch_diff_pattern) <ide> problem <<~EOS <ide> use GitHub pull request URLs: <del> https://github.com/#{match_obj[1]}/#{match_obj[2]}/pull/#{match_obj[3]}.patch <add> https://github.com/#{match_obj[1]}/#{match_obj[2]}/pull/#{match_obj[3]}.patch?full_index=1 <ide> Rather than patch-diff: <ide> #{patch_url} <ide> EOS <ide><path>Library/Homebrew/test/rubocops/patches_spec.rb <ide> def patches <ide> [{ message: <ide> <<~EOS, <ide> use GitHub pull request URLs: <del> https://github.com/foo/foo-bar/pull/100.patch <add> https://github.com/foo/foo-bar/pull/100.patch?full_index=1 <ide> Rather than patch-diff: <ide> https://patch-diff.githubusercontent.com/raw/foo/foo-bar/pull/100.patch <ide> EOS <ide> class Foo < Formula <ide> [{ message: <ide> <<~EOS, <ide> use GitHub pull request URLs: <del> https://github.com/foo/foo-bar/pull/100.patch <add> https://github.com/foo/foo-bar/pull/100.patch?full_index=1 <ide> Rather than patch-diff: <ide> https://patch-diff.githubusercontent.com/raw/foo/foo-bar/pull/100.patch <ide> EOS
2
PHP
PHP
make hotfile() public for vite
0d936a95f201ab696434d828743f1302eb6e55c6
<ide><path>src/Illuminate/Foundation/Vite.php <ide> public function withEntryPoints($entryPoints) <ide> * <ide> * @return string <ide> */ <del> protected function hotFile() <add> public function hotFile() <ide> { <ide> return $this->hotFile ?? public_path('/hot'); <ide> } <ide><path>src/Illuminate/Support/Facades/Vite.php <ide> * @method static string useCspNonce(?string $nonce = null) <ide> * @method static string|null cspNonce() <ide> * @method static string asset(string $asset, string|null $buildDirectory) <add> * @method static string hotFile() <ide> * @method static \Illuminate\Foundation\Vite useBuildDirectory(string $path) <ide> * @method static \Illuminate\Foundation\Vite useHotFile(string $path) <ide> * @method static \Illuminate\Foundation\Vite useIntegrityKey(string|false $key)
2
Ruby
Ruby
preserve collaction when changing column in mysql
3a0d0f4bd878bf180002831c616a524aaec39203
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def build_change_column_definition(table_name, column_name, type, **options) # : <ide> options[:comment] = column.comment <ide> end <ide> <add> unless options.key?(:collation) <add> options[:collation] = column.collation <add> end <add> <ide> unless options.key?(:auto_increment) <ide> options[:auto_increment] = column.auto_increment? <ide> end <ide><path>activerecord/test/cases/adapters/mysql2/charset_collation_test.rb <ide> class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase <ide> assert_equal "utf8mb4_general_ci", column.collation <ide> end <ide> <add> test "change column preserves collation" do <add> @connection.add_column :charset_collations, :description, :string, charset: "utf8mb4", collation: "utf8mb4_unicode_ci" <add> @connection.change_column :charset_collations, :description, :text <add> <add> column = @connection.columns(:charset_collations).find { |c| c.name == "description" } <add> assert_equal :text, column.type <add> assert_equal "utf8mb4_unicode_ci", column.collation <add> end <add> <ide> test "schema dump includes collation" do <ide> output = dump_table_schema("charset_collations") <ide> assert_match %r/create_table "charset_collations", id: { type: :string, collation: "utf8mb4_bin" }/, output
2
Javascript
Javascript
fix resource leak
7aa5924dc6e8d80980a9b79f3d5fc6305bf1aea7
<ide><path>lib/http.js <ide> function Agent(options) { <ide> var name = host + ':' + port; <ide> if (self.requests[name] && self.requests[name].length) { <ide> self.requests[name].shift().onSocket(socket); <add> if (self.requests[name].length === 0) { <add> // don't leak <add> delete this.requests[name]; <add> } <ide> } else { <ide> // If there are no pending requests just destroy the <ide> // socket and it will get removed from the pool. This <ide> Agent.prototype.removeSocket = function(s, name, host, port) { <ide> var index = this.sockets[name].indexOf(s); <ide> if (index !== -1) { <ide> this.sockets[name].splice(index, 1); <add> if (this.sockets[name].length === 0) { <add> // don't leak <add> delete this.sockets[name]; <add> } <ide> } <del> } else if (this.sockets[name] && this.sockets[name].length === 0) { <del> // don't leak <del> delete this.sockets[name]; <del> delete this.requests[name]; <ide> } <ide> if (this.requests[name] && this.requests[name].length) { <ide> // If we have pending requests and a socket gets closed a new one <ide><path>test/simple/test-http-client-agent.js <ide> function request(i) { <ide> var socket = req.socket; <ide> socket.on('close', function() { <ide> ++count; <del> assert.equal(http.globalAgent.sockets[name].length, max - count); <del> assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); <del> if (count === max) { <add> if (count < max) { <add> assert.equal(http.globalAgent.sockets[name].length, max - count); <add> assert.equal(http.globalAgent.sockets[name].indexOf(socket), -1); <add> } else { <add> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <add> assert(!http.globalAgent.requests.hasOwnProperty(name)); <ide> server.close(); <ide> } <ide> }); <ide><path>test/simple/test-http-keep-alive.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <del>var util = require('util'); <ide> <ide> var body = 'hello world\n'; <del>var headers = {'connection': 'keep-alive'}; <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, {'Content-Length': body.length}); <ide> var server = http.createServer(function(req, res) { <ide> }); <ide> <ide> var connectCount = 0; <add>var name = 'localhost:' + common.PORT; <add>var agent = new http.Agent({maxSockets: 1}); <add>var headers = {'connection': 'keep-alive'}; <ide> <ide> server.listen(common.PORT, function() { <del> var agent = new http.Agent({maxSockets: 1}); <del> var request = http.request({method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent}, function() { <del> assert.equal(1, agent.sockets['localhost:' + common.PORT].length); <add> http.get({ <add> path: '/', headers: headers, port: common.PORT, agent: agent <add> }, function(response) { <add> assert.equal(agent.sockets[name].length, 1); <add> assert.equal(agent.requests[name].length, 2); <ide> }); <del> request.end(); <ide> <del> request = http.request({method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent}, function() { <del> assert.equal(1, agent.sockets['localhost:' + common.PORT].length); <add> http.get({ <add> path: '/', headers: headers, port: common.PORT, agent: agent <add> }, function(response) { <add> assert.equal(agent.sockets[name].length, 1); <add> assert.equal(agent.requests[name].length, 1); <ide> }); <del> request.end(); <del> request = http.request({method: 'GET', path: '/', headers: headers, port: common.PORT, agent: agent}, function(response) { <add> <add> http.get({ <add> path: '/', headers: headers, port: common.PORT, agent: agent <add> }, function(response) { <ide> response.on('end', function() { <del> assert.equal(1, agent.sockets['localhost:' + common.PORT].length); <add> assert.equal(agent.sockets[name].length, 1); <add> assert(!agent.requests.hasOwnProperty(name)); <ide> server.close(); <ide> }); <ide> }); <del> request.end(); <add>}); <add> <add>process.on('exit', function() { <add> assert(!agent.sockets.hasOwnProperty(name)); <add> assert(!agent.requests.hasOwnProperty(name)); <ide> }); <ide><path>test/simple/test-http-upgrade-agent.js <ide> srv.listen(common.PORT, '127.0.0.1', function() { <ide> 'upgrade': 'websocket' <ide> } <ide> }; <add> var name = options.host + ':' + options.port; <ide> <ide> var req = http.request(options); <ide> req.end(); <ide> srv.listen(common.PORT, '127.0.0.1', function() { <ide> 'connection': 'upgrade', <ide> 'upgrade': 'websocket' }; <ide> assert.deepEqual(expectedHeaders, res.headers); <del> assert.equal(http.globalAgent.sockets[options.host + ':' + options.port].length, 1); <add> assert.equal(http.globalAgent.sockets[name].length, 1); <ide> <ide> process.nextTick(function() { <ide> // Make sure this request got removed from the pool. <del> assert.equal(http.globalAgent.sockets[options.host + ':' + options.port].length, 0); <add> assert(!http.globalAgent.sockets.hasOwnProperty(name)); <ide> socket.end(); <ide> srv.close(); <ide>
4
Text
Text
clarify the filenames
45a65ee45d7895b9ffaf3c0f85a87ccb3acc138f
<ide><path>docs/advanced/AsyncActions.md <ide> We’ll use separate types in this tutorial. <ide> <ide> Let’s start by defining the several synchronous action types and action creators we need in our example app. Here, the user can select a reddit to display: <ide> <add>#### `actions.js` <add> <ide> ```js <ide> export const SELECT_REDDIT = 'SELECT_REDDIT'; <ide>
1
Ruby
Ruby
fix possible xss vector in js escape helper
033a738817abd6e446e1b320cb7d1a5c15224e9a
<ide><path>actionview/lib/action_view/helpers/javascript_helper.rb <ide> module JavaScriptHelper <ide> "\n" => '\n', <ide> "\r" => '\n', <ide> '"' => '\\"', <del> "'" => "\\'" <add> "'" => "\\'", <add> "`" => "\\`", <add> "$" => "\\$" <ide> } <ide> <ide> JS_ESCAPE_MAP[(+"\342\200\250").force_encoding(Encoding::UTF_8).encode!] = "&#x2028;" <ide> def escape_javascript(javascript) <ide> if javascript.empty? <ide> result = "" <ide> else <del> result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u, JS_ESCAPE_MAP) <add> result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"']|[`]|[$])/u, JS_ESCAPE_MAP) <ide> end <ide> javascript.html_safe? ? result.html_safe : result <ide> end <ide><path>actionview/test/template/javascript_helper_test.rb <ide> def test_escape_javascript <ide> assert_equal %(dont <\\/close> tags), j(%(dont </close> tags)) <ide> end <ide> <add> def test_escape_backtick <add> assert_equal "\\`", escape_javascript("`") <add> end <add> <add> def test_escape_dollar_sign <add> assert_equal "\\$", escape_javascript("$") <add> end <add> <ide> def test_escape_javascript_with_safebuffer <ide> given = %('quoted' "double-quoted" new-line:\n </closed>) <ide> expect = %(\\'quoted\\' \\"double-quoted\\" new-line:\\n <\\/closed>)
2
Go
Go
change dettach to detach
fdec5197f145a1aa18329337746f6a94389da0a1
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) { <ide> <ide> // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode <ide> // but using --attach instead of -a to make sure we read the flag correctly <del>func (s *DockerSuite) TestRunAttachWithDettach(c *check.C) { <add>func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) { <ide> cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true") <ide> _, stderr, _, err := runCommandWithStdoutStderr(cmd) <ide> if err == nil {
1
Python
Python
remove "double" assignment in tf-bart like models
714855bd8fbff69c93e76193bbf46aa9dee06412
<ide><path>src/transformers/models/bart/modeling_tf_bart.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide><path>src/transformers/models/blenderbot/modeling_tf_blenderbot.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide><path>src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide><path>src/transformers/models/marian/modeling_tf_marian.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide><path>src/transformers/models/mbart/modeling_tf_mbart.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide> <ide><path>src/transformers/models/pegasus/modeling_tf_pegasus.py <ide> def call( <ide> attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape( <ide> attn_weights, (bsz, self.num_heads, tgt_len, src_len) <ide> ) <del> attn_weights = attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <add> attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len)) <ide> <ide> attn_probs = self.dropout(attn_weights, training=training) <ide>
6
Go
Go
use math.maxint32 instead of math.maxuint32
eb45602d2fa0fac8a694d2afb1c59ef60b0e1f77
<ide><path>daemon/logger/fluentd/fluentd.go <ide> func New(ctx logger.Context) (logger.Logger, error) { <ide> } <ide> logrus.Debugf("logging driver fluentd configured for container:%s, host:%s, port:%d, tag:%s.", ctx.ContainerID, host, port, tag) <ide> <del> // logger tries to recoonect 2**64 - 1 times <add> // logger tries to recoonect 2**32 - 1 times <ide> // failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds] <del> log, err := fluent.New(fluent.Config{FluentPort: port, FluentHost: host, RetryWait: 1000, MaxRetry: math.MaxUint32}) <add> log, err := fluent.New(fluent.Config{FluentPort: port, FluentHost: host, RetryWait: 1000, MaxRetry: math.MaxInt32}) <ide> if err != nil { <ide> return nil, err <ide> }
1
PHP
PHP
add tests for count with autofields
b6cddfdda9eb73ba37e9e652878b79d12f62f9d9
<ide><path>tests/TestCase/ORM/QueryTest.php <ide> public function testAutoFieldsWithContainQueryBuilder() { <ide> $this->assertArrayHasKey('name', $result['author']); <ide> $this->assertArrayHasKey('compute', $result); <ide> } <add> <add>/** <add> * Test count with autoFields <add> * <add> * @return void <add> */ <add> public function testAutoFieldsCount() { <add> $table = TableRegistry::get('Articles'); <add> $table->belongsTo('Authors'); <add> <add> $resultNormal = $table->find() <add> ->select(['myField' => '(SELECT RAND())']) <add> ->hydrate(false) <add> ->contain('Authors') <add> ->count(); <add> <add> $resultAutoFields = $table->find() <add> ->select(['myField' => '(SELECT RAND())']) <add> ->autoFields(true) <add> ->hydrate(false) <add> ->contain('Authors') <add> ->count(); <add> <add> $this->assertNotNull($resultNormal); <add> $this->assertNotNull($resultAutoFields); <add> $this->assertEquals($resultNormal, $resultAutoFields); <add> } <ide> <ide> }
1
Text
Text
add release notes for v5.5.6 and v5.5.7
8001e8616acbc467c77b8b02bc7787d6a9555b23
<ide><path>CHANGELOG-5.5.md <ide> # Release Notes for 5.5.x <ide> <add>## v5.5.7 (2017-09-19) <add> <add>### Fixed <add>- Fix `CacheClearCommand` binding ([#21256](https://github.com/laravel/framework/pull/21256)) <add> <add> <add>## v5.5.6 (2017-09-19) <add> <add>### Changed <add>- Clear real-time facades when running `cache:clear` ([#21250](https://github.com/laravel/framework/pull/21250), [1856601](https://github.com/laravel/framework/commit/185660178ad213140411ca27550cdaf44c650002)) <add> <add>### Fixed <add>- Reverted stable sort support in `Collection::sortBy()` ([#21255](https://github.com/laravel/framework/pull/21255)) <add> <add> <ide> ## v5.5.5 (2017-09-19) <ide> <ide> ### Added
1