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
Javascript
Javascript
improve test stability for ticket. close gh-1328
9214c37bbaa79aa99c85c8043a870c8cec3d7b0f
<ide><path>test/unit/effects.js <ide> test("Do not append px to 'fill-opacity' #9548", 1, function() { <ide> }); <ide> }); <ide> <del>test("line-height animates correctly (#13855)", function() { <del> expect( 12 ); <del> stop(); <del> <add>asyncTest("line-height animates correctly (#13855)", 12, function() { <ide> var <ide> animated = jQuery( <del> "<p style='line-height: 4;'>unitless</p>" + <del> "<p style='line-height: 50px;'>px</p>" + <del> "<p style='line-height: 420%;'>percent</p>" + <del> "<p style='line-height: 2.5em;'>em</p>" <add> "<p style='line-height: 5000;'>unitless</p>" + <add> "<p style='line-height: 5000px;'>px</p>" + <add> "<p style='line-height: 5000%;'>percent</p>" + <add> "<p style='line-height: 5000em;'>em</p>" <ide> ).appendTo("#qunit-fixture"), <ide> initialHeight = jQuery.map( animated, function( el ) { <ide> return jQuery( el ).height(); <ide> test("line-height animates correctly (#13855)", function() { <ide> var label = jQuery.text( this ), <ide> initial = initialHeight[ i ], <ide> height = jQuery( this ).height(); <del> ok( height < initial, "hide " + label + ": upper bound" ); <del> ok( height > initial / 2, "hide " + label + ": lower bound" ); <add> ok( height < initial, "hide " + label + ": upper bound; height:" + height + "; intitial: " + initial ); <add> ok( height > initial / 2, "hide " + label + ": lower bound; height:" + height + "; intitial/2: " + initial / 2 ); <ide> }); <ide> animated.stop( true, true ).hide().animate( { "line-height": "show" }, 1500 ); <ide> setTimeout(function() { <ide> animated.each(function( i ) { <ide> var label = jQuery.text( this ), <ide> initial = initialHeight[ i ], <ide> height = jQuery( this ).height(); <del> ok( height < initial / 2, "show " + label + ": upper bound" ); <add> ok( height < initial / 2, "show " + label + ": upper bound; height:" + height + "; intitial/2: " + initial / 2 ); <ide> }); <ide> animated.stop( true, true ); <ide> start();
1
Ruby
Ruby
add built_on & arch information
b338398a8c002953d64852c51f0d7b5e9c419332
<ide><path>Library/Homebrew/development_tools.rb <ide> def curl_handles_most_https_certificates? <ide> def subversion_handles_most_https_certificates? <ide> true <ide> end <add> <add> def build_system_info <add> { <add> "os" => ENV["HOMEBREW_SYSTEM"], <add> "os_version" => OS_VERSION, <add> "cpu_family" => Hardware::CPU.family, <add> } <add> end <add> alias generic_build_system_info build_system_info <ide> end <ide> end <ide> <ide><path>Library/Homebrew/extend/os/mac/development_tools.rb <ide> def custom_installation_instructions <ide> brew install gcc <ide> EOS <ide> end <add> <add> def build_system_info <add> build_info = { <add> "xcode" => MacOS::Xcode.version.to_s.presence, <add> "clt" => MacOS::CLT.version.to_s.presence, <add> } <add> generic_build_system_info.merge build_info <add> end <ide> end <ide> end <ide><path>Library/Homebrew/tab.rb <ide> def self.create(formula, compiler, stdlib) <ide> "stdlib" => stdlib, <ide> "aliases" => formula.aliases, <ide> "runtime_dependencies" => Tab.runtime_deps_hash(runtime_deps), <add> "arch" => Hardware::CPU.arch, <ide> "source" => { <ide> "path" => formula.specified_path.to_s, <ide> "tap" => formula.tap&.name, <ide> def self.create(formula, compiler, stdlib) <ide> "version_scheme" => formula.version_scheme, <ide> }, <ide> }, <add> "built_on" => DevelopmentTools.build_system_info, <ide> } <ide> <ide> new(attributes) <ide> def self.empty <ide> "version_scheme" => 0, <ide> }, <ide> }, <add> "built_on" => DevelopmentTools.generic_build_system_info, <ide> } <ide> <ide> new(attributes) <ide> def to_json(options = nil) <ide> "aliases" => aliases, <ide> "runtime_dependencies" => runtime_dependencies, <ide> "source" => source, <add> "built_on" => built_on, <ide> } <ide> <ide> JSON.generate(attributes, options) <ide><path>Library/Homebrew/test/caveats_spec.rb <ide> def plist <ide> "plist_test.plist" <ide> end <ide> end <del> allow(ENV).to receive(:[]).with("TMUX").and_return(true) <add> ENV["TMUX"] = "1" <ide> allow(Homebrew).to receive(:_system).with("/usr/bin/pbpaste").and_return(false) <ide> caveats = described_class.new(f).caveats <ide>
4
Python
Python
add downgrade to some fab migrations
f964fd47de5435f5c354c6211d24bd2dfaaffa9e
<ide><path>airflow/migrations/versions/2c6edca13270_resource_based_permissions.py <ide> def remap_permissions(): <ide> appbuilder.sm.delete_action(old_action_name) <ide> <ide> <add>def undo_remap_permissions(): <add> """Unapply Map Airflow permissions""" <add> appbuilder = create_app(config={'FAB_UPDATE_PERMS': False}).appbuilder <add> for old, new in mapping.items: <add> (new_resource_name, new_action_name) = new[0] <add> new_permission = appbuilder.sm.get_permission(new_action_name, new_resource_name) <add> if not new_permission: <add> continue <add> for old_resource_name, old_action_name in old: <add> old_permission = appbuilder.sm.create_permission(old_action_name, old_resource_name) <add> for role in appbuilder.sm.get_all_roles(): <add> if appbuilder.sm.permission_exists_in_one_or_more_roles( <add> new_resource_name, new_action_name, [role.id] <add> ): <add> appbuilder.sm.add_permission_to_role(role, old_permission) <add> appbuilder.sm.remove_permission_from_role(role, new_permission) <add> appbuilder.sm.delete_permission(new_action_name, new_resource_name) <add> <add> if not appbuilder.sm.get_action(new_action_name): <add> continue <add> resources = appbuilder.sm.get_all_resources() <add> if not any(appbuilder.sm.get_permission(new_action_name, resource.name) for resource in resources): <add> appbuilder.sm.delete_action(new_action_name) <add> <add> <ide> def upgrade(): <ide> """Apply Resource based permissions.""" <ide> log = logging.getLogger() <ide> def upgrade(): <ide> <ide> def downgrade(): <ide> """Unapply Resource based permissions.""" <add> log = logging.getLogger() <add> handlers = log.handlers[:] <add> undo_remap_permissions() <add> log.handlers = handlers <ide><path>airflow/migrations/versions/849da589634d_prefix_dag_permissions.py <ide> def prefix_individual_dag_permissions(session): <ide> session.commit() <ide> <ide> <add>def remove_prefix_in_individual_dag_permissions(session): <add> dag_perms = ['can_read', 'can_edit'] <add> prefix = "DAG:" <add> perms = ( <add> session.query(Permission) <add> .join(Action) <add> .filter(Action.name.in_(dag_perms)) <add> .join(Resource) <add> .filter(Resource.name.like(prefix + '%')) <add> .all() <add> ) <add> for permission in perms: <add> permission.resource.name = permission.resource.name[len(prefix) :] <add> session.commit() <add> <add> <ide> def get_or_create_dag_resource(session): <ide> dag_resource = get_resource_query(session, permissions.RESOURCE_DAG).first() <ide> if dag_resource: <ide> def get_or_create_dag_resource(session): <ide> return dag_resource <ide> <ide> <add>def get_or_create_all_dag_resource(session): <add> all_dag_resource = get_resource_query(session, 'all_dags').first() <add> if all_dag_resource: <add> return all_dag_resource <add> <add> all_dag_resource = Resource() <add> all_dag_resource.name = 'all_dags' <add> session.add(all_dag_resource) <add> session.commit() <add> <add> return all_dag_resource <add> <add> <ide> def get_or_create_action(session, action_name): <ide> action = get_action_query(session, action_name).first() <ide> if action: <ide> def migrate_to_new_dag_permissions(db): <ide> db.session.commit() <ide> <ide> <add>def undo_migrate_to_new_dag_permissions(session): <add> # Remove prefix from individual dag perms <add> remove_prefix_in_individual_dag_permissions(session) <add> <add> # Update existing permissions to use `can_dag_read` instead of `can_read` <add> can_read_action = get_action_query(session, 'can_read').first() <add> new_can_read_permissions = get_permission_with_action_query(session, can_read_action) <add> can_dag_read_action = get_or_create_action(session, 'can_dag_read') <add> update_permission_action(session, new_can_read_permissions, can_dag_read_action) <add> <add> # Update existing permissions to use `can_dag_edit` instead of `can_edit` <add> can_edit_action = get_action_query(session, 'can_edit').first() <add> new_can_edit_permissions = get_permission_with_action_query(session, can_edit_action) <add> can_dag_edit_action = get_or_create_action(session, 'can_dag_edit') <add> update_permission_action(session, new_can_edit_permissions, can_dag_edit_action) <add> <add> # Update existing permissions for `DAGs` resource to use `all_dags` resource. <add> dag_resource = get_resource_query(session, permissions.RESOURCE_DAG).first() <add> if dag_resource: <add> new_dag_permission = get_permission_with_resource_query(session, dag_resource) <add> old_all_dag_resource = get_or_create_all_dag_resource(session) <add> update_permission_resource(session, new_dag_permission, old_all_dag_resource) <add> <add> # Delete the `DAG` resource <add> session.delete(dag_resource) <add> <add> # Delete `can_read` action <add> if can_read_action: <add> session.delete(can_read_action) <add> <add> # Delete `can_edit` action <add> if can_edit_action: <add> session.delete(can_edit_action) <add> <add> session.commit() <add> <add> <ide> def upgrade(): <ide> db = SQLA() <ide> db.session = settings.Session <ide> def upgrade(): <ide> <ide> <ide> def downgrade(): <del> pass <add> db = SQLA() <add> db.session = settings.Session <add> undo_migrate_to_new_dag_permissions(db.session) <ide><path>airflow/migrations/versions/a13f7613ad25_resource_based_permissions_for_default_.py <ide> def remap_permissions(): <ide> appbuilder.sm.delete_action(old_action_name) <ide> <ide> <add>def undo_remap_permissions(): <add> """Unapply Map Airflow permissions""" <add> appbuilder = create_app(config={'FAB_UPDATE_PERMS': False}).appbuilder <add> for old, new in mapping.items(): <add> (new_resource_name, new_action_name) = new[0] <add> new_permission = appbuilder.sm.get_permission(new_action_name, new_resource_name) <add> if not new_permission: <add> continue <add> for old_action_name, old_resource_name in old: <add> old_permission = appbuilder.sm.create_permission(old_action_name, old_resource_name) <add> for role in appbuilder.sm.get_all_roles(): <add> if appbuilder.sm.permission_exists_in_one_or_more_roles( <add> new_resource_name, new_action_name, [role.id] <add> ): <add> appbuilder.sm.add_permission_to_role(role, old_permission) <add> appbuilder.sm.remove_permission_from_role(role, new_permission) <add> appbuilder.sm.delete_permission(new_action_name, new_resource_name) <add> <add> if not appbuilder.sm.get_action(new_action_name): <add> continue <add> resources = appbuilder.sm.get_all_resources() <add> if not any(appbuilder.sm.get_permission(new_action_name, resource.name) for resource in resources): <add> appbuilder.sm.delete_action(new_action_name) <add> <add> <ide> def upgrade(): <ide> """Apply Resource based permissions.""" <ide> log = logging.getLogger() <ide> def upgrade(): <ide> <ide> def downgrade(): <ide> """Unapply Resource based permissions.""" <add> log = logging.getLogger() <add> handlers = log.handlers[:] <add> undo_remap_permissions() <add> log.handlers = handlers
3
PHP
PHP
add default value for fileengine
e768f1455ce40e0f92c049011a52fab00bcb9348
<ide><path>src/Cache/Engine/FileEngine.php <ide> public function get($key, $default = null) <ide> $key = $this->_key($key); <ide> <ide> if (!$this->_init || $this->_setKey($key) === false) { <del> return null; <add> return $default; <ide> } <ide> <ide> if ($this->_config['lock']) { <ide> public function get($key, $default = null) <ide> $this->_File->flock(LOCK_UN); <ide> } <ide> <del> return null; <add> return $default; <ide> } <ide> <ide> $data = ''; <ide><path>tests/TestCase/Cache/Engine/FileEngineTest.php <ide> protected function _configCache($config = []) <ide> Cache::setConfig('file_test', array_merge($defaults, $config)); <ide> } <ide> <add> /** <add> * Test get with default value <add> * <add> * @return void <add> */ <add> public function testGetDefaultValue() <add> { <add> $file = Cache::pool('file_test'); <add> $this->assertFalse($file->get('nope', false)); <add> $this->assertNull($file->get('nope', null)); <add> $this->assertTrue($file->get('nope', true)); <add> $this->assertSame(0, $file->get('nope', 0)); <add> <add> $file->set('yep', 0); <add> $this->assertSame(0, $file->get('yep', false)); <add> } <add> <ide> /** <ide> * testReadAndWriteCache method <ide> * <ide> public function testReadAndWriteCacheExpired() <ide> * <ide> * @return void <ide> */ <del> public function testReadAndwrite() <add> public function testReadAndWrite() <ide> { <ide> $result = Cache::read('test', 'file_test'); <ide> $expecting = ''; <ide> public function testExpiry() <ide> <ide> sleep(2); <ide> $result = Cache::read('other_test', 'file_test'); <del> $this->assertNull($result); <add> $this->assertNull($result, 'Expired key no result.'); <add> $this->assertSame(0, Cache::pool('file_test')->get('other_test', 0), 'expired values get default.'); <ide> <ide> $this->_configCache(['duration' => '+1 second']); <ide>
2
Python
Python
extract tasklogreader from views.py
eb8683a7255e4efb7bc16c1209da4bc42f62e9bd
<ide><path>airflow/utils/log/log_reader.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import logging <add>from typing import Any, Dict, Iterator, List, Optional, Tuple <add> <add>from cached_property import cached_property <add> <add>from airflow.configuration import conf <add>from airflow.models import TaskInstance <add>from airflow.utils.helpers import render_log_filename <add> <add> <add>class TaskLogReader: <add> """ Task log reader""" <add> <add> def read_log_chunks(self, ti: TaskInstance, try_number: Optional[int], <add> metadata) -> Tuple[List[str], Dict[str, Any]]: <add> """ <add> Reads chunks of Task Instance logs. <add> <add> :param ti: The taskInstance <add> :type ti: TaskInstance <add> :param try_number: If provided, logs for the given try will be returned. <add> Otherwise, logs from all attempts are returned. <add> :type try_number: Optional[int] <add> :param metadata: A dictionary containing information about how to read the task log <add> :type metadata: dict <add> :rtype: Tuple[List[str], Dict[str, Any]] <add> <add> The following is an example of how to use this method to read log: <add> <add> .. code-block:: python <add> <add> logs, metadata = task_log_reader.read_log_chunks(ti, try_number, metadata) <add> logs = logs[0] if try_number is not None else logs <add> <add> where task_log_reader is an instance of TaskLogReader. The metadata will always <add> contain information about the task log which can enable you read logs to the <add> end. <add> """ <add> <add> logs, metadatas = self.log_handler.read(ti, try_number, metadata=metadata) <add> metadata = metadatas[0] <add> return logs, metadata <add> <add> def read_log_stream(self, ti: TaskInstance, try_number: Optional[int], <add> metadata: dict) -> Iterator[str]: <add> """ <add> Used to continuously read log to the end <add> <add> :param ti: The Task Instance <add> :type ti: TaskInstance <add> :param try_number: the task try number <add> :type try_number: Optional[int] <add> :param metadata: A dictionary containing information about how to read the task log <add> :type metadata: dict <add> :rtype: Iterator[str] <add> """ <add> <add> if try_number is None: <add> next_try = ti.next_try_number <add> try_numbers = list(range(1, next_try)) <add> else: <add> try_numbers = [try_number] <add> for current_try_number in try_numbers: <add> metadata.pop('end_of_log', None) <add> metadata.pop('max_offset', None) <add> metadata.pop('offset', None) <add> while 'end_of_log' not in metadata or not metadata['end_of_log']: <add> logs, metadata = self.read_log_chunks(ti, current_try_number, metadata) <add> yield "\n".join(logs) + "\n" <add> <add> @cached_property <add> def log_handler(self): <add> """Log handler, which is configured to read logs.""" <add> <add> logger = logging.getLogger('airflow.task') <add> task_log_reader = conf.get('logging', 'task_log_reader') <add> handler = next((handler for handler in logger.handlers if handler.name == task_log_reader), None) <add> return handler <add> <add> @property <add> def is_supported(self): <add> """Checks if a read operation is supported by a current log handler.""" <add> <add> return hasattr(self.log_handler, 'read') <add> <add> def render_log_filename(self, ti: TaskInstance, try_number: Optional[int] = None): <add> """ <add> Renders the log attachment filename <add> <add> :param ti: The task instance <add> :type ti: TaskInstance <add> :param try_number: The task try number <add> :type try_number: Optional[int] <add> :rtype: str <add> """ <add> <add> filename_template = conf.get('logging', 'LOG_FILENAME_TEMPLATE') <add> attachment_filename = render_log_filename( <add> ti=ti, <add> try_number="all" if try_number is None else try_number, <add> filename_template=filename_template) <add> return attachment_filename <ide><path>airflow/www/views.py <ide> from airflow.ti_deps.dependencies_deps import RUNNING_DEPS, SCHEDULER_QUEUED_DEPS <ide> from airflow.utils import timezone <ide> from airflow.utils.dates import infer_time_unit, scale_time_units <del>from airflow.utils.helpers import alchemy_to_dict, render_log_filename <add>from airflow.utils.helpers import alchemy_to_dict <add>from airflow.utils.log.log_reader import TaskLogReader <ide> from airflow.utils.platform import get_airflow_git_version <ide> from airflow.utils.session import create_session, provide_session <ide> from airflow.utils.state import State <ide> def get_logs_with_metadata(self, session=None): <ide> dag_id = request.args.get('dag_id') <ide> task_id = request.args.get('task_id') <ide> execution_date = request.args.get('execution_date') <del> dttm = timezone.parse(execution_date) <ide> if request.args.get('try_number') is not None: <ide> try_number = int(request.args.get('try_number')) <ide> else: <ide> def get_logs_with_metadata(self, session=None): <ide> <ide> return response <ide> <del> logger = logging.getLogger('airflow.task') <del> task_log_reader = conf.get('logging', 'task_log_reader') <del> handler = next((handler for handler in logger.handlers <del> if handler.name == task_log_reader), None) <add> task_log_reader = TaskLogReader() <add> if not task_log_reader.is_supported: <add> return jsonify( <add> message="Task log handler does not support read logs.", <add> error=True, <add> metadata={ <add> "end_of_log": True <add> } <add> ) <ide> <ide> ti = session.query(models.TaskInstance).filter( <ide> models.TaskInstance.dag_id == dag_id, <ide> models.TaskInstance.task_id == task_id, <del> models.TaskInstance.execution_date == dttm).first() <del> <del> def _get_logs_with_metadata(try_number, metadata): <del> if ti is None: <del> logs = ["*** Task instance did not exist in the DB\n"] <del> metadata['end_of_log'] = True <del> else: <del> logs, metadatas = handler.read(ti, try_number, metadata=metadata) <del> metadata = metadatas[0] <del> return logs, metadata <add> models.TaskInstance.execution_date == execution_date).first() <add> <add> if ti is None: <add> return jsonify( <add> message="*** Task instance did not exist in the DB\n", <add> error=True, <add> metadata={ <add> "end_of_log": True <add> } <add> ) <ide> <ide> try: <del> if ti is not None: <del> dag = current_app.dag_bag.get_dag(dag_id) <del> if dag: <del> ti.task = dag.get_task(ti.task_id) <add> dag = current_app.dag_bag.get_dag(dag_id) <add> if dag: <add> ti.task = dag.get_task(ti.task_id) <add> <ide> if response_format == 'json': <del> logs, metadata = _get_logs_with_metadata(try_number, metadata) <add> logs, metadata = task_log_reader.read_log_chunks(ti, try_number, metadata) <ide> message = logs[0] if try_number is not None else logs <ide> return jsonify(message=message, metadata=metadata) <ide> <del> filename_template = conf.get('logging', 'LOG_FILENAME_TEMPLATE') <del> attachment_filename = render_log_filename( <del> ti=ti, <del> try_number="all" if try_number is None else try_number, <del> filename_template=filename_template) <ide> metadata['download_logs'] = True <del> <del> def _generate_log_stream(try_number, metadata): <del> if try_number is None and ti is not None: <del> next_try = ti.next_try_number <del> try_numbers = list(range(1, next_try)) <del> else: <del> try_numbers = [try_number] <del> for try_number in try_numbers: <del> metadata.pop('end_of_log', None) <del> metadata.pop('max_offset', None) <del> metadata.pop('offset', None) <del> while 'end_of_log' not in metadata or not metadata['end_of_log']: <del> logs, metadata = _get_logs_with_metadata(try_number, metadata) <del> yield "\n".join(logs) + "\n" <del> return Response(_generate_log_stream(try_number, metadata), <del> mimetype="text/plain", <del> headers={"Content-Disposition": "attachment; filename={}".format( <del> attachment_filename)}) <add> attachment_filename = task_log_reader.render_log_filename(ti, try_number) <add> log_stream = task_log_reader.read_log_stream(ti, try_number, metadata) <add> return Response( <add> response=log_stream, <add> mimetype="text/plain", <add> headers={ <add> "Content-Disposition": f"attachment; filename={attachment_filename}" <add> }) <ide> except AttributeError as e: <del> error_message = ["Task log handler {} does not support read logs.\n{}\n" <del> .format(task_log_reader, str(e))] <add> error_message = [ <add> f"Task log handler does not support read logs.\n{str(e)}\n" <add> ] <ide> metadata['end_of_log'] = True <ide> return jsonify(message=error_message, error=True, metadata=metadata) <ide> <ide><path>tests/utils/log/test_log_reader.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>import copy <add>import logging <add>import os <add>import shutil <add>import sys <add>import tempfile <add>import unittest <add>from unittest import mock <add> <add>from airflow import DAG, settings <add>from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG <add>from airflow.models import TaskInstance <add>from airflow.operators.dummy_operator import DummyOperator <add>from airflow.utils import timezone <add>from airflow.utils.log.log_reader import TaskLogReader <add>from airflow.utils.session import create_session <add>from tests.test_utils.config import conf_vars <add>from tests.test_utils.db import clear_db_runs <add> <add> <add>class TestLogView(unittest.TestCase): <add> DAG_ID = "dag_log_reader" <add> TASK_ID = "task_log_reader" <add> DEFAULT_DATE = timezone.datetime(2017, 9, 1) <add> <add> def setUp(self): <add> self.maxDiff = None # pylint: disable=invalid-name <add> <add> # Make sure that the configure_logging is not cached <add> self.old_modules = dict(sys.modules) <add> <add> self.settings_folder = tempfile.mkdtemp() <add> self.log_dir = tempfile.mkdtemp() <add> <add> self._configure_loggers() <add> self._prepare_db() <add> self._prepare_log_files() <add> <add> def _prepare_log_files(self): <add> dir_path = f"{self.log_dir}/{self.DAG_ID}/{self.TASK_ID}/2017-09-01T00.00.00+00.00/" <add> os.makedirs(dir_path) <add> for try_number in range(1, 4): <add> with open(f"{dir_path}/{try_number}.log", "w+") as file: <add> file.write(f"try_number={try_number}.\n") <add> file.flush() <add> <add> def _prepare_db(self): <add> dag = DAG(self.DAG_ID, start_date=self.DEFAULT_DATE) <add> dag.sync_to_db() <add> with create_session() as session: <add> op = DummyOperator(task_id=self.TASK_ID, dag=dag) <add> self.ti = TaskInstance(task=op, execution_date=self.DEFAULT_DATE) <add> self.ti.try_number = 3 <add> <add> session.merge(self.ti) <add> <add> def _configure_loggers(self): <add> logging_config = copy.deepcopy(DEFAULT_LOGGING_CONFIG) <add> logging_config["handlers"]["task"]["base_log_folder"] = self.log_dir <add> logging_config["handlers"]["task"][ <add> "filename_template" <add> ] = "{{ ti.dag_id }}/{{ ti.task_id }}/{{ ts | replace(':', '.') }}/{{ try_number }}.log" <add> settings_file = os.path.join(self.settings_folder, "airflow_local_settings.py") <add> with open(settings_file, "w") as handle: <add> new_logging_file = "LOGGING_CONFIG = {}".format(logging_config) <add> handle.writelines(new_logging_file) <add> sys.path.append(self.settings_folder) <add> with conf_vars({("logging", "logging_config_class"): "airflow_local_settings.LOGGING_CONFIG"}): <add> settings.configure_logging() <add> <add> def tearDown(self): <add> logging.config.dictConfig(DEFAULT_LOGGING_CONFIG) <add> clear_db_runs() <add> <add> # Remove any new modules imported during the test run. This lets us <add> # import the same source files for more than one test. <add> for mod in [m for m in sys.modules if m not in self.old_modules]: <add> del sys.modules[mod] <add> <add> sys.path.remove(self.settings_folder) <add> shutil.rmtree(self.settings_folder) <add> shutil.rmtree(self.log_dir) <add> super().tearDown() <add> <add> def test_test_read_log_chunks_should_read_one_try(self): <add> task_log_reader = TaskLogReader() <add> logs, metadatas = task_log_reader.read_log_chunks(ti=self.ti, try_number=1, metadata={}) <add> <add> self.assertEqual( <add> [ <add> f"*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/1.log\n" <add> f"try_number=1.\n" <add> ], <add> logs, <add> ) <add> self.assertEqual({"end_of_log": True}, metadatas) <add> <add> def test_test_read_log_chunks_should_read_all_files(self): <add> task_log_reader = TaskLogReader() <add> logs, metadatas = task_log_reader.read_log_chunks(ti=self.ti, try_number=None, metadata={}) <add> <add> self.assertEqual( <add> [ <add> "*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/1.log\n" <add> "try_number=1.\n", <add> f"*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/2.log\n" <add> f"try_number=2.\n", <add> f"*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/3.log\n" <add> f"try_number=3.\n", <add> ], <add> logs, <add> ) <add> self.assertEqual({"end_of_log": True}, metadatas) <add> <add> def test_test_test_read_log_stream_should_read_one_try(self): <add> task_log_reader = TaskLogReader() <add> stream = task_log_reader.read_log_stream(ti=self.ti, try_number=1, metadata={}) <add> <add> self.assertEqual( <add> [ <add> "*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/1.log\n" <add> "try_number=1.\n" <add> "\n" <add> ], <add> list(stream), <add> ) <add> <add> def test_test_test_read_log_stream_should_read_all_logs(self): <add> task_log_reader = TaskLogReader() <add> stream = task_log_reader.read_log_stream(ti=self.ti, try_number=None, metadata={}) <add> self.assertEqual( <add> [ <add> "*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/1.log\n" <add> "try_number=1.\n" <add> "\n", <add> "*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/2.log\n" <add> "try_number=2.\n" <add> "\n", <add> "*** Reading local file: " <add> f"{self.log_dir}/dag_log_reader/task_log_reader/2017-09-01T00.00.00+00.00/3.log\n" <add> "try_number=3.\n" <add> "\n", <add> ], <add> list(stream), <add> ) <add> <add> @mock.patch("airflow.utils.log.file_task_handler.FileTaskHandler.read") <add> def test_read_log_stream_should_support_multiple_chunks(self, mock_read): <add> first_return = (["1st line"], [{}]) <add> second_return = (["2nd line"], [{"end_of_log": False}]) <add> third_return = (["3rd line"], [{"end_of_log": True}]) <add> fourth_return = (["should never be read"], [{"end_of_log": True}]) <add> mock_read.side_effect = [first_return, second_return, third_return, fourth_return] <add> <add> task_log_reader = TaskLogReader() <add> log_stream = task_log_reader.read_log_stream(ti=self.ti, try_number=1, metadata={}) <add> self.assertEqual(["1st line\n", "2nd line\n", "3rd line\n"], list(log_stream)) <add> <add> mock_read.assert_has_calls( <add> [ <add> mock.call(self.ti, 1, metadata={}), <add> mock.call(self.ti, 1, metadata={}), <add> mock.call(self.ti, 1, metadata={"end_of_log": False}), <add> ], <add> any_order=False, <add> ) <add> <add> @mock.patch("airflow.utils.log.file_task_handler.FileTaskHandler.read") <add> def test_read_log_stream_should_read_each_try_in_turn(self, mock_read): <add> first_return = (["try_number=1."], [{"end_of_log": True}]) <add> second_return = (["try_number=2."], [{"end_of_log": True}]) <add> third_return = (["try_number=3."], [{"end_of_log": True}]) <add> fourth_return = (["should never be read"], [{"end_of_log": True}]) <add> mock_read.side_effect = [first_return, second_return, third_return, fourth_return] <add> <add> task_log_reader = TaskLogReader() <add> log_stream = task_log_reader.read_log_stream(ti=self.ti, try_number=None, metadata={}) <add> self.assertEqual(['try_number=1.\n', 'try_number=2.\n', 'try_number=3.\n'], list(log_stream)) <add> <add> mock_read.assert_has_calls( <add> [ <add> mock.call(self.ti, 1, metadata={}), <add> mock.call(self.ti, 2, metadata={}), <add> mock.call(self.ti, 3, metadata={}), <add> ], <add> any_order=False, <add> ) <ide><path>tests/www/test_views.py <ide> from datetime import datetime as dt, timedelta, timezone as tz <ide> from typing import Any, Dict, Generator, List, NamedTuple <ide> from unittest import mock <add>from unittest.mock import PropertyMock <ide> from urllib.parse import quote_plus <ide> <ide> import jinja2 <ide> def test_get_logs_with_metadata_for_removed_dag(self, mock_read): <ide> self.assertIn('airflow log line', response.data.decode('utf-8')) <ide> self.assertEqual(200, response.status_code) <ide> <add> def test_get_logs_response_with_ti_equal_to_none(self): <add> url_template = "get_logs_with_metadata?dag_id={}&" \ <add> "task_id={}&execution_date={}&" \ <add> "try_number={}&metadata={}&format=file" <add> try_number = 1 <add> url = url_template.format(self.DAG_ID, <add> 'Non_Existing_ID', <add> quote_plus(self.DEFAULT_DATE.isoformat()), <add> try_number, <add> json.dumps({})) <add> response = self.client.get(url) <add> self.assertIn('message', response.json) <add> self.assertIn('error', response.json) <add> self.assertEqual("*** Task instance did not exist in the DB\n", <add> response.json['message']) <add> <add> def test_get_logs_with_json_response_format(self): <add> url_template = "get_logs_with_metadata?dag_id={}&" \ <add> "task_id={}&execution_date={}&" \ <add> "try_number={}&metadata={}&format=json" <add> try_number = 1 <add> url = url_template.format(self.DAG_ID, <add> self.TASK_ID, <add> quote_plus(self.DEFAULT_DATE.isoformat()), <add> try_number, <add> json.dumps({})) <add> response = self.client.get(url) <add> self.assertIn('message', response.json) <add> self.assertIn('metadata', response.json) <add> self.assertIn('Log for testing.', response.json['message']) <add> self.assertEqual(200, response.status_code) <add> <add> @mock.patch("airflow.www.views.TaskLogReader") <add> def test_get_logs_for_handler_without_read_method(self, mock_log_reader): <add> type(mock_log_reader.return_value).is_supported = PropertyMock(return_value=False) <add> <add> url_template = "get_logs_with_metadata?dag_id={}&" \ <add> "task_id={}&execution_date={}&" \ <add> "try_number={}&metadata={}&format=json" <add> try_number = 1 <add> url = url_template.format(self.DAG_ID, <add> self.TASK_ID, <add> quote_plus(self.DEFAULT_DATE.isoformat()), <add> try_number, <add> json.dumps({})) <add> response = self.client.get(url) <add> self.assertEqual(200, response.status_code) <add> self.assertIn('message', response.json) <add> self.assertIn('metadata', response.json) <add> self.assertIn( <add> 'Task log handler does not support read logs.', <add> response.json['message']) <add> <ide> <ide> class TestVersionView(TestBase): <ide> def test_version(self):
4
PHP
PHP
update doc block and remove inline assignment
a098ff28b8664a1c4c25445ac4a81e6660969903
<ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php <ide> public function value($data, $column = null) { <ide> * @param Model $model <ide> * @param array $queryData <ide> * @param integer $recursive <del> * @return array Array of resultset rows, or false if no rows matched <add> * @return array|false Array of resultset rows, or false if no rows matched <ide> */ <ide> public function read(Model $model, $queryData = array(), $recursive = null) { <ide> $results = parent::read($model, $queryData, $recursive); <ide><path>lib/Cake/Model/Datasource/DboSource.php <ide> public function fetchAll($sql, $params = array(), $options = array()) { <ide> if ($cache && ($cached = $this->getQueryCache($sql, $params)) !== false) { <ide> return $cached; <ide> } <del> if ($result = $this->execute($sql, array(), $params)) { <add> $result = $this->execute($sql, array(), $params); <add> if ($result) { <ide> $out = array(); <ide> <ide> if ($this->hasResult()) {
2
Javascript
Javascript
fix stragglers that were not qunit 2 compatible
2b80a62e2893c2c937213f8fce419d647baff7c4
<ide><path>packages/ember-debug/tests/main_test.js <ide> import { <ide> <ide> let originalEnvValue; <ide> let originalDeprecateHandler; <add>let originalWarnHandler; <ide> let originalWarnOptions; <ide> let originalDeprecationOptions; <ide> <ide> moduleFor('ember-debug', class extends TestCase { <ide> <ide> originalEnvValue = ENV.RAISE_ON_DEPRECATION; <ide> originalDeprecateHandler = HANDLERS.deprecate; <add> originalWarnHandler = HANDLERS.warn; <ide> originalWarnOptions = ENV._ENABLE_WARN_OPTIONS_SUPPORT; <ide> originalDeprecationOptions = ENV._ENABLE_DEPRECATION_OPTIONS_SUPPORT; <ide> <ide> moduleFor('ember-debug', class extends TestCase { <ide> <ide> teardown() { <ide> HANDLERS.deprecate = originalDeprecateHandler; <add> HANDLERS.warn = originalWarnHandler; <ide> <ide> ENV.RAISE_ON_DEPRECATION = originalEnvValue; <ide> ENV._ENABLE_WARN_OPTIONS_SUPPORT = originalWarnOptions; <ide> ENV._ENABLE_DEPRECATION_OPTIONS_SUPPORT = originalDeprecationOptions; <ide> } <add> <ide> ['@test Ember.deprecate does not throw if RAISE_ON_DEPRECATION is false'](assert) { <ide> assert.expect(1); <ide> <ide><path>packages/ember-runtime/tests/mixins/promise_proxy_test.js <ide> QUnit.test('should reset isFulfilled and isRejected when promise is reset', func <ide> assert.equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled'); <ide> }); <ide> <del>QUnit.test('should have content when isFulfilled is set', function() { <add>QUnit.test('should have content when isFulfilled is set', function(assert) { <ide> let deferred = EmberRSVP.defer(); <ide> <ide> let proxy = ObjectPromiseProxy.create({ <ide> promise: deferred.promise <ide> }); <ide> <del> proxy.addObserver('isFulfilled', () => equal(get(proxy, 'content'), true)); <add> proxy.addObserver('isFulfilled', () => assert.equal(get(proxy, 'content'), true)); <ide> <ide> run(deferred, 'resolve', true); <ide> }); <ide> QUnit.test('should have reason when isRejected is set', function(assert) { <ide> promise: deferred.promise <ide> }); <ide> <del> proxy.addObserver('isRejected', () => equal(get(proxy, 'reason'), error)); <add> proxy.addObserver('isRejected', () => assert.equal(get(proxy, 'reason'), error)); <ide> <ide> try { <ide> run(deferred, 'reject', error); <ide><path>packages/ember/tests/routing/basic_test.js <ide> QUnit.test('rejecting the model hooks promise with a string shows a good error', <ide> } <ide> }); <ide> <del> assert.throws(() => bootApplication(), rejectedMessage, 'expected an exception'); <add> assert.throws(() => bootApplication(), new RegExp(rejectedMessage), 'expected an exception'); <ide> <ide> Logger.error = originalLoggerError; <ide> }); <ide><path>packages/internal-test-helpers/lib/ember-dev/assertion.js <ide> AssertionAssert.prototype = { <ide> let { assert } = QUnit.config.current; <ide> <ide> if (this.env.runningProdBuild) { <del> QUnit.ok(true, 'Assertions disabled in production builds.'); <add> assert.ok(true, 'Assertions disabled in production builds.'); <ide> return; <ide> } <ide>
4
Mixed
Go
add support for comment in .dockerignore
8913dace341c8fc9f9a3ab9518c8521c161b307f
<ide><path>builder/dockerignore/dockerignore.go <ide> func ReadAll(reader io.ReadCloser) ([]string, error) { <ide> var excludes []string <ide> <ide> for scanner.Scan() { <del> pattern := strings.TrimSpace(scanner.Text()) <add> // Lines starting with # (comments) are ignored before processing <add> pattern := scanner.Text() <add> if strings.HasPrefix(pattern, "#") { <add> continue <add> } <add> pattern = strings.TrimSpace(pattern) <ide> if pattern == "" { <ide> continue <ide> } <ide><path>docs/reference/builder.md <ide> the working and the root directory. For example, the patterns <ide> in the `foo` subdirectory of `PATH` or in the root of the git <ide> repository located at `URL`. Neither excludes anything else. <ide> <add>If a line in `.dockerignore` file starts with `#` in column 1, then this line is <add>considered as a comment and is ignored before interpreted by the CLI. <add> <ide> Here is an example `.dockerignore` file: <ide> <ide> ``` <add># comment <ide> */temp* <ide> */*/temp* <ide> temp? <ide> This file causes the following build behavior: <ide> <ide> | Rule | Behavior | <ide> |----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| <add>| `# comment` | Ignored. | <ide> | `*/temp*` | Exclude files and directories whose names start with `temp` in any immediate subdirectory of the root. For example, the plain file `/somedir/temporary.txt` is excluded, as is the directory `/somedir/temp`. | <ide> | `*/*/temp*` | Exclude files and directories starting with `temp` from any subdirectory that is two levels below the root. For example, `/somedir/subdir/temporary.txt` is excluded. | <ide> | `temp?` | Exclude files and directories in the root directory whose names are a one-character extension of `temp`. For example, `/tempa` and `/tempb` are excluded. <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildDeleteCommittedFile(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> } <add> <add>// #20083 <add>func (s *DockerSuite) TestBuildDockerignoreComment(c *check.C) { <add> name := "testbuilddockerignorecleanpaths" <add> dockerfile := ` <add> FROM busybox <add> ADD . /tmp/ <add> RUN sh -c "(ls -la /tmp/#1)" <add> RUN sh -c "(! ls -la /tmp/#2)" <add> RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"` <add> ctx, err := fakeContext(dockerfile, map[string]string{ <add> "foo": "foo", <add> "foo2": "foo2", <add> "dir1/foo": "foo in dir1", <add> "#1": "# file 1", <add> "#2": "# file 2", <add> ".dockerignore": `# Visual C++ cache files <add># because we have git ;-) <add># The above comment is from #20083 <add>foo <add>#dir1/foo <add>foo2 <add># The following is considered as comment as # is at the beginning <add>#1 <add># The following is not considered as comment as # is not at the beginning <add> #2 <add>`, <add> }) <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer ctx.Close() <add> if _, err := buildImageFromContext(name, ctx, true); err != nil { <add> c.Fatal(err) <add> } <add>}
3
PHP
PHP
extract method for if check
8a3726385171855986a6f9e1e30b09d796dfea3c
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateImage($attribute, $value) <ide> */ <ide> protected function validateMimes($attribute, $value, $parameters) <ide> { <del> if ( ! $value instanceof File || ($value instanceof UploadedFile && ! $value->isValid())) <add> if ( ! $this->isAValidFileInstance($value)) <ide> { <ide> return false; <ide> } <ide> <del> // The Symfony File class should do a decent job of guessing the extension <del> // based on the true MIME type so we'll just loop through the array of <del> // extensions and compare it to the guessed extension of the files. <ide> return $value->getPath() != '' && in_array($value->guessExtension(), $parameters); <ide> } <ide> <add> /** <add> * Check that the given value is a valid file instnace. <add> * <add> * @param mixed $value <add> * @return bool <add> */ <add> protected function isAValidFileInstance($value) <add> { <add> if ($value instanceof UploadedFile && ! $value->isValid()) return false; <add> <add> return $value instanceof File; <add> } <add> <ide> /** <ide> * Validate that an attribute contains only alphabetic characters. <ide> *
1
Text
Text
make caveat in stream.md more concise
003e5b3404db3acb6f9e8e8e3f1ee6278855d586
<ide><path>doc/api/stream.md <ide> The `stream` module can be accessed using: <ide> const stream = require('stream'); <ide> ``` <ide> <del>While it is important for all Node.js users to understand how streams work, <del>the `stream` module itself is most useful for developers that are creating new <del>types of stream instances. Developers who are primarily *consuming* stream <del>objects will rarely (if ever) have need to use the `stream` module directly. <add>While it is important to understand how streams work, the `stream` module itself <add>is most useful for developers that are creating new types of stream instances. <add>Developers who are primarily *consuming* stream objects will rarely need to use <add>the `stream` module directly. <ide> <ide> ## Organization of this Document <ide>
1
Javascript
Javascript
improve flow types
da0b139b56123bc1bb9d41399cefe8a33a820a82
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> const warning = require('fbjs/lib/warning'); <ide> import type {TextStyleProp, ViewStyleProp} from 'StyleSheet'; <ide> import type {ColorValue} from 'StyleSheetTypes'; <ide> import type {ViewProps} from 'ViewPropTypes'; <del>import type {SyntheticEvent} from 'CoreEventTypes'; <add>import type {SyntheticEvent, ScrollEvent} from 'CoreEventTypes'; <ide> import type {PressEvent} from 'CoreEventTypes'; <ide> <ide> let AndroidTextInput; <ide> const onlyMultiline = { <ide> children: true, <ide> }; <ide> <del>type Range = $ReadOnly<{| <del> start: number, <del> end: number, <del>|}>; <del>type Selection = $ReadOnly<{| <del> start: number, <del> end?: number, <del>|}>; <del>type ContentSize = $ReadOnly<{| <del> width: number, <del> height: number, <del>|}>; <del>type ContentOffset = $ReadOnly<{| <del> x: number, <del> y: number, <del>|}>; <del>type ChangeEvent = SyntheticEvent< <add>export type ChangeEvent = SyntheticEvent< <ide> $ReadOnly<{| <del> target: number, <ide> eventCount: number, <add> target: number, <ide> text: string, <ide> |}>, <ide> >; <del>type TextInputEvent = SyntheticEvent< <add> <add>export type TextInputEvent = SyntheticEvent< <ide> $ReadOnly<{| <add> eventCount: number, <ide> previousText: string, <del> range: Range, <add> range: $ReadOnly<{| <add> start: number, <add> end: number, <add> |}>, <ide> target: number, <ide> text: string, <ide> |}>, <ide> >; <del>type ContentSizeChangeEvent = SyntheticEvent< <del> $ReadOnly<{| <del> target: number, <del> contentSize: ContentSize, <del> |}>, <del>>; <del>type ScrollEvent = SyntheticEvent< <add> <add>export type ContentSizeChangeEvent = SyntheticEvent< <ide> $ReadOnly<{| <ide> target: number, <del> contentOffset: ContentOffset, <add> contentSize: $ReadOnly<{| <add> width: number, <add> height: number, <add> |}>, <ide> |}>, <ide> >; <add> <ide> type TargetEvent = SyntheticEvent< <ide> $ReadOnly<{| <ide> target: number, <ide> |}>, <ide> >; <del>type SelectionChangeEvent = SyntheticEvent< <add> <add>export type BlurEvent = TargetEvent; <add>export type FocusEvent = TargetEvent; <add> <add>type Selection = $ReadOnly<{| <add> start: number, <add> end: number, <add>|}>; <add> <add>export type SelectionChangeEvent = SyntheticEvent< <ide> $ReadOnly<{| <ide> selection: Selection, <add> target: number, <ide> |}>, <ide> >; <del>type KeyPressEvent = SyntheticEvent< <add> <add>export type KeyPressEvent = SyntheticEvent< <ide> $ReadOnly<{| <ide> key: string, <add> target?: ?number, <add> eventCount?: ?number, <ide> |}>, <ide> >; <del>type EditingEvent = SyntheticEvent< <add> <add>export type EditingEvent = SyntheticEvent< <ide> $ReadOnly<{| <add> eventCount: number, <ide> text: string, <ide> target: number, <ide> |}>, <ide> type Props = $ReadOnly<{| <ide> returnKeyType?: ?ReturnKeyType, <ide> maxLength?: ?number, <ide> multiline?: ?boolean, <del> onBlur?: ?(e: TargetEvent) => void, <del> onFocus?: ?(e: TargetEvent) => void, <add> onBlur?: ?(e: BlurEvent) => void, <add> onFocus?: ?(e: FocusEvent) => void, <ide> onChange?: ?(e: ChangeEvent) => void, <ide> onChangeText?: ?(text: string) => void, <ide> onContentSizeChange?: ?(e: ContentSizeChangeEvent) => void, <ide> const TextInput = createReactClass({ <ide> ); <ide> }, <ide> <del> _onFocus: function(event: TargetEvent) { <add> _onFocus: function(event: FocusEvent) { <ide> if (this.props.onFocus) { <ide> this.props.onFocus(event); <ide> } <ide> const TextInput = createReactClass({ <ide> } <ide> }, <ide> <del> _onBlur: function(event: TargetEvent) { <add> _onBlur: function(event: BlurEvent) { <ide> if (this.props.onBlur) { <ide> this.props.onBlur(event); <ide> }
1
Text
Text
move gireeshpunathil to tsc emeritus
4c746a6cfda980c1cd0de6246781c0083d9e416c
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Franziska Hinkelmann** &lt;franziska.hinkelmann@gmail.com&gt; (she/her) <ide> * [gabrielschulhof](https://github.com/gabrielschulhof) - <ide> **Gabriel Schulhof** &lt;gabriel.schulhof@intel.com&gt; <del>* [gireeshpunathil](https://github.com/gireeshpunathil) - <del>**Gireesh Punathil** &lt;gpunathi@in.ibm.com&gt; (he/him) <ide> * [jasnell](https://github.com/jasnell) - <ide> **James M Snell** &lt;jasnell@gmail.com&gt; (he/him) <ide> * [joyeecheung](https://github.com/joyeecheung) - <ide> For information about the governance of the Node.js project, see <ide> **Jeremiah Senkpiel** &lt;fishrock123@rocketmail.com&gt; (he/they) <ide> * [gibfahn](https://github.com/gibfahn) - <ide> **Gibson Fahnestock** &lt;gibfahn@gmail.com&gt; (he/him) <add>* [gireeshpunathil](https://github.com/gireeshpunathil) - <add>**Gireesh Punathil** &lt;gpunathi@in.ibm.com&gt; (he/him) <ide> * [indutny](https://github.com/indutny) - <ide> **Fedor Indutny** &lt;fedor.indutny@gmail.com&gt; <ide> * [isaacs](https://github.com/isaacs) -
1
Javascript
Javascript
add segmentedcontrolios documentation to website
1c05aff424be56206daac12a540c7b925b7a76ce
<ide><path>website/server/extractDocs.js <ide> var components = [ <ide> '../Libraries/Components/Navigation/NavigatorIOS.ios.js', <ide> '../Libraries/Picker/PickerIOS.ios.js', <ide> '../Libraries/Components/ScrollView/ScrollView.js', <add> '../Libraries/Components/SegmentedControlIOS/SegmentedControlIOS.ios.js', <ide> '../Libraries/Components/SliderIOS/SliderIOS.js', <ide> '../Libraries/Components/SwitchIOS/SwitchIOS.ios.js', <ide> '../Libraries/Components/TabBarIOS/TabBarIOS.ios.js',
1
Ruby
Ruby
expose `mailbox_for` method
9f96d094a39100df53ea68b8bd6fa7fcafd96eac
<ide><path>actionmailbox/lib/action_mailbox/router.rb <ide> def add_route(address, to:) <ide> end <ide> <ide> def route(inbound_email) <del> if mailbox = match_to_mailbox(inbound_email) <add> if mailbox = mailbox_for(inbound_email) <ide> mailbox.receive(inbound_email) <ide> else <ide> inbound_email.bounced! <ide> def route(inbound_email) <ide> end <ide> end <ide> <add> def mailbox_for(inbound_email) <add> routes.detect { |route| route.match?(inbound_email) }.try(:mailbox_class) <add> end <add> <ide> private <ide> attr_reader :routes <del> <del> def match_to_mailbox(inbound_email) <del> routes.detect { |route| route.match?(inbound_email) }.try(:mailbox_class) <del> end <ide> end <ide> end <ide> <ide><path>actionmailbox/lib/action_mailbox/routing.rb <ide> def routing(routes) <ide> def route(inbound_email) <ide> router.route(inbound_email) <ide> end <add> <add> def mailbox_for(inbound_email) <add> router.route(inbound_email) <add> end <ide> end <ide> end <ide> end <ide><path>actionmailbox/test/unit/mailbox/routing_test.rb <ide> class ActionMailbox::Base::RoutingTest < ActiveSupport::TestCase <ide> assert_equal "Discussion: Let's debate these attachments", $processed <ide> end <ide> end <add> <add> test "mailbox_for" do <add> mail = create_inbound_email_from_fixture "welcome.eml", status: :pending <add> assert_equal RepliesMailbox, ApplicationMailbox.mailbox_for(mail) <add> end <ide> end <ide><path>actionmailbox/test/unit/router_test.rb <ide> class RouterTest < ActiveSupport::TestCase <ide> @router.add_route Array.new, to: :first <ide> end <ide> end <add> <add> test "single string mailbox_for" do <add> @router.add_routes("first@example.com" => :first) <add> <add> inbound_email = create_inbound_email_from_mail(to: "first@example.com", subject: "This is a reply") <add> assert_equal FirstMailbox, @router.mailbox_for(inbound_email) <add> end <add> <add> test "mailbox_for with no matches" do <add> @router.add_routes("first@example.com" => :first) <add> <add> inbound_email = create_inbound_email_from_mail(to: "second@example.com", subject: "This is a reply") <add> assert_nil @router.mailbox_for(inbound_email) <add> end <ide> end <ide> end
4
Javascript
Javascript
remove forced optimization from misc
7587a11adc5013721aae3e0bedb7fbd51e1ced5b
<ide><path>benchmark/misc/console.js <ide> const common = require('../common.js'); <ide> const assert = require('assert'); <ide> const Writable = require('stream').Writable; <ide> const util = require('util'); <del>const v8 = require('v8'); <del> <del>v8.setFlagsFromString('--allow_natives_syntax'); <ide> <ide> const methods = [ <ide> 'restAndSpread', <ide> function usingArgumentsAndApplyC() { <ide> nullStream.write(util.format.apply(null, arguments) + '\n'); <ide> } <ide> <del>function optimize(method, ...args) { <del> method(...args); <del> eval(`%OptimizeFunctionOnNextCall(${method.name})`); <del> method(...args); <del>} <del> <ide> function runUsingRestAndConcat(n) { <del> optimize(usingRestAndConcat, 'a', 1); <ide> <ide> var i = 0; <ide> bench.start(); <ide> function runUsingRestAndConcat(n) { <ide> function runUsingRestAndSpread(n, concat) { <ide> <ide> const method = concat ? usingRestAndSpreadC : usingRestAndSpreadTS; <del> optimize(method, 'this is %s of %d', 'a', 1); <ide> <ide> var i = 0; <ide> bench.start(); <ide> function runUsingRestAndSpread(n, concat) { <ide> function runUsingRestAndApply(n, concat) { <ide> <ide> const method = concat ? usingRestAndApplyC : usingRestAndApplyTS; <del> optimize(method, 'this is %s of %d', 'a', 1); <ide> <ide> var i = 0; <ide> bench.start(); <ide> function runUsingRestAndApply(n, concat) { <ide> function runUsingArgumentsAndApply(n, concat) { <ide> <ide> const method = concat ? usingArgumentsAndApplyC : usingArgumentsAndApplyTS; <del> optimize(method, 'this is %s of %d', 'a', 1); <ide> <ide> var i = 0; <ide> bench.start(); <ide><path>benchmark/misc/punycode.js <ide> function usingICU(val) { <ide> } <ide> <ide> function runPunycode(n, val) { <del> common.v8ForceOptimization(usingPunycode, val); <ide> var i = 0; <add> for (; i < n; i++) <add> usingPunycode(val); <ide> bench.start(); <ide> for (; i < n; i++) <ide> usingPunycode(val); <ide> bench.end(n); <ide> } <ide> <ide> function runICU(n, val) { <del> common.v8ForceOptimization(usingICU, val); <ide> var i = 0; <ide> bench.start(); <ide> for (; i < n; i++) <ide><path>benchmark/misc/util-extend-vs-object-assign.js <ide> <ide> const common = require('../common.js'); <ide> const util = require('util'); <del>const v8 = require('v8'); <ide> <ide> const bench = common.createBenchmark(main, { <ide> type: ['extend', 'assign'], <ide> const bench = common.createBenchmark(main, { <ide> function main(conf) { <ide> let fn; <ide> const n = conf.n | 0; <del> let v8command; <ide> <ide> if (conf.type === 'extend') { <ide> fn = util._extend; <del> v8command = '%OptimizeFunctionOnNextCall(util._extend)'; <ide> } else if (conf.type === 'assign') { <ide> fn = Object.assign; <del> // Object.assign is built-in, cannot be optimized <del> v8command = ''; <ide> } <ide> <ide> // Force-optimize the method to test so that the benchmark doesn't <ide> // get disrupted by the optimizer kicking in halfway through. <ide> for (var i = 0; i < conf.type.length * 10; i += 1) <ide> fn({}, process.env); <ide> <del> v8.setFlagsFromString('--allow_natives_syntax'); <del> eval(v8command); <del> <ide> var obj = new Proxy({}, { set: function(a, b, c) { return true; } }); <ide> <ide> bench.start();
3
Ruby
Ruby
improve the error message
7b96fd008e332949b9d53ffe08e9de20dbff0e2d
<ide><path>Library/Homebrew/utils/fork.rb <ide> def self.safe_fork(&_block) <ide> Process.wait(pid) unless socket.nil? <ide> raise Marshal.load(data) unless data.nil? || data.empty? <ide> raise Interrupt if $CHILD_STATUS.exitstatus == 130 <del> raise "Suspicious failure" unless $CHILD_STATUS.success? <add> raise "Forked child process failed: #{$CHILD_STATUS}" unless $CHILD_STATUS.success? <ide> end <ide> end <ide> end
1
Python
Python
fix setup.py to work from a released tarball
87e12c1dfc90fae5d0a2576add0c1879df815740
<ide><path>pavement.py <ide> sys.path.insert(0, os.path.dirname(__file__)) <ide> try: <ide> setup_py = __import__("setup") <del> FULLVERSION = setup_py.FULLVERSION <add> FULLVERSION = setup_py.VERSION <add> # This is duplicated from setup.py <add> if os.path.exists('.git'): <add> GIT_REVISION = setup_py.git_version() <add> elif os.path.exists('numpy/version.py'): <add> # must be a source distribution, use existing version file <add> from numpy.version import git_revision as GIT_REVISION <add> else: <add> GIT_REVISION = "Unknown" <add> <add> if not setup_py.ISRELEASED: <add> FULLVERSION += '.dev-' + GIT_REVISION[:7] <ide> finally: <ide> sys.path.pop(0) <ide> <ide> def dmg(options): <ide> ref = os.path.join(options.doc.destdir_pdf, "reference.pdf") <ide> user = os.path.join(options.doc.destdir_pdf, "userguide.pdf") <ide> if (not os.path.exists(ref)) or (not os.path.exists(user)): <add> import warnings <ide> warnings.warn("Docs need to be built first! Can't find them.") <ide> <ide> # Build the mpkg package <ide><path>setup.py <ide> def _minimal_ext_cmd(cmd): <ide> # a lot more robust than what was previously being used. <ide> builtins.__NUMPY_SETUP__ = True <ide> <del># Construct full version info. Needs to be in setup.py namespace, otherwise it <del># can't be accessed from pavement.py at build time. <del>FULLVERSION = VERSION <del>if os.path.exists('.git'): <del> GIT_REVISION = git_version() <del>elif os.path.exists('numpy/version.py'): <del> # must be a source distribution, use existing version file <del> from numpy.version import git_revision as GIT_REVISION <del>else: <del> GIT_REVISION = "Unknown" <del> <del>if not ISRELEASED: <del> FULLVERSION += '.dev-' + GIT_REVISION[:7] <ide> <ide> def write_version_py(filename='numpy/version.py'): <ide> cnt = """ <ide> def write_version_py(filename='numpy/version.py'): <ide> if not release: <ide> version = full_version <ide> """ <add> # Adding the git rev number needs to be done inside write_version_py(), <add> # otherwise the import of numpy.version messes up the build under Python 3. <add> FULLVERSION = VERSION <add> if os.path.exists('.git'): <add> GIT_REVISION = git_version() <add> elif os.path.exists('numpy/version.py'): <add> # must be a source distribution, use existing version file <add> from numpy.version import git_revision as GIT_REVISION <add> else: <add> GIT_REVISION = "Unknown" <add> <add> if not ISRELEASED: <add> FULLVERSION += '.dev-' + GIT_REVISION[:7] <add> <ide> a = open(filename, 'w') <ide> try: <ide> a.write(cnt % {'version': VERSION,
2
Ruby
Ruby
offload more filtering to the search api
f7ef4964a72d3dfb8c631cafe83ba1e2a8a5dacc
<ide><path>Library/Homebrew/utils.rb <ide> def uri_escape(query) <ide> <ide> def issues_for_formula name <ide> # don't include issues that just refer to the tool in their body <del> issues_matching(name).select { |issue| issue["state"] == "open" } <add> issues_matching(name, :state => "open") <ide> end <ide> <ide> def find_pull_requests query <ide> return if ENV['HOMEBREW_NO_GITHUB_API'] <ide> puts "Searching pull requests..." <ide> <del> open_or_closed_prs = issues_matching(query).select do |issue| <del> issue["pull_request"]["html_url"] <del> end <add> open_or_closed_prs = issues_matching(query, :type => "pr") <ide> <ide> open_prs = open_or_closed_prs.select {|i| i["state"] == "open" } <ide> if open_prs.any?
1
Javascript
Javascript
add support for shadow dom
387a23df737fcf8d0faf8762b757b2a428c5a906
<ide><path>src/core/core.helpers.js <ide> module.exports = function() { <ide> // @see http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser <ide> function getConstraintDimension(domNode, maxStyle, percentageProperty) { <ide> var view = document.defaultView; <del> var parentNode = domNode.parentNode; <add> var parentNode = helpers._getParentNode(domNode); <ide> var constrainedNode = view.getComputedStyle(domNode)[maxStyle]; <ide> var constrainedContainer = view.getComputedStyle(parentNode)[maxStyle]; <ide> var hasCNode = isConstrainedValue(constrainedNode); <ide> module.exports = function() { <ide> <ide> return padding.indexOf('%') > -1 ? parentDimension / parseInt(padding, 10) : parseInt(padding, 10); <ide> }; <add> /** <add> * @private <add> */ <add> helpers._getParentNode = function(domNode) { <add> var parent = domNode.parentNode; <add> if (parent && parent.host) { <add> parent = parent.host; <add> } <add> return parent; <add> }; <ide> helpers.getMaximumWidth = function(domNode) { <del> var container = domNode.parentNode; <add> var container = helpers._getParentNode(domNode); <ide> if (!container) { <ide> return domNode.clientWidth; <ide> } <ide> module.exports = function() { <ide> return isNaN(cw) ? w : Math.min(w, cw); <ide> }; <ide> helpers.getMaximumHeight = function(domNode) { <del> var container = domNode.parentNode; <add> var container = helpers._getParentNode(domNode); <ide> if (!container) { <ide> return domNode.clientHeight; <ide> } <ide><path>test/specs/core.helpers.tests.js <ide> describe('Core helper tests', function() { <ide> document.body.removeChild(div); <ide> }); <ide> <add> it ('should get the maximum width and height for a node in a ShadowRoot', function() { <add> // Create div with fixed size as a test bed <add> var div = document.createElement('div'); <add> div.style.width = '200px'; <add> div.style.height = '300px'; <add> <add> document.body.appendChild(div); <add> <add> if (!div.attachShadow) { <add> // Shadow DOM is not natively supported <add> return; <add> } <add> <add> var shadow = div.attachShadow({mode: 'closed'}); <add> <add> // Create the div we want to get the max size for <add> var innerDiv = document.createElement('div'); <add> shadow.appendChild(innerDiv); <add> <add> expect(helpers.getMaximumWidth(innerDiv)).toBe(200); <add> expect(helpers.getMaximumHeight(innerDiv)).toBe(300); <add> <add> document.body.removeChild(div); <add> }); <add> <ide> it ('should get the maximum width of a node that has a max-width style', function() { <ide> // Create div with fixed size as a test bed <ide> var div = document.createElement('div');
2
Ruby
Ruby
update the documentation for engine and railtie
4bacc2a66d26b2e257718bb44c89583f79c138e8
<ide><path>railties/lib/rails/engine.rb <ide> module Rails <ide> # # lib/my_engine.rb <ide> # module MyEngine <ide> # class Engine < Rails::Engine <del> # engine_name :my_engine <ide> # end <ide> # end <ide> # <ide> module Rails <ide> # Example: <ide> # <ide> # class MyEngine < Rails::Engine <del> # # config.middleware is shared configururation <del> # config.middleware.use MyEngine::Middleware <del> # <ide> # # Add a load path for this specific Engine <ide> # config.load_paths << File.expand_path("../lib/some/path", __FILE__) <add> # <add> # initializer "my_engine.add_middleware" do |app| <add> # app.middlewares.use MyEngine::Middleware <add> # end <ide> # end <ide> # <ide> # == Paths <ide><path>railties/lib/rails/railtie.rb <ide> module Rails <ide> # # lib/my_gem/railtie.rb <ide> # module MyGem <ide> # class Railtie < Rails::Railtie <del> # railtie_name :mygem <ide> # end <ide> # end <ide> # <ide> module Rails <ide> # <ide> # module MyGem <ide> # class Railtie < Rails::Railtie <del> # railtie_name :mygem <ide> # end <ide> # end <del> # <del> # * Make sure your Gem loads the railtie.rb file if Rails is loaded first, an easy <del> # way to check is by checking for the Rails constant which will exist if Rails <del> # has started: <del> # <del> # # lib/my_gem.rb <del> # module MyGem <del> # require 'lib/my_gem/railtie' if defined?(Rails) <del> # end <del> # <del> # * Or instead of doing the require automatically, you can ask your users to require <del> # it for you in their Gemfile: <del> # <del> # # #{USER_RAILS_ROOT}/Gemfile <del> # gem "my_gem", :require_as => ["my_gem", "my_gem/railtie"] <ide> # <ide> # == Initializers <ide> # <ide> module Rails <ide> # end <ide> # <ide> # If specified, the block can also receive the application object, in case you <del> # need to access some application specific configuration: <add> # need to access some application specific configuration, like middleware: <ide> # <ide> # class MyRailtie < Rails::Railtie <ide> # initializer "my_railtie.configure_rails_initialization" do |app| <del> # if app.config.cache_classes <del> # # some initialization behavior <del> # end <add> # app.middlewares.use MyRailtie::Middleware <ide> # end <ide> # end <ide> # <ide> module Rails <ide> # # Customize the ORM <ide> # config.generators.orm :my_railtie_orm <ide> # <del> # # Add a middleware <del> # config.middlewares.use MyRailtie::Middleware <del> # <ide> # # Add a to_prepare block which is executed once in production <ide> # # and before which request in development <ide> # config.to_prepare do <ide> module Rails <ide> # By registering it: <ide> # <ide> # class MyRailtie < Railtie <del> # subscriber MyRailtie::Subscriber.new <add> # subscriber :my_gem, MyRailtie::Subscriber.new <ide> # end <ide> # <ide> # Take a look in Rails::Subscriber docs for more information.
2
PHP
PHP
add test for accept header
f6b33db02c1323c7e7fce1467724ed2a8ad85c14
<ide><path>lib/Cake/Test/Case/Network/CakeRequestTest.php <ide> public function testParseAcceptWithQValue() { <ide> $this->assertEquals($expected, $result); <ide> } <ide> <add>/** <add> * Test parsing accept with a confusing accept value. <add> * <add> * @return void <add> */ <add> public function testParseAcceptNoQValues() { <add> $_SERVER['HTTP_ACCEPT'] = 'application/json, text/plain, */*'; <add> <add> $request = new CakeRequest('/', false); <add> $result = $request->parseAccept(); <add> $expected = array( <add> '1.0' => array('application/json', 'text/plain', '*/*'), <add> ); <add> $this->assertEquals($expected, $result); <add> } <add> <ide> /** <ide> * testBaseUrlAndWebrootWithModRewrite method <ide> *
1
Javascript
Javascript
fix typos on comments
619ba0000124f2b1fce5d9c763f92419df556282
<ide><path>examples/with-dynamic-import/pages/index.js <ide> export default class Index extends React.Component { <ide> <div> <ide> <Header /> <ide> <del> {/* Load immediately, but in a sepeate bundle */} <add> {/* Load immediately, but in a separate bundle */} <ide> <DynamicComponent1 /> <ide> <ide> {/* Show a progress indicator while loading */} <ide> export default class Index extends React.Component { <ide> {showMore && <DynamicComponent5 />} <ide> <button onClick={this.toggleShowMore}>Toggle Show More</button> <ide> <del> {/* Load multible components in one bundle */} <add> {/* Load multiple components in one bundle */} <ide> <DynamicBundle /> <ide> <ide> <p>HOME PAGE is here!</p>
1
Ruby
Ruby
move argument to fix warning
57336ea68b13ec816c9403f03c437e3e503b2ca5
<ide><path>Library/Homebrew/cmd/commands.rb <ide> module Homebrew <ide> def commands <ide> # Find commands in Homebrew/cmd <add> with_directory = false <ide> cmds = (HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"). <del> children(with_directory=false). <add> children(with_directory). <ide> map {|f| File.basename(f, '.rb')} <ide> puts "Built-in commands" <ide> puts_columns cmds
1
Javascript
Javascript
add alternative mapping using attributes
a170fc1a749effa98bfd1c2e1b30297ed47b451b
<ide><path>src/ng/directive/ngPluralize.js <ide> var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp <ide> restrict: 'EA', <ide> link: function(scope, element, attr) { <ide> var numberExp = attr.count, <del> whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs <add> whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs <ide> offset = attr.offset || 0, <del> whens = scope.$eval(whenExp), <add> whens = scope.$eval(whenExp) || {}, <ide> whensExpFns = {}, <ide> startSymbol = $interpolate.startSymbol(), <del> endSymbol = $interpolate.endSymbol(); <add> endSymbol = $interpolate.endSymbol(), <add> isWhen = /^when(Minus)?(.+)$/; <ide> <add> forEach(attr, function(expression, attributeName) { <add> if (isWhen.test(attributeName)) { <add> whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] = <add> element.attr(attr.$attr[attributeName]); <add> } <add> }); <ide> forEach(whens, function(expression, key) { <ide> whensExpFns[key] = <ide> $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + <ide><path>test/ng/directive/ngPluralizeSpec.js <ide> 'use strict'; <ide> <ide> describe('ngPluralize', function() { <del> var element; <add> var element, <add> elementAlt; <ide> <ide> <ide> afterEach(function(){ <ide> dealoc(element); <add> dealoc(elementAlt); <ide> }); <ide> <ide> <ide> describe('deal with pluralized strings without offset', function() { <ide> beforeEach(inject(function($rootScope, $compile) { <ide> element = $compile( <ide> '<ng:pluralize count="email"' + <del> "when=\"{'0': 'You have no new email'," + <add> "when=\"{'-1': 'You have negative email. Whohoo!'," + <add> "'0': 'You have no new email'," + <ide> "'one': 'You have one new email'," + <ide> "'other': 'You have {} new emails'}\">" + <ide> '</ng:pluralize>')($rootScope); <add> elementAlt = $compile( <add> '<ng:pluralize count="email" ' + <add> "when-minus-1='You have negative email. Whohoo!' " + <add> "when-0='You have no new email' " + <add> "when-one='You have one new email' " + <add> "when-other='You have {} new emails'>" + <add> '</ng:pluralize>')($rootScope); <ide> })); <ide> <ide> <ide> it('should show single/plural strings', inject(function($rootScope) { <ide> $rootScope.email = 0; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have no new email'); <add> expect(elementAlt.text()).toBe('You have no new email'); <ide> <ide> $rootScope.email = '0'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have no new email'); <add> expect(elementAlt.text()).toBe('You have no new email'); <ide> <ide> $rootScope.email = 1; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have one new email'); <add> expect(elementAlt.text()).toBe('You have one new email'); <ide> <ide> $rootScope.email = 0.01; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have 0.01 new emails'); <add> expect(elementAlt.text()).toBe('You have 0.01 new emails'); <ide> <ide> $rootScope.email = '0.1'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have 0.1 new emails'); <add> expect(elementAlt.text()).toBe('You have 0.1 new emails'); <ide> <ide> $rootScope.email = 2; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have 2 new emails'); <add> expect(elementAlt.text()).toBe('You have 2 new emails'); <ide> <ide> $rootScope.email = -0.1; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have -0.1 new emails'); <add> expect(elementAlt.text()).toBe('You have -0.1 new emails'); <ide> <ide> $rootScope.email = '-0.01'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have -0.01 new emails'); <add> expect(elementAlt.text()).toBe('You have -0.01 new emails'); <ide> <ide> $rootScope.email = -2; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have -2 new emails'); <add> expect(elementAlt.text()).toBe('You have -2 new emails'); <add> <add> $rootScope.email = -1; <add> $rootScope.$digest(); <add> expect(element.text()).toBe('You have negative email. Whohoo!'); <add> expect(elementAlt.text()).toBe('You have negative email. Whohoo!'); <ide> })); <ide> <ide> <ide> it('should show single/plural strings with mal-formed inputs', inject(function($rootScope) { <ide> $rootScope.email = ''; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe(''); <add> expect(elementAlt.text()).toBe(''); <ide> <ide> $rootScope.email = null; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe(''); <add> expect(elementAlt.text()).toBe(''); <ide> <ide> $rootScope.email = undefined; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe(''); <add> expect(elementAlt.text()).toBe(''); <ide> <ide> $rootScope.email = 'a3'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe(''); <add> expect(elementAlt.text()).toBe(''); <ide> <ide> $rootScope.email = '011'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have 11 new emails'); <add> expect(elementAlt.text()).toBe('You have 11 new emails'); <ide> <ide> $rootScope.email = '-011'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have -11 new emails'); <add> expect(elementAlt.text()).toBe('You have -11 new emails'); <ide> <ide> $rootScope.email = '1fff'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have one new email'); <add> expect(elementAlt.text()).toBe('You have one new email'); <ide> <ide> $rootScope.email = '0aa22'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have no new email'); <add> expect(elementAlt.text()).toBe('You have no new email'); <ide> <ide> $rootScope.email = '000001'; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('You have one new email'); <add> expect(elementAlt.text()).toBe('You have one new email'); <ide> })); <ide> }); <ide> <ide> describe('ngPluralize', function() { <ide> describe('deal with pluralized strings with offset', function() { <ide> it('should show single/plural strings with offset', inject(function($rootScope, $compile) { <ide> element = $compile( <del> "<ng:pluralize count=\"viewCount\" offset=2 " + <add> "<ng:pluralize count='viewCount' offset='2' " + <ide> "when=\"{'0': 'Nobody is viewing.'," + <ide> "'1': '{{p1}} is viewing.'," + <ide> "'2': '{{p1}} and {{p2}} are viewing.'," + <ide> "'one': '{{p1}}, {{p2}} and one other person are viewing.'," + <ide> "'other': '{{p1}}, {{p2}} and {} other people are viewing.'}\">" + <ide> "</ng:pluralize>")($rootScope); <add> elementAlt = $compile( <add> "<ng:pluralize count='viewCount' offset='2' " + <add> "when-0='Nobody is viewing.'" + <add> "when-1='{{p1}} is viewing.'" + <add> "when-2='{{p1}} and {{p2}} are viewing.'" + <add> "when-one='{{p1}}, {{p2}} and one other person are viewing.'" + <add> "when-other='{{p1}}, {{p2}} and {} other people are viewing.'>" + <add> "</ng:pluralize>")($rootScope); <ide> $rootScope.p1 = 'Igor'; <ide> $rootScope.p2 = 'Misko'; <ide> <ide> $rootScope.viewCount = 0; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Nobody is viewing.'); <add> expect(elementAlt.text()).toBe('Nobody is viewing.'); <ide> <ide> $rootScope.viewCount = 1; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor is viewing.'); <add> expect(elementAlt.text()).toBe('Igor is viewing.'); <ide> <ide> $rootScope.viewCount = 2; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor and Misko are viewing.'); <add> expect(elementAlt.text()).toBe('Igor and Misko are viewing.'); <ide> <ide> $rootScope.viewCount = 3; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor, Misko and one other person are viewing.'); <add> expect(elementAlt.text()).toBe('Igor, Misko and one other person are viewing.'); <ide> <ide> $rootScope.viewCount = 4; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor, Misko and 2 other people are viewing.'); <add> expect(elementAlt.text()).toBe('Igor, Misko and 2 other people are viewing.'); <ide> })); <ide> }); <ide> <ide> describe('ngPluralize', function() { <ide> "'one': '[[p1%% and one other person are viewing.'," + <ide> "'other': '[[p1%% and {} other people are viewing.'}\">" + <ide> "</ng:pluralize>")($rootScope); <add> elementAlt = $compile( <add> "<ng:pluralize count='viewCount' offset='1'" + <add> "when-0='Nobody is viewing.'" + <add> "when-1='[[p1%% is viewing.'" + <add> "when-one='[[p1%% and one other person are viewing.'" + <add> "when-other='[[p1%% and {} other people are viewing.'>" + <add> "</ng:pluralize>")($rootScope); <ide> $rootScope.p1 = 'Igor'; <ide> <ide> $rootScope.viewCount = 0; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Nobody is viewing.'); <add> expect(elementAlt.text()).toBe('Nobody is viewing.'); <ide> <ide> $rootScope.viewCount = 1; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor is viewing.'); <add> expect(elementAlt.text()).toBe('Igor is viewing.'); <ide> <ide> $rootScope.viewCount = 2; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor and one other person are viewing.'); <add> expect(elementAlt.text()).toBe('Igor and one other person are viewing.'); <ide> <ide> $rootScope.viewCount = 3; <ide> $rootScope.$digest(); <ide> expect(element.text()).toBe('Igor and 2 other people are viewing.'); <add> expect(elementAlt.text()).toBe('Igor and 2 other people are viewing.'); <ide> }); <ide> }) <ide> });
2
Mixed
Java
add many fromx operators + marbles
26dacd72f1929c78d84da41ec80dc1ae3996c9f9
<ide><path>docs/Operator-Matrix.md <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> <a name='flattenStreamAsObservable'></a>`flattenStreamAsObservable`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use flatMapStream().'>([67](#notes-67))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use flatMapStream().'>([67](#notes-67))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty thus no items to map.'>([27](#notes-27))</sup>| <ide> <a name='forEach'></a>`forEach`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>| <ide> <a name='forEachWhile'></a>`forEachWhile`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use subscribe().'>([68](#notes-68))</sup>| <del><a name='fromAction'></a>`fromAction`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromAction'></a>`fromAction`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Never empty.'>([23](#notes-23))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='fromArray'></a>`fromArray`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item. Use just().'>([69](#notes-69))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always one item. Use just().'>([70](#notes-70))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty. Use complete().'>([71](#notes-71))</sup>| <ide> <a name='fromCallable'></a>`fromCallable`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='fromCompletable'></a>`fromCompletable`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always error.'>([72](#notes-72))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>| <add><a name='fromCompletable'></a>`fromCompletable`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always error.'>([72](#notes-72))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>| <ide> <a name='fromCompletionStage'></a>`fromCompletionStage`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='fromFuture'></a>`fromFuture`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='fromIterable'></a>`fromIterable`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item. Use just().'>([69](#notes-69))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always one item. Use just().'>([70](#notes-70))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty. Use complete().'>([71](#notes-71))</sup>| <del><a name='fromMaybe'></a>`fromMaybe`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='fromObservable'></a>`fromObservable`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromMaybe'></a>`fromMaybe`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromObservable'></a>`fromObservable`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='fromOptional'></a>`fromOptional`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always one item. Use just().'>([70](#notes-70))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty. Use complete().'>([71](#notes-71))</sup>| <del><a name='fromPublisher'></a>`fromPublisher`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='fromRunnable'></a>`fromRunnable`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <del><a name='fromSingle'></a>`fromSingle`|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_half.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromPublisher'></a>`fromPublisher`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromRunnable'></a>`fromRunnable`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Never empty.'>([23](#notes-23))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <add><a name='fromSingle'></a>`fromSingle`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use wrap().'>([73](#notes-73))</sup>|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='fromStream'></a>`fromStream`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='At most one item. Use just().'>([69](#notes-69))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always one item. Use just().'>([70](#notes-70))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Always empty. Use complete().'>([71](#notes-71))</sup>| <ide> <a name='fromSupplier'></a>`fromSupplier`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)| <ide> <a name='generate'></a>`generate`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use fromSupplier().'>([74](#notes-74))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use fromSupplier().'>([74](#notes-74))</sup>|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use fromSupplier().'>([74](#notes-74))</sup>| <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> <a name='zip'></a>`zip`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use merge().'>([108](#notes-108))</sup>| <ide> <a name='zipArray'></a>`zipArray`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use mergeArray().'>([109](#notes-109))</sup>| <ide> <a name='zipWith'></a>`zipWith`|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![present](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_on.png)|![absent](https://raw.github.com/wiki/ReactiveX/RxJava/images/checkmark_off.png) <sup title='Use mergeWith().'>([110](#notes-110))</sup>| <add><a name='total'></a>**237 operators** | **215** | **209** | **108** | **93** | **76** | <ide> <ide> #### Notes <ide> <a name='notes-1'></a><sup>1</sup> Use [`contains()`](#contains).<br/> <ide> Operator | ![Flowable](https://raw.github.com/wiki/ReactiveX/RxJava/images/opmat <ide> 21. Maybe.doOnLifecycle() <ide> 22. Single.doOnLifecycle() <ide> 23. Completable.doOnLifecycle() <del>24. Flowable.fromAction() <del>25. Observable.fromAction() <del>26. Single.fromAction() <del>27. Flowable.fromCompletable() <del>28. Observable.fromCompletable() <del>29. Flowable.fromMaybe() <del>30. Observable.fromMaybe() <del>31. Single.fromMaybe() <del>32. Flowable.fromObservable() <del>33. Maybe.fromObservable() <del>34. Maybe.fromPublisher() <del>35. Flowable.fromRunnable() <del>36. Observable.fromRunnable() <del>37. Single.fromRunnable() <del>38. Flowable.fromSingle() <del>39. Observable.fromSingle() <del>40. Single.mergeArray() <del>41. Single.mergeArrayDelayError() <del>42. Single.ofType() <del>43. Completable.onErrorReturn() <del>44. Completable.onErrorReturnItem() <del>45. Maybe.safeSubscribe() <del>46. Single.safeSubscribe() <del>47. Completable.safeSubscribe() <del>48. Completable.sequenceEqual() <del>49. Maybe.startWith() <del>50. Single.startWith() <del>51. Maybe.timeInterval() <del>52. Single.timeInterval() <del>53. Completable.timeInterval() <del>54. Maybe.timestamp() <del>55. Single.timestamp() <del>56. Maybe.toFuture() <del>57. Completable.toFuture() <add>24. Single.mergeArray() <add>25. Single.mergeArrayDelayError() <add>26. Single.ofType() <add>27. Completable.onErrorReturn() <add>28. Completable.onErrorReturnItem() <add>29. Maybe.safeSubscribe() <add>30. Single.safeSubscribe() <add>31. Completable.safeSubscribe() <add>32. Completable.sequenceEqual() <add>33. Maybe.startWith() <add>34. Single.startWith() <add>35. Maybe.timeInterval() <add>36. Single.timeInterval() <add>37. Completable.timeInterval() <add>38. Maybe.timestamp() <add>39. Single.timestamp() <add>40. Maybe.toFuture() <add>41. Completable.toFuture() <ide><path>src/main/java/io/reactivex/rxjava3/core/Completable.java <ide> public static Completable fromFuture(@NonNull Future<?> future) { <ide> } <ide> <ide> /** <del> * Returns a {@code Completable} instance that when subscribed to, subscribes to the {@link Maybe} instance and <add> * Returns a {@code Completable} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and <ide> * emits an {@code onComplete} event if the maybe emits {@code onSuccess}/{@code onComplete} or forwards any <ide> * {@code onError} events. <ide> * <p> <ide> public static Completable fromFuture(@NonNull Future<?> future) { <ide> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> <ide> * </dl> <ide> * <p>History: 2.1.17 - beta <del> * @param <T> the value type of the {@link MaybeSource} element <del> * @param maybe the {@code Maybe} instance to subscribe to, not {@code null} <add> * @param <T> the value type of the {@code MaybeSource} element <add> * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} <ide> * @return the new {@code Completable} instance <ide> * @throws NullPointerException if {@code maybe} is {@code null} <ide> * @since 2.2 <ide><path>src/main/java/io/reactivex/rxjava3/core/Flowable.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.rxjava3.annotations.*; <del>import io.reactivex.rxjava3.core.Observable; <ide> import io.reactivex.rxjava3.disposables.Disposable; <ide> import io.reactivex.rxjava3.exceptions.*; <ide> import io.reactivex.rxjava3.flowables.*; <ide> import io.reactivex.rxjava3.internal.fuseable.ScalarSupplier; <ide> import io.reactivex.rxjava3.internal.jdk8.*; <ide> import io.reactivex.rxjava3.internal.operators.flowable.*; <add>import io.reactivex.rxjava3.internal.operators.maybe.MaybeToFlowable; <ide> import io.reactivex.rxjava3.internal.operators.mixed.*; <del>import io.reactivex.rxjava3.internal.operators.observable.*; <add>import io.reactivex.rxjava3.internal.operators.observable.ObservableFromPublisher; <add>import io.reactivex.rxjava3.internal.operators.single.SingleToFlowable; <ide> import io.reactivex.rxjava3.internal.schedulers.ImmediateThinScheduler; <ide> import io.reactivex.rxjava3.internal.subscribers.*; <ide> import io.reactivex.rxjava3.internal.util.*; <ide> public static <T> Flowable<T> error(@NonNull Throwable throwable) { <ide> return error(Functions.justSupplier(throwable)); <ide> } <ide> <add> /** <add> * Returns a {@code Flowable} instance that runs the given {@link Action} for each subscriber and <add> * emits either its exception or simply completes. <add> * <p> <add> * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromAction.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>This source doesn't produce any elements and effectively ignores downstream backpressure.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> <add> * <dt><b>Error handling:</b></dt> <add> * <dd> If the {@code Action} throws an exception, the respective {@link Throwable} is <add> * delivered to the downstream via {@link Subscriber#onError(Throwable)}, <add> * except when the downstream has canceled the resulting {@code Flowable} source. <add> * In this latter case, the {@code Throwable} is delivered to the global error handler via <add> * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. <add> * </dd> <add> * </dl> <add> * @param <T> the target type <add> * @param action the {@code Action} to run for each subscriber <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code action} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.PASS_THROUGH) <add> public static <T> Flowable<T> fromAction(@NonNull Action action) { <add> Objects.requireNonNull(action, "action is null"); <add> return RxJavaPlugins.onAssembly(new FlowableFromAction<>(action)); <add> } <add> <ide> /** <ide> * Converts an array into a {@link Publisher} that emits the items in the array. <ide> * <p> <ide> public static <T> Flowable<T> error(@NonNull Throwable throwable) { <ide> return RxJavaPlugins.onAssembly(new FlowableFromCallable<>(callable)); <ide> } <ide> <add> /** <add> * Wraps a {@link CompletableSource} into a {@code Flowable}. <add> * <p> <add> * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromCompletable.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>This source doesn't produce any elements and effectively ignores downstream backpressure.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the target type <add> * @param completableSource the {@code CompletableSource} to convert from <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code completableSource} is {@code null} <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.PASS_THROUGH) <add> public static <T> Flowable<T> fromCompletable(@NonNull CompletableSource completableSource) { <add> Objects.requireNonNull(completableSource, "completableSource is null"); <add> return RxJavaPlugins.onAssembly(new FlowableFromCompletable<>(completableSource)); <add> } <add> <ide> /** <ide> * Converts a {@link Future} into a {@link Publisher}. <ide> * <p> <ide> public static <T> Flowable<T> error(@NonNull Throwable throwable) { <ide> return RxJavaPlugins.onAssembly(new FlowableFromIterable<>(source)); <ide> } <ide> <add> /** <add> * Returns a {@code Flowable} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and <add> * emits {@code onSuccess} as a single item or forwards any {@code onComplete} or <add> * {@code onError} signal. <add> * <p> <add> * <img width="640" height="226" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromMaybe.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator honors backpressure from downstream.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code MaybeSource} element <add> * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code maybe} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.FULL) <add> public static <T> Flowable<T> fromMaybe(@NonNull MaybeSource<T> maybe) { <add> Objects.requireNonNull(maybe, "maybe is null"); <add> return RxJavaPlugins.onAssembly(new MaybeToFlowable<>(maybe)); <add> } <add> <add> /** <add> * Converts the given {@link ObservableSource} into a {@code Flowable} by applying the specified backpressure strategy. <add> * <p> <add> * Marble diagrams for the various backpressure strategies are as follows: <add> * <ul> <add> * <li>{@link BackpressureStrategy#BUFFER} <add> * <p> <add> * <img width="640" height="264" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromObservable.buffer.png" alt=""> <add> * </li> <add> * <li>{@link BackpressureStrategy#DROP} <add> * <p> <add> * <img width="640" height="374" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromObservable.drop.png" alt=""> <add> * </li> <add> * <li>{@link BackpressureStrategy#LATEST} <add> * <p> <add> * <img width="640" height="284" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromObservable.latest.png" alt=""> <add> * </li> <add> * <li>{@link BackpressureStrategy#ERROR} <add> * <p> <add> * <img width="640" height="365" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromObservable.error.png" alt=""> <add> * </li> <add> * <li>{@link BackpressureStrategy#MISSING} <add> * <p> <add> * <img width="640" height="397" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromObservable.missing.png" alt=""> <add> * </li> <add> * </ul> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator applies the chosen backpressure strategy of {@link BackpressureStrategy} enum.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * <add> * @param <T> the element type of the source and resulting sequence <add> * @param source the {@code ObservableSource} to convert <add> * @param strategy the backpressure strategy to apply <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code source} or {@code strategy} is {@code null} <add> */ <add> @BackpressureSupport(BackpressureKind.SPECIAL) <add> @CheckReturnValue <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @NonNull <add> public static <T> Flowable<T> fromObservable(@NonNull ObservableSource<T> source, @NonNull BackpressureStrategy strategy) { <add> Objects.requireNonNull(source, "source is null"); <add> Objects.requireNonNull(strategy, "strategy is null"); <add> Flowable<T> f = new FlowableFromObservable<>(source); <add> switch (strategy) { <add> case DROP: <add> return f.onBackpressureDrop(); <add> case LATEST: <add> return f.onBackpressureLatest(); <add> case MISSING: <add> return f; <add> case ERROR: <add> return RxJavaPlugins.onAssembly(new FlowableOnBackpressureError<>(f)); <add> default: <add> return f.onBackpressureBuffer(); <add> } <add> } <add> <ide> /** <ide> * Converts an arbitrary <em>Reactive Streams</em> {@link Publisher} into a {@code Flowable} if not already a <ide> * {@code Flowable}. <ide> public static <T> Flowable<T> fromPublisher(@NonNull Publisher<@NonNull ? extend <ide> return RxJavaPlugins.onAssembly(new FlowableFromPublisher<>(publisher)); <ide> } <ide> <add> /** <add> * Returns a {@code Flowable} instance that runs the given {@link Runnable} for each subscriber and <add> * emits either its exception or simply completes. <add> * <p> <add> * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromRunnable.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>This source doesn't produce any elements and effectively ignores downstream backpressure.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * <dt><b>Error handling:</b></dt> <add> * <dd> If the {@code Runnable} throws an exception, the respective {@link Throwable} is <add> * delivered to the downstream via {@link Subscriber#onError(Throwable)}, <add> * except when the downstream has canceled the resulting {@code Flowable} source. <add> * In this latter case, the {@code Throwable} is delivered to the global error handler via <add> * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. <add> * </dd> <add> * </dl> <add> * @param <T> the target type <add> * @param run the {@code Runnable} to run for each subscriber <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code run} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.PASS_THROUGH) <add> public static <T> Flowable<T> fromRunnable(@NonNull Runnable run) { <add> Objects.requireNonNull(run, "run is null"); <add> return RxJavaPlugins.onAssembly(new FlowableFromRunnable<>(run)); <add> } <add> <add> /** <add> * Returns a {@code Flowable} instance that when subscribed to, subscribes to the {@link SingleSource} instance and <add> * emits {@code onSuccess} as a single item or forwards the {@code onError} signal. <add> * <p> <add> * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Flowable.fromSingle.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator honors backpressure from downstream.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code SingleSource} element <add> * @param source the {@code SingleSource} instance to subscribe to, not {@code null} <add> * @return the new {@code Flowable} instance <add> * @throws NullPointerException if {@code source} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.FULL) <add> public static <T> Flowable<T> fromSingle(@NonNull SingleSource<T> source) { <add> Objects.requireNonNull(source, "source is null"); <add> return RxJavaPlugins.onAssembly(new SingleToFlowable<>(source)); <add> } <add> <ide> /** <ide> * Returns a {@code Flowable} that, when a {@link Subscriber} subscribes to it, invokes a supplier function you specify and then <ide> * emits the value returned from that function. <ide><path>src/main/java/io/reactivex/rxjava3/core/Maybe.java <ide> import io.reactivex.rxjava3.internal.operators.flowable.*; <ide> import io.reactivex.rxjava3.internal.operators.maybe.*; <ide> import io.reactivex.rxjava3.internal.operators.mixed.*; <add>import io.reactivex.rxjava3.internal.operators.observable.ObservableElementAtMaybe; <ide> import io.reactivex.rxjava3.internal.util.ErrorMode; <ide> import io.reactivex.rxjava3.observers.TestObserver; <ide> import io.reactivex.rxjava3.plugins.RxJavaPlugins; <ide> public static <T> Maybe<T> error(@NonNull Supplier<? extends Throwable> supplier <ide> } <ide> <ide> /** <del> * Returns a {@code Maybe} instance that runs the given {@link Action} for each subscriber and <add> * Returns a {@code Maybe} instance that runs the given {@link Action} for each observer and <ide> * emits either its exception or simply completes. <ide> * <p> <ide> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromAction.png" alt=""> <ide> public static <T> Maybe<T> error(@NonNull Supplier<? extends Throwable> supplier <ide> * <dt><b>Error handling:</b></dt> <ide> * <dd> If the {@code Action} throws an exception, the respective {@link Throwable} is <ide> * delivered to the downstream via {@link MaybeObserver#onError(Throwable)}, <del> * except when the downstream has disposed this {@code Maybe} source. <add> * except when the downstream has disposed the resulting {@code Maybe} source. <ide> * In this latter case, the {@code Throwable} is delivered to the global error handler via <ide> * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. <ide> * </dd> <ide> * </dl> <ide> * @param <T> the target type <del> * @param action the {@code Action} to run for each subscriber <add> * @param action the {@code Action} to run for each observer <ide> * @return the new {@code Maybe} instance <ide> * @throws NullPointerException if {@code action} is {@code null} <ide> */ <ide> public static <T> Maybe<T> fromSingle(@NonNull SingleSource<T> single) { <ide> } <ide> <ide> /** <del> * Returns a {@code Maybe} instance that runs the given {@link Runnable} for each subscriber and <add> * Wraps an {@link ObservableSource} into a {@code Maybe} and emits the very first item <add> * or completes if the source is empty. <add> * <p> <add> * <img width="640" height="276" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromObservable.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the target type <add> * @param source the {@code ObservableSource} to convert from <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code source} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Maybe<T> fromObservable(@NonNull ObservableSource<T> source) { <add> Objects.requireNonNull(source, "source is null"); <add> return RxJavaPlugins.onAssembly(new ObservableElementAtMaybe<>(source, 0L)); <add> } <add> <add> /** <add> * Wraps a {@link Publisher} into a {@code Maybe} and emits the very first item <add> * or completes if the source is empty. <add> * <p> <add> * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromPublisher.png" alt=""> <add> * <dl> <add> * <dt><b>Backpressure:</b></dt> <add> * <dd>The operator consumes the given {@code Publisher} in an unbounded manner <add> * (requesting {@link Long#MAX_VALUE}) but cancels it after one item received.</dd> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromPublisher} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the target type <add> * @param source the {@code Publisher} to convert from <add> * @return the new {@code Maybe} instance <add> * @throws NullPointerException if {@code source} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) <add> public static <T> Maybe<T> fromPublisher(@NonNull Publisher<T> source) { <add> Objects.requireNonNull(source, "source is null"); <add> return RxJavaPlugins.onAssembly(new FlowableElementAtMaybePublisher<>(source, 0L)); <add> } <add> <add> /** <add> * Returns a {@code Maybe} instance that runs the given {@link Runnable} for each observer and <ide> * emits either its exception or simply completes. <ide> * <p> <ide> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromRunnable.png" alt=""> <ide> public static <T> Maybe<T> fromSingle(@NonNull SingleSource<T> single) { <ide> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> <ide> * </dl> <ide> * @param <T> the target type <del> * @param run the {@code Runnable} to run for each subscriber <add> * @param run the {@code Runnable} to run for each observer <ide> * @return the new {@code Maybe} instance <ide> * @throws NullPointerException if {@code run} is {@code null} <ide> */ <ide><path>src/main/java/io/reactivex/rxjava3/core/Observable.java <ide> import io.reactivex.rxjava3.internal.jdk8.*; <ide> import io.reactivex.rxjava3.internal.observers.*; <ide> import io.reactivex.rxjava3.internal.operators.flowable.*; <add>import io.reactivex.rxjava3.internal.operators.maybe.MaybeToObservable; <ide> import io.reactivex.rxjava3.internal.operators.mixed.*; <ide> import io.reactivex.rxjava3.internal.operators.observable.*; <add>import io.reactivex.rxjava3.internal.operators.single.SingleToObservable; <ide> import io.reactivex.rxjava3.internal.util.*; <ide> import io.reactivex.rxjava3.observables.*; <ide> import io.reactivex.rxjava3.observers.*; <ide> public static <T> Observable<T> error(@NonNull Throwable throwable) { <ide> return error(Functions.justSupplier(throwable)); <ide> } <ide> <add> /** <add> * Returns an {@code Observable} instance that runs the given {@link Action} for each subscriber and <add> * emits either its exception or simply completes. <add> * <p> <add> * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.fromAction.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> <add> * <dt><b>Error handling:</b></dt> <add> * <dd> If the {@code Action} throws an exception, the respective {@link Throwable} is <add> * delivered to the downstream via {@link Observer#onError(Throwable)}, <add> * except when the downstream has canceled the resulting {@code Observable} source. <add> * In this latter case, the {@code Throwable} is delivered to the global error handler via <add> * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. <add> * </dd> <add> * </dl> <add> * @param <T> the target type <add> * @param action the {@code Action} to run for each subscriber <add> * @return the new {@code Observable} instance <add> * @throws NullPointerException if {@code action} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Observable<T> fromAction(@NonNull Action action) { <add> Objects.requireNonNull(action, "action is null"); <add> return RxJavaPlugins.onAssembly(new ObservableFromAction<>(action)); <add> } <add> <ide> /** <ide> * Converts an array into an {@link ObservableSource} that emits the items in the array. <ide> * <p> <ide> public static <T> Observable<T> fromCallable(@NonNull Callable<? extends T> call <ide> return RxJavaPlugins.onAssembly(new ObservableFromCallable<>(callable)); <ide> } <ide> <add> /** <add> * Wraps a {@link CompletableSource} into an {@code Observable}. <add> * <p> <add> * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromCompletable.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the target type <add> * @param completableSource the {@code CompletableSource} to convert from <add> * @return the new {@code Observable} instance <add> * @throws NullPointerException if {@code completableSource} is {@code null} <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Observable<T> fromCompletable(@NonNull CompletableSource completableSource) { <add> Objects.requireNonNull(completableSource, "completableSource is null"); <add> return RxJavaPlugins.onAssembly(new ObservableFromCompletable<>(completableSource)); <add> } <add> <ide> /** <ide> * Converts a {@link Future} into an {@code Observable}. <ide> * <p> <ide> public static <T> Observable<T> fromIterable(@NonNull Iterable<@NonNull ? extend <ide> return RxJavaPlugins.onAssembly(new ObservableFromIterable<>(source)); <ide> } <ide> <add> /** <add> * Returns an {@code Observable} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and <add> * emits {@code onSuccess} as a single item or forwards any {@code onComplete} or <add> * {@code onError} signal. <add> * <p> <add> * <img width="640" height="226" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromMaybe.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code MaybeSource} element <add> * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} <add> * @return the new {@code Observable} instance <add> * @throws NullPointerException if {@code maybe} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Observable<T> fromMaybe(@NonNull MaybeSource<T> maybe) { <add> Objects.requireNonNull(maybe, "maybe is null"); <add> return RxJavaPlugins.onAssembly(new MaybeToObservable<>(maybe)); <add> } <add> <ide> /** <ide> * Converts an arbitrary <em>Reactive Streams</em> {@link Publisher} into an {@code Observable}. <ide> * <p> <ide> public static <T> Observable<T> fromPublisher(@NonNull Publisher<@NonNull ? exte <ide> return RxJavaPlugins.onAssembly(new ObservableFromPublisher<>(publisher)); <ide> } <ide> <add> /** <add> * Returns an {@code Observable} instance that runs the given {@link Runnable} for each observer and <add> * emits either its exception or simply completes. <add> * <p> <add> * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromRunnable.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> <add> * <dt><b>Error handling:</b></dt> <add> * <dd> If the {@code Runnable} throws an exception, the respective {@link Throwable} is <add> * delivered to the downstream via {@link Observer#onError(Throwable)}, <add> * except when the downstream has canceled the resulting {@code Observable} source. <add> * In this latter case, the {@code Throwable} is delivered to the global error handler via <add> * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. <add> * </dd> <add> * </dl> <add> * @param <T> the target type <add> * @param run the {@code Runnable} to run for each observer <add> * @return the new {@code Observable} instance <add> * @throws NullPointerException if {@code run} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Observable<T> fromRunnable(@NonNull Runnable run) { <add> Objects.requireNonNull(run, "run is null"); <add> return RxJavaPlugins.onAssembly(new ObservableFromRunnable<>(run)); <add> } <add> <add> /** <add> * Returns an {@code Observable} instance that when subscribed to, subscribes to the {@link SingleSource} instance and <add> * emits {@code onSuccess} as a single item or forwards the {@code onError} signal. <add> * <p> <add> * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromSingle.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code SingleSource} element <add> * @param source the {@code SingleSource} instance to subscribe to, not {@code null} <add> * @return the new {@code Observable} instance <add> * @throws NullPointerException if {@code source} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Observable<T> fromSingle(@NonNull SingleSource<T> source) { <add> Objects.requireNonNull(source, "source is null"); <add> return RxJavaPlugins.onAssembly(new SingleToObservable<>(source)); <add> } <add> <ide> /** <ide> * Returns an {@code Observable} that, when an observer subscribes to it, invokes a supplier function you specify and then <ide> * emits the value returned from that function. <ide><path>src/main/java/io/reactivex/rxjava3/core/Single.java <ide> public static <T> Single<T> error(@NonNull Throwable throwable) { <ide> return toSingle(Flowable.fromFuture(future, timeout, unit)); <ide> } <ide> <add> /** <add> * Returns a {@code Single} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and <add> * emits {@code onSuccess} as a single item, turns an {@code onComplete} into {@link NoSuchElementException} error signal or <add> * forwards the {@code onError} signal. <add> * <p> <add> * <img width="640" height="241" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromMaybe.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code MaybeSource} element <add> * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code maybe} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Single<T> fromMaybe(@NonNull MaybeSource<T> maybe) { <add> Objects.requireNonNull(maybe, "maybe is null"); <add> return RxJavaPlugins.onAssembly(new MaybeToSingle<>(maybe, null)); <add> } <add> <add> /** <add> * Returns a {@code Single} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and <add> * emits {@code onSuccess} as a single item, emits the {@code defaultItem} for an {@code onComplete} signal or <add> * forwards the {@code onError} signal. <add> * <p> <add> * <img width="640" height="353" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromMaybe.v.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * @param <T> the value type of the {@code MaybeSource} element <add> * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} <add> * @param defaultItem the item to signal if the current {@code MaybeSource} is empty <add> * @return the new {@code Single} instance <add> * @throws NullPointerException if {@code maybe} or {@code defaultItem} is {@code null} <add> * @since 3.0.0 <add> */ <add> @CheckReturnValue <add> @NonNull <add> @SchedulerSupport(SchedulerSupport.NONE) <add> public static <T> Single<T> fromMaybe(@NonNull MaybeSource<T> maybe, @NonNull T defaultItem) { <add> Objects.requireNonNull(maybe, "maybe is null"); <add> Objects.requireNonNull(defaultItem, "defaultItem is null"); <add> return RxJavaPlugins.onAssembly(new MaybeToSingle<>(maybe, defaultItem)); <add> } <add> <ide> /** <ide> * Wraps a specific {@link Publisher} into a {@code Single} and signals its single element or error. <ide> * <p> <ide><path>src/main/java/io/reactivex/rxjava3/internal/fuseable/AbstractEmptyQueueFuseable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.fuseable; <add> <add>import io.reactivex.rxjava3.annotations.NonNull; <add> <add>/** <add> * Represents an empty, async-only {@link QueueFuseable} instance. <add> * <add> * @param <T> the output value type <add> * @since 3.0.0 <add> */ <add>public abstract class AbstractEmptyQueueFuseable<T> <add>implements QueueSubscription<T>, QueueDisposable<T> { <add> <add> @Override <add> public final int requestFusion(int mode) { <add> return mode & ASYNC; <add> } <add> <add> @Override <add> public final boolean offer(@NonNull T value) { <add> throw new UnsupportedOperationException("Should not be called!"); <add> } <add> <add> @Override <add> public final boolean offer(@NonNull T v1, @NonNull T v2) { <add> throw new UnsupportedOperationException("Should not be called!"); <add> } <add> <add> @Override <add> public final T poll() throws Throwable { <add> return null; // always empty <add> } <add> <add> @Override <add> public final boolean isEmpty() { <add> return true; // always empty <add> } <add> <add> @Override <add> public final void clear() { <add> // always empty <add> } <add> <add> @Override <add> public final void request(long n) { <add> // no items to request <add> } <add> <add> @Override <add> public void cancel() { <add> // default No-op <add> } <add> <add> @Override <add> public void dispose() { <add> // default No-op <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return false; <add> } <add>} <ide>\ No newline at end of file <ide><path>src/main/java/io/reactivex/rxjava3/internal/fuseable/CancellableQueueFuseable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.fuseable; <add> <add>/** <add> * Represents an empty, async-only {@link QueueFuseable} instance that tracks and exposes a <add> * canceled/disposed state. <add> * <add> * @param <T> the output value type <add> * @since 3.0.0 <add> */ <add>public final class CancellableQueueFuseable<T> <add>extends AbstractEmptyQueueFuseable<T> { <add> <add> volatile boolean disposed; <add> <add> @Override <add> public void cancel() { <add> disposed = true; <add> } <add> <add> @Override <add> public void dispose() { <add> disposed = true; <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return disposed; <add> } <add>} <ide>\ No newline at end of file <ide><path>src/main/java/io/reactivex/rxjava3/internal/observers/SubscriberCompletableObserver.java <del>/** <del> * Copyright (c) 2016-present, RxJava Contributors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <del> * compliance with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software distributed under the License is <del> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <del> * the License for the specific language governing permissions and limitations under the License. <del> */ <del> <del>package io.reactivex.rxjava3.internal.observers; <del> <del>import org.reactivestreams.*; <del> <del>import io.reactivex.rxjava3.core.CompletableObserver; <del>import io.reactivex.rxjava3.disposables.Disposable; <del>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <del> <del>public final class SubscriberCompletableObserver<T> implements CompletableObserver, Subscription { <del> final Subscriber<? super T> subscriber; <del> <del> Disposable upstream; <del> <del> public SubscriberCompletableObserver(Subscriber<? super T> subscriber) { <del> this.subscriber = subscriber; <del> } <del> <del> @Override <del> public void onComplete() { <del> subscriber.onComplete(); <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> subscriber.onError(e); <del> } <del> <del> @Override <del> public void onSubscribe(Disposable d) { <del> if (DisposableHelper.validate(this.upstream, d)) { <del> this.upstream = d; <del> <del> subscriber.onSubscribe(this); <del> } <del> } <del> <del> @Override <del> public void request(long n) { <del> // ignored, no values emitted anyway <del> } <del> <del> @Override <del> public void cancel() { <del> upstream.dispose(); <del> } <del>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableFromAction.java <ide> public CompletableFromAction(Action run) { <ide> protected void subscribeActual(CompletableObserver observer) { <ide> Disposable d = Disposable.empty(); <ide> observer.onSubscribe(d); <del> try { <del> run.run(); <del> } catch (Throwable e) { <del> Exceptions.throwIfFatal(e); <add> if (!d.isDisposed()) { <add> try { <add> run.run(); <add> } catch (Throwable e) { <add> Exceptions.throwIfFatal(e); <add> if (!d.isDisposed()) { <add> observer.onError(e); <add> } else { <add> RxJavaPlugins.onError(e); <add> } <add> return; <add> } <ide> if (!d.isDisposed()) { <del> observer.onError(e); <del> } else { <del> RxJavaPlugins.onError(e); <add> observer.onComplete(); <ide> } <del> return; <del> } <del> if (!d.isDisposed()) { <del> observer.onComplete(); <ide> } <ide> } <ide> <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableFromRunnable.java <ide> public CompletableFromRunnable(Runnable runnable) { <ide> protected void subscribeActual(CompletableObserver observer) { <ide> Disposable d = Disposable.empty(); <ide> observer.onSubscribe(d); <del> try { <del> runnable.run(); <del> } catch (Throwable e) { <del> Exceptions.throwIfFatal(e); <add> if (!d.isDisposed()) { <add> try { <add> runnable.run(); <add> } catch (Throwable e) { <add> Exceptions.throwIfFatal(e); <add> if (!d.isDisposed()) { <add> observer.onError(e); <add> } else { <add> RxJavaPlugins.onError(e); <add> } <add> return; <add> } <ide> if (!d.isDisposed()) { <del> observer.onError(e); <del> } else { <del> RxJavaPlugins.onError(e); <add> observer.onComplete(); <ide> } <del> return; <del> } <del> if (!d.isDisposed()) { <del> observer.onComplete(); <ide> } <ide> } <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableToFlowable.java <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.rxjava3.core.*; <del>import io.reactivex.rxjava3.internal.observers.SubscriberCompletableObserver; <add>import io.reactivex.rxjava3.internal.operators.flowable.FlowableFromCompletable; <ide> <ide> public final class CompletableToFlowable<T> extends Flowable<T> { <ide> <ide> public CompletableToFlowable(CompletableSource source) { <ide> <ide> @Override <ide> protected void subscribeActual(Subscriber<? super T> s) { <del> SubscriberCompletableObserver<T> os = new SubscriberCompletableObserver<>(s); <del> source.subscribe(os); <add> source.subscribe(new FlowableFromCompletable.FromCompletableObserver<>(s)); <ide> } <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/completable/CompletableToObservable.java <ide> package io.reactivex.rxjava3.internal.operators.completable; <ide> <ide> import io.reactivex.rxjava3.core.*; <del>import io.reactivex.rxjava3.disposables.Disposable; <del>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <del>import io.reactivex.rxjava3.internal.observers.BasicQueueDisposable; <add>import io.reactivex.rxjava3.internal.operators.observable.ObservableFromCompletable; <ide> <ide> /** <ide> * Wraps a Completable and exposes it as an Observable. <ide> public CompletableToObservable(CompletableSource source) { <ide> <ide> @Override <ide> protected void subscribeActual(Observer<? super T> observer) { <del> source.subscribe(new ObserverCompletableObserver(observer)); <del> } <del> <del> static final class ObserverCompletableObserver extends BasicQueueDisposable<Void> <del> implements CompletableObserver { <del> <del> final Observer<?> observer; <del> <del> Disposable upstream; <del> <del> ObserverCompletableObserver(Observer<?> observer) { <del> this.observer = observer; <del> } <del> <del> @Override <del> public void onComplete() { <del> observer.onComplete(); <del> } <del> <del> @Override <del> public void onError(Throwable e) { <del> observer.onError(e); <del> } <del> <del> @Override <del> public void onSubscribe(Disposable d) { <del> if (DisposableHelper.validate(upstream, d)) { <del> this.upstream = d; <del> observer.onSubscribe(this); <del> } <del> } <del> <del> @Override <del> public int requestFusion(int mode) { <del> return mode & ASYNC; <del> } <del> <del> @Override <del> public Void poll() { <del> return null; // always empty <del> } <del> <del> @Override <del> public boolean isEmpty() { <del> return true; <del> } <del> <del> @Override <del> public void clear() { <del> // always empty <del> } <del> <del> @Override <del> public void dispose() { <del> upstream.dispose(); <del> } <del> <del> @Override <del> public boolean isDisposed() { <del> return upstream.isDisposed(); <del> } <add> source.subscribe(new ObservableFromCompletable.FromCompletableObserver<>(observer)); <ide> } <ide> } <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableElementAtMaybePublisher.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import org.reactivestreams.Publisher; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.internal.operators.flowable.FlowableElementAtMaybe.ElementAtSubscriber; <add> <add>/** <add> * Emits the indexth element from a Publisher as a Maybe. <add> * <add> * @param <T> the element type of the source <add> * @since 3.0.0 <add> */ <add>public final class FlowableElementAtMaybePublisher<T> extends Maybe<T> { <add> <add> final Publisher<T> source; <add> <add> final long index; <add> <add> public FlowableElementAtMaybePublisher(Publisher<T> source, long index) { <add> this.source = source; <add> this.index = index; <add> } <add> <add> @Override <add> protected void subscribeActual(MaybeObserver<? super T> observer) { <add> source.subscribe(new ElementAtSubscriber<>(observer, index)); <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromAction.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import org.reactivestreams.Subscriber; <add> <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.CancellableQueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add> <add>/** <add> * Executes an {@link Action} and signals its exception or completes normally. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class FlowableFromAction<T> extends Flowable<T> implements Supplier<T> { <add> <add> final Action action; <add> <add> public FlowableFromAction(Action action) { <add> this.action = action; <add> } <add> <add> @Override <add> protected void subscribeActual(Subscriber<? super T> subscriber) { <add> CancellableQueueFuseable<T> qs = new CancellableQueueFuseable<>(); <add> subscriber.onSubscribe(qs); <add> <add> if (!qs.isDisposed()) { <add> <add> try { <add> action.run(); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> if (!qs.isDisposed()) { <add> subscriber.onError(ex); <add> } else { <add> RxJavaPlugins.onError(ex); <add> } <add> return; <add> } <add> <add> if (!qs.isDisposed()) { <add> subscriber.onComplete(); <add> } <add> } <add> } <add> <add> @Override <add> public T get() throws Throwable { <add> action.run(); <add> return null; // considered as onComplete() <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromCompletable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import org.reactivestreams.Subscriber; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.disposables.Disposable; <add>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <add>import io.reactivex.rxjava3.internal.fuseable.*; <add> <add>/** <add> * Wrap a Completable into a Flowable. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class FlowableFromCompletable<T> extends Flowable<T> implements HasUpstreamCompletableSource { <add> <add> final CompletableSource source; <add> <add> public FlowableFromCompletable(CompletableSource source) { <add> this.source = source; <add> } <add> <add> @Override <add> public CompletableSource source() { <add> return source; <add> } <add> <add> @Override <add> protected void subscribeActual(Subscriber<? super T> observer) { <add> source.subscribe(new FromCompletableObserver<T>(observer)); <add> } <add> <add> public static final class FromCompletableObserver<T> <add> extends AbstractEmptyQueueFuseable<T> <add> implements CompletableObserver { <add> <add> final Subscriber<? super T> downstream; <add> <add> Disposable upstream; <add> <add> public FromCompletableObserver(Subscriber<? super T> downstream) { <add> this.downstream = downstream; <add> } <add> <add> @Override <add> public void cancel() { <add> upstream.dispose(); <add> upstream = DisposableHelper.DISPOSED; <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.upstream, d)) { <add> this.upstream = d; <add> <add> downstream.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onComplete() { <add> upstream = DisposableHelper.DISPOSED; <add> downstream.onComplete(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> upstream = DisposableHelper.DISPOSED; <add> downstream.onError(e); <add> } <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromObservable.java <ide> import io.reactivex.rxjava3.disposables.Disposable; <ide> <ide> public final class FlowableFromObservable<T> extends Flowable<T> { <del> private final Observable<T> upstream; <ide> <del> public FlowableFromObservable(Observable<T> upstream) { <add> private final ObservableSource<T> upstream; <add> <add> public FlowableFromObservable(ObservableSource<T> upstream) { <ide> this.upstream = upstream; <ide> } <ide> <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromRunnable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import org.reactivestreams.Subscriber; <add> <add>import io.reactivex.rxjava3.core.Flowable; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import io.reactivex.rxjava3.internal.fuseable.CancellableQueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add> <add>/** <add> * Executes an {@link Runnable} and signals its exception or completes normally. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class FlowableFromRunnable<T> extends Flowable<T> implements Supplier<T> { <add> <add> final Runnable run; <add> <add> public FlowableFromRunnable(Runnable run) { <add> this.run = run; <add> } <add> <add> @Override <add> protected void subscribeActual(Subscriber<? super T> subscriber) { <add> CancellableQueueFuseable<T> qs = new CancellableQueueFuseable<>(); <add> subscriber.onSubscribe(qs); <add> <add> if (!qs.isDisposed()) { <add> <add> try { <add> run.run(); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> if (!qs.isDisposed()) { <add> subscriber.onError(ex); <add> } else { <add> RxJavaPlugins.onError(ex); <add> } <add> return; <add> } <add> <add> if (!qs.isDisposed()) { <add> subscriber.onComplete(); <add> } <add> } <add> } <add> <add> @Override <add> public T get() throws Throwable { <add> run.run(); <add> return null; // considered as onComplete() <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFromCompletable.java <ide> import io.reactivex.rxjava3.internal.fuseable.HasUpstreamCompletableSource; <ide> <ide> /** <del> * Wrap a Single into a Maybe. <add> * Wrap a Completable into a Maybe. <ide> * <ide> * @param <T> the value type <ide> */ <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeToSingle.java <ide> <ide> /** <ide> * Wraps a MaybeSource and exposes its onSuccess and onError signals and signals <del> * NoSuchElementException for onComplete. <add> * NoSuchElementException for onComplete if {@code defaultValue} is null. <ide> * <ide> * @param <T> the value type <ide> */ <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromAction.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.CancellableQueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add> <add>/** <add> * Executes an {@link Action} and signals its exception or completes normally. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class ObservableFromAction<T> extends Observable<T> implements Supplier<T> { <add> <add> final Action action; <add> <add> public ObservableFromAction(Action action) { <add> this.action = action; <add> } <add> <add> @Override <add> protected void subscribeActual(Observer<? super T> observer) { <add> CancellableQueueFuseable<T> qs = new CancellableQueueFuseable<>(); <add> observer.onSubscribe(qs); <add> <add> if (!qs.isDisposed()) { <add> <add> try { <add> action.run(); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> if (!qs.isDisposed()) { <add> observer.onError(ex); <add> } else { <add> RxJavaPlugins.onError(ex); <add> } <add> return; <add> } <add> <add> if (!qs.isDisposed()) { <add> observer.onComplete(); <add> } <add> } <add> } <add> <add> @Override <add> public T get() throws Throwable { <add> action.run(); <add> return null; // considered as onComplete() <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromCompletable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.disposables.Disposable; <add>import io.reactivex.rxjava3.internal.disposables.DisposableHelper; <add>import io.reactivex.rxjava3.internal.fuseable.*; <add> <add>/** <add> * Wrap a Completable into an Observable. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class ObservableFromCompletable<T> extends Observable<T> implements HasUpstreamCompletableSource { <add> <add> final CompletableSource source; <add> <add> public ObservableFromCompletable(CompletableSource source) { <add> this.source = source; <add> } <add> <add> @Override <add> public CompletableSource source() { <add> return source; <add> } <add> <add> @Override <add> protected void subscribeActual(Observer<? super T> observer) { <add> source.subscribe(new FromCompletableObserver<T>(observer)); <add> } <add> <add> public static final class FromCompletableObserver<T> <add> extends AbstractEmptyQueueFuseable<T> <add> implements CompletableObserver { <add> <add> final Observer<? super T> downstream; <add> <add> Disposable upstream; <add> <add> public FromCompletableObserver(Observer<? super T> downstream) { <add> this.downstream = downstream; <add> } <add> <add> @Override <add> public void dispose() { <add> upstream.dispose(); <add> upstream = DisposableHelper.DISPOSED; <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return upstream.isDisposed(); <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.upstream, d)) { <add> this.upstream = d; <add> <add> downstream.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onComplete() { <add> upstream = DisposableHelper.DISPOSED; <add> downstream.onComplete(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> upstream = DisposableHelper.DISPOSED; <add> downstream.onError(e); <add> } <add> } <add>} <ide><path>src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromRunnable.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.Exceptions; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import io.reactivex.rxjava3.internal.fuseable.CancellableQueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add> <add>/** <add> * Executes an {@link Runnable} and signals its exception or completes normally. <add> * <add> * @param <T> the value type <add> * @since 3.0.0 <add> */ <add>public final class ObservableFromRunnable<T> extends Observable<T> implements Supplier<T> { <add> <add> final Runnable run; <add> <add> public ObservableFromRunnable(Runnable run) { <add> this.run = run; <add> } <add> <add> @Override <add> protected void subscribeActual(Observer<? super T> observer) { <add> CancellableQueueFuseable<T> qs = new CancellableQueueFuseable<>(); <add> observer.onSubscribe(qs); <add> <add> if (!qs.isDisposed()) { <add> <add> try { <add> run.run(); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> if (!qs.isDisposed()) { <add> observer.onError(ex); <add> } else { <add> RxJavaPlugins.onError(ex); <add> } <add> return; <add> } <add> <add> if (!qs.isDisposed()) { <add> observer.onComplete(); <add> } <add> } <add> } <add> <add> @Override <add> public T get() throws Throwable { <add> run.run(); <add> return null; // considered as onComplete() <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/fuseable/CancellableQueueFuseableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.fuseable; <add> <add>import static org.junit.Assert.*; <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.testsupport.TestHelper; <add> <add>public class CancellableQueueFuseableTest { <add> <add> @Test <add> public void offer() { <add> TestHelper.assertNoOffer(new CancellableQueueFuseable<>()); <add> } <add> <add> @Test <add> public void cancel() { <add> CancellableQueueFuseable<Object> qs = new CancellableQueueFuseable<>(); <add> <add> assertFalse(qs.isDisposed()); <add> <add> qs.cancel(); <add> <add> assertTrue(qs.isDisposed()); <add> <add> qs.cancel(); <add> <add> assertTrue(qs.isDisposed()); <add> } <add> <add> @Test <add> public void dispose() { <add> CancellableQueueFuseable<Object> qs = new CancellableQueueFuseable<>(); <add> <add> assertFalse(qs.isDisposed()); <add> <add> qs.dispose(); <add> <add> assertTrue(qs.isDisposed()); <add> <add> qs.dispose(); <add> <add> assertTrue(qs.isDisposed()); <add> } <add> <add> @Test <add> public void cancel2() { <add> AbstractEmptyQueueFuseable<Object> qs = new AbstractEmptyQueueFuseable<Object>() {}; <add> <add> assertFalse(qs.isDisposed()); <add> <add> qs.cancel(); <add> } <add> <add> @Test <add> public void dispose2() { <add> AbstractEmptyQueueFuseable<Object> qs = new AbstractEmptyQueueFuseable<Object>() {}; <add> <add> assertFalse(qs.isDisposed()); <add> <add> qs.dispose(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableAndThenCompletableabTest.java <ide> public void run() { <ide> .andThen(Completable.complete()) <ide> .test(true) <ide> .assertEmpty(); <del> assertEquals(1, completableRunCount.get()); <add> assertEquals(0, completableRunCount.get()); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableFromActionTest.java <ide> package io.reactivex.rxjava3.internal.operators.completable; <ide> <ide> import static org.junit.Assert.assertEquals; <add>import static org.mockito.Mockito.*; <ide> <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> public void run() throws Exception { <ide> .test(true) <ide> .assertEmpty(); <ide> <del> assertEquals(1, calls.get()); <add> assertEquals(0, calls.get()); <ide> } <ide> <ide> @Test <ide> public void run() throws Exception { <ide> .test(true) <ide> .assertEmpty(); <ide> <del> assertEquals(1, calls.get()); <add> assertEquals(0, calls.get()); <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Action run = mock(Action.class); <add> <add> Completable.fromAction(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <ide> } <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableFromRunnableTest.java <ide> package io.reactivex.rxjava3.internal.operators.completable; <ide> <ide> import static org.junit.Assert.assertEquals; <add>import static org.mockito.Mockito.*; <ide> <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> public void run() { <ide> .test(true) <ide> .assertEmpty(); <ide> <del> assertEquals(1, calls.get()); <add> assertEquals(0, calls.get()); <ide> } <ide> <ide> @Test <ide> public void run() { <ide> .test(true) <ide> .assertEmpty(); <ide> <del> assertEquals(1, calls.get()); <add> assertEquals(0, calls.get()); <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Runnable run = mock(Runnable.class); <add> <add> Completable.fromRunnable(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <ide> } <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableToObservableTest.java <ide> <ide> package io.reactivex.rxjava3.internal.operators.completable; <ide> <del>import static org.junit.Assert.*; <del> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.rxjava3.core.*; <del>import io.reactivex.rxjava3.disposables.*; <ide> import io.reactivex.rxjava3.functions.Function; <del>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <del>import io.reactivex.rxjava3.internal.operators.completable.CompletableToObservable.ObserverCompletableObserver; <del>import io.reactivex.rxjava3.observers.TestObserver; <ide> import io.reactivex.rxjava3.testsupport.TestHelper; <ide> <ide> public class CompletableToObservableTest extends RxJavaTest { <ide> public Observable<?> apply(Completable c) throws Exception { <ide> }); <ide> } <ide> <del> @Test <del> public void fusion() throws Exception { <del> TestObserver<Void> to = new TestObserver<>(); <del> <del> ObserverCompletableObserver co = new ObserverCompletableObserver(to); <del> <del> Disposable d = Disposable.empty(); <del> <del> co.onSubscribe(d); <del> <del> assertEquals(QueueFuseable.NONE, co.requestFusion(QueueFuseable.SYNC)); <del> <del> assertEquals(QueueFuseable.ASYNC, co.requestFusion(QueueFuseable.ASYNC)); <del> <del> assertEquals(QueueFuseable.ASYNC, co.requestFusion(QueueFuseable.ANY)); <del> <del> assertTrue(co.isEmpty()); <del> <del> assertNull(co.poll()); <del> <del> co.clear(); <del> <del> assertFalse(co.isDisposed()); <del> <del> co.dispose(); <del> <del> assertTrue(d.isDisposed()); <del> <del> assertTrue(co.isDisposed()); <del> <del> TestHelper.assertNoOffer(co); <del> } <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromActionTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class FlowableFromActionTest extends RxJavaTest { <add> @Test <add> public void fromAction() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Action run = new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Flowable.fromAction(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Flowable.fromAction(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable<Object> source = Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionThrows() { <add> Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> throw new UnsupportedOperationException(); <add> } <add> }) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Test <add> public void callable() throws Throwable { <add> final int[] counter = { 0 }; <add> <add> Flowable<Void> m = Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> counter[0]++; <add> } <add> }); <add> <add> assertTrue(m.getClass().toString(), m instanceof Supplier); <add> <add> assertNull(((Supplier<Void>)m).get()); <add> <add> assertEquals(1, counter[0]); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestSubscriber<Object> ts = Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> cdl1.countDown(); <add> cdl2.await(5, TimeUnit.SECONDS); <add> } <add> }).subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> ts.cancel(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, InterruptedException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Action run = mock(Action.class); <add> <add> Flowable.fromAction(run) <add> .test(1L, true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestSubscriber<Object> ts = new TestSubscriber<>(); <add> <add> Flowable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> ts.cancel(); <add> } <add> }) <add> .subscribeWith(ts) <add> .assertEmpty(); <add> <add> assertTrue(ts.isCancelled()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Action action = mock(Action.class); <add> <add> Flowable.fromAction(action) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Action action = mock(Action.class); <add> <add> Flowable.fromAction(action) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromCompletableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class FlowableFromCompletableTest extends RxJavaTest { <add> @Test <add> public void fromCompletable() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> })) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Action run = new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Flowable.fromCompletable(Completable.fromAction(run)) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Flowable.fromCompletable(Completable.fromAction(run)) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable<Object> source = Flowable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> })); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableThrows() { <add> Flowable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> throw new UnsupportedOperationException(); <add> } <add> })) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestSubscriber<Object> ts = Flowable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> cdl1.countDown(); <add> cdl2.await(5, TimeUnit.SECONDS); <add> } <add> })) <add> .subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> ts.cancel(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, InterruptedException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Action run = mock(Action.class); <add> <add> Flowable.fromCompletable(Completable.fromAction(run)) <add> .test(1L, true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestSubscriber<Object> ts = new TestSubscriber<>(); <add> <add> Flowable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> ts.cancel(); <add> } <add> })) <add> .subscribeWith(ts) <add> .assertEmpty(); <add> <add> assertTrue(ts.isCancelled()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Action action = mock(Action.class); <add> <add> Flowable.fromCompletable(Completable.fromAction(action)) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Action action = mock(Action.class); <add> <add> Flowable.fromCompletable(Completable.fromAction(action)) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromMaybeTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.subjects.MaybeSubject; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.TestSubscriberEx; <add> <add>public class FlowableFromMaybeTest extends RxJavaTest { <add> <add> @Test <add> public void success() { <add> Flowable.fromMaybe(Maybe.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void empty() { <add> Flowable.fromMaybe(Maybe.empty().hide()) <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void error() { <add> Flowable.fromMaybe(Maybe.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void cancelComposes() { <add> MaybeSubject<Integer> ms = MaybeSubject.create(); <add> <add> TestSubscriber<Integer> ts = Flowable.fromMaybe(ms) <add> .test(); <add> <add> ts.assertEmpty(); <add> <add> assertTrue(ms.hasObservers()); <add> <add> ts.cancel(); <add> <add> assertFalse(ms.hasObservers()); <add> } <add> <add> @Test <add> public void asyncFusion() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Flowable.fromMaybe(Maybe.just(1)) <add> .subscribe(ts); <add> <add> ts <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(1); <add> } <add> <add> @Test <add> public void syncFusionRejected() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Flowable.fromMaybe(Maybe.just(1)) <add> .subscribe(ts); <add> <add> ts <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.NONE) <add> .assertResult(1); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromObservableTest.java <ide> public void error() { <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <add> <add> @Test <add> public void all() { <add> for (BackpressureStrategy mode : BackpressureStrategy.values()) { <add> Flowable.fromObservable(Observable.range(1, 5), mode) <add> .test() <add> .withTag("mode: " + mode) <add> .assertResult(1, 2, 3, 4, 5); <add> } <add> } <ide> } <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromRunnableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class FlowableFromRunnableTest extends RxJavaTest { <add> @Test <add> public void fromRunnable() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Runnable run = new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Flowable.fromRunnable(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Flowable.fromRunnable(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Flowable<Object> source = Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableThrows() { <add> Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> throw new UnsupportedOperationException(); <add> } <add> }) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Test <add> public void callable() throws Throwable { <add> final int[] counter = { 0 }; <add> <add> Flowable<Void> m = Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> counter[0]++; <add> } <add> }); <add> <add> assertTrue(m.getClass().toString(), m instanceof Supplier); <add> <add> assertNull(((Supplier<Void>)m).get()); <add> <add> assertEquals(1, counter[0]); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestSubscriber<Object> ts = Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> cdl1.countDown(); <add> try { <add> cdl2.await(5, TimeUnit.SECONDS); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> throw new TestException(e); <add> } <add> } <add> }).subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> ts.cancel(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, TestException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Runnable run = mock(Runnable.class); <add> <add> Flowable.fromRunnable(run) <add> .test(1L, true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestSubscriber<Object> ts = new TestSubscriber<>(); <add> <add> Flowable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> ts.cancel(); <add> } <add> }) <add> .subscribeWith(ts) <add> .assertEmpty(); <add> <add> assertTrue(ts.isCancelled()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Runnable action = mock(Runnable.class); <add> <add> Flowable.fromRunnable(action) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestSubscriberEx<Object> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Runnable action = mock(Runnable.class); <add> <add> Flowable.fromRunnable(action) <add> .subscribe(ts); <add> <add> ts.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableFromSingleTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.flowable; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.subjects.SingleSubject; <add>import io.reactivex.rxjava3.subscribers.TestSubscriber; <add>import io.reactivex.rxjava3.testsupport.TestSubscriberEx; <add> <add>public class FlowableFromSingleTest extends RxJavaTest { <add> <add> @Test <add> public void success() { <add> Flowable.fromSingle(Single.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void error() { <add> Flowable.fromSingle(Single.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void cancelComposes() { <add> SingleSubject<Integer> ms = SingleSubject.create(); <add> <add> TestSubscriber<Integer> ts = Flowable.fromSingle(ms) <add> .test(); <add> <add> ts.assertEmpty(); <add> <add> assertTrue(ms.hasObservers()); <add> <add> ts.cancel(); <add> <add> assertFalse(ms.hasObservers()); <add> } <add> <add> @Test <add> public void asyncFusion() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Flowable.fromSingle(Single.just(1)) <add> .subscribe(ts); <add> <add> ts <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(1); <add> } <add> <add> @Test <add> public void syncFusionRejected() { <add> TestSubscriberEx<Integer> ts = new TestSubscriberEx<>(); <add> ts.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Flowable.fromSingle(Single.just(1)) <add> .subscribe(ts); <add> <add> ts <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.NONE) <add> .assertResult(1); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFromObservableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.maybe; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add> <add>public class MaybeFromObservableTest extends RxJavaTest { <add> <add> @Test <add> public void empty() { <add> Maybe.fromObservable(Observable.empty().hide()) <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void just() { <add> Maybe.fromObservable(Observable.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void range() { <add> Maybe.fromObservable(Observable.range(1, 5).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void error() { <add> Maybe.fromObservable(Observable.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeFromPubisherTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.maybe; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add> <add>public class MaybeFromPubisherTest extends RxJavaTest { <add> <add> @Test <add> public void empty() { <add> Maybe.fromPublisher(Flowable.empty().hide()) <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void just() { <add> Maybe.fromPublisher(Flowable.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void range() { <add> Maybe.fromPublisher(Flowable.range(1, 5).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void error() { <add> Maybe.fromPublisher(Flowable.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromActionTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class ObservableFromActionTest extends RxJavaTest { <add> @Test <add> public void fromAction() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Action run = new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Observable.fromAction(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Observable.fromAction(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable<Object> source = Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromActionThrows() { <add> Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> throw new UnsupportedOperationException(); <add> } <add> }) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Test <add> public void callable() throws Throwable { <add> final int[] counter = { 0 }; <add> <add> Observable<Void> m = Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> counter[0]++; <add> } <add> }); <add> <add> assertTrue(m.getClass().toString(), m instanceof Supplier); <add> <add> assertNull(((Supplier<Void>)m).get()); <add> <add> assertEquals(1, counter[0]); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestObserver<Object> to = Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> cdl1.countDown(); <add> cdl2.await(5, TimeUnit.SECONDS); <add> } <add> }).subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> to.dispose(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, InterruptedException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Action run = mock(Action.class); <add> <add> Observable.fromAction(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<>(); <add> <add> Observable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> to.dispose(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Action action = mock(Action.class); <add> <add> Observable.fromAction(action) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Action action = mock(Action.class); <add> <add> Observable.fromAction(action) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromCompletableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.functions.*; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class ObservableFromCompletableTest extends RxJavaTest { <add> @Test <add> public void fromCompletable() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> })) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Action run = new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Observable.fromCompletable(Completable.fromAction(run)) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Observable.fromCompletable(Completable.fromAction(run)) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable<Object> source = Observable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> atomicInteger.incrementAndGet(); <add> } <add> })); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromCompletableThrows() { <add> Observable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> throw new UnsupportedOperationException(); <add> } <add> })) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestObserver<Object> to = Observable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> cdl1.countDown(); <add> cdl2.await(5, TimeUnit.SECONDS); <add> } <add> })).subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> to.dispose(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, InterruptedException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Action run = mock(Action.class); <add> <add> Observable.fromCompletable(Completable.fromAction(run)) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<>(); <add> <add> Observable.fromCompletable(Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> to.dispose(); <add> } <add> })) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Action action = mock(Action.class); <add> <add> Observable.fromCompletable(Completable.fromAction(action)) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Action action = mock(Action.class); <add> <add> Observable.fromCompletable(Completable.fromAction(action)) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromMaybeTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.subjects.MaybeSubject; <add>import io.reactivex.rxjava3.testsupport.TestObserverEx; <add> <add>public class ObservableFromMaybeTest extends RxJavaTest { <add> <add> @Test <add> public void success() { <add> Observable.fromMaybe(Maybe.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void empty() { <add> Observable.fromMaybe(Maybe.empty().hide()) <add> .test() <add> .assertResult(); <add> } <add> <add> @Test <add> public void error() { <add> Observable.fromMaybe(Maybe.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void cancelComposes() { <add> MaybeSubject<Integer> ms = MaybeSubject.create(); <add> <add> TestObserver<Integer> to = Observable.fromMaybe(ms) <add> .test(); <add> <add> to.assertEmpty(); <add> <add> assertTrue(ms.hasObservers()); <add> <add> to.dispose(); <add> <add> assertFalse(ms.hasObservers()); <add> } <add> <add> @Test <add> public void asyncFusion() { <add> TestObserverEx<Integer> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Observable.fromMaybe(Maybe.just(1)) <add> .subscribe(to); <add> <add> to <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(1); <add> } <add> <add> @Test <add> public void syncFusionRejected() { <add> TestObserverEx<Integer> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Observable.fromMaybe(Maybe.just(1)) <add> .subscribe(to); <add> <add> to <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.NONE) <add> .assertResult(1); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromRunnableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.List; <add>import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicInteger; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.functions.Supplier; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.plugins.RxJavaPlugins; <add>import io.reactivex.rxjava3.schedulers.Schedulers; <add>import io.reactivex.rxjava3.testsupport.*; <add> <add>public class ObservableFromRunnableTest extends RxJavaTest { <add> @Test <add> public void fromRunnable() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableTwice() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Runnable run = new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }; <add> <add> Observable.fromRunnable(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> <add> Observable.fromRunnable(run) <add> .test() <add> .assertResult(); <add> <add> assertEquals(2, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableInvokesLazy() { <add> final AtomicInteger atomicInteger = new AtomicInteger(); <add> <add> Observable<Object> source = Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> atomicInteger.incrementAndGet(); <add> } <add> }); <add> <add> assertEquals(0, atomicInteger.get()); <add> <add> source <add> .test() <add> .assertResult(); <add> <add> assertEquals(1, atomicInteger.get()); <add> } <add> <add> @Test <add> public void fromRunnableThrows() { <add> Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> throw new UnsupportedOperationException(); <add> } <add> }) <add> .test() <add> .assertFailure(UnsupportedOperationException.class); <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Test <add> public void callable() throws Throwable { <add> final int[] counter = { 0 }; <add> <add> Observable<Void> m = Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> counter[0]++; <add> } <add> }); <add> <add> assertTrue(m.getClass().toString(), m instanceof Supplier); <add> <add> assertNull(((Supplier<Void>)m).get()); <add> <add> assertEquals(1, counter[0]); <add> } <add> <add> @Test <add> public void noErrorLoss() throws Exception { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> final CountDownLatch cdl1 = new CountDownLatch(1); <add> final CountDownLatch cdl2 = new CountDownLatch(1); <add> <add> TestObserver<Object> to = Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> cdl1.countDown(); <add> try { <add> cdl2.await(5, TimeUnit.SECONDS); <add> } catch (InterruptedException e) { <add> e.printStackTrace(); <add> throw new TestException(e); <add> } <add> } <add> }).subscribeOn(Schedulers.single()).test(); <add> <add> assertTrue(cdl1.await(5, TimeUnit.SECONDS)); <add> <add> to.dispose(); <add> <add> int timeout = 10; <add> <add> while (timeout-- > 0 && errors.isEmpty()) { <add> Thread.sleep(100); <add> } <add> <add> TestHelper.assertUndeliverable(errors, 0, TestException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void disposedUpfront() throws Throwable { <add> Runnable run = mock(Runnable.class); <add> <add> Observable.fromRunnable(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<>(); <add> <add> Observable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> to.dispose(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void asyncFused() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Runnable action = mock(Runnable.class); <add> <add> Observable.fromRunnable(action) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add> <add> @Test <add> public void syncFusedRejected() throws Throwable { <add> TestObserverEx<Object> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Runnable action = mock(Runnable.class); <add> <add> Observable.fromRunnable(action) <add> .subscribe(to); <add> <add> to.assertFusionMode(QueueFuseable.NONE) <add> .assertResult(); <add> <add> verify(action).run(); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromSingleTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.observable; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.internal.fuseable.QueueFuseable; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.subjects.SingleSubject; <add>import io.reactivex.rxjava3.testsupport.TestObserverEx; <add> <add>public class ObservableFromSingleTest extends RxJavaTest { <add> <add> @Test <add> public void success() { <add> Observable.fromSingle(Single.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void error() { <add> Observable.fromSingle(Single.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void cancelComposes() { <add> SingleSubject<Integer> ms = SingleSubject.create(); <add> <add> TestObserver<Integer> to = Observable.fromSingle(ms) <add> .test(); <add> <add> to.assertEmpty(); <add> <add> assertTrue(ms.hasObservers()); <add> <add> to.dispose(); <add> <add> assertFalse(ms.hasObservers()); <add> } <add> <add> @Test <add> public void asyncFusion() { <add> TestObserverEx<Integer> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.ASYNC); <add> <add> Observable.fromSingle(Single.just(1)) <add> .subscribe(to); <add> <add> to <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.ASYNC) <add> .assertResult(1); <add> } <add> <add> @Test <add> public void syncFusionRejected() { <add> TestObserverEx<Integer> to = new TestObserverEx<>(); <add> to.setInitialFusionMode(QueueFuseable.SYNC); <add> <add> Observable.fromSingle(Single.just(1)) <add> .subscribe(to); <add> <add> to <add> .assertFuseable() <add> .assertFusionMode(QueueFuseable.NONE) <add> .assertResult(1); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/operators/single/SingleFromMaybeTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.rxjava3.internal.operators.single; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.NoSuchElementException; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.rxjava3.core.*; <add>import io.reactivex.rxjava3.exceptions.TestException; <add>import io.reactivex.rxjava3.observers.TestObserver; <add>import io.reactivex.rxjava3.subjects.MaybeSubject; <add> <add>public class SingleFromMaybeTest extends RxJavaTest { <add> <add> @Test <add> public void success() { <add> Single.fromMaybe(Maybe.just(1).hide()) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void empty() { <add> Single.fromMaybe(Maybe.empty().hide()) <add> .test() <add> .assertFailure(NoSuchElementException.class); <add> } <add> <add> @Test <add> public void emptyDefault() { <add> Single.fromMaybe(Maybe.empty().hide(), 1) <add> .test() <add> .assertResult(1); <add> } <add> <add> @Test <add> public void error() { <add> Single.fromMaybe(Maybe.error(new TestException()).hide()) <add> .test() <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void cancelComposes() { <add> MaybeSubject<Integer> ms = MaybeSubject.create(); <add> <add> TestObserver<Integer> to = Single.fromMaybe(ms) <add> .test(); <add> <add> to.assertEmpty(); <add> <add> assertTrue(ms.hasObservers()); <add> <add> to.dispose(); <add> <add> assertFalse(ms.hasObservers()); <add> } <add>} <ide><path>src/test/java/io/reactivex/rxjava3/internal/util/OperatorMatrixGenerator.java <ide> public static void main(String[] args) throws IOException { <ide> Map<String, Integer> notesMap = new HashMap<>(); <ide> List<String> notesList = new ArrayList<>(); <ide> List<String> tbdList = new ArrayList<>(); <add> int[] counters = new int[CLASSES.length]; <ide> <ide> for (String operatorName : sortedOperators) { <ide> out.print("<a name='"); <ide> out.print(operatorName); <ide> out.print("'></a>`"); <ide> out.print(operatorName); <ide> out.print("`|"); <add> int m = 0; <ide> for (Class<?> clazz : CLASSES) { <ide> if (operatorMap.get(clazz).contains(operatorName)) { <ide> out.print(PRESENT); <add> counters[m]++; <ide> } else { <ide> String notes = findNotes(clazz.getSimpleName(), operatorName); <ide> if (notes != null) { <ide> public static void main(String[] args) throws IOException { <ide> } <ide> } <ide> out.print("|"); <add> m++; <ide> } <ide> out.println(); <ide> } <add> out.print("<a name='total'></a>**"); <add> out.print(sortedOperators.size()); <add> out.print(" operators** |"); <add> for (int m = 0; m < counters.length; m++) { <add> out.print(" **"); <add> out.print(counters[m]); <add> out.print("** |"); <add> } <add> out.println(); <ide> <ide> if (!notesList.isEmpty()) { <ide> out.println(); <ide> static String findNotes(String clazzName, String operatorName) { <ide> " C flattenStreamAsObservable Always empty thus no items to map.", <ide> " MSC forEach Use [`subscribe()`](#subscribe).", <ide> " MSC forEachWhile Use [`subscribe()`](#subscribe).", <add> " S fromAction Never empty.", <ide> " M fromArray At most one item. Use [`just()`](#just) or [`empty()`](#empty).", <ide> " S fromArray Always one item. Use [`just()`](#just).", <ide> " C fromArray Always empty. Use [`complete()`](#complete).", <ide> static String findNotes(String clazzName, String operatorName) { <ide> " O fromObservable Use [`wrap()`](#wrap).", <ide> " S fromOptional Always one item. Use [`just()`](#just).", <ide> " C fromOptional Always empty. Use [`complete()`](#complete).", <add> " S fromRunnable Never empty.", <ide> " S fromSingle Use [`wrap()`](#wrap).", <ide> " M fromStream At most one item. Use [`just()`](#just) or [`empty()`](#empty).", <ide> " S fromStream Always one item. Use [`just()`](#just).", <ide><path>src/test/java/io/reactivex/rxjava3/validators/InternalWrongNaming.java <ide> static void checkInternalOperatorNaming(String baseClassName, String consumerCla <ide> fail.append("java.lang.RuntimeException: " + g.getName() + " mentions " + consumerClassName) <ide> .append("\r\n at io.reactivex.internal.operators.") <ide> .append(baseClassName.toLowerCase()).append(".").append(g.getName().replace(".java", "")) <del> .append(" (").append(g.getName()).append(":").append(i + 1).append(")\r\n\r\n"); <add> .append(".method(").append(g.getName()).append(":").append(i + 1).append(")\r\n\r\n"); <ide> <ide> count++; <ide> } <ide> public void flowableNoObserver() throws Exception { <ide> "FlowableCountSingle", <ide> "FlowableElementAtMaybe", <ide> "FlowableElementAtSingle", <add> "FlowableElementAtMaybePublisher", <add> "FlowableElementAtSinglePublisher", <add> "FlowableFromCompletable", <ide> "FlowableSingleSingle", <ide> "FlowableSingleMaybe", <ide> "FlowableLastMaybe",
44
Text
Text
update the shape of y_train and y_test
6b8a3bcd79beb264794ea72fd7a86c64c3f27736
<ide><path>docs/templates/datasets.md <ide> from keras.datasets import cifar10 <ide> - __Returns:__ <ide> - 2 tuples: <ide> - __x_train, x_test__: uint8 array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the `image_data_format` backend setting of either `channels_first` or `channels_last` respectively. <del> - __y_train, y_test__: uint8 array of category labels (integers in range 0-9) with shape (num_samples,). <add> - __y_train, y_test__: uint8 array of category labels (integers in range 0-9) with shape (num_samples, 1). <ide> <ide> <ide> --- <ide> from keras.datasets import cifar100 <ide> - __Returns:__ <ide> - 2 tuples: <ide> - __x_train, x_test__: uint8 array of RGB image data with shape (num_samples, 3, 32, 32) or (num_samples, 32, 32, 3) based on the `image_data_format` backend setting of either `channels_first` or `channels_last` respectively. <del> - __y_train, y_test__: uint8 array of category labels with shape (num_samples,). <add> - __y_train, y_test__: uint8 array of category labels with shape (num_samples, 1). <ide> <ide> - __Arguments:__ <ide>
1
Python
Python
fix vector linkage
5a7fd0fd3683fb5949f11e81109853020113ca1e
<ide><path>spacy/language.py <ide> from .lang.lex_attrs import LEX_ATTRS <ide> from . import util <ide> from .scorer import Scorer <add>from ._ml import link_vectors_to_models <ide> <ide> <ide> class BaseDefaults(object): <ide> def begin_training(self, get_gold_tuples=None, **cfg): <ide> self.vocab.vectors.data) <ide> else: <ide> device = None <add> link_vectors_to_models(self.vocab) <ide> for proc in self.pipeline: <ide> if hasattr(proc, 'begin_training'): <ide> context = proc.begin_training(get_gold_tuples(),
1
PHP
PHP
add instanceconfig to consolehelpers
9791dcf159bd24086697cb518babea6c2b7baa78
<ide><path>src/Console/ConsoleIo.php <ide> public function setLoggers($enable) <ide> * object has not already been loaded, it will be loaded and constructed. <ide> * <ide> * @param string $name The name of the helper to render <del> * @return Cake\Console\Helper The created helper instance. <add> * @param array $settings Configuration data for the helper. <add> * @return \Cake\Console\Helper The created helper instance. <ide> */ <del> public function helper($name) <add> public function helper($name, array $settings = []) <ide> { <ide> $name = ucfirst($name); <del> return $this->_helpers->load($name); <add> return $this->_helpers->load($name, $settings); <ide> } <ide> <ide> /** <ide><path>src/Console/Helper.php <ide> namespace Cake\Console; <ide> <ide> use Cake\Console\ConsoleIo; <add>use Cake\Core\InstanceConfigTrait; <ide> <ide> /** <ide> * Base class for Helpers. <ide> */ <ide> abstract class Helper <ide> { <add> use InstanceConfigTrait; <add> <add> /** <add> * Default config for this helper. <add> * <add> * @var array <add> */ <add> protected $_defaultConfig = []; <add> <ide> /** <del> * Constructor <add> * Constructor. <ide> * <del> * @param \Cake\Console\ConsoleIo $io An io instance. <add> * @param \Cake\Console\ConsoleIo $io The ConsoleIo instance to use. <add> * @param array $config The settings for this helper. <ide> */ <del> public function __construct(ConsoleIo $io) <add> public function __construct(ConsoleIo $io, array $config = []) <ide> { <ide> $this->_io = $io; <add> $this->config($config); <ide> } <ide> <ide> /** <ide><path>src/Console/HelperRegistry.php <ide> protected function _throwMissingClassError($class, $plugin) <ide> */ <ide> protected function _create($class, $alias, $settings) <ide> { <del> return new $class($this->_io); <add> return new $class($this->_io, $settings); <ide> } <ide> } <ide><path>tests/TestCase/Console/HelperRegistryTest.php <ide> public function tearDown() <ide> } <ide> <ide> /** <del> * test triggering callbacks on loaded tasks <add> * test loading helpers. <ide> * <ide> * @return void <ide> */ <ide> public function testLoad() <ide> } <ide> <ide> /** <del> * test missingtask exception <add> * test triggering callbacks on loaded helpers <add> * <add> * @return void <add> */ <add> public function testLoadWithConfig() <add> { <add> $result = $this->helpers->load('Simple', ['key' => 'value']); <add> $this->assertEquals('value', $result->config('key')); <add> } <add> <add> /** <add> * test missing helper exception <ide> * <ide> * @expectedException \Cake\Console\Exception\MissingHelperException <ide> * @return void
4
PHP
PHP
update some grammar in controller
49bb441cefa648f2f20587fe6dd854ac66ac21e1
<ide><path>lib/Cake/Controller/Controller.php <ide> * <ide> * Controllers should provide a number of 'action' methods. These are public methods on the controller <ide> * that are not prefixed with a '_' and not part of Controller. Each action serves as an endpoint for <del> * performing a specific action on a resource or collection of resources. For example adding or editing a new <add> * performing a specific action on a resource or collection of resources. For example: adding or editing a new <ide> * object, or listing a set of objects. <ide> * <ide> * You can access request parameters, using `$this->request`. The request object contains all the POST, GET and FILES <ide> class Controller extends Object implements CakeEventListener { <ide> <ide> /** <ide> * Holds current methods of the controller. This is a list of all the methods reachable <del> * via URL. Modifying this array, will allow you to change which methods can be reached. <add> * via URL. Modifying this array will allow you to change which methods can be reached. <ide> * <ide> * @var array <ide> */ <ide> class Controller extends Object implements CakeEventListener { <ide> public $modelKey = null; <ide> <ide> /** <del> * Holds any validation errors produced by the last call of the validateErrors() method/ <add> * Holds any validation errors produced by the last call of the validateErrors() method. <ide> * <ide> * @var array Validation errors, or false if none <ide> */ <ide> protected function _mergeUses($merge) { <ide> } <ide> <ide> /** <del> * Returns a list of all events that will fire in the controller during it's lifecycle. <add> * Returns a list of all events that will fire in the controller during its lifecycle. <ide> * You can override this function to add you own listener callbacks <ide> * <ide> * @return array
1
Mixed
Text
add docs section for spacy.cli.train.train
2fd8d616e77cd48a60007a4c64ca49d5833c1fee
<ide><path>spacy/cli/train.py <del>from typing import Optional, Dict, Any <add>from typing import Optional, Dict, Any, Union <ide> from pathlib import Path <ide> from wasabi import msg <ide> import typer <ide> def train_cli( <ide> <ide> <ide> def train( <del> config_path: Path, <del> output_path: Optional[Path] = None, <add> config_path: Union[str, Path], <add> output_path: Optional[Union[str, Path]] = None, <ide> *, <ide> use_gpu: int = -1, <ide> overrides: Dict[str, Any] = util.SimpleFrozenDict(), <ide> ): <add> config_path = util.ensure_path(config_path) <add> output_path = util.ensure_path(output_path) <ide> # Make sure all files and paths exists if they are needed <ide> if not config_path or (str(config_path) != "-" and not config_path.exists()): <ide> msg.fail("Config file not found", config_path, exits=1) <ide><path>website/docs/api/cli.md <ide> $ python -m spacy train [config_path] [--output] [--code] [--verbose] [--gpu-id] <ide> | overrides | Config parameters to override. Should be options starting with `--` that correspond to the config section and value to override, e.g. `--paths.train ./train.spacy`. ~~Any (option/flag)~~ | <ide> | **CREATES** | The final trained pipeline and the best trained pipeline. | <ide> <add>### Calling the training function from Python {#train-function new="3.2"} <add> <add>The training CLI exposes a `train` helper function that lets you run the <add>training just like `spacy train`. Usually it's easier to use the command line <add>directly, but if you need to kick off training from code this is how to do it. <add> <add>> #### Example <add>> <add>> ```python <add>> from spacy.cli.train import train <add>> <add>> train("./config.cfg", overrides={"paths.train": "./train.spacy", "paths.dev": "./dev.spacy"}) <add>> <add>> ``` <add> <add>| Name | Description | <add>| -------------- | ----------------------------------------------------------------------------------------------------------------------------- | <add>| `config_path` | Path to the config to use for training. ~~Union[str, Path]~~ | <add>| `output_path` | Optional name of directory to save output model in. If not provided a model will not be saved. ~~Optional[Union[str, Path]]~~ | <add>| _keyword-only_ | | <add>| `use_gpu` | Which GPU to use. Defaults to -1 for no GPU. ~~int~~ | <add>| `overrides` | Values to override config settings. ~~Dict[str, Any]~~ | <add> <ide> ## pretrain {#pretrain new="2.1" tag="command,experimental"} <ide> <ide> Pretrain the "token to vector" ([`Tok2vec`](/api/tok2vec)) layer of pipeline <ide><path>website/docs/api/top-level.md <ide> from the specified model. Intended for use in `[initialize.before_init]`. <ide> > after_pipeline_creation = {"@callbacks":"spacy.models_with_nvtx_range.v1"} <ide> > ``` <ide> <del>Recursively wrap the models in each pipe using [NVTX](https://nvidia.github.io/NVTX/) <del>range markers. These markers aid in GPU profiling by attributing specific operations <del>to a ~~Model~~'s forward or backprop passes. <add>Recursively wrap the models in each pipe using <add>[NVTX](https://nvidia.github.io/NVTX/) range markers. These markers aid in GPU <add>profiling by attributing specific operations to a ~~Model~~'s forward or <add>backprop passes. <ide> <ide> | Name | Description | <del>|------------------|------------------------------------------------------------------------------------------------------------------------------| <add>| ---------------- | ---------------------------------------------------------------------------------------------------------------------------- | <ide> | `forward_color` | Color identifier for forward passes. Defaults to `-1`. ~~int~~ | <ide> | `backprop_color` | Color identifier for backpropagation passes. Defaults to `-1`. ~~int~~ | <ide> | **CREATES** | A function that takes the current `nlp` and wraps forward/backprop passes in NVTX ranges. ~~Callable[[Language], Language]~~ | <ide> <del> <ide> ## Training data and alignment {#gold source="spacy/training"} <ide> <ide> ### training.offsets_to_biluo_tags {#offsets_to_biluo_tags tag="function"} <ide><path>website/docs/usage/training.md <ide> fly without having to save to and load from disk. <ide> $ python -m spacy init config - --lang en --pipeline ner,textcat --optimize accuracy | python -m spacy train - --paths.train ./corpus/train.spacy --paths.dev ./corpus/dev.spacy <ide> ``` <ide> <del><!-- TODO: add reference to Prodigy's commands once Prodigy nightly is available --> <del> <ide> ### Using variable interpolation {#config-interpolation} <ide> <ide> Another very useful feature of the config system is that it supports variable <ide> workers are stuck waiting for it to complete before they can continue. <ide> <ide> ## Internal training API {#api} <ide> <del><Infobox variant="warning"> <add><Infobox variant="danger"> <ide> <ide> spaCy gives you full control over the training loop. However, for most use <ide> cases, it's recommended to train your pipelines via the <ide> typically give you everything you need to train fully custom pipelines with <ide> <ide> </Infobox> <ide> <add>### Training from a Python script {#api-train new="3.2"} <add> <add>If you want to run the training from a Python script instead of using the <add>[`spacy train`](/api/cli#train) CLI command, you can call into the <add>[`train`](/api/cli#train-function) helper function directly. It takes the path <add>to the config file, an optional output directory and an optional dictionary of <add>[config overrides](#config-overrides). <add> <add>```python <add>from spacy.cli.train import train <add> <add>train("./config.cfg", overrides={"paths.train": "./train.spacy", "paths.dev": "./dev.spacy"}) <add>``` <add> <add>### Internal training loop API {#api-loop} <add> <add><Infobox variant="warning"> <add> <add>This section documents how the training loop and updates to the `nlp` object <add>work internally. You typically shouldn't have to implement this in Python unless <add>you're writing your own trainable components. To train a pipeline, use <add>[`spacy train`](/api/cli#train) or the [`train`](/api/cli#train-function) helper <add>function instead. <add> <add></Infobox> <add> <ide> The [`Example`](/api/example) object contains annotated training data, also <ide> called the **gold standard**. It's initialized with a [`Doc`](/api/doc) object <ide> that will hold the predictions, and another `Doc` object that holds the
4
Javascript
Javascript
remove deprecated argument
77dee25efd2fb114a56e83a165a97fef22c68316
<ide><path>benchmark/dns/lookup.js <ide> const common = require('../common.js'); <ide> const lookup = require('dns').lookup; <ide> <ide> const bench = common.createBenchmark(main, { <del> name: ['', '127.0.0.1', '::1'], <add> name: ['127.0.0.1', '::1'], <ide> all: ['true', 'false'], <ide> n: [5e6] <ide> });
1
Javascript
Javascript
restrict logging of errors with verbosity level
bdde3d66223181356e2101a39df15f925c11d776
<ide><path>src/shared/util.js <ide> function warn(msg) { <ide> // Fatal errors that should trigger the fallback UI and halt execution by <ide> // throwing an exception. <ide> function error(msg) { <del> // If multiple arguments were passed, pass them all to the log function. <del> if (arguments.length > 1) { <del> var logArguments = ['Error:']; <del> logArguments.push.apply(logArguments, arguments); <del> console.log.apply(console, logArguments); <del> // Join the arguments into a single string for the lines below. <del> msg = [].join.call(arguments, ' '); <del> } else { <add> if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { <ide> console.log('Error: ' + msg); <add> console.log(backtrace()); <ide> } <del> console.log(backtrace()); <ide> UnsupportedManager.notify(UNSUPPORTED_FEATURES.unknown); <ide> throw new Error(msg); <ide> }
1
Text
Text
add title and fix grammar
aff357387e8f66905253bbf46fed71ea5fd4869f
<ide><path>guide/portuguese/react/state-vs-props/index.md <ide> --- <ide> title: State vs Props <del>localeTitle: State vs Props <del>--- <ide>## State vs Props <del> <del>Quando começamos a trabalhar com os componentes do React, ouvimos frequentemente dois termos. Eles são `state` e `props` . Então, neste artigo, vamos explorar o que são e como eles diferem. <del> <del>## Estado: <del> <del>* Estado é algo que um componente possui. Pertence àquele componente particular onde é definido. Por exemplo, a idade de uma pessoa é um estado dessa pessoa. <del>* Estado é mutável. Mas isso pode ser alterado apenas pelo componente que o possui. Como eu só posso mudar minha idade, ninguém mais. <del>* Você pode alterar um estado usando `this.setState()` <del> <del>Veja o exemplo abaixo para ter uma ideia do estado: <del> <del>#### Person.js <del> <del>```javascript <del> import React from 'react'; <del> <del> class Person extends React.Component{ <del> constructor(props) { <del> super(props); <del> this.state = { <del> age:0 <del> this.incrementAge = this.incrementAge.bind(this) <del> } <del> <del> incrementAge(){ <del> this.setState({ <del> age:this.state.age + 1; <del> }); <del> } <del> <del> render(){ <del> return( <del> <div> <del> <label>My age is: {this.state.age}</label> <del> <button onClick={this.incrementAge}>Grow me older !!<button> <del> </div> <del> ); <del> } <del> } <del> <del> export default Person; <del>``` <del> <del>No exemplo acima, `age` é o estado do componente `Person` . <del> <del>## Adereços: <del> <del>* Adereços são semelhantes aos argumentos do método. Eles são passados ​​para um componente onde esse componente é usado. <del>* Adereços é imutável. Eles são somente leitura. <del> <del>Veja o exemplo abaixo para ter uma ideia de Adereços: <del> <del>#### Person.js <del> <del>```javascript <del> import React from 'react'; <del> <del> class Person extends React.Component{ <del> render(){ <del> return( <del> <div> <del> <label>I am a {this.props.character} person.</label> <del> </div> <del> ); <del> } <del> } <del> <del> export default Person; <del> <del> const person = <Person character = "good"></Person> <del>``` <del> <del>No exemplo acima, `const person = <Person character = "good"></Person>` estamos passando prop `character = "good"` prop para o componente `Person` . <del> <del>Dá saída como "Eu sou uma boa pessoa", na verdade eu sou. <del> <del>Há muito mais a aprender sobre Estado e Adereços. Muitas coisas podem ser aprendidas mergulhando na codificação. Então, sujem suas mãos codificando. <del> <del>Procure-me no [twitter,](https://twitter.com/getifyJr) se necessário. <del> <del>Codificação Feliz !!! <ide>\ No newline at end of file <add>localeTitle: Estado vs Adereços <add>--- <add> <add> <add>## Estado vs Adereços <add> <add>Quando começamos a trabalhar com os componentes do React, ouvimos frequentemente dois termos. Eles são `state` e `props`, ou `estado` e `adereços`. Então, neste artigo, vamos explorar o que são e como eles diferem. <add> <add>## Estado: <add> <add>* Estado é algo que um componente possui. Pertence àquele componente particular onde é definido. Por exemplo, a idade de uma pessoa é um estado dessa pessoa. <add>* Estado é mutável. Mas isso pode ser alterado apenas pelo componente que o possui. Como eu só posso mudar minha idade, ninguém mais. <add>* Você pode alterar um estado usando `this.setState()` <add> <add>Veja o exemplo abaixo para ter uma ideia do estado: <add> <add>#### Person.js <add> <add>```javascript <add> import React from 'react'; <add> <add> class Person extends React.Component{ <add> constructor(props) { <add> super(props); <add> this.state = { <add> age:0 <add> this.incrementAge = this.incrementAge.bind(this) <add> } <add> <add> incrementAge(){ <add> this.setState({ <add> age:this.state.age + 1; <add> }); <add> } <add> <add> render(){ <add> return( <add> <div> <add> <label>My age is: {this.state.age}</label> <add> <button onClick={this.incrementAge}>Grow me older !!<button> <add> </div> <add> ); <add> } <add> } <add> <add> export default Person; <add>``` <add> <add>No exemplo acima, `age` é o estado do componente `Person` . <add> <add>## Adereços: <add> <add>* Adereços são semelhantes aos argumentos do método. Eles são passados ​​para um componente onde esse componente é usado. <add>* Adereços são imutáveis. Eles são somente leitura. <add> <add>Veja o exemplo abaixo para ter uma ideia de Adereços: <add> <add>#### Person.js <add> <add>```javascript <add> import React from 'react'; <add> <add> class Person extends React.Component{ <add> render(){ <add> return( <add> <div> <add> <label>I am a {this.props.character} person.</label> <add> </div> <add> ); <add> } <add> } <add> <add> export default Person; <add> <add> const person = <Person character = "good"></Person> <add>``` <add> <add>No exemplo acima, `const person = <Person character = "good"></Person>` estamos passando prop `character = "good"` prop para o componente `Person` . <add> <add>Dá saída como "Eu sou uma boa pessoa", na verdade eu sou. <add> <add>Há muito mais a aprender sobre Estado e Adereços. Muitas coisas podem ser aprendidas mergulhando na codificação. Então, sujem suas mãos codificando. <add> <add>Procure-me no [twitter,](https://twitter.com/getifyJr) se necessário. <add> <add>Codificação Feliz !!!
1
Text
Text
fix a broken link
344b4bcb9578d163f8483ac7ec158d19e64e3a45
<ide><path>TRIAGING.md <ide> The following is done automatically so you don't have to worry about it: <ide> This process based on the idea of minimizing user pain <ide> [from this blog post](http://www.lostgarden.com/2008/05/improving-bug-triage-with-user-pain.html). <ide> <del>1. Open the list of [non triaged issues](https://github.com/angular/angular.js/issues?direction=desc&milestone=none&page=1&sort=created&state=open) <add>1. Open the list of [non triaged issues](https://github.com/angular/angular.js/issues?q=is%3Aopen+sort%3Acreated-desc+no%3Amilestone) <ide> * Sort by submit date, with the newest issues first <ide> * You don't have to do issues in order; feel free to pick and choose issues as you please. <ide> * You can triage older issues as well
1
Text
Text
improve chinese translation in euler-problem-2
304262a90f89aba88801551f1563dcf129d3609e
<ide><path>curriculum/challenges/chinese/08-coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers.chinese.md <ide> id: 5900f36e1000cf542c50fe81 <ide> challengeType: 5 <ide> title: 'Problem 2: Even Fibonacci Numbers' <ide> videoUrl: '' <del>localeTitle: 问题2:甚至斐波纳契数 <add>localeTitle: 问题2:斐波那契数列中的偶数 <ide> --- <ide> <ide> ## Description <del><section id="description"> Fibonacci序列中的每个新术语都是通过添加前两个术语生成的。从1和2开始,前10个术语将是: <div style="text-align: center;"> 1,2,3,5,8,13,21,34,55,89 ...... </div>通过考虑Fibonacci序列中的值不超过第<code>n</code>项的项,找到偶数项的和。 </section> <add><section id='description'> <add>在斐波那契数列中,每一项都是前两项的和(第一项和第二项除外)。如果从1和2开始,前十项是: <add><div style='text-align: center;'>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...</div> <add>求出斐波那契数列中值是偶数的项的和,至第<code>n</code>项(包括第<code>n</code>项)为止。 <add></section> <ide> <ide> ## Instructions <ide> <section id="instructions">
1
Ruby
Ruby
remove useless to_param call
df3c78296a404e83df141dbeead506e4884f2a0f
<ide><path>actionpack/lib/action_dispatch/http/url.rb <ide> def normalize_host(_host, options) <ide> if subdomain == true || !options.key?(:subdomain) <ide> return _host if options[:domain].nil? <ide> <del> host << extract_subdomain(_host, tld_length).to_param <add> host << extract_subdomain(_host, tld_length) <ide> elsif subdomain <ide> host << subdomain.to_param <ide> end
1
Text
Text
add french translation
17bfe165606d65eaab1f3cb71dc40532b520dfd5
<ide><path>threejs/lessons/fr/threejs-setup.md <del>Title: Configuration de Three.js <add>Title: Installation de Three.js <ide> Description: Comment configurer votre environnement de développement pour Three.js <del>TOC: Configuration <add>TOC: Setup <ide> <ide> Cette article fait parti d'une série consacrée à Three.js. Le premier article traité des [fondements de Three.js](threejs-fundamentals.html). <ide> Si vous ne l'avez pas encore lu, vous devriez peut-être commencer par là.
1
Javascript
Javascript
add hacks to make react art not warn from devtools
7ecff6a437bb79d0129005df782d8829a457141a
<ide><path>src/renderers/shared/stack/reconciler/ReactMultiChild.js <ide> 'use strict'; <ide> <ide> var ReactComponentEnvironment = require('ReactComponentEnvironment'); <add>var ReactInstanceMap = require('ReactInstanceMap'); <ide> var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes'); <ide> <ide> function processQueue(inst, updateQueue) { <ide> var setParentForInstrumentation = emptyFunction; <ide> var setChildrenForInstrumentation = emptyFunction; <ide> if (__DEV__) { <add> var getDebugID = function(inst) { <add> if (!inst._debugID) { <add> // Check for ART-like instances. TODO: This is silly/gross. <add> var internal; <add> if ((internal = ReactInstanceMap.get(inst))) { <add> inst = internal; <add> } <add> } <add> return inst._debugID; <add> }; <ide> setParentForInstrumentation = function(child) { <add> invariant(child._debugID != null, 'mooooooooooooooooooo'); <ide> if (child._debugID !== 0) { <del> ReactInstrumentation.debugTool.onSetParent(child._debugID, this._debugID); <add> ReactInstrumentation.debugTool.onSetParent( <add> child._debugID, <add> getDebugID(this._debugID) <add> ); <ide> } <ide> }; <ide> setChildrenForInstrumentation = function(children) { <ide> ReactInstrumentation.debugTool.onSetChildren( <del> this._debugID, <add> getDebugID(this), <ide> children ? Object.keys(children).map(key => children[key]._debugID) : [] <ide> ); <ide> };
1
Mixed
Javascript
change this -> me in source files
5fae4dd3050fbd51da13ec1f5433d7f487758763
<ide><path>docs/01-Chart-Configuration.md <ide> maintainAspectRatio | Boolean | true | Maintain the original canvas aspect ratio <ide> events | Array[String] | `["mousemove", "mouseout", "click", "touchstart", "touchmove", "touchend"]` | Events that the chart should listen to for tooltips and hovering <ide> onClick | Function | null | Called if the event is of type 'mouseup' or 'click'. Called in the context of the chart and passed an array of active elements <ide> legendCallback | Function | ` function (chart) { }` | Function to generate a legend. Receives the chart object to generate a legend from. Default implementation returns an HTML string. <add>onResize | Function | null | Called when a resize occurs. Gets passed two arguemnts: the chart instance and the new size. <ide> <ide> ### Title Configuration <ide> <ide><path>docs/09-Advanced.md <ide> Plugins will be called at the following times <ide> * End of update (before render occurs) <ide> * Start of draw <ide> * End of draw <add>* Before datasets draw <add>* After datasets draw <add>* Resize <ide> * Before an animation is started <ide> <ide> Plugins should derive from Chart.PluginBase and implement the following interface <ide> Plugins should derive from Chart.PluginBase and implement the following interfac <ide> beforeInit: function(chartInstance) { }, <ide> afterInit: function(chartInstance) { }, <ide> <add> resize: function(chartInstance, newChartSize) { }, <add> <ide> beforeUpdate: function(chartInstance) { }, <ide> afterScaleUpdate: function(chartInstance) { } <ide> afterUpdate: function(chartInstance) { }, <ide><path>src/controllers/controller.bar.js <ide> module.exports = function(Chart) { <ide> <ide> // Get the number of datasets that display bars. We use this to correctly calculate the bar width <ide> getBarCount: function getBarCount() { <add> var me = this; <ide> var barCount = 0; <del> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <del> var meta = this.chart.getDatasetMeta(datasetIndex); <del> if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) { <add> helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { <add> var meta = me.chart.getDatasetMeta(datasetIndex); <add> if (meta.bar && me.chart.isDatasetVisible(datasetIndex)) { <ide> ++barCount; <ide> } <del> }, this); <add> }, me); <ide> return barCount; <ide> }, <ide> <ide> update: function update(reset) { <del> helpers.each(this.getMeta().data, function(rectangle, index) { <del> this.updateElement(rectangle, index, reset); <del> }, this); <add> var me = this; <add> helpers.each(me.getMeta().data, function(rectangle, index) { <add> me.updateElement(rectangle, index, reset); <add> }, me); <ide> }, <ide> <ide> updateElement: function updateElement(rectangle, index, reset) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <del> var yScale = this.getScaleForId(meta.yAxisID); <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <add> var yScale = me.getScaleForId(meta.yAxisID); <ide> var scaleBase = yScale.getBasePixel(); <del> var rectangleElementOptions = this.chart.options.elements.rectangle; <add> var rectangleElementOptions = me.chart.options.elements.rectangle; <ide> var custom = rectangle.custom || {}; <del> var dataset = this.getDataset(); <add> var dataset = me.getDataset(); <ide> <ide> helpers.extend(rectangle, { <ide> // Utility <ide> _xScale: xScale, <ide> _yScale: yScale, <del> _datasetIndex: this.index, <add> _datasetIndex: me.index, <ide> _index: index, <ide> <ide> // Desired view properties <ide> _model: { <del> x: this.calculateBarX(index, this.index), <del> y: reset ? scaleBase : this.calculateBarY(index, this.index), <add> x: me.calculateBarX(index, me.index), <add> y: reset ? scaleBase : me.calculateBarY(index, me.index), <ide> <ide> // Tooltip <del> label: this.chart.data.labels[index], <add> label: me.chart.data.labels[index], <ide> datasetLabel: dataset.label, <ide> <ide> // Appearance <del> base: reset ? scaleBase : this.calculateBarBase(this.index, index), <del> width: this.calculateBarWidth(index), <add> base: reset ? scaleBase : me.calculateBarBase(me.index, index), <add> width: me.calculateBarWidth(index), <ide> backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor), <ide> borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped, <ide> borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor), <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarBase: function(datasetIndex, index) { <del> var meta = this.getMeta(); <del> var yScale = this.getScaleForId(meta.yAxisID); <add> var me = this; <add> var meta = me.getMeta(); <add> var yScale = me.getScaleForId(meta.yAxisID); <ide> var base = 0; <ide> <ide> if (yScale.options.stacked) { <del> var chart = this.chart; <add> var chart = me.chart; <ide> var datasets = chart.data.datasets; <ide> var value = datasets[datasetIndex].data[index]; <ide> <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> getRuler: function(index) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <del> var datasetCount = this.getBarCount(); <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <add> var datasetCount = me.getBarCount(); <ide> <ide> var tickWidth; <ide> <ide> module.exports = function(Chart) { <ide> var categorySpacing = (tickWidth - (tickWidth * xScale.options.categoryPercentage)) / 2; <ide> var fullBarWidth = categoryWidth / datasetCount; <ide> <del> if (xScale.ticks.length !== this.chart.data.labels.length) { <del> var perc = xScale.ticks.length / this.chart.data.labels.length; <add> if (xScale.ticks.length !== me.chart.data.labels.length) { <add> var perc = xScale.ticks.length / me.chart.data.labels.length; <ide> fullBarWidth = fullBarWidth * perc; <ide> } <ide> <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarX: function(index, datasetIndex) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <del> var barIndex = this.getBarIndex(datasetIndex); <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <add> var barIndex = me.getBarIndex(datasetIndex); <ide> <del> var ruler = this.getRuler(index); <del> var leftTick = xScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); <del> leftTick -= this.chart.isCombo ? (ruler.tickWidth / 2) : 0; <add> var ruler = me.getRuler(index); <add> var leftTick = xScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo); <add> leftTick -= me.chart.isCombo ? (ruler.tickWidth / 2) : 0; <ide> <ide> if (xScale.options.stacked) { <ide> return leftTick + (ruler.categoryWidth / 2) + ruler.categorySpacing; <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarY: function(index, datasetIndex) { <del> var meta = this.getMeta(); <del> var yScale = this.getScaleForId(meta.yAxisID); <del> var value = this.getDataset().data[index]; <add> var me = this; <add> var meta = me.getMeta(); <add> var yScale = me.getScaleForId(meta.yAxisID); <add> var value = me.getDataset().data[index]; <ide> <ide> if (yScale.options.stacked) { <ide> <ide> var sumPos = 0, <ide> sumNeg = 0; <ide> <ide> for (var i = 0; i < datasetIndex; i++) { <del> var ds = this.chart.data.datasets[i]; <del> var dsMeta = this.chart.getDatasetMeta(i); <del> if (dsMeta.bar && dsMeta.yAxisID === yScale.id && this.chart.isDatasetVisible(i)) { <add> var ds = me.chart.data.datasets[i]; <add> var dsMeta = me.chart.getDatasetMeta(i); <add> if (dsMeta.bar && dsMeta.yAxisID === yScale.id && me.chart.isDatasetVisible(i)) { <ide> if (ds.data[index] < 0) { <ide> sumNeg += ds.data[index] || 0; <ide> } else { <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> draw: function(ease) { <add> var me = this; <ide> var easingDecimal = ease || 1; <del> helpers.each(this.getMeta().data, function(rectangle, index) { <del> var d = this.getDataset().data[index]; <add> helpers.each(me.getMeta().data, function(rectangle, index) { <add> var d = me.getDataset().data[index]; <ide> if (d !== null && d !== undefined && !isNaN(d)) { <ide> rectangle.transition(easingDecimal).draw(); <ide> } <del> }, this); <add> }, me); <ide> }, <ide> <ide> setHoverStyle: function(rectangle) { <ide> module.exports = function(Chart) { <ide> <ide> Chart.controllers.horizontalBar = Chart.controllers.bar.extend({ <ide> updateElement: function updateElement(rectangle, index, reset, numBars) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <del> var yScale = this.getScaleForId(meta.yAxisID); <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <add> var yScale = me.getScaleForId(meta.yAxisID); <ide> var scaleBase = xScale.getBasePixel(); <ide> var custom = rectangle.custom || {}; <del> var dataset = this.getDataset(); <del> var rectangleElementOptions = this.chart.options.elements.rectangle; <add> var dataset = me.getDataset(); <add> var rectangleElementOptions = me.chart.options.elements.rectangle; <ide> <ide> helpers.extend(rectangle, { <ide> // Utility <ide> _xScale: xScale, <ide> _yScale: yScale, <del> _datasetIndex: this.index, <add> _datasetIndex: me.index, <ide> _index: index, <ide> <ide> // Desired view properties <ide> _model: { <del> x: reset ? scaleBase : this.calculateBarX(index, this.index), <del> y: this.calculateBarY(index, this.index), <add> x: reset ? scaleBase : me.calculateBarX(index, me.index), <add> y: me.calculateBarY(index, me.index), <ide> <ide> // Tooltip <del> label: this.chart.data.labels[index], <add> label: me.chart.data.labels[index], <ide> datasetLabel: dataset.label, <ide> <ide> // Appearance <del> base: reset ? scaleBase : this.calculateBarBase(this.index, index), <del> height: this.calculateBarHeight(index), <add> base: reset ? scaleBase : me.calculateBarBase(me.index, index), <add> height: me.calculateBarHeight(index), <ide> backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.backgroundColor, index, rectangleElementOptions.backgroundColor), <ide> borderSkipped: custom.borderSkipped ? custom.borderSkipped : rectangleElementOptions.borderSkipped, <ide> borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.borderColor, index, rectangleElementOptions.borderColor), <ide> borderWidth: custom.borderWidth ? custom.borderWidth : helpers.getValueAtIndexOrDefault(dataset.borderWidth, index, rectangleElementOptions.borderWidth) <ide> }, <ide> <ide> draw: function () { <del> <ide> var ctx = this._chart.ctx; <ide> var vm = this._view; <ide> <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarBase: function (datasetIndex, index) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <ide> var base = 0; <ide> <ide> if (xScale.options.stacked) { <ide> <del> var value = this.chart.data.datasets[datasetIndex].data[index]; <add> var value = me.chart.data.datasets[datasetIndex].data[index]; <ide> <ide> if (value < 0) { <ide> for (var i = 0; i < datasetIndex; i++) { <del> var negDS = this.chart.data.datasets[i]; <del> var negDSMeta = this.chart.getDatasetMeta(i); <del> if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(i)) { <add> var negDS = me.chart.data.datasets[i]; <add> var negDSMeta = me.chart.getDatasetMeta(i); <add> if (negDSMeta.bar && negDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) { <ide> base += negDS.data[index] < 0 ? negDS.data[index] : 0; <ide> } <ide> } <ide> } else { <ide> for (var j = 0; j < datasetIndex; j++) { <del> var posDS = this.chart.data.datasets[j]; <del> var posDSMeta = this.chart.getDatasetMeta(j); <del> if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(j)) { <add> var posDS = me.chart.data.datasets[j]; <add> var posDSMeta = me.chart.getDatasetMeta(j); <add> if (posDSMeta.bar && posDSMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(j)) { <ide> base += posDS.data[index] > 0 ? posDS.data[index] : 0; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> getRuler: function (index) { <del> var meta = this.getMeta(); <del> var yScale = this.getScaleForId(meta.yAxisID); <del> var datasetCount = this.getBarCount(); <add> var me = this; <add> var meta = me.getMeta(); <add> var yScale = me.getScaleForId(meta.yAxisID); <add> var datasetCount = me.getBarCount(); <ide> <ide> var tickHeight; <ide> if (yScale.options.type === 'category') { <ide> module.exports = function(Chart) { <ide> var categorySpacing = (tickHeight - (tickHeight * yScale.options.categoryPercentage)) / 2; <ide> var fullBarHeight = categoryHeight / datasetCount; <ide> <del> if (yScale.ticks.length !== this.chart.data.labels.length) { <del> var perc = yScale.ticks.length / this.chart.data.labels.length; <add> if (yScale.ticks.length !== me.chart.data.labels.length) { <add> var perc = yScale.ticks.length / me.chart.data.labels.length; <ide> fullBarHeight = fullBarHeight * perc; <ide> } <ide> <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarHeight: function (index) { <del> var yScale = this.getScaleForId(this.getMeta().yAxisID); <del> var ruler = this.getRuler(index); <add> var me = this; <add> var yScale = me.getScaleForId(me.getMeta().yAxisID); <add> var ruler = me.getRuler(index); <ide> return yScale.options.stacked ? ruler.categoryHeight : ruler.barHeight; <ide> }, <ide> <ide> calculateBarX: function (index, datasetIndex) { <del> var meta = this.getMeta(); <del> var xScale = this.getScaleForId(meta.xAxisID); <del> var value = this.getDataset().data[index]; <add> var me = this; <add> var meta = me.getMeta(); <add> var xScale = me.getScaleForId(meta.xAxisID); <add> var value = me.getDataset().data[index]; <ide> <ide> if (xScale.options.stacked) { <ide> <ide> var sumPos = 0, <ide> sumNeg = 0; <ide> <ide> for (var i = 0; i < datasetIndex; i++) { <del> var ds = this.chart.data.datasets[i]; <del> var dsMeta = this.chart.getDatasetMeta(i); <del> if (dsMeta.bar && dsMeta.xAxisID === xScale.id && this.chart.isDatasetVisible(i)) { <add> var ds = me.chart.data.datasets[i]; <add> var dsMeta = me.chart.getDatasetMeta(i); <add> if (dsMeta.bar && dsMeta.xAxisID === xScale.id && me.chart.isDatasetVisible(i)) { <ide> if (ds.data[index] < 0) { <ide> sumNeg += ds.data[index] || 0; <ide> } else { <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> calculateBarY: function (index, datasetIndex) { <del> var meta = this.getMeta(); <del> var yScale = this.getScaleForId(meta.yAxisID); <del> var barIndex = this.getBarIndex(datasetIndex); <del> <del> var ruler = this.getRuler(index); <del> var topTick = yScale.getPixelForValue(null, index, datasetIndex, this.chart.isCombo); <del> topTick -= this.chart.isCombo ? (ruler.tickHeight / 2) : 0; <add> var me = this; <add> var meta = me.getMeta(); <add> var yScale = me.getScaleForId(meta.yAxisID); <add> var barIndex = me.getBarIndex(datasetIndex); <add> <add> var ruler = me.getRuler(index); <add> var topTick = yScale.getPixelForValue(null, index, datasetIndex, me.chart.isCombo); <add> topTick -= me.chart.isCombo ? (ruler.tickHeight / 2) : 0; <ide> <ide> if (yScale.options.stacked) { <ide> return topTick + (ruler.categoryHeight / 2) + ruler.categorySpacing; <ide><path>src/controllers/controller.doughnut.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> update: function update(reset) { <del> var _this = this; <del> var chart = _this.chart, <add> var me = this; <add> var chart = me.chart, <ide> chartArea = chart.chartArea, <ide> opts = chart.options, <ide> arcOpts = opts.elements.arc, <ide> module.exports = function(Chart) { <ide> x: 0, <ide> y: 0 <ide> }, <del> meta = _this.getMeta(), <add> meta = me.getMeta(), <ide> cutoutPercentage = opts.cutoutPercentage, <ide> circumference = opts.circumference; <ide> <ide> module.exports = function(Chart) { <ide> chart.offsetX = offset.x * chart.outerRadius; <ide> chart.offsetY = offset.y * chart.outerRadius; <ide> <del> meta.total = _this.calculateTotal(); <add> meta.total = me.calculateTotal(); <ide> <del> _this.outerRadius = chart.outerRadius - (chart.radiusLength * _this.getRingIndex(_this.index)); <del> _this.innerRadius = _this.outerRadius - chart.radiusLength; <add> me.outerRadius = chart.outerRadius - (chart.radiusLength * me.getRingIndex(me.index)); <add> me.innerRadius = me.outerRadius - chart.radiusLength; <ide> <ide> helpers.each(meta.data, function(arc, index) { <del> _this.updateElement(arc, index, reset); <add> me.updateElement(arc, index, reset); <ide> }); <ide> }, <ide> <ide> updateElement: function(arc, index, reset) { <del> var _this = this; <del> var chart = _this.chart, <add> var me = this; <add> var chart = me.chart, <ide> chartArea = chart.chartArea, <ide> opts = chart.options, <ide> animationOpts = opts.animation, <ide> module.exports = function(Chart) { <ide> centerY = (chartArea.top + chartArea.bottom) / 2, <ide> startAngle = opts.rotation, // non reset case handled later <ide> endAngle = opts.rotation, // non reset case handled later <del> dataset = _this.getDataset(), <del> circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : _this.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)), <del> innerRadius = reset && animationOpts.animateScale ? 0 : _this.innerRadius, <del> outerRadius = reset && animationOpts.animateScale ? 0 : _this.outerRadius, <add> dataset = me.getDataset(), <add> circumference = reset && animationOpts.animateRotate ? 0 : arc.hidden ? 0 : me.calculateCircumference(dataset.data[index]) * (opts.circumference / (2.0 * Math.PI)), <add> innerRadius = reset && animationOpts.animateScale ? 0 : me.innerRadius, <add> outerRadius = reset && animationOpts.animateScale ? 0 : me.outerRadius, <ide> custom = arc.custom || {}, <ide> valueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; <ide> <ide> helpers.extend(arc, { <ide> // Utility <del> _datasetIndex: _this.index, <add> _datasetIndex: me.index, <ide> _index: index, <ide> <ide> // Desired view properties <ide> module.exports = function(Chart) { <ide> if (index === 0) { <ide> model.startAngle = opts.rotation; <ide> } else { <del> model.startAngle = _this.getMeta().data[index - 1]._model.endAngle; <add> model.startAngle = me.getMeta().data[index - 1]._model.endAngle; <ide> } <ide> <ide> model.endAngle = model.startAngle + model.circumference; <ide><path>src/controllers/controller.line.js <ide> module.exports = function(Chart) { <ide> <ide> draw: function(ease) { <ide> var me = this; <del> var meta = this.getMeta(); <add> var meta = me.getMeta(); <ide> var points = meta.data || []; <ide> var easingDecimal = ease || 1; <ide> var i, ilen; <ide><path>src/controllers/controller.polarArea.js <ide> module.exports = function(Chart) { <ide> linkScales: helpers.noop, <ide> <ide> update: function update(reset) { <del> var _this = this; <del> var chart = _this.chart; <add> var me = this; <add> var chart = me.chart; <ide> var chartArea = chart.chartArea; <del> var meta = _this.getMeta(); <add> var meta = me.getMeta(); <ide> var opts = chart.options; <ide> var arcOpts = opts.elements.arc; <ide> var minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); <ide> chart.outerRadius = Math.max((minSize - arcOpts.borderWidth / 2) / 2, 0); <ide> chart.innerRadius = Math.max(opts.cutoutPercentage ? (chart.outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); <ide> chart.radiusLength = (chart.outerRadius - chart.innerRadius) / chart.getVisibleDatasetCount(); <ide> <del> _this.outerRadius = chart.outerRadius - (chart.radiusLength * _this.index); <del> _this.innerRadius = _this.outerRadius - chart.radiusLength; <add> me.outerRadius = chart.outerRadius - (chart.radiusLength * me.index); <add> me.innerRadius = me.outerRadius - chart.radiusLength; <ide> <del> meta.count = _this.countVisibleElements(); <add> meta.count = me.countVisibleElements(); <ide> <ide> helpers.each(meta.data, function(arc, index) { <del> _this.updateElement(arc, index, reset); <add> me.updateElement(arc, index, reset); <ide> }); <ide> }, <ide> <ide> updateElement: function(arc, index, reset) { <del> var _this = this; <del> var chart = _this.chart; <add> var me = this; <add> var chart = me.chart; <ide> var chartArea = chart.chartArea; <del> var dataset = _this.getDataset(); <add> var dataset = me.getDataset(); <ide> var opts = chart.options; <ide> var animationOpts = opts.animation; <ide> var arcOpts = opts.elements.arc; <ide> module.exports = function(Chart) { <ide> var getValueAtIndexOrDefault = helpers.getValueAtIndexOrDefault; <ide> var labels = chart.data.labels; <ide> <del> var circumference = _this.calculateCircumference(dataset.data[index]); <add> var circumference = me.calculateCircumference(dataset.data[index]); <ide> var centerX = (chartArea.left + chartArea.right) / 2; <ide> var centerY = (chartArea.top + chartArea.bottom) / 2; <ide> <ide> // If there is NaN data before us, we need to calculate the starting angle correctly. <ide> // We could be way more efficient here, but its unlikely that the polar area chart will have a lot of data <ide> var visibleCount = 0; <del> var meta = _this.getMeta(); <add> var meta = me.getMeta(); <ide> for (var i = 0; i < index; ++i) { <ide> if (!isNaN(dataset.data[i]) && !meta.data[i].hidden) { <ide> ++visibleCount; <ide> module.exports = function(Chart) { <ide> <ide> helpers.extend(arc, { <ide> // Utility <del> _datasetIndex: _this.index, <add> _datasetIndex: me.index, <ide> _index: index, <ide> _scale: scale, <ide> <ide> module.exports = function(Chart) { <ide> }); <ide> <ide> // Apply border and fill style <del> _this.removeHoverStyle(arc); <add> me.removeHoverStyle(arc); <ide> <ide> arc.pivot(); <ide> }, <ide><path>src/controllers/controller.radar.js <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> update: function update(reset) { <del> var meta = this.getMeta(); <add> var me = this; <add> var meta = me.getMeta(); <ide> var line = meta.dataset; <ide> var points = meta.data; <ide> var custom = line.custom || {}; <del> var dataset = this.getDataset(); <del> var lineElementOptions = this.chart.options.elements.line; <del> var scale = this.chart.scale; <add> var dataset = me.getDataset(); <add> var lineElementOptions = me.chart.options.elements.line; <add> var scale = me.chart.scale; <ide> <ide> // Compatibility: If the properties are defined with only the old name, use those values <ide> if ((dataset.tension !== undefined) && (dataset.lineTension === undefined)) { <ide> module.exports = function(Chart) { <ide> <ide> helpers.extend(meta.dataset, { <ide> // Utility <del> _datasetIndex: this.index, <add> _datasetIndex: me.index, <ide> // Data <ide> _children: points, <ide> _loop: true, <ide> module.exports = function(Chart) { <ide> <ide> // Update Points <ide> helpers.each(points, function(point, index) { <del> this.updateElement(point, index, reset); <del> }, this); <add> me.updateElement(point, index, reset); <add> }, me); <ide> <ide> <ide> // Update bezier control points <del> this.updateBezierControlPoints(); <add> me.updateBezierControlPoints(); <ide> }, <ide> updateElement: function(point, index, reset) { <add> var me = this; <ide> var custom = point.custom || {}; <del> var dataset = this.getDataset(); <del> var scale = this.chart.scale; <del> var pointElementOptions = this.chart.options.elements.point; <add> var dataset = me.getDataset(); <add> var scale = me.chart.scale; <add> var pointElementOptions = me.chart.options.elements.point; <ide> var pointPosition = scale.getPointPositionForValue(index, dataset.data[index]); <ide> <ide> helpers.extend(point, { <ide> // Utility <del> _datasetIndex: this.index, <add> _datasetIndex: me.index, <ide> _index: index, <ide> _scale: scale, <ide> <ide> module.exports = function(Chart) { <ide> y: reset ? scale.yCenter : pointPosition.y, <ide> <ide> // Appearance <del> tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.tension, this.chart.options.elements.line.tension), <add> tension: custom.tension ? custom.tension : helpers.getValueOrDefault(dataset.tension, me.chart.options.elements.line.tension), <ide> radius: custom.radius ? custom.radius : helpers.getValueAtIndexOrDefault(dataset.pointRadius, index, pointElementOptions.radius), <ide> backgroundColor: custom.backgroundColor ? custom.backgroundColor : helpers.getValueAtIndexOrDefault(dataset.pointBackgroundColor, index, pointElementOptions.backgroundColor), <ide> borderColor: custom.borderColor ? custom.borderColor : helpers.getValueAtIndexOrDefault(dataset.pointBorderColor, index, pointElementOptions.borderColor), <ide> module.exports = function(Chart) { <ide> <ide> // Now pivot the point for animation <ide> point.pivot(); <del> }, this); <add> }); <ide> }, <ide> <ide> draw: function(ease) { <ide><path>src/core/core.animation.js <ide> module.exports = function(Chart) { <ide> dropFrames: 0, <ide> request: null, <ide> addAnimation: function(chartInstance, animationObject, duration, lazy) { <add> var me = this; <ide> <ide> if (!lazy) { <ide> chartInstance.animating = true; <ide> } <ide> <del> for (var index = 0; index < this.animations.length; ++index) { <del> if (this.animations[index].chartInstance === chartInstance) { <add> for (var index = 0; index < me.animations.length; ++index) { <add> if (me.animations[index].chartInstance === chartInstance) { <ide> // replacing an in progress animation <del> this.animations[index].animationObject = animationObject; <add> me.animations[index].animationObject = animationObject; <ide> return; <ide> } <ide> } <ide> <del> this.animations.push({ <add> me.animations.push({ <ide> chartInstance: chartInstance, <ide> animationObject: animationObject <ide> }); <ide> <ide> // If there are no animations queued, manually kickstart a digest, for lack of a better word <del> if (this.animations.length === 1) { <del> this.requestAnimationFrame(); <add> if (me.animations.length === 1) { <add> me.requestAnimationFrame(); <ide> } <ide> }, <ide> // Cancel the animation for a given chart instance <ide> module.exports = function(Chart) { <ide> } <ide> }, <ide> startDigest: function() { <add> var me = this; <ide> <ide> var startTime = Date.now(); <ide> var framesToDrop = 0; <ide> <del> if (this.dropFrames > 1) { <del> framesToDrop = Math.floor(this.dropFrames); <del> this.dropFrames = this.dropFrames % 1; <add> if (me.dropFrames > 1) { <add> framesToDrop = Math.floor(me.dropFrames); <add> me.dropFrames = me.dropFrames % 1; <ide> } <ide> <ide> var i = 0; <del> while (i < this.animations.length) { <del> if (this.animations[i].animationObject.currentStep === null) { <del> this.animations[i].animationObject.currentStep = 0; <add> while (i < me.animations.length) { <add> if (me.animations[i].animationObject.currentStep === null) { <add> me.animations[i].animationObject.currentStep = 0; <ide> } <ide> <del> this.animations[i].animationObject.currentStep += 1 + framesToDrop; <add> me.animations[i].animationObject.currentStep += 1 + framesToDrop; <ide> <del> if (this.animations[i].animationObject.currentStep > this.animations[i].animationObject.numSteps) { <del> this.animations[i].animationObject.currentStep = this.animations[i].animationObject.numSteps; <add> if (me.animations[i].animationObject.currentStep > me.animations[i].animationObject.numSteps) { <add> me.animations[i].animationObject.currentStep = me.animations[i].animationObject.numSteps; <ide> } <ide> <del> this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject); <del> if (this.animations[i].animationObject.onAnimationProgress && this.animations[i].animationObject.onAnimationProgress.call) { <del> this.animations[i].animationObject.onAnimationProgress.call(this.animations[i].chartInstance, this.animations[i]); <add> me.animations[i].animationObject.render(me.animations[i].chartInstance, me.animations[i].animationObject); <add> if (me.animations[i].animationObject.onAnimationProgress && me.animations[i].animationObject.onAnimationProgress.call) { <add> me.animations[i].animationObject.onAnimationProgress.call(me.animations[i].chartInstance, me.animations[i]); <ide> } <ide> <del> if (this.animations[i].animationObject.currentStep === this.animations[i].animationObject.numSteps) { <del> if (this.animations[i].animationObject.onAnimationComplete && this.animations[i].animationObject.onAnimationComplete.call) { <del> this.animations[i].animationObject.onAnimationComplete.call(this.animations[i].chartInstance, this.animations[i]); <add> if (me.animations[i].animationObject.currentStep === me.animations[i].animationObject.numSteps) { <add> if (me.animations[i].animationObject.onAnimationComplete && me.animations[i].animationObject.onAnimationComplete.call) { <add> me.animations[i].animationObject.onAnimationComplete.call(me.animations[i].chartInstance, me.animations[i]); <ide> } <ide> <ide> // executed the last frame. Remove the animation. <del> this.animations[i].chartInstance.animating = false; <add> me.animations[i].chartInstance.animating = false; <ide> <del> this.animations.splice(i, 1); <add> me.animations.splice(i, 1); <ide> } else { <ide> ++i; <ide> } <ide> } <ide> <ide> var endTime = Date.now(); <del> var dropFrames = (endTime - startTime) / this.frameDuration; <add> var dropFrames = (endTime - startTime) / me.frameDuration; <ide> <del> this.dropFrames += dropFrames; <add> me.dropFrames += dropFrames; <ide> <ide> // Do we have more stuff to animate? <del> if (this.animations.length > 0) { <del> this.requestAnimationFrame(); <add> if (me.animations.length > 0) { <add> me.requestAnimationFrame(); <ide> } <ide> } <ide> }; <ide><path>src/core/core.controller.js <ide> module.exports = function(Chart) { <ide> helpers.extend(Chart.Controller.prototype, { <ide> <ide> initialize: function initialize() { <add> var me = this; <ide> // Before init plugin notification <del> Chart.pluginService.notifyPlugins('beforeInit', [this]); <add> Chart.pluginService.notifyPlugins('beforeInit', [me]); <ide> <del> this.bindEvents(); <add> me.bindEvents(); <ide> <ide> // Make sure controllers are built first so that each dataset is bound to an axis before the scales <ide> // are built <del> this.ensureScalesHaveIDs(); <del> this.buildOrUpdateControllers(); <del> this.buildScales(); <del> this.updateLayout(); <del> this.resetElements(); <del> this.initToolTip(); <del> this.update(); <add> me.ensureScalesHaveIDs(); <add> me.buildOrUpdateControllers(); <add> me.buildScales(); <add> me.updateLayout(); <add> me.resetElements(); <add> me.initToolTip(); <add> me.update(); <ide> <ide> // After init plugin notification <del> Chart.pluginService.notifyPlugins('afterInit', [this]); <add> Chart.pluginService.notifyPlugins('afterInit', [me]); <ide> <del> return this; <add> return me; <ide> }, <ide> <ide> clear: function clear() { <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> resize: function resize(silent) { <del> var canvas = this.chart.canvas; <del> var newWidth = helpers.getMaximumWidth(this.chart.canvas); <del> var newHeight = (this.options.maintainAspectRatio && isNaN(this.chart.aspectRatio) === false && isFinite(this.chart.aspectRatio) && this.chart.aspectRatio !== 0) ? newWidth / this.chart.aspectRatio : helpers.getMaximumHeight(this.chart.canvas); <add> var me = this; <add> var chart = me.chart; <add> var canvas = chart.canvas; <add> var newWidth = helpers.getMaximumWidth(canvas); <add> var aspectRatio = chart.aspectRatio; <add> var newHeight = (me.options.maintainAspectRatio && isNaN(aspectRatio) === false && isFinite(aspectRatio) && aspectRatio !== 0) ? newWidth / aspectRatio : helpers.getMaximumHeight(canvas); <ide> <del> var sizeChanged = this.chart.width !== newWidth || this.chart.height !== newHeight; <add> var sizeChanged = chart.width !== newWidth || chart.height !== newHeight; <ide> <del> if (!sizeChanged) <del> return this; <add> if (!sizeChanged) { <add> return me; <add> } <add> <add> canvas.width = chart.width = newWidth; <add> canvas.height = chart.height = newHeight; <ide> <del> canvas.width = this.chart.width = newWidth; <del> canvas.height = this.chart.height = newHeight; <add> helpers.retinaScale(chart); <ide> <del> helpers.retinaScale(this.chart); <add> // Notify any plugins about the resize <add> var newSize = { width: newWidth, height: newHeight }; <add> Chart.pluginService.notifyPlugins('resize', [me, newSize]); <add> <add> // Notify of resize <add> if (me.options.onResize) { <add> me.options.onResize(me, newSize); <add> } <ide> <ide> if (!silent) { <del> this.stop(); <del> this.update(this.options.responsiveAnimationDuration); <add> me.stop(); <add> me.update(me.options.responsiveAnimationDuration); <ide> } <ide> <del> return this; <add> return me; <ide> }, <ide> <ide> ensureScalesHaveIDs: function ensureScalesHaveIDs() { <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> buildOrUpdateControllers: function buildOrUpdateControllers() { <add> var me = this; <ide> var types = []; <ide> var newControllers = []; <ide> <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> var meta = this.getDatasetMeta(datasetIndex); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> var meta = me.getDatasetMeta(datasetIndex); <ide> if (!meta.type) { <del> meta.type = dataset.type || this.config.type; <add> meta.type = dataset.type || me.config.type; <ide> } <ide> <ide> types.push(meta.type); <ide> <ide> if (meta.controller) { <ide> meta.controller.updateIndex(datasetIndex); <ide> } else { <del> meta.controller = new Chart.controllers[meta.type](this, datasetIndex); <add> meta.controller = new Chart.controllers[meta.type](me, datasetIndex); <ide> newControllers.push(meta.controller); <ide> } <del> }, this); <add> }, me); <ide> <ide> if (types.length > 1) { <ide> for (var i = 1; i < types.length; i++) { <ide> if (types[i] !== types[i - 1]) { <del> this.isCombo = true; <add> me.isCombo = true; <ide> break; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> resetElements: function resetElements() { <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> this.getDatasetMeta(datasetIndex).controller.reset(); <del> }, this); <add> var me = this; <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> me.getDatasetMeta(datasetIndex).controller.reset(); <add> }, me); <ide> }, <ide> <ide> update: function update(animationDuration, lazy) { <del> Chart.pluginService.notifyPlugins('beforeUpdate', [this]); <add> var me = this; <add> Chart.pluginService.notifyPlugins('beforeUpdate', [me]); <ide> <ide> // In case the entire data object changed <del> this.tooltip._data = this.data; <add> me.tooltip._data = me.data; <ide> <ide> // Make sure dataset controllers are updated and new controllers are reset <del> var newControllers = this.buildOrUpdateControllers(); <add> var newControllers = me.buildOrUpdateControllers(); <ide> <ide> // Make sure all dataset controllers have correct meta data counts <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> this.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); <del> }, this); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements(); <add> }, me); <ide> <del> Chart.layoutService.update(this, this.chart.width, this.chart.height); <add> Chart.layoutService.update(me, me.chart.width, me.chart.height); <ide> <ide> // Apply changes to the dataets that require the scales to have been calculated i.e BorderColor chages <del> Chart.pluginService.notifyPlugins('afterScaleUpdate', [this]); <add> Chart.pluginService.notifyPlugins('afterScaleUpdate', [me]); <ide> <ide> // Can only reset the new controllers after the scales have been updated <ide> helpers.each(newControllers, function(controller) { <ide> controller.reset(); <ide> }); <ide> <ide> // This will loop through any data and do the appropriate element update for the type <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> this.getDatasetMeta(datasetIndex).controller.update(); <del> }, this); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> me.getDatasetMeta(datasetIndex).controller.update(); <add> }, me); <ide> <ide> // Do this before render so that any plugins that need final scale updates can use it <del> Chart.pluginService.notifyPlugins('afterUpdate', [this]); <add> Chart.pluginService.notifyPlugins('afterUpdate', [me]); <ide> <del> this.render(animationDuration, lazy); <add> me.render(animationDuration, lazy); <ide> }, <ide> <ide> render: function render(duration, lazy) { <del> Chart.pluginService.notifyPlugins('beforeRender', [this]); <add> var me = this; <add> Chart.pluginService.notifyPlugins('beforeRender', [me]); <ide> <del> var animationOptions = this.options.animation; <add> var animationOptions = me.options.animation; <ide> if (animationOptions && ((typeof duration !== 'undefined' && duration !== 0) || (typeof duration === 'undefined' && animationOptions.duration !== 0))) { <ide> var animation = new Chart.Animation(); <ide> animation.numSteps = (duration || animationOptions.duration) / 16.66; //60 fps <ide> module.exports = function(Chart) { <ide> animation.onAnimationProgress = animationOptions.onProgress; <ide> animation.onAnimationComplete = animationOptions.onComplete; <ide> <del> Chart.animationService.addAnimation(this, animation, duration, lazy); <add> Chart.animationService.addAnimation(me, animation, duration, lazy); <ide> } else { <del> this.draw(); <add> me.draw(); <ide> if (animationOptions && animationOptions.onComplete && animationOptions.onComplete.call) { <del> animationOptions.onComplete.call(this); <add> animationOptions.onComplete.call(me); <ide> } <ide> } <del> return this; <add> return me; <ide> }, <ide> <ide> draw: function(ease) { <add> var me = this; <ide> var easingDecimal = ease || 1; <del> this.clear(); <add> me.clear(); <ide> <del> Chart.pluginService.notifyPlugins('beforeDraw', [this, easingDecimal]); <add> Chart.pluginService.notifyPlugins('beforeDraw', [me, easingDecimal]); <ide> <ide> // Draw all the scales <del> helpers.each(this.boxes, function(box) { <del> box.draw(this.chartArea); <del> }, this); <del> if (this.scale) { <del> this.scale.draw(); <add> helpers.each(me.boxes, function(box) { <add> box.draw(me.chartArea); <add> }, me); <add> if (me.scale) { <add> me.scale.draw(); <ide> } <ide> <del> Chart.pluginService.notifyPlugins('beforeDatasetDraw', [this, easingDecimal]); <add> Chart.pluginService.notifyPlugins('beforeDatasetDraw', [me, easingDecimal]); <ide> <ide> // Draw each dataset via its respective controller (reversed to support proper line stacking) <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> if (this.isDatasetVisible(datasetIndex)) { <del> this.getDatasetMeta(datasetIndex).controller.draw(ease); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> if (me.isDatasetVisible(datasetIndex)) { <add> me.getDatasetMeta(datasetIndex).controller.draw(ease); <ide> } <del> }, this, true); <add> }, me, true); <ide> <del> Chart.pluginService.notifyPlugins('afterDatasetDraw', [this, easingDecimal]); <add> Chart.pluginService.notifyPlugins('afterDatasetDraw', [me, easingDecimal]); <ide> <ide> // Finally draw the tooltip <del> this.tooltip.transition(easingDecimal).draw(); <add> me.tooltip.transition(easingDecimal).draw(); <ide> <del> Chart.pluginService.notifyPlugins('afterDraw', [this, easingDecimal]); <add> Chart.pluginService.notifyPlugins('afterDraw', [me, easingDecimal]); <ide> }, <ide> <ide> // Get the single element that was clicked on <ide> // @return : An object containing the dataset index and element index of the matching element. Also contains the rectangle that was draw <ide> getElementAtEvent: function(e) { <del> var eventPosition = helpers.getRelativePosition(e, this.chart); <add> var me = this; <add> var eventPosition = helpers.getRelativePosition(e, me.chart); <ide> var elementsArray = []; <ide> <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> if (this.isDatasetVisible(datasetIndex)) { <del> var meta = this.getDatasetMeta(datasetIndex); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> if (me.isDatasetVisible(datasetIndex)) { <add> var meta = me.getDatasetMeta(datasetIndex); <ide> helpers.each(meta.data, function(element, index) { <ide> if (element.inRange(eventPosition.x, eventPosition.y)) { <ide> elementsArray.push(element); <ide> return elementsArray; <ide> } <ide> }); <ide> } <del> }, this); <add> }); <ide> <ide> return elementsArray; <ide> }, <ide> <ide> getElementsAtEvent: function(e) { <del> var eventPosition = helpers.getRelativePosition(e, this.chart); <add> var me = this; <add> var eventPosition = helpers.getRelativePosition(e, me.chart); <ide> var elementsArray = []; <ide> <ide> var found = (function() { <del> if (this.data.datasets) { <del> for (var i = 0; i < this.data.datasets.length; i++) { <del> var meta = this.getDatasetMeta(i); <del> if (this.isDatasetVisible(i)) { <add> if (me.data.datasets) { <add> for (var i = 0; i < me.data.datasets.length; i++) { <add> var meta = me.getDatasetMeta(i); <add> if (me.isDatasetVisible(i)) { <ide> for (var j = 0; j < meta.data.length; j++) { <ide> if (meta.data[j].inRange(eventPosition.x, eventPosition.y)) { <ide> return meta.data[j]; <ide> module.exports = function(Chart) { <ide> } <ide> } <ide> } <del> }).call(this); <add> }).call(me); <ide> <ide> if (!found) { <ide> return elementsArray; <ide> } <ide> <del> helpers.each(this.data.datasets, function(dataset, datasetIndex) { <del> if (this.isDatasetVisible(datasetIndex)) { <del> var meta = this.getDatasetMeta(datasetIndex); <add> helpers.each(me.data.datasets, function(dataset, datasetIndex) { <add> if (me.isDatasetVisible(datasetIndex)) { <add> var meta = me.getDatasetMeta(datasetIndex); <ide> elementsArray.push(meta.data[found._index]); <ide> } <del> }, this); <add> }, me); <ide> <ide> return elementsArray; <ide> }, <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> getDatasetMeta: function(datasetIndex) { <del> var dataset = this.data.datasets[datasetIndex]; <add> var me = this; <add> var dataset = me.data.datasets[datasetIndex]; <ide> if (!dataset._meta) { <ide> dataset._meta = {}; <ide> } <ide> <del> var meta = dataset._meta[this.id]; <add> var meta = dataset._meta[me.id]; <ide> if (!meta) { <del> meta = dataset._meta[this.id] = { <add> meta = dataset._meta[me.id] = { <ide> type: null, <ide> data: [], <ide> dataset: null, <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> destroy: function destroy() { <del> this.stop(); <del> this.clear(); <del> helpers.unbindEvents(this, this.events); <del> helpers.removeResizeListener(this.chart.canvas.parentNode); <add> var me = this; <add> me.stop(); <add> me.clear(); <add> helpers.unbindEvents(me, me.events); <add> helpers.removeResizeListener(me.chart.canvas.parentNode); <ide> <ide> // Reset canvas height/width attributes <del> var canvas = this.chart.canvas; <del> canvas.width = this.chart.width; <del> canvas.height = this.chart.height; <add> var canvas = me.chart.canvas; <add> canvas.width = me.chart.width; <add> canvas.height = me.chart.height; <ide> <ide> // if we scaled the canvas in response to a devicePixelRatio !== 1, we need to undo that transform here <del> if (this.chart.originalDevicePixelRatio !== undefined) { <del> this.chart.ctx.scale(1 / this.chart.originalDevicePixelRatio, 1 / this.chart.originalDevicePixelRatio); <add> if (me.chart.originalDevicePixelRatio !== undefined) { <add> me.chart.ctx.scale(1 / me.chart.originalDevicePixelRatio, 1 / me.chart.originalDevicePixelRatio); <ide> } <ide> <ide> // Reset to the old style since it may have been changed by the device pixel ratio changes <del> canvas.style.width = this.chart.originalCanvasStyleWidth; <del> canvas.style.height = this.chart.originalCanvasStyleHeight; <add> canvas.style.width = me.chart.originalCanvasStyleWidth; <add> canvas.style.height = me.chart.originalCanvasStyleHeight; <ide> <del> Chart.pluginService.notifyPlugins('destroy', [this]); <add> Chart.pluginService.notifyPlugins('destroy', [me]); <ide> <del> delete Chart.instances[this.id]; <add> delete Chart.instances[me.id]; <ide> }, <ide> <ide> toBase64Image: function toBase64Image() { <ide> return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments); <ide> }, <ide> <ide> initToolTip: function initToolTip() { <del> this.tooltip = new Chart.Tooltip({ <del> _chart: this.chart, <del> _chartInstance: this, <del> _data: this.data, <del> _options: this.options.tooltips <del> }, this); <add> var me = this; <add> me.tooltip = new Chart.Tooltip({ <add> _chart: me.chart, <add> _chartInstance: me, <add> _data: me.data, <add> _options: me.options.tooltips <add> }, me); <ide> }, <ide> <ide> bindEvents: function bindEvents() { <del> helpers.bindEvents(this, this.options.events, function(evt) { <del> this.eventHandler(evt); <add> var me = this; <add> helpers.bindEvents(me, me.options.events, function(evt) { <add> me.eventHandler(evt); <ide> }); <ide> }, <ide> <ide><path>src/core/core.datasetController.js <ide> module.exports = function(Chart) { <ide> dataElementType: null, <ide> <ide> initialize: function(chart, datasetIndex) { <del> this.chart = chart; <del> this.index = datasetIndex; <del> this.linkScales(); <del> this.addElements(); <add> var me = this; <add> me.chart = chart; <add> me.index = datasetIndex; <add> me.linkScales(); <add> me.addElements(); <ide> }, <ide> <ide> updateIndex: function(datasetIndex) { <ide> this.index = datasetIndex; <ide> }, <ide> <ide> linkScales: function() { <del> var meta = this.getMeta(); <del> var dataset = this.getDataset(); <add> var me = this; <add> var meta = me.getMeta(); <add> var dataset = me.getDataset(); <ide> <ide> if (meta.xAxisID === null) { <del> meta.xAxisID = dataset.xAxisID || this.chart.options.scales.xAxes[0].id; <add> meta.xAxisID = dataset.xAxisID || me.chart.options.scales.xAxes[0].id; <ide> } <ide> if (meta.yAxisID === null) { <del> meta.yAxisID = dataset.yAxisID || this.chart.options.scales.yAxes[0].id; <add> meta.yAxisID = dataset.yAxisID || me.chart.options.scales.yAxes[0].id; <ide> } <ide> }, <ide> <ide><path>src/core/core.element.js <ide> module.exports = function(Chart) { <ide> helpers.extend(this, configuration); <ide> this.initialize.apply(this, arguments); <ide> }; <add> <ide> helpers.extend(Chart.Element.prototype, { <add> <ide> initialize: function() { <ide> this.hidden = false; <ide> }, <add> <ide> pivot: function() { <del> if (!this._view) { <del> this._view = helpers.clone(this._model); <add> var me = this; <add> if (!me._view) { <add> me._view = helpers.clone(me._model); <ide> } <del> this._start = helpers.clone(this._view); <del> return this; <add> me._start = helpers.clone(me._view); <add> return me; <ide> }, <add> <ide> transition: function(ease) { <del> if (!this._view) { <del> this._view = helpers.clone(this._model); <add> var me = this; <add> <add> if (!me._view) { <add> me._view = helpers.clone(me._model); <ide> } <ide> <ide> // No animation -> No Transition <ide> if (ease === 1) { <del> this._view = this._model; <del> this._start = null; <del> return this; <add> me._view = me._model; <add> me._start = null; <add> return me; <ide> } <ide> <del> if (!this._start) { <del> this.pivot(); <add> if (!me._start) { <add> me.pivot(); <ide> } <ide> <del> helpers.each(this._model, function(value, key) { <add> helpers.each(me._model, function(value, key) { <ide> <ide> if (key[0] === '_') { <ide> // Only non-underscored properties <ide> } <ide> <ide> // Init if doesn't exist <del> else if (!this._view.hasOwnProperty(key)) { <del> if (typeof value === 'number' && !isNaN(this._view[key])) { <del> this._view[key] = value * ease; <add> else if (!me._view.hasOwnProperty(key)) { <add> if (typeof value === 'number' && !isNaN(me._view[key])) { <add> me._view[key] = value * ease; <ide> } else { <del> this._view[key] = value; <add> me._view[key] = value; <ide> } <ide> } <ide> <ide> // No unnecessary computations <del> else if (value === this._view[key]) { <add> else if (value === me._view[key]) { <ide> // It's the same! Woohoo! <ide> } <ide> <ide> // Color transitions if possible <ide> else if (typeof value === 'string') { <ide> try { <del> var color = helpers.color(this._model[key]).mix(helpers.color(this._start[key]), ease); <del> this._view[key] = color.rgbString(); <add> var color = helpers.color(me._model[key]).mix(helpers.color(me._start[key]), ease); <add> me._view[key] = color.rgbString(); <ide> } catch (err) { <del> this._view[key] = value; <add> me._view[key] = value; <ide> } <ide> } <ide> // Number transitions <ide> else if (typeof value === 'number') { <del> var startVal = this._start[key] !== undefined && isNaN(this._start[key]) === false ? this._start[key] : 0; <del> this._view[key] = ((this._model[key] - startVal) * ease) + startVal; <add> var startVal = me._start[key] !== undefined && isNaN(me._start[key]) === false ? me._start[key] : 0; <add> me._view[key] = ((me._model[key] - startVal) * ease) + startVal; <ide> } <ide> // Everything else <ide> else { <del> this._view[key] = value; <add> me._view[key] = value; <ide> } <del> }, this); <add> }, me); <ide> <del> return this; <add> return me; <ide> }, <add> <ide> tooltipPosition: function() { <ide> return { <ide> x: this._model.x, <ide> y: this._model.y <ide> }; <ide> }, <add> <ide> hasValue: function() { <ide> return helpers.isNumber(this._model.x) && helpers.isNumber(this._model.y); <ide> } <ide><path>src/core/core.legend.js <ide> module.exports = function(Chart) { <ide> return helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) { <ide> return { <ide> text: dataset.label, <del> fillStyle: dataset.backgroundColor, <add> fillStyle: (!helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]), <ide> hidden: !chart.isDatasetVisible(i), <ide> lineCap: dataset.borderCapStyle, <ide> lineDash: dataset.borderDash, <ide> module.exports = function(Chart) { <ide> <ide> beforeUpdate: noop, <ide> update: function(maxWidth, maxHeight, margins) { <add> var me = this; <ide> <ide> // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) <del> this.beforeUpdate(); <add> me.beforeUpdate(); <ide> <ide> // Absorb the master measurements <del> this.maxWidth = maxWidth; <del> this.maxHeight = maxHeight; <del> this.margins = margins; <add> me.maxWidth = maxWidth; <add> me.maxHeight = maxHeight; <add> me.margins = margins; <ide> <ide> // Dimensions <del> this.beforeSetDimensions(); <del> this.setDimensions(); <del> this.afterSetDimensions(); <add> me.beforeSetDimensions(); <add> me.setDimensions(); <add> me.afterSetDimensions(); <ide> // Labels <del> this.beforeBuildLabels(); <del> this.buildLabels(); <del> this.afterBuildLabels(); <add> me.beforeBuildLabels(); <add> me.buildLabels(); <add> me.afterBuildLabels(); <ide> <ide> // Fit <del> this.beforeFit(); <del> this.fit(); <del> this.afterFit(); <add> me.beforeFit(); <add> me.fit(); <add> me.afterFit(); <ide> // <del> this.afterUpdate(); <add> me.afterUpdate(); <ide> <del> return this.minSize; <add> return me.minSize; <ide> }, <ide> afterUpdate: noop, <ide> <ide> // <ide> <ide> beforeSetDimensions: noop, <ide> setDimensions: function() { <add> var me = this; <ide> // Set the unconstrained dimension before label rotation <del> if (this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> // Reset position before calculating rotation <del> this.width = this.maxWidth; <del> this.left = 0; <del> this.right = this.width; <add> me.width = me.maxWidth; <add> me.left = 0; <add> me.right = me.width; <ide> } else { <del> this.height = this.maxHeight; <add> me.height = me.maxHeight; <ide> <ide> // Reset position before calculating rotation <del> this.top = 0; <del> this.bottom = this.height; <add> me.top = 0; <add> me.bottom = me.height; <ide> } <ide> <ide> // Reset padding <del> this.paddingLeft = 0; <del> this.paddingTop = 0; <del> this.paddingRight = 0; <del> this.paddingBottom = 0; <add> me.paddingLeft = 0; <add> me.paddingTop = 0; <add> me.paddingRight = 0; <add> me.paddingBottom = 0; <ide> <ide> // Reset minSize <del> this.minSize = { <add> me.minSize = { <ide> width: 0, <ide> height: 0 <ide> }; <ide> module.exports = function(Chart) { <ide> <ide> beforeBuildLabels: noop, <ide> buildLabels: function() { <del> this.legendItems = this.options.labels.generateLabels.call(this, this.chart); <del> if(this.options.reverse){ <del> this.legendItems.reverse(); <add> var me = this; <add> me.legendItems = me.options.labels.generateLabels.call(me, me.chart); <add> if(me.options.reverse){ <add> me.legendItems.reverse(); <ide> } <ide> }, <ide> afterBuildLabels: noop, <ide> module.exports = function(Chart) { <ide> <ide> beforeFit: noop, <ide> fit: function() { <del> var opts = this.options; <add> var me = this; <add> var opts = me.options; <ide> var labelOpts = opts.labels; <ide> var display = opts.display; <ide> <del> var ctx = this.ctx; <add> var ctx = me.ctx; <ide> <ide> var globalDefault = Chart.defaults.global, <ide> itemOrDefault = helpers.getValueOrDefault, <ide> module.exports = function(Chart) { <ide> labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); <ide> <ide> // Reset hit boxes <del> var hitboxes = this.legendHitBoxes = []; <add> var hitboxes = me.legendHitBoxes = []; <ide> <del> var minSize = this.minSize; <del> var isHorizontal = this.isHorizontal(); <add> var minSize = me.minSize; <add> var isHorizontal = me.isHorizontal(); <ide> <ide> if (isHorizontal) { <del> minSize.width = this.maxWidth; // fill all the width <add> minSize.width = me.maxWidth; // fill all the width <ide> minSize.height = display ? 10 : 0; <ide> } else { <ide> minSize.width = display ? 10 : 0; <del> minSize.height = this.maxHeight; // fill all the height <add> minSize.height = me.maxHeight; // fill all the height <ide> } <ide> <ide> // Increase sizes here <ide> module.exports = function(Chart) { <ide> // Labels <ide> <ide> // Width of each line of legend boxes. Labels wrap onto multiple lines when there are too many to fit on one <del> var lineWidths = this.lineWidths = [0]; <del> var totalHeight = this.legendItems.length ? fontSize + (labelOpts.padding) : 0; <add> var lineWidths = me.lineWidths = [0]; <add> var totalHeight = me.legendItems.length ? fontSize + (labelOpts.padding) : 0; <ide> <ide> ctx.textAlign = "left"; <ide> ctx.textBaseline = 'top'; <ide> ctx.font = labelFont; <ide> <del> helpers.each(this.legendItems, function(legendItem, i) { <add> helpers.each(me.legendItems, function(legendItem, i) { <ide> var width = labelOpts.boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; <del> if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= this.width) { <add> if (lineWidths[lineWidths.length - 1] + width + labelOpts.padding >= me.width) { <ide> totalHeight += fontSize + (labelOpts.padding); <del> lineWidths[lineWidths.length] = this.left; <add> lineWidths[lineWidths.length] = me.left; <ide> } <ide> <ide> // Store the hitbox width and height here. Final position will be updated in `draw` <ide> module.exports = function(Chart) { <ide> }; <ide> <ide> lineWidths[lineWidths.length - 1] += width + labelOpts.padding; <del> }, this); <add> }, me); <ide> <ide> minSize.height += totalHeight; <ide> <ide> module.exports = function(Chart) { <ide> } <ide> } <ide> <del> this.width = minSize.width; <del> this.height = minSize.height; <add> me.width = minSize.width; <add> me.height = minSize.height; <ide> }, <ide> afterFit: noop, <ide> <ide> module.exports = function(Chart) { <ide> <ide> // Actualy draw the legend on the canvas <ide> draw: function() { <del> var opts = this.options; <add> var me = this; <add> var opts = me.options; <ide> var labelOpts = opts.labels; <ide> var globalDefault = Chart.defaults.global, <ide> lineDefault = globalDefault.elements.line, <del> legendWidth = this.width, <del> lineWidths = this.lineWidths; <add> legendWidth = me.width, <add> lineWidths = me.lineWidths; <ide> <ide> if (opts.display) { <del> var ctx = this.ctx, <add> var ctx = me.ctx, <ide> cursor = { <del> x: this.left + ((legendWidth - lineWidths[0]) / 2), <del> y: this.top + labelOpts.padding, <add> x: me.left + ((legendWidth - lineWidths[0]) / 2), <add> y: me.top + labelOpts.padding, <ide> line: 0 <ide> }, <ide> itemOrDefault = helpers.getValueOrDefault, <ide> module.exports = function(Chart) { <ide> labelFont = helpers.fontString(fontSize, fontStyle, fontFamily); <ide> <ide> // Horizontal <del> if (this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> // Labels <ide> ctx.textAlign = "left"; <ide> ctx.textBaseline = 'top'; <ide> module.exports = function(Chart) { <ide> ctx.font = labelFont; <ide> <ide> var boxWidth = labelOpts.boxWidth, <del> hitboxes = this.legendHitBoxes; <add> hitboxes = me.legendHitBoxes; <ide> <del> helpers.each(this.legendItems, function(legendItem, i) { <add> helpers.each(me.legendItems, function(legendItem, i) { <ide> var textWidth = ctx.measureText(legendItem.text).width, <ide> width = boxWidth + (fontSize / 2) + textWidth, <ide> x = cursor.x, <ide> module.exports = function(Chart) { <ide> if (x + width >= legendWidth) { <ide> y = cursor.y += fontSize + (labelOpts.padding); <ide> cursor.line++; <del> x = cursor.x = this.left + ((legendWidth - lineWidths[cursor.line]) / 2); <add> x = cursor.x = me.left + ((legendWidth - lineWidths[cursor.line]) / 2); <ide> } <ide> <ide> // Set the ctx for the box <ide> module.exports = function(Chart) { <ide> } <ide> <ide> cursor.x += width + (labelOpts.padding); <del> }, this); <add> }, me); <ide> } else { <ide> <ide> } <ide> module.exports = function(Chart) { <ide> <ide> // Handle an event <ide> handleEvent: function(e) { <del> var position = helpers.getRelativePosition(e, this.chart.chart), <add> var me = this; <add> var position = helpers.getRelativePosition(e, me.chart.chart), <ide> x = position.x, <ide> y = position.y, <del> opts = this.options; <add> opts = me.options; <ide> <del> if (x >= this.left && x <= this.right && y >= this.top && y <= this.bottom) { <add> if (x >= me.left && x <= me.right && y >= me.top && y <= me.bottom) { <ide> // See if we are touching one of the dataset boxes <del> var lh = this.legendHitBoxes; <add> var lh = me.legendHitBoxes; <ide> for (var i = 0; i < lh.length; ++i) { <ide> var hitBox = lh[i]; <ide> <ide> if (x >= hitBox.left && x <= hitBox.left + hitBox.width && y >= hitBox.top && y <= hitBox.top + hitBox.height) { <ide> // Touching an element <ide> if (opts.onClick) { <del> opts.onClick.call(this, e, this.legendItems[i]); <add> opts.onClick.call(me, e, me.legendItems[i]); <ide> } <ide> break; <ide> } <ide><path>src/core/core.scale.js <ide> module.exports = function(Chart) { <ide> helpers.callCallback(this.options.beforeUpdate, [this]); <ide> }, <ide> update: function(maxWidth, maxHeight, margins) { <add> var me = this; <ide> <ide> // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) <del> this.beforeUpdate(); <add> me.beforeUpdate(); <ide> <ide> // Absorb the master measurements <del> this.maxWidth = maxWidth; <del> this.maxHeight = maxHeight; <del> this.margins = helpers.extend({ <add> me.maxWidth = maxWidth; <add> me.maxHeight = maxHeight; <add> me.margins = helpers.extend({ <ide> left: 0, <ide> right: 0, <ide> top: 0, <ide> bottom: 0 <ide> }, margins); <ide> <ide> // Dimensions <del> this.beforeSetDimensions(); <del> this.setDimensions(); <del> this.afterSetDimensions(); <add> me.beforeSetDimensions(); <add> me.setDimensions(); <add> me.afterSetDimensions(); <ide> <ide> // Data min/max <del> this.beforeDataLimits(); <del> this.determineDataLimits(); <del> this.afterDataLimits(); <add> me.beforeDataLimits(); <add> me.determineDataLimits(); <add> me.afterDataLimits(); <ide> <ide> // Ticks <del> this.beforeBuildTicks(); <del> this.buildTicks(); <del> this.afterBuildTicks(); <add> me.beforeBuildTicks(); <add> me.buildTicks(); <add> me.afterBuildTicks(); <ide> <del> this.beforeTickToLabelConversion(); <del> this.convertTicksToLabels(); <del> this.afterTickToLabelConversion(); <add> me.beforeTickToLabelConversion(); <add> me.convertTicksToLabels(); <add> me.afterTickToLabelConversion(); <ide> <ide> // Tick Rotation <del> this.beforeCalculateTickRotation(); <del> this.calculateTickRotation(); <del> this.afterCalculateTickRotation(); <add> me.beforeCalculateTickRotation(); <add> me.calculateTickRotation(); <add> me.afterCalculateTickRotation(); <ide> // Fit <del> this.beforeFit(); <del> this.fit(); <del> this.afterFit(); <add> me.beforeFit(); <add> me.fit(); <add> me.afterFit(); <ide> // <del> this.afterUpdate(); <add> me.afterUpdate(); <ide> <del> return this.minSize; <add> return me.minSize; <ide> <ide> }, <ide> afterUpdate: function() { <ide> module.exports = function(Chart) { <ide> helpers.callCallback(this.options.beforeSetDimensions, [this]); <ide> }, <ide> setDimensions: function() { <add> var me = this; <ide> // Set the unconstrained dimension before label rotation <del> if (this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> // Reset position before calculating rotation <del> this.width = this.maxWidth; <del> this.left = 0; <del> this.right = this.width; <add> me.width = me.maxWidth; <add> me.left = 0; <add> me.right = me.width; <ide> } else { <del> this.height = this.maxHeight; <add> me.height = me.maxHeight; <ide> <ide> // Reset position before calculating rotation <del> this.top = 0; <del> this.bottom = this.height; <add> me.top = 0; <add> me.bottom = me.height; <ide> } <ide> <ide> // Reset padding <del> this.paddingLeft = 0; <del> this.paddingTop = 0; <del> this.paddingRight = 0; <del> this.paddingBottom = 0; <add> me.paddingLeft = 0; <add> me.paddingTop = 0; <add> me.paddingRight = 0; <add> me.paddingBottom = 0; <ide> }, <ide> afterSetDimensions: function() { <ide> helpers.callCallback(this.options.afterSetDimensions, [this]); <ide> module.exports = function(Chart) { <ide> helpers.callCallback(this.options.beforeTickToLabelConversion, [this]); <ide> }, <ide> convertTicksToLabels: function() { <add> var me = this; <ide> // Convert ticks to strings <del> this.ticks = this.ticks.map(function(numericalTick, index, ticks) { <del> if (this.options.ticks.userCallback) { <del> return this.options.ticks.userCallback(numericalTick, index, ticks); <add> me.ticks = me.ticks.map(function(numericalTick, index, ticks) { <add> if (me.options.ticks.userCallback) { <add> return me.options.ticks.userCallback(numericalTick, index, ticks); <ide> } <del> return this.options.ticks.callback(numericalTick, index, ticks); <add> return me.options.ticks.callback(numericalTick, index, ticks); <ide> }, <del> this); <add> me); <ide> }, <ide> afterTickToLabelConversion: function() { <ide> helpers.callCallback(this.options.afterTickToLabelConversion, [this]); <ide> module.exports = function(Chart) { <ide> helpers.callCallback(this.options.beforeCalculateTickRotation, [this]); <ide> }, <ide> calculateTickRotation: function() { <del> var context = this.ctx; <add> var me = this; <add> var context = me.ctx; <ide> var globalDefaults = Chart.defaults.global; <del> var optionTicks = this.options.ticks; <add> var optionTicks = me.options.ticks; <ide> <ide> //Get the width of each grid by calculating the difference <ide> //between x offsets between 0 and 1. <ide> module.exports = function(Chart) { <ide> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <ide> context.font = tickLabelFont; <ide> <del> var firstWidth = context.measureText(this.ticks[0]).width; <del> var lastWidth = context.measureText(this.ticks[this.ticks.length - 1]).width; <add> var firstWidth = context.measureText(me.ticks[0]).width; <add> var lastWidth = context.measureText(me.ticks[me.ticks.length - 1]).width; <ide> var firstRotated; <ide> <del> this.labelRotation = optionTicks.minRotation || 0; <del> this.paddingRight = 0; <del> this.paddingLeft = 0; <add> me.labelRotation = optionTicks.minRotation || 0; <add> me.paddingRight = 0; <add> me.paddingLeft = 0; <ide> <del> if (this.options.display) { <del> if (this.isHorizontal()) { <del> this.paddingRight = lastWidth / 2 + 3; <del> this.paddingLeft = firstWidth / 2 + 3; <add> if (me.options.display) { <add> if (me.isHorizontal()) { <add> me.paddingRight = lastWidth / 2 + 3; <add> me.paddingLeft = firstWidth / 2 + 3; <ide> <del> if (!this.longestTextCache) { <del> this.longestTextCache = {}; <add> if (!me.longestTextCache) { <add> me.longestTextCache = {}; <ide> } <del> var originalLabelWidth = helpers.longestText(context, tickLabelFont, this.ticks, this.longestTextCache); <add> var originalLabelWidth = helpers.longestText(context, tickLabelFont, me.ticks, me.longestTextCache); <ide> var labelWidth = originalLabelWidth; <ide> var cosRotation; <ide> var sinRotation; <ide> <ide> // Allow 3 pixels x2 padding either side for label readability <ide> // only the index matters for a dataset scale, but we want a consistent interface between scales <del> var tickWidth = this.getPixelForTick(1) - this.getPixelForTick(0) - 6; <add> var tickWidth = me.getPixelForTick(1) - me.getPixelForTick(0) - 6; <ide> <ide> //Max label rotation can be set or default to 90 - also act as a loop counter <del> while (labelWidth > tickWidth && this.labelRotation < optionTicks.maxRotation) { <del> cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); <del> sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); <add> while (labelWidth > tickWidth && me.labelRotation < optionTicks.maxRotation) { <add> cosRotation = Math.cos(helpers.toRadians(me.labelRotation)); <add> sinRotation = Math.sin(helpers.toRadians(me.labelRotation)); <ide> <ide> firstRotated = cosRotation * firstWidth; <ide> <ide> // We're right aligning the text now. <del> if (firstRotated + tickFontSize / 2 > this.yLabelWidth) { <del> this.paddingLeft = firstRotated + tickFontSize / 2; <add> if (firstRotated + tickFontSize / 2 > me.yLabelWidth) { <add> me.paddingLeft = firstRotated + tickFontSize / 2; <ide> } <ide> <del> this.paddingRight = tickFontSize / 2; <add> me.paddingRight = tickFontSize / 2; <ide> <del> if (sinRotation * originalLabelWidth > this.maxHeight) { <add> if (sinRotation * originalLabelWidth > me.maxHeight) { <ide> // go back one step <del> this.labelRotation--; <add> me.labelRotation--; <ide> break; <ide> } <ide> <del> this.labelRotation++; <add> me.labelRotation++; <ide> labelWidth = cosRotation * originalLabelWidth; <ide> } <ide> } <ide> } <ide> <del> if (this.margins) { <del> this.paddingLeft = Math.max(this.paddingLeft - this.margins.left, 0); <del> this.paddingRight = Math.max(this.paddingRight - this.margins.right, 0); <add> if (me.margins) { <add> me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); <add> me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); <ide> } <ide> }, <ide> afterCalculateTickRotation: function() { <ide> module.exports = function(Chart) { <ide> helpers.callCallback(this.options.beforeFit, [this]); <ide> }, <ide> fit: function() { <add> var me = this; <ide> // Reset <del> var minSize = this.minSize = { <add> var minSize = me.minSize = { <ide> width: 0, <ide> height: 0 <ide> }; <ide> <del> var opts = this.options; <add> var opts = me.options; <ide> var globalDefaults = Chart.defaults.global; <ide> var tickOpts = opts.ticks; <ide> var scaleLabelOpts = opts.scaleLabel; <ide> var display = opts.display; <del> var isHorizontal = this.isHorizontal(); <add> var isHorizontal = me.isHorizontal(); <ide> <ide> var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); <ide> var tickFontStyle = helpers.getValueOrDefault(tickOpts.fontStyle, globalDefaults.defaultFontStyle); <ide> module.exports = function(Chart) { <ide> // Width <ide> if (isHorizontal) { <ide> // subtract the margins to line up with the chartArea if we are a full width scale <del> minSize.width = this.isFullWidth() ? this.maxWidth - this.margins.left - this.margins.right : this.maxWidth; <add> minSize.width = me.isFullWidth() ? me.maxWidth - me.margins.left - me.margins.right : me.maxWidth; <ide> } else { <ide> minSize.width = display ? tickMarkLength : 0; <ide> } <ide> module.exports = function(Chart) { <ide> if (isHorizontal) { <ide> minSize.height = display ? tickMarkLength : 0; <ide> } else { <del> minSize.height = this.maxHeight; // fill all the height <add> minSize.height = me.maxHeight; // fill all the height <ide> } <ide> <ide> // Are we showing a title for the scale? <ide> module.exports = function(Chart) { <ide> <ide> if (tickOpts.display && display) { <ide> // Don't bother fitting the ticks if we are not showing them <del> if (!this.longestTextCache) { <del> this.longestTextCache = {}; <add> if (!me.longestTextCache) { <add> me.longestTextCache = {}; <ide> } <ide> <del> var largestTextWidth = helpers.longestText(this.ctx, tickLabelFont, this.ticks, this.longestTextCache); <add> var largestTextWidth = helpers.longestText(me.ctx, tickLabelFont, me.ticks, me.longestTextCache); <ide> <ide> if (isHorizontal) { <ide> // A horizontal axis is more constrained by the height. <del> this.longestLabelWidth = largestTextWidth; <add> me.longestLabelWidth = largestTextWidth; <ide> <ide> // TODO - improve this calculation <del> var labelHeight = (Math.sin(helpers.toRadians(this.labelRotation)) * this.longestLabelWidth) + 1.5 * tickFontSize; <add> var labelHeight = (Math.sin(helpers.toRadians(me.labelRotation)) * me.longestLabelWidth) + 1.5 * tickFontSize; <ide> <del> minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight); <del> this.ctx.font = tickLabelFont; <add> minSize.height = Math.min(me.maxHeight, minSize.height + labelHeight); <add> me.ctx.font = tickLabelFont; <ide> <del> var firstLabelWidth = this.ctx.measureText(this.ticks[0]).width; <del> var lastLabelWidth = this.ctx.measureText(this.ticks[this.ticks.length - 1]).width; <add> var firstLabelWidth = me.ctx.measureText(me.ticks[0]).width; <add> var lastLabelWidth = me.ctx.measureText(me.ticks[me.ticks.length - 1]).width; <ide> <ide> // Ensure that our ticks are always inside the canvas. When rotated, ticks are right aligned which means that the right padding is dominated <ide> // by the font height <del> var cosRotation = Math.cos(helpers.toRadians(this.labelRotation)); <del> var sinRotation = Math.sin(helpers.toRadians(this.labelRotation)); <del> this.paddingLeft = this.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges <del> this.paddingRight = this.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated <add> var cosRotation = Math.cos(helpers.toRadians(me.labelRotation)); <add> var sinRotation = Math.sin(helpers.toRadians(me.labelRotation)); <add> me.paddingLeft = me.labelRotation !== 0 ? (cosRotation * firstLabelWidth) + 3 : firstLabelWidth / 2 + 3; // add 3 px to move away from canvas edges <add> me.paddingRight = me.labelRotation !== 0 ? (sinRotation * (tickFontSize / 2)) + 3 : lastLabelWidth / 2 + 3; // when rotated <ide> } else { <ide> // A vertical axis is more constrained by the width. Labels are the dominant factor here, so get that length first <del> var maxLabelWidth = this.maxWidth - minSize.width; <add> var maxLabelWidth = me.maxWidth - minSize.width; <ide> <ide> // Account for padding <ide> var mirror = tickOpts.mirror; <ide> if (!mirror) { <del> largestTextWidth += this.options.ticks.padding; <add> largestTextWidth += me.options.ticks.padding; <ide> } else { <ide> // If mirrored text is on the inside so don't expand <ide> largestTextWidth = 0; <ide> module.exports = function(Chart) { <ide> minSize.width += largestTextWidth; <ide> } else { <ide> // Expand to max size <del> minSize.width = this.maxWidth; <add> minSize.width = me.maxWidth; <ide> } <ide> <del> this.paddingTop = tickFontSize / 2; <del> this.paddingBottom = tickFontSize / 2; <add> me.paddingTop = tickFontSize / 2; <add> me.paddingBottom = tickFontSize / 2; <ide> } <ide> } <ide> <del> if (this.margins) { <del> this.paddingLeft = Math.max(this.paddingLeft - this.margins.left, 0); <del> this.paddingTop = Math.max(this.paddingTop - this.margins.top, 0); <del> this.paddingRight = Math.max(this.paddingRight - this.margins.right, 0); <del> this.paddingBottom = Math.max(this.paddingBottom - this.margins.bottom, 0); <add> if (me.margins) { <add> me.paddingLeft = Math.max(me.paddingLeft - me.margins.left, 0); <add> me.paddingTop = Math.max(me.paddingTop - me.margins.top, 0); <add> me.paddingRight = Math.max(me.paddingRight - me.margins.right, 0); <add> me.paddingBottom = Math.max(me.paddingBottom - me.margins.bottom, 0); <ide> } <ide> <del> this.width = minSize.width; <del> this.height = minSize.height; <add> me.width = minSize.width; <add> me.height = minSize.height; <ide> <ide> }, <ide> afterFit: function() { <ide> module.exports = function(Chart) { <ide> <ide> // Used for tick location, should <ide> getPixelForTick: function(index, includeOffset) { <del> if (this.isHorizontal()) { <del> var innerWidth = this.width - (this.paddingLeft + this.paddingRight); <del> var tickWidth = innerWidth / Math.max((this.ticks.length - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <del> var pixel = (tickWidth * index) + this.paddingLeft; <add> var me = this; <add> if (me.isHorizontal()) { <add> var innerWidth = me.width - (me.paddingLeft + me.paddingRight); <add> var tickWidth = innerWidth / Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <add> var pixel = (tickWidth * index) + me.paddingLeft; <ide> <ide> if (includeOffset) { <ide> pixel += tickWidth / 2; <ide> } <ide> <del> var finalVal = this.left + Math.round(pixel); <del> finalVal += this.isFullWidth() ? this.margins.left : 0; <add> var finalVal = me.left + Math.round(pixel); <add> finalVal += me.isFullWidth() ? me.margins.left : 0; <ide> return finalVal; <ide> } else { <del> var innerHeight = this.height - (this.paddingTop + this.paddingBottom); <del> return this.top + (index * (innerHeight / (this.ticks.length - 1))); <add> var innerHeight = me.height - (me.paddingTop + me.paddingBottom); <add> return me.top + (index * (innerHeight / (me.ticks.length - 1))); <ide> } <ide> }, <ide> <ide> // Utility for getting the pixel location of a percentage of scale <ide> getPixelForDecimal: function(decimal /*, includeOffset*/ ) { <del> if (this.isHorizontal()) { <del> var innerWidth = this.width - (this.paddingLeft + this.paddingRight); <del> var valueOffset = (innerWidth * decimal) + this.paddingLeft; <add> var me = this; <add> if (me.isHorizontal()) { <add> var innerWidth = me.width - (me.paddingLeft + me.paddingRight); <add> var valueOffset = (innerWidth * decimal) + me.paddingLeft; <ide> <del> var finalVal = this.left + Math.round(valueOffset); <del> finalVal += this.isFullWidth() ? this.margins.left : 0; <add> var finalVal = me.left + Math.round(valueOffset); <add> finalVal += me.isFullWidth() ? me.margins.left : 0; <ide> return finalVal; <ide> } else { <del> return this.top + (decimal * this.height); <add> return me.top + (decimal * me.height); <ide> } <ide> }, <ide> <ide> module.exports = function(Chart) { <ide> // Actualy draw the scale on the canvas <ide> // @param {rectangle} chartArea : the area of the chart to draw full grid lines on <ide> draw: function(chartArea) { <del> var options = this.options; <add> var me = this; <add> var options = me.options; <ide> if (!options.display) { <ide> return; <ide> } <ide> <del> var context = this.ctx; <add> var context = me.ctx; <ide> var globalDefaults = Chart.defaults.global; <ide> var optionTicks = options.ticks; <ide> var gridLines = options.gridLines; <ide> var scaleLabel = options.scaleLabel; <ide> <ide> var setContextLineSettings; <del> var isRotated = this.labelRotation !== 0; <add> var isRotated = me.labelRotation !== 0; <ide> var skipRatio; <ide> var scaleLabelX; <ide> var scaleLabelY; <ide> module.exports = function(Chart) { <ide> var scaleLabelFontFamily = helpers.getValueOrDefault(scaleLabel.fontFamily, globalDefaults.defaultFontFamily); <ide> var scaleLabelFont = helpers.fontString(scaleLabelFontSize, scaleLabelFontStyle, scaleLabelFontFamily); <ide> <del> var labelRotationRadians = helpers.toRadians(this.labelRotation); <add> var labelRotationRadians = helpers.toRadians(me.labelRotation); <ide> var cosRotation = Math.cos(labelRotationRadians); <ide> var sinRotation = Math.sin(labelRotationRadians); <del> var longestRotatedLabel = this.longestLabelWidth * cosRotation; <add> var longestRotatedLabel = me.longestLabelWidth * cosRotation; <ide> var rotatedLabelHeight = tickFontSize * sinRotation; <ide> <ide> // Make sure we draw text in the correct color and font <ide> context.fillStyle = tickFontColor; <ide> <del> if (this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> setContextLineSettings = true; <del> var yTickStart = options.position === "bottom" ? this.top : this.bottom - tl; <del> var yTickEnd = options.position === "bottom" ? this.top + tl : this.bottom; <add> var yTickStart = options.position === "bottom" ? me.top : me.bottom - tl; <add> var yTickEnd = options.position === "bottom" ? me.top + tl : me.bottom; <ide> skipRatio = false; <ide> <ide> // Only calculate the skip ratio with the half width of longestRotateLabel if we got an actual rotation <ide> module.exports = function(Chart) { <ide> longestRotatedLabel /= 2; <ide> } <ide> <del> if ((longestRotatedLabel + optionTicks.autoSkipPadding) * this.ticks.length > (this.width - (this.paddingLeft + this.paddingRight))) { <del> skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * this.ticks.length) / (this.width - (this.paddingLeft + this.paddingRight))); <add> if ((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length > (me.width - (me.paddingLeft + me.paddingRight))) { <add> skipRatio = 1 + Math.floor(((longestRotatedLabel + optionTicks.autoSkipPadding) * me.ticks.length) / (me.width - (me.paddingLeft + me.paddingRight))); <ide> } <ide> <ide> // if they defined a max number of optionTicks, <ide> // increase skipRatio until that number is met <del> if (maxTicks && this.ticks.length > maxTicks) { <del> while (!skipRatio || this.ticks.length / (skipRatio || 1) > maxTicks) { <add> if (maxTicks && me.ticks.length > maxTicks) { <add> while (!skipRatio || me.ticks.length / (skipRatio || 1) > maxTicks) { <ide> if (!skipRatio) { <ide> skipRatio = 1; <ide> } <ide> module.exports = function(Chart) { <ide> skipRatio = false; <ide> } <ide> <del> helpers.each(this.ticks, function (label, index) { <add> helpers.each(me.ticks, function (label, index) { <ide> // Blank optionTicks <del> var isLastTick = this.ticks.length === index + 1; <add> var isLastTick = me.ticks.length === index + 1; <ide> <ide> // Since we always show the last tick,we need may need to hide the last shown one before <del> var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= this.ticks.length); <add> var shouldSkip = (skipRatio > 1 && index % skipRatio > 0) || (index % skipRatio === 0 && index + skipRatio >= me.ticks.length); <ide> if (shouldSkip && !isLastTick || (label === undefined || label === null)) { <ide> return; <ide> } <del> var xLineValue = this.getPixelForTick(index); // xvalues for grid lines <del> var xLabelValue = this.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) <add> var xLineValue = me.getPixelForTick(index); // xvalues for grid lines <add> var xLabelValue = me.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) <ide> <ide> if (gridLines.display) { <del> if (index === (typeof this.zeroLineIndex !== 'undefined' ? this.zeroLineIndex : 0)) { <add> if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) { <ide> // Draw the first index specially <ide> context.lineWidth = gridLines.zeroLineWidth; <ide> context.strokeStyle = gridLines.zeroLineColor; <ide> module.exports = function(Chart) { <ide> <ide> if (optionTicks.display) { <ide> context.save(); <del> context.translate(xLabelValue + optionTicks.labelOffset, (isRotated) ? this.top + 12 : options.position === "top" ? this.bottom - tl : this.top + tl); <add> context.translate(xLabelValue + optionTicks.labelOffset, (isRotated) ? me.top + 12 : options.position === "top" ? me.bottom - tl : me.top + tl); <ide> context.rotate(labelRotationRadians * -1); <ide> context.font = tickLabelFont; <ide> context.textAlign = (isRotated) ? "right" : "center"; <ide> context.textBaseline = (isRotated) ? "middle" : options.position === "top" ? "bottom" : "top"; <ide> context.fillText(label, 0, 0); <ide> context.restore(); <ide> } <del> }, this); <add> }, me); <ide> <ide> if (scaleLabel.display) { <ide> // Draw the scale label <ide> module.exports = function(Chart) { <ide> context.fillStyle = scaleLabelFontColor; // render in correct colour <ide> context.font = scaleLabelFont; <ide> <del> scaleLabelX = this.left + ((this.right - this.left) / 2); // midpoint of the width <del> scaleLabelY = options.position === 'bottom' ? this.bottom - (scaleLabelFontSize / 2) : this.top + (scaleLabelFontSize / 2); <add> scaleLabelX = me.left + ((me.right - me.left) / 2); // midpoint of the width <add> scaleLabelY = options.position === 'bottom' ? me.bottom - (scaleLabelFontSize / 2) : me.top + (scaleLabelFontSize / 2); <ide> <ide> context.fillText(scaleLabel.labelString, scaleLabelX, scaleLabelY); <ide> } <ide> <ide> } else { <ide> setContextLineSettings = true; <del> var xTickStart = options.position === "right" ? this.left : this.right - 5; <del> var xTickEnd = options.position === "right" ? this.left + 5 : this.right; <add> var xTickStart = options.position === "right" ? me.left : me.right - 5; <add> var xTickEnd = options.position === "right" ? me.left + 5 : me.right; <ide> <del> helpers.each(this.ticks, function (label, index) { <add> helpers.each(me.ticks, function (label, index) { <ide> // If the callback returned a null or undefined value, do not draw this line <ide> if (label === undefined || label === null) { <ide> return; <ide> } <ide> <del> var yLineValue = this.getPixelForTick(index); // xvalues for grid lines <add> var yLineValue = me.getPixelForTick(index); // xvalues for grid lines <ide> <ide> if (gridLines.display) { <del> if (index === (typeof this.zeroLineIndex !== 'undefined' ? this.zeroLineIndex : 0)) { <add> if (index === (typeof me.zeroLineIndex !== 'undefined' ? me.zeroLineIndex : 0)) { <ide> // Draw the first index specially <ide> context.lineWidth = gridLines.zeroLineWidth; <ide> context.strokeStyle = gridLines.zeroLineColor; <ide> module.exports = function(Chart) { <ide> <ide> if (optionTicks.display) { <ide> var xLabelValue; <del> var yLabelValue = this.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) <add> var yLabelValue = me.getPixelForTick(index, gridLines.offsetGridLines); // x values for optionTicks (need to consider offsetLabel option) <ide> <ide> context.save(); <ide> <ide> if (options.position === "left") { <ide> if (optionTicks.mirror) { <del> xLabelValue = this.right + optionTicks.padding; <add> xLabelValue = me.right + optionTicks.padding; <ide> context.textAlign = "left"; <ide> } else { <del> xLabelValue = this.right - optionTicks.padding; <add> xLabelValue = me.right - optionTicks.padding; <ide> context.textAlign = "right"; <ide> } <ide> } else { <ide> // right side <ide> if (optionTicks.mirror) { <del> xLabelValue = this.left - optionTicks.padding; <add> xLabelValue = me.left - optionTicks.padding; <ide> context.textAlign = "right"; <ide> } else { <del> xLabelValue = this.left + optionTicks.padding; <add> xLabelValue = me.left + optionTicks.padding; <ide> context.textAlign = "left"; <ide> } <ide> } <ide> module.exports = function(Chart) { <ide> context.fillText(label, 0, 0); <ide> context.restore(); <ide> } <del> }, this); <add> }, me); <ide> <ide> if (scaleLabel.display) { <ide> // Draw the scale label <del> scaleLabelX = options.position === 'left' ? this.left + (scaleLabelFontSize / 2) : this.right - (scaleLabelFontSize / 2); <del> scaleLabelY = this.top + ((this.bottom - this.top) / 2); <add> scaleLabelX = options.position === 'left' ? me.left + (scaleLabelFontSize / 2) : me.right - (scaleLabelFontSize / 2); <add> scaleLabelY = me.top + ((me.bottom - me.top) / 2); <ide> var rotation = options.position === 'left' ? -0.5 * Math.PI : 0.5 * Math.PI; <ide> <ide> context.save(); <ide> module.exports = function(Chart) { <ide> // Draw the line at the edge of the axis <ide> context.lineWidth = gridLines.lineWidth; <ide> context.strokeStyle = gridLines.color; <del> var x1 = this.left, <del> x2 = this.right, <del> y1 = this.top, <del> y2 = this.bottom; <add> var x1 = me.left, <add> x2 = me.right, <add> y1 = me.top, <add> y2 = me.bottom; <ide> <ide> var aliasPixel = helpers.aliasPixel(context.lineWidth); <del> if (this.isHorizontal()) { <del> y1 = y2 = options.position === 'top' ? this.bottom : this.top; <add> if (me.isHorizontal()) { <add> y1 = y2 = options.position === 'top' ? me.bottom : me.top; <ide> y1 += aliasPixel; <ide> y2 += aliasPixel; <ide> } else { <del> x1 = x2 = options.position === 'left' ? this.right : this.left; <add> x1 = x2 = options.position === 'left' ? me.right : me.left; <ide> x1 += aliasPixel; <ide> x2 += aliasPixel; <ide> } <ide><path>src/core/core.title.js <ide> module.exports = function(Chart) { <ide> Chart.Title = Chart.Element.extend({ <ide> <ide> initialize: function(config) { <del> helpers.extend(this, config); <del> this.options = helpers.configMerge(Chart.defaults.global.title, config.options); <add> var me = this; <add> helpers.extend(me, config); <add> me.options = helpers.configMerge(Chart.defaults.global.title, config.options); <ide> <ide> // Contains hit boxes for each dataset (in dataset order) <del> this.legendHitBoxes = []; <add> me.legendHitBoxes = []; <ide> }, <ide> <ide> // These methods are ordered by lifecyle. Utilities then follow. <ide> <del> beforeUpdate: noop, <add> beforeUpdate: function () { <add> var chartOpts = this.chart.options; <add> if (chartOpts && chartOpts.title) { <add> this.options = helpers.configMerge(Chart.defaults.global.title, chartOpts.title); <add> } <add> }, <ide> update: function(maxWidth, maxHeight, margins) { <del> <add> var me = this; <add> <ide> // Update Lifecycle - Probably don't want to ever extend or overwrite this function ;) <del> this.beforeUpdate(); <add> me.beforeUpdate(); <ide> <ide> // Absorb the master measurements <del> this.maxWidth = maxWidth; <del> this.maxHeight = maxHeight; <del> this.margins = margins; <add> me.maxWidth = maxWidth; <add> me.maxHeight = maxHeight; <add> me.margins = margins; <ide> <ide> // Dimensions <del> this.beforeSetDimensions(); <del> this.setDimensions(); <del> this.afterSetDimensions(); <add> me.beforeSetDimensions(); <add> me.setDimensions(); <add> me.afterSetDimensions(); <ide> // Labels <del> this.beforeBuildLabels(); <del> this.buildLabels(); <del> this.afterBuildLabels(); <add> me.beforeBuildLabels(); <add> me.buildLabels(); <add> me.afterBuildLabels(); <ide> <ide> // Fit <del> this.beforeFit(); <del> this.fit(); <del> this.afterFit(); <add> me.beforeFit(); <add> me.fit(); <add> me.afterFit(); <ide> // <del> this.afterUpdate(); <add> me.afterUpdate(); <ide> <del> return this.minSize; <add> return me.minSize; <ide> <ide> }, <ide> afterUpdate: noop, <ide> module.exports = function(Chart) { <ide> <ide> beforeSetDimensions: noop, <ide> setDimensions: function() { <add> var me = this; <ide> // Set the unconstrained dimension before label rotation <del> if (this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> // Reset position before calculating rotation <del> this.width = this.maxWidth; <del> this.left = 0; <del> this.right = this.width; <add> me.width = me.maxWidth; <add> me.left = 0; <add> me.right = me.width; <ide> } else { <del> this.height = this.maxHeight; <add> me.height = me.maxHeight; <ide> <ide> // Reset position before calculating rotation <del> this.top = 0; <del> this.bottom = this.height; <add> me.top = 0; <add> me.bottom = me.height; <ide> } <ide> <ide> // Reset padding <del> this.paddingLeft = 0; <del> this.paddingTop = 0; <del> this.paddingRight = 0; <del> this.paddingBottom = 0; <add> me.paddingLeft = 0; <add> me.paddingTop = 0; <add> me.paddingRight = 0; <add> me.paddingBottom = 0; <ide> <ide> // Reset minSize <del> this.minSize = { <add> me.minSize = { <ide> width: 0, <ide> height: 0 <ide> }; <ide> module.exports = function(Chart) { <ide> beforeFit: noop, <ide> fit: function() { <ide> <del> var _this = this, <del> ctx = _this.ctx, <add> var me = this, <add> ctx = me.ctx, <ide> valueOrDefault = helpers.getValueOrDefault, <del> opts = _this.options, <add> opts = me.options, <ide> globalDefaults = Chart.defaults.global, <ide> display = opts.display, <ide> fontSize = valueOrDefault(opts.fontSize, globalDefaults.defaultFontSize), <del> minSize = _this.minSize; <add> minSize = me.minSize; <ide> <del> if (_this.isHorizontal()) { <del> minSize.width = _this.maxWidth; // fill all the width <add> if (me.isHorizontal()) { <add> minSize.width = me.maxWidth; // fill all the width <ide> minSize.height = display ? fontSize + (opts.padding * 2) : 0; <ide> } else { <ide> minSize.width = display ? fontSize + (opts.padding * 2) : 0; <del> minSize.height = _this.maxHeight; // fill all the height <add> minSize.height = me.maxHeight; // fill all the height <ide> } <ide> <del> _this.width = minSize.width; <del> _this.height = minSize.height; <add> me.width = minSize.width; <add> me.height = minSize.height; <ide> <ide> }, <ide> afterFit: noop, <ide> module.exports = function(Chart) { <ide> <ide> // Actualy draw the title block on the canvas <ide> draw: function() { <del> var _this = this, <del> ctx = _this.ctx, <add> var me = this, <add> ctx = me.ctx, <ide> valueOrDefault = helpers.getValueOrDefault, <del> opts = _this.options, <add> opts = me.options, <ide> globalDefaults = Chart.defaults.global; <ide> <ide> if (opts.display) { <ide> module.exports = function(Chart) { <ide> rotation = 0, <ide> titleX, <ide> titleY, <del> top = _this.top, <del> left = _this.left, <del> bottom = _this.bottom, <del> right = _this.right; <add> top = me.top, <add> left = me.left, <add> bottom = me.bottom, <add> right = me.right; <ide> <ide> ctx.fillStyle = valueOrDefault(opts.fontColor, globalDefaults.defaultFontColor); // render in correct colour <ide> ctx.font = titleFont; <ide> <ide> // Horizontal <del> if (_this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> titleX = left + ((right - left) / 2); // midpoint of the width <ide> titleY = top + ((bottom - top) / 2); // midpoint of the height <ide> } else { <ide> module.exports = function(Chart) { <ide> } <ide> } <ide> }); <del>}; <ide>\ No newline at end of file <add>}; <ide><path>src/core/core.tooltip.js <ide> module.exports = function(Chart) { <ide> <ide> // Args are: (tooltipItem, data) <ide> getBeforeBody: function() { <del> var me = this; <del> var lines = me._options.callbacks.beforeBody.apply(me, arguments); <add> var lines = this._options.callbacks.beforeBody.apply(this, arguments); <ide> return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; <ide> }, <ide> <ide> module.exports = function(Chart) { <ide> <ide> // Args are: (tooltipItem, data) <ide> getAfterBody: function() { <del> var me = this; <del> var lines = me._options.callbacks.afterBody.apply(me, arguments); <add> var lines = this._options.callbacks.afterBody.apply(this, arguments); <ide> return helpers.isArray(lines) ? lines : lines !== undefined ? [lines] : []; <ide> }, <ide> <ide> module.exports = function(Chart) { <ide> return me; <ide> }, <ide> getTooltipSize: function getTooltipSize(vm) { <del> var me = this; <del> var ctx = me._chart.ctx; <add> var ctx = this._chart.ctx; <ide> <ide> var size = { <ide> height: vm.yPadding * 2, // Tooltip Padding <ide> module.exports = function(Chart) { <ide> return pt; <ide> }, <ide> drawCaret: function drawCaret(tooltipPoint, size, opacity, caretPadding) { <del> var me = this; <del> var vm = me._view; <del> var ctx = me._chart.ctx; <add> var vm = this._view; <add> var ctx = this._chart.ctx; <ide> var x1, x2, x3; <ide> var y1, y2, y3; <ide> var caretSize = vm.caretSize; <ide> module.exports = function(Chart) { <ide> } <ide> }, <ide> drawBody: function drawBody(pt, vm, ctx, opacity) { <del> var me = this; <ide> var bodyFontSize = vm.bodyFontSize; <ide> var bodySpacing = vm.bodySpacing; <ide> var body = vm.body; <ide><path>src/elements/element.line.js <ide> module.exports = function(Chart) { <ide> <ide> Chart.elements.Line = Chart.Element.extend({ <ide> lineToNextPoint: function(previousPoint, point, nextPoint, skipHandler, previousSkipHandler) { <del> var ctx = this._chart.ctx; <add> var me = this; <add> var ctx = me._chart.ctx; <ide> <ide> if (point._view.skip) { <del> skipHandler.call(this, previousPoint, point, nextPoint); <add> skipHandler.call(me, previousPoint, point, nextPoint); <ide> } else if (previousPoint._view.skip) { <del> previousSkipHandler.call(this, previousPoint, point, nextPoint); <add> previousSkipHandler.call(me, previousPoint, point, nextPoint); <ide> } else if (point._view.tension === 0) { <ide> ctx.lineTo(point._view.x, point._view.y); <ide> } else { <ide> module.exports = function(Chart) { <ide> }, <ide> <ide> draw: function() { <del> var _this = this; <add> var me = this; <ide> <del> var vm = this._view; <del> var ctx = this._chart.ctx; <del> var first = this._children[0]; <del> var last = this._children[this._children.length - 1]; <add> var vm = me._view; <add> var ctx = me._chart.ctx; <add> var first = me._children[0]; <add> var last = me._children[me._children.length - 1]; <ide> <ide> function loopBackToStart(drawLineToCenter) { <ide> if (!first._view.skip && !last._view.skip) { <ide> module.exports = function(Chart) { <ide> ); <ide> } else if (drawLineToCenter) { <ide> // Go to center <del> ctx.lineTo(_this._view.scaleZero.x, _this._view.scaleZero.y); <add> ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y); <ide> } <ide> } <ide> <ide> ctx.save(); <ide> <ide> // If we had points and want to fill this line, do so. <del> if (this._children.length > 0 && vm.fill) { <add> if (me._children.length > 0 && vm.fill) { <ide> // Draw the background first (so the border is always on top) <ide> ctx.beginPath(); <ide> <del> helpers.each(this._children, function(point, index) { <del> var previous = helpers.previousItem(this._children, index); <del> var next = helpers.nextItem(this._children, index); <add> helpers.each(me._children, function(point, index) { <add> var previous = helpers.previousItem(me._children, index); <add> var next = helpers.nextItem(me._children, index); <ide> <ide> // First point moves to it's starting position no matter what <ide> if (index === 0) { <del> if (this._loop) { <add> if (me._loop) { <ide> ctx.moveTo(vm.scaleZero.x, vm.scaleZero.y); <ide> } else { <ide> ctx.moveTo(point._view.x, vm.scaleZero); <ide> } <ide> <ide> if (point._view.skip) { <del> if (!this._loop) { <del> ctx.moveTo(next._view.x, this._view.scaleZero); <add> if (!me._loop) { <add> ctx.moveTo(next._view.x, me._view.scaleZero); <ide> } <ide> } else { <ide> ctx.lineTo(point._view.x, point._view.y); <ide> } <ide> } else { <del> this.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { <del> if (this._loop) { <add> me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { <add> if (me._loop) { <ide> // Go to center <del> ctx.lineTo(this._view.scaleZero.x, this._view.scaleZero.y); <add> ctx.lineTo(me._view.scaleZero.x, me._view.scaleZero.y); <ide> } else { <del> ctx.lineTo(previousPoint._view.x, this._view.scaleZero); <del> ctx.moveTo(nextPoint._view.x, this._view.scaleZero); <add> ctx.lineTo(previousPoint._view.x, me._view.scaleZero); <add> ctx.moveTo(nextPoint._view.x, me._view.scaleZero); <ide> } <ide> }, function(previousPoint, point) { <ide> // If we skipped the last point, draw a line to ourselves so that the fill is nice <ide> ctx.lineTo(point._view.x, point._view.y); <ide> }); <ide> } <del> }, this); <add> }, me); <ide> <ide> // For radial scales, loop back around to the first point <del> if (this._loop) { <add> if (me._loop) { <ide> loopBackToStart(true); <ide> } else { <ide> //Round off the line by going to the base of the chart, back to the start, then fill. <del> ctx.lineTo(this._children[this._children.length - 1]._view.x, vm.scaleZero); <del> ctx.lineTo(this._children[0]._view.x, vm.scaleZero); <add> ctx.lineTo(me._children[me._children.length - 1]._view.x, vm.scaleZero); <add> ctx.lineTo(me._children[0]._view.x, vm.scaleZero); <ide> } <ide> <ide> ctx.fillStyle = vm.backgroundColor || globalDefaults.defaultColor; <ide> module.exports = function(Chart) { <ide> ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor; <ide> ctx.beginPath(); <ide> <del> helpers.each(this._children, function(point, index) { <del> var previous = helpers.previousItem(this._children, index); <del> var next = helpers.nextItem(this._children, index); <add> helpers.each(me._children, function(point, index) { <add> var previous = helpers.previousItem(me._children, index); <add> var next = helpers.nextItem(me._children, index); <ide> <ide> if (index === 0) { <ide> ctx.moveTo(point._view.x, point._view.y); <ide> } else { <del> this.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { <add> me.lineToNextPoint(previous, point, next, function(previousPoint, point, nextPoint) { <ide> ctx.moveTo(nextPoint._view.x, nextPoint._view.y); <ide> }, function(previousPoint, point) { <ide> // If we skipped the last point, move up to our point preventing a line from being drawn <ide> ctx.moveTo(point._view.x, point._view.y); <ide> }); <ide> } <del> }, this); <add> }, me); <ide> <del> if (this._loop && this._children.length > 0) { <add> if (me._loop && me._children.length > 0) { <ide> loopBackToStart(); <ide> } <ide> <ide><path>src/scales/scale.category.js <ide> module.exports = function(Chart) { <ide> var DatasetScale = Chart.Scale.extend({ <ide> // Implement this so that <ide> determineDataLimits: function() { <del> this.minIndex = 0; <del> this.maxIndex = this.chart.data.labels.length - 1; <add> var me = this; <add> me.minIndex = 0; <add> me.maxIndex = me.chart.data.labels.length - 1; <ide> var findIndex; <ide> <del> if (this.options.ticks.min !== undefined) { <add> if (me.options.ticks.min !== undefined) { <ide> // user specified min value <del> findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.min); <del> this.minIndex = findIndex !== -1 ? findIndex : this.minIndex; <add> findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.min); <add> me.minIndex = findIndex !== -1 ? findIndex : me.minIndex; <ide> } <ide> <del> if (this.options.ticks.max !== undefined) { <add> if (me.options.ticks.max !== undefined) { <ide> // user specified max value <del> findIndex = helpers.indexOf(this.chart.data.labels, this.options.ticks.max); <del> this.maxIndex = findIndex !== -1 ? findIndex : this.maxIndex; <add> findIndex = helpers.indexOf(me.chart.data.labels, me.options.ticks.max); <add> me.maxIndex = findIndex !== -1 ? findIndex : me.maxIndex; <ide> } <ide> <del> this.min = this.chart.data.labels[this.minIndex]; <del> this.max = this.chart.data.labels[this.maxIndex]; <add> me.min = me.chart.data.labels[me.minIndex]; <add> me.max = me.chart.data.labels[me.maxIndex]; <ide> }, <ide> <ide> buildTicks: function(index) { <add> var me = this; <ide> // If we are viewing some subset of labels, slice the original array <del> this.ticks = (this.minIndex === 0 && this.maxIndex === this.chart.data.labels.length - 1) ? this.chart.data.labels : this.chart.data.labels.slice(this.minIndex, this.maxIndex + 1); <add> me.ticks = (me.minIndex === 0 && me.maxIndex === me.chart.data.labels.length - 1) ? me.chart.data.labels : me.chart.data.labels.slice(me.minIndex, me.maxIndex + 1); <ide> }, <ide> <ide> getLabelForIndex: function(index, datasetIndex) { <ide> module.exports = function(Chart) { <ide> <ide> // Used to get data value locations. Value can either be an index or a numerical value <ide> getPixelForValue: function(value, index, datasetIndex, includeOffset) { <add> var me = this; <ide> // 1 is added because we need the length but we have the indexes <del> var offsetAmt = Math.max((this.maxIndex + 1 - this.minIndex - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <add> var offsetAmt = Math.max((me.maxIndex + 1 - me.minIndex - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <ide> <del> if (this.isHorizontal()) { <del> var innerWidth = this.width - (this.paddingLeft + this.paddingRight); <add> if (me.isHorizontal()) { <add> var innerWidth = me.width - (me.paddingLeft + me.paddingRight); <ide> var valueWidth = innerWidth / offsetAmt; <del> var widthOffset = (valueWidth * (index - this.minIndex)) + this.paddingLeft; <add> var widthOffset = (valueWidth * (index - me.minIndex)) + me.paddingLeft; <ide> <del> if (this.options.gridLines.offsetGridLines && includeOffset) { <add> if (me.options.gridLines.offsetGridLines && includeOffset) { <ide> widthOffset += (valueWidth / 2); <ide> } <ide> <del> return this.left + Math.round(widthOffset); <add> return me.left + Math.round(widthOffset); <ide> } else { <del> var innerHeight = this.height - (this.paddingTop + this.paddingBottom); <add> var innerHeight = me.height - (me.paddingTop + me.paddingBottom); <ide> var valueHeight = innerHeight / offsetAmt; <del> var heightOffset = (valueHeight * (index - this.minIndex)) + this.paddingTop; <add> var heightOffset = (valueHeight * (index - me.minIndex)) + me.paddingTop; <ide> <del> if (this.options.gridLines.offsetGridLines && includeOffset) { <add> if (me.options.gridLines.offsetGridLines && includeOffset) { <ide> heightOffset += (valueHeight / 2); <ide> } <ide> <del> return this.top + Math.round(heightOffset); <add> return me.top + Math.round(heightOffset); <ide> } <ide> }, <ide> getPixelForTick: function(index, includeOffset) { <ide> return this.getPixelForValue(this.ticks[index], index + this.minIndex, null, includeOffset); <ide> }, <ide> getValueForPixel: function(pixel) { <del> var value <del>; var offsetAmt = Math.max((this.ticks.length - ((this.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <del> var horz = this.isHorizontal(); <del> var innerDimension = horz ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); <add> var me = this; <add> var value; <add> var offsetAmt = Math.max((me.ticks.length - ((me.options.gridLines.offsetGridLines) ? 0 : 1)), 1); <add> var horz = me.isHorizontal(); <add> var innerDimension = horz ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); <ide> var valueDimension = innerDimension / offsetAmt; <ide> <del> if (this.options.gridLines.offsetGridLines) { <add> if (me.options.gridLines.offsetGridLines) { <ide> pixel -= (valueDimension / 2); <ide> } <del> pixel -= horz ? this.paddingLeft : this.paddingTop; <add> pixel -= horz ? me.paddingLeft : me.paddingTop; <ide> <ide> if (pixel <= 0) { <ide> value = 0; <ide><path>src/scales/scale.linear.js <ide> module.exports = function(Chart) { <ide> <ide> var LinearScale = Chart.LinearScaleBase.extend({ <ide> determineDataLimits: function() { <del> var _this = this; <del> var opts = _this.options; <add> var me = this; <add> var opts = me.options; <ide> var tickOpts = opts.ticks; <del> var chart = _this.chart; <add> var chart = me.chart; <ide> var data = chart.data; <ide> var datasets = data.datasets; <del> var isHorizontal = _this.isHorizontal(); <add> var isHorizontal = me.isHorizontal(); <ide> <ide> function IDMatches(meta) { <del> return isHorizontal ? meta.xAxisID === _this.id : meta.yAxisID === _this.id; <add> return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; <ide> } <ide> <ide> // First Calculate the range <del> _this.min = null; <del> _this.max = null; <add> me.min = null; <add> me.max = null; <ide> <ide> if (opts.stacked) { <ide> var valuesPerType = {}; <ide> module.exports = function(Chart) { <ide> <ide> if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <del> var value = +_this.getRightValue(rawValue); <add> var value = +me.getRightValue(rawValue); <ide> if (isNaN(value) || meta.data[index].hidden) { <ide> return; <ide> } <ide> module.exports = function(Chart) { <ide> var values = valuesForType.positiveValues.concat(valuesForType.negativeValues); <ide> var minVal = helpers.min(values); <ide> var maxVal = helpers.max(values); <del> _this.min = _this.min === null ? minVal : Math.min(_this.min, minVal); <del> _this.max = _this.max === null ? maxVal : Math.max(_this.max, maxVal); <add> me.min = me.min === null ? minVal : Math.min(me.min, minVal); <add> me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); <ide> }); <ide> <ide> } else { <ide> helpers.each(datasets, function(dataset, datasetIndex) { <ide> var meta = chart.getDatasetMeta(datasetIndex); <ide> if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <del> var value = +_this.getRightValue(rawValue); <add> var value = +me.getRightValue(rawValue); <ide> if (isNaN(value) || meta.data[index].hidden) { <ide> return; <ide> } <ide> <del> if (_this.min === null) { <del> _this.min = value; <del> } else if (value < _this.min) { <del> _this.min = value; <add> if (me.min === null) { <add> me.min = value; <add> } else if (value < me.min) { <add> me.min = value; <ide> } <ide> <del> if (_this.max === null) { <del> _this.max = value; <del> } else if (value > _this.max) { <del> _this.max = value; <add> if (me.max === null) { <add> me.max = value; <add> } else if (value > me.max) { <add> me.max = value; <ide> } <ide> }); <ide> } <ide> module.exports = function(Chart) { <ide> }, <ide> // Called after the ticks are built. We need <ide> handleDirectionalChanges: function() { <del> var me = this; <del> if (!me.isHorizontal()) { <add> if (!this.isHorizontal()) { <ide> // We are in a vertical orientation. The top value is the highest. So reverse the array <del> me.ticks.reverse(); <add> this.ticks.reverse(); <ide> } <ide> }, <ide> getLabelForIndex: function(index, datasetIndex) { <ide> module.exports = function(Chart) { <ide> getPixelForValue: function(value, index, datasetIndex, includeOffset) { <ide> // This must be called after fit has been run so that <ide> // this.left, this.top, this.right, and this.bottom have been defined <del> var _this = this; <del> var paddingLeft = _this.paddingLeft; <del> var paddingBottom = _this.paddingBottom; <del> var start = _this.start; <add> var me = this; <add> var paddingLeft = me.paddingLeft; <add> var paddingBottom = me.paddingBottom; <add> var start = me.start; <ide> <del> var rightValue = +_this.getRightValue(value); <add> var rightValue = +me.getRightValue(value); <ide> var pixel; <ide> var innerDimension; <del> var range = _this.end - start; <add> var range = me.end - start; <ide> <del> if (_this.isHorizontal()) { <del> innerDimension = _this.width - (paddingLeft + _this.paddingRight); <del> pixel = _this.left + (innerDimension / range * (rightValue - start)); <add> if (me.isHorizontal()) { <add> innerDimension = me.width - (paddingLeft + me.paddingRight); <add> pixel = me.left + (innerDimension / range * (rightValue - start)); <ide> return Math.round(pixel + paddingLeft); <ide> } else { <del> innerDimension = _this.height - (_this.paddingTop + paddingBottom); <del> pixel = (_this.bottom - paddingBottom) - (innerDimension / range * (rightValue - start)); <add> innerDimension = me.height - (me.paddingTop + paddingBottom); <add> pixel = (me.bottom - paddingBottom) - (innerDimension / range * (rightValue - start)); <ide> return Math.round(pixel); <ide> } <ide> }, <ide> getValueForPixel: function(pixel) { <del> var _this = this; <del> var isHorizontal = _this.isHorizontal(); <del> var paddingLeft = _this.paddingLeft; <del> var paddingBottom = _this.paddingBottom; <del> var innerDimension = isHorizontal ? _this.width - (paddingLeft + _this.paddingRight) : _this.height - (_this.paddingTop + paddingBottom); <del> var offset = (isHorizontal ? pixel - _this.left - paddingLeft : _this.bottom - paddingBottom - pixel) / innerDimension; <del> return _this.start + ((_this.end - _this.start) * offset); <add> var me = this; <add> var isHorizontal = me.isHorizontal(); <add> var paddingLeft = me.paddingLeft; <add> var paddingBottom = me.paddingBottom; <add> var innerDimension = isHorizontal ? me.width - (paddingLeft + me.paddingRight) : me.height - (me.paddingTop + paddingBottom); <add> var offset = (isHorizontal ? pixel - me.left - paddingLeft : me.bottom - paddingBottom - pixel) / innerDimension; <add> return me.start + ((me.end - me.start) * offset); <ide> }, <ide> getPixelForTick: function(index, includeOffset) { <ide> return this.getPixelForValue(this.ticksAsNumbers[index], null, null, includeOffset); <ide><path>src/scales/scale.linearbase.js <ide> module.exports = function(Chart) { <ide> <ide> Chart.LinearScaleBase = Chart.Scale.extend({ <ide> handleTickRangeOptions: function() { <del> var _this = this; <del> var opts = _this.options; <add> var me = this; <add> var opts = me.options; <ide> var tickOpts = opts.ticks; <ide> <ide> // If we are forcing it to begin at 0, but 0 will already be rendered on the chart, <ide> // do nothing since that would make the chart weird. If the user really wants a weird chart <ide> // axis, they can manually override it <ide> if (tickOpts.beginAtZero) { <del> var minSign = helpers.sign(_this.min); <del> var maxSign = helpers.sign(_this.max); <add> var minSign = helpers.sign(me.min); <add> var maxSign = helpers.sign(me.max); <ide> <ide> if (minSign < 0 && maxSign < 0) { <ide> // move the top up to 0 <del> _this.max = 0; <add> me.max = 0; <ide> } else if (minSign > 0 && maxSign > 0) { <ide> // move the botttom down to 0 <del> _this.min = 0; <add> me.min = 0; <ide> } <ide> } <ide> <ide> if (tickOpts.min !== undefined) { <del> _this.min = tickOpts.min; <add> me.min = tickOpts.min; <ide> } else if (tickOpts.suggestedMin !== undefined) { <del> _this.min = Math.min(_this.min, tickOpts.suggestedMin); <add> me.min = Math.min(me.min, tickOpts.suggestedMin); <ide> } <ide> <ide> if (tickOpts.max !== undefined) { <del> _this.max = tickOpts.max; <add> me.max = tickOpts.max; <ide> } else if (tickOpts.suggestedMax !== undefined) { <del> _this.max = Math.max(_this.max, tickOpts.suggestedMax); <add> me.max = Math.max(me.max, tickOpts.suggestedMax); <ide> } <ide> <del> if (_this.min === _this.max) { <del> _this.max++; <add> if (me.min === me.max) { <add> me.max++; <ide> <ide> if (!tickOpts.beginAtZero) { <del> _this.min--; <add> me.min--; <ide> } <ide> } <ide> }, <ide> getTickLimit: noop, <ide> handleDirectionalChanges: noop, <ide> <ide> buildTicks: function() { <del> var _this = this; <del> var opts = _this.options; <add> var me = this; <add> var opts = me.options; <ide> var tickOpts = opts.ticks; <ide> var getValueOrDefault = helpers.getValueOrDefault; <del> var isHorizontal = _this.isHorizontal(); <add> var isHorizontal = me.isHorizontal(); <ide> <del> var ticks = _this.ticks = []; <add> var ticks = me.ticks = []; <ide> <ide> // Figure out what the max number of ticks we can support it is based on the size of <ide> // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 <ide> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <ide> // the graph <ide> <del> var maxTicks = this.getTickLimit(); <add> var maxTicks = me.getTickLimit(); <ide> <ide> // Make sure we always have at least 2 ticks <ide> maxTicks = Math.max(2, maxTicks); <ide> module.exports = function(Chart) { <ide> if (fixedStepSizeSet) { <ide> spacing = getValueOrDefault(tickOpts.fixedStepSize, tickOpts.stepSize); <ide> } else { <del> var niceRange = helpers.niceNum(_this.max - _this.min, false); <add> var niceRange = helpers.niceNum(me.max - me.min, false); <ide> spacing = helpers.niceNum(niceRange / (maxTicks - 1), true); <ide> } <del> var niceMin = Math.floor(_this.min / spacing) * spacing; <del> var niceMax = Math.ceil(_this.max / spacing) * spacing; <add> var niceMin = Math.floor(me.min / spacing) * spacing; <add> var niceMax = Math.ceil(me.max / spacing) * spacing; <ide> var numSpaces = (niceMax - niceMin) / spacing; <ide> <ide> // If very close to our rounded value, use it. <ide> module.exports = function(Chart) { <ide> } <ide> ticks.push(tickOpts.max !== undefined ? tickOpts.max : niceMax); <ide> <del> this.handleDirectionalChanges(); <add> me.handleDirectionalChanges(); <ide> <ide> // At this point, we need to update our max and min given the tick values since we have expanded the <ide> // range of the scale <del> _this.max = helpers.max(ticks); <del> _this.min = helpers.min(ticks); <add> me.max = helpers.max(ticks); <add> me.min = helpers.min(ticks); <ide> <ide> if (tickOpts.reverse) { <ide> ticks.reverse(); <ide> <del> _this.start = _this.max; <del> _this.end = _this.min; <add> me.start = me.max; <add> me.end = me.min; <ide> } else { <del> _this.start = _this.min; <del> _this.end = _this.max; <add> me.start = me.min; <add> me.end = me.max; <ide> } <ide> }, <ide> convertTicksToLabels: function() { <del> var _this = this; <del> _this.ticksAsNumbers = _this.ticks.slice(); <del> _this.zeroLineIndex = _this.ticks.indexOf(0); <add> var me = this; <add> me.ticksAsNumbers = me.ticks.slice(); <add> me.zeroLineIndex = me.ticks.indexOf(0); <ide> <del> Chart.Scale.prototype.convertTicksToLabels.call(_this); <add> Chart.Scale.prototype.convertTicksToLabels.call(me); <ide> }, <ide> }); <ide> }; <ide>\ No newline at end of file <ide><path>src/scales/scale.logarithmic.js <ide> module.exports = function(Chart) { <ide> <ide> var LogarithmicScale = Chart.Scale.extend({ <ide> determineDataLimits: function() { <del> var _this = this; <del> var opts = _this.options; <add> var me = this; <add> var opts = me.options; <ide> var tickOpts = opts.ticks; <del> var chart = _this.chart; <add> var chart = me.chart; <ide> var data = chart.data; <ide> var datasets = data.datasets; <ide> var getValueOrDefault = helpers.getValueOrDefault; <del> var isHorizontal = _this.isHorizontal(); <add> var isHorizontal = me.isHorizontal(); <ide> function IDMatches(meta) { <del> return isHorizontal ? meta.xAxisID === _this.id : meta.yAxisID === _this.id; <add> return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id; <ide> } <ide> <ide> // Calculate Range <del> _this.min = null; <del> _this.max = null; <add> me.min = null; <add> me.max = null; <ide> <ide> if (opts.stacked) { <ide> var valuesPerType = {}; <ide> module.exports = function(Chart) { <ide> <ide> helpers.each(dataset.data, function(rawValue, index) { <ide> var values = valuesPerType[meta.type]; <del> var value = +_this.getRightValue(rawValue); <add> var value = +me.getRightValue(rawValue); <ide> if (isNaN(value) || meta.data[index].hidden) { <ide> return; <ide> } <ide> module.exports = function(Chart) { <ide> helpers.each(valuesPerType, function(valuesForType) { <ide> var minVal = helpers.min(valuesForType); <ide> var maxVal = helpers.max(valuesForType); <del> _this.min = _this.min === null ? minVal : Math.min(_this.min, minVal); <del> _this.max = _this.max === null ? maxVal : Math.max(_this.max, maxVal); <add> me.min = me.min === null ? minVal : Math.min(me.min, minVal); <add> me.max = me.max === null ? maxVal : Math.max(me.max, maxVal); <ide> }); <ide> <ide> } else { <ide> helpers.each(datasets, function(dataset, datasetIndex) { <ide> var meta = chart.getDatasetMeta(datasetIndex); <ide> if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { <ide> helpers.each(dataset.data, function(rawValue, index) { <del> var value = +_this.getRightValue(rawValue); <add> var value = +me.getRightValue(rawValue); <ide> if (isNaN(value) || meta.data[index].hidden) { <ide> return; <ide> } <ide> <del> if (_this.min === null) { <del> _this.min = value; <del> } else if (value < _this.min) { <del> _this.min = value; <add> if (me.min === null) { <add> me.min = value; <add> } else if (value < me.min) { <add> me.min = value; <ide> } <ide> <del> if (_this.max === null) { <del> _this.max = value; <del> } else if (value > _this.max) { <del> _this.max = value; <add> if (me.max === null) { <add> me.max = value; <add> } else if (value > me.max) { <add> me.max = value; <ide> } <ide> }); <ide> } <ide> }); <ide> } <ide> <del> _this.min = getValueOrDefault(tickOpts.min, _this.min); <del> _this.max = getValueOrDefault(tickOpts.max, _this.max); <add> me.min = getValueOrDefault(tickOpts.min, me.min); <add> me.max = getValueOrDefault(tickOpts.max, me.max); <ide> <del> if (_this.min === _this.max) { <del> if (_this.min !== 0 && _this.min !== null) { <del> _this.min = Math.pow(10, Math.floor(helpers.log10(_this.min)) - 1); <del> _this.max = Math.pow(10, Math.floor(helpers.log10(_this.max)) + 1); <add> if (me.min === me.max) { <add> if (me.min !== 0 && me.min !== null) { <add> me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1); <add> me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1); <ide> } else { <del> _this.min = 1; <del> _this.max = 10; <add> me.min = 1; <add> me.max = 10; <ide> } <ide> } <ide> }, <ide> buildTicks: function() { <del> var _this = this; <del> var opts = _this.options; <add> var me = this; <add> var opts = me.options; <ide> var tickOpts = opts.ticks; <ide> var getValueOrDefault = helpers.getValueOrDefault; <ide> <ide> // Reset the ticks array. Later on, we will draw a grid line at these positions <ide> // The array simply contains the numerical value of the spots where ticks will be <del> var ticks = _this.ticks = []; <add> var ticks = me.ticks = []; <ide> <ide> // Figure out what the max number of ticks we can support it is based on the size of <ide> // the axis area. For now, we say that the minimum tick spacing in pixels must be 50 <ide> // We also limit the maximum number of ticks to 11 which gives a nice 10 squares on <ide> // the graph <ide> <del> var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(_this.min)))); <add> var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(me.min)))); <ide> <del> while (tickVal < _this.max) { <add> while (tickVal < me.max) { <ide> ticks.push(tickVal); <ide> <ide> var exp = Math.floor(helpers.log10(tickVal)); <ide> module.exports = function(Chart) { <ide> var lastTick = getValueOrDefault(tickOpts.max, tickVal); <ide> ticks.push(lastTick); <ide> <del> if (!_this.isHorizontal()) { <add> if (!me.isHorizontal()) { <ide> // We are in a vertical orientation. The top value is the highest. So reverse the array <ide> ticks.reverse(); <ide> } <ide> <ide> // At this point, we need to update our max and min given the tick values since we have expanded the <ide> // range of the scale <del> _this.max = helpers.max(ticks); <del> _this.min = helpers.min(ticks); <add> me.max = helpers.max(ticks); <add> me.min = helpers.min(ticks); <ide> <ide> if (tickOpts.reverse) { <ide> ticks.reverse(); <ide> <del> _this.start = _this.max; <del> _this.end = _this.min; <add> me.start = me.max; <add> me.end = me.min; <ide> } else { <del> _this.start = _this.min; <del> _this.end = _this.max; <add> me.start = me.min; <add> me.end = me.max; <ide> } <ide> }, <ide> convertTicksToLabels: function() { <ide> module.exports = function(Chart) { <ide> return this.getPixelForValue(this.tickValues[index], null, null, includeOffset); <ide> }, <ide> getPixelForValue: function(value, index, datasetIndex, includeOffset) { <del> var _this = this; <add> var me = this; <ide> var innerDimension; <ide> var pixel; <ide> <del> var start = _this.start; <del> var newVal = +_this.getRightValue(value); <del> var range = helpers.log10(_this.end) - helpers.log10(start); <del> var paddingTop = _this.paddingTop; <del> var paddingBottom = _this.paddingBottom; <del> var paddingLeft = _this.paddingLeft; <add> var start = me.start; <add> var newVal = +me.getRightValue(value); <add> var range = helpers.log10(me.end) - helpers.log10(start); <add> var paddingTop = me.paddingTop; <add> var paddingBottom = me.paddingBottom; <add> var paddingLeft = me.paddingLeft; <ide> <del> if (_this.isHorizontal()) { <add> if (me.isHorizontal()) { <ide> <ide> if (newVal === 0) { <del> pixel = _this.left + paddingLeft; <add> pixel = me.left + paddingLeft; <ide> } else { <del> innerDimension = _this.width - (paddingLeft + _this.paddingRight); <del> pixel = _this.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); <add> innerDimension = me.width - (paddingLeft + me.paddingRight); <add> pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); <ide> pixel += paddingLeft; <ide> } <ide> } else { <ide> // Bottom - top since pixels increase downard on a screen <ide> if (newVal === 0) { <del> pixel = _this.top + paddingTop; <add> pixel = me.top + paddingTop; <ide> } else { <del> innerDimension = _this.height - (paddingTop + paddingBottom); <del> pixel = (_this.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); <add> innerDimension = me.height - (paddingTop + paddingBottom); <add> pixel = (me.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start))); <ide> } <ide> } <ide> <ide> return pixel; <ide> }, <ide> getValueForPixel: function(pixel) { <del> var _this = this; <add> var me = this; <ide> var offset; <del> var range = helpers.log10(_this.end) - helpers.log10(_this.start); <add> var range = helpers.log10(me.end) - helpers.log10(me.start); <ide> var value; <ide> var innerDimension; <ide> <del> if (_this.isHorizontal()) { <del> innerDimension = _this.width - (_this.paddingLeft + _this.paddingRight); <del> value = _this.start * Math.pow(10, (pixel - _this.left - _this.paddingLeft) * range / innerDimension); <add> if (me.isHorizontal()) { <add> innerDimension = me.width - (me.paddingLeft + me.paddingRight); <add> value = me.start * Math.pow(10, (pixel - me.left - me.paddingLeft) * range / innerDimension); <ide> } else { <del> innerDimension = _this.height - (_this.paddingTop + _this.paddingBottom); <del> value = Math.pow(10, (_this.bottom - _this.paddingBottom - pixel) * range / innerDimension) / _this.start; <add> innerDimension = me.height - (me.paddingTop + me.paddingBottom); <add> value = Math.pow(10, (me.bottom - me.paddingBottom - pixel) * range / innerDimension) / me.start; <ide> } <ide> <ide> return value; <ide><path>src/scales/scale.radialLinear.js <ide> module.exports = function(Chart) { <ide> me.handleTickRangeOptions(); <ide> }, <ide> getTickLimit: function() { <del> var me = this; <del> var tickOpts = me.options.ticks; <add> var tickOpts = this.options.ticks; <ide> var tickFontSize = helpers.getValueOrDefault(tickOpts.fontSize, globalDefaults.defaultFontSize); <del> return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(me.drawingArea / (1.5 * tickFontSize))); <add> return Math.min(tickOpts.maxTicksLimit ? tickOpts.maxTicksLimit : 11, Math.ceil(this.drawingArea / (1.5 * tickFontSize))); <ide> }, <ide> convertTicksToLabels: function() { <ide> var me = this; <ide><path>src/scales/scale.time.js <ide> module.exports = function(Chart) { <ide> return this.labelMoments[datasetIndex][index]; <ide> }, <ide> getMomentStartOf: function(tick) { <del> if (this.options.time.unit === 'week' && this.options.time.isoWeekday !== false) { <del> return tick.clone().startOf('isoWeek').isoWeekday(this.options.time.isoWeekday); <add> var me = this; <add> if (me.options.time.unit === 'week' && me.options.time.isoWeekday !== false) { <add> return tick.clone().startOf('isoWeek').isoWeekday(me.options.time.isoWeekday); <ide> } else { <del> return tick.clone().startOf(this.tickUnit); <add> return tick.clone().startOf(me.tickUnit); <ide> } <ide> }, <ide> determineDataLimits: function() { <del> this.labelMoments = []; <add> var me = this; <add> me.labelMoments = []; <ide> <ide> // Only parse these once. If the dataset does not have data as x,y pairs, we will use <ide> // these <ide> var scaleLabelMoments = []; <del> if (this.chart.data.labels && this.chart.data.labels.length > 0) { <del> helpers.each(this.chart.data.labels, function(label, index) { <del> var labelMoment = this.parseTime(label); <add> if (me.chart.data.labels && me.chart.data.labels.length > 0) { <add> helpers.each(me.chart.data.labels, function(label, index) { <add> var labelMoment = me.parseTime(label); <ide> <ide> if (labelMoment.isValid()) { <del> if (this.options.time.round) { <del> labelMoment.startOf(this.options.time.round); <add> if (me.options.time.round) { <add> labelMoment.startOf(me.options.time.round); <ide> } <ide> scaleLabelMoments.push(labelMoment); <ide> } <del> }, this); <add> }, me); <ide> <del> this.firstTick = moment.min.call(this, scaleLabelMoments); <del> this.lastTick = moment.max.call(this, scaleLabelMoments); <add> me.firstTick = moment.min.call(me, scaleLabelMoments); <add> me.lastTick = moment.max.call(me, scaleLabelMoments); <ide> } else { <del> this.firstTick = null; <del> this.lastTick = null; <add> me.firstTick = null; <add> me.lastTick = null; <ide> } <ide> <del> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <add> helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { <ide> var momentsForDataset = []; <del> var datasetVisible = this.chart.isDatasetVisible(datasetIndex); <add> var datasetVisible = me.chart.isDatasetVisible(datasetIndex); <ide> <ide> if (typeof dataset.data[0] === 'object' && dataset.data[0] !== null) { <ide> helpers.each(dataset.data, function(value, index) { <del> var labelMoment = this.parseTime(this.getRightValue(value)); <add> var labelMoment = me.parseTime(me.getRightValue(value)); <ide> <ide> if (labelMoment.isValid()) { <del> if (this.options.time.round) { <del> labelMoment.startOf(this.options.time.round); <add> if (me.options.time.round) { <add> labelMoment.startOf(me.options.time.round); <ide> } <ide> momentsForDataset.push(labelMoment); <ide> <ide> if (datasetVisible) { <ide> // May have gone outside the scale ranges, make sure we keep the first and last ticks updated <del> this.firstTick = this.firstTick !== null ? moment.min(this.firstTick, labelMoment) : labelMoment; <del> this.lastTick = this.lastTick !== null ? moment.max(this.lastTick, labelMoment) : labelMoment; <add> me.firstTick = me.firstTick !== null ? moment.min(me.firstTick, labelMoment) : labelMoment; <add> me.lastTick = me.lastTick !== null ? moment.max(me.lastTick, labelMoment) : labelMoment; <ide> } <ide> } <del> }, this); <add> }, me); <ide> } else { <ide> // We have no labels. Use the ones from the scale <ide> momentsForDataset = scaleLabelMoments; <ide> } <ide> <del> this.labelMoments.push(momentsForDataset); <del> }, this); <add> me.labelMoments.push(momentsForDataset); <add> }, me); <ide> <ide> // Set these after we've done all the data <del> if (this.options.time.min) { <del> this.firstTick = this.parseTime(this.options.time.min); <add> if (me.options.time.min) { <add> me.firstTick = me.parseTime(me.options.time.min); <ide> } <ide> <del> if (this.options.time.max) { <del> this.lastTick = this.parseTime(this.options.time.max); <add> if (me.options.time.max) { <add> me.lastTick = me.parseTime(me.options.time.max); <ide> } <ide> <ide> // We will modify these, so clone for later <del> this.firstTick = (this.firstTick || moment()).clone(); <del> this.lastTick = (this.lastTick || moment()).clone(); <add> me.firstTick = (me.firstTick || moment()).clone(); <add> me.lastTick = (me.lastTick || moment()).clone(); <ide> }, <ide> buildTicks: function(index) { <add> var me = this; <ide> <del> this.ctx.save(); <del> var tickFontSize = helpers.getValueOrDefault(this.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <del> var tickFontStyle = helpers.getValueOrDefault(this.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <del> var tickFontFamily = helpers.getValueOrDefault(this.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <add> me.ctx.save(); <add> var tickFontSize = helpers.getValueOrDefault(me.options.ticks.fontSize, Chart.defaults.global.defaultFontSize); <add> var tickFontStyle = helpers.getValueOrDefault(me.options.ticks.fontStyle, Chart.defaults.global.defaultFontStyle); <add> var tickFontFamily = helpers.getValueOrDefault(me.options.ticks.fontFamily, Chart.defaults.global.defaultFontFamily); <ide> var tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); <del> this.ctx.font = tickLabelFont; <add> me.ctx.font = tickLabelFont; <ide> <del> this.ticks = []; <del> this.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step <del> this.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc) <add> me.ticks = []; <add> me.unitScale = 1; // How much we scale the unit by, ie 2 means 2x unit per step <add> me.scaleSizeInUnits = 0; // How large the scale is in the base unit (seconds, minutes, etc) <ide> <ide> // Set unit override if applicable <del> if (this.options.time.unit) { <del> this.tickUnit = this.options.time.unit || 'day'; <del> this.displayFormat = this.options.time.displayFormats[this.tickUnit]; <del> this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); <del> this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, 1); <add> if (me.options.time.unit) { <add> me.tickUnit = me.options.time.unit || 'day'; <add> me.displayFormat = me.options.time.displayFormats[me.tickUnit]; <add> me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); <add> me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, 1); <ide> } else { <ide> // Determine the smallest needed unit of the time <del> var innerWidth = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); <add> var innerWidth = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); <ide> <ide> // Crude approximation of what the label length might be <del> var tempFirstLabel = this.tickFormatFunction(this.firstTick, 0, []); <del> var tickLabelWidth = this.ctx.measureText(tempFirstLabel).width; <del> var cosRotation = Math.cos(helpers.toRadians(this.options.ticks.maxRotation)); <del> var sinRotation = Math.sin(helpers.toRadians(this.options.ticks.maxRotation)); <add> var tempFirstLabel = me.tickFormatFunction(me.firstTick, 0, []); <add> var tickLabelWidth = me.ctx.measureText(tempFirstLabel).width; <add> var cosRotation = Math.cos(helpers.toRadians(me.options.ticks.maxRotation)); <add> var sinRotation = Math.sin(helpers.toRadians(me.options.ticks.maxRotation)); <ide> tickLabelWidth = (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation); <ide> var labelCapacity = innerWidth / (tickLabelWidth); <ide> <ide> // Start as small as possible <del> this.tickUnit = 'millisecond'; <del> this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); <del> this.displayFormat = this.options.time.displayFormats[this.tickUnit]; <add> me.tickUnit = 'millisecond'; <add> me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); <add> me.displayFormat = me.options.time.displayFormats[me.tickUnit]; <ide> <ide> var unitDefinitionIndex = 0; <ide> var unitDefinition = time.units[unitDefinitionIndex]; <ide> <ide> // While we aren't ideal and we don't have units left <ide> while (unitDefinitionIndex < time.units.length) { <ide> // Can we scale this unit. If `false` we can scale infinitely <del> this.unitScale = 1; <add> me.unitScale = 1; <ide> <del> if (helpers.isArray(unitDefinition.steps) && Math.ceil(this.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) { <add> if (helpers.isArray(unitDefinition.steps) && Math.ceil(me.scaleSizeInUnits / labelCapacity) < helpers.max(unitDefinition.steps)) { <ide> // Use one of the prefedined steps <ide> for (var idx = 0; idx < unitDefinition.steps.length; ++idx) { <del> if (unitDefinition.steps[idx] >= Math.ceil(this.scaleSizeInUnits / labelCapacity)) { <del> this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, unitDefinition.steps[idx]); <add> if (unitDefinition.steps[idx] >= Math.ceil(me.scaleSizeInUnits / labelCapacity)) { <add> me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, unitDefinition.steps[idx]); <ide> break; <ide> } <ide> } <ide> <ide> break; <del> } else if ((unitDefinition.maxStep === false) || (Math.ceil(this.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) { <add> } else if ((unitDefinition.maxStep === false) || (Math.ceil(me.scaleSizeInUnits / labelCapacity) < unitDefinition.maxStep)) { <ide> // We have a max step. Scale this unit <del> this.unitScale = helpers.getValueOrDefault(this.options.time.unitStepSize, Math.ceil(this.scaleSizeInUnits / labelCapacity)); <add> me.unitScale = helpers.getValueOrDefault(me.options.time.unitStepSize, Math.ceil(me.scaleSizeInUnits / labelCapacity)); <ide> break; <ide> } else { <ide> // Move to the next unit up <ide> ++unitDefinitionIndex; <ide> unitDefinition = time.units[unitDefinitionIndex]; <ide> <del> this.tickUnit = unitDefinition.name; <del> var leadingUnitBuffer = this.firstTick.diff(this.getMomentStartOf(this.firstTick), this.tickUnit, true); <del> var trailingUnitBuffer = this.getMomentStartOf(this.lastTick.clone().add(1, this.tickUnit)).diff(this.lastTick, this.tickUnit, true); <del> this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer; <del> this.displayFormat = this.options.time.displayFormats[unitDefinition.name]; <add> me.tickUnit = unitDefinition.name; <add> var leadingUnitBuffer = me.firstTick.diff(me.getMomentStartOf(me.firstTick), me.tickUnit, true); <add> var trailingUnitBuffer = me.getMomentStartOf(me.lastTick.clone().add(1, me.tickUnit)).diff(me.lastTick, me.tickUnit, true); <add> me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true) + leadingUnitBuffer + trailingUnitBuffer; <add> me.displayFormat = me.options.time.displayFormats[unitDefinition.name]; <ide> } <ide> } <ide> } <ide> <ide> var roundedStart; <ide> <ide> // Only round the first tick if we have no hard minimum <del> if (!this.options.time.min) { <del> this.firstTick = this.getMomentStartOf(this.firstTick); <del> roundedStart = this.firstTick; <add> if (!me.options.time.min) { <add> me.firstTick = me.getMomentStartOf(me.firstTick); <add> roundedStart = me.firstTick; <ide> } else { <del> roundedStart = this.getMomentStartOf(this.firstTick); <add> roundedStart = me.getMomentStartOf(me.firstTick); <ide> } <ide> <ide> // Only round the last tick if we have no hard maximum <del> if (!this.options.time.max) { <del> var roundedEnd = this.getMomentStartOf(this.lastTick); <del> if (roundedEnd.diff(this.lastTick, this.tickUnit, true) !== 0) { <del> // Do not use end of because we need this to be in the next time unit <del> this.lastTick = this.getMomentStartOf(this.lastTick.add(1, this.tickUnit)); <add> if (!me.options.time.max) { <add> var roundedEnd = me.getMomentStartOf(me.lastTick); <add> if (roundedEnd.diff(me.lastTick, me.tickUnit, true) !== 0) { <add> // Do not use end of because we need me to be in the next time unit <add> me.lastTick = me.getMomentStartOf(me.lastTick.add(1, me.tickUnit)); <ide> } <ide> } <ide> <del> this.smallestLabelSeparation = this.width; <add> me.smallestLabelSeparation = me.width; <ide> <del> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) { <del> for (var i = 1; i < this.labelMoments[datasetIndex].length; i++) { <del> this.smallestLabelSeparation = Math.min(this.smallestLabelSeparation, this.labelMoments[datasetIndex][i].diff(this.labelMoments[datasetIndex][i - 1], this.tickUnit, true)); <add> helpers.each(me.chart.data.datasets, function(dataset, datasetIndex) { <add> for (var i = 1; i < me.labelMoments[datasetIndex].length; i++) { <add> me.smallestLabelSeparation = Math.min(me.smallestLabelSeparation, me.labelMoments[datasetIndex][i].diff(me.labelMoments[datasetIndex][i - 1], me.tickUnit, true)); <ide> } <del> }, this); <add> }, me); <ide> <ide> // Tick displayFormat override <del> if (this.options.time.displayFormat) { <del> this.displayFormat = this.options.time.displayFormat; <add> if (me.options.time.displayFormat) { <add> me.displayFormat = me.options.time.displayFormat; <ide> } <ide> <ide> // first tick. will have been rounded correctly if options.time.min is not specified <del> this.ticks.push(this.firstTick.clone()); <add> me.ticks.push(me.firstTick.clone()); <ide> <ide> // For every unit in between the first and last moment, create a moment and add it to the ticks tick <del> for (var i = 1; i <= this.scaleSizeInUnits; ++i) { <del> var newTick = roundedStart.clone().add(i, this.tickUnit); <add> for (var i = 1; i <= me.scaleSizeInUnits; ++i) { <add> var newTick = roundedStart.clone().add(i, me.tickUnit); <ide> <ide> // Are we greater than the max time <del> if (this.options.time.max && newTick.diff(this.lastTick, this.tickUnit, true) >= 0) { <add> if (me.options.time.max && newTick.diff(me.lastTick, me.tickUnit, true) >= 0) { <ide> break; <ide> } <ide> <del> if (i % this.unitScale === 0) { <del> this.ticks.push(newTick); <add> if (i % me.unitScale === 0) { <add> me.ticks.push(newTick); <ide> } <ide> } <ide> <ide> // Always show the right tick <del> var diff = this.ticks[this.ticks.length - 1].diff(this.lastTick, this.tickUnit); <del> if (diff !== 0 || this.scaleSizeInUnits === 0) { <add> var diff = me.ticks[me.ticks.length - 1].diff(me.lastTick, me.tickUnit); <add> if (diff !== 0 || me.scaleSizeInUnits === 0) { <ide> // this is a weird case. If the <max> option is the same as the end option, we can't just diff the times because the tick was created from the roundedStart <ide> // but the last tick was not rounded. <del> if (this.options.time.max) { <del> this.ticks.push(this.lastTick.clone()); <del> this.scaleSizeInUnits = this.lastTick.diff(this.ticks[0], this.tickUnit, true); <add> if (me.options.time.max) { <add> me.ticks.push(me.lastTick.clone()); <add> me.scaleSizeInUnits = me.lastTick.diff(me.ticks[0], me.tickUnit, true); <ide> } else { <del> this.ticks.push(this.lastTick.clone()); <del> this.scaleSizeInUnits = this.lastTick.diff(this.firstTick, this.tickUnit, true); <add> me.ticks.push(me.lastTick.clone()); <add> me.scaleSizeInUnits = me.lastTick.diff(me.firstTick, me.tickUnit, true); <ide> } <ide> } <ide> <del> this.ctx.restore(); <add> me.ctx.restore(); <ide> }, <ide> // Get tooltip label <ide> getLabelForIndex: function(index, datasetIndex) { <del> var label = this.chart.data.labels && index < this.chart.data.labels.length ? this.chart.data.labels[index] : ''; <add> var me = this; <add> var label = me.chart.data.labels && index < me.chart.data.labels.length ? me.chart.data.labels[index] : ''; <ide> <del> if (typeof this.chart.data.datasets[datasetIndex].data[0] === 'object') { <del> label = this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]); <add> if (typeof me.chart.data.datasets[datasetIndex].data[0] === 'object') { <add> label = me.getRightValue(me.chart.data.datasets[datasetIndex].data[index]); <ide> } <ide> <ide> // Format nicely <del> if (this.options.time.tooltipFormat) { <del> label = this.parseTime(label).format(this.options.time.tooltipFormat); <add> if (me.options.time.tooltipFormat) { <add> label = me.parseTime(label).format(me.options.time.tooltipFormat); <ide> } <ide> <ide> return label; <ide> module.exports = function(Chart) { <ide> } <ide> }, <ide> convertTicksToLabels: function() { <del> this.tickMoments = this.ticks; <del> this.ticks = this.ticks.map(this.tickFormatFunction, this); <add> var me = this; <add> me.tickMoments = me.ticks; <add> me.ticks = me.ticks.map(me.tickFormatFunction, me); <ide> }, <ide> getPixelForValue: function(value, index, datasetIndex, includeOffset) { <del> var labelMoment = value && value.isValid && value.isValid() ? value : this.getLabelMoment(datasetIndex, index); <add> var me = this; <add> var labelMoment = value && value.isValid && value.isValid() ? value : me.getLabelMoment(datasetIndex, index); <ide> <ide> if (labelMoment) { <del> var offset = labelMoment.diff(this.firstTick, this.tickUnit, true); <add> var offset = labelMoment.diff(me.firstTick, me.tickUnit, true); <ide> <del> var decimal = offset / this.scaleSizeInUnits; <add> var decimal = offset / me.scaleSizeInUnits; <ide> <del> if (this.isHorizontal()) { <del> var innerWidth = this.width - (this.paddingLeft + this.paddingRight); <del> var valueWidth = innerWidth / Math.max(this.ticks.length - 1, 1); <del> var valueOffset = (innerWidth * decimal) + this.paddingLeft; <add> if (me.isHorizontal()) { <add> var innerWidth = me.width - (me.paddingLeft + me.paddingRight); <add> var valueWidth = innerWidth / Math.max(me.ticks.length - 1, 1); <add> var valueOffset = (innerWidth * decimal) + me.paddingLeft; <ide> <del> return this.left + Math.round(valueOffset); <add> return me.left + Math.round(valueOffset); <ide> } else { <del> var innerHeight = this.height - (this.paddingTop + this.paddingBottom); <del> var valueHeight = innerHeight / Math.max(this.ticks.length - 1, 1); <del> var heightOffset = (innerHeight * decimal) + this.paddingTop; <add> var innerHeight = me.height - (me.paddingTop + me.paddingBottom); <add> var valueHeight = innerHeight / Math.max(me.ticks.length - 1, 1); <add> var heightOffset = (innerHeight * decimal) + me.paddingTop; <ide> <del> return this.top + Math.round(heightOffset); <add> return me.top + Math.round(heightOffset); <ide> } <ide> } <ide> }, <ide> getPixelForTick: function(index, includeOffset) { <ide> return this.getPixelForValue(this.tickMoments[index], null, null, includeOffset); <ide> }, <ide> getValueForPixel: function(pixel) { <del> var innerDimension = this.isHorizontal() ? this.width - (this.paddingLeft + this.paddingRight) : this.height - (this.paddingTop + this.paddingBottom); <del> var offset = (pixel - (this.isHorizontal() ? this.left + this.paddingLeft : this.top + this.paddingTop)) / innerDimension; <del> offset *= this.scaleSizeInUnits; <del> return this.firstTick.clone().add(moment.duration(offset, this.tickUnit).asSeconds(), 'seconds'); <add> var me = this; <add> var innerDimension = me.isHorizontal() ? me.width - (me.paddingLeft + me.paddingRight) : me.height - (me.paddingTop + me.paddingBottom); <add> var offset = (pixel - (me.isHorizontal() ? me.left + me.paddingLeft : me.top + me.paddingTop)) / innerDimension; <add> offset *= me.scaleSizeInUnits; <add> return me.firstTick.clone().add(moment.duration(offset, me.tickUnit).asSeconds(), 'seconds'); <ide> }, <ide> parseTime: function(label) { <del> if (typeof this.options.time.parser === 'string') { <del> return moment(label, this.options.time.parser); <add> var me = this; <add> if (typeof me.options.time.parser === 'string') { <add> return moment(label, me.options.time.parser); <ide> } <del> if (typeof this.options.time.parser === 'function') { <del> return this.options.time.parser(label); <add> if (typeof me.options.time.parser === 'function') { <add> return me.options.time.parser(label); <ide> } <ide> // Date objects <ide> if (typeof label.getMonth === 'function' || typeof label === 'number') { <ide> module.exports = function(Chart) { <ide> return label; <ide> } <ide> // Custom parsing (return an instance of moment) <del> if (typeof this.options.time.format !== 'string' && this.options.time.format.call) { <add> if (typeof me.options.time.format !== 'string' && me.options.time.format.call) { <ide> console.warn("options.time.format is deprecated and replaced by options.time.parser. See http://nnnick.github.io/Chart.js/docs-v2/#scales-time-scale"); <del> return this.options.time.format(label); <add> return me.options.time.format(label); <ide> } <ide> // Moment format parsing <del> return moment(label, this.options.time.format); <add> return moment(label, me.options.time.format); <ide> } <ide> }); <ide> Chart.scaleService.registerScaleType("time", TimeScale, defaultConfig);
22
Ruby
Ruby
remove unused require
99782bd2b85c58a95ebd1a104c08a52487de6dd6
<ide><path>activesupport/lib/active_support/encrypted_file.rb <ide> <ide> require "pathname" <ide> require "active_support/message_encryptor" <del>require "active_support/core_ext/string/strip" <del>require "active_support/core_ext/module/delegation" <ide> <ide> module ActiveSupport <ide> class EncryptedFile
1
PHP
PHP
remove unnecessary else statement
46529ae3f24f69c65e159c8cdb16ce21da36a44c
<ide><path>src/Illuminate/Foundation/Console/ExceptionMakeCommand.php <ide> protected function getStub() <ide> return $this->option('report') <ide> ? __DIR__.'/stubs/exception-render-report.stub' <ide> : __DIR__.'/stubs/exception-render.stub'; <del> } else { <del> return $this->option('report') <del> ? __DIR__.'/stubs/exception-report.stub' <del> : __DIR__.'/stubs/exception.stub'; <ide> } <add> <add> return $this->option('report') <add> ? __DIR__.'/stubs/exception-report.stub' <add> : __DIR__.'/stubs/exception.stub'; <add> <ide> } <ide> <ide> /**
1
Text
Text
fix forgot import `applymiddleware`
3c4cc66fb70d7ca2641f2cfdbe1813179fb11959
<ide><path>docs/recipes/ConfiguringYourStore.md <ide> Let's add these to our existing `index.js`. <ide> import React from 'react' <ide> import { render } from 'react-dom' <ide> import { Provider } from 'react-redux' <del>import { createStore, compose } from 'redux' <add>import { applyMiddleware, createStore, compose } from 'redux' <ide> import thunkMiddleware from 'redux-thunk' <ide> import rootReducer from './reducers' <ide> import loggerMiddleware from './middleware/logger'
1
Go
Go
check return value of createsecretdir
426f4e48e3e53b2445835585d7957043a5fe6ab3
<ide><path>daemon/container_operations_unix.go <ide> func (daemon *Daemon) setupSecretDir(c *container.Container, hasSecretDir *bool) <ide> } <ide> <ide> if !*hasSecretDir { <del> daemon.createSecretDir(c) <add> if err := daemon.createSecretDir(c); err != nil { <add> return err <add> } <ide> *hasSecretDir = true <ide> } <ide> <ide> func (daemon *Daemon) setupConfigDir(c *container.Container, hasSecretDir *bool) <ide> configRef.Sensitive = true <ide> fPath, err = c.SensitiveConfigFilePath(*configRef.ConfigReference) <ide> if !*hasSecretDir { <del> daemon.createSecretDir(c) <add> if err := daemon.createSecretDir(c); err != nil { <add> return err <add> } <ide> *hasSecretDir = true <ide> } <ide> } else {
1
Javascript
Javascript
update ember.deprecate in ember-template-compiler
0425ad642a10545865ed6aa1a70c8cb072b7297f
<ide><path>packages/ember-template-compiler/lib/plugins/deprecate-view-and-controller-paths.js <ide> function deprecatePath(moduleName, node, path) { <ide> } <ide> <ide> return noDeprecate; <del> }, { url: 'http://emberjs.com/deprecations/v1.x#toc_view-and-controller-template-keywords', id: (path.parts && path.parts[0] === 'view' ? 'view.keyword.view' : 'view.keyword.controller') }); <add> }, { url: 'http://emberjs.com/deprecations/v1.x#toc_view-and-controller-template-keywords', id: (path.parts && path.parts[0] === 'view' ? 'view.keyword.view' : 'view.keyword.controller'), until: '2.0.0' }); <ide> } <ide> <ide> function validate(node) { <ide><path>packages/ember-template-compiler/lib/plugins/deprecate-view-helper.js <ide> function deprecateHelper(moduleName, node) { <ide> } else if (paramValue === 'select') { <ide> deprecateSelect(moduleName, node); <ide> } else { <del> Ember.deprecate(`Using the \`{{view "string"}}\` helper is deprecated. ${calculateLocationDisplay(moduleName, node.loc)}`, false, { url: 'http://emberjs.com/deprecations/v1.x#toc_ember-view', id: 'view.helper' }); <add> Ember.deprecate(`Using the \`{{view "string"}}\` helper is deprecated. ${calculateLocationDisplay(moduleName, node.loc)}`, <add> false, <add> { url: 'http://emberjs.com/deprecations/v1.x#toc_ember-view', id: 'view.helper', until: '2.0.0' }); <ide> } <ide> } <ide> <ide> function deprecateSelect(moduleName, node) { <del> Ember.deprecate(`Using \`{{view "select"}}\` is deprecated. ${calculateLocationDisplay(moduleName, node.loc)}`, false, { url: 'http://emberjs.com/deprecations/v1.x#toc_ember-select', id: 'view.helper.select' }); <add> Ember.deprecate(`Using \`{{view "select"}}\` is deprecated. ${calculateLocationDisplay(moduleName, node.loc)}`, <add> false, <add> { url: 'http://emberjs.com/deprecations/v1.x#toc_ember-select', id: 'view.helper.select', until: '2.0.0' }); <ide> } <ide> <ide> function validate(node) { <ide><path>packages/ember-template-compiler/lib/plugins/transform-each-into-collection.js <ide> TransformEachIntoCollection.prototype.transform = function TransformEachIntoColl <ide> let moduleInfo = calculateLocationDisplay(moduleName, legacyHashKey.loc); <ide> <ide> Ember.deprecate( <del> `Using '${legacyHashKey.key}' with '{{each}}' ${moduleInfo}is deprecated. Please refactor to a component.` <add> `Using '${legacyHashKey.key}' with '{{each}}' ${moduleInfo}is deprecated. Please refactor to a component.`, <add> false, <add> { id: 'ember-template-compiler.transform-each-into-collection', until: '2.0.0' } <ide> ); <ide> <ide> let list = node.params.shift(); <ide><path>packages/ember-template-compiler/lib/plugins/transform-input-on-to-onEvent.js <ide> TransformInputOnToOnEvent.prototype.transform = function TransformInputOnToOnEve <ide> <ide> if (normalizedOn && normalizedOn.value.type !== 'StringLiteral') { <ide> Ember.deprecate( <del> `Using a dynamic value for '#{normalizedOn.key}=' with the '{{input}}' helper ${moduleInfo}is deprecated.` <add> `Using a dynamic value for '#{normalizedOn.key}=' with the '{{input}}' helper ${moduleInfo}is deprecated.`, <add> false, <add> { id: 'ember-template-compiler.transform-input-on-to-onEvent.dynamic-value', until: '3.0.0' } <ide> ); <ide> <ide> normalizedOn.key = 'onEvent'; <ide> TransformInputOnToOnEvent.prototype.transform = function TransformInputOnToOnEve <ide> <ide> if (!action) { <ide> Ember.deprecate( <del> `Using '{{input ${normalizedOn.key}="${normalizedOn.value.value}" ...}}' without specifying an action ${moduleInfo}will do nothing.` <add> `Using '{{input ${normalizedOn.key}="${normalizedOn.value.value}" ...}}' without specifying an action ${moduleInfo}will do nothing.`, <add> false, <add> { id: 'ember-template-compiler.transform-input-on-to-onEvent.no-action', until: '3.0.0' } <ide> ); <ide> <ide> return; // exit early, if no action was available there is nothing to do <ide> TransformInputOnToOnEvent.prototype.transform = function TransformInputOnToOnEve <ide> let expected = `${normalizedOn ? normalizedOn.value.value : 'enter'}="${action.value.original}"`; <ide> <ide> Ember.deprecate( <del> `Using '{{input ${specifiedOn}action="${action.value.original}"}}' ${moduleInfo}is deprecated. Please use '{{input ${expected}}}' instead.` <add> `Using '{{input ${specifiedOn}action="${action.value.original}"}}' ${moduleInfo}is deprecated. Please use '{{input ${expected}}}' instead.`, <add> false, <add> { id: 'ember-template-compiler.transform-input-on-to-onEvent.normalized-on', until: '3.0.0' } <ide> ); <ide> if (!normalizedOn) { <ide> normalizedOn = b.pair('onEvent', b.string('enter')); <ide><path>packages/ember-template-compiler/lib/plugins/transform-old-binding-syntax.js <ide> TransformOldBindingSyntax.prototype.transform = function TransformOldBindingSynt <ide> if (key.substr(-7) === 'Binding') { <ide> let newKey = key.slice(0, -7); <ide> <del> Ember.deprecate(`You're using legacy binding syntax: ${key}=${exprToString(value)} ${sourceInformation}. Please replace with ${newKey}=${value.original}`); <add> Ember.deprecate( <add> `You're using legacy binding syntax: ${key}=${exprToString(value)} ${sourceInformation}. Please replace with ${newKey}=${value.original}`, <add> false, <add> { id: 'ember-template-compiler.transform-old-binding-syntax', until: '3.0.0' } <add> ); <ide> <ide> pair.key = newKey; <ide> if (value.type === 'StringLiteral') {
5
Javascript
Javascript
remove unused epic
c79afa99b54a0960fe411c1b1047874f1d6beef9
<ide><path>common/app/Nav/redux/bin-epic.js <del>import { ofType } from 'redux-epic'; <del> <del>import { types } from './'; <del> <del>import { hidePane } from '../../Panes/redux'; <del> <del>export default function binEpic(actions) { <del> return actions::ofType(types.clickOnMap) <del> .map(() => hidePane('Map')); <del>} <ide><path>common/app/Nav/redux/index.js <ide> import { <ide> } from 'berkeleys-redux-utils'; <ide> <ide> import loadCurrentChallengeEpic from './load-current-challenge-epic.js'; <del>import binEpic from './bin-epic.js'; <ide> import ns from '../ns.json'; <ide> import { createEventMetaCreator } from '../../redux'; <ide> <ide> export const epics = [ <del> loadCurrentChallengeEpic, <del> binEpic <add> loadCurrentChallengeEpic <ide> ]; <ide> <ide> export const types = createTypes([
2
Python
Python
reenable the test_conv_kernel_mask_rect_kernel
235068530b193c0786e9a038223f341d7008058f
<ide><path>keras/utils/conv_utils_test.py <ide> def test_conv_kernel_mask_almost_full_stride(self, *input_shape): <ide> ), <ide> ) <ide> <del> def DISABLED_test_conv_kernel_mask_rect_kernel(self, *input_shape): <add> def test_conv_kernel_mask_rect_kernel(self, *input_shape): <ide> padding = "valid" <ide> ndims = len(input_shape) <ide> strides = (1,) * ndims
1
Python
Python
remove old serialization tests
7253b4e649a4c1778b01e3d0a709852b0d54fdaa
<ide><path>spacy/tests/serialize/test_codecs.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>from ...serialize.packer import _BinaryCodec <del>from ...serialize.huffman import HuffmanCodec <del>from ...serialize.bits import BitArray <del> <del>import numpy <del>import pytest <del> <del> <del>def test_serialize_codecs_binary(): <del> codec = _BinaryCodec() <del> bits = BitArray() <del> array = numpy.array([0, 1, 0, 1, 1], numpy.int32) <del> codec.encode(array, bits) <del> result = numpy.array([0, 0, 0, 0, 0], numpy.int32) <del> bits.seek(0) <del> codec.decode(bits, result) <del> assert list(array) == list(result) <del> <del> <del>def test_serialize_codecs_attribute(): <del> freqs = {'the': 10, 'quick': 3, 'brown': 4, 'fox': 1, 'jumped': 5, <del> 'over': 8, 'lazy': 1, 'dog': 2, '.': 9} <del> int_map = {'the': 0, 'quick': 1, 'brown': 2, 'fox': 3, 'jumped': 4, <del> 'over': 5, 'lazy': 6, 'dog': 7, '.': 8} <del> <del> codec = HuffmanCodec([(int_map[string], freq) for string, freq in freqs.items()]) <del> bits = BitArray() <del> array = numpy.array([1, 7], dtype=numpy.int32) <del> codec.encode(array, bits) <del> result = numpy.array([0, 0], dtype=numpy.int32) <del> bits.seek(0) <del> codec.decode(bits, result) <del> assert list(array) == list(result) <del> <del> <del>def test_serialize_codecs_vocab(en_vocab): <del> words = ["the", "dog", "jumped"] <del> for word in words: <del> _ = en_vocab[word] <del> codec = HuffmanCodec([(lex.orth, lex.prob) for lex in en_vocab]) <del> bits = BitArray() <del> ids = [en_vocab[s].orth for s in words] <del> array = numpy.array(ids, dtype=numpy.int32) <del> codec.encode(array, bits) <del> result = numpy.array(range(len(array)), dtype=numpy.int32) <del> bits.seek(0) <del> codec.decode(bits, result) <del> assert list(array) == list(result) <ide><path>spacy/tests/serialize/test_huffman.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del>from __future__ import division <del> <del>from ...serialize.huffman import HuffmanCodec <del>from ...serialize.bits import BitArray <del> <del> <del>from heapq import heappush, heappop, heapify <del>from collections import defaultdict <del>import numpy <del>import pytest <del> <del> <del>def py_encode(symb2freq): <del> """Huffman encode the given dict mapping symbols to weights <del> From Rosetta Code <del> """ <del> heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] <del> heapify(heap) <del> while len(heap) > 1: <del> lo = heappop(heap) <del> hi = heappop(heap) <del> for pair in lo[1:]: <del> pair[1] = '0' + pair[1] <del> for pair in hi[1:]: <del> pair[1] = '1' + pair[1] <del> heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) <del> return dict(heappop(heap)[1:]) <del> <del> <del>def test_serialize_huffman_1(): <del> probs = numpy.zeros(shape=(10,), dtype=numpy.float32) <del> probs[0] = 0.3 <del> probs[1] = 0.2 <del> probs[2] = 0.15 <del> probs[3] = 0.1 <del> probs[4] = 0.06 <del> probs[5] = 0.02 <del> probs[6] = 0.01 <del> probs[7] = 0.005 <del> probs[8] = 0.0001 <del> probs[9] = 0.000001 <del> <del> codec = HuffmanCodec(list(enumerate(probs))) <del> py_codes = py_encode(dict(enumerate(probs))) <del> py_codes = list(py_codes.items()) <del> py_codes.sort() <del> assert codec.strings == [c for i, c in py_codes] <del> <del> <del>def test_serialize_huffman_empty(): <del> codec = HuffmanCodec({}) <del> assert codec.strings == [] <del> <del> <del>def test_serialize_huffman_round_trip(): <del> words = ['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'the', <del> 'lazy', 'dog', '.'] <del> freqs = {'the': 10, 'quick': 3, 'brown': 4, 'fox': 1, 'jumped': 5, <del> 'over': 8, 'lazy': 1, 'dog': 2, '.': 9} <del> <del> codec = HuffmanCodec(freqs.items()) <del> strings = list(codec.strings) <del> codes = dict([(codec.leaves[i], strings[i]) for i in range(len(codec.leaves))]) <del> bits = codec.encode(words) <del> string = ''.join('{0:b}'.format(c).rjust(8, '0')[::-1] for c in bits.as_bytes()) <del> for word in words: <del> code = codes[word] <del> assert string[:len(code)] == code <del> string = string[len(code):] <del> unpacked = [0] * len(words) <del> bits.seek(0) <del> codec.decode(bits, unpacked) <del> assert words == unpacked <del> <del> <del>def test_serialize_huffman_rosetta(): <del> text = "this is an example for huffman encoding" <del> symb2freq = defaultdict(int) <del> for ch in text: <del> symb2freq[ch] += 1 <del> by_freq = list(symb2freq.items()) <del> by_freq.sort(reverse=True, key=lambda item: item[1]) <del> symbols = [sym for sym, prob in by_freq] <del> <del> codec = HuffmanCodec(symb2freq.items()) <del> py_codec = py_encode(symb2freq) <del> <del> codes = dict([(codec.leaves[i], codec.strings[i]) for i in range(len(codec.leaves))]) <del> <del> my_lengths = defaultdict(int) <del> py_lengths = defaultdict(int) <del> for symb, freq in symb2freq.items(): <del> my = codes[symb] <del> my_lengths[len(my)] += freq <del> py_lengths[len(py_codec[symb])] += freq <del> my_exp_len = sum(length * weight for length, weight in my_lengths.items()) <del> py_exp_len = sum(length * weight for length, weight in py_lengths.items()) <del> assert my_exp_len == py_exp_len <del> <del> <del>@pytest.mark.models <del>def test_vocab(EN): <del> codec = HuffmanCodec([(w.orth, numpy.exp(w.prob)) for w in EN.vocab]) <del> expected_length = 0 <del> for i, code in enumerate(codec.strings): <del> leaf = codec.leaves[i] <del> expected_length += len(code) * numpy.exp(EN.vocab[leaf].prob) <del> assert 8 < expected_length < 15 <ide><path>spacy/tests/serialize/test_io.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>from ...tokens import Doc <del>from ..util import get_doc <del> <del>import pytest <del> <del> <del>def test_serialize_io_read_write(en_vocab, text_file_b): <del> text1 = ["This", "is", "a", "simple", "test", ".", "With", "a", "couple", "of", "sentences", "."] <del> text2 = ["This", "is", "another", "test", "document", "."] <del> <del> doc1 = get_doc(en_vocab, text1) <del> doc2 = get_doc(en_vocab, text2) <del> text_file_b.write(doc1.to_bytes()) <del> text_file_b.write(doc2.to_bytes()) <del> text_file_b.seek(0) <del> bytes1, bytes2 = Doc.read_bytes(text_file_b) <del> result1 = get_doc(en_vocab).from_bytes(bytes1) <del> result2 = get_doc(en_vocab).from_bytes(bytes2) <del> assert result1.text_with_ws == doc1.text_with_ws <del> assert result2.text_with_ws == doc2.text_with_ws <del> <del> <del>def test_serialize_io_left_right(en_vocab): <del> text = ["This", "is", "a", "simple", "test", ".", "With", "a", "couple", "of", "sentences", "."] <del> doc = get_doc(en_vocab, text) <del> result = Doc(en_vocab).from_bytes(doc.to_bytes()) <del> <del> for token in result: <del> assert token.head.i == doc[token.i].head.i <del> if token.head is not token: <del> assert token.i in [w.i for w in token.head.children] <del> for child in token.lefts: <del> assert child.head.i == token.i <del> for child in token.rights: <del> assert child.head.i == token.i <del> <del> <del>@pytest.mark.models <del>def test_lemmas(EN): <del> text = "The geese are flying" <del> doc = EN(text) <del> result = Doc(doc.vocab).from_bytes(doc.to_bytes()) <del> assert result[1].lemma_ == 'goose' <del> assert result[2].lemma_ == 'be' <del> assert result[3].lemma_ == 'fly' <ide><path>spacy/tests/serialize/test_packer.py <del># coding: utf-8 <del>from __future__ import unicode_literals <del> <del>from ...attrs import TAG, DEP, HEAD <del>from ...serialize.packer import Packer <del>from ...serialize.bits import BitArray <del> <del>from ..util import get_doc <del> <del>import pytest <del> <del> <del>@pytest.fixture <del>def text(): <del> return "the dog jumped" <del> <del> <del>@pytest.fixture <del>def text_b(): <del> return b"the dog jumped" <del> <del> <del>def test_serialize_char_packer(en_vocab, text_b): <del> packer = Packer(en_vocab, []) <del> bits = BitArray() <del> bits.seek(0) <del> byte_str = bytearray(text_b) <del> packer.char_codec.encode(byte_str, bits) <del> bits.seek(0) <del> result = [b''] * len(byte_str) <del> packer.char_codec.decode(bits, result) <del> assert bytearray(result) == byte_str <del> <del> <del>def test_serialize_packer_unannotated(en_tokenizer, text): <del> packer = Packer(en_tokenizer.vocab, []) <del> tokens = en_tokenizer(text) <del> assert tokens.text_with_ws == text <del> bits = packer.pack(tokens) <del> result = packer.unpack(bits) <del> assert result.text_with_ws == text <del> <del> <del>def test_packer_annotated(en_vocab, text): <del> heads = [1, 1, 0] <del> deps = ['det', 'nsubj', 'ROOT'] <del> tags = ['DT', 'NN', 'VBD'] <del> <del> attr_freqs = [ <del> (TAG, [(en_vocab.strings['NN'], 0.1), <del> (en_vocab.strings['DT'], 0.2), <del> (en_vocab.strings['JJ'], 0.01), <del> (en_vocab.strings['VBD'], 0.05)]), <del> (DEP, {en_vocab.strings['det']: 0.2, <del> en_vocab.strings['nsubj']: 0.1, <del> en_vocab.strings['adj']: 0.05, <del> en_vocab.strings['ROOT']: 0.1}.items()), <del> (HEAD, {0: 0.05, 1: 0.2, -1: 0.2, -2: 0.1, 2: 0.1}.items()) <del> ] <del> <del> packer = Packer(en_vocab, attr_freqs) <del> doc = get_doc(en_vocab, [t for t in text.split()], tags=tags, deps=deps, heads=heads) <del> <del> # assert doc.text_with_ws == text <del> assert [t.tag_ for t in doc] == tags <del> assert [t.dep_ for t in doc] == deps <del> assert [(t.head.i-t.i) for t in doc] == heads <del> <del> bits = packer.pack(doc) <del> result = packer.unpack(bits) <del> <del> # assert result.text_with_ws == text <del> assert [t.tag_ for t in result] == tags <del> assert [t.dep_ for t in result] == deps <del> assert [(t.head.i-t.i) for t in result] == heads <del> <del> <del>def test_packer_bad_chars(en_tokenizer): <del> text = "naja gut, is eher bl\xf6d und nicht mit reddit.com/digg.com vergleichbar; vielleicht auf dem weg dahin" <del> packer = Packer(en_tokenizer.vocab, []) <del> <del> doc = en_tokenizer(text) <del> bits = packer.pack(doc) <del> result = packer.unpack(bits) <del> assert result.string == doc.string <del> <del> <del>@pytest.mark.models <del>def test_packer_bad_chars_tags(EN): <del> text = "naja gut, is eher bl\xf6d und nicht mit reddit.com/digg.com vergleichbar; vielleicht auf dem weg dahin" <del> tags = ['JJ', 'NN', ',', 'VBZ', 'DT', 'NN', 'JJ', 'NN', 'NN', <del> 'ADD', 'NN', ':', 'NN', 'NN', 'NN', 'NN', 'NN'] <del> <del> tokens = EN.tokenizer(text) <del> doc = get_doc(tokens.vocab, [t.text for t in tokens], tags=tags) <del> byte_string = doc.to_bytes() <del> result = get_doc(tokens.vocab).from_bytes(byte_string) <del> assert [t.tag_ for t in result] == [t.tag_ for t in doc]
4
Text
Text
add missing italics to list items in readme
21fcca7fdc8622567b79bc84c3921a9ae7c22501
<ide><path>README.md <ide> This is usually difficult for several reasons: <ide> typically don't work well with each other, requiring awkward <ide> custom integrations. <ide> <del> * Conflicting dependencies. Different applications may depend on <add> * *Conflicting dependencies*. Different applications may depend on <ide> different versions of the same dependency. Packaging tools handle <ide> these situations with various degrees of ease - but they all <ide> handle them in different and incompatible ways, which again forces <ide> the developer to do extra work. <ide> <del> * Custom dependencies. A developer may need to prepare a custom <add> * *Custom dependencies*. A developer may need to prepare a custom <ide> version of their application's dependency. Some packaging systems <ide> can handle custom versions of a dependency, others can't - and all <ide> of them handle it differently.
1
Ruby
Ruby
add missing blacklisted formulae
0432feabd33e4fa02e5089783080e9568c982a77
<ide><path>Library/Homebrew/test/missing_formula_spec.rb <ide> expect("haskell-platform").to be_blacklisted <ide> end <ide> <add> specify "mysqldump-secure is blacklisted" do <add> expect("mysqldump-secure").to be_blacklisted <add> end <add> <add> specify "ngrok is blacklisted" do <add> expect("ngrok").to be_blacklisted <add> end <add> <ide> specify "Xcode is blacklisted", :needs_macos do <ide> expect(%w[xcode Xcode]).to all be_blacklisted <ide> end
1
Ruby
Ruby
remove private def
0fe2bb816f60f4daf5d0d24468af94be971d0eaf
<ide><path>actioncable/test/channel/stream_test.rb <ide> def send_confirmation <ide> transmit_subscription_confirmation <ide> end <ide> <del> private def pick_coder(coder) <del> case coder <del> when nil, "json" <del> ActiveSupport::JSON <del> when "custom" <del> DummyEncoder <del> when "none" <del> nil <add> private <add> def pick_coder(coder) <add> case coder <add> when nil, "json" <add> ActiveSupport::JSON <add> when "custom" <add> DummyEncoder <add> when "none" <add> nil <add> end <ide> end <del> end <ide> end <ide> <ide> module DummyEncoder <ide><path>actionmailer/test/abstract_unit.rb <ide> def self.root <ide> class ActiveSupport::TestCase <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <ide> end <ide><path>actionpack/test/abstract_unit.rb <ide> def translate_exceptions(result) <ide> class ActiveSupport::TestCase <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <ide> end <ide> <ide> class DrivenByRackTest < ActionDispatch::SystemTestCase <ide><path>actionpack/test/controller/new_base/render_context_test.rb <ide> def with_layout <ide> "controller context!" <ide> end <ide> <del> # 3) Set view_context to self <del> private def view_context <del> self <del> end <add> private <add> # 3) Set view_context to self <add> def view_context <add> self <add> end <ide> end <ide> <ide> class RenderContextTest < Rack::TestCase <ide><path>actionview/test/abstract_unit.rb <ide> class ActiveSupport::TestCase <ide> include ActionDispatch::DrawOnce <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <ide> end <ide><path>actionview/test/template/form_helper/form_with_test.rb <ide> def test_form_with_attribute_not_on_model <ide> <ide> def test_form_with_doesnt_call_private_or_protected_properties_on_form_object_skipping_value <ide> obj = Class.new do <del> private def private_property <del> "That would be great." <del> end <add> private <add> def private_property <add> "That would be great." <add> end <ide> <del> protected def protected_property <del> "I believe you have my stapler." <del> end <add> protected <add> def protected_property <add> "I believe you have my stapler." <add> end <ide> end.new <ide> <ide> form_with(model: obj, scope: "other_name", url: "/", id: "edit-other-name") do |f| <ide><path>activemodel/test/cases/helper.rb <ide> class ActiveModel::TestCase < ActiveSupport::TestCase <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <ide> end <ide><path>activesupport/test/abstract_unit.rb <ide> class ActiveSupport::TestCase <ide> include ActiveSupport::Testing::MethodCallAssertions <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <del> <del> def frozen_error_class <del> Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <add> <add> def frozen_error_class <add> Object.const_defined?(:FrozenError) ? FrozenError : RuntimeError <add> end <ide> end <ide><path>railties/test/abstract_unit.rb <ide> class Application < Rails::Application <ide> class ActiveSupport::TestCase <ide> include ActiveSupport::Testing::Stream <ide> <del> # Skips the current run on Rubinius using Minitest::Assertions#skip <del> private def rubinius_skip(message = "") <del> skip message if RUBY_ENGINE == "rbx" <del> end <del> # Skips the current run on JRuby using Minitest::Assertions#skip <del> private def jruby_skip(message = "") <del> skip message if defined?(JRUBY_VERSION) <del> end <add> private <add> # Skips the current run on Rubinius using Minitest::Assertions#skip <add> def rubinius_skip(message = "") <add> skip message if RUBY_ENGINE == "rbx" <add> end <add> <add> # Skips the current run on JRuby using Minitest::Assertions#skip <add> def jruby_skip(message = "") <add> skip message if defined?(JRUBY_VERSION) <add> end <ide> end
9
Python
Python
fix issue #566
150e02d72e7db3832a816cbd9d62fefc969f81fe
<ide><path>spacy/language.py <ide> def create_tokenizer(cls, nlp=None): <ide> def create_tagger(cls, nlp=None): <ide> if nlp is None: <ide> return Tagger(cls.create_vocab(), features=cls.tagger_features) <del> elif nlp.path is None: <add> elif nlp.path is False: <ide> return Tagger(nlp.vocab, features=cls.tagger_features) <del> elif not (nlp.path / 'pos').exists(): <add> elif nlp.path is None or not (nlp.path / 'pos').exists(): <ide> return None <ide> else: <ide> return Tagger.load(nlp.path / 'pos', nlp.vocab) <ide> def create_tagger(cls, nlp=None): <ide> def create_parser(cls, nlp=None): <ide> if nlp is None: <ide> return DependencyParser(cls.create_vocab(), features=cls.parser_features) <del> elif nlp.path is None: <add> elif nlp.path is False: <ide> return DependencyParser(nlp.vocab, features=cls.parser_features) <del> elif not (nlp.path / 'deps').exists(): <add> elif nlp.path is None or not (nlp.path / 'deps').exists(): <ide> return None <ide> else: <ide> return DependencyParser.load(nlp.path / 'deps', nlp.vocab) <ide> def create_parser(cls, nlp=None): <ide> def create_entity(cls, nlp=None): <ide> if nlp is None: <ide> return EntityRecognizer(cls.create_vocab(), features=cls.entity_features) <del> elif nlp.path is None: <add> elif nlp.path is False: <ide> return EntityRecognizer(nlp.vocab, features=cls.entity_features) <del> elif not (nlp.path / 'ner').exists(): <add> elif nlp.path is None or not (nlp.path / 'ner').exists(): <ide> return None <ide> else: <ide> return EntityRecognizer.load(nlp.path / 'ner', nlp.vocab) <ide> def create_entity(cls, nlp=None): <ide> def create_matcher(cls, nlp=None): <ide> if nlp is None: <ide> return Matcher(cls.create_vocab()) <del> elif nlp.path is None: <add> elif nlp.path is False: <ide> return Matcher(nlp.vocab) <del> elif not (nlp.path / 'vocab').exists(): <add> elif nlp.path is None or not (nlp.path / 'vocab').exists(): <ide> return None <ide> else: <ide> return Matcher.load(nlp.path / 'vocab', nlp.vocab)
1
Javascript
Javascript
remove error messages for readability
5ea88b74965adba15ad8233c78397e2d7ce5dd3a
<ide><path>test/addons/async-hooks-promise/test.js <ide> if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) { <ide> // Baseline to make sure the internal field isn't being set. <ide> assert.strictEqual( <ide> binding.getPromiseField(Promise.resolve(1)), <del> 0, <del> 'Promise internal field used despite missing enabled AsyncHook'); <add> 0); <ide> <ide> const hook0 = async_hooks.createHook({}).enable(); <ide> <ide> // Check that no PromiseWrap is created when there are no hook callbacks. <ide> assert.strictEqual( <ide> binding.getPromiseField(Promise.resolve(1)), <del> 0, <del> 'Promise internal field used despite missing enabled AsyncHook'); <add> 0); <ide> <ide> hook0.disable(); <ide> <ide> hook1.disable(); <ide> setImmediate(() => { <ide> assert.strictEqual( <ide> binding.getPromiseField(Promise.resolve(1)), <del> 0, <del> 'Promise internal field used despite missing enabled AsyncHook'); <add> 0); <ide> });
1
Python
Python
join code segments with newlines in between
afdbe1880e03014b8a1076005af858d4e52e85fa
<ide><path>weave/ext_tools.py <ide> def __init__(self,name,compiler=''): <ide> def add_function(self,func): <ide> self.functions.append(func) <ide> def module_code(self): <del> code = self.warning_code() + \ <del> self.header_code() + \ <del> self.support_code() + \ <del> self.function_code() + \ <del> self.python_function_definition_code() + \ <del> self.module_init_code() <add> code = '\n'.join([self.warning_code(), <add> self.header_code(), <add> self.support_code(), <add> self.function_code(), <add> self.python_function_definition_code(), <add> self.module_init_code()]) <ide> return code <ide> <ide> def arg_specs(self):
1
Go
Go
remove some dead code
42b87e6a4b1f58fbd5383ce0c12206c994232732
<ide><path>libnetwork/types/types.go <ide> func (br badRequest) Error() string { <ide> } <ide> func (br badRequest) BadRequest() {} <ide> <del>type maskBadRequest string <del> <ide> type notFound string <ide> <ide> func (nf notFound) Error() string { <ide> func (ns noService) Error() string { <ide> } <ide> func (ns noService) NoService() {} <ide> <del>type maskNoService string <del> <ide> type timeout string <ide> <ide> func (to timeout) Error() string {
1
Python
Python
fix gfile issue with numpy by using io library
f0de6d562e31dbac430c9360bf11b6610f73a327
<ide><path>compression/decoder.py <ide> python decoder.py --input_codes=output_codes.pkl --iteration=15 \ <ide> --output_directory=/tmp/compression_output/ --model=residual_gru.pb <ide> """ <add>import io <ide> import os <ide> <ide> import numpy as np <ide> def main(_): <ide> print '\nInput codes not found.\n' <ide> return <ide> <del> with tf.gfile.FastGFile(FLAGS.input_codes, 'rb') as code_file: <del> loaded_codes = np.load(code_file) <add> contents = '' <add> with tf.gfile.FastGFile(FLAGS.input_codes, 'r') as code_file: <add> contents = code_file.read() <add> loaded_codes = np.load(io.BytesIO(contents)) <ide> assert ['codes', 'shape'] not in loaded_codes.files <ide> loaded_shape = loaded_codes['shape'] <ide> loaded_array = loaded_codes['codes'] <ide><path>compression/encoder.py <ide> python encoder.py --input_image=/your/image/here.png \ <ide> --output_codes=output_codes.pkl --iteration=15 --model=residual_gru.pb <ide> """ <add>import io <ide> import os <ide> <ide> import numpy as np <ide> def main(_): <ide> int_codes = (int_codes + 1)/2 <ide> export = np.packbits(int_codes.reshape(-1)) <ide> <del> with tf.gfile.FastGFile(FLAGS.output_codes, 'wb') as code_file: <del> np.savez_compressed(code_file, shape=int_codes.shape, codes=export) <add> output = io.BytesIO() <add> np.savez_compressed(output, shape=int_codes.shape, codes=export) <add> with tf.gfile.FastGFile(FLAGS.output_codes, 'w') as code_file: <add> code_file.write(output.getvalue()) <ide> <ide> <ide> if __name__ == '__main__':
2
Javascript
Javascript
escape webpackcontext.id value
6c6eb3ae9816f342cf2843ea6131f07bcc335f58
<ide><path>lib/ContextModule.js <ide> ContextModule.prototype.source = function() { <ide> "};\n", <ide> "webpackContext.resolve = webpackContextResolve;\n", <ide> "module.exports = webpackContext;\n", <del> "webpackContext.id = " + this.id + ";\n" <add> "webpackContext.id = " + JSON.stringify(this.id) + ";\n" <ide> ]; <ide> } else if(this.blocks && this.blocks.length > 0) { <ide> var items = this.blocks.map(function(block) { <ide> ContextModule.prototype.source = function() { <ide> "\treturn Object.keys(map);\n", <ide> "};\n", <ide> "module.exports = webpackAsyncContext;\n", <del> "webpackAsyncContext.id = " + this.id + ";\n" <add> "webpackAsyncContext.id = " + JSON.stringify(this.id) + ";\n" <ide> ]; <ide> } else { <ide> str = [ <ide> ContextModule.prototype.source = function() { <ide> "webpackEmptyContext.keys = function() { return []; };\n", <ide> "webpackEmptyContext.resolve = webpackEmptyContext;\n", <ide> "module.exports = webpackEmptyContext;\n", <del> "webpackEmptyContext.id = " + this.id + ";\n" <add> "webpackEmptyContext.id = " + JSON.stringify(this.id) + ";\n" <ide> ]; <ide> } <ide> if(this.useSourceMap) {
1
Go
Go
fix potential race in volume creation
8d7c7bd2e3aba3bba72264d477c56444c5dc6350
<ide><path>daemon/volumes.go <ide> func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error) <ide> return nil, err <ide> } <ide> // Check if a volume already exists for this and use it <del> vol := container.daemon.volumes.Get(path) <del> if vol == nil { <del> vol, err = container.daemon.volumes.NewVolume(path, writable) <del> if err != nil { <del> return nil, err <del> } <add> vol, err := container.daemon.volumes.FindOrCreateVolume(path, writable) <add> if err != nil { <add> return nil, err <ide> } <ide> mounts[mountToPath] = &Mount{container: container, volume: vol, MountToPath: mountToPath, Writable: writable} <ide> } <ide> func (container *Container) parseVolumeMountConfig() (map[string]*Mount, error) <ide> continue <ide> } <ide> <del> vol, err := container.daemon.volumes.NewVolume("", true) <add> vol, err := container.daemon.volumes.FindOrCreateVolume("", true) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>volumes/repository.go <ide> func NewRepository(configPath string, driver graphdriver.Driver) (*Repository, e <ide> return repo, repo.restore() <ide> } <ide> <del>func (r *Repository) NewVolume(path string, writable bool) (*Volume, error) { <add>func (r *Repository) newVolume(path string, writable bool) (*Volume, error) { <ide> var ( <ide> isBindMount bool <ide> err error <ide> func (r *Repository) NewVolume(path string, writable bool) (*Volume, error) { <ide> if err := v.initialize(); err != nil { <ide> return nil, err <ide> } <del> if err := r.Add(v); err != nil { <del> return nil, err <del> } <del> return v, nil <add> <add> return v, r.add(v) <ide> } <ide> <ide> func (r *Repository) restore() error { <ide> func (r *Repository) get(path string) *Volume { <ide> func (r *Repository) Add(volume *Volume) error { <ide> r.lock.Lock() <ide> defer r.lock.Unlock() <add> return r.add(volume) <add>} <add> <add>func (r *Repository) add(volume *Volume) error { <ide> if vol := r.get(volume.Path); vol != nil { <ide> return fmt.Errorf("Volume exists: %s", volume.ID) <ide> } <ide> func (r *Repository) createNewVolumePath(id string) (string, error) { <ide> <ide> return path, nil <ide> } <add> <add>func (r *Repository) FindOrCreateVolume(path string, writable bool) (*Volume, error) { <add> r.lock.Lock() <add> defer r.lock.Unlock() <add> <add> if path == "" { <add> return r.newVolume(path, writable) <add> } <add> <add> if v := r.get(path); v != nil { <add> return v, nil <add> } <add> <add> return r.newVolume(path, writable) <add>}
2
Javascript
Javascript
fix nativelinking split
b70152cdefcc6f8e9e519ffac591ab26f49dedc8
<ide><path>Libraries/Linking/Linking.js <ide> import Platform from '../Utilities/Platform'; <ide> import NativeLinkingManager from './NativeLinkingManager'; <ide> import NativeIntentAndroid from './NativeIntentAndroid'; <ide> import invariant from 'invariant'; <add>import nullthrows from 'nullthrows'; <ide> <ide> /** <ide> * `Linking` gives you a general interface to interact with both incoming <ide> import invariant from 'invariant'; <ide> */ <ide> class Linking extends NativeEventEmitter { <ide> constructor() { <del> super(Platform.OS === 'ios' ? NativeLinkingManager : undefined); <add> super(Platform.OS === 'ios' ? nullthrows(NativeLinkingManager) : undefined); <ide> } <ide> <ide> /** <ide> class Linking extends NativeEventEmitter { <ide> openURL(url: string): Promise<void> { <ide> this._validateURL(url); <ide> if (Platform.OS === 'android') { <del> return NativeIntentAndroid.openURL(url); <add> return nullthrows(NativeIntentAndroid).openURL(url); <ide> } else { <del> return NativeLinkingManager.openURL(url); <add> return nullthrows(NativeLinkingManager).openURL(url); <ide> } <ide> } <ide> <ide> class Linking extends NativeEventEmitter { <ide> canOpenURL(url: string): Promise<boolean> { <ide> this._validateURL(url); <ide> if (Platform.OS === 'android') { <del> return NativeIntentAndroid.canOpenURL(url); <add> return nullthrows(NativeIntentAndroid).canOpenURL(url); <ide> } else { <del> return NativeLinkingManager.canOpenURL(url); <add> return nullthrows(NativeLinkingManager).canOpenURL(url); <ide> } <ide> } <ide> <ide> class Linking extends NativeEventEmitter { <ide> */ <ide> openSettings(): Promise<void> { <ide> if (Platform.OS === 'android') { <del> return NativeIntentAndroid.openSettings(); <add> return nullthrows(NativeIntentAndroid).openSettings(); <ide> } else { <del> return NativeLinkingManager.openSettings(); <add> return nullthrows(NativeLinkingManager).openSettings(); <ide> } <ide> } <ide> <ide> class Linking extends NativeEventEmitter { <ide> getInitialURL(): Promise<?string> { <ide> return Platform.OS === 'android' <ide> ? InteractionManager.runAfterInteractions().then(() => <del> NativeIntentAndroid.getInitialURL(), <add> nullthrows(NativeIntentAndroid).getInitialURL(), <ide> ) <del> : NativeLinkingManager.getInitialURL(); <add> : nullthrows(NativeLinkingManager).getInitialURL(); <ide> } <ide> <ide> /* <ide> class Linking extends NativeEventEmitter { <ide> }>, <ide> ): Promise<void> { <ide> if (Platform.OS === 'android') { <del> return NativeIntentAndroid.sendIntent(action, extras); <add> return nullthrows(NativeIntentAndroid).sendIntent(action, extras); <ide> } else { <ide> return new Promise((resolve, reject) => reject(new Error('Unsupported'))); <ide> } <ide><path>Libraries/Linking/NativeIntentAndroid.js <ide> export interface Spec extends TurboModule { <ide> ) => Promise<void>; <ide> } <ide> <del>export default (TurboModuleRegistry.getEnforcing<Spec>('IntentAndroid'): Spec); <add>export default (TurboModuleRegistry.get<Spec>('IntentAndroid'): ?Spec); <ide><path>Libraries/Linking/NativeLinkingManager.js <ide> export interface Spec extends TurboModule { <ide> +removeListeners: (count: number) => void; <ide> } <ide> <del>export default (TurboModuleRegistry.getEnforcing<Spec>('LinkingManager'): Spec); <add>export default (TurboModuleRegistry.get<Spec>('LinkingManager'): ?Spec);
3
Text
Text
add v3.13.2 to changelog
bc435eb0a11868f7e0f8381f9a4bb2ba7728d9e8
<ide><path>CHANGELOG.md <ide> - [#18381](https://github.com/emberjs/ember.js/pull/18381) Drop Node 6 and 11 support. <ide> - [#18410](https://github.com/emberjs/ember.js/pull/18410) Use ember-cli-htmlbars for inline precompilation if possible. <ide> <add>### v3.13.2 (September 25, 2019) <add> <add>- [#18429](https://github.com/emberjs/ember.js/pull/18429) [BUGFIX] Fix incorrect error message when opting into using Octane, and missing optional features. <add> <ide> ### v3.13.1 (September 23, 2019) <ide> <ide> - [#18273](https://github.com/emberjs/ember.js/pull/18273) [BUGFIX] Fix issues with SSR rehydration of <title>.
1
Ruby
Ruby
add head tests
a24a919a40f09930c5ef9f2fe811d16e83fa963a
<ide><path>Library/Homebrew/test/install_test.rb <ide> def test_install_keg_only_outdated <ide> cmd("install", "testball1", "--force") <ide> end <ide> <add> def test_install_head_installed <add> initial_env = ENV.to_hash <add> %w[AUTHOR COMMITTER].each do |role| <add> ENV["GIT_#{role}_NAME"] = "brew tests" <add> ENV["GIT_#{role}_EMAIL"] = "brew-tests@localhost" <add> ENV["GIT_#{role}_DATE"] = "Thu May 21 00:04:11 2009 +0100" <add> end <add> <add> repo_path = HOMEBREW_CACHE.join("repo") <add> repo_path.join("bin").mkpath <add> <add> repo_path.cd do <add> shutup do <add> system "git", "init" <add> system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo" <add> FileUtils.touch "bin/something.bin" <add> FileUtils.touch "README" <add> system "git", "add", "--all" <add> system "git", "commit", "-m", "Initial repo commit" <add> end <add> end <add> <add> setup_test_formula "testball1", <<-EOS.undent <add> version "1.0" <add> head "file://#{repo_path}", :using => :git <add> def install <add> prefix.install Dir["*"] <add> end <add> EOS <add> <add> # Ignore dependencies, because we'll try to resolve requirements in build.rb <add> # and there will be the git requirement, but we cannot instantiate git <add> # formula since we only have testball1 formula. <add> assert_match "#{HOMEBREW_CELLAR}/testball1/HEAD-2ccdf4f", cmd("install", "testball1", "--HEAD", "--ignore-dependencies") <add> assert_match "testball1-HEAD-2ccdf4f already installed", <add> cmd("install", "testball1", "--HEAD", "--ignore-dependencies") <add> assert_match "#{HOMEBREW_CELLAR}/testball1/HEAD-2ccdf4f", cmd("unlink", "testball1") <add> assert_match "#{HOMEBREW_CELLAR}/testball1/1.0", cmd("install", "testball1") <add> <add> ensure <add> ENV.replace(initial_env) <add> repo_path.rmtree <add> end <add> <ide> def test_install_with_invalid_option <ide> setup_test_formula "testball1" <ide> assert_match "testball1: this formula has no --with-fo option so it will be ignored!",
1
Go
Go
apply apparmor before restrictions
76fa7d588adfe644824d9a00dafce2d2991a7013
<ide><path>pkg/apparmor/apparmor.go <ide> func IsEnabled() bool { <ide> return false <ide> } <ide> <del>func ApplyProfile(pid int, name string) error { <add>func ApplyProfile(name string) error { <ide> if name == "" { <ide> return nil <ide> } <ide><path>pkg/apparmor/apparmor_disabled.go <ide> <ide> package apparmor <ide> <del>import () <del> <ide> func IsEnabled() bool { <ide> return false <ide> } <ide> <del>func ApplyProfile(pid int, name string) error { <add>func ApplyProfile(name string) error { <ide> return nil <ide> } <ide><path>pkg/libcontainer/console/console.go <ide> package console <ide> <ide> import ( <ide> "fmt" <del> "github.com/dotcloud/docker/pkg/label" <del> "github.com/dotcloud/docker/pkg/system" <ide> "os" <ide> "path/filepath" <ide> "syscall" <add> <add> "github.com/dotcloud/docker/pkg/label" <add> "github.com/dotcloud/docker/pkg/system" <ide> ) <ide> <ide> // Setup initializes the proper /dev/console inside the rootfs path <ide><path>pkg/libcontainer/nsinit/init.go <ide> func Init(container *libcontainer.Container, uncleanRootfs, consolePath string, <ide> <ide> runtime.LockOSThread() <ide> <add> if err := apparmor.ApplyProfile(container.Context["apparmor_profile"]); err != nil { <add> return fmt.Errorf("set apparmor profile %s: %s", container.Context["apparmor_profile"], err) <add> } <add> if err := label.SetProcessLabel(container.Context["process_label"]); err != nil { <add> return fmt.Errorf("set process label %s", err) <add> } <ide> if container.Context["restrictions"] != "" { <ide> if err := restrict.Restrict(); err != nil { <ide> return err <ide> } <ide> } <del> <del> if err := apparmor.ApplyProfile(os.Getpid(), container.Context["apparmor_profile"]); err != nil { <del> return err <del> } <del> if err := label.SetProcessLabel(container.Context["process_label"]); err != nil { <del> return fmt.Errorf("set process label %s", err) <del> } <ide> if err := FinalizeNamespace(container); err != nil { <ide> return fmt.Errorf("finalize namespace %s", err) <ide> } <ide><path>pkg/libcontainer/security/restrict/restrict.go <ide> package restrict <ide> <ide> import ( <ide> "fmt" <del> "os" <del> "path/filepath" <ide> "syscall" <ide> <ide> "github.com/dotcloud/docker/pkg/system" <ide> func Restrict() error { <ide> if err := system.Mount("/dev/null", "/proc/kcore", "", syscall.MS_BIND, ""); err != nil { <ide> return fmt.Errorf("unable to bind-mount /dev/null over /proc/kcore") <ide> } <del> <del> // This weird trick will allow us to mount /proc read-only, while being able to use AppArmor. <del> // This is because apparently, loading an AppArmor profile requires write access to /proc/1/attr. <del> // So we do another mount of procfs, ensure it's write-able, and bind-mount a subset of it. <del> if err := os.Mkdir(".proc", 0700); err != nil { <del> return fmt.Errorf("unable to create temporary proc mountpoint .proc: %s", err) <del> } <del> if err := system.Mount("proc", ".proc", "proc", 0, ""); err != nil { <del> return fmt.Errorf("unable to mount proc on temporary proc mountpoint: %s", err) <del> } <del> if err := system.Mount("proc", ".proc", "", syscall.MS_REMOUNT, ""); err != nil { <del> return fmt.Errorf("unable to remount proc read-write: %s", err) <del> } <del> for _, path := range []string{"attr", "task"} { <del> if err := system.Mount(filepath.Join(".proc", "1", path), filepath.Join("proc", "1", path), "", syscall.MS_BIND, ""); err != nil { <del> return fmt.Errorf("unable to bind-mount %s: %s", path, err) <del> } <del> } <del> if err := system.Unmount(".proc", 0); err != nil { <del> return fmt.Errorf("unable to unmount temporary proc filesystem: %s", err) <del> } <del> return os.RemoveAll(".proc") <add> return nil <ide> }
5
Python
Python
multi doc update
8d8f26d02bd8710832931949b78b7619cef66273
<ide><path>celery/bin/multi.py <ide> # specify fully qualified nodenames <ide> $ celery multi start foo@worker.example.com bar@worker.example.com -c 3 <ide> <add> # fully qualified nodenames but using the current hostname <add> $ celery multi start foo@%h bar@%h <add> <ide> # Advanced example starting 10 workers in the background: <ide> # * Three of the workers processes the images and video queue <ide> # * Two of the workers processes the data queue with loglevel DEBUG
1
Text
Text
note ruby dependencies
e408cc8b246f1ad9bc3b7d0dada97967332631df
<ide><path>README.md <ide> messages back and forth over the websocket cable connection. This dependency may <ide> be alleviated in the future, but for the moment that's what it is. So be sure to have <ide> Redis installed and running. <ide> <add>The Ruby side of things is built on top of Faye-Websocket and Celluiod. <ide> <ide> ## Deployment <ide>
1
Java
Java
reduce memory consumption
9877a9e6b7d299dc32a447340bbbd0ee6a1076b5
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java <ide> protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] <ide> <ide> List<Object> allInterceptors = new ArrayList<>(); <ide> if (specificInterceptors != null) { <del> allInterceptors.addAll(Arrays.asList(specificInterceptors)); <add> if (specificInterceptors.length > 0) { <add> // specificInterceptors may equals PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS <add> allInterceptors.addAll(Arrays.asList(specificInterceptors)); <add> } <ide> if (commonInterceptors.length > 0) { <ide> if (this.applyCommonInterceptorsFirst) { <ide> allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
1
Text
Text
add v3.23.0-beta.2 to changelog
3a866f974b6605db8a9a2b32355a7388de6ed536
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.23.0-beta.2 (October 19, 2020) <add> <add>- [#19193](https://github.com/emberjs/ember.js/pull/19193) [BUGFIX] Ensure user lifecycle hooks are untracked <add>- [#19213](https://github.com/emberjs/ember.js/pull/19213) [BUGFIX] Update rendering engine to improve error ergonomics. <add> <ide> ### v3.23.0-beta.1 (October 5, 2020) <ide> <ide> - [#19160](https://github.com/emberjs/ember.js/pull/19160) / [#19182](https://github.com/emberjs/ember.js/pull/19182) [FEATURE] Implements the helper manager feature specified in the [Helper Managers RFC](https://github.com/emberjs/rfcs/blob/master/text/0625-helper-managers.md).
1
Go
Go
add mae jemison to name generator
ac1d8bc760de76b815cffe4a2dfb03059f2d86bc
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> // Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil <ide> "jang", <ide> <add> // Mae Carol Jemison - is an American engineer, physician, and former NASA astronaut. She became the first black woman to travel in space when she served as a mission specialist aboard the Space Shuttle Endeavour - https://en.wikipedia.org/wiki/Mae_Jemison <add> "jemison", <add> <ide> // Betty Jennings - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Jean_Bartik <ide> "jennings", <ide>
1
Go
Go
move sysinit to a submodule
db999667245926569b161747eed7e08b2ec1c34c
<ide><path>docker-init/docker-init.go <add>package main <add> <add>import ( <add> "github.com/dotcloud/docker/sysinit" <add>) <add> <add>var ( <add> GITCOMMIT string <add> VERSION string <add>) <add> <add>func main() { <add> // Running in init mode <add> sysinit.SysInit() <add> return <add>} <ide><path>docker/docker.go <ide> import ( <ide> "flag" <ide> "fmt" <ide> "github.com/dotcloud/docker" <add> "github.com/dotcloud/docker/sysinit" <ide> "github.com/dotcloud/docker/utils" <ide> "io/ioutil" <ide> "log" <ide> var ( <ide> func main() { <ide> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" { <ide> // Running in init mode <del> docker.SysInit() <add> sysinit.SysInit() <ide> return <ide> } <ide> // FIXME: Switch d and D ? (to be more sshd like) <ide><path>runtime_test.go <ide> package docker <ide> import ( <ide> "bytes" <ide> "fmt" <add> "github.com/dotcloud/docker/sysinit" <ide> "github.com/dotcloud/docker/utils" <ide> "io" <ide> "log" <ide> func init() { <ide> <ide> // Hack to run sys init during unit testing <ide> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" { <del> SysInit() <add> sysinit.SysInit() <ide> return <ide> } <ide> <add><path>sysinit/sysinit.go <del><path>sysinit.go <del>package docker <add>package sysinit <ide> <ide> import ( <ide> "flag"
4
Ruby
Ruby
fix regression in
652c5bc865ebda25ead84c5cab04a4688b4e2b9a
<ide><path>Library/Homebrew/formula_installer.rb <ide> def pour <ide> end <ide> <ide> keg = Keg.new(formula.prefix) <add> tab = Tab.for_keg(keg) <add> Tab.clear_cache <ide> <del> unless formula.bottle_specification.skip_relocation? <del> tab = Tab.for_keg(keg) <del> Tab.clear_cache <del> keg.replace_placeholders_with_locations tab.changed_files <del> end <add> skip_linkage = formula.bottle_specification.skip_relocation? <add> keg.replace_placeholders_with_locations tab.changed_files, skip_linkage: skip_linkage <ide> <ide> Pathname.glob("#{formula.bottle_prefix}/{etc,var}/**/*") do |path| <ide> path.extend(InstallRenamed) <ide><path>Library/Homebrew/keg_relocate.rb <ide> def replace_locations_with_placeholders <ide> replace_text_in_files(relocation) <ide> end <ide> <del> def replace_placeholders_with_locations(files) <add> def replace_placeholders_with_locations(files, skip_linkage: false) <ide> relocation = Relocation.new( <ide> old_prefix: PREFIX_PLACEHOLDER, <ide> old_cellar: CELLAR_PLACEHOLDER, <ide> def replace_placeholders_with_locations(files) <ide> new_cellar: HOMEBREW_CELLAR.to_s, <ide> new_repository: HOMEBREW_REPOSITORY.to_s <ide> ) <del> relocate_dynamic_linkage(relocation) <add> relocate_dynamic_linkage(relocation) unless skip_linkage <ide> replace_text_in_files(relocation, files: files) <ide> end <ide>
2
Python
Python
fix circular import in onnx.utils
b6a65ae52a6df67180be8f1e162a3d1829a51bc0
<ide><path>src/transformers/onnx/utils.py <ide> <ide> from ctypes import c_float, sizeof <ide> from enum import Enum <del>from typing import Optional, Union <add>from typing import TYPE_CHECKING, Optional, Union <ide> <del>from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer <add> <add>if TYPE_CHECKING: <add> from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer # tests_ignore <ide> <ide> <ide> class ParameterFormat(Enum): <ide> def compute_serialized_parameters_size(num_parameters: int, dtype: ParameterForm <ide> return num_parameters * dtype.size <ide> <ide> <del>def get_preprocessor(model_name: str) -> Optional[Union[AutoTokenizer, AutoFeatureExtractor, AutoProcessor]]: <add>def get_preprocessor(model_name: str) -> Optional[Union["AutoTokenizer", "AutoFeatureExtractor", "AutoProcessor"]]: <ide> """ <ide> Gets a preprocessor (tokenizer, feature extractor or processor) that is available for `model_name`. <ide> <ide> def get_preprocessor(model_name: str) -> Optional[Union[AutoTokenizer, AutoFeatu <ide> returned. If both a tokenizer and a feature extractor exist, an error is raised. The function returns <ide> `None` if no preprocessor is found. <ide> """ <add> # Avoid circular imports by only importing this here. <add> from .. import AutoFeatureExtractor, AutoProcessor, AutoTokenizer # tests_ignore <add> <ide> try: <ide> return AutoProcessor.from_pretrained(model_name) <ide> except (ValueError, OSError, KeyError):
1
PHP
PHP
fix incorrect assertion
827dc77a1114be297ff4b8e2a651ee400740c059
<ide><path>lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php <ide> public function testPaginateOrderModelDefault() { <ide> <ide> $Controller->PaginatorControllerPost->order = 'PaginatorControllerPost.id'; <ide> $result = $Controller->Paginator->validateSort($Controller->PaginatorControllerPost, array()); <del> $this->assertEmpty($result['order']); <add> $this->assertArrayNotHasKey('order', $result); <ide> <ide> $Controller->PaginatorControllerPost->order = array( <ide> 'PaginatorControllerPost.id',
1
Go
Go
remove thin pool if 'initdevmapper' failed
ea22d7ab91e7febc69433b979160dda8a79ad46e
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> func (devices *DeviceSet) enableDeferredRemovalDeletion() error { <ide> return nil <ide> } <ide> <del>func (devices *DeviceSet) initDevmapper(doInit bool) error { <add>func (devices *DeviceSet) initDevmapper(doInit bool) (retErr error) { <ide> // give ourselves to libdm as a log handler <ide> devicemapper.LogInit(devices) <ide> <ide> func (devices *DeviceSet) initDevmapper(doInit bool) error { <ide> if err := devicemapper.CreatePool(devices.getPoolName(), dataFile, metadataFile, devices.thinpBlockSize); err != nil { <ide> return err <ide> } <add> defer func() { <add> if retErr != nil { <add> err = devices.deactivatePool() <add> if err != nil { <add> logrus.Warnf("devmapper: Failed to deactivatePool: %v", err) <add> } <add> } <add> }() <ide> } <ide> <ide> // Pool already exists and caller did not pass us a pool. That means
1
Ruby
Ruby
swallow resourcenotfound error on find_every
4dc05bc8a9824b9404cebecaba28f9f248f9995e
<ide><path>activeresource/lib/active_resource/base.rb <ide> def create(attributes = {}) <ide> # <ide> # StreetAddress.find(1, :params => { :person_id => 1 }) <ide> # # => GET /people/1/street_addresses/1.xml <add> # <add> # == Failure or missing data <add> # A failure to find the requested object raises a ResourceNotFound <add> # exception if the find was called with an id. <add> # With any other scope, find returns nil when no data is returned. <add> # <add> # Person.find(1) <add> # # => raises ResourcenotFound <add> # <add> # Person.find(:all) <add> # Person.find(:first) <add> # Person.find(:last) <add> # # => nil <ide> def find(*arguments) <ide> scope = arguments.slice!(0) <ide> options = arguments.slice!(0) || {} <ide> def exists?(id, options = {}) <ide> private <ide> # Find every resource <ide> def find_every(options) <del> case from = options[:from] <del> when Symbol <del> instantiate_collection(get(from, options[:params])) <del> when String <del> path = "#{from}#{query_string(options[:params])}" <del> instantiate_collection(connection.get(path, headers) || []) <del> else <del> prefix_options, query_options = split_options(options[:params]) <del> path = collection_path(prefix_options, query_options) <del> instantiate_collection( (connection.get(path, headers) || []), prefix_options ) <add> begin <add> case from = options[:from] <add> when Symbol <add> instantiate_collection(get(from, options[:params])) <add> when String <add> path = "#{from}#{query_string(options[:params])}" <add> instantiate_collection(connection.get(path, headers) || []) <add> else <add> prefix_options, query_options = split_options(options[:params]) <add> path = collection_path(prefix_options, query_options) <add> instantiate_collection( (connection.get(path, headers) || []), prefix_options ) <add> end <add> rescue ActiveResource::ResourceNotFound <add> # Swallowing ResourceNotFound exceptions and return nil - as per <add> # ActiveRecord. <add> nil <ide> end <ide> end <ide> <ide><path>activeresource/test/cases/finder_test.rb <ide> def setup <ide> mock.get "/people/1/addresses.xml", {}, @addresses <ide> mock.get "/people/1/addresses/1.xml", {}, @addy <ide> mock.get "/people/1/addresses/2.xml", {}, nil, 404 <add> mock.get "/people/2/addresses.xml", {}, nil, 404 <ide> mock.get "/people/2/addresses/1.xml", {}, nil, 404 <ide> mock.get "/people/Greg/addresses/1.xml", {}, @addy <ide> mock.put "/people/1/addresses/1.xml", {}, nil, 204 <ide> def test_find_by_id_not_found <ide> assert_raise(ActiveResource::ResourceNotFound) { StreetAddress.find(1) } <ide> end <ide> <add> def test_find_all_sub_objects <add> all = StreetAddress.find(:all, :params => { :person_id => 1 }) <add> assert_equal 1, all.size <add> assert_kind_of StreetAddress, all.first <add> end <add> <add> def test_find_all_sub_objects_not_found <add> assert_nothing_raised do <add> addys = StreetAddress.find(:all, :params => { :person_id => 2 }) <add> end <add> end <add> <ide> def test_find_all_by_from <ide> ActiveResource::HttpMock.respond_to { |m| m.get "/companies/1/people.xml", {}, @people_david } <ide>
2
Ruby
Ruby
add method fields_for_with_index to formhelper
7c562d5e460d97b18e4f3367b3cfb13401732920
<ide><path>actionpack/lib/action_view/helpers/form_helper.rb <ide> def apply_form_for_options!(object_or_array, options) #:nodoc: <ide> # ... <ide> # <% end %> <ide> # <add> # In addition, you may want to have access to the current iteration index. <add> # In that case, you can use a similar method called fields_for_with_index <add> # which receives a block with an extra parameter: <add> # <add> # <%= form_for @person do |person_form| %> <add> # ... <add> # <%= person_form.fields_for_with_index :projects do |project_fields, index| %> <add> # Position: <%= index %> <add> # Name: <%= project_fields.text_field :name %> <add> # <% end %> <add> # ... <add> # <% end %> <add> # <ide> # When projects is already an association on Person you can use <ide> # +accepts_nested_attributes_for+ to define the writer method for you: <ide> # <ide> def #{selector}(method, options = {}) # def text_field(method, options = {}) <ide> RUBY_EVAL <ide> end <ide> <add> def fields_for_with_index(record_name, record_object = nil, fields_options = {}, &block) <add> index = fields_options[:index] || options[:child_index] || nested_child_index(@object_name) <add> block_with_index = Proc.new{ |obj| block.call(obj, index) } <add> fields_for(record_name, record_object, fields_options, &block_with_index) <add> end <add> <ide> def fields_for(record_name, record_object = nil, fields_options = {}, &block) <ide> fields_options, record_object = record_object, nil if record_object.is_a?(Hash) <ide> fields_options[:builder] ||= options[:builder] <ide><path>actionpack/test/template/form_helper_test.rb <ide> def test_nested_fields_for_with_index_and_parent_fields <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_index_and_parent_fields <add> form_for(@post, :index => 1) do |c| <add> concat c.text_field(:title) <add> concat c.fields_for_with_index('comment', @comment, :index => 1) { |r, comment_index| <add> concat r.text_field(:name, "data-index" => comment_index) <add> } <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') do <add> "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" + <add> "<input name='post[1][comment][1][name]' size='30' type='text' id='post_1_comment_1_name' value='new comment' data-index='1' />" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_form_for_with_index_and_nested_fields_for <ide> output_buffer = form_for(@post, :index => 1) do |f| <ide> concat f.fields_for(:comment, @post) { |c| <ide> def test_nested_fields_for_with_index_radio_button <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_index_radio_button <add> form_for(@post) do |f| <add> concat f.fields_for_with_index(:comment, @post, :index => 5) { |c, index| <add> concat c.radio_button(:title, "hello", "data-index" => index) <add> } <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', 'put') do <add> "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' data-index='5' />" <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_nested_fields_for_with_auto_index_on_both <ide> form_for(@post, :as => "post[]") do |f| <ide> concat f.fields_for("comment[]", @post) { |c| <ide> def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collecti <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_existing_records_on_a_nested_attributes_collection_association <add> @post.comments = Array.new(2) { |id| Comment.new(id + 1) } <add> <add> form_for(@post) do |f| <add> concat f.text_field(:title) <add> @post.comments.each do |comment| <add> concat f.fields_for_with_index(:comments, comment) { |cf, index| <add> concat cf.text_field(:name, "data-index" => index) <add> } <add> end <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do <add> '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + <add> '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" data-index="0" />' + <add> '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + <add> '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" data-index="1" />' + <add> '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id <ide> @post.comments = Array.new(2) { |id| Comment.new(id + 1) } <ide> @post.author = Author.new(321) <ide> def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collecti <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id <add> @post.comments = Array.new(2) { |id| Comment.new(id + 1) } <add> @post.author = Author.new(321) <add> <add> form_for(@post) do |f| <add> concat f.text_field(:title) <add> concat f.fields_for(:author) { |af| <add> concat af.text_field(:name) <add> } <add> @post.comments.each do |comment| <add> concat f.fields_for_with_index(:comments, comment, :include_id => false) { |cf, index| <add> concat cf.text_field(:name, 'data-index' => index) <add> } <add> end <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do <add> '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + <add> '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + <add> '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + <add> '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" data-index="0" />' + <add> '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" data-index="1" />' <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <ide> def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_disabled_hidden_id_inherited <ide> @post.comments = Array.new(2) { |id| Comment.new(id + 1) } <ide> @post.author = Author.new(321) <ide> def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_as <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_new_records_on_a_nested_attributes_collection_association <add> @post.comments = [Comment.new, Comment.new] <add> <add> form_for(@post) do |f| <add> concat f.text_field(:title) <add> @post.comments.each do |comment| <add> concat f.fields_for_with_index(:comments, comment) { |cf, index| <add> concat cf.text_field(:name, "data-index" => index) <add> } <add> end <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do <add> '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + <add> '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" data-index="0" />' + <add> '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" data-index="1" />' <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <add> <ide> def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association <ide> @post.comments = [Comment.new(321), Comment.new] <ide> <ide> def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_ <ide> assert_dom_equal expected, output_buffer <ide> end <ide> <add> def test_nested_fields_for_with_index_with_existing_and_new_records_on_a_nested_attributes_collection_association <add> @post.comments = [Comment.new(321), Comment.new] <add> <add> form_for(@post) do |f| <add> concat f.text_field(:title) <add> @post.comments.each do |comment| <add> concat f.fields_for_with_index(:comments, comment) { |cf, index| <add> concat cf.text_field(:name, "data-index" => index) <add> } <add> end <add> end <add> <add> expected = whole_form('/posts/123', 'edit_post_123', 'edit_post', :method => 'put') do <add> '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + <add> '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" data-index="0" />' + <add> '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + <add> '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" data-index="1" />' <add> end <add> <add> assert_dom_equal expected, output_buffer <add> end <add> <add> <ide> def test_nested_fields_for_with_an_empty_supplied_attributes_collection <ide> form_for(@post) do |f| <ide> concat f.text_field(:title)
2
Go
Go
allow anonymous pulls
96010e3ca134acb4707bbbb1fd8649d7de671229
<ide><path>commands.go <ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string <ide> return nil <ide> } <ide> <del> if srv.runtime.authConfig == nil { <del> return fmt.Errorf("Please login prior to push. ('docker login')") <del> } <del> <ide> if srv.runtime.graph.LookupRemoteImage(remote, srv.runtime.authConfig) { <ide> fmt.Fprintf(stdout, "Pulling %s...\n", remote) <ide> if err := srv.runtime.graph.PullImage(remote, srv.runtime.authConfig); err != nil {
1
PHP
PHP
fix compatibility with php 5.2
c5092851d1e0caa960aa324cebac6405be946179
<ide><path>lib/Cake/Test/Case/Utility/SecurityTest.php <ide> public function testEncryptInvalidData() { <ide> Security::encrypt($txt, $key); <ide> } <ide> <del> <ide> /** <ide> * Test that short keys cause errors <ide> * <ide><path>lib/Cake/Utility/Security.php <ide> protected static function _crypt($password, $salt = false) { <ide> * @throws CakeException On invalid data or key. <ide> */ <ide> public static function encrypt($plain, $key) { <del> static::_checkKey($key, 'encrypt()'); <add> self::_checkKey($key, 'encrypt()'); <ide> if (empty($plain)) { <ide> throw new CakeException(__d('cake_dev', 'The data to encrypt cannot be empty.')); <ide> } <ide> protected static function _checkKey($key, $method) { <ide> * @throws CakeException On invalid data or key. <ide> */ <ide> public static function decrypt($cipher, $key) { <del> static::_checkKey($key, 'decrypt()'); <add> self::_checkKey($key, 'decrypt()'); <ide> if (empty($cipher)) { <ide> throw new CakeException(__d('cake_dev', 'The data to decrypt cannot be empty.')); <ide> }
2
Go
Go
use osl.initoscontext appropriately
64edd40fcccedaccccdc8091ad27c003786ce2b4
<ide><path>libnetwork/drivers/ipvlan/ipvlan_endpoint.go <ide> import ( <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/netutils" <add> "github.com/docker/libnetwork/osl" <ide> "github.com/docker/libnetwork/types" <ide> "github.com/vishvananda/netlink" <ide> ) <ide> <ide> // CreateEndpoint assigns the mac, ip and endpoint id for the new container <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> epOptions map[string]interface{}) error { <add> defer osl.InitOSContext()() <ide> <ide> if err := validateID(nid, eid); err != nil { <ide> return err <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> <ide> // DeleteEndpoint remove the endpoint and associated netlink interface <ide> func (d *driver) DeleteEndpoint(nid, eid string) error { <add> defer osl.InitOSContext()() <ide> if err := validateID(nid, eid); err != nil { <ide> return err <ide> } <ide><path>libnetwork/drivers/ipvlan/ipvlan_joinleave.go <ide> func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, <ide> <ide> // Leave method is invoked when a Sandbox detaches from an endpoint. <ide> func (d *driver) Leave(nid, eid string) error { <add> defer osl.InitOSContext()() <ide> network, err := d.getNetwork(nid) <ide> if err != nil { <ide> return err <ide><path>libnetwork/drivers/ipvlan/ipvlan_network.go <ide> import ( <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/options" <add> "github.com/docker/libnetwork/osl" <ide> "github.com/docker/libnetwork/types" <ide> ) <ide> <ide> // CreateNetwork the network for the specified driver type <ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, ipV4Data, ipV6Data []driverapi.IPAMData) error { <add> defer osl.InitOSContext()() <ide> kv, err := kernel.GetKernelVersion() <ide> if err != nil { <ide> return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err) <ide> func (d *driver) createNetwork(config *configuration) error { <ide> <ide> // DeleteNetwork the network for the specified driver type <ide> func (d *driver) DeleteNetwork(nid string) error { <add> defer osl.InitOSContext()() <ide> n := d.network(nid) <ide> if n == nil { <ide> return fmt.Errorf("network id %s not found", nid) <ide><path>libnetwork/drivers/ipvlan/ipvlan_setup.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/libnetwork/osl" <ide> "github.com/vishvananda/netlink" <ide> ) <ide> <ide> const ( <ide> <ide> // createIPVlan Create the ipvlan slave specifying the source name <ide> func createIPVlan(containerIfName, parent, ipvlanMode string) (string, error) { <del> defer osl.InitOSContext()() <del> <ide> // Set the ipvlan mode. Default is bridge mode <ide> mode, err := setIPVlanMode(ipvlanMode) <ide> if err != nil { <ide><path>libnetwork/drivers/macvlan/macvlan_endpoint.go <ide> import ( <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/netutils" <add> "github.com/docker/libnetwork/osl" <ide> "github.com/docker/libnetwork/types" <ide> "github.com/vishvananda/netlink" <ide> ) <ide> <ide> // CreateEndpoint assigns the mac, ip and endpoint id for the new container <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> epOptions map[string]interface{}) error { <add> defer osl.InitOSContext()() <ide> <ide> if err := validateID(nid, eid); err != nil { <ide> return err <ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, <ide> <ide> // DeleteEndpoint remove the endpoint and associated netlink interface <ide> func (d *driver) DeleteEndpoint(nid, eid string) error { <add> defer osl.InitOSContext()() <ide> if err := validateID(nid, eid); err != nil { <ide> return err <ide> } <ide><path>libnetwork/drivers/macvlan/macvlan_joinleave.go <ide> func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, <ide> <ide> // Leave method is invoked when a Sandbox detaches from an endpoint. <ide> func (d *driver) Leave(nid, eid string) error { <add> defer osl.InitOSContext()() <ide> network, err := d.getNetwork(nid) <ide> if err != nil { <ide> return err <ide><path>libnetwork/drivers/macvlan/macvlan_network.go <ide> import ( <ide> "github.com/docker/libnetwork/driverapi" <ide> "github.com/docker/libnetwork/netlabel" <ide> "github.com/docker/libnetwork/options" <add> "github.com/docker/libnetwork/osl" <ide> "github.com/docker/libnetwork/types" <ide> ) <ide> <ide> // CreateNetwork the network for the specified driver type <ide> func (d *driver) CreateNetwork(nid string, option map[string]interface{}, ipV4Data, ipV6Data []driverapi.IPAMData) error { <add> defer osl.InitOSContext()() <ide> kv, err := kernel.GetKernelVersion() <ide> if err != nil { <ide> return fmt.Errorf("failed to check kernel version for %s driver support: %v", macvlanType, err) <ide> func (d *driver) createNetwork(config *configuration) error { <ide> <ide> // DeleteNetwork the network for the specified driver type <ide> func (d *driver) DeleteNetwork(nid string) error { <add> defer osl.InitOSContext()() <ide> n := d.network(nid) <ide> if n == nil { <ide> return fmt.Errorf("network id %s not found", nid) <ide><path>libnetwork/drivers/macvlan/macvlan_setup.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/Sirupsen/logrus" <del> "github.com/docker/libnetwork/osl" <ide> "github.com/vishvananda/netlink" <ide> ) <ide> <ide> const ( <ide> <ide> // Create the macvlan slave specifying the source name <ide> func createMacVlan(containerIfName, parent, macvlanMode string) (string, error) { <del> defer osl.InitOSContext()() <del> <ide> // Set the macvlan mode. Default is bridge mode <ide> mode, err := setMacVlanMode(macvlanMode) <ide> if err != nil {
8
Python
Python
fix displacy output in evaluate cli
30e1a89aeb8004fc37023d98709bf9d76e04f37d
<ide><path>spacy/cli/evaluate.py <ide> def evaluate( <ide> <ide> if displacy_path: <ide> factory_names = [nlp.get_pipe_meta(pipe).factory for pipe in nlp.pipe_names] <del> docs = [ex.predicted for ex in dev_dataset] <add> docs = list(nlp.pipe(ex.reference.text for ex in dev_dataset[:displacy_limit])) <ide> render_deps = "parser" in factory_names <ide> render_ents = "ner" in factory_names <ide> render_parses(
1
Ruby
Ruby
update rubocop to 0.34.2
87769ee970c71e757ccc5637f315a93c2e0cb141
<ide><path>Library/Homebrew/cmd/style.rb <ide> def style <ide> ARGV.formulae.map(&:path) <ide> end <ide> <del> Homebrew.install_gem_setup_path! "rubocop", "0.34.1" <add> Homebrew.install_gem_setup_path! "rubocop", "0.34.2" <ide> <ide> args = [ <ide> "--format", "simple", "--force-exclusion", "--config",
1
Ruby
Ruby
add backward compatibility for testing cookies
e864ff7259ed9e4c61a146c635aedc3c60779931
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def recycle! <ide> @method = @request_method = nil <ide> @fullpath = @ip = @remote_ip = nil <ide> @env['action_dispatch.request.query_parameters'] = {} <del> cookie_jar.reset! <add> @set_cookies ||= {} <add> @set_cookies.update(Hash[cookie_jar.instance_variable_get("@set_cookies").map{ |k,o| [k,o[:value]] }]) <add> deleted_cookies = cookie_jar.instance_variable_get("@delete_cookies") <add> @set_cookies.reject!{ |k,v| deleted_cookies.include?(k) } <add> cookie_jar.update(rack_cookies) <add> cookie_jar.update(cookies) <add> cookie_jar.update(@set_cookies) <add> cookie_jar.recycle! <ide> end <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> def write(headers) <ide> @delete_cookies.each { |k, v| ::Rack::Utils.delete_cookie_header!(headers, k, v) } <ide> end <ide> <del> def reset! #:nodoc: <add> def recycle! #:nodoc: <ide> @set_cookies.clear <ide> @delete_cookies.clear <ide> end <ide><path>actionpack/lib/action_dispatch/testing/test_request.rb <ide> require 'active_support/core_ext/object/blank' <add>require 'active_support/core_ext/hash/indifferent_access' <ide> require 'active_support/core_ext/hash/reverse_merge' <ide> require 'rack/utils' <ide> <ide> def initialize(env = {}) <ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) <ide> super(DEFAULT_ENV.merge(env)) <ide> <del> @cookies = nil <ide> self.host = 'test.host' <ide> self.remote_addr = '0.0.0.0' <ide> self.user_agent = 'Rails Testing' <ide> def accept=(mime_types) <ide> @env.delete('action_dispatch.request.accepts') <ide> @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",") <ide> end <add> <add> alias :rack_cookies :cookies <add> <add> def cookies <add> @cookies ||= {}.with_indifferent_access <add> end <ide> end <ide> end <ide><path>actionpack/test/dispatch/cookies_test.rb <ide> def test_deletings_cookie_with_several_preset_domains_using_other_domain <ide> assert_cookie_header "user_name=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" <ide> end <ide> <del> <add> <ide> def test_cookies_hash_is_indifferent_access <ide> get :symbol_key <ide> assert_equal "david", cookies[:user_name] <ide> def test_cookies_can_be_cleared <ide> end <ide> <ide> def test_can_set_http_cookie_header <del> @request.env['HTTP_COOKIE'] = "user_name=david" <add> @request.env['HTTP_COOKIE'] = 'user_name=david' <add> get :noop <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <add> get :noop <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <add> @request.env['HTTP_COOKIE'] = 'user_name=andrew' <add> get :noop <add> assert_equal 'andrew', cookies['user_name'] <add> assert_equal 'andrew', cookies[:user_name] <add> end <add> <add> def test_can_set_request_cookies <add> @request.cookies['user_name'] = 'david' <add> get :noop <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <add> get :noop <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <add> @request.cookies[:user_name] = 'andrew' <add> get :noop <add> assert_equal 'andrew', cookies['user_name'] <add> assert_equal 'andrew', cookies[:user_name] <add> end <add> <add> def test_cookies_precedence_over_http_cookie <add> @request.env['HTTP_COOKIE'] = 'user_name=andrew' <add> get :authenticate <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <add> get :noop <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> end <add> <add> def test_cookies_precedence_over_request_cookies <add> @request.cookies['user_name'] = 'andrew' <add> get :authenticate <add> assert_equal 'david', cookies['user_name'] <add> assert_equal 'david', cookies[:user_name] <add> <ide> get :noop <ide> assert_equal 'david', cookies['user_name'] <ide> assert_equal 'david', cookies[:user_name]
4
Java
Java
remove extraneous warning
750a46a12eefeb6c0723e91c169f53ac3a1c1990
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java <ide> public void onCatalystInstanceDestroy() { <ide> public boolean supportsWebWorkers() { <ide> ReactModule module = getClass().getAnnotation(ReactModule.class); <ide> if (module == null) { <del> FLog.w( <del> ReactConstants.TAG, <del> "Module " + getName() + <del> " lacks @ReactModule annotation, assuming false for supportsWebWorkers()"); <ide> return false; <ide> } <ide> return module.supportsWebWorkers();
1
Go
Go
add tests for rmi
5cff374b140b4a836b7082d009bcfe9a6e96f1af
<ide><path>integration-cli/docker_cli_by_digest_test.go <ide> func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *check.C) <ide> dockerCmd(c, "pull", imageReference) <ide> // just in case... <ide> <add> dockerCmd(c, "tag", imageReference, repoName+":sometag") <add> <ide> imageID := inspectField(c, imageReference, "Id") <ide> <ide> dockerCmd(c, "rmi", imageID) <add> <add> _, err = inspectFieldWithError(imageID, "Id") <add> c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) <ide> } <ide> <ide> func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *check.C) { <ide> func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *check.C) { <ide> c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) <ide> } <ide> <add>func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *check.C) { <add> pushDigest, err := setupImage(c) <add> c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) <add> <add> repo2 := fmt.Sprintf("%s/%s", repoName, "repo2") <add> <add> // pull from the registry using the <name>@<digest> reference <add> imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) <add> dockerCmd(c, "pull", imageReference) <add> <add> imageID := inspectField(c, imageReference, "Id") <add> <add> repoTag := repoName + ":sometag" <add> repoTag2 := repo2 + ":othertag" <add> dockerCmd(c, "tag", imageReference, repoTag) <add> dockerCmd(c, "tag", imageReference, repoTag2) <add> <add> dockerCmd(c, "rmi", repoTag) <add> <add> // rmi should have deleted repoTag and image reference, but left repoTag2 <add> inspectField(c, repoTag2, "Id") <add> _, err = inspectFieldWithError(imageReference, "Id") <add> c.Assert(err, checker.NotNil, check.Commentf("image digest reference should have been removed")) <add> <add> _, err = inspectFieldWithError(repoTag, "Id") <add> c.Assert(err, checker.NotNil, check.Commentf("image tag reference should have been removed")) <add> <add> dockerCmd(c, "rmi", repoTag2) <add> <add> // rmi should have deleted the tag, the digest reference, and the image itself <add> _, err = inspectFieldWithError(imageID, "Id") <add> c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) <add>} <add> <ide> // TestPullFailsWithAlteredManifest tests that a `docker pull` fails when <ide> // we have modified a manifest blob and its digest cannot be verified. <ide> // This is the schema2 version of the test.
1
Javascript
Javascript
move nicenum to helpers.math, cleanup ie fallbacks
e3cdd7323a2a0813ac8d544f71410b2a2d452e4e
<ide><path>src/helpers/helpers.math.js <ide> import {isFinite as isFiniteNumber} from './helpers.core'; <ide> <add>/** <add> * @alias Chart.helpers.math <add> * @namespace <add> */ <add> <ide> export const PI = Math.PI; <ide> export const TAU = 2 * PI; <ide> export const PITAU = TAU + PI; <ide> export const HALF_PI = PI / 2; <ide> export const QUARTER_PI = PI / 4; <ide> export const TWO_THIRDS_PI = PI * 2 / 3; <ide> <add>export const log10 = Math.log10; <add>export const sign = Math.sign; <add> <ide> /** <del> * @alias Chart.helpers.math <del> * @namespace <add> * Implementation of the nice number algorithm used in determining where axis labels will go <add> * @return {number} <ide> */ <add>export function niceNum(range) { <add> const niceRange = Math.pow(10, Math.floor(log10(range))); <add> const fraction = range / niceRange; <add> const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; <add> return niceFraction * niceRange; <add>} <ide> <ide> /** <ide> * Returns an array of factors sorted from 1 to sqrt(value) <ide> export function _factorize(value) { <ide> return result; <ide> } <ide> <del>export const log10 = Math.log10 || function(x) { <del> const exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10. <del> // Check for whole powers of 10, <del> // which due to floating point rounding error should be corrected. <del> const powerOf10 = Math.round(exponent); <del> const isPowerOf10 = x === Math.pow(10, powerOf10); <del> <del> return isPowerOf10 ? powerOf10 : exponent; <del>}; <del> <ide> export function isNumber(n) { <ide> return !isNaN(parseFloat(n)) && isFinite(n); <ide> } <ide> export function _setMinAndMaxByKey(array, target, property) { <ide> } <ide> } <ide> <del>export const sign = Math.sign ? <del> function(x) { <del> return Math.sign(x); <del> } : <del> function(x) { <del> x = +x; // convert to a number <del> if (x === 0 || isNaN(x)) { <del> return x; <del> } <del> return x > 0 ? 1 : -1; <del> }; <del> <ide> export function toRadians(degrees) { <ide> return degrees * (PI / 180); <ide> } <ide><path>src/scales/scale.linearbase.js <ide> import {isNullOrUndef} from '../helpers/helpers.core'; <del>import {almostEquals, almostWhole, log10, _decimalPlaces, _setMinAndMaxByKey, sign} from '../helpers/helpers.math'; <add>import {almostEquals, almostWhole, niceNum, _decimalPlaces, _setMinAndMaxByKey, sign} from '../helpers/helpers.math'; <ide> import Scale from '../core/core.scale'; <ide> import {formatNumber} from '../core/core.intl'; <ide> <del>/** <del> * Implementation of the nice number algorithm used in determining where axis labels will go <del> * @return {number} <del> */ <del>function niceNum(range) { <del> const exponent = Math.floor(log10(range)); <del> const fraction = range / Math.pow(10, exponent); <del> let niceFraction; <del> <del> if (fraction <= 1.0) { <del> niceFraction = 1; <del> } else if (fraction <= 2) { <del> niceFraction = 2; <del> } else if (fraction <= 5) { <del> niceFraction = 5; <del> } else { <del> niceFraction = 10; <del> } <del> <del> return niceFraction * Math.pow(10, exponent); <del>} <del> <ide> /** <ide> * Generate a set of linear ticks <ide> * @param generationOptions the options used to generate the ticks
2
Python
Python
check the allowed values for the logging level
3172be041e3de95f546123e3b66f06c6adcf32d5
<ide><path>airflow/configuration.py <ide> class AirflowConfigParser(ConfigParser): <ide> }, <ide> } <ide> <del> enums = {("core", "default_task_weight_rule"): WeightRule} <add> _available_logging_levels = ['CRITICAL', 'FATAL', 'ERROR', 'WARN', 'WARNING', 'INFO', 'DEBUG'] <add> enums_options = { <add> ("core", "default_task_weight_rule"): sorted(WeightRule.all_weight_rules()), <add> ('core', 'mp_start_method'): multiprocessing.get_all_start_methods(), <add> ("scheduler", "file_parsing_sort_mode"): ["modified_time", "random_seeded_by_host", "alphabetical"], <add> ("logging", "logging_level"): _available_logging_levels, <add> ("logging", "fab_logging_level"): _available_logging_levels, <add> } <ide> <ide> # This method transforms option names on every read, get, or set operation. <ide> # This changes from the default behaviour of ConfigParser from lowercasing <ide> def validate(self): <ide> <ide> def _validate_enums(self): <ide> """Validate that enum type config has an accepted value""" <del> for (section, setting), enum_class in self.enums.items(): <del> if self.has_option(section, setting): <del> value = self.get(section, setting) <del> if not enum_class.is_valid(value): <add> for (section_key, option_key), enum_options in self.enums_options.items(): <add> if self.has_option(section_key, option_key): <add> value = self.get(section_key, option_key) <add> if value not in enum_options: <ide> raise AirflowConfigException( <del> f"{value} is not an accepted config for [{section}] {setting}" <add> f"`[{section_key}] {option_key}` should not be " <add> + f"{value!r}. Possible values: {', '.join(enum_options)}." <ide> ) <ide> <ide> def _validate_config_dependencies(self): <ide> def _validate_config_dependencies(self): <ide> f"See {get_docs_url('howto/set-up-database.html#setting-up-a-sqlite-database')}" <ide> ) <ide> <del> if self.has_option('core', 'mp_start_method'): <del> mp_start_method = self.get('core', 'mp_start_method') <del> start_method_options = multiprocessing.get_all_start_methods() <del> <del> if mp_start_method not in start_method_options: <del> raise AirflowConfigException( <del> "mp_start_method should not be " <del> + mp_start_method <del> + ". Possible values are " <del> + ", ".join(start_method_options) <del> ) <del> <del> if self.has_option("scheduler", "file_parsing_sort_mode"): <del> list_mode = self.get("scheduler", "file_parsing_sort_mode") <del> file_parser_modes = {"modified_time", "random_seeded_by_host", "alphabetical"} <del> <del> if list_mode not in file_parser_modes: <del> raise AirflowConfigException( <del> "`[scheduler] file_parsing_sort_mode` should not be " <del> + f"{list_mode}. Possible values are {', '.join(file_parser_modes)}." <del> ) <del> <ide> def _using_old_value(self, old, current_value): <ide> return old.search(current_value) is not None <ide> <ide><path>airflow/utils/weight_rule.py <ide> class WeightRule: <ide> UPSTREAM = 'upstream' <ide> ABSOLUTE = 'absolute' <ide> <del> _ALL_WEIGHT_RULES = set() # type: Set[str] <add> _ALL_WEIGHT_RULES: Set[str] = set() <ide> <ide> @classmethod <ide> def is_valid(cls, weight_rule): <ide> """Check if weight rule is valid.""" <ide> return weight_rule in cls.all_weight_rules() <ide> <ide> @classmethod <del> def all_weight_rules(cls): <add> def all_weight_rules(cls) -> Set[str]: <ide> """Returns all weight rules""" <ide> if not cls._ALL_WEIGHT_RULES: <ide> cls._ALL_WEIGHT_RULES = { <ide><path>tests/core/test_configuration.py <ide> def test_enum_default_task_weight_rule_from_conf(self): <ide> with pytest.raises(AirflowConfigException) as ctx: <ide> test_conf.validate() <ide> exception = str(ctx.value) <del> message = "sidestream is not an accepted config for [core] default_task_weight_rule" <add> message = ( <add> "`[core] default_task_weight_rule` should not be 'sidestream'. Possible values: " <add> "absolute, downstream, upstream." <add> ) <add> assert message == exception <add> <add> def test_enum_logging_levels(self): <add> test_conf = AirflowConfigParser(default_config='') <add> test_conf.read_dict({'logging': {'logging_level': 'XXX'}}) <add> with pytest.raises(AirflowConfigException) as ctx: <add> test_conf.validate() <add> exception = str(ctx.value) <add> message = ( <add> "`[logging] logging_level` should not be 'XXX'. Possible values: " <add> "CRITICAL, FATAL, ERROR, WARN, WARNING, INFO, DEBUG." <add> ) <ide> assert message == exception
3
Text
Text
fix code example in upgrading guide [ci skip]
52735e92454504a3d8ec873b63ed1665ba061208
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> However, you will need to make a change if you are using `form_for` to update <ide> a resource in conjunction with a custom route using the `PUT` HTTP method: <ide> <ide> ```ruby <del>resources :users, do <add>resources :users do <ide> put :update_name, on: :member <ide> end <ide> ```
1
Ruby
Ruby
rewrote the tests for has_secure_password
19a4ef305d84f4aad633c25f850967bbc375da84
<ide><path>activemodel/test/cases/secure_password_new_test.rb <add>require 'cases/helper' <add>require 'models/user' <add>require 'models/visitor' <add> <add>require 'active_support/all' <add>class SecurePasswordTest < ActiveModel::TestCase <add> setup do <add> ActiveModel::SecurePassword.min_cost = true <add> <add> @user = User.new <add> @visitor = Visitor.new <add> <add> # Simulate loading an existing user from the DB <add> @existing_user = User.new <add> @existing_user.password_digest = BCrypt::Password.create('password', cost: BCrypt::Engine::MIN_COST) <add> end <add> <add> teardown do <add> ActiveModel::SecurePassword.min_cost = false <add> end <add> <add> test "create and updating without validations" do <add> assert @visitor.valid?(:create), 'visitor should be valid' <add> assert @visitor.valid?(:update), 'visitor should be valid' <add> <add> @visitor.password = '123' <add> @visitor.password_confirmation = '456' <add> <add> assert @visitor.valid?(:create), 'visitor should be valid' <add> assert @visitor.valid?(:update), 'visitor should be valid' <add> end <add> <add> test "create a new user with validation and a blank password" do <add> @user.password = '' <add> assert !@user.valid?(:create), 'user should be invalid' <add> assert_equal 1, @user.errors.count <add> assert_equal ["can't be blank"], @user.errors[:password] <add> end <add> <add> test "create a new user with validation and a nil password" do <add> @user.password = nil <add> assert !@user.valid?(:create), 'user should be invalid' <add> assert_equal 1, @user.errors.count <add> assert_equal ["can't be blank"], @user.errors[:password] <add> end <add> <add> test "create a new user with validation and a blank password confirmation" do <add> @user.password = 'password' <add> @user.password_confirmation = '' <add> assert !@user.valid?(:create), 'user should be invalid' <add> assert_equal 1, @user.errors.count <add> assert_equal ["doesn't match Password"], @user.errors[:password_confirmation] <add> end <add> <add> test "create a new user with validation and a nil password confirmation" do <add> @user.password = 'password' <add> @user.password_confirmation = nil <add> assert @user.valid?(:create), 'user should be valid' <add> end <add> <add> test "create a new user with validation and an incorrect password confirmation" do <add> @user.password = 'password' <add> @user.password_confirmation = 'something else' <add> assert !@user.valid?(:create), 'user should be invalid' <add> assert_equal 1, @user.errors.count <add> assert_equal ["doesn't match Password"], @user.errors[:password_confirmation] <add> end <add> <add> test "create a new user with validation and a correct password confirmation" do <add> @user.password = 'password' <add> @user.password_confirmation = 'something else' <add> assert !@user.valid?(:create), 'user should be invalid' <add> assert_equal 1, @user.errors.count <add> assert_equal ["doesn't match Password"], @user.errors[:password_confirmation] <add> end <add> <add> test "update an existing user with validation and no change in password" do <add> assert @existing_user.valid?(:update), 'user should be valid' <add> end <add> <add> test "updating an existing user with validation and a blank password" do <add> @existing_user.password = '' <add> assert @existing_user.valid?(:update), 'user should be valid' <add> end <add> <add> test "updating an existing user with validation and a blank password and password_confirmation" do <add> @existing_user.password = '' <add> @existing_user.password_confirmation = '' <add> assert @existing_user.valid?(:update), 'user should be valid' <add> end <add> <add> test "updating an existing user with validation and a nil password" do <add> @existing_user.password = nil <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["can't be blank"], @existing_user.errors[:password] <add> end <add> <add> test "updating an existing user with validation and a blank password confirmation" do <add> @existing_user.password = 'password' <add> @existing_user.password_confirmation = '' <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation] <add> end <add> <add> test "updating an existing user with validation and a nil password confirmation" do <add> @existing_user.password = 'password' <add> @existing_user.password_confirmation = nil <add> assert @existing_user.valid?(:update), 'user should be valid' <add> end <add> <add> test "updating an existing user with validation and an incorrect password confirmation" do <add> @existing_user.password = 'password' <add> @existing_user.password_confirmation = 'something else' <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation] <add> end <add> <add> test "updating an existing user with validation and a correct password confirmation" do <add> @existing_user.password = 'password' <add> @existing_user.password_confirmation = 'something else' <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["doesn't match Password"], @existing_user.errors[:password_confirmation] <add> end <add> <add> test "updating an existing user with validation and a blank password digest" do <add> @existing_user.password_digest = '' <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["can't be blank"], @existing_user.errors[:password] <add> end <add> <add> test "updating an existing user with validation and a nil password digest" do <add> @existing_user.password_digest = nil <add> assert !@existing_user.valid?(:update), 'user should be invalid' <add> assert_equal 1, @existing_user.errors.count <add> assert_equal ["can't be blank"], @existing_user.errors[:password] <add> end <add> <add> test "setting a blank password should not change an existing password" do <add> @existing_user.password = '' <add> assert @existing_user.password_digest == 'password' <add> end <add> <add> test "setting a nil password should clear an existing password" do <add> @existing_user.password = nil <add> assert_equal nil, @existing_user.password_digest <add> end <add> <add> test "authenticate" do <add> @user.password = "secret" <add> <add> assert !@user.authenticate("wrong") <add> assert @user.authenticate("secret") <add> end <add> <add> test "Password digest cost defaults to bcrypt default cost when min_cost is false" do <add> ActiveModel::SecurePassword.min_cost = false <add> <add> @user.password = "secret" <add> assert_equal BCrypt::Engine::DEFAULT_COST, @user.password_digest.cost <add> end <add> <add> test "Password digest cost honors bcrypt cost attribute when min_cost is false" do <add> ActiveModel::SecurePassword.min_cost = false <add> BCrypt::Engine.cost = 5 <add> <add> @user.password = "secret" <add> assert_equal BCrypt::Engine.cost, @user.password_digest.cost <add> end <add> <add> test "Password digest cost can be set to bcrypt min cost to speed up tests" do <add> ActiveModel::SecurePassword.min_cost = true <add> <add> @user.password = "secret" <add> assert_equal BCrypt::Engine::MIN_COST, @user.password_digest.cost <add> end <add>end <ide><path>activemodel/test/models/oauthed_user.rb <ide> class OauthedUser <ide> <ide> has_secure_password(validations: false) <ide> <del> attr_accessor :password_digest, :password_salt <add> attr_accessor :password_digest <ide> end <ide><path>activemodel/test/models/user.rb <ide> class User <ide> <ide> has_secure_password <ide> <del> attr_accessor :password_digest, :password_salt <add> attr_accessor :password_digest <ide> end
3
Ruby
Ruby
rewrite postfix conditional
16fde6fbdb094d0e31f63d69f596461ba294000f
<ide><path>Library/Homebrew/formula_installer.rb <ide> def summary <ide> end <ide> <ide> def build_time <del> @build_time ||= Time.now - @start_time unless interactive? or @start_time.nil? <add> @build_time ||= Time.now - @start_time if @start_time && !interactive? <ide> end <ide> <ide> def sanitized_ARGV_options
1
Ruby
Ruby
add missing require to `active_model/naming`
f96929ae5f3e7f98d25628184b07f3aa0579f4ff
<ide><path>activemodel/lib/active_model/naming.rb <ide> require "active_support/core_ext/hash/except" <ide> require "active_support/core_ext/module/introspection" <ide> require "active_support/core_ext/module/redefine_method" <add>require "active_support/core_ext/module/delegation" <ide> <ide> module ActiveModel <ide> class Name
1
Python
Python
fix broken master (isort fix)
164a7078b89e349cc7d23651542562309983f25e
<ide><path>airflow/www/views.py <ide> from sqlalchemy import and_, desc, func, or_, union_all <ide> from sqlalchemy.orm import joinedload <ide> from wtforms import SelectField, validators <del>from airflow.utils import json as utils_json <ide> <ide> import airflow <ide> from airflow import models, plugins_manager, settings <ide> from airflow.security import permissions <ide> from airflow.ti_deps.dep_context import DepContext <ide> from airflow.ti_deps.dependencies_deps import RUNNING_DEPS, SCHEDULER_QUEUED_DEPS <del>from airflow.utils import timezone <add>from airflow.utils import json as utils_json, timezone <ide> from airflow.utils.dates import infer_time_unit, scale_time_units <ide> from airflow.utils.helpers import alchemy_to_dict <ide> from airflow.utils.log.log_reader import TaskLogReader
1
Ruby
Ruby
enforce https for debian's anonscm
4422bd1f341e57038a8852ca9f8c46c31dbdbcad
<ide><path>Library/Homebrew/cmd/audit.rb <ide> def audit_urls <ide> %r{^http://tools\.ietf\.org/}, <ide> %r{^http://launchpad\.net/}, <ide> %r{^http://bitbucket\.org/}, <add> %r{^http://anonscm\.debian\.org/}, <ide> %r{^http://cpan\.metacpan\.org/}, <ide> %r{^http://hackage\.haskell\.org/}, <ide> %r{^http://(?:[^/]*\.)?archive\.org}, <ide> def audit_urls <ide> problem "#{p} should be `https://cpan.metacpan.org/#{$1}`" <ide> when %r{^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)}i <ide> problem "#{p} should be `https://download.gnome.org/#{$2}`" <add> when %r{^git://anonscm\.debian\.org/users/(.*)}i <add> problem "#{p} should be `https://anonscm.debian.org/git/users/#{$1}`" <ide> end <ide> end <ide>
1
Ruby
Ruby
fix a problem where nil was appearing in the list
2f98032fc92ce16125f8628b4d3c283f10494f4d
<ide><path>activesupport/lib/active_support/dependencies.rb <ide> def get(key) <ide> locked :concat, :each, :delete_if, :<< <ide> <ide> def new_constants_for(frames) <del> frames.map do |mod_name, prior_constants| <add> constants = [] <add> frames.each do |mod_name, prior_constants| <ide> mod = Inflector.constantize(mod_name) if Dependencies.qualified_const_defined?(mod_name) <ide> next unless mod.is_a?(Module) <ide> <ide> new_constants = mod.local_constant_names - prior_constants <ide> get(mod_name).concat(new_constants) <ide> <del> new_constants.map do |suffix| <del> ([mod_name, suffix] - ["Object"]).join("::") <add> new_constants.each do |suffix| <add> constants << ([mod_name, suffix] - ["Object"]).join("::") <ide> end <del> end.flatten <add> end <add> constants <ide> end <ide> <ide> # Add a set of modules to the watch stack, remembering the initial constants
1
Java
Java
fix warning in scrollview classes
d97a1a52c5df50ee649b7f89aa2067cac094381d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewHelper.java <ide> void onScroll( <ide> } <ide> <ide> // Support global native listeners for scroll events <del> private static Set<ScrollListener> sScrollListeners = <add> private static final Set<ScrollListener> sScrollListeners = <ide> Collections.newSetFromMap(new WeakHashMap<ScrollListener, Boolean>()); <ide> <ide> // If all else fails, this is the hardcoded value in OverScroller.java, in AOSP.
1
Python
Python
add test for ticket #271
9e10fed57df87e3a934470df2487583382af020e
<ide><path>numpy/core/tests/test_regression.py <ide> def check_swap_real(self, level=rlevel): <ide> assert_equal(N.arange(4,dtype='<c8').imag.max(),0.0) <ide> assert_equal(N.arange(4,dtype='>c8').real.max(),3.0) <ide> assert_equal(N.arange(4,dtype='<c8').real.max(),3.0) <add> <add> def check_masked_array_repeat(self, level=rlevel): <add> """Ticket #271""" <add> N.ma.array([1],mask=False).repeat(10) <ide> <ide> def check_multiple_assign(self, level=rlevel): <ide> """Ticket #273"""
1
PHP
PHP
fix return type
bc86a662357307dd0d061f190d4a7047b02d6edb
<ide><path>src/Http/Client/Adapter/Curl.php <ide> protected function createResponse($handle, $responseData): array <ide> * Execute the curl handle. <ide> * <ide> * @param resource $ch Curl Resource handle <del> * @return string <add> * @return string|bool <ide> */ <del> protected function exec($ch): string <add> protected function exec($ch) <ide> { <ide> return curl_exec($ch); <ide> }
1
Go
Go
use unique names for custom bridges
d2c6602cac9908072935e43b8e19d9105e3d209c
<ide><path>integration-cli/docker_cli_daemon_test.go <ide> func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *testing.T) { <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge1" <ide> bridgeIP := "192.169.1.1/24" <ide> _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) <ide> <ide> func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *testing.T) { <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge2" <ide> bridgeIP := "192.169.1.1/24" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP) <ide> func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *testing.T) { <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge3" <ide> bridgeIP := "10.2.2.1/16" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP) <ide> func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *testi <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge4" <ide> bridgeIP := "172.27.42.1/16" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP) <ide> func (s *DockerDaemonSuite) TestDaemonICCPing(c *testing.T) { <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge5" <ide> bridgeIP := "192.169.1.1/24" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP) <ide> func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *testing.T) { <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge6" <ide> bridgeIP := "192.169.1.1/24" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP) <ide> func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *tes <ide> // which may happen if it was created with the same IP range. <ide> deleteInterface(c, "docker0") <ide> <del> bridgeName := "external-bridge" <add> bridgeName := "ext-bridge7" <ide> bridgeIP := "192.169.1.1/24" <ide> <ide> createInterface(c, "bridge", bridgeName, bridgeIP)
1
Java
Java
introduce subprotocolhandler abstraction
9e20a25607aeb54dc0d636727fb67b92e00dab1e
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/websocket/SubProtocolHandler.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.websocket; <add> <add>import java.util.List; <add> <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageChannel; <add>import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.WebSocketMessage; <add>import org.springframework.web.socket.WebSocketSession; <add> <add> <add>/** <add> * A contract for handling WebSocket messages as part of a higher level protocol, referred <add> * to as "sub-protocol" in the WebSocket RFC specification. Handles both <add> * {@link WebSocketMessage}s from a client as well as {@link Message}s to a client. <add> * <p> <add> * Implementations of this interface can be configured on a <add> * {@link SubProtocolWebSocketHandler} which selects a sub-protocol handler to delegate <add> * messages to based on the sub-protocol requested by the client through the <add> * {@code Sec-WebSocket-Protocol} request header. <add> * <add> * @author Andy Wilkinson <add> * @author Rossen Stoyanchev <add> * <add> * @since 4.0 <add> */ <add>public interface SubProtocolHandler { <add> <add> /** <add> * Return the list of sub-protocols supported by this handler, never {@code null}. <add> */ <add> List<String> getSupportedProtocols(); <add> <add> /** <add> * Handle the given {@link WebSocketMessage} received from a client. <add> * <add> * @param session the client session <add> * @param message the client message <add> * @param outputChannel an output channel to send messages to <add> */ <add> void handleMessageFromClient(WebSocketSession session, WebSocketMessage message, <add> MessageChannel outputChannel) throws Exception; <add> <add> /** <add> * Handle the given {@link Message} to the client associated with the given WebSocket <add> * session. <add> * <add> * @param session the client session <add> * @param message the client message <add> */ <add> void handleMessageToClient(WebSocketSession session, Message<?> message) throws Exception; <add> <add> /** <add> * Resolve the session id from the given message or return {@code null}. <add> * <add> * @param the message to resolve the session id from <add> */ <add> String resolveSessionId(Message<?> message); <add> <add> /** <add> * Invoked after a {@link WebSocketSession} has started. <add> * <add> * @param session the client session <add> * @param outputChannel a channel <add> */ <add> void afterSessionStarted(WebSocketSession session, MessageChannel outputChannel) throws Exception; <add> <add> /** <add> * Invoked after a {@link WebSocketSession} has ended. <add> * <add> * @param session the client session <add> * @param closeStatus the reason why the session was closed <add> * @param outputChannel a channel <add> */ <add> void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, <add> MessageChannel outputChannel) throws Exception; <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/websocket/SubProtocolWebSocketHandler.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.websocket; <add> <add>import java.util.Arrays; <add>import java.util.List; <add>import java.util.Map; <add>import java.util.TreeMap; <add>import java.util.concurrent.ConcurrentHashMap; <add> <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.messaging.Message; <add>import org.springframework.messaging.MessageChannel; <add>import org.springframework.messaging.MessageHandler; <add>import org.springframework.messaging.MessagingException; <add>import org.springframework.util.Assert; <add>import org.springframework.util.CollectionUtils; <add>import org.springframework.web.socket.CloseStatus; <add>import org.springframework.web.socket.WebSocketHandler; <add>import org.springframework.web.socket.WebSocketMessage; <add>import org.springframework.web.socket.WebSocketSession; <add> <add> <add>/** <add> * A {@link WebSocketHandler} that delegates messages to a {@link SubProtocolHandler} <add> * based on the sub-protocol value requested by the client through the <add> * {@code Sec-WebSocket-Protocol} request header A default handler can also be configured <add> * to use if the client does not request a specific sub-protocol. <add> * <add> * @author Rossen Stoyanchev <add> * @author Andy Wilkinson <add> * <add> * @since 4.0 <add> */ <add>public class SubProtocolWebSocketHandler implements WebSocketHandler, MessageHandler { <add> <add> private final Log logger = LogFactory.getLog(SubProtocolWebSocketHandler.class); <add> <add> private final MessageChannel outputChannel; <add> <add> private final Map<String, SubProtocolHandler> protocolHandlers = <add> new TreeMap<String, SubProtocolHandler>(String.CASE_INSENSITIVE_ORDER); <add> <add> private SubProtocolHandler defaultProtocolHandler; <add> <add> private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); <add> <add> <add> /** <add> * @param outputChannel <add> */ <add> public SubProtocolWebSocketHandler(MessageChannel outputChannel) { <add> Assert.notNull(outputChannel, "outputChannel is required"); <add> this.outputChannel = outputChannel; <add> } <add> <add> /** <add> * Configure one or more handlers to use depending on the sub-protocol requested by <add> * the client in the WebSocket handshake request. <add> * <add> * @param protocolHandlers the sub-protocol handlers to use <add> */ <add> public void setProtocolHandlers(List<SubProtocolHandler> protocolHandlers) { <add> this.protocolHandlers.clear(); <add> for (SubProtocolHandler handler: protocolHandlers) { <add> List<String> protocols = handler.getSupportedProtocols(); <add> if (CollectionUtils.isEmpty(protocols)) { <add> logger.warn("No sub-protocols, ignoring handler " + handler); <add> continue; <add> } <add> for (String protocol: protocols) { <add> SubProtocolHandler replaced = this.protocolHandlers.put(protocol, handler); <add> if (replaced != null) { <add> throw new IllegalStateException("Failed to map handler " + handler <add> + " to protocol '" + protocol + "', it is already mapped to handler " + replaced); <add> } <add> } <add> } <add> if ((this.protocolHandlers.size() == 1) &&(this.defaultProtocolHandler == null)) { <add> this.defaultProtocolHandler = this.protocolHandlers.values().iterator().next(); <add> } <add> } <add> <add> /** <add> * @return the configured sub-protocol handlers <add> */ <add> public Map<String, SubProtocolHandler> getProtocolHandlers() { <add> return this.protocolHandlers; <add> } <add> <add> /** <add> * Set the {@link SubProtocolHandler} to use when the client did not request a <add> * sub-protocol. <add> * <add> * @param defaultProtocolHandler the default handler <add> */ <add> public void setDefaultProtocolHandler(SubProtocolHandler defaultProtocolHandler) { <add> this.defaultProtocolHandler = defaultProtocolHandler; <add> if (this.protocolHandlers.isEmpty()) { <add> setProtocolHandlers(Arrays.asList(defaultProtocolHandler)); <add> } <add> } <add> <add> /** <add> * @return the default sub-protocol handler to use <add> */ <add> public SubProtocolHandler getDefaultProtocolHandler() { <add> return this.defaultProtocolHandler; <add> } <add> <add> <add> @Override <add> public void afterConnectionEstablished(WebSocketSession session) throws Exception { <add> this.sessions.put(session.getId(), session); <add> getProtocolHandler(session).afterSessionStarted(session, this.outputChannel); <add> } <add> <add> protected final SubProtocolHandler getProtocolHandler(WebSocketSession session) { <add> SubProtocolHandler handler; <add> String protocol = session.getAcceptedProtocol(); <add> if (protocol != null) { <add> handler = this.protocolHandlers.get(protocol); <add> Assert.state(handler != null, <add> "No handler for sub-protocol '" + protocol + "', handlers=" + this.protocolHandlers); <add> } <add> else { <add> handler = this.defaultProtocolHandler; <add> Assert.state(handler != null, <add> "No sub-protocol was requested and a default sub-protocol handler was not configured"); <add> } <add> return handler; <add> } <add> <add> @Override <add> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { <add> getProtocolHandler(session).handleMessageFromClient(session, message, this.outputChannel); <add> } <add> <add> @Override <add> public void handleMessage(Message<?> message) throws MessagingException { <add> <add> String sessionId = resolveSessionId(message); <add> if (sessionId == null) { <add> logger.error("sessionId not found in message " + message); <add> return; <add> } <add> <add> WebSocketSession session = this.sessions.get(sessionId); <add> if (session == null) { <add> logger.error("Session not found for session with id " + sessionId); <add> return; <add> } <add> <add> try { <add> getProtocolHandler(session).handleMessageToClient(session, message); <add> } <add> catch (Exception e) { <add> logger.error("Failed to send message to client " + message, e); <add> } <add> } <add> <add> private String resolveSessionId(Message<?> message) { <add> for (SubProtocolHandler handler : this.protocolHandlers.values()) { <add> String sessionId = handler.resolveSessionId(message); <add> if (sessionId != null) { <add> return sessionId; <add> } <add> } <add> if (this.defaultProtocolHandler != null) { <add> String sessionId = this.defaultProtocolHandler.resolveSessionId(message); <add> if (sessionId != null) { <add> return sessionId; <add> } <add> } <add> return null; <add> } <add> <add> @Override <add> public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { <add> } <add> <add> @Override <add> public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { <add> this.sessions.remove(session.getId()); <add> getProtocolHandler(session).afterSessionEnded(session, closeStatus, this.outputChannel); <add> } <add> <add> @Override <add> public boolean supportsPartialMessages() { <add> return false; <add> } <add> <add>} <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/package-info.java <ide> /** <del> * Generic support for simple messaging protocols (like STOMP). <add> * Generic support for SImple Messaging Protocols such as STOMP. <ide> */ <ide> package org.springframework.messaging.simp; <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java <ide> public void start() { <ide> <ide> /** <ide> * Open a "system" session for sending messages from parts of the application <del> * not assoicated with a client STOMP session. <add> * not associated with a client STOMP session. <ide> */ <ide> private void openSystemSession() { <ide> <ide> public void forward(Message<?> message) { <ide> } <ide> } <ide> <del> private boolean forwardInternal(Message<?> message, TcpConnection<String, String> connection) { <add> private boolean forwardInternal(final Message<?> message, TcpConnection<String, String> connection) { <ide> if (logger.isTraceEnabled()) { <ide> logger.trace("Forwarding message to STOMP broker, message id=" + message.getHeaders().getId()); <ide> } <ide> byte[] bytes = stompMessageConverter.fromMessage(message); <del> connection.send(new String(bytes, Charset.forName("UTF-8"))); <add> connection.send(new String(bytes, Charset.forName("UTF-8")), new Consumer<Boolean>() { <add> @Override <add> public void accept(Boolean success) { <add> if (!success) { <add> String sessionId = StompHeaderAccessor.wrap(message).getSessionId(); <add> relaySessions.remove(sessionId); <add> sendError(sessionId, "Failed to relay message to broker"); <add> } <add> } <add> }); <ide> <ide> // TODO: detect if send fails and send ERROR downstream (except on DISCONNECT) <ide> return true; <add><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompProtocolHandler.java <del><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompWebSocketHandler.java <ide> * you may not use this file except in compliance with the License. <ide> * You may obtain a copy of the License at <ide> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <add> * http://www.apache.org/licenses/LICENSE-2.0 <ide> * <ide> * Unless required by applicable law or agreed to in writing, software <ide> * distributed under the License is distributed on an "AS IS" BASIS, <ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <add> <ide> package org.springframework.messaging.simp.stomp; <ide> <ide> import java.io.IOException; <ide> import java.nio.charset.Charset; <ide> import java.security.Principal; <del>import java.util.Map; <add>import java.util.Arrays; <add>import java.util.List; <ide> import java.util.Set; <del>import java.util.concurrent.ConcurrentHashMap; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.messaging.Message; <ide> import org.springframework.messaging.MessageChannel; <del>import org.springframework.messaging.MessageHandler; <add>import org.springframework.messaging.handler.websocket.SubProtocolHandler; <ide> import org.springframework.messaging.simp.SimpMessageType; <ide> import org.springframework.messaging.simp.handler.MutableUserQueueSuffixResolver; <ide> import org.springframework.messaging.support.MessageBuilder; <add>import org.springframework.util.Assert; <ide> import org.springframework.web.socket.CloseStatus; <ide> import org.springframework.web.socket.TextMessage; <add>import org.springframework.web.socket.WebSocketMessage; <ide> import org.springframework.web.socket.WebSocketSession; <del>import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter; <del> <del>import reactor.util.Assert; <del> <ide> <ide> /** <add> * A {@link SubProtocolHandler} for STOMP that supports versions 1.0, 1.1, and 1.2 of the <add> * STOMP specification. <add> * <ide> * @author Rossen Stoyanchev <del> * @since 4.0 <add> * @author Andy Wilkinson <ide> */ <del>public class StompWebSocketHandler extends TextWebSocketHandlerAdapter implements MessageHandler { <add>public class StompProtocolHandler implements SubProtocolHandler { <ide> <ide> /** <ide> * The name of the header set on the CONNECTED frame indicating the name of the user <ide> public class StompWebSocketHandler extends TextWebSocketHandlerAdapter implement <ide> */ <ide> public static final String QUEUE_SUFFIX_HEADER = "queue-suffix"; <ide> <del> <del> private static Log logger = LogFactory.getLog(StompWebSocketHandler.class); <del> <del> private MessageChannel dispatchChannel; <del> <del> private MutableUserQueueSuffixResolver queueSuffixResolver; <add> private final Log logger = LogFactory.getLog(StompProtocolHandler.class); <ide> <ide> private final StompMessageConverter stompMessageConverter = new StompMessageConverter(); <ide> <del> private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>(); <del> <del> <del> /** <del> * @param dispatchChannel the channel to send client STOMP/WebSocket messages to <del> */ <del> public StompWebSocketHandler(MessageChannel dispatchChannel) { <del> Assert.notNull(dispatchChannel, "dispatchChannel is required"); <del> this.dispatchChannel = dispatchChannel; <del> } <add> private MutableUserQueueSuffixResolver queueSuffixResolver; <ide> <ide> <ide> /** <ide> public MutableUserQueueSuffixResolver getUserQueueSuffixResolver() { <ide> return this.queueSuffixResolver; <ide> } <ide> <del> public StompMessageConverter getStompMessageConverter() { <del> return this.stompMessageConverter; <del> } <del> <del> <ide> @Override <del> public void afterConnectionEstablished(WebSocketSession session) throws Exception { <del> this.sessions.put(session.getId(), session); <add> public List<String> getSupportedProtocols() { <add> return Arrays.asList("v10.stomp", "v11.stomp", "v12.stomp"); <ide> } <ide> <ide> /** <ide> * Handle incoming WebSocket messages from clients. <ide> */ <del> @Override <del> protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) { <add> public void handleMessageFromClient(WebSocketSession session, WebSocketMessage webSocketMessage, <add> MessageChannel outputChannel) { <add> <ide> try { <del> String payload = textMessage.getPayload(); <add> Assert.isInstanceOf(TextMessage.class, webSocketMessage); <add> String payload = ((TextMessage)webSocketMessage).getPayload(); <ide> Message<?> message = this.stompMessageConverter.toMessage(payload); <ide> <ide> // TODO: validate size limits <ide> protected void handleTextMessage(WebSocketSession session, TextMessage textMessa <ide> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <ide> headers.setSessionId(session.getId()); <ide> headers.setUser(session.getPrincipal()); <add> <ide> message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); <ide> <ide> if (SimpMessageType.CONNECT.equals(headers.getMessageType())) { <ide> handleConnect(session, message); <ide> } <ide> <del> this.dispatchChannel.send(message); <add> outputChannel.send(message); <ide> <ide> } <ide> catch (Throwable t) { <ide> protected void handleTextMessage(WebSocketSession session, TextMessage textMessa <ide> } <ide> } <ide> <add> /** <add> * Handle STOMP messages going back out to WebSocket clients. <add> */ <add> @Override <add> public void handleMessageToClient(WebSocketSession session, Message<?> message) { <add> <add> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <add> headers.setCommandIfNotSet(StompCommand.MESSAGE); <add> <add> if (StompCommand.CONNECTED.equals(headers.getCommand())) { <add> // Ignore for now since we already sent it <add> return; <add> } <add> <add> if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) { <add> // TODO: failed message delivery mechanism <add> logger.error("Ignoring message, no subscriptionId header: " + message); <add> return; <add> } <add> <add> if (!(message.getPayload() instanceof byte[])) { <add> // TODO: failed message delivery mechanism <add> logger.error("Ignoring message, expected byte[] content: " + message); <add> return; <add> } <add> <add> try { <add> message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); <add> byte[] bytes = this.stompMessageConverter.fromMessage(message); <add> session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); <add> } <add> catch (Throwable t) { <add> sendErrorMessage(session, t); <add> } <add> finally { <add> if (StompCommand.ERROR.equals(headers.getCommand())) { <add> try { <add> session.close(CloseStatus.PROTOCOL_ERROR); <add> } <add> catch (IOException e) { <add> } <add> } <add> } <add> } <add> <ide> protected void handleConnect(WebSocketSession session, Message<?> message) throws IOException { <ide> <ide> StompHeaderAccessor connectHeaders = StompHeaderAccessor.wrap(message); <ide> protected void sendErrorMessage(WebSocketSession session, Throwable error) { <ide> } <ide> <ide> @Override <del> public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { <del> <del> String sessionId = session.getId(); <del> this.sessions.remove(sessionId); <del> <del> if ((this.queueSuffixResolver != null) && (session.getPrincipal() != null)) { <del> this.queueSuffixResolver.removeQueueSuffix(session.getPrincipal().getName(), sessionId); <del> } <del> <del> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); <del> headers.setSessionId(sessionId); <del> Message<?> message = MessageBuilder.withPayloadAndHeaders(new byte[0], headers).build(); <del> this.dispatchChannel.send(message); <add> public String resolveSessionId(Message<?> message) { <add> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <add> return headers.getSessionId(); <ide> } <ide> <del> /** <del> * Handle STOMP messages going back out to WebSocket clients. <del> */ <ide> @Override <del> public void handleMessage(Message<?> message) { <del> <del> StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); <del> headers.setCommandIfNotSet(StompCommand.MESSAGE); <del> <del> if (StompCommand.CONNECTED.equals(headers.getCommand())) { <del> // Ignore for now since we already sent it <del> return; <del> } <del> <del> String sessionId = headers.getSessionId(); <del> if (sessionId == null) { <del> // TODO: failed message delivery mechanism <del> logger.error("Ignoring message, no sessionId header: " + message); <del> return; <del> } <del> <del> WebSocketSession session = this.sessions.get(sessionId); <del> if (session == null) { <del> // TODO: failed message delivery mechanism <del> logger.error("Ignoring message, sessionId not found: " + message); <del> return; <del> } <add> public void afterSessionStarted(WebSocketSession session, MessageChannel outputChannel) { <add> } <ide> <del> if (StompCommand.MESSAGE.equals(headers.getCommand()) && (headers.getSubscriptionId() == null)) { <del> // TODO: failed message delivery mechanism <del> logger.error("Ignoring message, no subscriptionId header: " + message); <del> return; <del> } <add> @Override <add> public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) { <ide> <del> if (!(message.getPayload() instanceof byte[])) { <del> // TODO: failed message delivery mechanism <del> logger.error("Ignoring message, expected byte[] content: " + message); <del> return; <add> if ((this.queueSuffixResolver != null) && (session.getPrincipal() != null)) { <add> this.queueSuffixResolver.removeQueueSuffix(session.getPrincipal().getName(), session.getId()); <ide> } <ide> <del> try { <del> message = MessageBuilder.withPayloadAndHeaders(message.getPayload(), headers).build(); <del> byte[] bytes = this.stompMessageConverter.fromMessage(message); <del> session.sendMessage(new TextMessage(new String(bytes, Charset.forName("UTF-8")))); <del> } <del> catch (Throwable t) { <del> sendErrorMessage(session, t); <del> } <del> finally { <del> if (StompCommand.ERROR.equals(headers.getCommand())) { <del> try { <del> session.close(CloseStatus.PROTOCOL_ERROR); <del> } <del> catch (IOException e) { <del> } <del> } <del> } <add> StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT); <add> headers.setSessionId(session.getId()); <add> Message<?> message = MessageBuilder.withPayloadAndHeaders(new byte[0], headers).build(); <add> outputChannel.send(message); <ide> } <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/package-info.java <add>/** <add> * Generic support for simple messaging protocols (like STOMP). <add> */ <add>package org.springframework.messaging.simp.stomp; <ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/websocket/SubProtocolWebSocketHandlerTests.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIOsNS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.messaging.handler.websocket; <add> <add>import java.util.Arrays; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.mockito.Mock; <add>import org.mockito.MockitoAnnotations; <add>import org.springframework.messaging.MessageChannel; <add>import org.springframework.web.socket.support.TestWebSocketSession; <add> <add>import static org.mockito.Mockito.*; <add> <add> <add>/** <add> * Test fixture for {@link SubProtocolWebSocketHandler}. <add> * <add> * @author Rossen Stoyanchev <add> * @author Andy Wilkinson <add> */ <add>public class SubProtocolWebSocketHandlerTests { <add> <add> private SubProtocolWebSocketHandler webSocketHandler; <add> <add> private TestWebSocketSession session; <add> <add> @Mock <add> SubProtocolHandler stompHandler; <add> <add> @Mock <add> SubProtocolHandler mqttHandler; <add> <add> @Mock <add> SubProtocolHandler defaultHandler; <add> <add> @Mock <add> MessageChannel channel; <add> <add> <add> @Before <add> public void setup() { <add> MockitoAnnotations.initMocks(this); <add> <add> this.webSocketHandler = new SubProtocolWebSocketHandler(this.channel); <add> when(stompHandler.getSupportedProtocols()).thenReturn(Arrays.asList("STOMP")); <add> when(mqttHandler.getSupportedProtocols()).thenReturn(Arrays.asList("MQTT")); <add> <add> this.session = new TestWebSocketSession(); <add> this.session.setId("1"); <add> } <add> <add> <add> @Test <add> public void subProtocolMatch() throws Exception { <add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler)); <add> this.session.setAcceptedProtocol("sToMp"); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> <add> verify(this.stompHandler).afterSessionStarted(session, this.channel); <add> verify(this.mqttHandler, times(0)).afterSessionStarted(session, this.channel); <add> } <add> <add> @Test <add> public void subProtocolDefaultHandlerOnly() throws Exception { <add> this.webSocketHandler.setDefaultProtocolHandler(stompHandler); <add> this.session.setAcceptedProtocol("sToMp"); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> <add> verify(this.stompHandler).afterSessionStarted(session, this.channel); <add> } <add> <add> @Test(expected=IllegalStateException.class) <add> public void subProtocolNoMatch() throws Exception { <add> this.webSocketHandler.setDefaultProtocolHandler(defaultHandler); <add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler)); <add> this.session.setAcceptedProtocol("wamp"); <add> <add> this.webSocketHandler.afterConnectionEstablished(session); <add> } <add> <add> @Test <add> public void noSubProtocol() throws Exception { <add> this.webSocketHandler.setDefaultProtocolHandler(defaultHandler); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> <add> verify(this.defaultHandler).afterSessionStarted(session, this.channel); <add> verify(this.stompHandler, times(0)).afterSessionStarted(session, this.channel); <add> verify(this.mqttHandler, times(0)).afterSessionStarted(session, this.channel); <add> } <add> <add> @Test <add> public void noSubProtocolOneHandler() throws Exception { <add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler)); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> <add> verify(this.stompHandler).afterSessionStarted(session, this.channel); <add> } <add> <add> @Test(expected=IllegalStateException.class) <add> public void noSubProtocolTwoHandlers() throws Exception { <add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler)); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> } <add> <add> @Test(expected=IllegalStateException.class) <add> public void noSubProtocolNoDefaultHandler() throws Exception { <add> this.webSocketHandler.setProtocolHandlers(Arrays.asList(stompHandler, mqttHandler)); <add> this.webSocketHandler.afterConnectionEstablished(session); <add> } <add> <add>} <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketHandler.java <ide> * A handler for WebSocket messages and lifecycle events. <ide> * <ide> * <p>Implementations of this interface are encouraged to handle exceptions locally where <del> * it makes sense or alternatively let the exception bubble up in which case the exception <del> * is logged and the session closed with <del> * {@link CloseStatus#SERVER_ERROR SERVER_ERROR(1011)} by default. The exception handling <add> * it makes sense or alternatively let the exception bubble up in which case by default <add> * the exception is logged and the session closed with <add> * {@link CloseStatus#SERVER_ERROR SERVER_ERROR(1011)}. The exception handling <ide> * strategy is provided by <ide> * {@link org.springframework.web.socket.support.ExceptionWebSocketHandlerDecorator <del> * ExceptionWebSocketHandlerDecorator}, which can be customized or replaced by decorating <add> * ExceptionWebSocketHandlerDecorator} and it can be customized or replaced by decorating <ide> * the {@link WebSocketHandler} with a different decorator. <ide> * <ide> * @author Rossen Stoyanchev <ide> public interface WebSocketHandler { <ide> * transport error has occurred. Although the session may technically still be open, <ide> * depending on the underlying implementation, sending messages at this point is <ide> * discouraged and most likely will not succeed. <add> * <ide> * @throws Exception this method can handle or propagate exceptions; see class-level <ide> * Javadoc for details. <ide> */ <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/support/MultiProtocolWebSocketHandler.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.socket.support; <del> <del>import java.util.Collections; <del>import java.util.HashMap; <del>import java.util.Map; <del> <del>import org.springframework.util.Assert; <del>import org.springframework.web.socket.CloseStatus; <del>import org.springframework.web.socket.WebSocketHandler; <del>import org.springframework.web.socket.WebSocketMessage; <del>import org.springframework.web.socket.WebSocketSession; <del> <del> <del>/** <del> * A {@link WebSocketHandler} that delegates to other {@link WebSocketHandler} instances <del> * based on the sub-protocol value accepted at the handshake. A default handler can also <del> * be configured for use by default when a sub-protocol value if the WebSocket session <del> * does not have a sub-protocol value associated with it. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>public class MultiProtocolWebSocketHandler implements WebSocketHandler { <del> <del> private WebSocketHandler defaultHandler; <del> <del> private Map<String, WebSocketHandler> handlers = new HashMap<String, WebSocketHandler>(); <del> <del> <del> /** <del> * Configure {@link WebSocketHandler}'s to use by sub-protocol. The values for <del> * sub-protocols are case insensitive. <del> */ <del> public void setProtocolHandlers(Map<String, WebSocketHandler> protocolHandlers) { <del> this.handlers.clear(); <del> for (String protocol : protocolHandlers.keySet()) { <del> this.handlers.put(protocol.toLowerCase(), protocolHandlers.get(protocol)); <del> } <del> } <del> <del> /** <del> * Return a read-only copy of the sub-protocol handler map. <del> */ <del> public Map<String, WebSocketHandler> getProtocolHandlers() { <del> return Collections.unmodifiableMap(this.handlers); <del> } <del> <del> /** <del> * Set the default {@link WebSocketHandler} to use if a sub-protocol was not <del> * requested. <del> */ <del> public void setDefaultProtocolHandler(WebSocketHandler defaultHandler) { <del> this.defaultHandler = defaultHandler; <del> } <del> <del> /** <del> * Return the default {@link WebSocketHandler} to be used. <del> */ <del> public WebSocketHandler getDefaultProtocolHandler() { <del> return this.defaultHandler; <del> } <del> <del> <del> @Override <del> public void afterConnectionEstablished(WebSocketSession session) throws Exception { <del> WebSocketHandler handler = getHandlerForSession(session); <del> handler.afterConnectionEstablished(session); <del> } <del> <del> private WebSocketHandler getHandlerForSession(WebSocketSession session) { <del> WebSocketHandler handler = null; <del> String protocol = session.getAcceptedProtocol(); <del> if (protocol != null) { <del> handler = this.handlers.get(protocol.toLowerCase()); <del> Assert.state(handler != null, <del> "No WebSocketHandler for sub-protocol '" + protocol + "', handlers=" + this.handlers); <del> } <del> else { <del> handler = this.defaultHandler; <del> Assert.state(handler != null, <del> "No sub-protocol was requested and no default WebSocketHandler was configured"); <del> } <del> return handler; <del> } <del> <del> @Override <del> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { <del> WebSocketHandler handler = getHandlerForSession(session); <del> handler.handleMessage(session, message); <del> } <del> <del> @Override <del> public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { <del> WebSocketHandler handler = getHandlerForSession(session); <del> handler.handleTransportError(session, exception); <del> } <del> <del> @Override <del> public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { <del> WebSocketHandler handler = getHandlerForSession(session); <del> handler.afterConnectionClosed(session, closeStatus); <del> } <del> <del> @Override <del> public boolean supportsPartialMessages() { <del> return false; <del> } <del> <del>} <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/support/MultiProtocolWebSocketHandlerTests.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIOsNS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.socket.support; <del> <del>import java.util.HashMap; <del>import java.util.Map; <del> <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.mockito.Mock; <del>import org.mockito.MockitoAnnotations; <del>import org.springframework.web.socket.WebSocketHandler; <del> <del>import static org.mockito.Mockito.*; <del> <del> <del>/** <del> * Test fixture for {@link MultiProtocolWebSocketHandler}. <del> * <del> * @author Rossen Stoyanchev <del> */ <del>public class MultiProtocolWebSocketHandlerTests { <del> <del> private MultiProtocolWebSocketHandler multiProtocolHandler; <del> <del> @Mock <del> WebSocketHandler stompHandler; <del> <del> @Mock <del> WebSocketHandler mqttHandler; <del> <del> @Mock <del> WebSocketHandler defaultHandler; <del> <del> <del> @Before <del> public void setup() { <del> <del> MockitoAnnotations.initMocks(this); <del> <del> Map<String, WebSocketHandler> handlers = new HashMap<String, WebSocketHandler>(); <del> handlers.put("STOMP", this.stompHandler); <del> handlers.put("MQTT", this.mqttHandler); <del> <del> this.multiProtocolHandler = new MultiProtocolWebSocketHandler(); <del> this.multiProtocolHandler.setProtocolHandlers(handlers); <del> this.multiProtocolHandler.setDefaultProtocolHandler(this.defaultHandler); <del> } <del> <del> <del> @Test <del> public void subProtocol() throws Exception { <del> <del> TestWebSocketSession session = new TestWebSocketSession(); <del> session.setAcceptedProtocol("sToMp"); <del> <del> this.multiProtocolHandler.afterConnectionEstablished(session); <del> <del> verify(this.stompHandler).afterConnectionEstablished(session); <del> verifyZeroInteractions(this.mqttHandler); <del> } <del> <del> @Test(expected=IllegalStateException.class) <del> public void subProtocolNoMatch() throws Exception { <del> <del> TestWebSocketSession session = new TestWebSocketSession(); <del> session.setAcceptedProtocol("wamp"); <del> <del> this.multiProtocolHandler.afterConnectionEstablished(session); <del> } <del> <del> @Test <del> public void noSubProtocol() throws Exception { <del> <del> TestWebSocketSession session = new TestWebSocketSession(); <del> <del> this.multiProtocolHandler.afterConnectionEstablished(session); <del> <del> verify(this.defaultHandler).afterConnectionEstablished(session); <del> verifyZeroInteractions(this.stompHandler, this.mqttHandler); <del> } <del> <del> @Test(expected=IllegalStateException.class) <del> public void noSubProtocolNoDefaultHandler() throws Exception { <del> <del> TestWebSocketSession session = new TestWebSocketSession(); <del> <del> this.multiProtocolHandler.setDefaultProtocolHandler(null); <del> this.multiProtocolHandler.afterConnectionEstablished(session); <del> } <del> <del>}
10
PHP
PHP
add array_prepend helper
91e3510b447629dd609850779e63511941a1c25a
<ide><path>src/Illuminate/Support/helpers.php <ide> function array_pluck($array, $value, $key = null) <ide> } <ide> } <ide> <add>if (! function_exists('array_prepend')) { <add> /** <add> * Push an item onto the beginning of an array. <add> * <add> * @param array $array <add> * @param mixed $value <add> * @param mixed $key <add> * @return array <add> */ <add> function array_prepend($array, $value, $key = null) <add> { <add> return Arr::prepend($array, $value, $key); <add> } <add>} <add> <ide> if (! function_exists('array_pull')) { <ide> /** <ide> * Get a value from the array, and remove it.
1
Javascript
Javascript
fix texteditor tests
aa1f5dde83f5e4457de023a25fcf54306cc0b7af
<ide><path>spec/text-editor-spec.js <ide> describe('TextEditor', () => { <ide> }) <ide> }) <ide> <del> describe('when the editor is constructed with the grammar option set', () => { <del> beforeEach(async () => { <del> await atom.packages.activatePackage('language-coffee-script') <del> }) <del> <del> it('sets the grammar', () => { <del> editor = new TextEditor({grammar: atom.grammars.grammarForScopeName('source.coffee')}) <del> expect(editor.getGrammar().name).toBe('CoffeeScript') <del> }) <del> }) <del> <ide> describe('softWrapAtPreferredLineLength', () => { <ide> it('soft wraps the editor at the preferred line length unless the editor is narrower or the editor is mini', () => { <ide> editor.update({ <ide><path>src/text-editor.js <ide> class TextEditor { <ide> toggleLineCommentForBufferRow (row) { this.toggleLineCommentsForBufferRows(row, row) } <ide> <ide> toggleLineCommentsForBufferRows (start, end) { <del> let { <del> commentStartString, <del> commentEndString <del> } = this.buffer.getLanguageMode().commentStringsForPosition(Point(start, 0)) <add> const languageMode = this.buffer.getLanguageMode() <add> let {commentStartString, commentEndString} = <add> languageMode.commentStringsForPosition && <add> languageMode.commentStringsForPosition(Point(start, 0)) || {} <ide> if (!commentStartString) return <ide> commentStartString = commentStartString.trim() <ide>
2
Ruby
Ruby
improve bottle test
e27bddc82ae85e94a2f0016b176ea2a9c6dd824d
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> require "bundler" <ide> require "testing_env" <add>require "core_formula_repository" <ide> <ide> class IntegrationCommandTests < Homebrew::TestCase <ide> def cmd_output(*args) <ide> def cmd_output(*args) <ide> ENV["HOMEBREW_BREW_FILE"] = HOMEBREW_PREFIX/"bin/brew" <ide> ENV["HOMEBREW_INTEGRATION_TEST"] = args.join " " <ide> ENV["HOMEBREW_TEST_TMPDIR"] = TEST_TMPDIR <del> Utils.popen_read(RUBY_PATH, *cmd_args).chomp <add> read, write = IO.pipe <add> begin <add> pid = fork do <add> read.close <add> $stdout.reopen(write) <add> $stderr.reopen(write) <add> write.close <add> exec RUBY_PATH, *cmd_args <add> end <add> write.close <add> read.read.chomp <add> ensure <add> Process.wait(pid) <add> read.close <add> end <ide> end <ide> end <ide> <ide> def test_install <ide> <ide> def test_bottle <ide> cmd("install", "--build-bottle", testball) <add> assert_match "Formula not from core or any taps", <add> cmd_fail("bottle", "--no-revision", testball) <add> formula_file = CoreFormulaRepository.new.formula_dir/"testball.rb" <add> formula_file.write <<-EOS.undent <add> class Testball < Formula <add> url "https://example.com/testabll-0.1.tar.gz" <add> end <add> EOS <ide> HOMEBREW_CACHE.cd do <del> assert_match(/testball-0\.1.*\.bottle\.tar\.gz/, <del> cmd_output("bottle", "--no-revision", testball)) <add> assert_match /testball-0\.1.*\.bottle\.tar\.gz/, <add> cmd_output("bottle", "--no-revision", "testball") <ide> end <ide> ensure <del> cmd("uninstall", "--force", testball) <add> cmd("uninstall", "--force", "testball") <ide> cmd("cleanup", "--force", "--prune=all") <add> formula_file.unlink <ide> end <ide> <ide> def test_uninstall <del> cmd("install", "--build-bottle", testball) <add> cmd("install", testball) <ide> assert_match "Uninstalling testball", cmd("uninstall", "--force", testball) <ide> ensure <ide> cmd("cleanup", "--force", "--prune=all")
1
Java
Java
android subpixel text
65e4e674fca7127fd7800ae011cab449561f475b
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/text/CustomStyleSpan.java <ide> private static void apply( <ide> } else { <ide> paint.setTypeface(Typeface.defaultFromStyle(want)); <ide> } <add> paint.setSubpixelText(true); <ide> } <ide> <ide> }
1
PHP
PHP
improve return type that may be null
b85f906bef8865f6d15525dbf2d9db6618c50d64
<ide><path>src/Illuminate/Cookie/CookieJar.php <ide> public function hasQueued($key, $path = null) <ide> * @param string $key <ide> * @param mixed $default <ide> * @param string|null $path <del> * @return \Symfony\Component\HttpFoundation\Cookie <add> * @return \Symfony\Component\HttpFoundation\Cookie|null <ide> */ <ide> public function queued($key, $default = null, $path = null) <ide> { <ide><path>src/Illuminate/Routing/Route.php <ide> public function hasParameter($name) <ide> * <ide> * @param string $name <ide> * @param mixed $default <del> * @return string|object <add> * @return string|object|null <ide> */ <ide> public function parameter($name, $default = null) <ide> { <ide> public function parameter($name, $default = null) <ide> * <ide> * @param string $name <ide> * @param mixed $default <del> * @return string <add> * @return string|null <ide> */ <ide> public function originalParameter($name, $default = null) <ide> {
2