content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Ruby | Ruby | remove redundant method | cf278a6effcb86437b33008f16c59f5a4ba8878e | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def normalize_options!
<ide> @options.merge!(default_controller_and_action)
<ide> end
<ide>
<del> def normalize_format!
<del> if options[:format] == true
<del> options[:format] = /.+/
<del> elsif options[:format] == false
<del> options.delete(:format)
<del> end
<del> end
<del>
<ide> def normalize_requirements!
<ide> constraints.each do |key, requirement|
<ide> next unless segment_keys.include?(key) || key == :controller | 1 |
Python | Python | improve triggerruledep typing and readability | 0cf3cb1a4968eff264cc4e7ed2da2f0ece6d2c99 | <ide><path>airflow/ti_deps/deps/base_ti_dep.py
<ide> # under the License.
<ide> from __future__ import annotations
<ide>
<del>from typing import NamedTuple
<add>from typing import TYPE_CHECKING, Any, Iterator, NamedTuple
<ide>
<ide> from airflow.ti_deps.dep_context import DepContext
<ide> from airflow.utils.session import provide_session
<ide>
<add>if TYPE_CHECKING:
<add> from sqlalchemy.orm import Session
<add>
<add> from airflow.models.taskinstance import TaskInstance
<add>
<ide>
<ide> class BaseTIDep:
<ide> """
<ide> class BaseTIDep:
<ide> # to some tasks (e.g. depends_on_past is not specified by all tasks).
<ide> IS_TASK_DEP = False
<ide>
<del> def __init__(self):
<del> pass
<del>
<del> def __eq__(self, other):
<add> def __eq__(self, other: Any) -> bool:
<ide> return isinstance(self, type(other))
<ide>
<del> def __hash__(self):
<add> def __hash__(self) -> int:
<ide> return hash(type(self))
<ide>
<del> def __repr__(self):
<add> def __repr__(self) -> str:
<ide> return f"<TIDep({self.name})>"
<ide>
<ide> @property
<del> def name(self):
<del> """
<del> The human-readable name for the dependency. Use the classname as the default name
<del> if this method is not overridden in the subclass.
<add> def name(self) -> str:
<add> """The human-readable name for the dependency.
<add>
<add> Use the class name as the default if ``NAME`` is not provided.
<ide> """
<ide> return getattr(self, "NAME", self.__class__.__name__)
<ide>
<del> def _get_dep_statuses(self, ti, session, dep_context):
<add> def _get_dep_statuses(
<add> self,
<add> ti: TaskInstance,
<add> session: Session,
<add> dep_context: DepContext,
<add> ) -> Iterator[TIDepStatus]:
<ide> """
<ide> Abstract method that returns an iterable of TIDepStatus objects that describe
<ide> whether the given task instance has this dependency met.
<ide> def _get_dep_statuses(self, ti, session, dep_context):
<ide> raise NotImplementedError
<ide>
<ide> @provide_session
<del> def get_dep_statuses(self, ti, session, dep_context=None):
<add> def get_dep_statuses(
<add> self,
<add> ti: TaskInstance,
<add> session: Session,
<add> dep_context: DepContext | None = None,
<add> ) -> Iterator[TIDepStatus]:
<ide> """
<ide> Wrapper around the private _get_dep_statuses method that contains some global
<ide> checks for all dependencies.
<ide> def get_dep_statuses(self, ti, session, dep_context=None):
<ide> :param session: database session
<ide> :param dep_context: the context for which this dependency should be evaluated for
<ide> """
<del> if dep_context is None:
<del> dep_context = DepContext()
<add> cxt = DepContext() if dep_context is None else dep_context
<ide>
<del> if self.IGNORABLE and dep_context.ignore_all_deps:
<add> if self.IGNORABLE and cxt.ignore_all_deps:
<ide> yield self._passing_status(reason="Context specified all dependencies should be ignored.")
<ide> return
<ide>
<del> if self.IS_TASK_DEP and dep_context.ignore_task_deps:
<add> if self.IS_TASK_DEP and cxt.ignore_task_deps:
<ide> yield self._passing_status(reason="Context specified all task dependencies should be ignored.")
<ide> return
<ide>
<del> yield from self._get_dep_statuses(ti, session, dep_context)
<add> yield from self._get_dep_statuses(ti, session, cxt)
<ide>
<ide> @provide_session
<del> def is_met(self, ti, session, dep_context=None):
<add> def is_met(self, ti: TaskInstance, session: Session, dep_context: DepContext | None = None) -> bool:
<ide> """
<ide> Returns whether or not this dependency is met for a given task instance. A
<ide> dependency is considered met if all of the dependency statuses it reports are
<ide> def is_met(self, ti, session, dep_context=None):
<ide> return all(status.passed for status in self.get_dep_statuses(ti, session, dep_context))
<ide>
<ide> @provide_session
<del> def get_failure_reasons(self, ti, session, dep_context=None):
<add> def get_failure_reasons(
<add> self,
<add> ti: TaskInstance,
<add> session: Session,
<add> dep_context: DepContext | None = None,
<add> ) -> Iterator[str]:
<ide> """
<ide> Returns an iterable of strings that explain why this dependency wasn't met.
<ide>
<ide> def get_failure_reasons(self, ti, session, dep_context=None):
<ide> if not dep_status.passed:
<ide> yield dep_status.reason
<ide>
<del> def _failing_status(self, reason=""):
<add> def _failing_status(self, reason: str = "") -> TIDepStatus:
<ide> return TIDepStatus(self.name, False, reason)
<ide>
<del> def _passing_status(self, reason=""):
<add> def _passing_status(self, reason: str = "") -> TIDepStatus:
<ide> return TIDepStatus(self.name, True, reason)
<ide>
<ide>
<ide><path>airflow/ti_deps/deps/trigger_rule_dep.py
<ide> from __future__ import annotations
<ide>
<ide> from collections import Counter
<del>from typing import TYPE_CHECKING
<add>from typing import TYPE_CHECKING, Iterator, NamedTuple
<ide>
<ide> from sqlalchemy import func
<ide>
<ide> from airflow.ti_deps.dep_context import DepContext
<del>from airflow.ti_deps.deps.base_ti_dep import BaseTIDep
<del>from airflow.utils.session import NEW_SESSION, provide_session
<del>from airflow.utils.state import State
<add>from airflow.ti_deps.deps.base_ti_dep import BaseTIDep, TIDepStatus
<add>from airflow.utils.state import TaskInstanceState
<ide> from airflow.utils.trigger_rule import TriggerRule as TR
<ide>
<ide> if TYPE_CHECKING:
<ide> from airflow.models.taskinstance import TaskInstance
<ide>
<ide>
<del>class TriggerRuleDep(BaseTIDep):
<del> """
<del> Determines if a task's upstream tasks are in a state that allows a given task instance
<del> to run.
<add>class _UpstreamTIStates(NamedTuple):
<add> """States of the upstream tis for a specific ti.
<add>
<add> This is used to determine whether the specific ti can run in this iteration.
<ide> """
<ide>
<del> NAME = "Trigger Rule"
<del> IGNORABLE = True
<del> IS_TASK_DEP = True
<add> success: int
<add> skipped: int
<add> failed: int
<add> upstream_failed: int
<add> removed: int
<add> done: int
<ide>
<del> @staticmethod
<del> def _get_states_count_upstream_ti(task, finished_tis):
<del> """
<del> This function returns the states of the upstream tis for a specific ti in order to determine
<del> whether this ti can run in this iteration
<add> @classmethod
<add> def calculate(cls, ti: TaskInstance, finished_tis: list[TaskInstance]) -> _UpstreamTIStates:
<add> """Calculate states for a task instance.
<ide>
<ide> :param ti: the ti that we want to calculate deps for
<ide> :param finished_tis: all the finished tasks of the dag_run
<ide> """
<add> task = ti.task
<ide> counter = Counter(ti.state for ti in finished_tis if ti.task_id in task.upstream_task_ids)
<del> return (
<del> counter.get(State.SUCCESS, 0),
<del> counter.get(State.SKIPPED, 0),
<del> counter.get(State.FAILED, 0),
<del> counter.get(State.UPSTREAM_FAILED, 0),
<del> counter.get(State.REMOVED, 0),
<del> sum(counter.values()),
<add> return _UpstreamTIStates(
<add> success=counter.get(TaskInstanceState.SUCCESS, 0),
<add> skipped=counter.get(TaskInstanceState.SKIPPED, 0),
<add> failed=counter.get(TaskInstanceState.FAILED, 0),
<add> upstream_failed=counter.get(TaskInstanceState.UPSTREAM_FAILED, 0),
<add> removed=counter.get(TaskInstanceState.REMOVED, 0),
<add> done=sum(counter.values()),
<ide> )
<ide>
<del> @provide_session
<del> def _get_dep_statuses(self, ti, session, dep_context: DepContext):
<add>
<add>class TriggerRuleDep(BaseTIDep):
<add> """
<add> Determines if a task's upstream tasks are in a state that allows a given task instance
<add> to run.
<add> """
<add>
<add> NAME = "Trigger Rule"
<add> IGNORABLE = True
<add> IS_TASK_DEP = True
<add>
<add> def _get_dep_statuses(
<add> self,
<add> ti: TaskInstance,
<add> session: Session,
<add> dep_context: DepContext,
<add> ) -> Iterator[TIDepStatus]:
<ide> # Checking that all upstream dependencies have succeeded
<ide> if not ti.task.upstream_list:
<ide> yield self._passing_status(reason="The task instance did not have any upstream tasks.")
<ide> def _get_dep_statuses(self, ti, session, dep_context: DepContext):
<ide> if ti.task.trigger_rule == TR.ALWAYS:
<ide> yield self._passing_status(reason="The task had a always trigger rule set.")
<ide> return
<del> # see if the task name is in the task upstream for our task
<del> successes, skipped, failed, upstream_failed, removed, done = self._get_states_count_upstream_ti(
<del> task=ti.task, finished_tis=dep_context.ensure_finished_tis(ti.get_dagrun(session), session)
<del> )
<ide>
<del> yield from self._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=successes,
<del> skipped=skipped,
<del> failed=failed,
<del> upstream_failed=upstream_failed,
<del> removed=removed,
<del> done=done,
<del> flag_upstream_failed=dep_context.flag_upstream_failed,
<del> dep_context=dep_context,
<del> session=session,
<del> )
<add> yield from self._evaluate_trigger_rule(ti=ti, dep_context=dep_context, session=session)
<ide>
<ide> @staticmethod
<ide> def _count_upstreams(ti: TaskInstance, *, session: Session):
<ide> def _count_upstreams(ti: TaskInstance, *, session: Session):
<ide> )
<ide> return len(upstream_task_ids) + mapped_tis_addition
<ide>
<del> @provide_session
<ide> def _evaluate_trigger_rule(
<ide> self,
<ide> ti: TaskInstance,
<del> successes,
<del> skipped,
<del> failed,
<del> upstream_failed,
<del> removed,
<del> done,
<del> flag_upstream_failed,
<ide> dep_context: DepContext,
<del> session: Session = NEW_SESSION,
<del> ):
<del> """
<del> Yields a dependency status that indicate whether the given task instance's trigger
<del> rule was met.
<add> session: Session,
<add> ) -> Iterator[TIDepStatus]:
<add> """Evaluate whether ``ti``'s trigger rule was met.
<ide>
<del> :param ti: the task instance to evaluate the trigger rule of
<del> :param successes: Number of successful upstream tasks
<del> :param skipped: Number of skipped upstream tasks
<del> :param failed: Number of failed upstream tasks
<del> :param upstream_failed: Number of upstream_failed upstream tasks
<del> :param done: Number of completed upstream tasks
<del> :param flag_upstream_failed: This is a hack to generate
<del> the upstream_failed state creation while checking to see
<del> whether the task instance is runnable. It was the shortest
<del> path to add the feature
<del> :param session: database session
<add> :param ti: Task instance to evaluate the trigger rule of.
<add> :param dep_context: The current dependency context.
<add> :param session: Database session.
<ide> """
<add> finished_tis = dep_context.ensure_finished_tis(ti.get_dagrun(session), session)
<add> upstream_states = _UpstreamTIStates.calculate(ti, finished_tis)
<add>
<add> success = upstream_states.success
<add> skipped = upstream_states.skipped
<add> failed = upstream_states.failed
<add> upstream_failed = upstream_states.upstream_failed
<add> removed = upstream_states.removed
<add> done = upstream_states.done
<add>
<ide> task = ti.task
<del> upstream = self._count_upstreams(ti, session=session)
<ide> trigger_rule = task.trigger_rule
<add> upstream = self._count_upstreams(ti, session=session)
<ide> upstream_done = done >= upstream
<del> upstream_tasks_state = {
<del> "total": upstream,
<del> "successes": successes,
<del> "skipped": skipped,
<del> "failed": failed,
<del> "removed": removed,
<del> "upstream_failed": upstream_failed,
<del> "done": done,
<del> }
<del> changed: bool = False
<del> if flag_upstream_failed:
<add>
<add> changed = False
<add> if dep_context.flag_upstream_failed:
<ide> if trigger_rule == TR.ALL_SUCCESS:
<ide> if upstream_failed or failed:
<del> changed = ti.set_state(State.UPSTREAM_FAILED, session)
<add> changed = ti.set_state(TaskInstanceState.UPSTREAM_FAILED, session)
<ide> elif skipped:
<del> changed = ti.set_state(State.SKIPPED, session)
<del> elif removed and successes and ti.map_index > -1:
<del> if ti.map_index >= successes:
<del> changed = ti.set_state(State.REMOVED, session)
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<add> elif removed and success and ti.map_index > -1:
<add> if ti.map_index >= success:
<add> changed = ti.set_state(TaskInstanceState.REMOVED, session)
<ide> elif trigger_rule == TR.ALL_FAILED:
<del> if successes or skipped:
<del> changed = ti.set_state(State.SKIPPED, session)
<add> if success or skipped:
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide> elif trigger_rule == TR.ONE_SUCCESS:
<ide> if upstream_done and done == skipped:
<ide> # if upstream is done and all are skipped mark as skipped
<del> changed = ti.set_state(State.SKIPPED, session)
<del> elif upstream_done and successes <= 0:
<del> # if upstream is done and there are no successes mark as upstream failed
<del> changed = ti.set_state(State.UPSTREAM_FAILED, session)
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<add> elif upstream_done and success <= 0:
<add> # if upstream is done and there are no success mark as upstream failed
<add> changed = ti.set_state(TaskInstanceState.UPSTREAM_FAILED, session)
<ide> elif trigger_rule == TR.ONE_FAILED:
<ide> if upstream_done and not (failed or upstream_failed):
<del> changed = ti.set_state(State.SKIPPED, session)
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide> elif trigger_rule == TR.ONE_DONE:
<del> if upstream_done and not (failed or successes):
<del> changed = ti.set_state(State.SKIPPED, session)
<add> if upstream_done and not (failed or success):
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide> elif trigger_rule == TR.NONE_FAILED:
<ide> if upstream_failed or failed:
<del> changed = ti.set_state(State.UPSTREAM_FAILED, session)
<add> changed = ti.set_state(TaskInstanceState.UPSTREAM_FAILED, session)
<ide> elif trigger_rule == TR.NONE_FAILED_MIN_ONE_SUCCESS:
<ide> if upstream_failed or failed:
<del> changed = ti.set_state(State.UPSTREAM_FAILED, session)
<add> changed = ti.set_state(TaskInstanceState.UPSTREAM_FAILED, session)
<ide> elif skipped == upstream:
<del> changed = ti.set_state(State.SKIPPED, session)
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide> elif trigger_rule == TR.NONE_SKIPPED:
<ide> if skipped:
<del> changed = ti.set_state(State.SKIPPED, session)
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide> elif trigger_rule == TR.ALL_SKIPPED:
<del> if successes or failed:
<del> changed = ti.set_state(State.SKIPPED, session)
<add> if success or failed:
<add> changed = ti.set_state(TaskInstanceState.SKIPPED, session)
<ide>
<ide> if changed:
<ide> dep_context.have_changed_ti_states = True
<ide>
<ide> if trigger_rule == TR.ONE_SUCCESS:
<del> if successes <= 0:
<add> if success <= 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires one upstream task success, "
<del> f"but none were found. upstream_tasks_state={upstream_tasks_state}, "
<add> f"but none were found. upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> def _evaluate_trigger_rule(
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires one upstream task failure, "
<del> f"but none were found. upstream_tasks_state={upstream_tasks_state}, "
<add> f"but none were found. upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> elif trigger_rule == TR.ONE_DONE:
<del> if successes + failed <= 0:
<add> if success + failed <= 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}'"
<ide> "requires at least one upstream task failure or success"
<del> f"but none were failed or success. upstream_tasks_state={upstream_tasks_state}, "
<add> f"but none were failed or success. upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> elif trigger_rule == TR.ALL_SUCCESS:
<del> num_failures = upstream - successes
<add> num_failures = upstream - success
<ide> if ti.map_index > -1:
<ide> num_failures -= removed
<ide> if num_failures > 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have "
<ide> f"succeeded, but found {num_failures} non-success(es). "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> elif trigger_rule == TR.ALL_FAILED:
<del> num_successes = upstream - failed - upstream_failed
<add> num_success = upstream - failed - upstream_failed
<ide> if ti.map_index > -1:
<del> num_successes -= removed
<del> if num_successes > 0:
<add> num_success -= removed
<add> if num_success > 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have failed, "
<del> f"but found {num_successes} non-failure(s). "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"but found {num_success} non-failure(s). "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> def _evaluate_trigger_rule(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have "
<ide> f"completed, but found {upstream_done} task(s) that were not done. "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> elif trigger_rule == TR.NONE_FAILED:
<del> num_failures = upstream - successes - skipped
<add> num_failures = upstream - success - skipped
<ide> if ti.map_index > -1:
<ide> num_failures -= removed
<ide> if num_failures > 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have "
<ide> f"succeeded or been skipped, but found {num_failures} non-success(es). "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> elif trigger_rule == TR.NONE_FAILED_MIN_ONE_SUCCESS:
<del> num_failures = upstream - successes - skipped
<add> num_failures = upstream - success - skipped
<ide> if ti.map_index > -1:
<ide> num_failures -= removed
<ide> if num_failures > 0:
<ide> yield self._failing_status(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have "
<ide> f"succeeded or been skipped, but found {num_failures} non-success(es). "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> def _evaluate_trigger_rule(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to not have been "
<ide> f"skipped, but found {skipped} task(s) skipped. "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide> def _evaluate_trigger_rule(
<ide> reason=(
<ide> f"Task's trigger rule '{trigger_rule}' requires all upstream tasks to have been "
<ide> f"skipped, but found {num_non_skipped} task(s) in non skipped state. "
<del> f"upstream_tasks_state={upstream_tasks_state}, "
<add> f"upstream_states={upstream_states}, "
<ide> f"upstream_task_ids={task.upstream_task_ids}"
<ide> )
<ide> )
<ide><path>tests/models/test_taskinstance.py
<ide> from airflow.ti_deps.dependencies_deps import REQUEUEABLE_DEPS, RUNNING_DEPS
<ide> from airflow.ti_deps.dependencies_states import RUNNABLE_STATES
<ide> from airflow.ti_deps.deps.base_ti_dep import TIDepStatus
<del>from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep
<add>from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep, _UpstreamTIStates
<ide> from airflow.utils import timezone
<ide> from airflow.utils.db import merge_conn
<ide> from airflow.utils.session import create_session, provide_session
<ide> def test_depends_on_past(self, dag_maker):
<ide> # Numeric fields are in order:
<ide> # successes, skipped, failed, upstream_failed, done, removed
<ide> @pytest.mark.parametrize(
<del> "trigger_rule,successes,skipped,failed,upstream_failed,done,removed,"
<del> "flag_upstream_failed,expect_state,expect_completed",
<add> "trigger_rule, upstream_states, flag_upstream_failed, expect_state, expect_completed",
<ide> [
<ide> #
<ide> # Tests for all_success
<ide> #
<del> ["all_success", 5, 0, 0, 0, 0, 0, True, None, True],
<del> ["all_success", 2, 0, 0, 0, 0, 0, True, None, False],
<del> ["all_success", 2, 0, 1, 0, 0, 0, True, State.UPSTREAM_FAILED, False],
<del> ["all_success", 2, 1, 0, 0, 0, 0, True, State.SKIPPED, False],
<add> ["all_success", _UpstreamTIStates(5, 0, 0, 0, 0, 0), True, None, True],
<add> ["all_success", _UpstreamTIStates(2, 0, 0, 0, 0, 0), True, None, False],
<add> ["all_success", _UpstreamTIStates(2, 0, 1, 0, 0, 0), True, State.UPSTREAM_FAILED, False],
<add> ["all_success", _UpstreamTIStates(2, 1, 0, 0, 0, 0), True, State.SKIPPED, False],
<ide> #
<ide> # Tests for one_success
<ide> #
<del> ["one_success", 5, 0, 0, 0, 5, 0, True, None, True],
<del> ["one_success", 2, 0, 0, 0, 2, 0, True, None, True],
<del> ["one_success", 2, 0, 1, 0, 3, 0, True, None, True],
<del> ["one_success", 2, 1, 0, 0, 3, 0, True, None, True],
<del> ["one_success", 0, 5, 0, 0, 5, 0, True, State.SKIPPED, False],
<del> ["one_success", 0, 4, 1, 0, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 3, 1, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 4, 0, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 5, 0, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 4, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 0, 5, 5, 0, True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, True],
<add> ["one_success", _UpstreamTIStates(0, 5, 0, 0, 0, 5), True, State.SKIPPED, False],
<add> ["one_success", _UpstreamTIStates(0, 4, 1, 0, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 3, 1, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 4, 0, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 5, 0, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 4, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 0, 5, 0, 5), True, State.UPSTREAM_FAILED, False],
<ide> #
<ide> # Tests for all_failed
<ide> #
<del> ["all_failed", 5, 0, 0, 0, 5, 0, True, State.SKIPPED, False],
<del> ["all_failed", 0, 0, 5, 0, 5, 0, True, None, True],
<del> ["all_failed", 2, 0, 0, 0, 2, 0, True, State.SKIPPED, False],
<del> ["all_failed", 2, 0, 1, 0, 3, 0, True, State.SKIPPED, False],
<del> ["all_failed", 2, 1, 0, 0, 3, 0, True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(0, 0, 5, 0, 0, 5), True, None, True],
<add> ["all_failed", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, State.SKIPPED, False],
<ide> #
<ide> # Tests for one_failed
<ide> #
<del> ["one_failed", 5, 0, 0, 0, 0, 0, True, None, False],
<del> ["one_failed", 2, 0, 0, 0, 0, 0, True, None, False],
<del> ["one_failed", 2, 0, 1, 0, 0, 0, True, None, True],
<del> ["one_failed", 2, 1, 0, 0, 3, 0, True, None, False],
<del> ["one_failed", 2, 3, 0, 0, 5, 0, True, State.SKIPPED, False],
<add> ["one_failed", _UpstreamTIStates(5, 0, 0, 0, 0, 0), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 0, 0, 0, 0, 0), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 0, 1, 0, 0, 0), True, None, True],
<add> ["one_failed", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 3, 0, 0, 0, 5), True, State.SKIPPED, False],
<ide> #
<ide> # Tests for done
<ide> #
<del> ["all_done", 5, 0, 0, 0, 5, 0, True, None, True],
<del> ["all_done", 2, 0, 0, 0, 2, 0, True, None, False],
<del> ["all_done", 2, 0, 1, 0, 3, 0, True, None, False],
<del> ["all_done", 2, 1, 0, 0, 3, 0, True, None, False],
<add> ["all_done", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, None, True],
<add> ["all_done", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, None, False],
<add> ["all_done", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, None, False],
<add> ["all_done", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, False],
<ide> ],
<ide> )
<ide> def test_check_task_dependencies(
<ide> self,
<add> monkeypatch,
<add> dag_maker,
<ide> trigger_rule: str,
<del> successes: int,
<del> skipped: int,
<del> failed: int,
<del> removed: int,
<del> upstream_failed: int,
<del> done: int,
<add> upstream_states: _UpstreamTIStates,
<ide> flag_upstream_failed: bool,
<ide> expect_state: State,
<ide> expect_completed: bool,
<del> dag_maker,
<ide> ):
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: upstream_states)
<add>
<ide> with dag_maker() as dag:
<ide> downstream = EmptyOperator(task_id="downstream", trigger_rule=trigger_rule)
<ide> for i in range(5):
<ide> def test_check_task_dependencies(
<ide>
<ide> ti = dag_maker.create_dagrun(execution_date=run_date).get_task_instance(downstream.task_id)
<ide> ti.task = downstream
<add>
<ide> dep_results = TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=successes,
<del> skipped=skipped,
<del> failed=failed,
<del> removed=removed,
<del> upstream_failed=upstream_failed,
<del> done=done,
<del> dep_context=DepContext(),
<del> flag_upstream_failed=flag_upstream_failed,
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=dag_maker.session,
<ide> )
<ide> completed = all(dep.passed for dep in dep_results)
<ide>
<ide> def test_check_task_dependencies(
<ide> # Numeric fields are in order:
<ide> # successes, skipped, failed, upstream_failed, done,removed
<ide> @pytest.mark.parametrize(
<del> "trigger_rule,successes,skipped,failed,upstream_failed,done,removed,"
<del> "flag_upstream_failed,expect_state,expect_completed",
<add> "trigger_rule, upstream_states, flag_upstream_failed, expect_state, expect_completed",
<ide> [
<ide> #
<ide> # Tests for all_success
<ide> #
<del> ["all_success", 5, 0, 0, 0, 0, 0, True, None, True],
<del> ["all_success", 2, 0, 0, 0, 0, 0, True, None, False],
<del> ["all_success", 2, 0, 1, 0, 0, 0, True, State.UPSTREAM_FAILED, False],
<del> ["all_success", 2, 1, 0, 0, 0, 0, True, State.SKIPPED, False],
<del> ["all_success", 3, 0, 0, 0, 0, 2, True, State.REMOVED, True], # ti.map_index >=successes
<add> ["all_success", _UpstreamTIStates(5, 0, 0, 0, 0, 0), True, None, True],
<add> ["all_success", _UpstreamTIStates(2, 0, 0, 0, 0, 0), True, None, False],
<add> ["all_success", _UpstreamTIStates(2, 0, 1, 0, 0, 0), True, State.UPSTREAM_FAILED, False],
<add> ["all_success", _UpstreamTIStates(2, 1, 0, 0, 0, 0), True, State.SKIPPED, False],
<add> # ti.map_index >= success
<add> ["all_success", _UpstreamTIStates(3, 0, 0, 0, 2, 0), True, State.REMOVED, True],
<ide> #
<ide> # Tests for one_success
<ide> #
<del> ["one_success", 5, 0, 0, 0, 5, 0, True, None, True],
<del> ["one_success", 2, 0, 0, 0, 2, 0, True, None, True],
<del> ["one_success", 2, 0, 1, 0, 3, 0, True, None, True],
<del> ["one_success", 2, 1, 0, 0, 3, 0, True, None, True],
<del> ["one_success", 0, 5, 0, 0, 5, 0, True, State.SKIPPED, False],
<del> ["one_success", 0, 4, 1, 0, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 3, 1, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 4, 0, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 5, 0, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 4, 1, 5, 0, True, State.UPSTREAM_FAILED, False],
<del> ["one_success", 0, 0, 0, 5, 5, 0, True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, None, True],
<add> ["one_success", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, True],
<add> ["one_success", _UpstreamTIStates(0, 5, 0, 0, 0, 5), True, State.SKIPPED, False],
<add> ["one_success", _UpstreamTIStates(0, 4, 1, 0, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 3, 1, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 4, 0, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 5, 0, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 4, 1, 0, 5), True, State.UPSTREAM_FAILED, False],
<add> ["one_success", _UpstreamTIStates(0, 0, 0, 5, 0, 5), True, State.UPSTREAM_FAILED, False],
<ide> #
<ide> # Tests for all_failed
<ide> #
<del> ["all_failed", 5, 0, 0, 0, 5, 0, True, State.SKIPPED, False],
<del> ["all_failed", 0, 0, 5, 0, 5, 0, True, None, True],
<del> ["all_failed", 2, 0, 0, 0, 2, 0, True, State.SKIPPED, False],
<del> ["all_failed", 2, 0, 1, 0, 3, 0, True, State.SKIPPED, False],
<del> ["all_failed", 2, 1, 0, 0, 3, 0, True, State.SKIPPED, False],
<del> ["all_failed", 2, 1, 0, 0, 4, 1, True, State.SKIPPED, False], # One removed
<add> ["all_failed", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(0, 0, 5, 0, 0, 5), True, None, True],
<add> ["all_failed", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, State.SKIPPED, False],
<add> ["all_failed", _UpstreamTIStates(2, 1, 0, 0, 1, 4), True, State.SKIPPED, False], # One removed
<ide> #
<ide> # Tests for one_failed
<ide> #
<del> ["one_failed", 5, 0, 0, 0, 0, 0, True, None, False],
<del> ["one_failed", 2, 0, 0, 0, 0, 0, True, None, False],
<del> ["one_failed", 2, 0, 1, 0, 0, 0, True, None, True],
<del> ["one_failed", 2, 1, 0, 0, 3, 0, True, None, False],
<del> ["one_failed", 2, 3, 0, 0, 5, 0, True, State.SKIPPED, False],
<del> ["one_failed", 2, 2, 0, 0, 5, 1, True, State.SKIPPED, False], # One removed
<add> ["one_failed", _UpstreamTIStates(5, 0, 0, 0, 0, 0), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 0, 0, 0, 0, 0), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 0, 1, 0, 0, 0), True, None, True],
<add> ["one_failed", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, False],
<add> ["one_failed", _UpstreamTIStates(2, 3, 0, 0, 0, 5), True, State.SKIPPED, False],
<add> ["one_failed", _UpstreamTIStates(2, 2, 0, 0, 1, 5), True, State.SKIPPED, False], # One removed
<ide> #
<ide> # Tests for done
<ide> #
<del> ["all_done", 5, 0, 0, 0, 5, 0, True, None, True],
<del> ["all_done", 2, 0, 0, 0, 2, 0, True, None, False],
<del> ["all_done", 2, 0, 1, 0, 3, 0, True, None, False],
<del> ["all_done", 2, 1, 0, 0, 3, 0, True, None, False],
<add> ["all_done", _UpstreamTIStates(5, 0, 0, 0, 0, 5), True, None, True],
<add> ["all_done", _UpstreamTIStates(2, 0, 0, 0, 0, 2), True, None, False],
<add> ["all_done", _UpstreamTIStates(2, 0, 1, 0, 0, 3), True, None, False],
<add> ["all_done", _UpstreamTIStates(2, 1, 0, 0, 0, 3), True, None, False],
<ide> ],
<ide> )
<ide> def test_check_task_dependencies_for_mapped(
<ide> self,
<add> monkeypatch,
<add> dag_maker,
<add> session,
<ide> trigger_rule: str,
<del> successes: int,
<del> skipped: int,
<del> failed: int,
<del> removed: int,
<del> upstream_failed: int,
<del> done: int,
<add> upstream_states: _UpstreamTIStates,
<ide> flag_upstream_failed: bool,
<ide> expect_state: State,
<ide> expect_completed: bool,
<del> dag_maker,
<del> session,
<ide> ):
<ide> from airflow.decorators import task
<ide>
<ide> def do_something(i):
<ide> def do_something_else(i):
<ide> return 1
<ide>
<del> with dag_maker(dag_id="test_dag"):
<add> with dag_maker(dag_id="test_dag", session=session):
<ide> nums = do_something.expand(i=[i + 1 for i in range(5)])
<ide> do_something_else.expand(i=nums)
<ide>
<ide> dr = dag_maker.create_dagrun()
<ide>
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: upstream_states)
<ide> ti = dr.get_task_instance("do_something_else", session=session)
<ide> ti.map_index = 0
<ide> for map_index in range(1, 5):
<ide> def do_something_else(i):
<ide> ti.task = downstream
<ide> dep_results = TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=successes,
<del> skipped=skipped,
<del> failed=failed,
<del> removed=removed,
<del> upstream_failed=upstream_failed,
<del> done=done,
<del> dep_context=DepContext(),
<del> flag_upstream_failed=flag_upstream_failed,
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=session,
<ide> )
<ide> completed = all(dep.passed for dep in dep_results)
<ide>
<ide><path>tests/ti_deps/deps/test_trigger_rule_dep.py
<ide> from __future__ import annotations
<ide>
<ide> from datetime import datetime
<del>from unittest.mock import Mock
<add>from unittest import mock
<ide>
<ide> import pytest
<ide>
<del>from airflow import settings
<del>from airflow.models import DAG
<ide> from airflow.models.baseoperator import BaseOperator
<ide> from airflow.models.taskinstance import TaskInstance
<ide> from airflow.operators.empty import EmptyOperator
<ide> from airflow.ti_deps.dep_context import DepContext
<del>from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep
<del>from airflow.utils import timezone
<del>from airflow.utils.session import create_session
<del>from airflow.utils.state import State, TaskInstanceState
<add>from airflow.ti_deps.deps.trigger_rule_dep import TriggerRuleDep, _UpstreamTIStates
<add>from airflow.utils.state import DagRunState, TaskInstanceState
<ide> from airflow.utils.trigger_rule import TriggerRule
<del>from tests.models import DEFAULT_DATE
<del>from tests.test_utils.db import clear_db_runs
<ide>
<ide>
<ide> @pytest.fixture
<del>def get_task_instance(session, dag_maker):
<del> def _get_task_instance(trigger_rule=TriggerRule.ALL_SUCCESS, state=None, upstream_task_ids=None):
<add>def get_task_instance(monkeypatch, session, dag_maker):
<add> def _get_task_instance(
<add> trigger_rule: TriggerRule = TriggerRule.ALL_SUCCESS,
<add> *,
<add> success: int | list[str] = 0,
<add> skipped: int | list[str] = 0,
<add> failed: int | list[str] = 0,
<add> upstream_failed: int | list[str] = 0,
<add> removed: int | list[str] = 0,
<add> done: int = 0,
<add> ):
<ide> with dag_maker(session=session):
<ide> task = BaseOperator(
<del> task_id="test_task", trigger_rule=trigger_rule, start_date=datetime(2015, 1, 1)
<add> task_id="test_task",
<add> trigger_rule=trigger_rule,
<add> start_date=datetime(2015, 1, 1),
<ide> )
<del> if upstream_task_ids:
<del> [EmptyOperator(task_id=task_id) for task_id in upstream_task_ids] >> task
<add> for upstreams in (success, skipped, failed, upstream_failed, removed, done):
<add> if not isinstance(upstreams, int):
<add> [EmptyOperator(task_id=task_id) for task_id in upstreams] >> task
<ide> dr = dag_maker.create_dagrun()
<ide> ti = dr.task_instances[0]
<ide> ti.task = task
<add>
<add> fake_upstream_states = _UpstreamTIStates(
<add> success=(success if isinstance(success, int) else len(success)),
<add> skipped=(skipped if isinstance(skipped, int) else len(skipped)),
<add> failed=(failed if isinstance(failed, int) else len(failed)),
<add> upstream_failed=(upstream_failed if isinstance(upstream_failed, int) else len(upstream_failed)),
<add> removed=(removed if isinstance(removed, int) else len(removed)),
<add> done=done,
<add> )
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: fake_upstream_states)
<add>
<ide> return ti
<ide>
<ide> return _get_task_instance
<ide>
<ide>
<ide> @pytest.fixture
<ide> def get_mapped_task_dagrun(session, dag_maker):
<del> def _get_dagrun(trigger_rule=TriggerRule.ALL_SUCCESS, state=State.SUCCESS):
<add> def _get_dagrun(trigger_rule=TriggerRule.ALL_SUCCESS, state=TaskInstanceState.SUCCESS):
<ide> from airflow.decorators import task
<ide>
<ide> @task
<ide> def test_no_upstream_tasks(self, get_task_instance):
<ide> """
<ide> If the TI has no upstream TIs then there is nothing to check and the dep is passed
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_DONE, State.UP_FOR_RETRY)
<add> ti = get_task_instance(TriggerRule.ALL_DONE)
<ide> assert TriggerRuleDep().is_met(ti=ti)
<ide>
<ide> def test_always_tr(self, get_task_instance):
<ide> """
<ide> The always trigger rule should always pass this dep
<ide> """
<del> ti = get_task_instance(TriggerRule.ALWAYS, State.UP_FOR_RETRY)
<add> ti = get_task_instance(TriggerRule.ALWAYS)
<ide> assert TriggerRuleDep().is_met(ti=ti)
<ide>
<ide> def test_one_success_tr_success(self, get_task_instance):
<ide> """
<ide> One-success trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_SUCCESS, State.UP_FOR_RETRY)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_SUCCESS,
<add> success=1,
<add> skipped=2,
<add> failed=3,
<add> removed=0,
<add> upstream_failed=2,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=2,
<del> failed=2,
<del> removed=0,
<del> upstream_failed=2,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_one_success_tr_failure(self, get_task_instance):
<ide> """
<ide> One-success trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_SUCCESS)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_SUCCESS,
<add> success=0,
<add> skipped=2,
<add> failed=2,
<add> removed=0,
<add> upstream_failed=2,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=2,
<del> removed=0,
<del> upstream_failed=2,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_one_failure_tr_failure(self, get_task_instance):
<ide> """
<ide> One-failure trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_FAILED)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_FAILED,
<add> success=2,
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=2,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_one_failure_tr_success(self, get_task_instance):
<ide> """
<ide> One-failure trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_FAILED)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_FAILED,
<add> success=0,
<add> skipped=2,
<add> failed=2,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=2,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide>
<add> def test_one_failure_tr_success_no_failed(self, get_task_instance):
<add> """
<add> One-failure trigger rule success
<add> """
<add> ti = get_task_instance(
<add> TriggerRule.ONE_FAILED,
<add> success=0,
<add> skipped=2,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=2,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=2,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_one_done_tr_success(self, get_task_instance):
<ide> """
<ide> One-done trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_DONE)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_DONE,
<add> success=2,
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=2,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide>
<add> def test_one_done_tr_success_with_failed(self, get_task_instance):
<add> """
<add> One-done trigger rule success
<add> """
<add> ti = get_task_instance(
<add> TriggerRule.ONE_DONE,
<add> success=0,
<add> skipped=0,
<add> failed=2,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=2,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_one_done_tr_skip(self, get_task_instance):
<ide> """
<ide> One-done trigger rule skip
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_DONE)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_DONE,
<add> success=0,
<add> skipped=2,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_one_done_tr_upstream_failed(self, get_task_instance):
<ide> """
<ide> One-done trigger rule upstream_failed
<ide> """
<del> ti = get_task_instance(TriggerRule.ONE_DONE)
<add> ti = get_task_instance(
<add> TriggerRule.ONE_DONE,
<add> success=0,
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=2,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=2,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_all_success_tr_success(self, get_task_instance):
<ide> """
<ide> All-success trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_SUCCESS, upstream_task_ids=["FakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_SUCCESS,
<add> success=["FakeTaskID"],
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=1,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=1,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_all_success_tr_failure(self, get_task_instance):
<ide> """
<ide> All-success trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_SUCCESS, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_SUCCESS,
<add> success=["FakeTaskID"],
<add> skipped=0,
<add> failed=["OtherFakeTaskID"],
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=0,
<del> failed=1,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> assert not dep_statuses[0].passed
<ide>
<del> def test_all_success_tr_skip(self, get_task_instance):
<add> @pytest.mark.parametrize(
<add> "flag_upstream_failed, expected_ti_state",
<add> [(True, TaskInstanceState.SKIPPED), (False, None)],
<add> )
<add> def test_all_success_tr_skip(self, get_task_instance, flag_upstream_failed, expected_ti_state):
<ide> """
<ide> All-success trigger rule fails when some upstream tasks are skipped.
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_SUCCESS, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<del> )
<add> ti = get_task_instance(
<add> TriggerRule.ALL_SUCCESS,
<add> success=["FakeTaskID"],
<add> skipped=["OtherFakeTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<ide> )
<del> assert len(dep_statuses) == 1
<del> assert not dep_statuses[0].passed
<del>
<del> def test_all_success_tr_skip_flag_upstream(self, get_task_instance):
<del> """
<del> All-success trigger rule fails when some upstream tasks are skipped. The state of the ti
<del> should be set to SKIPPED when flag_upstream_failed is True.
<del> """
<del> ti = get_task_instance(TriggerRule.ALL_SUCCESS, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=Mock(),
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> assert not dep_statuses[0].passed
<del> assert ti.state == State.SKIPPED
<add> assert ti.state == expected_ti_state
<ide>
<del> def test_none_failed_tr_success(self, get_task_instance):
<add> @pytest.mark.parametrize("flag_upstream_failed", [True, False])
<add> def test_none_failed_tr_success(self, get_task_instance, flag_upstream_failed):
<ide> """
<ide> All success including skip trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.NONE_FAILED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<del> )
<add> ti = get_task_instance(
<add> TriggerRule.NONE_FAILED,
<add> success=["FakeTaskID"],
<add> skipped=["OtherFakeTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<ide> )
<del> assert len(dep_statuses) == 0
<del>
<del> def test_none_failed_tr_skipped(self, get_task_instance):
<del> """
<del> All success including all upstream skips trigger rule success
<del> """
<del> ti = get_task_instance(TriggerRule.NONE_FAILED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=Mock(),
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<del> assert ti.state == State.NONE
<add> assert ti.state is None
<ide>
<ide> def test_none_failed_tr_failure(self, get_task_instance):
<ide> """
<ide> All success including skip trigger rule failure
<ide> """
<ide> ti = get_task_instance(
<del> TriggerRule.NONE_FAILED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID", "FailedFakeTaskID"]
<add> TriggerRule.NONE_FAILED,
<add> success=["FakeTaskID"],
<add> skipped=["OtherFakeTaskID"],
<add> failed=["FailedFakeTaskID"],
<add> removed=0,
<add> upstream_failed=0,
<add> done=3,
<ide> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=1,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_none_failed_min_one_success_tr_success(self, get_task_instance):
<ide> All success including skip trigger rule success
<ide> """
<ide> ti = get_task_instance(
<del> TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"]
<add> TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
<add> success=["FakeTaskID"],
<add> skipped=["OtherFakeTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<ide> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_none_failed_min_one_success_tr_skipped(self, get_task_instance):
<ide> All success including all upstream skips trigger rule success
<ide> """
<ide> ti = get_task_instance(
<del> TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"]
<add> TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
<add> success=0,
<add> skipped=["FakeTaskID", "OtherFakeTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<ide> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=2,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=Mock(),
<add> dep_context=DepContext(flag_upstream_failed=True),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<del> assert ti.state == State.SKIPPED
<add> assert ti.state == TaskInstanceState.SKIPPED
<ide>
<ide> def test_none_failed_min_one_success_tr_failure(self, session, get_task_instance):
<ide> """
<ide> All success including skip trigger rule failure
<ide> """
<ide> ti = get_task_instance(
<ide> TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS,
<del> upstream_task_ids=["FakeTaskID", "OtherFakeTaskID", "FailedFakeTaskID"],
<add> success=["FakeTaskID"],
<add> skipped=["OtherFakeTaskID"],
<add> failed=["FailedFakeTaskID"],
<add> removed=0,
<add> upstream_failed=0,
<add> done=3,
<ide> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=1,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_all_failed_tr_success(self, get_task_instance):
<ide> """
<ide> All-failed trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_FAILED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_FAILED,
<add> success=0,
<add> skipped=0,
<add> failed=["FakeTaskID", "OtherFakeTaskID"],
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=2,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_all_failed_tr_failure(self, get_task_instance):
<ide> """
<ide> All-failed trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_FAILED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_FAILED,
<add> success=["FakeTaskID", "OtherFakeTaskID"],
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=2,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> def test_all_done_tr_success(self, get_task_instance):
<ide> """
<ide> All-done trigger rule success
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_DONE, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_DONE,
<add> success=["FakeTaskID", "OtherFakeTaskID"],
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=2,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 0
<ide> def test_all_skipped_tr_failure(self, get_task_instance):
<ide> """
<ide> All-skipped trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_SKIPPED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_SKIPPED,
<add> success=["FakeTaskID"],
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=1,
<add> )
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=1,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> assert not dep_statuses[0].passed
<ide>
<del> def test_all_skipped_tr_success(self, get_task_instance):
<add> @pytest.mark.parametrize("flag_upstream_failed", [True, False])
<add> def test_all_skipped_tr_success(self, get_task_instance, flag_upstream_failed):
<ide> """
<ide> All-skipped trigger rule success
<ide> """
<ide> ti = get_task_instance(
<del> TriggerRule.ALL_SKIPPED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID", "FailedFakeTaskID"]
<del> )
<del> with create_session() as session:
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=0,
<del> skipped=3,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<del> )
<del> assert len(dep_statuses) == 0
<del>
<del> # with `flag_upstream_failed` set to True
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=0,
<del> skipped=3,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<add> TriggerRule.ALL_SKIPPED,
<add> success=0,
<add> skipped=["FakeTaskID", "OtherFakeTaskID", "FailedFakeTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=3,
<add> )
<add> dep_statuses = tuple(
<add> TriggerRuleDep()._evaluate_trigger_rule(
<add> ti=ti,
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=mock.Mock(),
<ide> )
<del> assert len(dep_statuses) == 0
<add> )
<add> assert len(dep_statuses) == 0
<ide>
<ide> def test_all_done_tr_failure(self, get_task_instance):
<ide> """
<ide> All-done trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.ALL_DONE, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID"])
<add> ti = get_task_instance(
<add> TriggerRule.ALL_DONE,
<add> success=["FakeTaskID"],
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=1,
<add> )
<add> EmptyOperator(task_id="OtherFakeTeakID", dag=ti.task.dag) >> ti.task # An unfinished upstream.
<add>
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=1,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<ide> assert len(dep_statuses) == 1
<ide> assert not dep_statuses[0].passed
<ide>
<del> def test_none_skipped_tr_success(self, get_task_instance):
<add> @pytest.mark.parametrize("flag_upstream_failed", [True, False])
<add> def test_none_skipped_tr_success(self, get_task_instance, flag_upstream_failed):
<ide> """
<ide> None-skipped trigger rule success
<ide> """
<ide> ti = get_task_instance(
<del> TriggerRule.NONE_SKIPPED, upstream_task_ids=["FakeTaskID", "OtherFakeTaskID", "FailedFakeTaskID"]
<del> )
<del> with create_session() as session:
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=2,
<del> skipped=0,
<del> failed=1,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<del> )
<del> assert len(dep_statuses) == 0
<del>
<del> # with `flag_upstream_failed` set to True
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=3,
<del> removed=0,
<del> upstream_failed=0,
<del> done=3,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<add> TriggerRule.NONE_SKIPPED,
<add> success=["FakeTaskID", "OtherFakeTaskID"],
<add> skipped=0,
<add> failed=["FailedFakeTaskID"],
<add> removed=0,
<add> upstream_failed=0,
<add> done=3,
<add> )
<add> dep_statuses = tuple(
<add> TriggerRuleDep()._evaluate_trigger_rule(
<add> ti=ti,
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=mock.Mock(),
<ide> )
<del> assert len(dep_statuses) == 0
<add> )
<add> assert len(dep_statuses) == 0
<ide>
<del> def test_none_skipped_tr_failure(self, get_task_instance):
<add> @pytest.mark.parametrize("flag_upstream_failed", [True, False])
<add> def test_none_skipped_tr_failure(self, get_task_instance, flag_upstream_failed):
<ide> """
<ide> None-skipped trigger rule failure
<ide> """
<del> ti = get_task_instance(TriggerRule.NONE_SKIPPED, upstream_task_ids=["FakeTaskID", "SkippedTaskID"])
<del>
<del> with create_session() as session:
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<del> )
<del> assert len(dep_statuses) == 1
<del> assert not dep_statuses[0].passed
<del>
<del> # with `flag_upstream_failed` set to True
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=1,
<del> skipped=1,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=2,
<del> flag_upstream_failed=True,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<add> ti = get_task_instance(
<add> TriggerRule.NONE_SKIPPED,
<add> success=["FakeTaskID"],
<add> skipped=["SkippedTaskID"],
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=2,
<add> )
<add> dep_statuses = tuple(
<add> TriggerRuleDep()._evaluate_trigger_rule(
<add> ti=ti,
<add> dep_context=DepContext(flag_upstream_failed=flag_upstream_failed),
<add> session=mock.Mock(),
<ide> )
<del> assert len(dep_statuses) == 1
<del> assert not dep_statuses[0].passed
<del>
<del> # Fail until all upstream tasks have completed execution
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=0,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<add> )
<add> assert len(dep_statuses) == 1
<add> assert not dep_statuses[0].passed
<add>
<add> def test_none_skipped_tr_failure_empty(self, get_task_instance):
<add> """
<add> None-skipped trigger rule fails until all upstream tasks have completed execution
<add> """
<add> ti = get_task_instance(
<add> TriggerRule.NONE_SKIPPED,
<add> success=0,
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=0,
<add> )
<add> EmptyOperator(task_id="FakeTeakID", dag=ti.task.dag) >> ti.task # An unfinished upstream.
<add>
<add> dep_statuses = tuple(
<add> TriggerRuleDep()._evaluate_trigger_rule(
<add> ti=ti,
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<del> assert len(dep_statuses) == 1
<del> assert not dep_statuses[0].passed
<add> )
<add> assert len(dep_statuses) == 1
<add> assert not dep_statuses[0].passed
<ide>
<ide> def test_unknown_tr(self, get_task_instance):
<ide> """
<ide> Unknown trigger rules should cause this dep to fail
<ide> """
<del> ti = get_task_instance()
<add> ti = get_task_instance(
<add> TriggerRule.DUMMY,
<add> success=1,
<add> skipped=0,
<add> failed=0,
<add> removed=0,
<add> upstream_failed=0,
<add> done=1,
<add> )
<ide> ti.task.trigger_rule = "Unknown Trigger Rule"
<add>
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=1,
<del> skipped=0,
<del> failed=0,
<del> removed=0,
<del> upstream_failed=0,
<del> done=1,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session="Fake Session",
<add> dep_context=DepContext(flag_upstream_failed=False),
<add> session=mock.Mock(),
<ide> )
<ide> )
<del>
<ide> assert len(dep_statuses) == 1
<ide> assert not dep_statuses[0].passed
<ide>
<del> def test_get_states_count_upstream_ti(self):
<add> def test_UpstreamTIStates(self, session, dag_maker):
<ide> """
<del> this test tests the helper function '_get_states_count_upstream_ti' as a unit and inside update_state
<add> this test tests the helper class '_UpstreamTIStates' as a unit and inside update_state
<ide> """
<del> from airflow.ti_deps.dep_context import DepContext
<del>
<del> get_states_count_upstream_ti = TriggerRuleDep._get_states_count_upstream_ti
<del> session = settings.Session()
<del> now = timezone.utcnow()
<del> dag = DAG("test_dagrun_with_pre_tis", start_date=DEFAULT_DATE, default_args={"owner": "owner1"})
<del>
<del> with dag:
<del> op1 = EmptyOperator(task_id="A")
<del> op2 = EmptyOperator(task_id="B")
<del> op3 = EmptyOperator(task_id="C")
<del> op4 = EmptyOperator(task_id="D")
<del> op5 = EmptyOperator(task_id="E", trigger_rule=TriggerRule.ONE_FAILED)
<del>
<del> op1.set_downstream([op2, op3]) # op1 >> op2, op3
<del> op4.set_upstream([op3, op2]) # op3, op2 >> op4
<del> op5.set_upstream([op2, op3, op4]) # (op2, op3, op4) >> op5
<del>
<del> clear_db_runs()
<del> dag.clear()
<del> dr = dag.create_dagrun(
<del> run_id="test_dagrun_with_pre_tis", state=State.RUNNING, execution_date=now, start_date=now
<del> )
<add> with dag_maker(session=session):
<add> op1 = EmptyOperator(task_id="op1")
<add> op2 = EmptyOperator(task_id="op2")
<add> op3 = EmptyOperator(task_id="op3")
<add> op4 = EmptyOperator(task_id="op4")
<add> op5 = EmptyOperator(task_id="op5", trigger_rule=TriggerRule.ONE_FAILED)
<ide>
<del> ti_op1 = dr.get_task_instance(op1.task_id, session)
<del> ti_op2 = dr.get_task_instance(op2.task_id, session)
<del> ti_op3 = dr.get_task_instance(op3.task_id, session)
<del> ti_op4 = dr.get_task_instance(op4.task_id, session)
<del> ti_op5 = dr.get_task_instance(op5.task_id, session)
<del> ti_op1.task = op1
<del> ti_op2.task = op2
<del> ti_op3.task = op3
<del> ti_op4.task = op4
<del> ti_op5.task = op5
<add> op1 >> (op2, op3) >> op4
<add> (op2, op3, op4) >> op5
<ide>
<del> ti_op1.set_state(state=State.SUCCESS, session=session)
<del> ti_op2.set_state(state=State.FAILED, session=session)
<del> ti_op3.set_state(state=State.SUCCESS, session=session)
<del> ti_op4.set_state(state=State.SUCCESS, session=session)
<del> ti_op5.set_state(state=State.SUCCESS, session=session)
<add> dr = dag_maker.create_dagrun()
<add> tis = {ti.task_id: ti for ti in dr.task_instances}
<ide>
<del> session.commit()
<add> tis["op1"].state = TaskInstanceState.SUCCESS
<add> tis["op2"].state = TaskInstanceState.FAILED
<add> tis["op3"].state = TaskInstanceState.SUCCESS
<add> tis["op4"].state = TaskInstanceState.SUCCESS
<add> tis["op5"].state = TaskInstanceState.SUCCESS
<ide>
<ide> # check handling with cases that tasks are triggered from backfill with no finished tasks
<del> finished_tis = DepContext().ensure_finished_tis(ti_op2.dag_run, session)
<del> assert get_states_count_upstream_ti(finished_tis=finished_tis, task=op2) == (1, 0, 0, 0, 0, 1)
<del> finished_tis = dr.get_task_instances(state=State.finished, session=session)
<del> assert get_states_count_upstream_ti(finished_tis=finished_tis, task=op4) == (1, 0, 1, 0, 0, 2)
<del> assert get_states_count_upstream_ti(finished_tis=finished_tis, task=op5) == (2, 0, 1, 0, 0, 3)
<add> finished_tis = tis.values()
<add> assert _UpstreamTIStates.calculate(ti=tis["op2"], finished_tis=finished_tis) == (1, 0, 0, 0, 0, 1)
<add> assert _UpstreamTIStates.calculate(ti=tis["op4"], finished_tis=finished_tis) == (1, 0, 1, 0, 0, 2)
<add> assert _UpstreamTIStates.calculate(ti=tis["op5"], finished_tis=finished_tis) == (2, 0, 1, 0, 0, 3)
<ide>
<del> dr.update_state()
<del> assert State.SUCCESS == dr.state
<add> dr.update_state(session=session)
<add> assert dr.state == DagRunState.SUCCESS
<ide>
<ide> def test_mapped_task_upstream_removed_with_all_success_trigger_rules(
<del> self, session, get_mapped_task_dagrun
<add> self,
<add> monkeypatch,
<add> session,
<add> get_mapped_task_dagrun,
<ide> ):
<ide> """
<ide> Test ALL_SUCCESS trigger rule with mapped task upstream removed
<ide> def test_mapped_task_upstream_removed_with_all_success_trigger_rules(
<ide> ti = dr.get_task_instance(task_id="do_something_else", map_index=3, session=session)
<ide> ti.task = task
<ide>
<add> upstream_states = _UpstreamTIStates(
<add> success=3,
<add> skipped=0,
<add> failed=0,
<add> removed=2,
<add> upstream_failed=0,
<add> done=5,
<add> )
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: upstream_states)
<add>
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=3,
<del> skipped=0,
<del> failed=0,
<del> removed=2,
<del> upstream_failed=0,
<del> done=5,
<del> flag_upstream_failed=True, # marks the task as removed if upstream is removed
<del> dep_context=DepContext(),
<add> # Marks the task as removed if upstream is removed.
<add> dep_context=DepContext(flag_upstream_failed=True),
<ide> session=session,
<ide> )
<ide> )
<del>
<ide> assert len(dep_statuses) == 0
<ide> assert ti.state == TaskInstanceState.REMOVED
<ide>
<ide> def test_mapped_task_upstream_removed_with_all_failed_trigger_rules(
<del> self, session, get_mapped_task_dagrun
<add> self,
<add> monkeypatch,
<add> session,
<add> get_mapped_task_dagrun,
<ide> ):
<ide> """
<ide> Test ALL_FAILED trigger rule with mapped task upstream removed
<ide> """
<ide>
<del> dr, task = get_mapped_task_dagrun(trigger_rule=TriggerRule.ALL_FAILED, state=State.FAILED)
<add> dr, task = get_mapped_task_dagrun(trigger_rule=TriggerRule.ALL_FAILED, state=TaskInstanceState.FAILED)
<ide>
<ide> # ti with removed upstream ti
<ide> ti = dr.get_task_instance(task_id="do_something_else", map_index=3, session=session)
<ide> ti.task = task
<ide>
<add> upstream_states = _UpstreamTIStates(
<add> success=0,
<add> skipped=0,
<add> failed=3,
<add> removed=2,
<add> upstream_failed=0,
<add> done=5,
<add> )
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: upstream_states)
<add>
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=0,
<del> skipped=0,
<del> failed=3,
<del> removed=2,
<del> upstream_failed=0,
<del> done=5,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<add> dep_context=DepContext(flag_upstream_failed=False),
<ide> session=session,
<ide> )
<ide> )
<ide>
<ide> assert len(dep_statuses) == 0
<ide>
<add> @pytest.mark.parametrize(
<add> "trigger_rule",
<add> [TriggerRule.NONE_FAILED, TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS],
<add> )
<ide> def test_mapped_task_upstream_removed_with_none_failed_trigger_rules(
<del> self, session, get_mapped_task_dagrun
<add> self,
<add> monkeypatch,
<add> session,
<add> get_mapped_task_dagrun,
<add> trigger_rule,
<ide> ):
<ide> """
<ide> Test NONE_FAILED trigger rule with mapped task upstream removed
<ide> """
<del> dr, task = get_mapped_task_dagrun(trigger_rule=TriggerRule.NONE_FAILED)
<add> dr, task = get_mapped_task_dagrun(trigger_rule=trigger_rule)
<ide>
<ide> # ti with removed upstream ti
<ide> ti = dr.get_task_instance(task_id="do_something_else", map_index=3, session=session)
<ide> ti.task = task
<ide>
<del> dep_statuses = tuple(
<del> TriggerRuleDep()._evaluate_trigger_rule(
<del> ti=ti,
<del> successes=3,
<del> skipped=0,
<del> failed=0,
<del> removed=2,
<del> upstream_failed=0,
<del> done=5,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<del> session=session,
<del> )
<add> upstream_states = _UpstreamTIStates(
<add> success=3,
<add> skipped=0,
<add> failed=0,
<add> removed=2,
<add> upstream_failed=0,
<add> done=5,
<ide> )
<del>
<del> assert len(dep_statuses) == 0
<del>
<del> def test_mapped_task_upstream_removed_with_none_failed_min_one_success_trigger_rules(
<del> self, session, get_mapped_task_dagrun
<del> ):
<del> """
<del> Test NONE_FAILED_MIN_ONE_SUCCESS trigger rule with mapped task upstream removed
<del> """
<del> dr, task = get_mapped_task_dagrun(trigger_rule=TriggerRule.NONE_FAILED_MIN_ONE_SUCCESS)
<del>
<del> # ti with removed upstream ti
<del> ti = dr.get_task_instance(task_id="do_something_else", map_index=3, session=session)
<del> ti.task = task
<add> monkeypatch.setattr(_UpstreamTIStates, "calculate", lambda *_: upstream_states)
<ide>
<ide> dep_statuses = tuple(
<ide> TriggerRuleDep()._evaluate_trigger_rule(
<ide> ti=ti,
<del> successes=3,
<del> skipped=0,
<del> failed=0,
<del> removed=2,
<del> upstream_failed=0,
<del> done=5,
<del> flag_upstream_failed=False,
<del> dep_context=DepContext(),
<add> dep_context=DepContext(flag_upstream_failed=False),
<ide> session=session,
<ide> )
<ide> ) | 4 |
Javascript | Javascript | fix typos in code comment | 0506d294dc5a51556e935a50a754aa7cbd7a7977 | <ide><path>lib/events.js
<ide> EventEmitter.prototype.addListener = function(type, listener) {
<ide>
<ide> if (!this._events) this._events = {};
<ide>
<del> // To avoid recursion in the case that type == "newListeners"! Before
<del> // adding it to the listeners, first emit "newListeners".
<add> // To avoid recursion in the case that type == "newListener"! Before
<add> // adding it to the listeners, first emit "newListener".
<ide> if (this._events.newListener) {
<ide> this.emit('newListener', type, typeof listener.listener === 'function' ?
<ide> listener.listener : listener); | 1 |
Ruby | Ruby | remove warning for setting eager_load | 382f52ddbb248cc3b5562aa033def3c33625f49a | <ide><path>railties/test/application/multiple_applications_test.rb
<ide> def test_initializers_run_on_different_applications_go_to_the_same_class
<ide> assert_equal 0, run_count, "Without loading the initializers, the count should be 0"
<ide>
<ide> # Set config.eager_load to false so that an eager_load warning doesn't pop up
<del> AppTemplate::Application.new { config.eager_load = false }.initialize!
<add> AppTemplate::Application.create { config.eager_load = false }.initialize!
<ide>
<ide> assert_equal 3, run_count, "There should have been three initializers that incremented the count"
<ide> end | 1 |
Python | Python | fix the path to `mypy.ini` | ba35907d202f66a35fb460ef7a6c01e0e2631f81 | <ide><path>runtests.py
<ide> def main(argv):
<ide> config = os.path.join(
<ide> site_dir,
<ide> "numpy",
<del> "tests",
<ide> "typing",
<add> "tests",
<add> "data",
<ide> "mypy.ini",
<ide> )
<ide> | 1 |
Javascript | Javascript | fix some more tests | 21c4c133daca61ebf8b5b42433e50b189d2d4ece | <ide><path>packages/ember-metal/lib/tags.js
<ide> export function markObjectAsDirty(meta, propertyKey) {
<ide> let objectTag = meta.readableTag();
<ide>
<ide> if (objectTag !== undefined) {
<del> objectTag.dirty();
<add> objectTag.inner.dirty();
<ide> }
<ide>
<ide> let tags = meta.readableTags();
<ide> export function markObjectAsDirty(meta, propertyKey) {
<ide> }
<ide>
<ide> if (propertyKey === 'content' && meta.isProxy()) {
<del> objectTag.contentDidChange();
<add> objectTag.inner.contentDidChange();
<ide> }
<ide>
<ide> if (objectTag !== undefined || propertyTag !== undefined) { | 1 |
Python | Python | fix typo auto_add -> auto_now | ea151e858dda765c8805038bb967e2dcdf65116a | <ide><path>celery/models.py
<ide> class TaskMeta(models.Model):
<ide> task_id = models.CharField(_(u"task id"), max_length=255, unique=True)
<ide> is_done = models.BooleanField(_(u"is done"), default=False)
<del> date_done = models.DateTimeField(_(u"done at"), auto_add=True)
<add> date_done = models.DateTimeField(_(u"done at"), auto_now=True)
<ide> objects = TaskManager()
<ide>
<ide> class Meta: | 1 |
Javascript | Javascript | fail tests on errors in renderer | 8c5794eab3cfb8a027bd6eb338a3ba16f03d3564 | <ide><path>src/__tests__/setupTests.js
<ide> env.beforeEach(() => {
<ide> // Fake timers let us flush Bridge operations between setup and assertions.
<ide> jest.useFakeTimers();
<ide>
<add> const originalConsoleError = console.error;
<add> console.error = (...args) => {
<add> if (args[0] === 'Warning: React DevTools encountered an error: %s') {
<add> // Rethrow errors from React.
<add> throw args[1];
<add> }
<add> originalConsoleError.apply(console, args);
<add> };
<add>
<ide> installHook(global);
<ide>
<ide> const bridgeListeners = []; | 1 |
Text | Text | update changelog for version 1.8.2 | 3b7cdfcd6b7a1c22a8318afaac16e5328b56ff1f | <ide><path>CHANGELOG.md
<ide> # Changelog
<ide>
<add>## 1.8.2 (2015-09-10)
<add>
<add>### Distribution:
<add>
<add>- Fixes rare edge case of handling GNU LongLink and LongName entries.
<add>- Fix ^C on docker pull.
<add>- Fix docker pull issues on client disconnection.
<add>- Fix issue that caused the daemon to panic when loggers weren't configured properly.
<add>- Fix goroutine leak pulling images from registry V2.
<add>
<add>### Runtime:
<add>
<add>- Fix a bug mounting cgroups for docker daemons running inside docker containers.
<add>- Initialize log configuration properly.
<add>
<add>### Client:
<add>
<add>- Handle `-q` flag in `docker ps` properly when there is a default format.
<add>
<add>### Networking:
<add>
<add>- Fix several corner cases with netlink.
<add>
<add>### Contrib:
<add>
<add>- Fix several issues with bash completion.
<add>
<ide> ## 1.8.1 (2015-08-12)
<ide>
<ide> ### Distribution | 1 |
Javascript | Javascript | add scalelabel to core.scale | 73729877546e9bb0445e72a97978860685ccb0aa | <ide><path>src/core/core.scale.js
<ide> offsetGridLines: false,
<ide> },
<ide>
<add> // scale label
<add> scaleLabel: {
<add> fontColor: '#666',
<add> fontFamily: 'Helvetica Neue',
<add> fontSize: 12,
<add> fontStyle: 'normal',
<add>
<add> // actual label
<add> labelString: '',
<add>
<add> // display property
<add> show: false,
<add> },
<add>
<ide> // label settings
<ide> ticks: {
<ide> show: true, | 1 |
Javascript | Javascript | remove reload on servercomponentchanges in pages | 6fefa98b3678233376a38d798869d6fe8a2a758d | <ide><path>packages/next/client/dev/error-overlay/hot-dev-client.js
<ide> function processMessage(e) {
<ide> )
<ide> return handleSuccess()
<ide> }
<del>
<del> case 'serverComponentChanges': {
<del> sendMessage(
<del> JSON.stringify({
<del> event: 'server-component-reload-page',
<del> clientId: window.__nextDevClientId,
<del> })
<del> )
<del> return window.location.reload()
<del> }
<ide> default: {
<ide> if (customHmrEventHandler) {
<ide> customHmrEventHandler(obj) | 1 |
Javascript | Javascript | fix clear color bug | 6161ab5733c23e7a7d77c97d093d6bbfa31cdc53 | <ide><path>src/renderers/webgl/WebGLState.js
<ide> function WebGLState( gl, extensions, paramThreeToGL ) {
<ide>
<ide> var color = new Vector4();
<ide> var currentColorMask = null;
<del> var currentColorClear = new Vector4();
<add> var currentColorClear = new Vector4( 0, 0, 0, 0 );
<ide>
<ide> return {
<ide>
<ide> function WebGLState( gl, extensions, paramThreeToGL ) {
<ide> locked = false;
<ide>
<ide> currentColorMask = null;
<del> currentColorClear.set( 0, 0, 0, 1 );
<add> currentColorClear.set( - 1, 0, 0, 0 );
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | improve test coverage in perf_hooks | 3826d692cc60cf8a7ea6dc48b425fd75dcc697df | <ide><path>test/parallel/test-http2-perf_hooks.js
<ide> const obs = new PerformanceObserver(common.mustCall((items) => {
<ide> assert.fail('invalid entry name');
<ide> }
<ide> }, 4));
<add>
<add>// Should throw if entryTypes are not valid
<add>{
<add> const expectedError = { code: 'ERR_VALID_PERFORMANCE_ENTRY_TYPE' };
<add> const wrongEntryTypes = { entryTypes: ['foo', 'bar', 'baz'] };
<add> assert.throws(() => obs.observe(wrongEntryTypes), expectedError);
<add>}
<add>
<ide> obs.observe({ entryTypes: ['http2'] });
<ide>
<ide> const body = | 1 |
Javascript | Javascript | introduce react native cli | 833ca598bc7553cd60080705da076454ab5c544b | <ide><path>packager/parseCommandLine.js
<ide>
<ide> var optimist = require('optimist');
<ide>
<del>function parseCommandLine(config) {
<add>function parseCommandLine(config, args) {
<add> args = args || process.argv;
<ide> // optimist default API requires you to write the command name three time
<ide> // This is a small wrapper to accept an object instead
<ide> for (var i = 0; i < config.length; ++i) {
<ide> function parseCommandLine(config) {
<ide> optimist.demand(config[i].command);
<ide> }
<ide> }
<del> var argv = optimist.parse(process.argv);
<add> var argv = optimist.parse(args);
<ide>
<ide> // optimist doesn't have support for --dev=false, instead it returns 'false'
<ide> for (var i = 0; i < config.length; ++i) {
<ide><path>private-cli/index.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>require('babel-core/register')({
<add> only: [
<add> /react-native-github\/private-cli\/src/
<add> ],
<add>});
<add>
<add>var cli = require('./src/cli');
<add>var fs = require('fs');
<add>var gracefulFs = require('graceful-fs');
<add>
<add>// graceful-fs helps on getting an error when we run out of file
<add>// descriptors. When that happens it will enqueue the operation and retry it.
<add>gracefulFs.gracefulify(fs);
<add>
<add>module.exports = cli;
<ide><path>private-cli/src/cli.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const Config = require('./util/Config');
<add>const dependencies = require('./dependencies/dependencies');
<add>const Promise = require('promise');
<add>
<add>const documentedCommands = {
<add> dependencies: dependencies,
<add>};
<add>
<add>const hiddenCommands = {
<add> '-h': help,
<add> '--help': help,
<add>};
<add>
<add>/**
<add> * Programmatic entry point for the cli. This function runs the given
<add> * command passing it the arguments array.
<add> */
<add>function run(command, commandArgs) {
<add> if (!command) {
<add> throw new Error(helpMessage());
<add> }
<add> commandArgs = commandArgs || [];
<add>
<add> const commandToExec = documentedCommands[command] || hiddenCommands[command];
<add> if (!commandToExec) {
<add> throw new Error(helpMessage(command));
<add> }
<add>
<add> commandToExec(commandArgs, Config.get()).done();
<add>}
<add>
<add>function helpMessage(command) {
<add> const validCommands = Object
<add> .keys(documentedCommands)
<add> .map(c => '"' + c + '"')
<add> .join(' | ');
<add>
<add> if (command) {
<add> return 'Unknown command "' + command + '". ' +
<add> 'Available commands: ' + validCommands;
<add> } else {
<add> return 'Must specify a command. Available commands: ' +
<add> validCommands;
<add> }
<add>}
<add>
<add>function help() {
<add> console.log(helpMessage());
<add> return Promise.resolve();
<add>}
<add>
<add>module.exports.run = run;
<ide><path>private-cli/src/dependencies/dependencies.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const fs = require('fs');
<add>const log = require('../util/log').out('dependencies');
<add>const parseCommandLine = require('../../../packager/parseCommandLine');
<add>const path = require('path');
<add>const Promise = require('Promise');
<add>const ReactPackager = require('../../../packager/react-packager');
<add>
<add>/**
<add> * Returns the dependencies an entry path has.
<add> */
<add>function dependencies(argv, conf) {
<add> return new Promise((resolve, reject) => {
<add> _dependencies(argv, conf, resolve, reject);
<add> });
<add>}
<add>
<add>function _dependencies(argv, conf, resolve, reject) {
<add> const args = parseCommandLine([
<add> {
<add> command: 'entry-file',
<add> description: 'Absolute path to the root JS file',
<add> type: 'string',
<add> required: true,
<add> }, {
<add> command: 'output',
<add> description: 'File name where to store the output, ex. /tmp/dependencies.txt',
<add> type: 'string',
<add> }
<add> ], argv);
<add>
<add> const rootModuleAbsolutePath = args['entry-file'];
<add> if (!fs.existsSync(rootModuleAbsolutePath)) {
<add> reject(`File ${rootModuleAbsolutePath} does not exist`);
<add> }
<add>
<add> const config = {
<add> projectRoots: conf.getProjectRoots(),
<add> assetRoots: conf.getAssetRoots(),
<add> blacklistRE: conf.getBlacklistRE(),
<add> transformModulePath: conf.getTransformModulePath(),
<add> };
<add>
<add> const relativePath = config.projectRoots.map(root =>
<add> path.relative(
<add> root,
<add> rootModuleAbsolutePath
<add> )
<add> )[0];
<add>
<add> const writeToFile = args.output;
<add> const outStream = writeToFile
<add> ? fs.createWriteStream(args.output)
<add> : process.stdout;
<add>
<add> log('Running ReactPackager');
<add> log('Waiting for the packager.');
<add> resolve(ReactPackager.createClientFor(config).then(client => {
<add> log('Packager client was created');
<add> return client.getDependencies(relativePath)
<add> .then(deps => {
<add> log('Packager returned dependencies');
<add> client.close();
<add>
<add> deps.forEach(module => {
<add> // Temporary hack to disable listing dependencies not under this directory.
<add> // Long term, we need either
<add> // (a) JS code to not depend on anything outside this directory, or
<add> // (b) Come up with a way to declare this dependency in Buck.
<add> const isInsideProjectRoots = config.projectRoots.filter(root =>
<add> module.path.startsWith(root)
<add> ).length > 0;
<add>
<add> if (isInsideProjectRoots) {
<add> outStream.write(module.path + '\n');
<add> }
<add> });
<add> writeToFile && outStream.end();
<add> log('Wrote dependencies to output file');
<add> });
<add> }));
<add>}
<add>
<add>module.exports = dependencies;
<ide><path>private-cli/src/util/Config.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const fs = require('fs');
<add>const path = require('path');
<add>
<add>const RN_CLI_CONFIG = 'rn-cli.config.js';
<add>let cachedConfig = null;
<add>
<add>/**
<add> * Module capable of getting the configuration that should be used for
<add> * the `rn-cli`. The configuration file is a JS file named `rn-cli.conf.js`.
<add> * It has to be on any parent directory of the cli.
<add> */
<add>const Config = {
<add> get() {
<add> if (cachedConfig) {
<add> return cachedConfig;
<add> }
<add>
<add> const parentDir = findParentDirectory(__dirname, RN_CLI_CONFIG);
<add>
<add> if (!parentDir) {
<add> throw new Error(
<add> 'Can\'t find "rn-cli.config.js" file in any parent folder of "' +
<add> __dirname + '"'
<add> );
<add> }
<add>
<add> cachedConfig = require(path.join(parentDir, RN_CLI_CONFIG));
<add> return cachedConfig;
<add> }
<add>};
<add>
<add>// Finds the most near ancestor starting at `currentFullPath` that has
<add>// a file named `filename`
<add>function findParentDirectory(currentFullPath, filename) {
<add> const root = path.parse(currentFullPath).root;
<add> const testDir = (parts) => {
<add> if (parts.length === 0) {
<add> return null;
<add> }
<add>
<add> const fullPath = path.join(root, parts.join(path.sep));
<add>
<add> var exists = fs.existsSync(path.join(fullPath, filename));
<add> return exists ? fullPath : testDir(parts.slice(0, -1));
<add> };
<add>
<add> return testDir(currentFullPath.substring(1).split(path.sep));
<add>}
<add>
<add>module.exports = Config;
<ide><path>private-cli/src/util/__mocks__/log.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>module.exports.out = () => jest.genMockFn();
<add>module.exports.err = () => jest.genMockFn();
<ide><path>private-cli/src/util/log.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>function log(stream, module) {
<add> return function() {
<add> const message = Array.prototype.slice.call(arguments).join(' ');
<add> stream.write(module + ': ' + message + '\n');
<add> };
<add>}
<add>
<add>module.exports.out = log.bind(null, process.stdout);
<add>module.exports.err = log.bind(null, process.stderr); | 7 |
Javascript | Javascript | fix typo getnormalvector() -> gettangent() | fab25f9fea0cc3739c0de6b11399134ff325696a | <ide><path>src/extras/core/CurvePath.js
<ide> THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
<ide> // check for out of bounds?
<ide>
<ide> var pathPt = path.getPoint( xNorm );
<del> var normal = path.getNormalVector( xNorm );
<add> var normal = path.getTangent( xNorm );
<ide> normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
<ide>
<ide> p.x = pathPt.x + normal.x; | 1 |
PHP | PHP | add hints to database/driver & dialect | fe7765dfe66f8e638e5d767dc0e2a8d8491c147f | <ide><path>src/Database/Dialect/MysqlDialectTrait.php
<ide> public function schemaDialect()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function disableForeignKeySQL()
<add> public function disableForeignKeySQL(): string
<ide> {
<ide> return 'SET foreign_key_checks = 0';
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function enableForeignKeySQL()
<add> public function enableForeignKeySQL(): string
<ide> {
<ide> return 'SET foreign_key_checks = 1';
<ide> }
<ide><path>src/Database/Dialect/PostgresDialectTrait.php
<ide> public function schemaDialect()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function disableForeignKeySQL()
<add> public function disableForeignKeySQL(): string
<ide> {
<ide> return 'SET CONSTRAINTS ALL DEFERRED';
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function enableForeignKeySQL()
<add> public function enableForeignKeySQL(): string
<ide> {
<ide> return 'SET CONSTRAINTS ALL IMMEDIATE';
<ide> }
<ide><path>src/Database/Dialect/SqliteDialectTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function schemaDialect()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function disableForeignKeySQL()
<add> public function disableForeignKeySQL(): string
<ide> {
<ide> return 'PRAGMA foreign_keys = OFF';
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function enableForeignKeySQL()
<add> public function enableForeignKeySQL(): string
<ide> {
<ide> return 'PRAGMA foreign_keys = ON';
<ide> }
<ide><path>src/Database/Dialect/SqlserverDialectTrait.php
<ide> public function schemaDialect()
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function savePointSQL($name)
<add> public function savePointSQL(string $name): string
<ide> {
<ide> return 'SAVE TRANSACTION t' . $name;
<ide> }
<ide> public function savePointSQL($name)
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function releaseSavePointSQL($name)
<add> public function releaseSavePointSQL(string $name): string
<ide> {
<ide> return 'COMMIT TRANSACTION t' . $name;
<ide> }
<ide> public function releaseSavePointSQL($name)
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function rollbackSavePointSQL($name)
<add> public function rollbackSavePointSQL(string $name): string
<ide> {
<ide> return 'ROLLBACK TRANSACTION t' . $name;
<ide> }
<ide> public function newCompiler()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function disableForeignKeySQL()
<add> public function disableForeignKeySQL(): string
<ide> {
<ide> return 'EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"';
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function enableForeignKeySQL()
<add> public function enableForeignKeySQL(): string
<ide> {
<ide> return 'EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"';
<ide> }
<ide><path>src/Database/Driver.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> protected function _connect($dsn, array $config)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function connect();
<add> abstract public function connect(): bool;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function disconnect()
<add> public function disconnect(): void
<ide> {
<ide> $this->_connection = null;
<ide> }
<ide> public function setConnection($connection)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function enabled();
<add> abstract public function enabled(): bool;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function prepare($query)
<add> public function prepare($query): StatementInterface
<ide> {
<ide> $this->connect();
<ide> $isObject = $query instanceof Query;
<ide> public function prepare($query)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function beginTransaction()
<add> public function beginTransaction(): bool
<ide> {
<ide> $this->connect();
<ide> if ($this->_connection->inTransaction()) {
<ide> public function beginTransaction()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function commitTransaction()
<add> public function commitTransaction(): bool
<ide> {
<ide> $this->connect();
<ide> if (!$this->_connection->inTransaction()) {
<ide> public function commitTransaction()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function rollbackTransaction()
<add> public function rollbackTransaction(): bool
<ide> {
<ide> $this->connect();
<ide> if (!$this->_connection->inTransaction()) {
<ide> public function rollbackTransaction()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function releaseSavePointSQL($name);
<add> abstract public function releaseSavePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function savePointSQL($name);
<add> abstract public function savePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function rollbackSavePointSQL($name);
<add> abstract public function rollbackSavePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function disableForeignKeySQL();
<add> abstract public function disableForeignKeySQL(): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function enableForeignKeySQL();
<add> abstract public function enableForeignKeySQL(): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function supportsDynamicConstraints();
<add> abstract public function supportsDynamicConstraints(): bool;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function supportsSavePoints()
<add> public function supportsSavePoints(): bool
<ide> {
<ide> return true;
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function quote($value, $type)
<add> public function quote($value, $type): string
<ide> {
<ide> $this->connect();
<ide>
<ide> public function quote($value, $type)
<ide> *
<ide> * @return bool
<ide> */
<del> public function supportsQuoting()
<add> public function supportsQuoting(): bool
<ide> {
<ide> $this->connect();
<ide>
<ide> abstract public function schemaDialect();
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> abstract public function quoteIdentifier($identifier);
<add> abstract public function quoteIdentifier(string $identifier): string;
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function schemaValue($value)
<add> public function schemaValue($value): string
<ide> {
<ide> if ($value === null) {
<ide> return 'NULL';
<ide> public function schemaValue($value)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function schema()
<add> public function schema(): string
<ide> {
<ide> return $this->_config['schema'];
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function lastInsertId($table = null, $column = null)
<add> public function lastInsertId(?string $table = null, ?string $column = null)
<ide> {
<ide> $this->connect();
<ide>
<ide> public function lastInsertId($table = null, $column = null)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function isConnected()
<add> public function isConnected(): bool
<ide> {
<ide> if ($this->_connection === null) {
<ide> $connected = false;
<ide> public function isConnected()
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function enableAutoQuoting($enable = true)
<add> public function enableAutoQuoting(bool $enable = true): DriverInterface
<ide> {
<ide> $this->_autoQuoting = (bool)$enable;
<ide>
<ide> public function enableAutoQuoting($enable = true)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function isAutoQuotingEnabled()
<add> public function isAutoQuotingEnabled(): bool
<ide> {
<ide> return $this->_autoQuoting;
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function compileQuery(Query $query, ValueBinder $generator)
<add> public function compileQuery(Query $query, ValueBinder $generator): array
<ide> {
<ide> $processor = $this->newCompiler();
<ide> $translator = $this->queryTranslator($query->type());
<ide><path>src/Database/Driver/Mysql.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Query;
<ide> use Cake\Database\Statement\MysqlStatement;
<add>use Cake\Database\StatementInterface;
<ide> use PDO;
<ide>
<ide> /**
<ide> class Mysql extends Driver
<ide> *
<ide> * @return bool true on success
<ide> */
<del> public function connect()
<add> public function connect(): bool
<ide> {
<ide> if ($this->_connection) {
<ide> return true;
<ide> public function connect()
<ide> *
<ide> * @return bool true if it is valid to use this driver
<ide> */
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return in_array('mysql', PDO::getAvailableDrivers());
<ide> }
<ide> public function enabled()
<ide> * @param string|\Cake\Database\Query $query The query to prepare.
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<del> public function prepare($query)
<add> public function prepare($query): StatementInterface
<ide> {
<ide> $this->connect();
<ide> $isObject = $query instanceof Query;
<ide> public function prepare($query)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function schema()
<add> public function schema(): string
<ide> {
<ide> return $this->_config['database'];
<ide> }
<ide>
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function supportsDynamicConstraints()
<add> public function supportsDynamicConstraints(): bool
<ide> {
<ide> return true;
<ide> }
<ide> public function supportsDynamicConstraints()
<ide> *
<ide> * @return bool
<ide> */
<del> public function supportsNativeJson()
<add> public function supportsNativeJson(): bool
<ide> {
<ide> if ($this->_supportsNativeJson !== null) {
<ide> return $this->_supportsNativeJson;
<ide> }
<ide>
<ide> if ($this->_version === null) {
<del> $this->_version = $this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
<add> $this->_version = (string)$this->_connection->getAttribute(PDO::ATTR_SERVER_VERSION);
<ide> }
<ide>
<ide> return $this->_supportsNativeJson = version_compare($this->_version, '5.7.0', '>=');
<ide><path>src/Database/Driver/Postgres.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class Postgres extends Driver
<ide> *
<ide> * @return bool true on success
<ide> */
<del> public function connect()
<add> public function connect(): bool
<ide> {
<ide> if ($this->_connection) {
<ide> return true;
<ide> public function connect()
<ide> *
<ide> * @return bool true if it is valid to use this driver
<ide> */
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return in_array('pgsql', PDO::getAvailableDrivers());
<ide> }
<ide> public function enabled()
<ide> * @param string $encoding The encoding to use.
<ide> * @return void
<ide> */
<del> public function setEncoding($encoding)
<add> public function setEncoding(string $encoding): void
<ide> {
<ide> $this->connect();
<ide> $this->_connection->exec('SET NAMES ' . $this->_connection->quote($encoding));
<ide> public function setEncoding($encoding)
<ide> * @param string $schema The schema names to set `search_path` to.
<ide> * @return void
<ide> */
<del> public function setSchema($schema)
<add> public function setSchema(string $schema): void
<ide> {
<ide> $this->connect();
<ide> $this->_connection->exec('SET search_path TO ' . $this->_connection->quote($schema));
<ide> public function setSchema($schema)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function supportsDynamicConstraints()
<add> public function supportsDynamicConstraints(): bool
<ide> {
<ide> return true;
<ide> }
<ide><path>src/Database/Driver/Sqlite.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Database\Dialect\SqliteDialectTrait;
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Query;
<add>use Cake\Database\StatementInterface;
<ide> use Cake\Database\Statement\PDOStatement;
<ide> use Cake\Database\Statement\SqliteStatement;
<ide> use PDO;
<ide> class Sqlite extends Driver
<ide> *
<ide> * @return bool true on success
<ide> */
<del> public function connect()
<add> public function connect(): bool
<ide> {
<ide> if ($this->_connection) {
<ide> return true;
<ide> public function connect()
<ide> *
<ide> * @return bool true if it is valid to use this driver
<ide> */
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return in_array('sqlite', PDO::getAvailableDrivers());
<ide> }
<ide> public function enabled()
<ide> * @param string|\Cake\Database\Query $query The query to prepare.
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<del> public function prepare($query)
<add> public function prepare($query): StatementInterface
<ide> {
<ide> $this->connect();
<ide> $isObject = $query instanceof Query;
<ide> public function prepare($query)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function supportsDynamicConstraints()
<add> public function supportsDynamicConstraints(): bool
<ide> {
<ide> return false;
<ide> }
<ide><path>src/Database/Driver/Sqlserver.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Database\Dialect\SqlserverDialectTrait;
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Query;
<add>use Cake\Database\StatementInterface;
<ide> use Cake\Database\Statement\SqlserverStatement;
<ide> use PDO;
<ide>
<ide> class Sqlserver extends Driver
<ide> * @throws \InvalidArgumentException if an unsupported setting is in the driver config
<ide> * @return bool true on success
<ide> */
<del> public function connect()
<add> public function connect(): bool
<ide> {
<ide> if ($this->_connection) {
<ide> return true;
<ide> public function connect()
<ide> $config['flags'][PDO::SQLSRV_ATTR_ENCODING] = $config['encoding'];
<ide> }
<ide> $port = '';
<del> if (strlen($config['port'])) {
<add> if ($config['port']) {
<ide> $port = ',' . $config['port'];
<ide> }
<ide>
<ide> public function connect()
<ide> *
<ide> * @return bool true if it is valid to use this driver
<ide> */
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return in_array('sqlsrv', PDO::getAvailableDrivers());
<ide> }
<ide> public function enabled()
<ide> * @param string|\Cake\Database\Query $query The query to prepare.
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<del> public function prepare($query)
<add> public function prepare($query): StatementInterface
<ide> {
<ide> $this->connect();
<ide> $options = [PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL];
<ide> public function prepare($query)
<ide> /**
<ide> * {@inheritDoc}
<ide> */
<del> public function supportsDynamicConstraints()
<add> public function supportsDynamicConstraints(): bool
<ide> {
<ide> return true;
<ide> }
<ide><path>src/Database/DriverInterface.php
<ide> interface DriverInterface
<ide> *
<ide> * @return bool True on success, false on failure.
<ide> */
<del> public function connect();
<add> public function connect(): bool;
<ide>
<ide> /**
<ide> * Disconnects from database server.
<ide> *
<ide> * @return void
<ide> */
<del> public function disconnect();
<add> public function disconnect(): void;
<ide>
<ide> /**
<ide> * Returns correct connection resource or object that is internally used.
<ide> public function setConnection($connection);
<ide> *
<ide> * @return bool True if it is valid to use this driver.
<ide> */
<del> public function enabled();
<add> public function enabled(): bool;
<ide>
<ide> /**
<ide> * Prepares a sql statement to be executed.
<ide> *
<ide> * @param string|\Cake\Database\Query $query The query to turn into a prepared statement.
<ide> * @return \Cake\Database\StatementInterface
<ide> */
<del> public function prepare($query);
<add> public function prepare($query): StatementInterface;
<ide>
<ide> /**
<ide> * Starts a transaction.
<ide> *
<ide> * @return bool True on success, false otherwise.
<ide> */
<del> public function beginTransaction();
<add> public function beginTransaction(): bool;
<ide>
<ide> /**
<ide> * Commits a transaction.
<ide> *
<ide> * @return bool True on success, false otherwise.
<ide> */
<del> public function commitTransaction();
<add> public function commitTransaction(): bool;
<ide>
<ide> /**
<ide> * Rollbacks a transaction.
<ide> *
<ide> * @return bool True on success, false otherwise.
<ide> */
<del> public function rollbackTransaction();
<add> public function rollbackTransaction(): bool;
<ide>
<ide> /**
<ide> * Get the SQL for releasing a save point.
<ide> *
<ide> * @param string $name The table name.
<ide> * @return string
<ide> */
<del> public function releaseSavePointSQL($name);
<add> public function releaseSavePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * Get the SQL for creating a save point.
<ide> *
<ide> * @param string $name The table name.
<ide> * @return string
<ide> */
<del> public function savePointSQL($name);
<add> public function savePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * Get the SQL for rollingback a save point.
<ide> *
<ide> * @param string $name The table name.
<ide> * @return string
<ide> */
<del> public function rollbackSavePointSQL($name);
<add> public function rollbackSavePointSQL(string $name): string;
<ide>
<ide> /**
<ide> * Get the SQL for disabling foreign keys.
<ide> *
<ide> * @return string
<ide> */
<del> public function disableForeignKeySQL();
<add> public function disableForeignKeySQL(): string;
<ide>
<ide> /**
<ide> * Get the SQL for enabling foreign keys.
<ide> *
<ide> * @return string
<ide> */
<del> public function enableForeignKeySQL();
<add> public function enableForeignKeySQL(): string;
<ide>
<ide> /**
<ide> * Returns whether the driver supports adding or dropping constraints
<ide> * to already created tables.
<ide> *
<ide> * @return bool true if driver supports dynamic constraints.
<ide> */
<del> public function supportsDynamicConstraints();
<add> public function supportsDynamicConstraints(): bool;
<ide>
<ide> /**
<ide> * Returns whether this driver supports save points for nested transactions.
<ide> *
<ide> * @return bool True if save points are supported, false otherwise.
<ide> */
<del> public function supportsSavePoints();
<add> public function supportsSavePoints(): bool;
<ide>
<ide> /**
<ide> * Returns a value in a safe representation to be used in a query string
<ide> *
<ide> * @param mixed $value The value to quote.
<del> * @param string $type Type to be used for determining kind of quoting to perform.
<add> * @param string|int $type Type to be used for determining kind of quoting to perform.
<ide> * @return string
<ide> */
<del> public function quote($value, $type);
<add> public function quote($value, $type): string;
<ide>
<ide> /**
<ide> * Checks if the driver supports quoting.
<ide> *
<ide> * @return bool
<ide> */
<del> public function supportsQuoting();
<add> public function supportsQuoting(): bool;
<ide>
<ide> /**
<ide> * Returns a callable function that will be used to transform a passed Query object.
<ide> public function supportsQuoting();
<ide> * (select, insert, update, delete).
<ide> * @return callable
<ide> */
<del> public function queryTranslator($type);
<add> public function queryTranslator(string $type);
<ide>
<ide> /**
<ide> * Get the schema dialect.
<ide> public function schemaDialect();
<ide> * @param string $identifier The identifier expression to quote.
<ide> * @return string
<ide> */
<del> public function quoteIdentifier($identifier);
<add> public function quoteIdentifier(string $identifier): string;
<ide>
<ide> /**
<ide> * Escapes values for use in schema definitions.
<ide> *
<ide> * @param mixed $value The value to escape.
<ide> * @return string String for use in schema definitions.
<ide> */
<del> public function schemaValue($value);
<add> public function schemaValue($value): string;
<ide>
<ide> /**
<ide> * Returns the schema name that's being used.
<ide> *
<ide> * @return string
<ide> */
<del> public function schema();
<add> public function schema(): string;
<ide>
<ide> /**
<ide> * Returns last id generated for a table or sequence in database.
<ide> public function schema();
<ide> * @param string|null $column the name of the column representing the primary key.
<ide> * @return string|int
<ide> */
<del> public function lastInsertId($table = null, $column = null);
<add> public function lastInsertId(?string $table = null, ?string $column = null);
<ide>
<ide> /**
<ide> * Checks whether or not the driver is connected.
<ide> *
<ide> * @return bool
<ide> */
<del> public function isConnected();
<add> public function isConnected(): bool;
<ide>
<ide> /**
<ide> * Sets whether or not this driver should automatically quote identifiers
<ide> public function isConnected();
<ide> * @param bool $enable Whether to enable auto quoting
<ide> * @return $this
<ide> */
<del> public function enableAutoQuoting($enable = true);
<add> public function enableAutoQuoting(bool $enable = true): self;
<ide>
<ide> /**
<ide> * Returns whether or not this driver should automatically quote identifiers
<ide> * in queries.
<ide> *
<ide> * @return bool
<ide> */
<del> public function isAutoQuotingEnabled();
<add> public function isAutoQuotingEnabled(): bool;
<ide>
<ide> /**
<ide> * Transforms the passed query to this Driver's dialect and returns an instance
<ide> public function isAutoQuotingEnabled();
<ide> * @return array containing 2 entries. The first entity is the transformed query
<ide> * and the second one the compiled SQL.
<ide> */
<del> public function compileQuery(Query $query, ValueBinder $generator);
<add> public function compileQuery(Query $query, ValueBinder $generator): array;
<ide>
<ide> /**
<ide> * Returns an instance of a QueryCompiler.
<ide><path>src/Database/SqlDialectTrait.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> trait SqlDialectTrait
<ide> * @param string $identifier The identifier to quote.
<ide> * @return string
<ide> */
<del> public function quoteIdentifier($identifier)
<add> public function quoteIdentifier(string $identifier): string
<ide> {
<ide> $identifier = trim($identifier);
<ide>
<ide> protected function _insertQueryTranslator($query)
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function savePointSQL($name)
<add> public function savePointSQL(string $name): string
<ide> {
<ide> return 'SAVEPOINT LEVEL' . $name;
<ide> }
<ide> public function savePointSQL($name)
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function releaseSavePointSQL($name)
<add> public function releaseSavePointSQL(string $name): string
<ide> {
<ide> return 'RELEASE SAVEPOINT LEVEL' . $name;
<ide> }
<ide> public function releaseSavePointSQL($name)
<ide> * @param string $name save point name
<ide> * @return string
<ide> */
<del> public function rollbackSavePointSQL($name)
<add> public function rollbackSavePointSQL(string $name): string
<ide> {
<ide> return 'ROLLBACK TO SAVEPOINT LEVEL' . $name;
<ide> }
<ide><path>tests/TestCase/Database/Driver/MysqlTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Driver/PostgresTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Driver/SqliteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/Driver/SqlserverTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Database/DriverTest.php
<ide> public function testSchemaValueConnectionQuoting()
<ide> $connection
<ide> ->expects($this->once())
<ide> ->method('quote')
<del> ->with($value, PDO::PARAM_STR);
<add> ->with($value, PDO::PARAM_STR)
<add> ->will($this->returnValue('string'));
<ide>
<ide> $this->driver->setConnection($connection);
<del>
<ide> $this->driver->schemaValue($value);
<ide> }
<ide>
<ide><path>tests/test_app/Plugin/TestPlugin/src/Database/Driver/TestDriver.php
<ide>
<ide> class TestDriver extends Sqlite
<ide> {
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return true;
<ide> }
<ide><path>tests/test_app/TestApp/Database/Driver/TestDriver.php
<ide>
<ide> class TestDriver extends Sqlite
<ide> {
<del> public function enabled()
<add> public function enabled(): bool
<ide> {
<ide> return true;
<ide> } | 18 |
Ruby | Ruby | improve use of default_prefix? in tests | 234e4aec96297145e1760bc3d8ff6cc9f6f64713 | <ide><path>Library/Homebrew/os/linux/global.rb
<ide> module Homebrew
<del> DEFAULT_PREFIX = if ENV["HOMEBREW_FORCE_HOMEBREW_ON_LINUX"]
<add> DEFAULT_PREFIX ||= if ENV["HOMEBREW_FORCE_HOMEBREW_ON_LINUX"]
<ide> "/usr/local".freeze
<ide> else
<ide> "/home/linuxbrew/.linuxbrew".freeze
<ide><path>Library/Homebrew/test/diagnostic_checks_spec.rb
<ide> end
<ide>
<ide> specify "#check_homebrew_prefix" do
<del> # the integration tests are run in a special prefix
<add> allow(Homebrew).to receive(:default_prefix?).and_return(false)
<ide> expect(subject.check_homebrew_prefix)
<ide> .to match("Your Homebrew's prefix is not #{Homebrew::DEFAULT_PREFIX}")
<ide> end
<ide><path>Library/Homebrew/test/support/lib/config.rb
<ide>
<ide> TEST_SHA1 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<ide> TEST_SHA256 = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".freeze
<add>
<add># For testing's sake always assume the default prefix
<add>module Homebrew
<add> DEFAULT_PREFIX = HOMEBREW_PREFIX.to_s.freeze
<add>end
<ide><path>Library/Homebrew/test/utils/analytics_spec.rb
<ide> end
<ide>
<ide> it "returns OS_VERSION and prefix when HOMEBREW_PREFIX is a custom prefix" do
<del> stub_const("HOMEBREW_PREFIX", "blah")
<add> allow(Homebrew).to receive(:default_prefix?).and_return(false)
<ide> expect(described_class.os_prefix_ci).to include("#{OS_VERSION}, #{described_class.custom_prefix_label}")
<ide> end
<ide>
<add> it "does not include prefix when HOMEBREW_PREFIX is the default prefix" do
<add> expect(described_class.os_prefix_ci).not_to include(described_class.custom_prefix_label)
<add> end
<add>
<ide> it "includes CI when ENV['CI'] is set" do
<ide> ENV["CI"] = "true"
<ide> expect(described_class.os_prefix_ci).to include("CI")
<ide> end
<del>
<del> it "does not include prefix when HOMEBREW_PREFIX is the default prefix" do
<del> stub_const("HOMEBREW_PREFIX", Homebrew::DEFAULT_PREFIX)
<del> expect(described_class.os_prefix_ci).not_to include(described_class.custom_prefix_label)
<del> end
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/utils/analytics.rb
<ide> def clear_os_prefix_ci
<ide> def os_prefix_ci
<ide> @os_prefix_ci ||= begin
<ide> os = OS_VERSION
<del> prefix = ", #{custom_prefix_label}" if Homebrew.default_prefix?
<add> prefix = ", #{custom_prefix_label}" unless Homebrew.default_prefix?
<ide> ci = ", CI" if ENV["CI"]
<ide> "#{os}#{prefix}#{ci}"
<ide> end | 5 |
Javascript | Javascript | fix voxel diagram | b4910892bfa32c0fdc25d72d1336d8b34aec8fe1 | <ide><path>threejs/lessons/resources/threejs-voxel-geometry.js
<ide> import {threejsLessonUtils} from './threejs-lesson-utils.js';
<ide> wire: '#DDD',
<ide> };
<ide> const lightColors = {
<del> wore: '#000',
<add> wire: '#000',
<ide> };
<ide> const colors = isDarkMode ? darkColors : lightColors;
<ide> | 1 |
Ruby | Ruby | fix typo in test desctiption [skip ci] | 7d74b73a066c3e996787ca021c5bbf21d8d0749e | <ide><path>actionpack/test/controller/http_basic_authentication_test.rb
<ide> def test_encode_credentials_has_no_newline
<ide> assert_no_match(/\n/, result)
<ide> end
<ide>
<del> test "succesful authentication with uppercase authorization scheme" do
<add> test "successful authentication with uppercase authorization scheme" do
<ide> @request.env['HTTP_AUTHORIZATION'] = "BASIC #{::Base64.encode64("lifo:world")}"
<ide> get :index
<ide> | 1 |
Java | Java | avoid deprecated comparators in tests | 9543384d9e3b7c51aa997a47b3758a0284ff72d4 | <ide><path>spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.beans.support;
<ide>
<del>import org.junit.Test;
<add>import java.util.Comparator;
<ide>
<del>import org.springframework.util.comparator.CompoundComparator;
<add>import org.junit.Test;
<ide>
<ide> import static org.junit.Assert.*;
<ide>
<ide> /**
<del> * Unit tests for {@link PropertyComparator}
<del> *
<del> * @see org.springframework.util.comparator.ComparatorTests
<add> * Unit tests for {@link PropertyComparator}.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Chris Beams
<ide> public void testPropertyComparator() {
<ide> Dog dog2 = new Dog();
<ide> dog2.setNickName("biscy");
<ide>
<del> PropertyComparator c = new PropertyComparator("nickName", false, true);
<add> PropertyComparator<Dog> c = new PropertyComparator<>("nickName", false, true);
<ide> assertTrue(c.compare(dog, dog2) > 0);
<ide> assertTrue(c.compare(dog, dog) == 0);
<ide> assertTrue(c.compare(dog2, dog) < 0);
<ide> public void testPropertyComparator() {
<ide> public void testPropertyComparatorNulls() {
<ide> Dog dog = new Dog();
<ide> Dog dog2 = new Dog();
<del> PropertyComparator c = new PropertyComparator("nickName", false, true);
<add> PropertyComparator<Dog> c = new PropertyComparator<>("nickName", false, true);
<ide> assertTrue(c.compare(dog, dog2) == 0);
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> @Test
<ide> public void testCompoundComparator() {
<del> CompoundComparator<Dog> c = new CompoundComparator<>();
<del> c.addComparator(new PropertyComparator("lastName", false, true));
<add> Comparator<Dog> c = new PropertyComparator<>("lastName", false, true);
<ide>
<ide> Dog dog1 = new Dog();
<ide> dog1.setFirstName("macy");
<ide> public void testCompoundComparator() {
<ide>
<ide> assertTrue(c.compare(dog1, dog2) == 0);
<ide>
<del> c.addComparator(new PropertyComparator("firstName", false, true));
<add> c = c.thenComparing(new PropertyComparator<>("firstName", false, true));
<ide> assertTrue(c.compare(dog1, dog2) > 0);
<ide>
<ide> dog2.setLastName("konikk dog");
<ide> assertTrue(c.compare(dog2, dog1) > 0);
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> @Test
<ide> public void testCompoundComparatorInvert() {
<del> CompoundComparator<Dog> c = new CompoundComparator<>();
<del> c.addComparator(new PropertyComparator("lastName", false, true));
<del> c.addComparator(new PropertyComparator("firstName", false, true));
<add> Comparator<Dog> c = (new PropertyComparator<Dog>("lastName", false, true)).
<add> thenComparing(new PropertyComparator<>("firstName", false, true));
<ide> Dog dog1 = new Dog();
<ide> dog1.setFirstName("macy");
<ide> dog1.setLastName("grayspots");
<ide> public void testCompoundComparatorInvert() {
<ide> dog2.setLastName("grayspots");
<ide>
<ide> assertTrue(c.compare(dog1, dog2) > 0);
<del> c.invertOrder();
<add> c = c.reversed();
<ide> assertTrue(c.compare(dog1, dog2) < 0);
<ide> }
<ide>
<ide> private static class Dog implements Comparable<Object> {
<ide>
<ide> private String lastName;
<ide>
<del> @Override
<del> public int compareTo(Object o) {
<del> return nickName.compareTo(((Dog)o).nickName);
<del> }
<del>
<ide> public String getNickName() {
<ide> return nickName;
<ide> }
<ide> public String getLastName() {
<ide> public void setLastName(String lastName) {
<ide> this.lastName = lastName;
<ide> }
<add>
<add> @Override
<add> public int compareTo(Object o) {
<add> return this.nickName.compareTo(((Dog) o).nickName);
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/comparator/CompoundComparatorTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.junit.rules.ExpectedException;
<ide>
<ide> /**
<del> * Test for {@link ComparableComparator}.
<add> * Test for {@link CompoundComparator}.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Chris Beams
<ide> * @author Phillip Webb
<ide> */
<add>@Deprecated
<ide> public class CompoundComparatorTests {
<ide>
<ide> @Rule
<ide><path>spring-core/src/test/java/org/springframework/util/comparator/InvertibleComparatorTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> * @author Chris Beams
<ide> * @author Phillip Webb
<ide> */
<del>
<add>@Deprecated
<ide> public class InvertibleComparatorTests {
<ide>
<del> private Comparator<Integer> comparator = new ComparableComparator<>();
<add> private final Comparator<Integer> comparator = new ComparableComparator<>();
<add>
<ide>
<ide> @Test(expected = IllegalArgumentException.class)
<ide> public void shouldNeedComparator() throws Exception {
<ide> public void shouldNeedComparatorWithAscending() throws Exception {
<ide>
<ide> @Test
<ide> public void shouldDefaultToAscending() throws Exception {
<del> InvertibleComparator<Integer> invertibleComparator =
<del> new InvertibleComparator<>(comparator);
<add> InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator);
<ide> assertThat(invertibleComparator.isAscending(), is(true));
<ide> assertThat(invertibleComparator.compare(1, 2), is(-1));
<ide> }
<ide>
<ide> @Test
<ide> public void shouldInvert() throws Exception {
<del> InvertibleComparator<Integer> invertibleComparator =
<del> new InvertibleComparator<>(comparator);
<add> InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator);
<ide> assertThat(invertibleComparator.isAscending(), is(true));
<ide> assertThat(invertibleComparator.compare(1, 2), is(-1));
<ide> invertibleComparator.invertOrder();
<ide> public void shouldInvert() throws Exception {
<ide>
<ide> @Test
<ide> public void shouldCompareAscending() throws Exception {
<del> InvertibleComparator<Integer> invertibleComparator =
<del> new InvertibleComparator<>(comparator, true);
<add> InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator, true);
<ide> assertThat(invertibleComparator.compare(1, 2), is(-1));
<ide> }
<ide>
<ide> @Test
<ide> public void shouldCompareDescending() throws Exception {
<del> InvertibleComparator<Integer> invertibleComparator =
<del> new InvertibleComparator<>(comparator, false);
<add> InvertibleComparator<Integer> invertibleComparator = new InvertibleComparator<>(comparator, false);
<ide> assertThat(invertibleComparator.compare(1, 2), is(1));
<ide> }
<ide> | 3 |
Javascript | Javascript | improve an error message | 0fbe0a02df0a99c34c5b1e6abb92a450284cfca8 | <ide><path>test/parallel/test-cluster-master-kill.js
<ide> if (cluster.isWorker) {
<ide> }));
<ide>
<ide> process.once('exit', () => {
<del> assert.strictEqual(typeof pid, 'number', 'did not get worker pid info');
<add> assert.strictEqual(typeof pid, 'number',
<add> `got ${pid} instead of a worker pid`);
<ide> assert.strictEqual(alive, false, 'worker was alive after master died');
<ide> });
<ide> | 1 |
Java | Java | filter irrelevant nodes in staxhandler tests | 78b6ba05696ac48799f4ced6c909e971927e7fff | <ide><path>spring-core/src/test/java/org/springframework/util/xml/AbstractStaxHandlerTestCase.java
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import org.w3c.dom.Document;
<add>import org.w3c.dom.Node;
<ide> import org.xml.sax.InputSource;
<ide> import org.xml.sax.XMLReader;
<ide> import org.xml.sax.helpers.XMLReaderFactory;
<add>import org.xmlunit.util.Predicate;
<ide>
<ide> import javax.xml.parsers.DocumentBuilder;
<ide> import javax.xml.parsers.DocumentBuilderFactory;
<ide> public abstract class AbstractStaxHandlerTestCase {
<ide>
<ide> private XMLReader xmlReader;
<ide>
<add> private Predicate<Node> nodeFilter = n -> n.getNodeType() != Node.COMMENT_NODE
<add> && n.getNodeType() != Node.DOCUMENT_TYPE_NODE && n.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
<add>
<ide> @Before
<ide> public void createXMLReader() throws Exception {
<ide> xmlReader = XMLReaderFactory.createXMLReader();
<ide> public void noNamespacePrefixes() throws Exception {
<ide>
<ide> xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));
<ide>
<del> assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML));
<add> assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
<ide> }
<ide>
<ide> private static boolean wwwSpringframeworkOrgIsAccessible() {
<ide> public void namespacePrefixes() throws Exception {
<ide>
<ide> xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));
<ide>
<del> assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML));
<add> assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
<ide> }
<ide>
<ide> @Test
<ide> public void noNamespacePrefixesDom() throws Exception {
<ide>
<ide> xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));
<ide>
<del> assertThat(result, isSimilarTo(expected));
<add> assertThat(result, isSimilarTo(expected).withNodeFilter(nodeFilter));
<ide> }
<ide>
<ide> @Test
<ide> public void namespacePrefixesDom() throws Exception {
<ide>
<ide> xmlReader.parse(new InputSource(new StringReader(SIMPLE_XML)));
<ide>
<del> assertThat(expected, isSimilarTo(result));
<add> assertThat(expected, isSimilarTo(result).withNodeFilter(nodeFilter));
<ide> }
<ide>
<ide> | 1 |
Text | Text | add windows link to building doc | 445421f961e9b5642f383a9dfee432de0df39a75 | <ide><path>README.md
<ide> It will automatically update when a new release is available.
<ide> ### Requirements
<ide>
<ide> * Mountain Lion
<add> * Looking for Windows support? Read [here](https://github.com/atom/atom/blob/master/docs/building-atom.md).
<ide> * Boxen (Obviously Atom won't release with this requirement)
<ide>
<ide> ### Installation
<ide> It will automatically update when a new release is available.
<ide> 2. `cd ~/github/atom`
<ide>
<ide> 3. `script/build`
<add>
<add>
<add>[building] | 1 |
Python | Python | add ufsparse to the libraries search path | d91521e5fd858726998146e6055f677cc3aeb011 | <ide><path>numpy/distutils/system_info.py
<ide> def libpaths(paths,bits):
<ide> '/opt/local/lib','/sw/lib'], platform_bits)
<ide> default_include_dirs = ['/usr/local/include',
<ide> '/opt/include', '/usr/include',
<add> # path of umfpack under macports
<add> '/opt/local/include/ufsparse',
<ide> '/opt/local/include', '/sw/include',
<ide> '/usr/include/suitesparse']
<ide> default_src_dirs = ['.','/usr/local/src', '/opt/src','/sw/src'] | 1 |
PHP | PHP | check `validate` option before validating | 20334b3a2db3886a2de79331c6e565d3f478f5cc | <ide><path>src/ORM/Table.php
<ide> protected function _processSave($entity, $options) {
<ide> $associated = $options['associated'];
<ide> $options['associated'] = [];
<ide>
<del> if (!$this->validate($entity, $options)) {
<add> if ($options['validate'] && !$this->validate($entity, $options)) {
<ide> return false;
<ide> }
<ide> | 1 |
Python | Python | remove print statement | 808d8740d6ed4162256d5ea5dd182a7cf92688a5 | <ide><path>spacy/cli/train.py
<ide> def _render_parses(i, to_render):
<ide>
<ide>
<ide> def print_progress(itn, losses, dev_scores, cpu_wps=0.0, gpu_wps=0.0):
<del> print(locals())
<ide> scores = {}
<ide> for col in ['dep_loss', 'tag_loss', 'uas', 'tags_acc', 'token_acc',
<ide> 'ents_p', 'ents_r', 'ents_f', 'cpu_wps', 'gpu_wps']: | 1 |
Javascript | Javascript | fix handling of large timeouts | 0c47219a72fcf58c639ccb37ddf6b01b2261e793 | <ide><path>lib/timers.js
<ide> exports.active = function(item) {
<ide> exports.setTimeout = function(callback, after) {
<ide> var timer;
<ide>
<del> after = ~~after;
<del> if (after < 1 || after > TIMEOUT_MAX) {
<add> after *= 1; // coalesce to number or NaN
<add>
<add> if (!(after >= 1 && after <= TIMEOUT_MAX)) {
<ide> after = 1; // schedule on next tick, follows browser behaviour
<ide> }
<ide>
<ide> exports.setInterval = function(callback, repeat) {
<ide>
<ide> if (process.domain) timer.domain = process.domain;
<ide>
<del> repeat = ~~repeat;
<del> if (repeat < 1 || repeat > TIMEOUT_MAX) {
<add> repeat *= 1; // coalesce to number or NaN
<add>
<add> if (!(repeat >= 1 && repeat <= TIMEOUT_MAX)) {
<ide> repeat = 1; // schedule on next tick, follows browser behaviour
<ide> }
<ide>
<ide><path>test/simple/test-timers.js
<ide> var inputs = [
<ide> 1,
<ide> 1.0,
<ide> 10,
<del> 2147483648 // browser behaviour: timeouts > 2^31-1 run on next tick
<add> 2147483648, // browser behaviour: timeouts > 2^31-1 run on next tick
<add> 12345678901234 // ditto
<ide> ];
<ide>
<ide> var timeouts = []; | 2 |
Text | Text | add filter to /images/json docs | a20bf5e61c542fea377345d5318293b44c65cbb5 | <ide><path>docs/reference/api/docker_remote_api_v1.12.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide>
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.13.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Create an image
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.14.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Create an image
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.15.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Create an image
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.16.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Create an image
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.17.md
<ide> Query Parameters:
<ide> - **all** – 1/True/true or 0/False/false, default false
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Build image from a Dockerfile
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.18.md
<ide> Query Parameters:
<ide> - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - dangling=true
<ide> - label=`key` or `key=value` of an image label
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Build image from a Dockerfile
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.19.md
<ide> Query Parameters:
<ide> - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - `dangling=true`
<ide> - `label=key` or `key=value` of an image label
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Build image from a Dockerfile
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.20.md
<ide> Query Parameters:
<ide> - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Available filters:
<ide> - `dangling=true`
<ide> - `label=key` or `key=value` of an image label
<add>- **filter** - only return images with the specified name
<ide>
<ide> ### Build image from a Dockerfile
<ide> | 9 |
Text | Text | add missing semicolon to doc | b4072ba427be0d56910f9f8bcd5c5082d4a10ac7 | <ide><path>docs/basics/Actions.md
<ide> The `dispatch()` function can be accessed directly from the store as [`store.dis
<ide>
<ide> export const ADD_TODO = 'ADD_TODO';
<ide> export const COMPLETE_TODO = 'COMPLETE_TODO';
<del>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'
<add>export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
<ide>
<ide> /*
<ide> * other constants | 1 |
Python | Python | use pipeline for _set | 276753698a2d38a3c2b05af2ce22c13dffff738b | <ide><path>celery/backends/redis.py
<ide> def set(self, key, value, **retry_policy):
<ide> return self.ensure(self._set, (key, value), **retry_policy)
<ide>
<ide> def _set(self, key, value):
<del> client = self.client
<add> pipe = self.client.pipeline()
<ide> if self.expires:
<del> client.setex(key, value, self.expires)
<add> pipe.setex(key, value, self.expires)
<ide> else:
<del> client.set(key, value)
<del> client.publish(key, value)
<add> pipe.set(key, value)
<add> pipe.publish(key, value)
<add> pipe.execute()
<ide>
<ide> def delete(self, key):
<ide> self.client.delete(key) | 1 |
Python | Python | add some comments | 951ef735af7a190f2a0220c827e3aa2d9e9c07b9 | <ide><path>celery/buckets.py
<ide> def put(self, job):
<ide> put_nowait = put
<ide>
<ide> def _get(self):
<del> # If the first queue is always returning items, we would never
<del> # get to fetching items from the other queues.
<del> # So we always iterate over all the queues and put any ready
<del> # items on a queue called "immediate". This queue is always checked
<del> # for cached items first.
<add> # If the first bucket is always returning items, we would never
<add> # get to fetch items from the other buckets. So we always iterate over
<add> # all the buckets and put any ready items into a queue called
<add> # "immediate". This queue is always checked for cached items first.
<ide> if self.immediate:
<ide> try:
<ide> return 0, self.immediate.get_nowait()
<ide> except QueueEmpty:
<ide> pass
<ide>
<del> remainding_times = []
<del>
<add> remaining_times = []
<ide> for bucket in self.buckets.values():
<del> remainding = bucket.expected_time()
<del> if not remainding:
<add> remaining = bucket.expected_time()
<add> if not remaining:
<ide> try:
<add> # Just put any ready items into the immediate queue.
<ide> self.immediate.put_nowait(bucket.get_nowait())
<ide> except QueueEmpty:
<ide> pass
<ide> else:
<del> remainding_times.append(remainding)
<add> remaining_times.append(remaining)
<ide>
<add> # Try the immediate queue again.
<ide> try:
<ide> return 0, self.immediate.get_nowait()
<ide> except QueueEmpty:
<del> if not remainding_times:
<add> if not remaining_times:
<add> # No items in any of the buckets.
<ide> raise
<del> return min(remainding_times), None
<add>
<add> # There's items, but have to wait before we can retrieve them,
<add> # return the shortest remaining time.
<add> return min(remaining_times), None
<ide>
<ide> def get(self, block=True, timeout=None):
<ide> """Retrive the task from the first available bucket.
<ide> def get(self, block=True, timeout=None):
<ide> did_timeout = lambda: timeout and time.time() - time_start > timeout
<ide>
<ide> while True:
<del> remainding_time, item = self._get()
<del> if remainding_time:
<add> remaining_time, item = self._get()
<add> if remaining_time:
<ide> if not block or did_timeout():
<ide> raise QueueEmpty
<del> time.sleep(remainding_time)
<add> time.sleep(remaining_time)
<ide> else:
<ide> return item
<ide> | 1 |
PHP | PHP | fix errors and add first draft of tests | da700052109c4606d011857d785efba11ea05009 | <ide><path>src/View/Helper/FormHelper.php
<ide> public function control(string $fieldName, array $options = []): string
<ide> $options = $this->_parseOptions($fieldName, $options);
<ide> $options += ['id' => $this->_domId($fieldName)];
<ide>
<del> if ($options['type'] != 'hidden') {
<add> // Hidden inputs don't need aria.
<add> // Multiple checkboxes can't have aria generated for them at this layer.
<add> if ($options['type'] !== 'hidden' && ($options['type'] !== 'select' && !isset($options['multiple']))) {
<ide> $isFieldError = $this->isFieldError($fieldName);
<add> $labelText = null;
<add> if (isset($options['label']) && is_string($options['label'])) {
<add> $labelText = $options['label'];
<add> } elseif (isset($options['placeholder'])) {
<add> $labelText = $options['placeholder'];
<add> }
<ide> $options += [
<del> 'aria-label' => isset($options['label']) && is_string($options['label']) ? $options['label'] : $options['placeholder'],
<add> 'aria-label' => $labelText,
<ide> 'aria-required' => $options['required'] == true ? 'true' : null,
<ide> 'aria-invalid' => $isFieldError ? 'true' : null,
<ide> 'aria-describedby' => $isFieldError ? $this->_domId($fieldName) . '-error' : null,
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testErrorMessageDisplay(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[title]',
<del> 'id' => 'article-title', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[title]',
<add> 'id' => 'article-title',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-title-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-title-error']],
<ide> 'error message',
<ide> '/div',
<ide> '/div',
<ide> public function testErrorMessageDisplay(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[title]',
<del> 'id' => 'article-title', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[title]',
<add> 'id' => 'article-title',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> // TODO this seems wrong as the id doesn't exist.
<add> 'aria-describedby' => 'article-title-error',
<ide> ],
<ide> '/div',
<ide> ];
<ide> public function testErrorMessageDisplay(): void
<ide> 'Content',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[content]',
<del> 'id' => 'article-content', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[content]',
<add> 'id' => 'article-content',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-content-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-content-error']],
<ide> 'some <strong>test</strong> data with <a href="#">HTML</a> chars',
<ide> '/div',
<ide> '/div',
<ide> public function testErrorMessageDisplay(): void
<ide> 'Content',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[content]',
<del> 'id' => 'article-content', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[content]',
<add> 'id' => 'article-content',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-content-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-content-error']],
<ide> 'some <strong>test</strong> data with <a href="#">HTML</a> chars',
<ide> '/div',
<ide> '/div',
<ide> public function testErrorMessageDisplay(): void
<ide> 'Content',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[content]',
<del> 'id' => 'article-content', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[content]',
<add> 'id' => 'article-content',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-content-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-content-error']],
<ide> 'some <strong>test</strong> data with <a href="#">HTML</a> chars',
<ide> '/div',
<ide> '/div',
<ide> public function testEmptyErrorValidation(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[title]',
<del> 'id' => 'article-title', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[title]',
<add> 'id' => 'article-title',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-title-error'
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-title-error']],
<ide> [],
<ide> '/div',
<ide> '/div',
<ide> public function testEmptyControlErrorValidation(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Article[title]',
<del> 'id' => 'article-title', 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'article-title-error',
<add> 'type' => 'text',
<add> 'name' => 'Article[title]',
<add> 'id' => 'article-title',
<add> 'class' => 'form-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-title-error']],
<ide> [],
<ide> '/div',
<ide> '/div',
<ide> public function testControlErrorMessage(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'title',
<del> 'id' => 'title', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'title',
<add> 'id' => 'title',
<add> 'class' => 'form-error',
<ide> 'required' => 'required',
<ide> 'data-validity-message' => 'This field cannot be left empty',
<ide> 'oninvalid' => 'this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)',
<ide> 'oninput' => 'this.setCustomValidity('')',
<add> 'aria-required' => 'true',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'title-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'title-error']],
<ide> 'Custom error!',
<ide> '/div',
<ide> '/div',
<ide> public function testControlErrorMessage(): void
<ide> 'type' => 'text',
<ide> 'name' => 'title',
<ide> 'id' => 'title',
<add> 'aria-required' => 'true',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'title-error',
<ide> 'class' => 'form-error',
<ide> 'required' => 'required',
<ide> 'data-validity-message' => 'This field cannot be left empty',
<ide> 'oninvalid' => 'this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)',
<ide> 'oninput' => 'this.setCustomValidity('')',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'title-error']],
<ide> 'Custom error!',
<ide> '/div',
<ide> '/div',
<ide> public function testFormValidationAssociated(): void
<ide> $this->Form->create($entity, ['context' => ['table' => 'Articles']]);
<ide>
<ide> $result = $this->Form->error('nested.foo');
<del> $this->assertSame('<div class="error-message">not a valid bar</div>', $result);
<add> $this->assertSame('<div class="error-message" id="nested-foo-error">not a valid bar</div>', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testFormValidationAssociatedSecondLevel(): void
<ide> $inner->setError('bar', ['not a valid one']);
<ide> $this->Form->create($entity, ['context' => ['table' => 'Articles']]);
<ide> $result = $this->Form->error('nested.foo.bar');
<del> $this->assertSame('<div class="error-message">not a valid one</div>', $result);
<add> $this->assertSame('<div class="error-message" id="nested-foo-bar-error">not a valid one</div>', $result);
<ide> }
<ide>
<ide> /**
<ide> public function testFormValidationMultiRecord(): void
<ide> 'Email',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'email', 'name' => '0[email]', 'id' => '0-email',
<del> 'class' => 'form-error', 'maxlength' => 255, 'value' => '',
<add> 'type' => 'email',
<add> 'name' => '0[email]',
<add> 'id' => '0-email',
<add> 'class' => 'form-error',
<add> 'maxlength' => 255,
<add> 'value' => '',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => '0-email-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => '0-email-error']],
<ide> 'invalid email',
<ide> '/div',
<ide> '/div',
<ide> public function testFormValidationMultiRecord(): void
<ide> 'Name',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => '1[name]', 'id' => '1-name',
<del> 'class' => 'form-error', 'maxlength' => 255, 'value' => '',
<add> 'type' => 'text',
<add> 'name' => '1[name]',
<add> 'id' => '1-name',
<add> 'class' => 'form-error',
<add> 'maxlength' => 255,
<add> 'value' => '',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => '1-name-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => '1-name-error']],
<ide> 'This is wrong',
<ide> '/div',
<ide> '/div',
<ide> public function testControlCustomization(): void
<ide> 'Field',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'field',
<del> 'id' => 'field', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'field',
<add> 'id' => 'field',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'field-error',
<ide> ],
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'field-error']],
<ide> 'Badness!',
<ide> '/div',
<ide> '/div',
<ide> public function testControlCustomization(): void
<ide> 'Field',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'field',
<del> 'id' => 'field', 'class' => 'form-error',
<add> 'type' => 'text',
<add> 'name' => 'field',
<add> 'id' => 'field',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> // TODO this seems bad as the id doesn't exist.
<add> 'aria-describedby' => 'field-error',
<ide> ],
<ide> ['span' => ['class' => 'error-message']],
<ide> 'Badness!',
<ide> public function testControlCustomization(): void
<ide> 'label' => ['for' => 'field'],
<ide> 'Field',
<ide> '/label',
<del> 'input' => ['type' => 'text', 'name' => 'field', 'id' => 'field', 'class' => 'form-error'],
<del> ['div' => ['class' => 'error-message']],
<add> 'input' => [
<add> 'type' => 'text',
<add> 'name' => 'field',
<add> 'id' => 'field',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'field-error',
<add> ],
<add> ['div' => ['class' => 'error-message', 'id' => 'field-error']],
<ide> 'Le login doit contenir au moins 2 caractères',
<ide> '/div',
<ide> '/div',
<ide> public function testControlCustomization(): void
<ide> 'label' => ['for' => 'field'],
<ide> 'Field',
<ide> '/label',
<del> 'input' => ['type' => 'text', 'name' => 'field', 'id' => 'field', 'class' => 'form-error'],
<del> ['div' => ['class' => 'error-message']],
<add> 'input' => [
<add> 'type' => 'text',
<add> 'name' => 'field',
<add> 'id' => 'field',
<add> 'class' => 'form-error',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => 'field-error',
<add> ],
<add> ['div' => ['class' => 'error-message', 'id' => 'field-error']],
<ide> 'login too large',
<ide> '/div',
<ide> '/div',
<ide> public function testControlCheckbox(): void
<ide> 'input' => ['type' => 'hidden', 'name' => 'Articles[disabled]', 'value' => '0'],
<ide> 'label' => ['for' => 'articles-disabled'],
<ide> ['input' => [
<add> 'aria-label' => 'Disabled',
<ide> 'type' => 'checkbox',
<ide> 'name' => 'Articles[disabled]',
<ide> 'value' => '1',
<ide> public function testControlCheckbox(): void
<ide> 'name' => 'Articles[confirm]',
<ide> 'value' => '1',
<ide> 'id' => 'articles-confirm',
<add> 'aria-label' => 'Confirm <b>me</b>!',
<ide> ]],
<ide> 'Confirm <b>me</b>!',
<ide> '/label',
<ide> public function testError(): void
<ide>
<ide> $result = $this->Form->error('Article.field');
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> 'email',
<ide> '/div',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->error('Article.field', '<strong>Badness!</strong>');
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> '<strong>Badness!</strong>',
<ide> '/div',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->error('Article.field', '<strong>Badness!</strong>', ['escape' => false]);
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> '<strong', 'Badness!', '/strong',
<ide> '/div',
<ide> ];
<ide> public function testErrorRuleName(): void
<ide>
<ide> $result = $this->Form->error('Article.field');
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> 'Your email was not good',
<ide> '/div',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->error('Article.field', ['email' => 'Email in use']);
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> 'Email in use',
<ide> '/div',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide>
<ide> $result = $this->Form->error('Article.field', ['Your email was not good' => 'Email in use']);
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> 'Email in use',
<ide> '/div',
<ide> ];
<ide> public function testErrorRuleName(): void
<ide> 'Your email was not good' => 'Email in use',
<ide> ]);
<ide> $expected = [
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'article-field-error']],
<ide> 'Key is preferred',
<ide> '/div',
<ide> ];
<ide> public function testErrorMessages(): void
<ide> 'email' => 'No good!',
<ide> ]);
<ide> $expected = [
<del> 'div' => ['class' => 'error-message'],
<add> 'div' => ['class' => 'error-message', 'id' => 'article-field-error'],
<ide> 'No good!',
<ide> '/div',
<ide> ];
<ide> public function testErrorMultipleMessages(): void
<ide> 'email' => 'No good!',
<ide> ]);
<ide> $expected = [
<del> 'div' => ['class' => 'error-message'],
<add> 'div' => ['class' => 'error-message', 'id' => 'field-error'],
<ide> 'ul' => [],
<ide> '<li', 'Cannot be empty', '/li',
<ide> '<li', 'No good!', '/li',
<ide> public function testErrorsForBelongsToManySelect(): void
<ide> '/label',
<ide> 'input' => ['type' => 'hidden', 'name' => 'spacecraft[_ids]', 'value' => ''],
<ide> 'select' => [
<del> 'name' => 'spacecraft[_ids][]', 'id' => 'spacecraft-ids',
<add> 'name' => 'spacecraft[_ids][]',
<add> 'id' => 'spacecraft-ids',
<ide> 'multiple' => 'multiple',
<ide> ],
<ide> ['option' => ['value' => '1']],
<ide> public function testErrorsForBelongsToManySelect(): void
<ide> 'Helios',
<ide> '/option',
<ide> '/select',
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => 'spacecraft-error']],
<ide> 'Invalid',
<ide> '/div',
<ide> '/div',
<ide> public function testControlLabelFalse(): void
<ide> $expected = [
<ide> 'div' => ['class' => 'input text required'],
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'type' => 'text',
<ide> 'required' => 'required',
<ide> 'id' => 'title',
<ide> public function testFormMagicControlLabel(): void
<ide> 'My label',
<ide> '/label',
<ide> 'input' => [
<del> 'type' => 'text', 'name' => 'Contacts[name]',
<del> 'id' => 'contacts-name', 'maxlength' => '255',
<add> 'type' => 'text',
<add> 'name' => 'Contacts[name]',
<add> 'id' => 'contacts-name',
<add> 'maxlength' => '255',
<add> 'aria-label' => 'My label',
<ide> ],
<ide> ];
<ide> $this->assertHtml($expected, $result);
<ide> public function testMultiRecordForm(): void
<ide> 'name',
<ide> 'class' => 'form-error',
<ide> 'id' => '0-comments-0-comment',
<add> 'aria-invalid' => 'true',
<add> 'aria-describedby' => '0-comments-0-comment-error',
<ide> 'rows' => 5
<ide> ],
<ide> 'Value',
<ide> '/textarea',
<del> ['div' => ['class' => 'error-message']],
<add> ['div' => ['class' => 'error-message', 'id' => '0-comments-0-comment-error']],
<ide> 'Not valid',
<ide> '/div',
<ide> '/div'
<ide> public function testMultiRecordForm(): void
<ide> '/label',
<ide> 'textarea' => [
<ide> 'name',
<add> 'aria-required' => 'true',
<ide> 'required' => 'required',
<ide> 'id' => '0-comments-1-comment',
<ide> 'rows' => 5,
<ide> public function testHtml5ErrorMessage(): void
<ide> 'Password',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'password',
<ide> 'name' => 'password',
<ide> 'type' => 'password',
<ide> public function testHtml5ErrorMessage(): void
<ide> 'Phone',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'phone',
<ide> 'name' => 'phone',
<ide> 'type' => 'tel',
<ide> public function testHtml5ErrorMessage(): void
<ide> 'Email',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'email',
<ide> 'name' => 'email',
<ide> 'type' => 'email',
<ide> public function testHtml5ErrorMessageInTemplateVars(): void
<ide> 'Password',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'password',
<ide> 'name' => 'password',
<ide> 'type' => 'password',
<ide> public function testHtml5ErrorMessageInTemplateVars(): void
<ide> 'Phone',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'phone',
<ide> 'name' => 'phone',
<ide> 'type' => 'tel',
<ide> public function testHtml5ErrorMessageInTemplateVars(): void
<ide> 'Email',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id' => 'email',
<ide> 'name' => 'email',
<ide> 'type' => 'email',
<ide> public function testRequiredAttribute(): void
<ide> 'type' => 'text',
<ide> 'name' => 'title',
<ide> 'id' => 'title',
<add> 'aria-required' => 'true',
<ide> 'required' => 'required',
<ide> 'data-validity-message' => 'This field cannot be left empty',
<ide> 'oninvalid' => 'this.setCustomValidity(''); if (!this.value) this.setCustomValidity(this.dataset.validityMessage)',
<ide> public function testControlMaxLengthArrayContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text',
<ide> public function testControlMaxLengthEntityContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text',
<ide> public function testControlMaxLengthEntityContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text',
<ide> public function testControlMaxLengthEntityContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text',
<ide> public function testControlMinMaxLengthEntityContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text',
<ide> public function testControlMaxLengthFormContext(): void
<ide> 'Title',
<ide> '/label',
<ide> 'input' => [
<add> 'aria-required' => 'true',
<ide> 'id',
<ide> 'name' => 'title',
<ide> 'type' => 'text', | 2 |
Text | Text | update chinese translation of sass | 087946adc15e2d3a4006e87ca1b441741b8b57ba | <ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/apply-a-style-until-a-condition-is-met-with-while.chinese.md
<ide> id: 587d7dbf367417b2b2512bbb
<ide> title: Apply a Style Until a Condition is Met with @while
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 应用样式直到满足@while的条件
<add>forumTopicId: 301454
<add>localeTitle: 使用 @while 当条件满足时样式生效
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>@while</code>指令是一个与JavaScript <code>while</code>循环具有类似功能的选项。它会创建CSS规则,直到满足条件。 <code>@for</code>挑战给出了一个创建简单网格系统的示例。这也适用于<code>@while</code> 。 <blockquote> $ x:1; <br> @while $ x <13 { <br> .col - #{$ x} {width:100%/ 12 * $ x;} <br> $ x:$ x + 1; <br> } </blockquote>首先,定义变量<code>$x</code>并将其设置为1.接下来,使用<code>@while</code>指令创建网格系统, <i>而</i> <code>$x</code>小于13.在设置<code>width</code>的CSS规则后, <code>$x</code>增加1以避免无限循环。 </section>
<add><section id='description'>
<add>Sass 中的<code>@while</code>指令与 JavaScript 中的<code>while</code>类似。只要满足条件,它就会一直创建 CSS 代码。
<add><code>@for</code>挑战提供了一个创建简单网格系统的示例。这也适用于<code>@while</code>。
<add>
<add>```scss
<add>$x: 1;
<add>@while $x < 13 {
<add> .col-#{$x} { width: 100%/12 * $x;}
<add> $x: $x + 1;
<add>}
<add>```
<add>
<add>首先,定义变量<code>$x</code>并将其设置为 1。接下来,使用<code>@while</code>指令,当<code>$x</code>小于 13 时创建网格系统 。
<add>在设置<code>width</code>的 CSS 规则后,<code>$x</code>增加 1 以避免无限循环。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>@while</code>创建一系列具有不同<code>font-sizes</code>的类。从<code>text-1</code>到<code>text-10</code>应该有10个不同的类。然后将<code>font-size</code>设置为5px乘以当前索引号。确保避免无限循环! </section>
<add><section id='instructions'>
<add>使用<code>@while</code>创建一系列具有不同<code>font-sizes</code>的 class。
<add>从<code>text-1</code>到<code>text-10</code>应该有 10 个不同的 class。然后将<code>font-size</code>设置为 15px 乘以当前索引号。注意不要写成死循环!
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应使用<code>@while</code>指令。
<del> testString: 'assert(code.match(/@while /g), "Your code should use the <code>@while</code> directive.");'
<del> - text: 您的代码应将索引变量设置为1才能启动。
<del> testString: 'assert(code.match(/\$.*:\s*?1;/gi), "Your code should set an index variable to 1 to start.");'
<del> - text: 您的代码应该递增计数器变量。
<del> testString: 'assert(code.match(/\$(.*):\s*?\$\1\s*?\+\s*?1;/gi), "Your code should increment the counter variable.");'
<del> - text: 您的<code>.text-1</code>类的<code>font-size</code>为5px。
<del> testString: 'assert($(".text-1").css("font-size") == "5px", "Your <code>.text-1</code> class should have a <code>font-size</code> of 5px.");'
<del> - text: 您的<code>.text-2</code>类的<code>font-size</code>为10px。
<del> testString: 'assert($(".text-2").css("font-size") == "10px", "Your <code>.text-2</code> class should have a <code>font-size</code> of 10px.");'
<del> - text: 您的<code>.text-3</code>类的<code>font-size</code>为15px。
<del> testString: 'assert($(".text-3").css("font-size") == "15px", "Your <code>.text-3</code> class should have a <code>font-size</code> of 15px.");'
<del> - text: 您的<code>.text-4</code>类的<code>font-size</code>为20px。
<del> testString: 'assert($(".text-4").css("font-size") == "20px", "Your <code>.text-4</code> class should have a <code>font-size</code> of 20px.");'
<del> - text: 您的<code>.text-5</code>类的<code>font-size</code>为25px。
<del> testString: 'assert($(".text-5").css("font-size") == "25px", "Your <code>.text-5</code> class should have a <code>font-size</code> of 25px.");'
<del> - text: 您的<code>.text-6</code>类的<code>font-size</code>为30px。
<del> testString: 'assert($(".text-6").css("font-size") == "30px", "Your <code>.text-6</code> class should have a <code>font-size</code> of 30px.");'
<del> - text: 您的<code>.text-7</code>类的<code>font-size</code>为35px。
<del> testString: 'assert($(".text-7").css("font-size") == "35px", "Your <code>.text-7</code> class should have a <code>font-size</code> of 35px.");'
<del> - text: 您的<code>.text-8</code>类的<code>font-size</code>为40px。
<del> testString: 'assert($(".text-8").css("font-size") == "40px", "Your <code>.text-8</code> class should have a <code>font-size</code> of 40px.");'
<del> - text: 您的<code>.text-9</code>类的<code>font-size</code>为45px。
<del> testString: 'assert($(".text-9").css("font-size") == "45px", "Your <code>.text-9</code> class should have a <code>font-size</code> of 45px.");'
<del> - text: 您的<code>.text-10</code>类的<code>font-size</code>为50px。
<del> testString: 'assert($(".text-10").css("font-size") == "50px", "Your <code>.text-10</code> class should have a <code>font-size</code> of 50px.");'
<add> - text: 你的代码应使用<code>@while</code>指令。
<add> testString: assert(code.match(/@while /g));
<add> - text: 你的代码应将索引变量设置为 1 才能启动。
<add> testString: assert(code.match(/\$.*:\s*?1;/gi));
<add> - text: 你的代码应该递增计数器变量。
<add> testString: assert(code.match(/\$(.*)\s*?:\s*\$\1\s*\+\s*1\s*;/gi));
<add> - text: <code>.text-1</code>class 的<code>font-size</code>应为 15px。
<add> testString: assert($('.text-1').css('font-size') == '15px');
<add> - text: <code>.text-2</code>class 的<code>font-size</code>应为 30px。
<add> testString: assert($('.text-2').css('font-size') == '30px');
<add> - text: <code>.text-3</code>class 的<code>font-size</code>应为 45px。
<add> testString: assert($('.text-3').css('font-size') == '45px');
<add> - text: <code>.text-4</code>class 的<code>font-size</code>应为 60px。
<add> testString: assert($('.text-4').css('font-size') == '60px');
<add> - text: <code>.text-5</code>class 的<code>font-size</code>应为 75px。
<add> testString: assert($('.text-5').css('font-size') == '75px');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <p class="text-3">Hello</p>
<ide> <p class="text-4">Hello</p>
<ide> <p class="text-5">Hello</p>
<del><p class="text-6">Hello</p>
<del><p class="text-7">Hello</p>
<del><p class="text-8">Hello</p>
<del><p class="text-9">Hello</p>
<del><p class="text-10">Hello</p>
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> $x: 1;
<add> @while $x < 6 {
<add> .text-#{$x}{
<add> font-size: 15px * $x;
<add> }
<add> $x: $x + 1;
<add> }
<add></style>
<add>
<add><p class="text-1">Hello</p>
<add><p class="text-2">Hello</p>
<add><p class="text-3">Hello</p>
<add><p class="text-4">Hello</p>
<add><p class="text-5">Hello</p>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/create-reusable-css-with-mixins.chinese.md
<ide> id: 587d7dbd367417b2b2512bb6
<ide> title: Create Reusable CSS with Mixins
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用Mixins创建可重用的CSS
<add>forumTopicId: 301455
<add>localeTitle: 用 Mixins 创建可重用 CSS
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在Sass中, <code>mixin</code>是一组CSS声明,可以在整个样式表中重用。较新的CSS功能需要一段时间才能完全采用并准备好在所有浏览器中使用。随着功能添加到浏览器中,使用它们的CSS规则可能需要供应商前缀。考虑“盒子阴影”: <blockquote> div { <br> -webkit-box-shadow:0px 0px 4px #fff; <br> -moz-box-shadow:0px 0px 4px #fff; <br> -ms-box-shadow:0px 0px 4px #fff; <br> box-shadow:0px 0px 4px #fff; <br> } </blockquote>对于具有<code>box-shadow</code>所有元素重写此规则,或者更改每个值以测试不同的效果,需要进行大量的输入。 <code>Mixins</code>就像CSS的功能。这是如何写一个: <blockquote> @mixin box-shadow($x,$y,$blur,$c){ <br> -webkit-box-shadow:$x $y $blur $c; <br> -moz-box-shadow:$x $y $blur $c; <br> -ms-box-shadow:$x $y $blur $c; <br> box-shadow:$x $y $blur $c; <br> } </blockquote>该定义以<code>@mixin</code>开头,后跟自定义名称。参数(上例中的<code>$x</code> , <code>$y</code> , <code>$blur</code>和<code>$c</code> )是可选的。现在,只要需要一个<code>box-shadow</code>规则,只需要调用<code>mixin</code>一行代替必须输入所有供应商前缀。使用<code>@include</code>指令调用<code>mixin</code> : <blockquote> div { <br> @include box-shadow(0px,0px,4px,#fff); <br> } </blockquote></section>
<add><section id='description'>
<add>在 Sass 中,<code>mixin</code>是一组 CSS 声明,可以在整个样式表中重复使用。
<add>CSS 的新功能需要一段时间适配后,所有浏览器后才能完全使用。随着浏览器的不断升级,使用这些 CSS 规则时可能需要添加浏览器前缀。比如 "box-shadow":
<add>
<add>```scss
<add>div {
<add> -webkit-box-shadow: 0px 0px 4px #fff;
<add> -moz-box-shadow: 0px 0px 4px #fff;
<add> -ms-box-shadow: 0px 0px 4px #fff;
<add> box-shadow: 0px 0px 4px #fff;
<add>}
<add>```
<add>
<add>对于所有具有<code>box-shadow</code>属性的元素重写此规则,或者更改每个值以测试不同的效果,需要花费大量的精力。
<add><code>Mixins</code>就像 CSS 的函数。以下是一个例子:
<add>
<add>```scss
<add>@mixin box-shadow($x, $y, $blur, $c){
<add> -webkit-box-shadow: $x $y $blur $c;
<add> -moz-box-shadow: $x $y $blur $c;
<add> -ms-box-shadow: $x $y $blur $c;
<add> box-shadow: $x $y $blur $c;
<add>}
<add>```
<add>
<add>定义以<code>@mixin</code>开头,后跟自定义名称。参数(<code>$x</code>,<code>$y</code>,<code>$blur</code>,以及上例中的<code>$c</code>是可选的。
<add>现在,只要在需要的地方使用<code>@include</code>调用上面定义的<code>mixin</code>,就可以自动添加好所有的浏览器前缀:<code>mixin</code>使用<code>@include</code>指令调用:
<add>
<add>```scss
<add>div {
<add> @include box-shadow(0px, 0px, 4px, #fff);
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">为<code>border-radius</code>写一个<code>mixin</code>并给它一个<code>$radius</code>参数。它应该使用示例中的所有供应商前缀。然后使用<code>border-radius</code> <code>mixin</code>为<code>#awesome</code>元素提供15px的边界半径。 </section>
<add><section id='instructions'>
<add>为<code>border-radius</code>写一个<code>mixin</code>,并给它一个<code>$radius</code>参数。它应该使用示例中的所有浏览器前缀,然后使用<code>border-radius mixin</code>为<code>#awesome</code>元素提供 15px 的边框半径。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的代码应该声明一个名为<code>border-radius</code>的<code>mixin</code> ,它有一个名为<code>$radius</code>的参数。
<add> - text: 你应声明名为<code>border-radius</code>的<code>mixin</code>,其中包含名为<code>$radius</code>的参数。
<ide> testString: assert(code.match(/@mixin\s+?border-radius\s*?\(\s*?\$radius\s*?\)\s*?{/gi));
<del> - text: 您的代码应包含使用<code>$radius</code>参数的<code>-webkit-border-radius</code> vender前缀。
<add> - text: 你应该给<code>$radius</code>添加<code>-webkit-border-radius</code>浏览器前缀。
<ide> testString: assert(code.match(/-webkit-border-radius:\s*?\$radius;/gi));
<del> - text: 您的代码应包含使用<code>$radius</code>参数的<code>-moz-border-radius</code> vender前缀。
<add> - text: 你应该给<code>$radius</code>添加<code>-moz-border-radius</code>浏览器前缀。
<ide> testString: assert(code.match(/-moz-border-radius:\s*?\$radius;/gi));
<del> - text: 您的代码应包含使用<code>$radius</code>参数的<code>-ms-border-radius</code> vender前缀。
<add> - text: 你应该给<code>$radius</code>添加<code>-ms-border-radius</code>浏览器前缀。
<ide> testString: assert(code.match(/-ms-border-radius:\s*?\$radius;/gi));
<del> - text: 您的代码应包含使用<code>$radius</code>参数的一般<code>border-radius</code>规则。
<add> - text: 你应该给<code>$radius</code>添加<code>border-radius</code>。
<ide> testString: assert(code.match(/border-radius:\s*?\$radius;/gi).length == 4);
<del> - text: 您的代码应使用<code>@include</code>关键字调用<code>border-radius mixin</code> ,将其设置为15px。
<add> - text: 你应使用<code>@include</code>关键字调用<code>border-radius mixin</code>,并将其设置为 15px。
<ide> testString: assert(code.match(/@include\s+?border-radius\(\s*?15px\s*?\);/gi));
<ide>
<ide> ```
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> @mixin border-radius($radius) {
<add> -webkit-border-radius: $radius;
<add> -moz-border-radius: $radius;
<add> -ms-border-radius: $radius;
<add> border-radius: $radius;
<add> }
<add>
<add> #awesome {
<add> width: 150px;
<add> height: 150px;
<add> background-color: green;
<add> @include border-radius(15px);
<add> }
<add></style>
<add>
<add><div id="awesome"></div>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/extend-one-set-of-css-styles-to-another-element.chinese.md
<ide> id: 587d7fa5367417b2b2512bbd
<ide> title: Extend One Set of CSS Styles to Another Element
<ide> challengeType: 0
<del>videoUrl: ''
<add>forumTopicId: 301456
<ide> localeTitle: 将一组CSS样式扩展到另一个元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Sass有一个名为<code>extend</code>的功能,可以很容易地从一个元素中借用CSS规则并在另一个元素上构建它们。例如,下面的CSS规则块会设置一个<code>.panel</code>类。它有<code>background-color</code> , <code>height</code>和<code>border</code> 。 <blockquote> 。面板{ <br>背景颜色:红色; <br>身高:70px; <br>边框:2px纯绿色; <br> } </blockquote>现在你想要另一个名为<code>.big-panel</code> 。它具有与<code>.panel</code>相同的基本属性,但也需要<code>width</code>和<code>font-size</code> 。可以从<code>.panel</code>复制并粘贴初始CSS规则,但是当您添加更多类型的面板时,代码会变得重复。 <code>extend</code>指令是一种重用为一个元素编写的规则的简单方法,然后为另一个元素添加更多: <blockquote> 。大面板{ <br> @extend .panel; <br>宽度:150px; <br> font-size:2em; <br> } </blockquote>除了新样式之外, <code>.big-panel</code>还具有与<code>.panel</code>相同的属性。 </section>
<add><section id='description'>
<add>Sass 有一个名为<code>extend</code>的功能,可以很容易地从一个元素中借用 CSS 规则并在另一个元素上重用它们。
<add>例如,下面的 CSS 规则块设置了<code>.panel</code>class 的样式。它有<code>background-color</code>,<code>height</code>和<code>border</code>。
<add>
<add>```scss
<add>.panel{
<add> background-color: red;
<add> height: 70px;
<add> border: 2px solid green;
<add>}
<add>```
<add>
<add>现在你需要另一个名为<code>.big-panel</code>的面板。它具有与<code>.panel</code>相同的基本属性,但还需要<code>width</code>和<code>font-size</code>。
<add>可以从<code>.panel</code>复制并粘贴初始 CSS 规则,但是当你添加更多类型的面板时,代码会变得重复。
<add><code>extend</code>指令是一种重用为一个元素编写的规则的简单方法,然后为另一个元素添加更多:
<add>
<add>```scss
<add>.big-panel{
<add> @extend .panel;
<add> width: 150px;
<add> font-size: 2em;
<add>}
<add>```
<add>
<add>除了新样式之外,<code>.big-panel</code>将具有与<code>.panel</code>相同的属性。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个扩展<code>.info</code>的类<code>.info-important</code> ,并将<code>background-color</code>设置为洋红色。 </section>
<add><section id='instructions'>
<add>创建一个扩展<code>.info</code>的 class<code>.info-important</code>,并将<code>background-color</code>设置为洋红色。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>info-important</code>类应该将<code>background-color</code>设置为<code>magenta</code> 。
<add> - text: <code>info-important</code>class 应该将<code>background-color</code>设置为<code>magenta</code>。
<ide> testString: assert(code.match(/\.info-important\s*?{[\s\S]*background-color\s*?:\s*?magenta\s*?;[\s\S]*}/gi));
<del> - text: 您的<code>info-important</code>类应使用<code>@extend</code>从<code>info</code>类继承样式。
<add> - text: <code>info-important</code>class 应使用<code>@extend</code>继承<code>info</code>class 的样式。
<ide> testString: assert(code.match(/\.info-important\s*?{[\s\S]*@extend\s*?.info\s*?;[\s\S]*/gi));
<ide>
<ide> ```
<ide> tests:
<ide> <div class="info">
<ide> <p>This is a simple post. It has basic styling and can be extended for other uses.</p>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> h3{
<add> text-align: center;
<add> }
<add> .info{
<add> width: 200px;
<add> border: 1px solid black;
<add> margin: 0 auto;
<add> }
<add> .info-important{
<add> @extend .info;
<add> background-color: magenta;
<add> }
<add>
<add>
<add>
<add></style>
<add><h3>Posts</h3>
<add><div class="info-important">
<add> <p>This is an important post. It should extend the class ".info" and have its own CSS styles.</p>
<add></div>
<add>
<add><div class="info">
<add> <p>This is a simple post. It has basic styling and can be extended for other uses.</p>
<add></div>
<add>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/nest-css-with-sass.chinese.md
<ide> id: 587d7dbd367417b2b2512bb5
<ide> title: Nest CSS with Sass
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用Sass嵌套CSS
<add>forumTopicId: 301457
<add>localeTitle: 用 Sass 嵌套 CSS
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Sass允许<code>nesting</code> CSS规则,这是组织样式表的有用方法。通常,每个元素都定位在不同的行上以对其进行样式设置,如下所示: <blockquote> nav { <br>背景颜色:红色; <br> } <br><br> nav ul { <br> list-style:none; <br> } <br><br> nav ul li { <br> display:inline-block; <br> } </blockquote>对于大型项目,CSS文件将包含许多行和规则。这是<code>nesting</code>可以通过在相应的父元素中放置子样式规则来帮助组织代码的地方: <blockquote> nav { <br>背景颜色:红色; <br><br> ul { <br> list-style:none; <br><br> li { <br> display:inline-block; <br> } <br> } <br> } <br></blockquote></section>
<add><section id='description'>
<add>Sass 允许 CSS 规则的<code>嵌套</code>,这在写样式表的时候会很有用。
<add>在 CSS 里,每个元素的样式都需要写在独立的代码块中,如下所示:
<add>
<add>```scss
<add>nav {
<add> background-color: red;
<add>}
<add>
<add>nav ul {
<add> list-style: none;
<add>}
<add>
<add>nav ul li {
<add> display: inline-block;
<add>}
<add>```
<add>
<add>对于一个大型项目,CSS 规则会很复杂。这时,引入<code>嵌套</code>功能(即在对应的父元素中写子元素的样式)可以有效地简化代码:
<add>
<add>```scss
<add>nav {
<add> background-color: red;
<add>
<add> ul {
<add> list-style: none;
<add>
<add> li {
<add> display: inline-block;
<add> }
<add> }
<add>}
<add>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用上面显示的<code>nesting</code>技术为<code>.blog-post</code>元素的两个子元素重新组织CSS规则。出于测试目的, <code>h1</code>应该位于<code>p</code>元素之前。 </section>
<add><section id='instructions'>
<add>根据上面关于嵌套的例子,来简化<code>.blog-post<code>中两个子元素的 CSS 代码。出于测试目的,<code>h1</code>应该出现在<code>p</code>元素之前。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该重新组织CSS规则,以便<code>h1</code>和<code>p</code>嵌套在<code>.blog-post</code>父元素中。
<add> - text: 你应重新组织 CSS 规则,以便<code>h1</code>和<code>p</code>嵌套在<code>.blog-post</code>父元素中。
<ide> testString: assert(code.match(/\.blog-post\s*?{\s*?h1\s*?{\s*?text-align:\s*?center;\s*?color:\s*?blue;\s*?}\s*?p\s*?{\s*?font-size:\s*?20px;\s*?}\s*?}/gi));
<ide>
<ide> ```
<ide> tests:
<ide> <h1>Blog Title</h1>
<ide> <p>This is a paragraph</p>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> .blog-post {
<add> h1 {
<add> text-align: center;
<add> color: blue;
<add> }
<add> p {
<add> font-size: 20px;
<add> }
<add> }
<add></style>
<add>
<add><div class="blog-post">
<add> <h1>Blog Title</h1>
<add> <p>This is a paragraph</p>
<add></div>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/split-your-styles-into-smaller-chunks-with-partials.chinese.md
<ide> id: 587d7dbf367417b2b2512bbc
<ide> title: Split Your Styles into Smaller Chunks with Partials
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用Partials将您的样式拆分为较小的块
<add>forumTopicId: 301459
<add>localeTitle: 用 Partials 将你的样式分成小块
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>Partials</code>在萨斯是持有的CSS代码段单独的文件。这些是在其他Sass文件中导入和使用的。这是将类似代码分组到模块中以保持组织有效的好方法。 <code>partials</code>名称以下划线( <code>_</code> )字符开头,告诉Sass它是CSS的一小部分,而不是将其转换为CSS文件。此外,Sass文件以<code>.scss</code>文件扩展名结尾。要将<code>partial</code>的代码放入另一个Sass文件中,请使用<code>@import</code>指令。例如,如果所有<code>mixins</code>都保存在名为“_mixins.scss”的<code>partial</code> ,并且在“main.scss”文件中需要它们,则这是在主文件中使用它们的方法: <blockquote> //在main.scss文件中<br><br> @import'commpins' </blockquote>请注意, <code>import</code>语句中不需要下划线 - Sass理解它是<code>partial</code> 。将<code>partial</code>导入文件后,可以使用所有变量, <code>mixins</code>和其他代码。 </section>
<add><section id='description'>
<add>Sass 中的<code>Partials</code>是包含 CSS 代码段的单独文件。这些是在其他 Sass 文件中导入和使用的。我们可以把类似代码放到模块中,以保持代码结构规整且易于管理。
<add><code>partials</code>的名称以下划线(<code>_</code>)字符开头,告诉 Sass 它是 CSS 的一小部分,而不是将其转换为 CSS 文件。此外,Sass 文件以<code>.scss</code>文件扩展名结尾。要将<code>partial</code>中的代码放入另一个 Sass 文件中,请使用<code>@import</code>指令。
<add>例如,如果所有<code>mixins</code>都保存在名为 "_mixins.scss " 的<code>partial</code>中,并且在"main.scss "文件中需要它们,这是如何在主文件中使用它们:
<add>
<add>```scss
<add>// In the main.scss file
<add>
<add>@import 'mixins'
<add>```
<add>
<add>请注意,<code>import</code>语句中不需要下划线——Sass 知道它是<code>partial</code>。将<code>partial</code>导入文件后,可以使用所有变量<code>mixins</code>和其他代码。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">编写<code>@import</code>语句,将名为<code>_variables.scss</code>的<code>partial</code>导入main.scss文件。 </section>
<add><section id='instructions'>
<add>编写<code>@import</code>语句,将名为<code>_variables.scss</code>的<code>partial</code>导入 main.scss 文件。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应使用<code>@import</code>指令,并且不应在文件名中包含下划线。
<add> - text: 你的代码应使用<code>@import</code>指令,并且不应在文件名中包含下划线。
<ide> testString: assert(code.match(/@import\s+?('|")variables\1/gi));
<ide>
<ide> ```
<ide> tests:
<ide> ```html
<ide> // The main.scss file
<ide>
<add>
<add>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add>// The main.scss file
<add>@import 'variables'
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/store-data-with-sass-variables.chinese.md
<ide> id: 587d7dbd367417b2b2512bb4
<ide> title: Store Data with Sass Variables
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用Sass变量存储数据
<add>forumTopicId: 301460
<add>localeTitle: 用 Sass 变量存储数据
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Sass的一个与CSS不同的特性是它使用变量。它们被声明并设置为存储数据,类似于JavaScript。在JavaScript中,使用<code>let</code>和<code>const</code>关键字定义变量。在Sass中,变量以<code>$</code>开头,后跟变量名。以下是几个例子: <blockquote> $ main-fonts:Arial,sans-serif; <br> $ headings-color:green; <br><br> //使用变量: <br> h1 { <br> font-family:$ main-fonts; <br>颜色:$ headings-color; <br> } </blockquote>变量有用的一个例子是当许多元素需要是相同的颜色时。如果更改了该颜色,则编辑代码的唯一位置是变量值。 </section>
<add><section id='description'>
<add>Sass 不同于 CSS 的一个特点是它允许使用变量。我们可以在 Sass 中声明变量,并为它赋值,就像我们在 JavaScript 中一样。
<add>在 JavaScript 中,变量是使用<code>let</code>和<code>const</code>关键字定义的。在 Sass 中,变量以<code>$</code>开头的,后跟变量名。
<add>这里有几个例子:
<add>
<add>```scss
<add>$main-fonts: Arial, sans-serif;
<add>$headings-color: green;
<add>
<add>//To use variables:
<add>h1 {
<add> font-family: $main-fonts;
<add> color: $headings-color;
<add>}
<add>```
<add>
<add>当需要把多个元素设置成相同颜色时,变量就会很有用。一旦我们需要更改颜色,只需要改变这个变量的值就好。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个变量<code>$text-color</code>并将其设置为红色。然后将<code>.blog-post</code>和<code>h2</code>的<code>color</code>属性值更改为<code>$text-color</code>变量。 </section>
<add><section id='instructions'>
<add>创建一个变量<code>$text-color</code>并将其设置为红色。然后更改<code>.blog-post</code>和<code>h2</code>的<code>color</code>属性的值为<code>$text-color</code>变量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该具有为<code>$text-color</code>声明的Sass变量,其值为red。
<add> - text: 你应该为<code>$text-color</code>声明一个值为红色的 Sass 变量。
<ide> testString: assert(code.match(/\$text-color:\s*?red;/g));
<del> - text: 您的代码应使用<code>$text-color</code>变量来更改<code>.blog-post</code>和<code>h2</code>项的<code>color</code> 。
<add> - text: 你应使用<code>$text-color</code>变量来更改<code>.blog-post</code>和<code>h2</code>的<code>颜色</code>。
<ide> testString: assert(code.match(/color:\s*?\$text-color;/g));
<del> - text: 您的<code>.blog-post</code>元素应该是红色。
<add> - text: <code>.blog-post</code>元素应为红色。
<ide> testString: assert($('.blog-post').css('color') == 'rgb(255, 0, 0)');
<del> - text: 你的<code>h2</code>元素应该是红色。
<add> - text: <code>h2</code>元素应为红色。
<ide> testString: assert($('h2').css('color') == 'rgb(255, 0, 0)');
<ide>
<ide> ```
<ide> tests:
<ide> <h2>Here is another header</h2>
<ide> <p>Even more random text within a paragraph</p>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> $text-color: red;
<add>
<add> .header{
<add> text-align: center;
<add> }
<add> .blog-post, h2 {
<add> color: $text-color;
<add> }
<add></style>
<add>
<add><h1 class="header">Learn Sass</h1>
<add><div class="blog-post">
<add> <h2>Some random title</h2>
<add> <p>This is a paragraph with some random text in it</p>
<add></div>
<add><div class="blog-post">
<add> <h2>Header #2</h2>
<add> <p>Here is some more random text.</p>
<add></div>
<add><div class="blog-post">
<add> <h2>Here is another header</h2>
<add> <p>Even more random text within a paragraph</p>
<add></div>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-each-to-map-over-items-in-a-list.chinese.md
<ide> id: 587d7dbf367417b2b2512bba
<ide> title: Use @each to Map Over Items in a List
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用@each映射列表中的项目
<add>forumTopicId: 301461
<add>localeTitle: 使用 @each 遍历列表中的项目
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一个挑战显示了<code>@for</code>指令如何使用起始值和结束值循环一定次数。 Sass还提供了<code>@each</code>指令,它循环遍历列表或映射中的每个项目。在每次迭代时,变量将从列表或映射分配给当前值。 <blockquote> @each $颜色为蓝色,红色,绿色{ <br> 。#{$ color} -text {color:$ color;} <br> } </blockquote>地图的语法略有不同。这是一个例子: <blockquote> $ colors:(color1:blue,color2:red,color3:green); <br><br> @each $ key,$ colors in colors { <br> 。#{$ color} -text {color:$ color;} <br> } </blockquote>请注意,需要<code>$key</code>变量来引用地图中的键。否则,编译后的CSS将有<code>color1</code> , <code>color2</code> ...在里面。以上两个代码示例都转换为以下CSS: <blockquote> .blue-text { <br>颜色:蓝色; <br> } <br><br> .red-text { <br>红色; <br> } <br><br> .green-text { <br>颜色:绿色; <br> } </blockquote></section>
<add><section id='description'>
<add>
<add>最后一个挑战显示了<code>@for</code>指令如何使用起始值和结束值循环一定次数。Sass 还提供<code>@each</code>指令,该指令循环遍历列表或映射中的每个项目。
<add>在每次迭代时,变量将从列表映射赋值给当前值。
<add>
<add>```scss
<add>@each $color in blue, red, green {
<add> .#{$color}-text {color: $color;}
<add>}
<add>```
<add>
<add>map 的语法略有不同。这是一个例子:
<add>
<add>```scss
<add>$colors: (color1: blue, color2: red, color3: green);
<add>
<add>@each $key, $color in $colors {
<add> .#{$color}-text {color: $color;}
<add>}
<add>```
<add>
<add>请注意,需要<code>$key</code>变量来引用 map 中的键。否则,编译后的 CSS 将包含<code>color1</code>,<code>color2</code>......
<add>以上两个代码示例都转换为以下 CSS:
<add>
<add>```scss
<add>.blue-text {
<add> color: blue;
<add>}
<add>
<add>.red-text {
<add> color: red;
<add>}
<add>
<add>.green-text {
<add> color: green;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">编写一个<code>@each</code>列表的<code>@each</code>指令: <code>blue, black, red</code> ,并将每个变量分配给<code>.color-bg</code>类,其中“颜色”部分为每个项目更改。每个类应该将<code>background-color</code>设置为相应的颜色。 </section>
<add><section id='instructions'>
<add>
<add>编写一个<code>@each</code>指令,通过一个列表:<code>blue,black,red</code>并将每个变量分配给<code>.color-bg</code>class, 其中每个项目的“颜色”部分都会发生变化。
<add>每个 class 都应该将<code>background-color</code>设置为相应的颜色。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该使用<code>@each</code>指令。
<add> - text: 你的代码应使用<code>@each</code>指令。
<ide> testString: assert(code.match(/@each /g));
<del> - text: 您的<code>.blue-bg</code>类应该具有蓝色的<code>background-color</code> 。
<add> - text: <code>.blue-bg</code>class 背景色应为蓝色。
<ide> testString: assert($('.blue-bg').css('background-color') == 'rgb(0, 0, 255)');
<del> - text: 你的<code>.black-bg</code>类的<code>background-color</code>为黑色。
<add> - text: <code>.black-bg</code>class 背景色应为黑色。
<ide> testString: assert($('.black-bg').css('background-color') == 'rgb(0, 0, 0)');
<del> - text: 您的<code>.red-bg</code>类应该具有红色的<code>background-color</code> 。
<add> - text: <code>.red-bg</code>class 背景色应为红色。
<ide> testString: assert($('.red-bg').css('background-color') == 'rgb(255, 0, 0)');
<ide>
<ide> ```
<ide> tests:
<ide> <div class="blue-bg"></div>
<ide> <div class="black-bg"></div>
<ide> <div class="red-bg"></div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>The solution requires using the $color variable twice: once for the class name and once for setting the background color. You can use either the list or map data type.
<add>
<add>### List Data type
<add>
<add>```html
<add><style type='text/sass'>
<add>
<add> @each $color in blue, black, red {
<add> .#{$color}-bg {background-color: $color;}
<add> }
<add>
<add> div {
<add> height: 200px;
<add> width: 200px;
<add> }
<add></style>
<add>
<add><div class="blue-bg"></div>
<add><div class="black-bg"></div>
<add><div class="red-bg"></div>
<ide> ```
<ide>
<del>/section>
<add>### Map Data type
<add>
<add>```html
<add><style type='text/sass'>
<add>
<add> $colors: (color1: blue, color2: black, color3: red);
<add>
<add> @each $key, $color in $colors {
<add> .#{$color}-bg {background-color: $color;}
<add> }
<add>
<add> div {
<add> height: 200px;
<add> width: 200px;
<add> }
<add></style>
<add>
<add><div class="blue-bg"></div>
<add><div class="black-bg"></div>
<add><div class="red-bg"></div>
<add>```
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-for-to-create-a-sass-loop.chinese.md
<ide> id: 587d7dbe367417b2b2512bb9
<ide> title: Use @for to Create a Sass Loop
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用@for创建Sass循环
<add>forumTopicId: 301462
<add>localeTitle: 使用 @for 创建一个 Sass 循环
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>@for</code>指令在循环中添加样式,非常类似于JavaScript中的<code>for</code>循环。 <code>@for</code>以两种方式使用:“ <code>@for</code> ”或“ <code>@for</code> ”。主要区别在于“从头到尾” <em>排除</em>了结束号码,“从头到尾” <em>包括</em>结束号码。这是一个开始<b>到</b>最后的例子: <blockquote> @for $ i从1到12 { <br> .col - #{$ i} {width:100%/ 12 * $ i; } <br> } </blockquote> <code>#{$i}</code>部分是将变量( <code>i</code> )与文本组合成字符串的语法。当Sass文件转换为CSS时,它看起来像这样: <blockquote> .col-1 { <br>宽度:8.33333%; <br> } <br><br> .col-2 { <br>宽度:16.66667%; <br> } <br><br> ... <br><br> .col-12 { <br>宽度:100%; <br> } </blockquote>这是创建网格布局的有效方法。现在,您有12个可用作CSS类的列宽选项。 </section>
<add><section id='description'>
<add>你可以在 Sass 中使用<code>@for</code>循环,它的表现类似与 JavaScript 中的<code>for</code>循环。
<add><code>@for</code>以两种方式使用:"start through end" 或 "start to end"。主要区别在于“开始结束”<em> 排除 </em> 结束号码,而“开始结束”<em> 包括 </em> 结束号码。
<add>这是一个开始 <b> 到 </b> 结束示例:
<add>
<add>```scss
<add>@for $i from 1 through 12 {
<add> .col-#{$i} { width: 100%/12 * $i; }
<add>}
<add>```
<add>
<add><code>#{$i}</code>部分是将变量(<code>i</code>)与文本组合成字符串的语法。当 Sass 文件转换为 CSS 时,它看起来像这样:
<add>
<add>```scss
<add>.col-1 {
<add> width: 8.33333%;
<add>}
<add>
<add>.col-2 {
<add> width: 16.66667%;
<add>}
<add>
<add>...
<add>
<add>.col-12 {
<add> width: 100%;
<add>}
<add>```
<add>
<add>这是创建网格布局的有效方法。现在,你有 12 个可用作 CSS classes 的列宽选项。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个<code>@for</code>指令,它接受一个从1 <b>到</b> 6的变量<code>$j</code> 。它应该创建5个名为<code>.text-1</code>到<code>.text-5</code> ,其中每个类的<code>font-size</code>设置为10px乘以索引。 </section>
<add><section id='instructions'>
<add>编写<code>@for</code>指令,使<code>$j</code>的值为从 1(包含)到 6(不包含)。
<add>它应该创建 5 个名为<code>.text-1</code>的 classes 到<code>.text-5</code>,其中每个 class 的<code>font-size</code>设置为 15px 乘以索引。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应使用<code>@for</code>指令。
<add> - text: 你应使用<code>@for</code>指令。
<ide> testString: assert(code.match(/@for /g));
<del> - text: 您的<code>.text-1</code>类的<code>font-size</code>为10px。
<add> - text: <code>.text-1</code>class 的<code>font-size</code>应为 15px。
<ide> testString: assert($('.text-1').css('font-size') == '15px');
<del> - text: 您的<code>.text-2</code>类的<code>font-size</code>为20px。
<add> - text: <code>.text-2</code>class 的<code>font-size</code>应为 30px。
<ide> testString: assert($('.text-2').css('font-size') == '30px');
<del> - text: 您的<code>.text-3</code>类的<code>font-size</code>为30px。
<add> - text: <code>.text-3</code>class 的<code>font-size</code>应为 45px。
<ide> testString: assert($('.text-3').css('font-size') == '45px');
<del> - text: 您的<code>.text-4</code>类的<code>font-size</code>为40px。
<add> - text: <code>.text-4</code>class 的<code>font-size</code>应为 60px。
<ide> testString: assert($('.text-4').css('font-size') == '60px');
<del> - text: 您的<code>.text-5</code>类的<code>font-size</code>为50px。
<add> - text: <code>.text-5</code>class 的<code>font-size</code>应为 75px。
<ide> testString: assert($('.text-5').css('font-size') == '75px');
<ide>
<ide> ```
<ide> tests:
<ide> <p class="text-3">Hello</p>
<ide> <p class="text-4">Hello</p>
<ide> <p class="text-5">Hello</p>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add>
<add>@for $i from 1 through 5 {
<add> .text-#{$i} { font-size: 15px * $i; }
<add>}
<add>
<add></style>
<add>
<add><p class="text-1">Hello</p>
<add><p class="text-2">Hello</p>
<add><p class="text-3">Hello</p>
<add><p class="text-4">Hello</p>
<add><p class="text-5">Hello</p>
<ide> ```
<ide>
<del>/section>
<add>```html
<add><style type='text/sass'>
<add>
<add>@for $i from 1 to 6 {
<add> .text-#{$i} { font-size: 15px * $i; }
<add>}
<add>
<add></style>
<add>
<add><p class="text-1">Hello</p>
<add><p class="text-2">Hello</p>
<add><p class="text-3">Hello</p>
<add><p class="text-4">Hello</p>
<add><p class="text-5">Hello</p>
<add>```
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles.chinese.md
<ide> id: 587d7dbe367417b2b2512bb8
<ide> title: Use @if and @else to Add Logic To Your Styles
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用@if和@else将逻辑添加到您的样式
<add>forumTopicId: 301463
<add>localeTitle: 使用 @if 和 @else 为你的样式添加逻辑
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Sass中的<code>@if</code>指令对于测试特定情况很有用 - 它就像JavaScript中的<code>if</code>语句一样。 <blockquote> @mixin make-bold($ bool){ <br> @if $ bool == true { <br> font-weight:bold; <br> } <br> } </blockquote>就像在JavaScript中一样, <code>@else if</code>和<code>@else</code>测试更多条件: <blockquote> @mixin text-effect($ val){ <br> @if $ val == danger { <br>红色; <br> } <br> @else if $ val == alert { <br>颜色:黄色; <br> } <br> @else if $ val == success { <br>颜色:绿色; <br> } <br> @else { <br>颜色:黑色; <br> } <br> } </blockquote></section>
<add><section id='description'>
<add>Sass 中的<code>@if</code>指令对于测试特定情况非常有用--它的工作方式与 JavaScript</code>中的<code>if</code>语句类似。
<add>
<add>```scss
<add>@mixin make-bold($bool) {
<add> @if $bool == true {
<add> font-weight: bold;
<add> }
<add>}
<add>```
<add>
<add>类似 JavaScript,你可以在 Sass 中使用<code>@else if</code>和<code>@else</code>添加更多条件:
<add>
<add>```scss
<add>@mixin text-effect($val) {
<add> @if $val == danger {
<add> color: red;
<add> }
<add> @else if $val == alert {
<add> color: yellow;
<add> }
<add> @else if $val == success {
<add> color: green;
<add> }
<add> @else {
<add> color: black;
<add> }
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>border-stroke</code>的<code>mixin</code> ,它接受一个参数<code>$val</code> 。 <code>mixin</code>应使用<code>@if</code> , <code>@else if</code>和<code>@else</code>检查以下条件:
<del><blockquote>光 - 1px纯黑色<br>中等 - 3px纯黑色<br>重 - 6px纯黑色 </blockquote>
<del>如果<code>$val</code>不是<code>light</ code>,<code>medium</code>,或者<code>heavy</code>,则边框应该设置为<code>none</code>。
<add><section id='instructions'>
<add>创建一个名为<code>border-stroke</code>的<code>mixin</code>,它接受一个参数<code>$val</code>。<code>mixin</code>应使用<code>@if</code>,<code>@else if</code>和<code>@else</code>检查以下条件:
<add>
<add>```scss
<add>light - 1px solid black
<add>medium - 3px solid black
<add>heavy - 6px solid black
<add>```
<add>
<add>如果 <code>$val</code> 不是 <code>light</code>、<code>medium</code> 或者 <code>heavy</code>,border 应该设置为 <code>none</code>。
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的代码应该声明一个名为<code>border-stroke</code>的<code>mixin</code> ,它有一个名为<code>$val</code>的参数。
<add> - text: 你应该声明一个名为<code>border-stroke</code>的<code>mixin</code>,它有一个名为<code>$val</code>的参数。
<ide> testString: assert(code.match(/@mixin\s+?border-stroke\s*?\(\s*?\$val\s*?\)\s*?{/gi));
<del> - text: 你的<code>mixin</code>应该有一个<code>@if</code>语句来检查<code>$val</code>是否很亮,并将<code>border</code>设置为1px纯黑色。
<add> - text: <code>mixin</code>应该有一个<code>@if</code>语句来检查<code>$val</code>是否很轻,并将<code>border</code>设置为 1px 纯黑色。
<ide> testString: assert(code.match(/@if\s+?\$val\s*?===?\s*?light\s*?{\s*?border\s*?:\s*?1px\s+?solid\s+?black\s*?;\s*?}/gi));
<del> - text: 你的<code>mixin</code>应该有一个<code>@else if</code>语句来检查<code>$val</code>是否为中等,并将<code>border</code>设置为3px纯黑色。
<add> - text: <code>mixin</code>应该有一个<code>@else if</code>语句来检查<code>$val</code>是否中等,并设置<code>border</code>为3px 纯黑色。
<ide> testString: assert(code.match(/@else\s+?if\s+?\$val\s*?===?\s*?medium\s*?{\s*?border\s*?:\s*?3px\s+?solid\s+?black\s*?;\s*?}/gi));
<del> - text: 你的<code>mixin</code>应该有一个<code>@else if</code>语句来检查<code>$val</code>是否很重,并将<code>border</code>设置为6px纯黑色。
<add> - text: <code>mixin</code>应该有一个<code>@else if</code>语句来检查<code>$val</code>是否很重,并设置<code>border</code>为6px 纯黑色。
<ide> testString: assert(code.match(/@else\s+?if\s+?\$val\s*?===?\s*?heavy\s*?{\s*?border\s*?:\s*?6px\s+?solid\s+?black\s*?;\s*?}/gi));
<del> - text: 你的<code>mixin</code>应该有一个<code>@else</code>语句来设置<code>border</code>为none。
<add> - text: <code>mixin</code>应该有一个<code>@else</code>语句来将<code>border</code>设置为 none。
<ide> testString: assert(code.match(/@else\s*?{\s*?border\s*?:\s*?none\s*?;\s*?}/gi));
<ide>
<ide> ```
<ide> tests:
<ide> </style>
<ide>
<ide> <div id="box"></div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>```html
<add><style type='text/sass'>
<add> @mixin border-stroke($val) {
<add> @if $val == light {
<add> border: 1px solid black;
<add> }
<add> @else if $val == medium {
<add> border: 3px solid black;
<add> }
<add> @else if $val == heavy {
<add> border: 6px solid black;
<add> }
<add> @else {
<add> border: none;
<add> }
<add> }
<add>
<add>
<add> #box {
<add> width: 150px;
<add> height: 150px;
<add> background-color: red;
<add> @include border-stroke(medium);
<add> }
<add></style>
<add>
<add><div id="box"></div>
<ide> ```
<ide>
<del>/section>
<add></section> | 9 |
Javascript | Javascript | add pt-br for localization | cc64f19b947dd16718b5a8046a54190d0cd3e4bf | <ide><path>src/locale/pt-BR.js
<add>import "locale";
<add>
<add>d3.locale.pt_BR = d3.locale({
<add> decimal: ',',
<add> thousands: '.',
<add> grouping: [3],
<add> currency: ['R$', ''],
<add> dateTime: '%A, %e de %B de %Y. %X',
<add> date: '%d/%m/%Y',
<add> time: '%H:%M:%S',
<add> periods: ['AM', 'PM'],
<add> days: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
<add> shortDays: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
<add> months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
<add> shortMonths: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez']
<add>});
<ide><path>test/locale/locale-ptbr-test.js
<add>var vows = require("vows"),
<add> load = require("../load"),
<add> assert = require("../assert"),
<add> time = require("../time/time"),
<add> local = time.local;
<add>
<add>var suite = vows.describe("d3.locale");
<add>
<add>suite.addBatch({
<add> "locale": {
<add> topic: load("locale/pt-BR").expression("d3.locale.pt_BR"),
<add>
<add> "numberFormat": {
<add> topic: function(locale) {
<add> return locale.numberFormat;
<add> },
<add> "formats numbers": function(format) {
<add> var f = format(",.2f");
<add> assert.equal(f(12345.67), "12.345,67");
<add> },
<add> "formats currencies": function(format) {
<add> var f = format("$,.2f");
<add> assert.equal(f(12345.67), "R$12.345,67");
<add> },
<add> "formats currencies with SI-prefix notation and currency suffix": function(format) {
<add> var f = format("$,.4s");
<add> assert.equal(f(12345.67), "R$12,35k");
<add> }
<add> },
<add>
<add> "timeFormat": {
<add> topic: function(locale) {
<add> return locale.timeFormat;
<add> },
<add>
<add> "format": {
<add> "formats locale date and time": function(format) {
<add> var f = format("%c");
<add> assert.equal(f(local(1990, 0, 1)), "Segunda, 1 de Janeiro de 1990. 00:00:00");
<add> },
<add> "formats locale date": function(format) {
<add> var f = format("%x");
<add> assert.equal(f(local(1990, 0, 1)), "01/01/1990");
<add> },
<add> "formats locale time": function(format) {
<add> var f = format("%X");
<add> assert.equal(f(local(1990, 0, 1)), "00:00:00");
<add> },
<add> "formats abbreviated weekday": function(format) {
<add> var f = format("%a");
<add> assert.equal(f(local(1990, 0, 1)), "Seg");
<add> assert.equal(f(local(1990, 0, 2)), "Ter");
<add> assert.equal(f(local(1990, 0, 3)), "Qua");
<add> assert.equal(f(local(1990, 0, 4)), "Qui");
<add> assert.equal(f(local(1990, 0, 5)), "Sex");
<add> assert.equal(f(local(1990, 0, 6)), "Sáb");
<add> assert.equal(f(local(1990, 0, 7)), "Dom");
<add> },
<add> "formats weekday": function(format) {
<add> var f = format("%A");
<add> assert.equal(f(local(1990, 0, 1)), "Segunda");
<add> assert.equal(f(local(1990, 0, 2)), "Terça");
<add> assert.equal(f(local(1990, 0, 3)), "Quarta");
<add> assert.equal(f(local(1990, 0, 4)), "Quinta");
<add> assert.equal(f(local(1990, 0, 5)), "Sexta");
<add> assert.equal(f(local(1990, 0, 6)), "Sábado");
<add> assert.equal(f(local(1990, 0, 7)), "Domingo");
<add> },
<add> "formats abbreviated month": function(format) {
<add> var f = format("%b");
<add> assert.equal(f(local(1990, 0, 1)), "Jan");
<add> assert.equal(f(local(1990, 1, 1)), "Fev");
<add> assert.equal(f(local(1990, 2, 1)), "Mar");
<add> assert.equal(f(local(1990, 3, 1)), "Abr");
<add> assert.equal(f(local(1990, 4, 1)), "Mai");
<add> assert.equal(f(local(1990, 5, 1)), "Jun");
<add> assert.equal(f(local(1990, 6, 1)), "Jul");
<add> assert.equal(f(local(1990, 7, 1)), "Ago");
<add> assert.equal(f(local(1990, 8, 1)), "Set");
<add> assert.equal(f(local(1990, 9, 1)), "Out");
<add> assert.equal(f(local(1990, 10, 1)), "Nov");
<add> assert.equal(f(local(1990, 11, 1)), "Dez");
<add> },
<add> "formats month": function(format) {
<add> var f = format("%B");
<add> assert.equal(f(local(1990, 0, 1)), "Janeiro");
<add> assert.equal(f(local(1990, 1, 1)), "Fevereiro");
<add> assert.equal(f(local(1990, 2, 1)), "Março");
<add> assert.equal(f(local(1990, 3, 1)), "Abril");
<add> assert.equal(f(local(1990, 4, 1)), "Maio");
<add> assert.equal(f(local(1990, 5, 1)), "Junho");
<add> assert.equal(f(local(1990, 6, 1)), "Julho");
<add> assert.equal(f(local(1990, 7, 1)), "Agosto");
<add> assert.equal(f(local(1990, 8, 1)), "Setembro");
<add> assert.equal(f(local(1990, 9, 1)), "Outubro");
<add> assert.equal(f(local(1990, 10, 1)), "Novembro");
<add> assert.equal(f(local(1990, 11, 1)), "Dezembro");
<add> },
<add> "formats AM or PM": function(format) {
<add> var f = format("%p");
<add> assert.equal(f(local(1990, 0, 1, 0)), "AM");
<add> assert.equal(f(local(1990, 0, 1, 13)), "PM");
<add> }
<add> },
<add>
<add> "parse": {
<add> "parses locale date and time": function(format) {
<add> var p = format("%c").parse;
<add> assert.deepEqual(p("Segunda, 1 de Janeiro de 1990. 00:00:00"), local(1990, 0, 1));
<add> },
<add> "parses locale date": function(format) {
<add> var p = format("%x").parse;
<add> assert.deepEqual(p("01/01/1990"), local(1990, 0, 1));
<add> }
<add> }
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 2 |
Ruby | Ruby | fix deprecation warning in scaffold controllers | e84edf13c2984c071e91e747995075bd80b1c194 | <ide><path>railties/lib/rails/generators/active_model.rb
<ide> def initialize(name)
<ide>
<ide> # GET index
<ide> def self.all(klass)
<del> "#{klass}.all"
<add> "#{klass}.all.to_a"
<ide> end
<ide>
<ide> # GET show | 1 |
Javascript | Javascript | resolve more conflicts | 4963e37c83da93dcd377c3c4c5b6b05bfffdccb2 | <ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> var uvInfo = [];
<ide> var i = 0;
<del> while ( subNodes.LayerElementUV[ i ] ) {
<add> while ( subNodes.LayerElementUV[ i ] ){
<ide>
<del> uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
<del> i ++;
<add> uvInfo.push(getUVs( subNodes.LayerElementUV[ i ] ));
<add> i++;
<ide>
<ide> }
<ide> | 1 |
Javascript | Javascript | fix cidfonttype2 large cmap tables | e4e864766df1c2252197113378ad0e191665e219 | <ide><path>src/fonts.js
<ide> var Font = (function Font() {
<ide> }
<ide>
<ide> var glyphs = [], ids = [];
<del> var usedUnicodes = [], unusedUnicode = kCmapGlyphOffset;
<add> var usedUnicodes = [];
<ide> var cidToGidMap = properties.cidToGidMap;
<del> for (i = 1; i < numGlyphs; i++) {
<add> var unassignedUnicodeItems = [];
<add> for (var i = 1; i < numGlyphs; i++) {
<ide> var cid = cidToGidMap ? cidToGidMap.indexOf(i) : i;
<ide> var unicode = this.toUnicode[cid];
<ide> if (!unicode || isSpecialUnicode(unicode) ||
<ide> unicode in usedUnicodes) {
<del> // overriding the special special symbols mapping
<del> while (unusedUnicode in usedUnicodes)
<del> unusedUnicode++;
<del> this.toUnicode[cid] = unicode = unusedUnicode++;
<del> if (unusedUnicode >= kCmapGlyphOffset + kSizeOfGlyphArea) {
<del> // overflow of the user defined symblos range
<del> // using symbols that a little bit lower than this range
<del> unusedUnicode = kCmapGlyphOffset - numGlyphs;
<del> }
<add> unassignedUnicodeItems.push(i);
<add> continue;
<ide> }
<ide> usedUnicodes[unicode] = true;
<ide> glyphs.push({ unicode: unicode, code: cid });
<ide> ids.push(i);
<ide> }
<add> // checking if unassigned symbols will fit the user defined symbols
<add> // if those symbols too many, probably they will not be used anyway
<add> if (unassignedUnicodeItems.length <= kSizeOfGlyphArea) {
<add> var unusedUnicode = kCmapGlyphOffset;
<add> for (var j = 0, jj = unassignedUnicodeItems.length; j < jj; j++) {
<add> var i = unassignedUnicodeItems[j];
<add> var cid = cidToGidMap ? cidToGidMap.indexOf(i) : i;
<add> while (unusedUnicode in usedUnicodes)
<add> unusedUnicode++;
<add> var unicode = unusedUnicode++;
<add> this.toUnicode[cid] = unicode;
<add> usedUnicodes[unicode] = true;
<add> glyphs.push({ unicode: unicode, code: cid });
<add> ids.push(i);
<add> }
<add> }
<ide> cmap.data = createCMapTable(glyphs, ids);
<ide> } else {
<ide> var cmapTable = readCMapTable(cmap, font); | 1 |
Text | Text | make use .env file challenge clearer | 344c9afa80f64ef4620c64d0aa249543806b80d9 | <ide><path>curriculum/challenges/english/05-back-end-development-and-apis/basic-node-and-express/use-the-.env-file.md
<ide> Let's add an environment variable as a configuration option.
<ide>
<ide> Create a `.env` file in the root of your project directory, and store the variable `MESSAGE_STYLE=uppercase` in it.
<ide>
<del>Then, in the `/json` GET route handler you created in the last challenge, transform the response object's message to uppercase if `process.env.MESSAGE_STYLE` equals `uppercase`. The response object should either be `{"message": "Hello json"}` or `{"message": "HELLO JSON"}`, depending on the `MESSAGE_STYLE` value.
<add>Then, in the `/json` GET route handler you created in the last challenge access `process.env.MESSAGE_STYLE` and transform the response object's `message` to uppercase if the variable equals `uppercase`. The response object should either be `{"message": "Hello json"}` or `{"message": "HELLO JSON"}`, depending on the `MESSAGE_STYLE` value.
<ide>
<ide> **Note:** If you are using Replit, you cannot create a `.env` file. Instead, use the built-in <dfn>SECRETS</dfn> tab to add the variable.
<ide> | 1 |
Text | Text | add pr to release notes | bf79bc039570df2e75a6d53a07a08268edf99b4e | <ide><path>actionpack/CHANGELOG.md
<del>* Add `ActionController#helpers` to get access to the view context in the controller
<add>* Add `ActionController#helpers` to get access to the view context at the controller
<ide> level.
<ide>
<ide> *Rafael Mendonça França*
<ide><path>guides/source/5_0_release_notes.md
<ide> Please refer to the [Changelog][action-pack] for detailed changes.
<ide> ([Pull Request](https://github.com/rails/rails/pull/23827))
<ide>
<ide>
<add>* Add `ActionController#helpers` to get access to the view context
<add> at the controller level.
<add> ([Pull Request](https://github.com/rails/rails/pull/24866))
<add>
<ide> Action View
<ide> -------------
<ide> | 2 |
PHP | PHP | deprecate unused helper properties | 35cb88c3e1e276aac4fda7321a3b1747f4240db4 | <ide><path>src/View/Helper.php
<ide> class Helper implements EventListenerInterface
<ide> public $request;
<ide>
<ide> /**
<del> * Holds the fields ['field_name' => ['type' => 'string', 'length' => 100]],
<del> * primaryKey and validates ['field_name']
<add> * Unused.
<ide> *
<ide> * @var array
<add> * @deprecated 3.7.0 This property is unused and will be removed in 4.0.0.
<ide> */
<ide> public $fieldset = [];
<ide>
<ide> /**
<del> * Holds tag templates.
<add> * Unused.
<ide> *
<ide> * @var array
<add> * @deprecated 3.7.0 This property is unused and will be removed in 4.0.0.
<ide> */
<ide> public $tags = [];
<ide>
<ide> public function __debugInfo()
<ide> {
<ide> return [
<ide> 'helpers' => $this->helpers,
<del> 'fieldset' => $this->fieldset,
<del> 'tags' => $this->tags,
<ide> 'implementedEvents' => $this->implementedEvents(),
<ide> '_config' => $this->getConfig(),
<ide> ];
<ide><path>tests/TestCase/View/HelperTest.php
<ide> public function testDebugInfo()
<ide> 'Html',
<ide> 'TestPlugin.OtherHelper'
<ide> ],
<del> 'fieldset' => [],
<del> 'tags' => [],
<ide> 'implementedEvents' => [
<ide> ],
<ide> '_config' => [ | 2 |
Javascript | Javascript | support non-declared buffer.type | 9020017a802f693a1b00d28921af1b9b76c514c0 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> return _each( json.buffers, function ( buffer ) {
<ide>
<del> if ( buffer.type === 'arraybuffer' ) {
<add> if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
<ide>
<ide> return new Promise( function ( resolve ) {
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> } );
<ide>
<add> } else {
<add>
<add> console.warn( 'THREE.GLTFLoader: ' + buffer.type + ' buffer type is not supported' );
<add>
<ide> }
<ide>
<ide> } ); | 1 |
Go | Go | get child processes before main process die | 5a1e5cf8c9bff51f6314754c039bf7511e2fb613 | <ide><path>daemon/execdriver/native/driver.go
<ide> func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*o
<ide> return nil, err
<ide> }
<ide>
<add> processes, err := c.Processes()
<add>
<ide> process, err := os.FindProcess(pid)
<ide> s, err := process.Wait()
<ide> if err != nil { | 1 |
Text | Text | add react seoul 2017 to the conferences list | f76467e8e5fd01d6586cd0d506c0503f7d29ab38 | <ide><path>docs/community/conferences.md
<ide> October 25–27, Bratislava, Slovakia
<ide>
<ide> [Website](https://reactiveconf.com)
<ide>
<add>### React Seoul 2017
<add>November 4 in Seoul, South Korea
<add>
<add>[Website](http://seoul.reactjs.kr/en)
<add>
<ide> ### React Day Berlin
<ide> December 2, Berlin, Germany
<ide> | 1 |
PHP | PHP | correct unused attributes | 3d5e4aa88ac6d12cf469573abe4558a137e722fc | <ide><path>tests/test_app/TestApp/Controller/Component/BananaComponent.php
<ide> class BananaComponent extends Component {
<ide> */
<ide> public $testField = 'BananaField';
<ide>
<del>/**
<del> * startup method
<del> *
<del> * @param Event $event
<del> * @param Controller $controller
<del> * @return string
<del> */
<del> public function startup(Event $event) {
<del> $controller->bar = 'fail';
<del> }
<ide> }
<ide><path>tests/test_app/TestApp/Controller/Component/OrangeComponent.php
<ide> public function initialize(array $config) {
<ide> * startup method
<ide> *
<ide> * @param Event $event
<del> * @param Controller $controller
<ide> * @return string
<ide> */
<ide> public function startup(Event $event) {
<del> $controller->foo = 'pass';
<add> $this->Controller->foo = 'pass';
<ide> }
<ide> } | 2 |
Ruby | Ruby | fix the truffleruby implementation | 151ba1ab0c5acb191795c78d4a2974cd00df3a04 | <ide><path>activesupport/lib/active_support/descendants_tracker.rb
<ide> def [](object)
<ide> end
<ide>
<ide> def []=(object, _present)
<del> @map[object_id] = object
<add> @map[object.object_id] = object
<ide> end
<ide> end
<ide> WeakSet.new | 1 |
Text | Text | pull request template | 7f4115c0990b5121878e38069d386f168fac6b7b | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<del><!-- This line specifies which issue to close after the pull request is merged. -->
<del>Fixes #{issue number}
<add># What does this PR do?
<add>
<add><!--
<add>Congratulations! You've made it this far! You're not quite done yet though.
<add>
<add>Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.
<add>
<add>Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.
<add>
<add>Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
<add>-->
<add>
<add><!-- Remove if not applicable -->
<add>
<add>Fixes # (issue)
<add>
<add>
<add>## Before submitting
<add>- [ ] This PR fixes a typo or improves the docs (you can dimiss the other checks if that's the case).
<add>- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/master/CONTRIBUTING.md#start-contributing-pull-requests),
<add> Pull Request section?
<add>- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
<add> to the it if that's the case.
<add>- [ ] Did you make sure to update the documentation with your changes? Here are the
<add> [documentation guidelines](https://github.com/huggingface/transformers/tree/master/docs), and
<add> [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/master/docs#writing-source-documentation).
<add>- [ ] Did you write any new necessary tests?
<add>
<add>
<add>## Who can review?
<add>
<add>Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
<add>members/contributors which may be interested in your PR.
<add>
<add><!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @
<add>
<add> If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
<add> Please tag fewer than 3 people.
<add>
<add> albert, bert, GPT2, XLM: @LysandreJik
<add> tokenizers: @mfuntowicz
<add> Trainer: @sgugger
<add> Speed and Memory Benchmarks: @patrickvonplaten
<add> Model Cards: @julien-c
<add> Translation: @sshleifer
<add> Summarization: @sshleifer
<add> TextGeneration: @TevenLeScao
<add> examples/distillation: @VictorSanh
<add> nlp datasets: [different repo](https://github.com/huggingface/nlp)
<add> rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)
<add> Text Generation: @TevenLeScao
<add> Blenderbot, Bart, Marian, Pegasus: @sshleifer
<add> T5: @patrickvonplaten
<add> Longformer/Reformer: @patrickvonplaten
<add> TransfoXL/XLNet: @TevenLeScao
<add> examples/seq2seq: @sshleifer
<add> examples/bert-loses-patience: @JetRunner
<add> tensorflow: @jplu
<add> examples/token-classification: @stefan-it
<add> documentation: @sgugger
<add> -->
<ide>\ No newline at end of file | 1 |
PHP | PHP | allow customization of mail message building | 6535186b0f71a6b0cc2d8a821f3de209c05bcf4f | <ide><path>src/Illuminate/Auth/Notifications/ResetPassword.php
<ide> class ResetPassword extends Notification
<ide> */
<ide> public $token;
<ide>
<add> /**
<add> * The callback that should be used to build the mail message.
<add> *
<add> * @var \Closure|null
<add> */
<add> public static $toMailCallback;
<add>
<ide> /**
<ide> * Create a notification instance.
<ide> *
<ide> public function via($notifiable)
<ide> */
<ide> public function toMail($notifiable)
<ide> {
<add> if (static::$toMailCallback) {
<add> return call_user_func(static::$toMailCallback, $notifiable, $this->token);
<add> }
<add>
<ide> return (new MailMessage)
<ide> ->line('You are receiving this email because we received a password reset request for your account.')
<ide> ->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
<ide> ->line('If you did not request a password reset, no further action is required.');
<ide> }
<add>
<add> /**
<add> * Set a callback that should be used when building the notification mail message.
<add> *
<add> * @param \Closure $callback
<add> * @return void
<add> */
<add> public static function toMailUsing($callback)
<add> {
<add> static::$toMailCallback = $callback;
<add> }
<ide> } | 1 |
Ruby | Ruby | replace ui uses of 'folder' with 'directory' | 4ee255134d791ab79655422f9760a86b0dc55372 | <ide><path>Library/Homebrew/build.rb
<ide> def install f
<ide> if ARGV.flag? '--git'
<ide> system "git init"
<ide> system "git add -A"
<del> puts "This folder is now a git repo. Make your changes and then use:"
<add> puts "This directory is now a git repo. Make your changes and then use:"
<ide> puts " git diff | pbcopy"
<ide> puts "to copy the diff to the clipboard."
<ide> end
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def __check_subdir_access base
<ide> cant_read.sort!
<ide> if cant_read.length > 0
<ide> puts <<-EOS.undent
<del> Some folders in #{target} aren't writable.
<add> Some directories in #{target} aren't writable.
<ide> This can happen if you "sudo make install" software that isn't managed
<ide> by Homebrew. If a brew tries to add locale information to one of these
<del> folders, then the install will fail during the link step.
<add> directories, then the install will fail during the link step.
<ide> You should probably `chown` them:
<ide>
<ide> EOS
<ide> def __check_folder_access base, msg
<ide>
<ide> def check_access_pkgconfig
<ide> __check_folder_access 'lib/pkgconfig',
<del> 'If a brew tries to write a .pc file to this folder, the install will\n'+
<add> 'If a brew tries to write a .pc file to this directory, the install will\n'+
<ide> 'fail during the link step.'
<ide> end
<ide>
<ide> def check_access_include
<ide> __check_folder_access 'include',
<del> 'If a brew tries to write a header file to this folder, the install will\n'+
<add> 'If a brew tries to write a header file to this directory, the install will\n'+
<ide> 'fail during the link step.'
<ide> end
<ide>
<ide> def check_access_etc
<ide> __check_folder_access 'etc',
<del> 'If a brew tries to write a file to this folder, the install will\n'+
<add> 'If a brew tries to write a file to this directory, the install will\n'+
<ide> 'fail during the link step.'
<ide> end
<ide>
<ide> def check_access_share
<ide> __check_folder_access 'share',
<del> 'If a brew tries to write a file to this folder, the install will\n'+
<add> 'If a brew tries to write a file to this directory, the install will\n'+
<ide> 'fail during the link step.'
<ide> end
<ide>
<ide> def check_xcode_prefix
<ide> return if prefix.nil?
<ide> if prefix.to_s.match(' ')
<ide> puts <<-EOS.undent
<del> Xcode is installed to a folder with a space in the name.
<add> Xcode is installed to a directory with a space in the name.
<ide> This may cause some formulae, such as libiconv, to fail to build.
<ide>
<ide> EOS
<ide> def check_for_config_scripts
<ide>
<ide> unless config_scripts.empty?
<ide> puts <<-EOS.undent
<del> Some "config" scripts were found in your path, but not in system or Homebrew folders.
<add> Some "config" scripts were found in your path, but not in system or
<add> Homebrew directories.
<ide>
<del> `./configure` scripts often look for *-config scripts to determine if software packages
<del> are installed, and what additional flags to use when compiling and linking.
<add> `./configure` scripts often look for *-config scripts to determine if
<add> software packages are installed, and what additional flags to use when
<add> compiling and linking.
<ide>
<del> Having additional scripts in your path can confuse software installed via Homebrew if
<del> the config script overrides a system or Homebrew provided script of the same name.
<add> Having additional scripts in your path can confuse software installed via
<add> Homebrew if the config script overrides a system or Homebrew provided
<add> script of the same name.
<ide>
<ide> EOS
<ide>
<ide> def check_for_symlinked_cellar
<ide> which resolves to: #{HOMEBREW_CELLAR.realpath}
<ide>
<ide> The recommended Homebrew installations are either:
<del> (A) Have Cellar be a real folder inside of your HOMEBREW_PREFIX
<add> (A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX
<ide> (B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar".
<ide>
<ide> Older installations of Homebrew may have created a symlinked Cellar, but this can
<ide> def check_for_multiple_volumes
<ide>
<ide> unless where_cellar == where_temp
<ide> puts <<-EOS.undent
<del> Your Cellar & TEMP folders are on different volumes.
<add> Your Cellar and TEMP directories are on different volumes.
<ide>
<ide> OS X won't move relative symlinks across volumes unless the target file
<ide> already exists.
<ide>
<ide> Brews known to be affected by this are Git and Narwhal.
<ide>
<ide> You should set the "HOMEBREW_TEMP" environmental variable to a suitable
<del> folder on the same volume as your Cellar.
<add> directory on the same volume as your Cellar.
<ide>
<ide> EOS
<ide> end
<ide> def check_for_enthought_python
<ide> Enthought Python was found in your PATH.
<ide>
<ide> This can cause build problems, as this software installs its own
<del> copies of iconv and libxml2 into folders that are picked up by
<add> copies of iconv and libxml2 into directories that are picked up by
<ide> other build systems.
<ide>
<ide> EOS
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def check_PATH
<ide> def check_manpages
<ide> # Check for man pages that aren't in share/man
<ide> if (f.prefix+'man').exist?
<del> opoo 'A top-level "man" folder was found.'
<add> opoo 'A top-level "man" directory was found.'
<ide> puts "Homebrew requires that man pages live under share."
<ide> puts 'This can often be fixed by passing "--mandir=#{man}" to configure.'
<ide> @show_summary_heading = true
<ide> def check_manpages
<ide> def check_infopages
<ide> # Check for info pages that aren't in share/info
<ide> if (f.prefix+'info').exist?
<del> opoo 'A top-level "info" folder was found.'
<add> opoo 'A top-level "info" directory was found.'
<ide> puts "Homebrew suggests that info pages live under share."
<ide> puts 'This can often be fixed by passing "--infodir=#{info}" to configure.'
<ide> @show_summary_heading = true | 3 |
Python | Python | add test_connection to salesforcehook | ed26b86a506b07ecf66c314e5514bd906e608359 | <ide><path>airflow/providers/salesforce/hooks/salesforce.py
<ide> def object_to_df(
<ide> df["time_fetched_from_salesforce"] = fetched_time
<ide>
<ide> return df
<add>
<add> def test_connection(self):
<add> """Test the Salesforce connectivity"""
<add> try:
<add> self.describe_object("Account")
<add> status = True
<add> message = "Connection successfully tested"
<add> except Exception as e:
<add> status = False
<add> message = str(e)
<add>
<add> return status, message
<ide><path>tests/providers/salesforce/hooks/test_salesforce.py
<ide> def test_backcompat_prefix_both_prefers_short(self, mock_client):
<ide> username=None,
<ide> version="52.0",
<ide> )
<add>
<add> @patch(
<add> "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object",
<add> return_value={"fields": [{"name": "field_1"}, {"name": "field_2"}]},
<add> )
<add> def test_connection_success(self, mock_describe_object):
<add> hook = SalesforceHook("my_conn")
<add> status, msg = hook.test_connection()
<add> assert status is True
<add> assert msg == "Connection successfully tested"
<add>
<add> @patch(
<add> "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object",
<add> side_effect=Exception("Test"),
<add> )
<add> def test_connection_failure(self, mock_describe_object):
<add> hook = SalesforceHook("my_conn")
<add> status, msg = hook.test_connection()
<add> assert status is False
<add> assert msg == "Test" | 2 |
Python | Python | fix syntax error | 61a4ef0b4649583863fba9c4c3892a43ba9506ea | <ide><path>spacy/training/loggers.py
<ide> def log_step(info: Dict[str, Any]):
<ide> ) from None
<ide> scores = []
<ide> for col in score_cols:
<del> score = float(info["other_scores"].get(col, 0.0)))
<add> score = float(info["other_scores"].get(col, 0.0))
<ide> if col != "speed":
<ide> score *= 100
<del> scores.append("{0:.2f}".format(score)
<add> scores.append("{0:.2f}".format(score))
<ide> data = (
<ide> [info["epoch"], info["step"]]
<ide> + losses | 1 |
Go | Go | move replaceorappendenvvalues to container package | 7164b66cfc70b43bad98e156e72e305b66aa8ca4 | <ide><path>container/container_unix.go
<ide> import (
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/pkg/system"
<del> "github.com/docker/docker/utils"
<ide> "github.com/docker/docker/volume"
<ide> "github.com/opencontainers/runc/libcontainer/label"
<ide> "golang.org/x/sys/unix"
<ide> func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string
<ide> // because the env on the container can override certain default values
<ide> // we need to replace the 'env' keys where they match and append anything
<ide> // else.
<del> env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
<add> env = ReplaceOrAppendEnvValues(env, container.Config.Env)
<ide> return env
<ide> }
<ide>
<ide><path>container/container_windows.go
<ide> import (
<ide> "path/filepath"
<ide>
<ide> containertypes "github.com/docker/docker/api/types/container"
<del> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> // Container holds fields specific to the Windows implementation. See
<ide> func (container *Container) CreateDaemonEnvironment(_ bool, linkedEnv []string)
<ide> // because the env on the container can override certain default values
<ide> // we need to replace the 'env' keys where they match and append anything
<ide> // else.
<del> return utils.ReplaceOrAppendEnvValues(linkedEnv, container.Config.Env)
<add> return ReplaceOrAppendEnvValues(linkedEnv, container.Config.Env)
<ide> }
<ide>
<ide> // UnmountIpcMounts unmounts Ipc related mounts.
<add><path>container/env.go
<del><path>utils/utils.go
<del>package utils
<add>package container
<ide>
<ide> import (
<ide> "strings"
<add><path>container/env_test.go
<del><path>utils/utils_test.go
<del>package utils
<add>package container
<ide>
<ide> import "testing"
<ide>
<ide><path>daemon/exec.go
<ide> import (
<ide> "github.com/docker/docker/pkg/pools"
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/term"
<del> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> // Seconds to wait after sending TERM before trying KILL
<ide> func (d *Daemon) getActiveContainer(name string) (*container.Container, error) {
<ide>
<ide> // ContainerExecCreate sets up an exec in a running container.
<ide> func (d *Daemon) ContainerExecCreate(name string, config *types.ExecConfig) (string, error) {
<del> container, err := d.getActiveContainer(name)
<add> cntr, err := d.getActiveContainer(name)
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> func (d *Daemon) ContainerExecCreate(name string, config *types.ExecConfig) (str
<ide> execConfig.OpenStdin = config.AttachStdin
<ide> execConfig.OpenStdout = config.AttachStdout
<ide> execConfig.OpenStderr = config.AttachStderr
<del> execConfig.ContainerID = container.ID
<add> execConfig.ContainerID = cntr.ID
<ide> execConfig.DetachKeys = keys
<ide> execConfig.Entrypoint = entrypoint
<ide> execConfig.Args = args
<ide> execConfig.Tty = config.Tty
<ide> execConfig.Privileged = config.Privileged
<ide> execConfig.User = config.User
<ide>
<del> linkedEnv, err := d.setupLinkedContainers(container)
<add> linkedEnv, err := d.setupLinkedContainers(cntr)
<ide> if err != nil {
<ide> return "", err
<ide> }
<del> execConfig.Env = utils.ReplaceOrAppendEnvValues(container.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
<add> execConfig.Env = container.ReplaceOrAppendEnvValues(cntr.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
<ide> if len(execConfig.User) == 0 {
<del> execConfig.User = container.Config.User
<add> execConfig.User = cntr.Config.User
<ide> }
<ide>
<del> d.registerExecCommand(container, execConfig)
<add> d.registerExecCommand(cntr, execConfig)
<ide>
<del> d.LogContainerEvent(container, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
<add> d.LogContainerEvent(cntr, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
<ide>
<ide> return execConfig.ID, nil
<ide> } | 5 |
PHP | PHP | use specific ordering | 9038f11a2f6ab320940d6817e3d4b5c8230b11ec | <ide><path>lib/Cake/Test/TestCase/ORM/TableTest.php
<ide> public function testUpdateAll() {
<ide> $result = $table->updateAll($fields, ['id <' => 4]);
<ide> $this->assertTrue($result);
<ide>
<del> $result = $table->find('all')->select(['username'])->toArray();
<add> $result = $table->find('all')
<add> ->select(['username'])
<add> ->order(['id' => 'asc'])
<add> ->toArray();
<ide> $expected = array_fill(0, 3, $fields);
<ide> $expected[] = ['username' => 'garrett'];
<ide> $this->assertEquals($expected, $result); | 1 |
Javascript | Javascript | use native driver even if gestures are enabled | 4220063f8464a9778fd8470b3fb95fe502fb1bd0 | <ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStack.js
<ide> */
<ide> 'use strict';
<ide>
<del>const NativeAnimatedModule = require('NativeModules').NativeAnimatedModule;
<ide> const NavigationCard = require('NavigationCard');
<ide> const NavigationCardStackPanResponder = require('NavigationCardStackPanResponder');
<ide> const NavigationCardStackStyleInterpolator = require('NavigationCardStackStyleInterpolator');
<ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> {
<ide> _configureTransition = () => {
<ide> const isVertical = this.props.direction === 'vertical';
<ide> const animationConfig = {};
<del> if (
<del> !!NativeAnimatedModule
<del>
<del> // Gestures do not work with the current iteration of native animation
<del> // driving. When gestures are disabled, we can drive natively.
<del> && !this.props.enableGestures
<del>
<del> // Native animation support also depends on the transforms used:
<del> && NavigationCardStackStyleInterpolator.canUseNativeDriver(isVertical)
<del> ) {
<add> if (NavigationCardStackStyleInterpolator.canUseNativeDriver(isVertical)) {
<ide> animationConfig.useNativeDriver = true;
<ide> }
<ide> return animationConfig; | 1 |
Ruby | Ruby | remove some unneeded `require`s | 6e20d2758281a9f331edecc56b6dd4f8df86f277 | <ide><path>Library/Homebrew/extend/os/linux/system_config.rb
<ide> # typed: true
<ide> # frozen_string_literal: true
<ide>
<del>require "formula"
<ide> require "os/linux/glibc"
<ide> require "system_command"
<ide>
<ide> def dump_verbose_config(out = $stdout)
<ide> out.puts "/usr/bin/gcc: #{host_gcc_version}"
<ide> out.puts "/usr/bin/ruby: #{host_ruby_version}" if RUBY_PATH != HOST_RUBY_PATH
<ide> ["glibc", "gcc", "xorg"].each do |f|
<del> out.puts "#{f}: #{formula_linked_version f}"
<add> out.puts "#{f}: #{formula_linked_version(f)}"
<ide> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/uninstall.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "keg"
<del>require "formula"
<ide>
<ide> module Homebrew
<ide> # Helper module for uninstalling kegs. | 2 |
Ruby | Ruby | remove debug statements | 370ef3e8bbafb5076737f9d9a79d83f70123a228 | <ide><path>activerecord/test/cases/dirty_test.rb
<ide> def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_ma
<ide> target = Class.new(ActiveRecord::Base)
<ide> target.table_name = 'pirates'
<ide>
<del> pirate = target.create
<del> p pirate.created_on
<add> pirate = target.create!
<ide> pirate.created_on = pirate.created_on
<del> p pirate.created_on
<del> p pirate.changes
<ide> assert !pirate.created_on_changed?
<ide> end
<ide> end | 1 |
Java | Java | fix copyright year & method names in spring-test | 8a37521a3cd5dc0d51599abf9824c35513816fbb | <ide><path>spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
<ide>
<ide> /**
<del> * JUnit 4 based integration test which verifies correct {@link ContextCache
<add> * JUnit 4 based integration test which verifies correct {@linkplain ContextCache
<ide> * application context caching} in conjunction with the
<ide> * {@link SpringJUnit4ClassRunner} and the {@link DirtiesContext
<ide> * @DirtiesContext} annotation at the class level.
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public static final class TimedSpringRunnerTestCase {
<ide>
<ide> // Should Pass.
<ide> @Test(timeout = 2000)
<del> public void testJUnitTimeoutWithNoOp() {
<add> public void jUnitTimeoutWithNoOp() {
<ide> /* no-op */
<ide> }
<ide>
<ide> // Should Pass.
<ide> @Test
<ide> @Timed(millis = 2000)
<del> public void testSpringTimeoutWithNoOp() {
<add> public void springTimeoutWithNoOp() {
<ide> /* no-op */
<ide> }
<ide>
<ide> // Should Fail due to timeout.
<ide> @Test(timeout = 10)
<del> public void testJUnitTimeoutWithOneSecondWait() throws Exception {
<add> public void jUnitTimeoutWithSleep() throws Exception {
<ide> Thread.sleep(20);
<ide> }
<ide>
<ide> // Should Fail due to timeout.
<ide> @Test
<ide> @Timed(millis = 10)
<del> public void testSpringTimeoutWithOneSecondWait() throws Exception {
<add> public void springTimeoutWithSleep() throws Exception {
<ide> Thread.sleep(20);
<ide> }
<ide>
<ide> // Should Fail due to duplicate configuration.
<ide> @Test(timeout = 200)
<ide> @Timed(millis = 200)
<del> public void testSpringAndJUnitTimeout() {
<add> public void springAndJUnitTimeouts() {
<ide> /* no-op */
<ide> }
<ide> } | 3 |
Python | Python | fix typo in app_ctx_globals_class doc in app.py | 1d49343bb19933f5f8057a548cb69657d8cbd699 | <ide><path>flask/app.py
<ide> class Flask(_PackageBoundObject):
<ide> #:
<ide> #: 1. Store arbitrary attributes on flask.g.
<ide> #: 2. Add a property for lazy per-request database connectors.
<del> #: 3. Return None instead of AttributeError on expected attributes.
<add> #: 3. Return None instead of AttributeError on unexpected attributes.
<ide> #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
<ide> #:
<ide> #: In Flask 0.9 this property was called `request_globals_class` but it | 1 |
Text | Text | add changelog entry for references statements | 17d2115e3df6caf15d554b44e28177069fa3ed5b | <ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add `add_reference` and `remove_reference` schema statements. Aliases, `add_belongs_to`
<add> and `remove_belongs_to` are acceptable. References are reversible.
<add> Examples:
<add>
<add> # Create a user_id column
<add> add_reference(:products, :user)
<add> # Create a supplier_id, supplier_type columns and appropriate index
<add> add_reference(:products, :supplier, polymorphic: true, index: true)
<add> # Remove polymorphic reference
<add> remove_reference(:products, :supplier, polymorphic: true)
<add>
<add> *Aleksey Magusev*
<add>
<ide> * Add `:default` and `:null` options to `column_exists?`.
<ide>
<ide> column_exists?(:testings, :taggable_id, :integer, null: false) | 1 |
Python | Python | add dispatch to build process | f2cb33bcf60e72924b46dd652af64d0af8da2508 | <ide><path>numpy/core/code_generators/generate_umath.py
<ide> def english_upper(s):
<ide> Ufunc(2, 1, None, # One is only a unit to the right, not the left
<ide> docstrings.get('numpy.core.umath.floor_divide'),
<ide> 'PyUFunc_DivisionTypeResolver',
<del> TD(intfltcmplx),
<add> TD(intfltcmplx, cfunc_alias='divide', dispatch=[('loops_arithmetic', 'BHILQ')]),
<ide> [TypeDescription('m', FullTypeDescr, 'mq', 'm'),
<ide> TypeDescription('m', FullTypeDescr, 'md', 'm'),
<ide> TypeDescription('m', FullTypeDescr, 'mm', 'q'),
<ide><path>numpy/core/setup.py
<ide> def generate_umath_c(ext, build_dir):
<ide> join('src', 'umath', 'loops.c.src'),
<ide> join('src', 'umath', 'loops_unary_fp.dispatch.c.src'),
<ide> join('src', 'umath', 'loops_arithm_fp.dispatch.c.src'),
<add> join('src', 'umath', 'loops_arithmetic.dispatch.c.src'),
<ide> join('src', 'umath', 'loops_trigonometric.dispatch.c.src'),
<ide> join('src', 'umath', 'loops_exponent_log.dispatch.c.src'),
<ide> join('src', 'umath', 'matmul.h.src'), | 2 |
Text | Text | add onboarding resources | 7a3ed9822941173669a89dba1d0b58e1b3c3a1ec | <ide><path>doc/onboarding-extras.md
<add>## Who to CC in issues
<add>
<add>* `lib/buffer`: @trevnorris
<add>* `lib/child_process`: @cjihrig, @bnoordhuis, @piscisaereus
<add>* `lib/cluster`: @cjihrig, @bnoordhuis, @piscisaereus
<add>* `lib/{crypto,tls,https}`: @indutny, @shigeki, @nodejs/crypto
<add>* `lib/domains`: @misterdjules
<add>* `lib/{_}http{*}`: @indutny, @bnoordhuis, @nodejs/http
<add>* `lib/net`: @indutny, @bnoordhuis, @piscisaereus, @chrisdickinson, @nodejs/streams
<add>* `lib/{_}stream{s|*}`: @nodejs/streams
<add>* `lib/repl`: @fishrock123
<add>* `lib/timers`: @fishrock123, @misterdjules
<add>* `lib/zlib`: @indutny, @bnoordhuis
<add>
<add>* `src/async-wrap.*`: @trevnorris
<add>* `src/node_crypto.*`: @indutny, @shigeki, @nodejs/crypto
<add>
<add>* `test/*`: @nodejs/testing, @trott
<add>
<add>* `tools/eslint`, `.eslintrc`: @silverwind, @trott
<add>
<add>* upgrading v8: @bnoordhuis / @targos / @ofrobots
<add>* upgrading npm: @thealphanerd, @fishrock123
<add>
<add>
<add>When things need extra attention, are controversial, or `semver-major`: @nodejs/ctc
<add>
<add>If you cannot find who to cc for a file, `git shortlog -n -s <file>` may help.
<add>
<add>
<add>## Labels
<add>
<add>### By Subsystem
<add>
<add>We generally sort issues by a concept of "subsystem" so that we know what part(s) of the codebase it touches.
<add>
<add>**Subsystems generally are**:
<add>
<add>* `lib/*.js`
<add>* `doc`, `build`, `tools`, `test`, `deps`, `lib / src` (special), and there may be others.
<add>* `meta` for anything non-code (process) related
<add>
<add>There may be more than one subsystem valid for any particular issue / PR.
<add>
<add>
<add>### General
<add>
<add>Please use these when possible / appropriate
<add>
<add>* `confirmed-bug` - Bugs you have verified exist
<add>* `discuss` - Things that need larger discussion
<add>* `feature request` - Any issue that requests a new feature (usually not PRs)
<add>* `good first contribution` - Issues suitable for newcomers to process
<add>
<add>* `semver-{minor,major}`
<add> * be conservative – that is, if a change has the remote *chance* of breaking something, go for semver-major
<add> * when adding a semver label, add a comment explaining why you're adding it
<add> * minor vs. patch: roughly: "does it add a new method / does it add a new section to the docs"
<add> * major vs. everything else: run last versions tests against this version, if they pass, **probably** minor or patch
<add> * A breaking change helper ([full source](https://gist.github.com/chrisdickinson/ba532fa0e4e243fb7b44)):
<add> ```
<add> git checkout $(git show -s --pretty='%T' $(git show-ref -d $(git describe --abbrev=0) | tail -n1 | awk '{print $1}')) -- test; make -j8 test
<add> ```
<add>
<add>
<add>### Other Labels
<add>
<add>* Operating system labels
<add> * `os x`, `windows`, `solaris`
<add> * No linux, linux is the implied default
<add>* Architecture labels
<add> * `arm`, `mips`
<add> * No x86{_64}, since that is the implied default
<add>* `lts-agenda`, `lts-watch-v*`
<add> * tag things that should be discussed to go into LTS or should go into a specific LTS branch
<add> * (usually only semver-patch things)
<add> * will come more naturally over time
<add>
<add>
<add>## Updating Node.js from Upstream
<add>
<add>* `git remote add upstream git://github.com/nodejs/node.git`
<add>
<add>to update from nodejs/node:
<add>* `git checkout master`
<add>* `git remote update -p` OR `git fetch --all` (I prefer the former)
<add>* `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`)
<add>
<add>
<add>## If `git am` fails
<add>
<add>* if `git am` fails – use `git am --abort`
<add> * this usually means the PR needs updated
<add> * prefer to make the originating user update the code, since they have it fresh in mind
<add>* first, reattempt with `git am -3` (3-way merge)`
<add>* if `-3` still fails, and you need to get it merged:
<add> * `git fetch origin pull/N/head:pr-N && git checkout pr-N && git rebase master`
<add>
<add>
<add>## best practices
<add>
<add>* commit often, out to your github fork (origin), open a PR
<add>* when making PRs make sure to spend time on the description:
<add> * every moment you spend writing a good description quarters the amount of time it takes to understand your code.
<add>* usually prefer to only squash at the *end* of your work, depends on the change
<ide><path>doc/onboarding.md
<add>## pre-setup
<add>
<add>Ensure everyone is added to https://github.com/orgs/nodejs/teams/collaborators
<add>
<add>
<add>## onboarding to nodejs
<add>
<add>### intros
<add>
<add>
<add>### **thank you** for doing this
<add>
<add> * going to cover four things:
<add> * local setup
<add> * some project goals & values
<add> * issues, labels, and reviewing code
<add> * merging code
<add>
<add>
<add>### setup:
<add>
<add> * notifications setup
<add> * use https://github.com/notifications or set up email
<add> * watching the main repo will flood your inbox, so be prepared
<add>
<add>
<add> * git:
<add> * make sure you have whitespace=fix: `git config --global --add core.whitespace fix`
<add> * usually PR from your own github fork
<add> * [**See "Updating Node.js from Upstream"**](./onboarding-extras.md#updating-nodejs-from-upstream)
<add> * make new branches for all commits you make!
<add>
<add>
<add> * `#node-dev` on `chat.freenode.net` is the best place to interact with the CTC / other collaborators
<add>
<add>
<add>### a little deeper about the project
<add>
<add> * collaborators are effectively part owners
<add> * the project has the goals of its contributors
<add>
<add>
<add> * but, there are some higher-level goals and values
<add> * not everything belongs in core (if it can be done reasonably in userland, let it stay in userland)
<add> * empathy towards users matters (this is in part why we onboard people)
<add> * generally: try to be nice to people
<add>
<add>
<add>### managing the issue tracker
<add>
<add> * you have (mostly) free rein – don't hesitate to close an issue if you are confident that it should be closed
<add> * this will come more naturally over time
<add> * IMPORTANT: be nice about closing issues, let people know why, and that issues and PRs can be reopened if necessary
<add> * Still need to follow the Code of Conduct.
<add>
<add>
<add> * labels:
<add> * generally sort issues by a concept of "subsystem" so that we know what part(s) of the codebase it touches, though there are also other useful labels.
<add> * [**See "Labels"**](./onboarding-extras.md#labels)
<add> * `ctc-agenda` if a topic is controversial or isn't coming to a conclusion after an extended time.
<add> * `semver-{minor,major}`:
<add> * be conservative – that is, if a change has the remote *chance* of breaking something, go for `semver-major`
<add> * when adding a semver label, add a comment explaining why you're adding it
<add> * it's cached locally in your brain at that moment!
<add>
<add>
<add> * Notifying humans
<add> * [**See "Who to CC in issues"**](./onboarding-extras.md#who-to-cc-in-issues)
<add> * will also come more naturally over time
<add>
<add>
<add> * reviewing:
<add> * primary goal is for the codebase to improve
<add> * secondary (but not far off) is for the person submitting code to succeed
<add> * helps grow the community
<add> * and draws new people into the project
<add> * Review a bit at a time. It is **very important** to not overwhelm newer people.
<add> * it is tempting to micro-optimize / make everything about relative perf,
<add> don't succumb to that temptation. we change v8 a lot more often now, contortions
<add> that are zippy today may be unnecessary in the future
<add> * be aware: your opinion carries a lot of weight!
<add> * nits are fine, but try to avoid stalling the PR
<add> * note that they are nits when you comment
<add> * if they really are stalling nits, fix them yourself on merge (but try to let PR authors know they can fix these)
<add> * improvement doesn't have to come all at once
<add> * minimum wait for comments time
<add> * There is a minimum waiting time which we try to respect for non-trivial changes, so that people who may have important input in such a distributed project are able to respond.
<add> * It may help to set time limits and expectations:
<add> * the collaborators are very distributed so it is unlikely that they will be looking at stuff the same time as you are.
<add> * before merging code: give folks at least one working day to respond: "If no one objects, tomorrow at <time> I'll merge this in."
<add> * please always either specify your timezone, or use UTC time
<add> * set reminders
<add> * check in on the code every once in a while (set reminders!)
<add> * 48 hours for non-trivial changes, and 72 hours on weekends.
<add> * if a PR is abandoned, check if they'd mind if you took it over (especially if it just has nits left)
<add> * you have the power to `LGTM` another collaborator or TSC / CTC members' work
<add>
<add>
<add> * what belongs in node:
<add> * opinions vary, but I find the following helpful:
<add> * if node itself needs it (due to historic reasons), then it belongs in node
<add> * that is to say, url is there because of http, freelist is there because of http, et al
<add> * also, things that cannot be done outside of core, or only with significant pain (example: async-wrap)
<add>
<add>
<add> * CI testing:
<add> * lives here: https://ci.nodejs.org/
<add> * not automatically run - some of the platforms we test do not have full sandboxing support so we need to ensure what we run on it isn't potentially malicious
<add> * make sure to log in – we use github authentication so it should be seamless
<add> * go to "node-test-pull-request" and "Build with parameters"
<add> * fill in the pull request number without the `#`, and check the verification that you have reviewed the code for potential malice
<add> * The other options shouldn't need to be adjusted in most cases.
<add> * link to the CI run in the PR by commenting "CI: <ci run link>"
<add>
<add>
<add>### process for getting code in:
<add>
<add> * the collaborator guide is a great resource: https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md#technical-howto
<add>
<add>
<add> * no one (including TSC or CTC members) pushes directly to master without review
<add> * an exception is made for release commits only
<add>
<add>
<add> * one "LGTM" is usually sufficient, except for semver-major changes
<add> * the more the better
<add> * semver-major (breaking) changes must be reviewed in some form by the CTC
<add>
<add>
<add> * be sure to wait before merging non-trivial changes
<add> * 48 hours for non-trivial changes, and 72 hours on weekends.
<add>
<add>
<add> * **make sure to run the PR through CI before merging!** (Except for documentation PRs)
<add>
<add>
<add> * once code is ready to go in:
<add> * [**See "Landing PRs"**](#landing-prs) below
<add>
<add>
<add> * what if something goes wrong?
<add> * ping a CTC member
<add> * `#node-dev` on freenode
<add> * force-pushing to fix things after is allowed for ~10 minutes, be sure to notify people in IRC if you need to do this, but avoid it
<add> * Info on PRs that don't like to apply found under [**"If `git am` fails"**](./onboarding-extras.md#if-git-am-fails).
<add>
<add>
<add>### Landing PRs
<add>
<add>* Please never use GitHub's green "Merge Pull Request" button.
<add> * If you do, please force-push removing the merge.
<add>
<add>Update your `master` branch (or whichever branch you are landing on, almost always `master`)
<add>
<add>* [**See "Updating Node.js from Upstream"**](./onboarding-extras.md#updating-nodejs-from-upstream)
<add>
<add>Landing a PR
<add>
<add>* if it all looks good, `curl -L 'url-of-pr.patch' | git am`
<add>* `git rebase -i upstream/master`
<add>* squash into logical commits if necessary
<add>* `./configure && make -j8 test` (`-j8` builds node in parallel with 8 threads. adjust to the number of cores (or processor-level threads) your processor has (or slightly more) for best results.)
<add>* Amend the commit description
<add> * commits should follow `subsystem[,subsystem]: small description\n\nbig description\n\n<metadata>`
<add> * first line 50 columns, all others 72
<add> * add metadata:
<add> * `Fixes: <full-issue-url>`
<add> * `Reviewed-By: human <email>`
<add> * Easiest to use `git log` then do a search
<add> * (`/Name` + `enter` (+ `n` as much as you need to) in vim)
<add> * `PR-URL: <full-pr-url>`
<add>* `git push upstream master`
<add> * close the original PR with "Landed in `<commit hash>`".
<add>
<add>
<add>### exercise: make PRs adding yourselves to the README.
<add>
<add> * Example: https://github.com/nodejs/node/commit/7b09aade8468e1c930f36b9c81e6ac2ed5bc8732
<add> * to see full URL: `git log 7b09aade8468e1c930f36b9c81e6ac2ed5bc8732 -1`
<add> * Collaborators in alphabetical order by username
<add> * Label your pull request with the `doc` subsystem label
<add> * If you would like to run CI on your PR, feel free to
<add> * Make sure to added the `PR-URL: <full-pr-url>`!
<add>
<add>
<add>### final notes:
<add>
<add> * don't worry about making mistakes: everybody makes them, there's a lot to internalize and that takes time (and we recognize that!)
<add> * very few (no?) mistakes are unrecoverable
<add> * the existing node committers trust you and are grateful for your help!
<add> * other repos:
<add> * https://github.com/nodejs/dev-policy
<add> * https://github.com/nodejs/NG
<add> * https://github.com/nodejs/api
<add> * https://github.com/nodejs/build
<add> * https://github.com/nodejs/docs
<add> * https://github.com/nodejs/nodejs.org
<add> * https://github.com/nodejs/readable-stream
<add> * https://github.com/nodejs/LTS | 2 |
Mixed | Ruby | remove redundant files | 198b7ade596813ff2b01cc885ad3aab58c1550d1 | <ide><path>scripts/README.md
<del># 0.0.1-API-Parser
<del>
<del>Parser for fixing this: https://github.com/Homebrew/brew/issues/5725
<del>
<del>## Overview
<del>
<del>Homebrew is used to install software (packages). Homebrew uses 'formulae' to determine how a package is installed.
<del>This project will automatically check which packages have had newer versions released, whether the package has an open PR on homebrew, and display the results.
<del>
<del>## High-level Solution
<del>
<del>- Fetch latest package version information from [repology.org](https://repology.org/) and store on file system.
<del>- Fetch Homebrew Formulae information from [HomeBrew Formulae](https://formulae.brew.sh)
<del>- Compare Current Homebrew Formulae version numbers and those coming from Repology's API and Livecheck.
<del>- Determine whether package has open PR.
<del>- Display results.
<del>
<del>## Details
<del>
<del>- This project can be run automatically at set intervals via GitHub Actions.
<del>- Executing `ruby printPackageUpdates.rb` from the command line will query
<del> both the Repology and Homebrew APIs. Homebrew's current version of each
<del> package will be compared to the latest version of the package, per Repology's response.
<del>- Homebrew's livecheck is also queried for each package, and that data is parsed, if available.
<del>- Checks whether there is open PR for package.
<del>- Each outdated package will be displayed to the console like so:
<del>- Note that some packages will not be included in the Livecheck response. Those will have a 'Livecheck latest:' value of 'Not found'.
<del>
<del>```
<del>Package: openclonk
<del>Brew current: 7.0
<del>Repology latest: 8.1
<del>Livecheck latest: 8.1
<del>Has Open PR?: true
<del>
<del>Package: openjdk
<del>Brew current: 13.0.2+8
<del>Repology latest: 15.0.0.0~14
<del>Livecheck latest: Not found.
<del>Has Open PR?: false
<del>
<del>Package: opentsdb
<del>Brew current: 2.3.1
<del>Repology latest: 2.4.0
<del>Livecheck latest: 2.4.0
<del>Has Open PR?: true
<del>```
<ide><path>scripts/helpers/api_parser.rb
<del>require 'net/http'
<del>require 'json'
<del>
<del>require_relative 'brew_commands'
<del>require_relative 'homebrew_formula'
<del>
<del>class ApiParser
<del> def call_api(url)
<del> puts "- Calling API #{url}"
<del> uri = URI(url)
<del> response = Net::HTTP.get(uri)
<del>
<del> puts "- Parsing response"
<del> JSON.parse(response)
<del> end
<del>
<del> def query_repology_api(last_package_in_response = '')
<del> url = 'https://repology.org/api/v1/projects/' + last_package_in_response + '?inrepo=homebrew&outdated=1'
<del>
<del> self.call_api(url)
<del> end
<del>
<del> def parse_repology_api()
<del> puts "\n-------- Query outdated packages from Repology --------"
<del> page_no = 1
<del> puts "\n- Paginating repology api page: #{page_no}"
<del>
<del> outdated_packages = self.query_repology_api('')
<del> last_pacakge_index = outdated_packages.size - 1
<del> response_size = outdated_packages.size
<del>
<del> while response_size > 1 do
<del> page_no += 1
<del> puts "\n- Paginating repology api page: #{page_no}"
<del>
<del> last_package_in_response = outdated_packages.keys[last_pacakge_index]
<del> response = self.query_repology_api("#{last_package_in_response}/")
<del>
<del> response_size = response.size
<del> outdated_packages.merge!(response)
<del> last_pacakge_index = outdated_packages.size - 1
<del> end
<del>
<del> puts "\n- #{outdated_packages.size} outdated pacakges identified by repology"
<del> outdated_packages
<del> end
<del>
<del> def query_homebrew
<del> puts "\n-------- Get Homebrew Formulas --------"
<del> self.call_api('https://formulae.brew.sh/api/formula.json')
<del> end
<del>
<del> def parse_homebrew_formulas()
<del> formulas = self.query_homebrew()
<del> parsed_homebrew_formulas = {}
<del>
<del> formulas.each do |formula|
<del> parsed_homebrew_formulas[formula['name']] = {
<del> "fullname" => formula["full_name"],
<del> "oldname" => formula["oldname"],
<del> "version" => formula["versions"]['stable'],
<del> "download_url" => formula["urls"]['stable']['url'],
<del> }
<del> end
<del>
<del> parsed_homebrew_formulas
<del> end
<del>
<del> def validate_packages(outdated_repology_packages, brew_formulas)
<del> puts "\n-------- Verify Outdated Repology packages as Homebrew Formulas --------"
<del> packages = {}
<del>
<del> outdated_repology_packages.each do |package_name, repo_using_package|
<del> # Identify homebrew repo
<del> repology_homebrew_repo = repo_using_package.select { |repo| repo['repo'] == 'homebrew' }[0]
<del> next if repology_homebrew_repo.empty?
<del>
<del> latest_version = nil
<del>
<del> # Identify latest version amongst repos
<del> repo_using_package.each do |repo|
<del> latest_version = repo['version'] if repo['status'] == 'newest'
<del> end
<del>
<del> repology_homebrew_repo['latest_version'] = latest_version if latest_version
<del> homebrew_package_details = brew_formulas[repology_homebrew_repo['srcname']]
<del>
<del> # Format package
<del> packages[repology_homebrew_repo['srcname']] = format_package(homebrew_package_details, repology_homebrew_repo)
<del> end
<del>
<del> packages
<del> end
<del>
<del>
<del> def format_package(homebrew_details, repology_details)
<del> puts "- Formatting package: #{repology_details['srcname']}"
<del>
<del> homebrew_formula = HomebrewFormula.new
<del> new_download_url = homebrew_formula.generate_new_download_url(homebrew_details['download_url'], homebrew_details['version'], repology_details['latest_version'])
<del>
<del> brew_commands = BrewCommands.new
<del> livecheck_response = brew_commands.livecheck_check_formula(repology_details['srcname'])
<del> has_open_pr = brew_commands.check_for_open_pr(repology_details['srcname'], new_download_url)
<del>
<del> formatted_package = {
<del> 'fullname'=> homebrew_details['fullname'],
<del> 'repology_version' => repology_details['latest_version'],
<del> 'homebrew_version' => homebrew_details['version'],
<del> 'livecheck_latest_version' => livecheck_response['livecheck_latest_version'],
<del> 'current_download_url' => homebrew_details['download_url'],
<del> 'latest_download_url' => new_download_url,
<del> 'repology_latest_version' => repology_details['latest_version'],
<del> 'has_open_pr' => has_open_pr
<del> }
<del>
<del> formatted_package
<del> end
<del>
<del> def display_version_data(outdated_packages)
<del> puts "==============Formatted outdated packages============\n"
<del>
<del> outdated_packages.each do |package_name, package_details|
<del> puts ""
<del> puts "Package: #{package_name}"
<del> puts "Brew current: #{package_details['homebrew_version']}"
<del> puts "Repology latest: #{package_details['repology_version']}"
<del> puts "Livecheck latest: #{package_details['livecheck_latest_version']}"
<del> puts "Has Open PR?: #{package_details['has_open_pr']}"
<del> end
<del> end
<del>
<del>end
<ide><path>scripts/helpers/parsed_file.rb
<del>require 'fileutils'
<del>
<del>class ParsedFile
<del>
<del> def get_latest_file(directory)
<del> puts "- retrieving latest file in directory: #{directory}"
<del> Dir.glob("#{directory}/*").max_by(1) {|f| File.mtime(f)}[0]
<del> end
<del>
<del> def save_to(directory, data)
<del> # Create directory if does not exist
<del> FileUtils.mkdir_p directory unless Dir.exists?(directory)
<del>
<del> puts "- Generating datetime stamp"
<del> #Include time to the filename for uniqueness when fetching multiple times a day
<del> date_time = Time.new.strftime("%Y-%m-%dT%H_%M_%S")
<del>
<del> # Writing parsed data to file
<del> puts "- Writing data to file"
<del> File.write("#{directory}/#{date_time}.txt", data)
<del> end
<del>
<del>end
<ide>\ No newline at end of file | 3 |
Ruby | Ruby | add failing test for | 73d8a90bee79106c965ad35151870941ab38d951 | <ide><path>actionpack/test/dispatch/routing_test.rb
<ide> def test_absolute_controller_namespace
<ide> assert_equal '/foo', foo_root_path
<ide> end
<ide>
<add> def test_trailing_slash
<add> draw do
<add> resources :streams
<add> end
<add>
<add> get '/streams'
<add> assert @response.ok?, 'route without trailing slash should work'
<add>
<add> get '/streams/'
<add> assert @response.ok?, 'route with trailing slash should work'
<add>
<add> get '/streams?foobar'
<add> assert @response.ok?, 'route without trailing slash and with QUERY_STRING should work'
<add>
<add> get '/streams/?foobar'
<add> assert @response.ok?, 'route with trailing slash and with QUERY_STRING should work'
<add> end
<add>
<ide> private
<ide>
<ide> def draw(&block) | 1 |
Text | Text | remove deprecated file-loader | 0b16b530100319f160ca1360b9ee9e7eb2a76530 | <ide><path>README.md
<ide> or are automatically applied via regex from your webpack configuration.
<ide>
<ide> #### Files
<ide>
<del>| Name | Status | Install Size | Description |
<del>| :-----------------: | :---------: | :----------: | :------------------------------------------------------------------- |
<del>| [val-loader][val] | ![val-npm] | ![val-size] | Executes code as module and considers exports as JS code |
<del>| [file-loader][file] | ![file-npm] | ![file-size] | Emits the file into the output folder and returns the (relative) url |
<del>
<del>[raw]: https://github.com/webpack-contrib/raw-loader
<del>[raw-npm]: https://img.shields.io/npm/v/raw-loader.svg
<del>[raw-size]: https://packagephobia.com/badge?p=raw-loader
<add>| Name | Status | Install Size | Description |
<add>| :---------------: | :--------: | :----------: | :------------------------------------------------------- |
<add>| [val-loader][val] | ![val-npm] | ![val-size] | Executes code as module and considers exports as JS code |
<add>
<ide> [val]: https://github.com/webpack-contrib/val-loader
<ide> [val-npm]: https://img.shields.io/npm/v/val-loader.svg
<ide> [val-size]: https://packagephobia.com/badge?p=val-loader
<del>[url]: https://github.com/webpack-contrib/url-loader
<del>[url-npm]: https://img.shields.io/npm/v/url-loader.svg
<del>[url-size]: https://packagephobia.com/badge?p=url-loader
<del>[file]: https://github.com/webpack-contrib/file-loader
<del>[file-npm]: https://img.shields.io/npm/v/file-loader.svg
<del>[file-size]: https://packagephobia.com/badge?p=file-loader
<ide>
<ide> #### JSON
<ide> | 1 |
Ruby | Ruby | move another migrator test to the correct class | ad2af42bb299f762a5a969370ee5378d34ebbc53 | <ide><path>activerecord/test/cases/migration_test.rb
<ide> def test_finds_pending_migrations
<ide> assert_equal migrations[0].name, 'InterleavedInnocentJointable'
<ide> end
<ide>
<del> def test_relative_migrations
<del> list = Dir.chdir(MIGRATIONS_ROOT) do
<del> ActiveRecord::Migrator.up("valid/", 1)
<del> end
<del>
<del> migration_proxy = list.find { |item|
<del> item.name == 'ValidPeopleHaveLastNames'
<del> }
<del> assert migration_proxy, 'should find pending migration'
<del> end
<del>
<ide> def test_only_loads_pending_migrations
<ide> # migrate up to 1
<ide> ActiveRecord::Migrator.up(MIGRATIONS_ROOT + "/valid", 1)
<ide><path>activerecord/test/cases/migrator_test.rb
<ide> def test_deprecated_constructor
<ide> ActiveRecord::Migrator.new(:up, MIGRATIONS_ROOT + "/interleaved/pass_2")
<ide> end
<ide> end
<add>
<add> def test_relative_migrations
<add> list = Dir.chdir(MIGRATIONS_ROOT) do
<add> ActiveRecord::Migrator.migrations("valid/")
<add> end
<add>
<add> migration_proxy = list.find { |item|
<add> item.name == 'ValidPeopleHaveLastNames'
<add> }
<add> assert migration_proxy, 'should find pending migration'
<add> end
<ide> end
<ide> end | 2 |
Text | Text | add detail for how to update llhttp | 321e2493a43558afd074c97a5d996166c46f2667 | <ide><path>doc/contributing/maintaining-http.md
<ide> to align them with the APIs built for the client.
<ide> The low-level implementation of the
<ide> [HTTP](https://nodejs.org/docs/latest/api/http.html)
<ide> and [HTTPS](https://nodejs.org/docs/latest/api/https.html) APIs
<del>are maintained in the [llttp](https://github.com/nodejs/llhttp)
<add>are maintained in the [llhttp](https://github.com/nodejs/llhttp)
<ide> repository. Updates are pulled into Node.js under
<del>[deps/llhttp](https://github.com/nodejs/node/tree/HEAD/deps/llhttp)
<add>[deps/llhttp](https://github.com/nodejs/node/tree/HEAD/deps/llhttp).
<add>
<add>In order to update Node.js with a new version of llhttp:
<add>
<add>* check out the tagged release that you want to update to (a release
<add> should be created in the llhttp repo before updating Node.js).
<add>* run `npm install` in the directory that you checked out llhttp.
<add>* run `make release` in the directory that you checked out llhttp.
<add>* copy the contents of the `release` directory from the directory you
<add> checked llhttp out to
<add> [deps/llhttp](https://github.com/nodejs/node/tree/HEAD/deps/llhttp)
<add>
<add>It should look like the following:
<add>
<add>```console
<add>├── CMakeLists.txt
<add>├── common.gypi
<add>├── include
<add>│ └── llhttp.h
<add>├── LICENSE-MIT
<add>├── llhttp.gyp
<add>├── README.md
<add>└── src
<add> ├── api.c
<add> ├── http.c
<add> └── llhttp.c
<add>```
<ide>
<ide> The low-level implementation is made available in the Node.js API through
<ide> JavaScript code in the [lib](https://github.com/nodejs/node/tree/HEAD/lib) | 1 |
Ruby | Ruby | consolidate bottle defaults and remove a method | 7e8c693218499811897ebc502aa2cac5c7ab59cc | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_regex
<ide> Pathname::BOTTLE_EXTNAME_RX
<ide> end
<ide>
<del>def bottle_root_url f
<del> root_url = f.bottle.root_url
<del> root_url ||= 'https://downloads.sf.net/project/machomebrew/Bottles'
<del>end
<del>
<ide> def bottle_url f, tag=bottle_tag
<del> "#{bottle_root_url(f)}/#{bottle_filename(f, {:tag => tag})}"
<add> "#{f.bottle.root_url}/#{bottle_filename(f, :tag => tag)}"
<ide> end
<ide>
<ide> def bottle_tag
<ide><path>Library/Homebrew/software_spec.rb
<ide> def initialize
<ide> @revision = 0
<ide> @prefix = '/usr/local'
<ide> @cellar = '/usr/local/Cellar'
<del> @root_url = nil
<add> @root_url = 'https://downloads.sf.net/project/machomebrew/Bottles'
<ide> end
<ide>
<ide> # Checksum methods in the DSL's bottle block optionally take | 2 |
Java | Java | use hassize() where possible | 1e83e889aa227d9f84c8c212fe6d8772afe33614 | <ide><path>spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
<ide> void scanAndRefresh() {
<ide> context.getBean(uncapitalize(ComponentForScanning.class.getSimpleName()));
<ide> context.getBean(uncapitalize(Jsr330NamedForScanning.class.getSimpleName()));
<ide> Map<String, Object> beans = context.getBeansWithAnnotation(Configuration.class);
<del> assertThat(beans).size().isEqualTo(1);
<add> assertThat(beans).hasSize(1);
<ide> }
<ide>
<ide> @Test
<ide> void registerAndRefresh() {
<ide> context.getBean("testBean");
<ide> context.getBean("name");
<ide> Map<String, Object> beans = context.getBeansWithAnnotation(Configuration.class);
<del> assertThat(beans).size().isEqualTo(2);
<add> assertThat(beans).hasSize(2);
<ide> }
<ide>
<ide> @Test
<ide> void getBeansWithAnnotation() {
<ide> context.getBean("testBean");
<ide> context.getBean("name");
<ide> Map<String, Object> beans = context.getBeansWithAnnotation(Configuration.class);
<del> assertThat(beans).size().isEqualTo(2);
<add> assertThat(beans).hasSize(2);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-context/src/test/java/org/springframework/scheduling/config/ScheduledTaskRegistrarTests.java
<ide> void getFixedDelayTasks() {
<ide> @Test
<ide> void addCronTaskWithValidExpression() {
<ide> this.taskRegistrar.addCronTask(no_op, "* * * * * ?");
<del> assertThat(this.taskRegistrar.getCronTaskList()).size().isEqualTo(1);
<add> assertThat(this.taskRegistrar.getCronTaskList()).hasSize(1);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/event/CustomTestEventTests.java
<ide> public void clearEvents() {
<ide>
<ide> @Test
<ide> public void customTestEventPublished() {
<del> assertThat(events).size().isEqualTo(1);
<add> assertThat(events).hasSize(1);
<ide> CustomEvent customEvent = events.get(0);
<ide> assertThat(customEvent.getSource()).isEqualTo(getClass());
<ide> assertThat(customEvent.getTestName()).isEqualTo("customTestEventPublished");
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/SpringExtensionParameterizedTests.java
<ide> class SpringExtensionParameterizedTests {
<ide> @ParameterizedTest
<ide> @ValueSource(strings = { "Dilbert", "Wally" })
<ide> void people(String name, @Autowired List<Person> people) {
<del> assertThat(people.stream().map(Person::getName).filter(name::equals)).size().isEqualTo(1);
<add> assertThat(people.stream().map(Person::getName).filter(name::equals)).hasSize(1);
<ide> }
<ide>
<ide> @ParameterizedTest
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/defaultmethods/GenericComicCharactersInterfaceDefaultMethodsTests.java
<ide>
<ide> @Test
<ide> default void autowiredParameterWithParameterizedList(@Autowired List<C> characters) {
<del> assertThat(characters).as("Number of characters in context").size().isEqualTo(getExpectedNumCharacters());
<add> assertThat(characters).as("Number of characters in context").hasSize(getExpectedNumCharacters());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/generics/GenericComicCharactersTests.java
<ide> void autowiredFields() {
<ide> assertThat(this.character).as("Character should have been @Autowired by Spring").isNotNull();
<ide> assertThat(this.character).as("character's name").extracting(Character::getName).isEqualTo(getExpectedName());
<del> assertThat(this.characters).as("Number of characters in context").size().isEqualTo(getExpectedNumCharacters());
<add> assertThat(this.characters).as("Number of characters in context").hasSize(getExpectedNumCharacters());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web/src/test/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolverTests.java
<ide> public class MappingMediaTypeFileExtensionResolverTests {
<ide> public void resolveExtensions() {
<ide> List<String> extensions = this.resolver.resolveFileExtensions(MediaType.APPLICATION_JSON);
<ide>
<del> assertThat(extensions).size().isEqualTo(1);
<add> assertThat(extensions).hasSize(1);
<ide> assertThat(extensions.get(0)).isEqualTo("json");
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestScopedControllerAdviceIntegrationTests.java
<ide> void loadContextWithRequestScopedControllerAdvice() {
<ide> assertThatCode(context::refresh).doesNotThrowAnyException();
<ide>
<ide> List<ControllerAdviceBean> adviceBeans = ControllerAdviceBean.findAnnotatedBeans(context);
<del> assertThat(adviceBeans).size().isEqualTo(1);
<add> assertThat(adviceBeans).hasSize(1);
<ide> assertThat(adviceBeans.get(0))//
<ide> .returns(RequestScopedControllerAdvice.class, ControllerAdviceBean::getBeanType)//
<ide> .returns(42, ControllerAdviceBean::getOrder); | 8 |
Javascript | Javascript | add ktx2exporter | 746f66b295b4190a0c5d5fb305a0ed290e5aa169 | <ide><path>examples/jsm/exporters/KTX2Exporter.js
<add>import {
<add> FloatType,
<add> HalfFloatType,
<add> UnsignedByteType,
<add> RGBAFormat,
<add> RGFormat,
<add> RGIntegerFormat,
<add> RedFormat,
<add> RedIntegerFormat,
<add> LinearEncoding,
<add> sRGBEncoding,
<add> DataTexture,
<add> REVISION,
<add>} from 'three';
<add>
<add>import {
<add> write,
<add> KTX2Container,
<add> KHR_DF_CHANNEL_RGBSDA_ALPHA,
<add> KHR_DF_CHANNEL_RGBSDA_BLUE,
<add> KHR_DF_CHANNEL_RGBSDA_GREEN,
<add> KHR_DF_CHANNEL_RGBSDA_RED,
<add> KHR_DF_MODEL_RGBSDA,
<add> KHR_DF_PRIMARIES_BT709,
<add> KHR_DF_SAMPLE_DATATYPE_FLOAT,
<add> KHR_DF_SAMPLE_DATATYPE_LINEAR,
<add> KHR_DF_SAMPLE_DATATYPE_SIGNED,
<add> KHR_DF_TRANSFER_LINEAR,
<add> KHR_DF_TRANSFER_SRGB,
<add> VK_FORMAT_R16_SFLOAT,
<add> VK_FORMAT_R16G16_SFLOAT,
<add> VK_FORMAT_R16G16B16A16_SFLOAT,
<add> VK_FORMAT_R32_SFLOAT,
<add> VK_FORMAT_R32G32_SFLOAT,
<add> VK_FORMAT_R32G32B32A32_SFLOAT,
<add> VK_FORMAT_R8_SRGB,
<add> VK_FORMAT_R8_UNORM,
<add> VK_FORMAT_R8G8_SRGB,
<add> VK_FORMAT_R8G8_UNORM,
<add> VK_FORMAT_R8G8B8A8_SRGB,
<add> VK_FORMAT_R8G8B8A8_UNORM,
<add> } from '../libs/ktx-parse.module.js';
<add>
<add>const VK_FORMAT_MAP = {
<add>
<add> [RGBAFormat]: {
<add> [FloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R32G32B32A32_SFLOAT,
<add> },
<add> [HalfFloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R16G16B16A16_SFLOAT,
<add> },
<add> [UnsignedByteType]: {
<add> [LinearEncoding]: VK_FORMAT_R8G8B8A8_UNORM,
<add> [sRGBEncoding]: VK_FORMAT_R8G8B8A8_SRGB,
<add> },
<add> },
<add>
<add> [RGFormat]: {
<add> [FloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R32G32_SFLOAT,
<add> },
<add> [HalfFloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R16G16_SFLOAT,
<add> },
<add> [UnsignedByteType]: {
<add> [LinearEncoding]: VK_FORMAT_R8G8_UNORM,
<add> [sRGBEncoding]: VK_FORMAT_R8G8_SRGB,
<add> },
<add> },
<add>
<add> [RedFormat]: {
<add> [FloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R32_SFLOAT,
<add> },
<add> [HalfFloatType]: {
<add> [LinearEncoding]: VK_FORMAT_R16_SFLOAT,
<add> },
<add> [UnsignedByteType]: {
<add> [LinearEncoding]: VK_FORMAT_R8_SRGB,
<add> [sRGBEncoding]: VK_FORMAT_R8_UNORM,
<add> },
<add> },
<add>
<add>};
<add>
<add>const KHR_DF_CHANNEL_MAP = {
<add>
<add> 0: KHR_DF_CHANNEL_RGBSDA_RED,
<add> 1: KHR_DF_CHANNEL_RGBSDA_GREEN,
<add> 2: KHR_DF_CHANNEL_RGBSDA_BLUE,
<add> 3: KHR_DF_CHANNEL_RGBSDA_ALPHA,
<add>
<add>};
<add>
<add>const ERROR_INPUT = 'THREE.KTX2Exporter: Supported inputs are DataTexture, Data3DTexture, or WebGLRenderer and WebGLRenderTarget.';
<add>const ERROR_FORMAT = 'THREE.KTX2Exporter: Supported formats are RGBAFormat, RGFormat, or RedFormat.';
<add>const ERROR_TYPE = 'THREE.KTX2Exporter: Supported types are FloatType, HalfFloatType, or UnsignedByteType."';
<add>const ERROR_ENCODING = 'THREE.KTX2Exporter: Supported encodings are sRGB (UnsignedByteType only) or Linear.';
<add>
<add>export class KTX2Exporter {
<add>
<add> parse( arg1, arg2 ) {
<add>
<add> let texture;
<add>
<add> if ( arg1.isDataTexture || arg1.isData3DTexture ) {
<add>
<add> texture = arg1;
<add>
<add> } else if ( arg1.isWebGLRenderer && arg2.isWebGLRenderTarget ) {
<add>
<add> texture = toDataTexture( arg1, arg2 );
<add>
<add> } else {
<add>
<add> throw new Error( ERROR_INPUT );
<add>
<add> }
<add>
<add> if ( VK_FORMAT_MAP[ texture.format ] === undefined ) {
<add>
<add> throw new Error( ERROR_FORMAT );
<add>
<add> }
<add>
<add> if ( VK_FORMAT_MAP[ texture.format ][ texture.type ] === undefined ) {
<add>
<add> throw new Error( ERROR_TYPE );
<add>
<add> }
<add>
<add> if ( VK_FORMAT_MAP[ texture.format ][ texture.type ][ texture.encoding ] === undefined ) {
<add>
<add> throw new Error( ERROR_ENCODING );
<add>
<add> }
<add>
<add> //
<add>
<add> const array = texture.image.data;
<add> const channelCount = getChannelCount( texture );
<add> const container = new KTX2Container();
<add>
<add> container.vkFormat = VK_FORMAT_MAP[ texture.format ][ texture.type ][ texture.encoding ];
<add> container.typeSize = array.BYTES_PER_ELEMENT;
<add> container.pixelWidth = texture.image.width;
<add> container.pixelHeight = texture.image.height;
<add>
<add> if ( texture.isData3DTexture ) {
<add>
<add> container.pixelDepth = texture.image.depth;
<add>
<add> }
<add>
<add> //
<add>
<add> const basicDesc = container.dataFormatDescriptor[ 0 ];
<add>
<add> // TODO: After `texture.encoding` is replaced, distinguish between
<add> // non-color data (unspecified model and primaries) and sRGB or Linear-sRGB colors.
<add> basicDesc.colorModel = KHR_DF_MODEL_RGBSDA;
<add> basicDesc.colorPrimaries = KHR_DF_PRIMARIES_BT709;
<add> basicDesc.transferFunction = texture.encoding === sRGBEncoding
<add> ? KHR_DF_TRANSFER_SRGB
<add> : KHR_DF_TRANSFER_LINEAR;
<add>
<add> basicDesc.texelBlockDimension = [ 0, 0, 0, 0 ];
<add>
<add> basicDesc.bytesPlane = [
<add>
<add> container.typeSize * channelCount, 0, 0, 0, 0, 0, 0, 0,
<add>
<add> ];
<add>
<add> for ( let i = 0; i < channelCount; ++ i ) {
<add>
<add> let channelType = KHR_DF_CHANNEL_MAP[ i ];
<add>
<add> if ( texture.encoding === LinearEncoding ) {
<add>
<add> channelType |= KHR_DF_SAMPLE_DATATYPE_LINEAR;
<add>
<add> }
<add>
<add> if ( texture.type === FloatType || texture.type === HalfFloatType ) {
<add>
<add> channelType |= KHR_DF_SAMPLE_DATATYPE_FLOAT;
<add> channelType |= KHR_DF_SAMPLE_DATATYPE_SIGNED;
<add>
<add> }
<add>
<add> basicDesc.samples.push( {
<add>
<add> channelType: channelType,
<add> bitOffset: i * array.BYTES_PER_ELEMENT,
<add> bitLength: array.BYTES_PER_ELEMENT * 8 - 1,
<add> samplePosition: [0, 0, 0, 0],
<add> sampleLower: texture.type === UnsignedByteType ? 0 : -1,
<add> sampleUpper: texture.type === UnsignedByteType ? 255 : 1,
<add>
<add> } );
<add>
<add> }
<add>
<add> //
<add>
<add> container.levels = [ {
<add>
<add> levelData: new Uint8Array( array.buffer, array.byteOffset, array.byteLength ),
<add> uncompressedByteLength: array.byteLength,
<add>
<add> } ];
<add>
<add> //
<add>
<add> container.keyValue['KTXwriter'] = `three.js ${ REVISION }`;
<add>
<add> //
<add>
<add> return write( container, { keepWriter: true } );
<add>
<add> }
<add>
<add>}
<add>
<add>function toDataTexture( renderer, rtt ) {
<add>
<add> const channelCount = getChannelCount( rtt.texture );
<add>
<add> let view;
<add>
<add> if ( rtt.texture.type === FloatType ) {
<add>
<add> view = new Float32Array( rtt.width * rtt.height * channelCount );
<add>
<add> } else if ( rtt.texture.type === HalfFloatType ) {
<add>
<add> view = new Uint16Array( rtt.width * rtt.height * channelCount );
<add>
<add> } else if ( rtt.texture.type === UnsignedByteType ) {
<add>
<add> view = new Uint8Array( rtt.width * rtt.height * channelCount );
<add>
<add> } else {
<add>
<add> throw new Error( ERROR_TYPE );
<add>
<add> }
<add>
<add> renderer.readRenderTargetPixels( rtt, 0, 0, rtt.width, rtt.height, view );
<add>
<add> return new DataTexture( view, rtt.width, rt.height, rtt.texture.format, rtt.texture.type );
<add>
<add>}
<add>
<add>function getChannelCount( texture ) {
<add>
<add> switch ( texture.format ) {
<add>
<add> case RGBAFormat:
<add>
<add> return 4;
<add>
<add> case RGFormat:
<add> case RGIntegerFormat:
<add>
<add> return 2;
<add>
<add> case RedFormat:
<add> case RedIntegerFormat:
<add>
<add> return 1;
<add>
<add> default:
<add>
<add> throw new Error( ERROR_FORMAT );
<add>
<add> }
<add>
<add>}
<ide><path>examples/jsm/libs/ktx-parse.module.js
<del>const t=new Uint8Array([0]),e=[171,75,84,88,32,50,48,187,13,10,26,10];var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB"}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT"}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC"}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB"}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2"}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA"}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG"}(f||(f={}));class U{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=n.NONE,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:i.BASICFORMAT,versionNumber:2,descriptorBlockSize:40,colorModel:s.UNSPECIFIED,colorPrimaries:a.SRGB,transferFunction:a.SRGB,flags:o.ALPHA_STRAIGHT,texelBlockDimension:{x:4,y:4,z:1,w:1},bytesPlane:[],samples:[]}],this.keyValue={},this.globalData=null}}class c{constructor(t,e,n,i){this._dataView=new DataView(t.buffer,t.byteOffset+e,n),this._littleEndian=i,this._offset=0}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,t}_skip(t){return this._offset+=t,this}_scan(t,e=0){const n=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==e&&i<t;)i++,this._offset++;return i<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}function h(t){return"undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}function _(t){return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}function g(t){let e=0;for(const n of t)e+=n.byteLength;const n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n}function p(t){const n=new Uint8Array(t.buffer,t.byteOffset,e.length);if(n[0]!==e[0]||n[1]!==e[1]||n[2]!==e[2]||n[3]!==e[3]||n[4]!==e[4]||n[5]!==e[5]||n[6]!==e[6]||n[7]!==e[7]||n[8]!==e[8]||n[9]!==e[9]||n[10]!==e[10]||n[11]!==e[11])throw new Error("Missing KTX 2.0 identifier.");const i=new U,s=17*Uint32Array.BYTES_PER_ELEMENT,a=new c(t,e.length,s,!0);i.vkFormat=a._nextUint32(),i.typeSize=a._nextUint32(),i.pixelWidth=a._nextUint32(),i.pixelHeight=a._nextUint32(),i.pixelDepth=a._nextUint32(),i.layerCount=a._nextUint32(),i.faceCount=a._nextUint32();const r=a._nextUint32();i.supercompressionScheme=a._nextUint32();const o=a._nextUint32(),l=a._nextUint32(),f=a._nextUint32(),h=a._nextUint32(),g=a._nextUint64(),p=a._nextUint64(),x=new c(t,e.length+s,3*r*8,!0);for(let e=0;e<r;e++)i.levels.push({levelData:new Uint8Array(t.buffer,t.byteOffset+x._nextUint64(),x._nextUint64()),uncompressedByteLength:x._nextUint64()});const u=new c(t,o,l,!0),y={vendorId:u._skip(4)._nextUint16(),descriptorType:u._nextUint16(),versionNumber:u._nextUint16(),descriptorBlockSize:u._nextUint16(),colorModel:u._nextUint8(),colorPrimaries:u._nextUint8(),transferFunction:u._nextUint8(),flags:u._nextUint8(),texelBlockDimension:{x:u._nextUint8()+1,y:u._nextUint8()+1,z:u._nextUint8()+1,w:u._nextUint8()+1},bytesPlane:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],samples:[]},D=(y.descriptorBlockSize/4-6)/4;for(let t=0;t<D;t++)y.samples[t]={bitOffset:u._nextUint16(),bitLength:u._nextUint8(),channelID:u._nextUint8(),samplePosition:[u._nextUint8(),u._nextUint8(),u._nextUint8(),u._nextUint8()],sampleLower:u._nextUint32(),sampleUpper:u._nextUint32()};i.dataFormatDescriptor.length=0,i.dataFormatDescriptor.push(y);const b=new c(t,f,h,!0);for(;b._offset<h;){const t=b._nextUint32(),e=b._scan(t),n=_(e),s=b._scan(t-e.byteLength);i.keyValue[n]=n.match(/^ktx/i)?_(s):s,b._offset%4&&b._skip(4-b._offset%4)}if(p<=0)return i;const d=new c(t,g,p,!0),B=d._nextUint16(),w=d._nextUint16(),A=d._nextUint32(),S=d._nextUint32(),m=d._nextUint32(),L=d._nextUint32(),I=[];for(let t=0;t<r;t++)I.push({imageFlags:d._nextUint32(),rgbSliceByteOffset:d._nextUint32(),rgbSliceByteLength:d._nextUint32(),alphaSliceByteOffset:d._nextUint32(),alphaSliceByteLength:d._nextUint32()});const R=g+d._offset,E=R+A,T=E+S,O=T+m,P=new Uint8Array(t.buffer,t.byteOffset+R,A),C=new Uint8Array(t.buffer,t.byteOffset+E,S),F=new Uint8Array(t.buffer,t.byteOffset+T,m),G=new Uint8Array(t.buffer,t.byteOffset+O,L);return i.globalData={endpointCount:B,selectorCount:w,imageDescs:I,endpointsData:P,selectorsData:C,tablesData:F,extendedData:G},i}function x(){return(x=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}const u={keepWriter:!1};function y(n,s={}){s=x({},u,s);let a=new ArrayBuffer(0);if(n.globalData){const t=new ArrayBuffer(20+5*n.globalData.imageDescs.length*4),e=new DataView(t);e.setUint16(0,n.globalData.endpointCount,!0),e.setUint16(2,n.globalData.selectorCount,!0),e.setUint32(4,n.globalData.endpointsData.byteLength,!0),e.setUint32(8,n.globalData.selectorsData.byteLength,!0),e.setUint32(12,n.globalData.tablesData.byteLength,!0),e.setUint32(16,n.globalData.extendedData.byteLength,!0);for(let t=0;t<n.globalData.imageDescs.length;t++){const i=n.globalData.imageDescs[t];e.setUint32(20+5*t*4+0,i.imageFlags,!0),e.setUint32(20+5*t*4+4,i.rgbSliceByteOffset,!0),e.setUint32(20+5*t*4+8,i.rgbSliceByteLength,!0),e.setUint32(20+5*t*4+12,i.alphaSliceByteOffset,!0),e.setUint32(20+5*t*4+16,i.alphaSliceByteLength,!0)}a=g([t,n.globalData.endpointsData,n.globalData.selectorsData,n.globalData.tablesData,n.globalData.extendedData])}const r=[];let o=n.keyValue;s.keepWriter||(o=x({},n.keyValue,{KTXwriter:"KTX-Parse v0.2.1"}));for(const e in o){const n=o[e],i=h(e),s="string"==typeof n?h(n):n,a=i.byteLength+1+s.byteLength+1,l=a%4?4-a%4:0;r.push(g([new Uint32Array([a]),i,t,s,t,new Uint8Array(l).fill(0)]))}const l=g(r),f=new ArrayBuffer(44),U=new DataView(f);if(1!==n.dataFormatDescriptor.length||n.dataFormatDescriptor[0].descriptorType!==i.BASICFORMAT)throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");const c=n.dataFormatDescriptor[0];U.setUint32(0,44,!0),U.setUint16(4,c.vendorId,!0),U.setUint16(6,c.descriptorType,!0),U.setUint16(8,c.versionNumber,!0),U.setUint16(10,c.descriptorBlockSize,!0),U.setUint8(12,c.colorModel),U.setUint8(13,c.colorPrimaries),U.setUint8(14,c.transferFunction),U.setUint8(15,c.flags),U.setUint8(16,c.texelBlockDimension.x-1),U.setUint8(17,c.texelBlockDimension.y-1),U.setUint8(18,c.texelBlockDimension.z-1),U.setUint8(19,c.texelBlockDimension.w-1);for(let t=0;t<8;t++)U.setUint8(20+t,c.bytesPlane[t]);for(let t=0;t<c.samples.length;t++){const e=c.samples[t],n=28+16*t;U.setUint16(n+0,e.bitOffset,!0),U.setUint8(n+2,e.bitLength),U.setUint8(n+3,e.channelID),U.setUint8(n+4,e.samplePosition[0]),U.setUint8(n+5,e.samplePosition[1]),U.setUint8(n+6,e.samplePosition[2]),U.setUint8(n+7,e.samplePosition[3]),U.setUint32(n+8,e.sampleLower,!0),U.setUint32(n+12,e.sampleUpper,!0)}const _=e.length+68+3*n.levels.length*8,p=_+f.byteLength;let y=p+l.byteLength;y%8&&(y+=8-y%8);const D=[],b=new DataView(new ArrayBuffer(3*n.levels.length*8));let d=y+a.byteLength;for(let t=0;t<n.levels.length;t++){const e=n.levels[t];D.push(e.levelData),b.setBigUint64(24*t+0,BigInt(d),!0),b.setBigUint64(24*t+8,BigInt(e.levelData.byteLength),!0),b.setBigUint64(24*t+16,BigInt(e.uncompressedByteLength),!0),d+=e.levelData.byteLength}const B=new ArrayBuffer(68),w=new DataView(B);return w.setUint32(0,n.vkFormat,!0),w.setUint32(4,n.typeSize,!0),w.setUint32(8,n.pixelWidth,!0),w.setUint32(12,n.pixelHeight,!0),w.setUint32(16,n.pixelDepth,!0),w.setUint32(20,n.layerCount,!0),w.setUint32(24,n.faceCount,!0),w.setUint32(28,n.levels.length,!0),w.setUint32(32,n.supercompressionScheme,!0),w.setUint32(36,_,!0),w.setUint32(40,f.byteLength,!0),w.setUint32(44,p,!0),w.setUint32(48,l.byteLength,!0),w.setBigUint64(52,BigInt(y),!0),w.setBigUint64(60,BigInt(a.byteLength),!0),new Uint8Array(g([new Uint8Array(e).buffer,B,b.buffer,f,l,new ArrayBuffer(y-(p+l.byteLength)),a,...D]))}export{l as KTX2ChannelETC1S,f as KTX2ChannelUASTC,U as KTX2Container,i as KTX2DescriptorType,o as KTX2Flags,s as KTX2Model,a as KTX2Primaries,n as KTX2SupercompressionScheme,r as KTX2Transfer,p as read,y as write};
<add>const t=0,e=1,n=2,i=3,s=0,a=0,r=2,o=0,l=1,f=160,U=161,c=162,h=163,_=0,p=1,g=0,y=1,x=2,u=3,b=4,d=5,m=6,w=7,D=8,B=9,L=10,A=11,k=12,v=13,S=14,I=15,O=16,T=17,V=18,E=0,F=1,P=2,C=3,z=4,M=5,W=6,N=7,H=8,K=9,X=10,j=11,R=0,Y=1,q=2,G=13,J=14,Q=15,Z=128,$=64,tt=32,et=16,nt=0,it=1,st=2,at=3,rt=4,ot=5,lt=6,ft=7,Ut=8,ct=9,ht=10,_t=13,pt=14,gt=15,yt=16,xt=17,ut=20,bt=21,dt=22,mt=23,wt=24,Dt=27,Bt=28,Lt=29,At=30,kt=31,vt=34,St=35,It=36,Ot=37,Tt=38,Vt=41,Et=42,Ft=43,Pt=44,Ct=45,zt=48,Mt=49,Wt=50,Nt=58,Ht=59,Kt=62,Xt=63,jt=64,Rt=65,Yt=68,qt=69,Gt=70,Jt=71,Qt=74,Zt=75,$t=76,te=77,ee=78,ne=81,ie=82,se=83,ae=84,re=85,oe=88,le=89,fe=90,Ue=91,ce=92,he=95,_e=96,pe=97,ge=98,ye=99,xe=100,ue=101,be=102,de=103,me=104,we=105,De=106,Be=107,Le=108,Ae=109,ke=110,ve=111,Se=112,Ie=113,Oe=114,Te=115,Ve=116,Ee=117,Fe=118,Pe=119,Ce=120,ze=121,Me=122,We=123,Ne=124,He=125,Ke=126,Xe=127,je=128,Re=129,Ye=130,qe=131,Ge=132,Je=133,Qe=134,Ze=135,$e=136,tn=137,en=138,nn=139,sn=140,an=141,rn=142,on=143,ln=144,fn=145,Un=146,cn=147,hn=148,_n=149,pn=150,gn=151,yn=152,xn=153,un=154,bn=155,dn=156,mn=157,wn=158,Dn=159,Bn=160,Ln=161,An=162,kn=163,vn=164,Sn=165,In=166,On=167,Tn=168,Vn=169,En=170,Fn=171,Pn=172,Cn=173,zn=174,Mn=175,Wn=176,Nn=177,Hn=178,Kn=179,Xn=180,jn=181,Rn=182,Yn=183,qn=184,Gn=1000156007,Jn=1000156008,Qn=1000156009,Zn=1000156010,$n=1000156011,ti=1000156017,ei=1000156018,ni=1000156019,ii=1000156020,si=1000156021,ai=1000054e3,ri=1000054001,oi=1000054002,li=1000054003,fi=1000054004,Ui=1000054005,ci=1000054006,hi=1000054007,_i=1000066e3,pi=1000066001,gi=1000066002,yi=1000066003,xi=1000066004,ui=1000066005,bi=1000066006,di=1000066007,mi=1000066008,wi=1000066009,Di=1000066010,Bi=1000066011,Li=1000066012,Ai=1000066013,ki=100034e4,vi=1000340001;class Si{constructor(){this.vkFormat=0,this.typeSize=1,this.pixelWidth=0,this.pixelHeight=0,this.pixelDepth=0,this.layerCount=0,this.faceCount=1,this.supercompressionScheme=0,this.levels=[],this.dataFormatDescriptor=[{vendorId:0,descriptorType:0,descriptorBlockSize:0,versionNumber:2,colorModel:0,colorPrimaries:1,transferFunction:2,flags:0,texelBlockDimension:[0,0,0,0],bytesPlane:[0,0,0,0,0,0,0,0],samples:[]}],this.keyValue={},this.globalData=null}}class Ii{constructor(t,e,n,i){this._dataView=new DataView(t.buffer,t.byteOffset+e,n),this._littleEndian=i,this._offset=0}_nextUint8(){const t=this._dataView.getUint8(this._offset);return this._offset+=1,t}_nextUint16(){const t=this._dataView.getUint16(this._offset,this._littleEndian);return this._offset+=2,t}_nextUint32(){const t=this._dataView.getUint32(this._offset,this._littleEndian);return this._offset+=4,t}_nextUint64(){const t=this._dataView.getUint32(this._offset,this._littleEndian)+2**32*this._dataView.getUint32(this._offset+4,this._littleEndian);return this._offset+=8,t}_nextInt32(){const t=this._dataView.getInt32(this._offset,this._littleEndian);return this._offset+=4,t}_skip(t){return this._offset+=t,this}_scan(t,e=0){const n=this._offset;let i=0;for(;this._dataView.getUint8(this._offset)!==e&&i<t;)i++,this._offset++;return i<t&&this._offset++,new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+n,i)}}const Oi=new Uint8Array([0]),Ti=[171,75,84,88,32,50,48,187,13,10,26,10];function Vi(t){return"undefined"!=typeof TextEncoder?(new TextEncoder).encode(t):Buffer.from(t)}function Ei(t){return"undefined"!=typeof TextDecoder?(new TextDecoder).decode(t):Buffer.from(t).toString("utf8")}function Fi(t){let e=0;for(const n of t)e+=n.byteLength;const n=new Uint8Array(e);let i=0;for(const e of t)n.set(new Uint8Array(e),i),i+=e.byteLength;return n}function Pi(t){const e=new Uint8Array(t.buffer,t.byteOffset,Ti.length);if(e[0]!==Ti[0]||e[1]!==Ti[1]||e[2]!==Ti[2]||e[3]!==Ti[3]||e[4]!==Ti[4]||e[5]!==Ti[5]||e[6]!==Ti[6]||e[7]!==Ti[7]||e[8]!==Ti[8]||e[9]!==Ti[9]||e[10]!==Ti[10]||e[11]!==Ti[11])throw new Error("Missing KTX 2.0 identifier.");const n=new Si,i=17*Uint32Array.BYTES_PER_ELEMENT,s=new Ii(t,Ti.length,i,!0);n.vkFormat=s._nextUint32(),n.typeSize=s._nextUint32(),n.pixelWidth=s._nextUint32(),n.pixelHeight=s._nextUint32(),n.pixelDepth=s._nextUint32(),n.layerCount=s._nextUint32(),n.faceCount=s._nextUint32();const a=s._nextUint32();n.supercompressionScheme=s._nextUint32();const r=s._nextUint32(),o=s._nextUint32(),l=s._nextUint32(),f=s._nextUint32(),U=s._nextUint64(),c=s._nextUint64(),h=new Ii(t,Ti.length+i,3*a*8,!0);for(let e=0;e<a;e++)n.levels.push({levelData:new Uint8Array(t.buffer,t.byteOffset+h._nextUint64(),h._nextUint64()),uncompressedByteLength:h._nextUint64()});const _=new Ii(t,r,o,!0),p={vendorId:_._skip(4)._nextUint16(),descriptorType:_._nextUint16(),versionNumber:_._nextUint16(),descriptorBlockSize:_._nextUint16(),colorModel:_._nextUint8(),colorPrimaries:_._nextUint8(),transferFunction:_._nextUint8(),flags:_._nextUint8(),texelBlockDimension:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],bytesPlane:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],samples:[]},g=(p.descriptorBlockSize/4-6)/4;for(let t=0;t<g;t++){const e={bitOffset:_._nextUint16(),bitLength:_._nextUint8(),channelType:_._nextUint8(),samplePosition:[_._nextUint8(),_._nextUint8(),_._nextUint8(),_._nextUint8()],sampleLower:-Infinity,sampleUpper:Infinity};64&e.channelType?(e.sampleLower=_._nextInt32(),e.sampleUpper=_._nextInt32()):(e.sampleLower=_._nextUint32(),e.sampleUpper=_._nextUint32()),p.samples[t]=e}n.dataFormatDescriptor.length=0,n.dataFormatDescriptor.push(p);const y=new Ii(t,l,f,!0);for(;y._offset<f;){const t=y._nextUint32(),e=y._scan(t),i=Ei(e),s=y._scan(t-e.byteLength);n.keyValue[i]=i.match(/^ktx/i)?Ei(s):s,y._offset%4&&y._skip(4-y._offset%4)}if(c<=0)return n;const x=new Ii(t,U,c,!0),u=x._nextUint16(),b=x._nextUint16(),d=x._nextUint32(),m=x._nextUint32(),w=x._nextUint32(),D=x._nextUint32(),B=[];for(let t=0;t<a;t++)B.push({imageFlags:x._nextUint32(),rgbSliceByteOffset:x._nextUint32(),rgbSliceByteLength:x._nextUint32(),alphaSliceByteOffset:x._nextUint32(),alphaSliceByteLength:x._nextUint32()});const L=U+x._offset,A=L+d,k=A+m,v=k+w,S=new Uint8Array(t.buffer,t.byteOffset+L,d),I=new Uint8Array(t.buffer,t.byteOffset+A,m),O=new Uint8Array(t.buffer,t.byteOffset+k,w),T=new Uint8Array(t.buffer,t.byteOffset+v,D);return n.globalData={endpointCount:u,selectorCount:b,imageDescs:B,endpointsData:S,selectorsData:I,tablesData:O,extendedData:T},n}function Ci(){return(Ci=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])}return t}).apply(this,arguments)}const zi={keepWriter:!1};function Mi(t,e={}){e=Ci({},zi,e);let n=new ArrayBuffer(0);if(t.globalData){const e=new ArrayBuffer(20+5*t.globalData.imageDescs.length*4),i=new DataView(e);i.setUint16(0,t.globalData.endpointCount,!0),i.setUint16(2,t.globalData.selectorCount,!0),i.setUint32(4,t.globalData.endpointsData.byteLength,!0),i.setUint32(8,t.globalData.selectorsData.byteLength,!0),i.setUint32(12,t.globalData.tablesData.byteLength,!0),i.setUint32(16,t.globalData.extendedData.byteLength,!0);for(let e=0;e<t.globalData.imageDescs.length;e++){const n=t.globalData.imageDescs[e];i.setUint32(20+5*e*4+0,n.imageFlags,!0),i.setUint32(20+5*e*4+4,n.rgbSliceByteOffset,!0),i.setUint32(20+5*e*4+8,n.rgbSliceByteLength,!0),i.setUint32(20+5*e*4+12,n.alphaSliceByteOffset,!0),i.setUint32(20+5*e*4+16,n.alphaSliceByteLength,!0)}n=Fi([e,t.globalData.endpointsData,t.globalData.selectorsData,t.globalData.tablesData,t.globalData.extendedData])}const i=[];let s=t.keyValue;e.keepWriter||(s=Ci({},t.keyValue,{KTXwriter:"KTX-Parse v0.3.1"}));for(const t in s){const e=s[t],n=Vi(t),a="string"==typeof e?Vi(e):e,r=n.byteLength+1+a.byteLength+1,o=r%4?4-r%4:0;i.push(Fi([new Uint32Array([r]),n,Oi,a,Oi,new Uint8Array(o).fill(0)]))}const a=Fi(i);if(1!==t.dataFormatDescriptor.length||0!==t.dataFormatDescriptor[0].descriptorType)throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");const r=t.dataFormatDescriptor[0],o=new ArrayBuffer(28+16*r.samples.length),l=new DataView(o),f=24+16*r.samples.length;if(l.setUint32(0,o.byteLength,!0),l.setUint16(4,r.vendorId,!0),l.setUint16(6,r.descriptorType,!0),l.setUint16(8,r.versionNumber,!0),l.setUint16(10,f,!0),l.setUint8(12,r.colorModel),l.setUint8(13,r.colorPrimaries),l.setUint8(14,r.transferFunction),l.setUint8(15,r.flags),!Array.isArray(r.texelBlockDimension))throw new Error("texelBlockDimension is now an array. For dimensionality `d`, set `d - 1`.");l.setUint8(16,r.texelBlockDimension[0]),l.setUint8(17,r.texelBlockDimension[1]),l.setUint8(18,r.texelBlockDimension[2]),l.setUint8(19,r.texelBlockDimension[3]);for(let t=0;t<8;t++)l.setUint8(20+t,r.bytesPlane[t]);for(let t=0;t<r.samples.length;t++){const e=r.samples[t],n=28+16*t;if(e.channelID)throw new Error("channelID has been renamed to channelType.");l.setUint16(n+0,e.bitOffset,!0),l.setUint8(n+2,e.bitLength),l.setUint8(n+3,e.channelType),l.setUint8(n+4,e.samplePosition[0]),l.setUint8(n+5,e.samplePosition[1]),l.setUint8(n+6,e.samplePosition[2]),l.setUint8(n+7,e.samplePosition[3]),64&e.channelType?(l.setInt32(n+8,e.sampleLower,!0),l.setInt32(n+12,e.sampleUpper,!0)):(l.setUint32(n+8,e.sampleLower,!0),l.setUint32(n+12,e.sampleUpper,!0))}const U=Ti.length+68+3*t.levels.length*8,c=U+o.byteLength;let h=n.byteLength>0?c+a.byteLength:0;h%8&&(h+=8-h%8);const _=[],p=new DataView(new ArrayBuffer(3*t.levels.length*8));let g=(h||c+a.byteLength)+n.byteLength;for(let e=0;e<t.levels.length;e++){const n=t.levels[e];_.push(n.levelData),p.setBigUint64(24*e+0,BigInt(g),!0),p.setBigUint64(24*e+8,BigInt(n.levelData.byteLength),!0),p.setBigUint64(24*e+16,BigInt(n.uncompressedByteLength),!0),g+=n.levelData.byteLength}const y=new ArrayBuffer(68),x=new DataView(y);return x.setUint32(0,t.vkFormat,!0),x.setUint32(4,t.typeSize,!0),x.setUint32(8,t.pixelWidth,!0),x.setUint32(12,t.pixelHeight,!0),x.setUint32(16,t.pixelDepth,!0),x.setUint32(20,t.layerCount,!0),x.setUint32(24,t.faceCount,!0),x.setUint32(28,t.levels.length,!0),x.setUint32(32,t.supercompressionScheme,!0),x.setUint32(36,U,!0),x.setUint32(40,o.byteLength,!0),x.setUint32(44,c,!0),x.setUint32(48,a.byteLength,!0),x.setBigUint64(52,BigInt(n.byteLength>0?h:0),!0),x.setBigUint64(60,BigInt(n.byteLength),!0),new Uint8Array(Fi([new Uint8Array(Ti).buffer,y,p.buffer,o,a,h>0?new ArrayBuffer(h-(c+a.byteLength)):new ArrayBuffer(0),n,..._]))}export{Q as KHR_DF_CHANNEL_RGBSDA_ALPHA,q as KHR_DF_CHANNEL_RGBSDA_BLUE,J as KHR_DF_CHANNEL_RGBSDA_DEPTH,Y as KHR_DF_CHANNEL_RGBSDA_GREEN,R as KHR_DF_CHANNEL_RGBSDA_RED,G as KHR_DF_CHANNEL_RGBSDA_STENCIL,p as KHR_DF_FLAG_ALPHA_PREMULTIPLIED,_ as KHR_DF_FLAG_ALPHA_STRAIGHT,s as KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT,c as KHR_DF_MODEL_ASTC,f as KHR_DF_MODEL_ETC1,h as KHR_DF_MODEL_ETC1S,U as KHR_DF_MODEL_ETC2,l as KHR_DF_MODEL_RGBSDA,o as KHR_DF_MODEL_UNSPECIFIED,W as KHR_DF_PRIMARIES_ACES,N as KHR_DF_PRIMARIES_ACESCC,j as KHR_DF_PRIMARIES_ADOBERGB,z as KHR_DF_PRIMARIES_BT2020,P as KHR_DF_PRIMARIES_BT601_EBU,C as KHR_DF_PRIMARIES_BT601_SMPTE,F as KHR_DF_PRIMARIES_BT709,M as KHR_DF_PRIMARIES_CIEXYZ,X as KHR_DF_PRIMARIES_DISPLAYP3,H as KHR_DF_PRIMARIES_NTSC1953,K as KHR_DF_PRIMARIES_PAL525,E as KHR_DF_PRIMARIES_UNSPECIFIED,tt as KHR_DF_SAMPLE_DATATYPE_EXPONENT,Z as KHR_DF_SAMPLE_DATATYPE_FLOAT,et as KHR_DF_SAMPLE_DATATYPE_LINEAR,$ as KHR_DF_SAMPLE_DATATYPE_SIGNED,O as KHR_DF_TRANSFER_ACESCC,T as KHR_DF_TRANSFER_ACESCCT,V as KHR_DF_TRANSFER_ADOBERGB,w as KHR_DF_TRANSFER_BT1886,k as KHR_DF_TRANSFER_DCIP3,B as KHR_DF_TRANSFER_HLG_EOTF,D as KHR_DF_TRANSFER_HLG_OETF,u as KHR_DF_TRANSFER_ITU,y as KHR_DF_TRANSFER_LINEAR,b as KHR_DF_TRANSFER_NTSC,S as KHR_DF_TRANSFER_PAL625_EOTF,v as KHR_DF_TRANSFER_PAL_OETF,L as KHR_DF_TRANSFER_PQ_EOTF,A as KHR_DF_TRANSFER_PQ_OETF,d as KHR_DF_TRANSFER_SLOG,m as KHR_DF_TRANSFER_SLOG2,x as KHR_DF_TRANSFER_SRGB,I as KHR_DF_TRANSFER_ST240,g as KHR_DF_TRANSFER_UNSPECIFIED,a as KHR_DF_VENDORID_KHRONOS,r as KHR_DF_VERSION,e as KHR_SUPERCOMPRESSION_BASISLZ,t as KHR_SUPERCOMPRESSION_NONE,i as KHR_SUPERCOMPRESSION_ZLIB,n as KHR_SUPERCOMPRESSION_ZSTD,Si as KTX2Container,Ut as VK_FORMAT_A1R5G5B5_UNORM_PACK16,qt as VK_FORMAT_A2B10G10R10_SINT_PACK32,Rt as VK_FORMAT_A2B10G10R10_SNORM_PACK32,Yt as VK_FORMAT_A2B10G10R10_UINT_PACK32,jt as VK_FORMAT_A2B10G10R10_UNORM_PACK32,Xt as VK_FORMAT_A2R10G10B10_SINT_PACK32,Ht as VK_FORMAT_A2R10G10B10_SNORM_PACK32,Kt as VK_FORMAT_A2R10G10B10_UINT_PACK32,Nt as VK_FORMAT_A2R10G10B10_UNORM_PACK32,vi as VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT,ki as VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT,Bi as VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT,Xn as VK_FORMAT_ASTC_10x10_SRGB_BLOCK,Kn as VK_FORMAT_ASTC_10x10_UNORM_BLOCK,mi as VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT,zn as VK_FORMAT_ASTC_10x5_SRGB_BLOCK,Cn as VK_FORMAT_ASTC_10x5_UNORM_BLOCK,wi as VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT,Wn as VK_FORMAT_ASTC_10x6_SRGB_BLOCK,Mn as VK_FORMAT_ASTC_10x6_UNORM_BLOCK,Di as VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT,Hn as VK_FORMAT_ASTC_10x8_SRGB_BLOCK,Nn as VK_FORMAT_ASTC_10x8_UNORM_BLOCK,Li as VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT,Rn as VK_FORMAT_ASTC_12x10_SRGB_BLOCK,jn as VK_FORMAT_ASTC_12x10_UNORM_BLOCK,Ai as VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT,qn as VK_FORMAT_ASTC_12x12_SRGB_BLOCK,Yn as VK_FORMAT_ASTC_12x12_UNORM_BLOCK,_i as VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT,wn as VK_FORMAT_ASTC_4x4_SRGB_BLOCK,mn as VK_FORMAT_ASTC_4x4_UNORM_BLOCK,pi as VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT,Bn as VK_FORMAT_ASTC_5x4_SRGB_BLOCK,Dn as VK_FORMAT_ASTC_5x4_UNORM_BLOCK,gi as VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT,An as VK_FORMAT_ASTC_5x5_SRGB_BLOCK,Ln as VK_FORMAT_ASTC_5x5_UNORM_BLOCK,yi as VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT,vn as VK_FORMAT_ASTC_6x5_SRGB_BLOCK,kn as VK_FORMAT_ASTC_6x5_UNORM_BLOCK,xi as VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT,In as VK_FORMAT_ASTC_6x6_SRGB_BLOCK,Sn as VK_FORMAT_ASTC_6x6_UNORM_BLOCK,ui as VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT,Tn as VK_FORMAT_ASTC_8x5_SRGB_BLOCK,On as VK_FORMAT_ASTC_8x5_UNORM_BLOCK,bi as VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT,En as VK_FORMAT_ASTC_8x6_SRGB_BLOCK,Vn as VK_FORMAT_ASTC_8x6_UNORM_BLOCK,di as VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT,Pn as VK_FORMAT_ASTC_8x8_SRGB_BLOCK,Fn as VK_FORMAT_ASTC_8x8_UNORM_BLOCK,Me as VK_FORMAT_B10G11R11_UFLOAT_PACK32,$n as VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16,si as VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16,at as VK_FORMAT_B4G4R4A4_UNORM_PACK16,ft as VK_FORMAT_B5G5R5A1_UNORM_PACK16,ot as VK_FORMAT_B5G6R5_UNORM_PACK16,Mt as VK_FORMAT_B8G8R8A8_SINT,Ct as VK_FORMAT_B8G8R8A8_SNORM,Wt as VK_FORMAT_B8G8R8A8_SRGB,zt as VK_FORMAT_B8G8R8A8_UINT,Pt as VK_FORMAT_B8G8R8A8_UNORM,St as VK_FORMAT_B8G8R8_SINT,kt as VK_FORMAT_B8G8R8_SNORM,It as VK_FORMAT_B8G8R8_SRGB,vt as VK_FORMAT_B8G8R8_UINT,At as VK_FORMAT_B8G8R8_UNORM,Qe as VK_FORMAT_BC1_RGBA_SRGB_BLOCK,Je as VK_FORMAT_BC1_RGBA_UNORM_BLOCK,Ge as VK_FORMAT_BC1_RGB_SRGB_BLOCK,qe as VK_FORMAT_BC1_RGB_UNORM_BLOCK,$e as VK_FORMAT_BC2_SRGB_BLOCK,Ze as VK_FORMAT_BC2_UNORM_BLOCK,en as VK_FORMAT_BC3_SRGB_BLOCK,tn as VK_FORMAT_BC3_UNORM_BLOCK,sn as VK_FORMAT_BC4_SNORM_BLOCK,nn as VK_FORMAT_BC4_UNORM_BLOCK,rn as VK_FORMAT_BC5_SNORM_BLOCK,an as VK_FORMAT_BC5_UNORM_BLOCK,ln as VK_FORMAT_BC6H_SFLOAT_BLOCK,on as VK_FORMAT_BC6H_UFLOAT_BLOCK,Un as VK_FORMAT_BC7_SRGB_BLOCK,fn as VK_FORMAT_BC7_UNORM_BLOCK,Ne as VK_FORMAT_D16_UNORM,je as VK_FORMAT_D16_UNORM_S8_UINT,Re as VK_FORMAT_D24_UNORM_S8_UINT,Ke as VK_FORMAT_D32_SFLOAT,Ye as VK_FORMAT_D32_SFLOAT_S8_UINT,We as VK_FORMAT_E5B9G9R9_UFLOAT_PACK32,dn as VK_FORMAT_EAC_R11G11_SNORM_BLOCK,bn as VK_FORMAT_EAC_R11G11_UNORM_BLOCK,un as VK_FORMAT_EAC_R11_SNORM_BLOCK,xn as VK_FORMAT_EAC_R11_UNORM_BLOCK,pn as VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK,_n as VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK,yn as VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK,gn as VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK,hn as VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK,cn as VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK,Zn as VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16,ii as VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16,fi as VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG,ai as VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG,Ui as VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG,ri as VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG,ci as VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG,oi as VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG,hi as VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG,li as VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG,Qn as VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,Jn as VK_FORMAT_R10X6G10X6_UNORM_2PACK16,Gn as VK_FORMAT_R10X6_UNORM_PACK16,ni as VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16,ei as VK_FORMAT_R12X4G12X4_UNORM_2PACK16,ti as VK_FORMAT_R12X4_UNORM_PACK16,pe as VK_FORMAT_R16G16B16A16_SFLOAT,_e as VK_FORMAT_R16G16B16A16_SINT,ce as VK_FORMAT_R16G16B16A16_SNORM,he as VK_FORMAT_R16G16B16A16_UINT,Ue as VK_FORMAT_R16G16B16A16_UNORM,fe as VK_FORMAT_R16G16B16_SFLOAT,le as VK_FORMAT_R16G16B16_SINT,re as VK_FORMAT_R16G16B16_SNORM,oe as VK_FORMAT_R16G16B16_UINT,ae as VK_FORMAT_R16G16B16_UNORM,se as VK_FORMAT_R16G16_SFLOAT,ie as VK_FORMAT_R16G16_SINT,ee as VK_FORMAT_R16G16_SNORM,ne as VK_FORMAT_R16G16_UINT,te as VK_FORMAT_R16G16_UNORM,$t as VK_FORMAT_R16_SFLOAT,Zt as VK_FORMAT_R16_SINT,Jt as VK_FORMAT_R16_SNORM,Qt as VK_FORMAT_R16_UINT,Gt as VK_FORMAT_R16_UNORM,Ae as VK_FORMAT_R32G32B32A32_SFLOAT,Le as VK_FORMAT_R32G32B32A32_SINT,Be as VK_FORMAT_R32G32B32A32_UINT,De as VK_FORMAT_R32G32B32_SFLOAT,we as VK_FORMAT_R32G32B32_SINT,me as VK_FORMAT_R32G32B32_UINT,de as VK_FORMAT_R32G32_SFLOAT,be as VK_FORMAT_R32G32_SINT,ue as VK_FORMAT_R32G32_UINT,xe as VK_FORMAT_R32_SFLOAT,ye as VK_FORMAT_R32_SINT,ge as VK_FORMAT_R32_UINT,st as VK_FORMAT_R4G4B4A4_UNORM_PACK16,it as VK_FORMAT_R4G4_UNORM_PACK8,lt as VK_FORMAT_R5G5B5A1_UNORM_PACK16,rt as VK_FORMAT_R5G6B5_UNORM_PACK16,ze as VK_FORMAT_R64G64B64A64_SFLOAT,Ce as VK_FORMAT_R64G64B64A64_SINT,Pe as VK_FORMAT_R64G64B64A64_UINT,Fe as VK_FORMAT_R64G64B64_SFLOAT,Ee as VK_FORMAT_R64G64B64_SINT,Ve as VK_FORMAT_R64G64B64_UINT,Te as VK_FORMAT_R64G64_SFLOAT,Oe as VK_FORMAT_R64G64_SINT,Ie as VK_FORMAT_R64G64_UINT,Se as VK_FORMAT_R64_SFLOAT,ve as VK_FORMAT_R64_SINT,ke as VK_FORMAT_R64_UINT,Et as VK_FORMAT_R8G8B8A8_SINT,Tt as VK_FORMAT_R8G8B8A8_SNORM,Ft as VK_FORMAT_R8G8B8A8_SRGB,Vt as VK_FORMAT_R8G8B8A8_UINT,Ot as VK_FORMAT_R8G8B8A8_UNORM,Bt as VK_FORMAT_R8G8B8_SINT,wt as VK_FORMAT_R8G8B8_SNORM,Lt as VK_FORMAT_R8G8B8_SRGB,Dt as VK_FORMAT_R8G8B8_UINT,mt as VK_FORMAT_R8G8B8_UNORM,bt as VK_FORMAT_R8G8_SINT,xt as VK_FORMAT_R8G8_SNORM,dt as VK_FORMAT_R8G8_SRGB,ut as VK_FORMAT_R8G8_UINT,yt as VK_FORMAT_R8G8_UNORM,pt as VK_FORMAT_R8_SINT,ht as VK_FORMAT_R8_SNORM,gt as VK_FORMAT_R8_SRGB,_t as VK_FORMAT_R8_UINT,ct as VK_FORMAT_R8_UNORM,Xe as VK_FORMAT_S8_UINT,nt as VK_FORMAT_UNDEFINED,He as VK_FORMAT_X8_D24_UNORM_PACK32,Pi as read,Mi as write}; | 2 |
PHP | PHP | use import cleanup | e780ddabe0d9ea233af14a4cff48077da988c0e2 | <ide><path>src/View/AjaxView.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Controller\Controller;
<del>use Cake\Core\Configure;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide> use Cake\Network\Response;
<ide><path>src/View/Cell.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Core\App;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Model\ModelAwareTrait;
<ide><path>src/View/Form/EntityContext.php
<ide> use Cake\ORM\Entity;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\Utility\Inflector;
<del>use Cake\Validation\Validator;
<ide> use Cake\View\Form\ContextInterface;
<ide> use Traversable;
<ide>
<ide><path>src/View/Helper.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Core\Plugin;
<ide> use Cake\Event\EventListener;
<ide> use Cake\Routing\Router;
<del>use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<ide>
<ide> /**
<ide><path>src/View/Helper/CacheHelper.php
<ide> namespace Cake\View\Helper;
<ide>
<ide> use Cake\Core\Configure;
<add>use Cake\Event\Event;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Helper;
<ide>
<ide> protected function _enabled() {
<ide> * @param string $output The output for the file.
<ide> * @return string Updated content.
<ide> */
<del> public function afterRenderFile($event, $viewFile, $output) {
<add> public function afterRenderFile(Event $event, $viewFile, $output) {
<ide> if ($this->_enabled()) {
<ide> return $this->_parseContent($viewFile, $output);
<ide> }
<ide> public function afterRenderFile($event, $viewFile, $output) {
<ide> * @param string $layoutFile Layout file name.
<ide> * @return void
<ide> */
<del> public function afterLayout($event, $layoutFile) {
<add> public function afterLayout(Event $event, $layoutFile) {
<ide> if ($this->_enabled()) {
<ide> $this->_View->assign(
<ide> 'content',
<ide><path>src/View/Helper/FlashHelper.php
<ide> */
<ide> namespace Cake\View\Helper;
<ide>
<del>use Cake\Network\Session;
<ide> use Cake\View\Helper;
<del>use Cake\View\View;
<ide>
<ide> /**
<ide> * FlashHelper class to render flash messages.
<ide><path>src/View/Helper/FormHelper.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Error;
<ide> use Cake\ORM\Entity;
<del>use Cake\ORM\TableRegistry;
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Hash;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Helper;
<ide> use Cake\View\Helper\IdGeneratorTrait;
<ide> use Cake\View\Helper\StringTemplateTrait;
<del>use Cake\View\StringTemplate;
<ide> use Cake\View\View;
<ide> use Cake\View\Widget\WidgetRegistry;
<ide> use DateTime;
<ide><path>src/View/Helper/HtmlHelper.php
<ide> */
<ide> namespace Cake\View\Helper;
<ide>
<del>use Cake\Core\App;
<ide> use Cake\Core\Configure;
<del>use Cake\Error;
<ide> use Cake\Network\Response;
<del>use Cake\Utility\Inflector;
<ide> use Cake\View\Helper;
<ide> use Cake\View\Helper\StringTemplateTrait;
<ide> use Cake\View\View;
<ide><path>src/View/Helper/NumberHelper.php
<ide>
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<del>use Cake\Utility\Hash;
<ide> use Cake\View\Helper;
<ide> use Cake\View\View;
<ide>
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> */
<ide> namespace Cake\View\Helper;
<ide>
<add>use Cake\Event\Event;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\View\Helper;
<del>use Cake\View\View;
<ide>
<ide> /**
<ide> * Pagination Helper class for easy generation of pagination links.
<ide> class PaginatorHelper extends Helper {
<ide> * @param string $viewFile The view file being rendered.
<ide> * @return void
<ide> */
<del> public function beforeRender($event, $viewFile) {
<add> public function beforeRender(Event $event, $viewFile) {
<ide> $this->config(
<ide> 'options.url',
<ide> array_merge($this->request->params['pass'], $this->request->query)
<ide><path>src/View/Helper/SessionHelper.php
<ide> */
<ide> namespace Cake\View\Helper;
<ide>
<del>use Cake\Network\Session;
<ide> use Cake\View\Helper;
<ide> use Cake\View\Helper\StringTemplateTrait;
<del>use Cake\View\View;
<ide>
<ide> /**
<ide> * Session Helper.
<ide><path>src/View/Helper/StringTemplateTrait.php
<ide> public function formatTemplate($name, $data) {
<ide> */
<ide> public function templater() {
<ide> if (empty($this->_templater)) {
<del> $class = $this->config('templateClass') ?: '\Cake\View\StringTemplate';
<add> $class = $this->config('templateClass') ?: 'Cake\View\StringTemplate';
<ide> $this->_templater = new $class;
<ide>
<ide> $templates = $this->config('templates');
<ide><path>src/View/Helper/TextHelper.php
<ide>
<ide> use Cake\Core\App;
<ide> use Cake\Error;
<del>use Cake\Utility\Hash;
<ide> use Cake\View\Helper;
<ide> use Cake\View\View;
<ide>
<ide><path>src/View/HelperRegistry.php
<ide> namespace Cake\View;
<ide>
<ide> use Cake\Core\App;
<del>use Cake\Event\EventManager;
<ide> use Cake\Event\EventManagerTrait;
<ide> use Cake\Utility\ObjectRegistry;
<ide> use Cake\View\View;
<ide><path>src/View/JsonView.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide><path>src/View/View.php
<ide> namespace Cake\View;
<ide>
<ide> use Cake\Cache\Cache;
<del>use Cake\Controller\Controller;
<ide> use Cake\Core\App;
<ide> use Cake\Core\Configure;
<ide> use Cake\Core\Plugin;
<ide><path>src/View/Widget/DateTime.php
<ide> */
<ide> namespace Cake\View\Widget;
<ide>
<del>use Cake\Utility\Time;
<ide> use Cake\View\Form\ContextInterface;
<ide> use Cake\View\StringTemplate;
<add>use Cake\View\Widget\SelectBox;
<ide> use Cake\View\Widget\WidgetInterface;
<ide>
<ide> /**
<ide> class DateTime implements WidgetInterface {
<ide> * @param \Cake\View\StringTemplate $templates Templates list.
<ide> * @param \Cake\View\Widget\SelectBox $selectBox Selectbox widget instance.
<ide> */
<del> public function __construct($templates, $selectBox) {
<add> public function __construct(StringTemplate $templates, SelectBox $selectBox) {
<ide> $this->_select = $selectBox;
<ide> $this->_templates = $templates;
<ide> }
<ide><path>src/View/XmlView.php
<ide> */
<ide> namespace Cake\View;
<ide>
<del>use Cake\Controller\Controller;
<ide> use Cake\Core\Configure;
<ide> use Cake\Event\EventManager;
<ide> use Cake\Network\Request;
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> namespace Cake\Test\TestCase\View\Helper;
<ide>
<ide> use Cake\Core\Configure;
<add>use Cake\Event\Event;
<ide> use Cake\Network\Request;
<ide> use Cake\Routing\Router;
<ide> use Cake\TestSuite\TestCase;
<ide> public function testPassedArgsMergingWithUrlOptions() {
<ide>
<ide> $this->Paginator->request->params['pass'] = array(2);
<ide> $this->Paginator->request->query = array('page' => 1, 'foo' => 'bar', 'x' => 'y');
<del> $this->Paginator->beforeRender(null, 'posts/index');
<add> $this->Paginator->beforeRender(new Event('Foo.bar'), 'posts/index');
<ide>
<ide> $result = $this->Paginator->sort('title');
<ide> $expected = array( | 19 |
Python | Python | call engine.dispose after fork. closes | e268766c4af2088f0a51074e100fb0d3b45fbfeb | <ide><path>celery/backends/database/session.py
<ide> from __future__ import absolute_import
<ide>
<ide> from collections import defaultdict
<add>from multiprocessing.util import register_after_fork
<ide>
<ide> from sqlalchemy import create_engine
<ide> from sqlalchemy.orm import sessionmaker
<ide> __all__ = ['ResultSession', 'get_engine', 'create_session']
<ide>
<ide>
<add>class _after_fork(object):
<add> registered = False
<add>
<add> def __call__(self):
<add> self.registered = False # child must reregister
<add> for engine in list(_ENGINES.values()):
<add> engine.dispose()
<add> _ENGINES.clear()
<add> _SESSIONS.clear()
<add>after_fork = _after_fork()
<add>
<add>
<ide> def get_engine(dburi, **kwargs):
<del> if dburi not in _ENGINES:
<del> _ENGINES[dburi] = create_engine(dburi, **kwargs)
<del> return _ENGINES[dburi]
<add> try:
<add> return _ENGINES[dburi]
<add> except KeyError:
<add> engine = _ENGINES[dburi] = create_engine(dburi, **kwargs)
<add> after_fork.registered = True
<add> register_after_fork(after_fork, after_fork)
<add> return engine
<ide>
<ide>
<ide> def create_session(dburi, short_lived_sessions=False, **kwargs):
<ide> engine = get_engine(dburi, **kwargs)
<ide> if short_lived_sessions or dburi not in _SESSIONS:
<del> _SESSIONS[dburi] = sessionmaker(bind=engine)
<add> session = _SESSIONS[dburi] = sessionmaker(bind=engine)
<ide> return engine, _SESSIONS[dburi]
<ide>
<ide> | 1 |
Ruby | Ruby | add regression test for tz grep | 53d68bd964af17484898c5cd5e21a8ce9c359143 | <ide><path>actionpack/test/template/form_options_helper_test.rb
<ide> def test_time_zone_select_with_priority_zones_as_regexp
<ide> "</select>",
<ide> html
<ide> end
<add>
<add> def test_time_zone_select_with_priority_zones_as_regexp_using_grep_finds_no_zones
<add> @firm = Firm.new("D")
<add>
<add> priority_zones = /A|D/
<add> @fake_timezones.each_with_index do |tz, i|
<add> priority_zones.stubs(:===).with(tz).raises(Exception)
<add> end
<add>
<add> html = time_zone_select("firm", "time_zone", priority_zones)
<add> assert_dom_equal "<select id=\"firm_time_zone\" name=\"firm[time_zone]\">" +
<add> "<option value=\"\" disabled=\"disabled\">-------------</option>\n" +
<add> "<option value=\"A\">A</option>\n" +
<add> "<option value=\"B\">B</option>\n" +
<add> "<option value=\"C\">C</option>\n" +
<add> "<option value=\"D\" selected=\"selected\">D</option>\n" +
<add> "<option value=\"E\">E</option>" +
<add> "</select>",
<add> html
<add> end
<ide>
<ide> def test_time_zone_select_with_default_time_zone_and_nil_value
<ide> @firm = Firm.new() | 1 |
Javascript | Javascript | remove jstd leftovers | 89efb12ed852070a93777c5ff0ed3f9bc822bdf0 | <ide><path>angularFiles.js
<ide> angularFiles = {
<ide> 'test/matchers.js',
<ide> 'test/ngScenario/*.js',
<ide> 'test/ngScenario/output/*.js',
<del> 'test/ngScenario/jstd-scenario-adapter/*.js',
<ide> 'test/*.js',
<ide> 'test/auto/*.js',
<ide> 'test/ng/**/*.js',
<ide> angularFiles = {
<ide> ],
<ide>
<ide> 'jstd': [
<del> 'lib/jasmine/jasmine.js',
<del> 'lib/jasmine-jstd-adapter/JasmineAdapter.js',
<ide> 'components/jquery/jquery.js',
<ide> 'test/jquery_remove.js',
<ide> '@angularSrc',
<ide> 'src/publishExternalApis.js',
<ide> '@angularSrcModules',
<ide> '@angularScenario',
<del> 'src/ngScenario/jstd-scenario-adapter/Adapter.js',
<ide> '@angularTest',
<ide> 'example/personalLog/*.js',
<ide> 'example/personalLog/test/*.js'
<ide> angularFiles = {
<ide>
<ide> 'jstdScenario': [
<ide> 'build/angular-scenario.js',
<del> 'build/jstd-scenario-adapter-config.js',
<del> 'build/jstd-scenario-adapter.js',
<ide> 'build/docs/docs-scenario.js'
<ide> ],
<ide>
<ide> "jstdModules": [
<del> 'lib/jasmine/jasmine.js',
<del> 'lib/jasmine-jstd-adapter/JasmineAdapter.js',
<ide> 'build/angular.js',
<ide> '@angularSrcModules',
<ide> 'src/ngScenario/browserTrigger.js',
<ide> angularFiles = {
<ide> ],
<ide>
<ide> 'jstdPerf': [
<del> 'lib/jasmine/jasmine.js',
<del> 'lib/jasmine-jstd-adapter/JasmineAdapter.js',
<ide> '@angularSrc',
<ide> '@angularSrcModules',
<ide> 'src/ngMock/angular-mocks.js',
<ide> angularFiles = {
<ide> ],
<ide>
<ide> 'jstdJquery': [
<del> 'lib/jasmine/jasmine.js',
<del> 'lib/jasmine-jstd-adapter/JasmineAdapter.js',
<ide> 'components/jquery/jquery.js',
<ide> 'test/jquery_alias.js',
<ide> '@angularSrc',
<ide> 'src/publishExternalApis.js',
<ide> '@angularSrcModules',
<ide> '@angularScenario',
<del> 'src/ngScenario/jstd-scenario-adapter/Adapter.js',
<ide> '@angularTest',
<ide> 'example/personalLog/*.js',
<ide>
<ide><path>test/ngScenario/jstd-scenario-adapter/AdapterSpecs.js
<del>'use strict';
<del>
<del>describe('jstd-adapter', function() {
<del> var fakeJSTD = { pluginRegistrar: { register: function() {} } },
<del> originalNavigateTo = angular.scenario.Application.prototype.navigateTo;
<del>
<del> /**
<del> * Reverts hack on angular.scenario.Application.navigateTo
<del> * We should revert this hack after any single call of initScenarioAdapter,
<del> * so that it doesn't influence other tests...
<del> */
<del> function revertNavigateToHack() {
<del> angular.scenario.Application.prototype.navigateTo = originalNavigateTo;
<del> }
<del>
<del> /**
<del> * Helper for building angular.scenario.ObjectModel.Spec
<del> * @returns {angular.scenario.ObjectModel.Spec}
<del> */
<del> function buildSpec(status, name, duration, definitions, error, line) {
<del> var spec = new angular.scenario.ObjectModel.Spec(
<del> 'fake-id', name || 'name', definitions || ['desc1', 'desc2']);
<del> spec.duration = duration || 10;
<del> spec.status = status || 'success';
<del> spec.error = error || '';
<del> spec.line = line || '';
<del>
<del> return spec;
<del> }
<del>
<del> /**
<del> * Helper for building angular.scenario.ObjectModel.Spec with error and error line
<del> * @returns {angular.scenario.ObjectModel.Spec}
<del> */
<del> function buildErrorSpec(error, line, status, name) {
<del> return buildSpec(status || 'error', name, null, null, error, line);
<del> }
<del>
<del> /**
<del> * Helper for building TestConfiguration
<del> * @returns {jstestdriver.TestRunConfiguration}
<del> */
<del> function buildTestConf(type) {
<del> return new jstestdriver.TestRunConfiguration(
<del> new jstestdriver.TestCaseInfo('Fake test - ' + Math.random(), function() {}, type), null);
<del> }
<del>
<del> /**
<del> * Helper for building SCENARIO TestConfiguration
<del> * @returns {jstestdriver.TestRunConfiguration}
<del> */
<del> function buildScenarioTestConf() {
<del> return buildTestConf(SCENARIO_TYPE);
<del> }
<del>
<del> describe('initScenarioAdapter', function() {
<del> afterEach(revertNavigateToHack);
<del>
<del> it('should create and register plugin if jstestdriver defined', function() {
<del> spyOn(fakeJSTD.pluginRegistrar, 'register');
<del> initScenarioAdapter(fakeJSTD);
<del> expect(fakeJSTD.pluginRegistrar.register).toHaveBeenCalled();
<del> expect(fakeJSTD.pluginRegistrar.register.mostRecentCall.args[0] instanceof JstdPlugin);
<del> });
<del>
<del> it('should do nothing if jstestdriver not defined', function() {
<del> expect(function() {
<del> initScenarioAdapter(undefined);
<del> }).not.toThrow();
<del> });
<del>
<del> it('should set setUpAndRun callback to plugin', function() {
<del> var runFn = jasmine.createSpy('setUpAndRun');
<del> plugin.runScenario = null;
<del>
<del> initScenarioAdapter(fakeJSTD, runFn);
<del> expect(plugin.runScenario).toBe(runFn);
<del> });
<del>
<del> describe('navigateTo', function() {
<del> var fakeJSTD = { pluginRegistrar: { register: function() {} } },
<del> app = new angular.scenario.Application(_jQuery('<div></div>')),
<del> navigateSpy;
<del>
<del> beforeEach(function() {
<del> navigateSpy = spyOn(angular.scenario.Application.prototype, 'navigateTo');
<del> });
<del>
<del> it('should add url prefix when jstd defined', function() {
<del> initScenarioAdapter(fakeJSTD, null, {relativeUrlPrefix: '/prefix/'});
<del>
<del> app.navigateTo('test.html');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('/prefix/test.html');
<del> });
<del>
<del> it('should add forward-slash as default url prefix when jstd defined', function() {
<del> initScenarioAdapter(fakeJSTD);
<del>
<del> app.navigateTo('test.html');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('/test.html');
<del> });
<del>
<del> it('should not change url when jstd not defined', function() {
<del> initScenarioAdapter(null);
<del>
<del> app.navigateTo('test.html');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('test.html');
<del> });
<del>
<del> it('should not change hash url', function() {
<del> initScenarioAdapter(fakeJSTD);
<del>
<del> app.navigateTo('#/index.html/a');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('#/index.html/a');
<del> });
<del>
<del> it('should not change absolute url', function() {
<del> initScenarioAdapter(fakeJSTD);
<del>
<del> app.navigateTo('/index.html/a');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('/index.html/a');
<del> });
<del>
<del> it('should not change "about:blank" url', function() {
<del> initScenarioAdapter(fakeJSTD);
<del>
<del> app.navigateTo('about:blank');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('about:blank');
<del> });
<del>
<del> it('should not change url with domain', function() {
<del> initScenarioAdapter(fakeJSTD);
<del>
<del> app.navigateTo('http://www.google.com');
<del> expect(navigateSpy).toHaveBeenCalled();
<del> expect(navigateSpy.mostRecentCall.args[0]).toEqual('http://www.google.com');
<del> });
<del> });
<del> });
<del>
<del> describe('JstdPlugin', function() {
<del> var p;
<del>
<del> beforeEach(function() {
<del> p = new JstdPlugin();
<del> });
<del>
<del> describe('runTestConfiguration', function() {
<del> var initScenarioSpy, onTestSpy, onAllTestsSpy, spec, modelSpec;
<del>
<del> beforeEach(function() {
<del> initScenarioSpy = jasmine.createSpy('initScenarioAndRun');
<del> onTestSpy = jasmine.createSpy('onOneTest');
<del> onAllTestsSpy = jasmine.createSpy('onAllTests');
<del>
<del> p.runScenario = initScenarioSpy;
<del> spec = {id: 'fake', name: 'Spec Name'};
<del> modelSpec = new angular.scenario.ObjectModel.Spec(spec.id, spec.name);
<del> });
<del>
<del> it('should ignore non scenario test cases', function() {
<del> expect(p.runTestConfiguration(buildTestConf(), onTestSpy, onAllTestsSpy)).toBe(false);
<del> expect(p.runTestConfiguration(buildTestConf('async'), onTestSpy, onAllTestsSpy)).toBe(false);
<del> expect(initScenarioSpy).not.toHaveBeenCalled();
<del> expect(onTestSpy).not.toHaveBeenCalled();
<del> expect(onAllTestsSpy).not.toHaveBeenCalled();
<del> });
<del>
<del> it('should return true when scenario test case', function() {
<del> expect(p.runTestConfiguration(buildScenarioTestConf(), onTestSpy, onAllTestsSpy)).toBe(true);
<del> });
<del>
<del> it('should call initAndRunTests when scenario test case', function() {
<del> p.runTestConfiguration(buildScenarioTestConf(), onTestSpy, onAllTestsSpy);
<del> expect(initScenarioSpy).toHaveBeenCalled();
<del> });
<del> });
<del>
<del> describe('getTestRunsConfigurationFor', function() {
<del> it('should add TestRunConfiguration with SCENARIO_TYPE TestCase', function() {
<del> var configurations = [];
<del> p.getTestRunsConfigurationFor(null, null, configurations);
<del>
<del> expect(configurations.length).toBe(1);
<del> expect(configurations[0] instanceof jstestdriver.TestRunConfiguration).toBe(true);
<del> expect(configurations[0].getTestCaseInfo().getType()).toEqual(SCENARIO_TYPE);
<del> });
<del>
<del> it('should always return true', function() {
<del> expect(p.getTestRunsConfigurationFor(null, null, [])).toBe(true);
<del> });
<del> });
<del> });
<del>
<del> describe('createTestResultFromSpec', function() {
<del> it('should return jstestdriver.TestResult instance', function() {
<del> expect(createTestResultFromSpec(buildSpec()) instanceof jstestdriver.TestResult).toBe(true);
<del> });
<del>
<del> it('should set proper test name', function() {
<del> expect(createTestResultFromSpec(buildSpec()).testName).toEqual('name');
<del> });
<del>
<del> it('should set duration', function() {
<del> expect(createTestResultFromSpec(buildSpec()).time).toEqual(10);
<del> });
<del>
<del> it('should set test case - full definition name', function() {
<del> var spec = buildSpec();
<del> expect(createTestResultFromSpec(spec).testCaseName).toEqual(spec.fullDefinitionName);
<del> });
<del>
<del> it('should set passed result when success', function() {
<del> expect(createTestResultFromSpec(buildSpec('success')).result)
<del> .toEqual(jstestdriver.TestResult.RESULT.PASSED);
<del> });
<del>
<del> it('should set error result when error', function() {
<del> expect(createTestResultFromSpec(buildSpec('error')).result)
<del> .toEqual(jstestdriver.TestResult.RESULT.ERROR);
<del> });
<del>
<del> it('should set failed result when failure', function() {
<del> expect(createTestResultFromSpec(buildSpec('failure')).result)
<del> .toEqual(jstestdriver.TestResult.RESULT.FAILED);
<del> });
<del>
<del> it('should set error message when error/failure', function() {
<del> expect(createTestResultFromSpec(buildErrorSpec('error-message')).message)
<del> .toEqual('error-message');
<del> });
<del>
<del> it('should log line number when error/failure', function() {
<del> expect(createTestResultFromSpec(buildErrorSpec('msg', 'line-number')).log)
<del> .toEqual('line-number');
<del> });
<del> });
<del>
<del> describe('angular.scenario.output.jstd', function() {
<del> var model;
<del>
<del> beforeEach(function() {
<del> var runner = new angular.scenario.testing.MockRunner(),
<del> context = _jQuery("<div></div>");
<del>
<del> plugin = new JstdPlugin();
<del> model = new angular.scenario.ObjectModel(runner);
<del> angular.scenario.output.jstd(context, runner, model);
<del>
<del> spyOn(plugin, 'reportEnd');
<del> spyOn(plugin, 'reportResult');
<del> });
<del>
<del> it('should report end of all tests', function() {
<del> model.emit('RunnerEnd');
<del> expect(plugin.reportEnd).toHaveBeenCalled();
<del> });
<del>
<del> it('should report jstestdriver.TestResult', function() {
<del> model.emit('SpecEnd', buildSpec());
<del> expect(plugin.reportResult).toHaveBeenCalled();
<del> expect(plugin.reportResult.argsForCall[0][0] instanceof jstestdriver.TestResult).toBe(true);
<del> });
<del> });
<del>
<del> // couple of higher level tests (wiring objects together)
<del> describe('HIGHER LEVEL', function() {
<del> var initScenarioSpy, onTestSpy, onAllTestsSpy, model;
<del>
<del> beforeEach(function() {
<del> plugin = new JstdPlugin();
<del> initScenarioSpy = jasmine.createSpy('initScenarioAndRun');
<del> onTestSpy = jasmine.createSpy('onOneTest');
<del> onAllTestsSpy = jasmine.createSpy('onAllTests');
<del>
<del> var runner = new angular.scenario.testing.MockRunner(),
<del> context = _jQuery("<div></div>");
<del>
<del> model = new angular.scenario.ObjectModel(runner);
<del> angular.scenario.output.jstd(context, runner, model);
<del>
<del> initScenarioAdapter(fakeJSTD, initScenarioSpy);
<del> plugin.runTestConfiguration(buildScenarioTestConf(), onTestSpy, onAllTestsSpy);
<del> });
<del>
<del> afterEach(revertNavigateToHack);
<del>
<del> it('should report and of test suite', function() {
<del> model.emit('RunnerEnd');
<del> expect(onAllTestsSpy).toHaveBeenCalled();
<del> });
<del>
<del> it('should report success test result', function() {
<del> model.emit('SpecEnd', buildSpec('success', 'name'));
<del> expect(onTestSpy).toHaveBeenCalled();
<del> var result = onTestSpy.argsForCall[0][0];
<del> expect(result instanceof jstestdriver.TestResult).toBe(true);
<del> expect(result.testName).toEqual('name');
<del> expect(result.result).toEqual(jstestdriver.TestResult.RESULT.PASSED);
<del> });
<del>
<del> it('should report error test result', function() {
<del> model.emit('SpecEnd', buildSpec('error'));
<del> expect(onTestSpy).toHaveBeenCalled();
<del> var result = onTestSpy.argsForCall[0][0];
<del> expect(result.result).toEqual(jstestdriver.TestResult.RESULT.ERROR);
<del> });
<del>
<del> it('should report failed test result', function() {
<del> model.emit('SpecEnd', buildSpec('failure'));
<del> expect(onTestSpy).toHaveBeenCalled();
<del> var result = onTestSpy.argsForCall[0][0];
<del> expect(result.result).toEqual(jstestdriver.TestResult.RESULT.FAILED);
<del> });
<del> });
<del>}); | 2 |
Javascript | Javascript | set custom schema | 07cf7e3e7228ee43ea9e70520b0b4b137c86c75e | <ide><path>client/gatsby-node.js
<ide> exports.onCreatePage = async ({ page, actions }) => {
<ide> }
<ide> };
<ide>
<add>exports.createSchemaCustomization = ({ actions }) => {
<add> const { createTypes } = actions;
<add> const typeDefs = `
<add> type ChallengeNode implements Node {
<add> files: ChallengeFile
<add> }
<add> type ChallengeFile {
<add> indexcss: FileContents
<add> indexhtml: FileContents
<add> indexjs: FileContents
<add> indexjsx: FileContents
<add> }
<add> type FileContents {
<add> key: String
<add> ext: String
<add> name: String
<add> contents: String
<add> head: String
<add> tail: String
<add> editableRegionBoundaries: [Int]
<add> }
<add> `;
<add> createTypes(typeDefs);
<add>};
<add>
<ide> // TODO: this broke the React challenges, not sure why, but I'll investigate
<ide> // further and reimplement if it's possible and necessary (Oliver)
<add>// I'm still not sure why, but the above schema seems to work.
<ide> // Typically the schema can be inferred, but not when some challenges are
<ide> // skipped (at time of writing the Chinese only has responsive web design), so
<ide> // this makes the missing fields explicit. | 1 |
Javascript | Javascript | add plunkr support | 7c67b2fb6afbc18f3593c64a5f339f04f9003f3c | <ide><path>docs/src/templates/js/docs.js
<ide> docsApp.directive.code = function() {
<ide>
<ide> docsApp.directive.sourceEdit = function(getEmbeddedTemplate) {
<ide> return {
<del> template: '<button ng-click="fiddle($event)" class="btn btn-primary pull-right"><i class="icon-pencil icon-white"></i> Edit</button>\n',
<add> template: '<div class="btn-group pull-right">' +
<add> '<a class="btn dropdown-toggle btn-primary" data-toggle="dropdown" href>' +
<add> ' <i class="icon-pencil icon-white"></i> Edit<span class="caret"></span>' +
<add> '</a>' +
<add> '<ul class="dropdown-menu">' +
<add> ' <li><a ng-click="plunkr($event)" href="">In Plunkr</a></li>' +
<add> ' <li><a ng-click="fiddle($event)" href="">In JsFiddle</a></li>' +
<add> '</ul>',
<ide> scope: true,
<del> controller: function($scope, $attrs, openJsFiddle) {
<add> controller: function($scope, $attrs, openJsFiddle, openPlunkr) {
<ide> var sources = {
<ide> module: $attrs.sourceEdit,
<ide> deps: read($attrs.sourceEditDeps),
<ide> docsApp.directive.sourceEdit = function(getEmbeddedTemplate) {
<ide> $scope.fiddle = function(e) {
<ide> e.stopPropagation();
<ide> openJsFiddle(sources);
<del> }
<add> };
<add> $scope.plunkr = function(e) {
<add> e.stopPropagation();
<add> openPlunkr(sources);
<add> };
<ide> }
<ide> }
<ide>
<ide> docsApp.serviceFactory.formPostData = function($document) {
<ide> };
<ide> };
<ide>
<add>docsApp.serviceFactory.openPlunkr = function(templateMerge, formPostData, angularUrls) {
<add> return function(content) {
<add> var allFiles = [].concat(content.js, content.css, content.html);
<add> var indexHtmlContent = '<!doctype html>\n' +
<add> '<html ng-app>\n' +
<add> ' <head>\n' +
<add> ' <script src="{{angularJSUrl}}"></script>\n' +
<add> '{{scriptDeps}}\n' +
<add> ' </head>\n' +
<add> ' <body>\n\n' +
<add> '{{indexContents}}' +
<add> '\n\n </body>\n' +
<add> '</html>\n';
<add> var scriptDeps = '';
<add> angular.forEach(content.deps, function(file) {
<add> if (file.name !== 'angular.js') {
<add> scriptDeps += ' <script src="' + file.name + '"></script>\n'
<add> }
<add> });
<add> indexProp = {
<add> angularJSUrl: angularUrls['angular.js'],
<add> scriptDeps: scriptDeps,
<add> indexContents: content.html[0].content
<add> };
<add> var postData = {};
<add> angular.forEach(allFiles, function(file, index) {
<add> if (file.content && file.name != 'index.html') {
<add> postData['files[' + file.name + ']'] = file.content;
<add> }
<add> });
<add>
<add> postData['files[index.html]'] = templateMerge(indexHtmlContent, indexProp);
<add>
<add> postData.description = 'AngularJS Example Plunkr';
<add>
<add> formPostData('http://plnkr.co/edit/?p=preview', postData);
<add> };
<add>};
<add>
<add>docsApp.serviceFactory.openJsFiddle = function(templateMerge, formPostData, angularUrls) {
<ide>
<del>docsApp.serviceFactory.openJsFiddle = function(templateMerge, getEmbeddedTemplate, formPostData, angularUrls) {
<ide> var HTML = '<div ng-app=\"{{module}}\">\n{{html:2}}</div>',
<ide> CSS = '</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> \n' +
<ide> '{{head:0}}<style>\n.ng-invalid { border: 1px solid red; }\n{{css}}', | 1 |
Python | Python | remove check for containerimage | 516840542769f8c879973e356b8a121d7581b439 | <ide><path>libcloud/container/drivers/lxd.py
<ide> def deploy_container(self, name, image, cluster=None,
<ide> if parameters:
<ide> parameters = json.loads(parameters)
<ide>
<del> if isinstance(image, ContainerImage):
<del> container = self._deploy_container_from_image(name=name, image=image, parameters=parameters,
<add> container = self._deploy_container_from_image(name=name, image=image, parameters=parameters,
<ide> container_params=container_params)
<del> else:
<del> raise LXDAPIException(message="'image' parameter must be a ContainerImage")
<ide>
<ide> if start:
<ide> container.start() | 1 |
PHP | PHP | add new tests | 591d2194b731804c438301a82522190c4397581c | <ide><path>tests/Integration/Database/EloquentFactoryBuilderTest.php
<ide> protected function getEnvironmentSetUp($app)
<ide> ];
<ide> });
<ide>
<add> $factory->define(FactoryBuildableProfile::class, function (Generator $faker) {
<add> return [
<add> 'user_id' => function () {
<add> return factory(FactoryBuildableUser::class)->create()->id;
<add> }
<add> ];
<add> });
<add>
<add> $factory->after(FactoryBuildableUser::class, 'make', function (FactoryBuildableUser $user, Generator $faker) {
<add> $profile =factory(FactoryBuildableProfile::class)->make(['user_id' => $user->id]);
<add> $user->setRelation('profile', $profile);
<add> });
<add>
<add> $factory->define(FactoryBuildableTeam::class, function (Generator $faker) {
<add> return [
<add> 'name' => $faker->name,
<add> 'owner_id' => function () {
<add> return factory(FactoryBuildableUser::class)->create()->id;
<add> },
<add> ];
<add> });
<add>
<add> $factory->after(FactoryBuildableTeam::class, function (FactoryBuildableTeam $team, Generator $faker) {
<add> $team->users()->attach($team->owner);
<add> });
<add>
<ide> $factory->define(FactoryBuildableServer::class, function (Generator $faker) {
<ide> return [
<ide> 'name' => $faker->name,
<ide> public function setUp()
<ide> $table->string('email');
<ide> });
<ide>
<add> Schema::create('profiles', function ($table) {
<add> $table->increments('id');
<add> $table->unsignedInteger('user_id');
<add> });
<add>
<add> Schema::create('teams', function ($table) {
<add> $table->increments('id');
<add> $table->string('name');
<add> $table->string('owner_id');
<add> });
<add>
<add> Schema::create('team_users', function ($table) {
<add> $table->increments('id');
<add> $table->unsignedInteger('team_id');
<add> $table->unsignedInteger('user_id');
<add> });
<add>
<ide> Schema::connection('alternative-connection')->create('users', function ($table) {
<ide> $table->increments('id');
<ide> $table->string('name');
<ide> public function creating_models_on_custom_connection()
<ide> $this->assertTrue($user->is($dbUser));
<ide> }
<ide>
<add> /** @test **/
<add> public function creating_models_with_after_callback()
<add> {
<add> $team = factory(FactoryBuildableTeam::class)->create();
<add>
<add> $this->assertTrue($team->users->contains($team->owner));
<add> }
<add>
<ide> /** @test */
<ide> public function making_models_with_a_custom_connection()
<ide> {
<ide> public function making_models_with_a_custom_connection()
<ide>
<ide> $this->assertEquals('alternative-connection', $user->getConnectionName());
<ide> }
<add>
<add> /** @test **/
<add> public function making_models_with_after_callback()
<add> {
<add> $user = factory(FactoryBuildableUser::class)->make();
<add>
<add> $this->assertNotNull($user->profile);
<add> }
<ide> }
<ide>
<ide> class FactoryBuildableUser extends Model
<ide> public function servers()
<ide> {
<ide> return $this->hasMany(FactoryBuildableServer::class, 'user_id');
<ide> }
<add>
<add> public function profile()
<add> {
<add> return $this->hasOne(FactoryBuildableProfile::class, 'user_id');
<add> }
<add>}
<add>
<add>class FactoryBuildableProfile extends Model
<add>{
<add> public $table = 'profiles';
<add> public $timestamps = false;
<add> protected $guarded = ['id'];
<add>
<add> public function user()
<add> {
<add> return $this->belongsTo(FactoryBuildableUser::class, 'user_id');
<add> }
<add>}
<add>
<add>class FactoryBuildableTeam extends Model
<add>{
<add> public $table = 'teams';
<add> public $timestamps = false;
<add> protected $guarded = ['id'];
<add>
<add> public function owner()
<add> {
<add> return $this->belongsTo(FactoryBuildableUser::class, 'owner_id');
<add> }
<add>
<add> public function users()
<add> {
<add> return $this->belongsToMany(
<add> FactoryBuildableUser::class,
<add> 'team_users',
<add> 'team_id',
<add> 'user_id'
<add> );
<add> }
<ide> }
<ide>
<ide> class FactoryBuildableServer extends Model | 1 |
Python | Python | fix code style | c5a407e95af8127fff0e5e5c8e0ebcaeed0288e1 | <ide><path>spacy/tests/vocab_vectors/test_vocab_api.py
<ide> def test_vocab_api_contains(en_vocab, text):
<ide>
<ide> def test_vocab_writing_system(en_vocab):
<ide> assert en_vocab.writing_system["direction"] == "ltr"
<del> assert en_vocab.writing_system["has_case"] == True
<add> assert en_vocab.writing_system["has_case"] is True | 1 |
Python | Python | replace deprecated functions | a46f826f5e3f063dc39cce339d4f836a167ce6b1 | <ide><path>im2txt/im2txt/ops/image_embedding_test.py
<ide> def testTrainableTrueIsTrainingTrue(self):
<ide> self.assertEqual([self._batch_size, 2048], embeddings.get_shape().as_list())
<ide>
<ide> self._verifyParameterCounts()
<del> self._assertCollectionSize(376, tf.GraphKeys.VARIABLES)
<add> self._assertCollectionSize(376, tf.GraphKeys.GLOBAL_VARIABLES)
<ide> self._assertCollectionSize(188, tf.GraphKeys.TRAINABLE_VARIABLES)
<ide> self._assertCollectionSize(188, tf.GraphKeys.UPDATE_OPS)
<ide> self._assertCollectionSize(94, tf.GraphKeys.REGULARIZATION_LOSSES)
<ide> def testTrainableTrueIsTrainingFalse(self):
<ide> self.assertEqual([self._batch_size, 2048], embeddings.get_shape().as_list())
<ide>
<ide> self._verifyParameterCounts()
<del> self._assertCollectionSize(376, tf.GraphKeys.VARIABLES)
<add> self._assertCollectionSize(376, tf.GraphKeys.GLOBAL_VARIABLES)
<ide> self._assertCollectionSize(188, tf.GraphKeys.TRAINABLE_VARIABLES)
<ide> self._assertCollectionSize(0, tf.GraphKeys.UPDATE_OPS)
<ide> self._assertCollectionSize(94, tf.GraphKeys.REGULARIZATION_LOSSES)
<ide> def testTrainableFalseIsTrainingTrue(self):
<ide> self.assertEqual([self._batch_size, 2048], embeddings.get_shape().as_list())
<ide>
<ide> self._verifyParameterCounts()
<del> self._assertCollectionSize(376, tf.GraphKeys.VARIABLES)
<add> self._assertCollectionSize(376, tf.GraphKeys.GLOBAL_VARIABLES)
<ide> self._assertCollectionSize(0, tf.GraphKeys.TRAINABLE_VARIABLES)
<ide> self._assertCollectionSize(0, tf.GraphKeys.UPDATE_OPS)
<ide> self._assertCollectionSize(0, tf.GraphKeys.REGULARIZATION_LOSSES)
<ide> def testTrainableFalseIsTrainingFalse(self):
<ide> self.assertEqual([self._batch_size, 2048], embeddings.get_shape().as_list())
<ide>
<ide> self._verifyParameterCounts()
<del> self._assertCollectionSize(376, tf.GraphKeys.VARIABLES)
<add> self._assertCollectionSize(376, tf.GraphKeys.GLOBAL_VARIABLES)
<ide> self._assertCollectionSize(0, tf.GraphKeys.TRAINABLE_VARIABLES)
<ide> self._assertCollectionSize(0, tf.GraphKeys.UPDATE_OPS)
<ide> self._assertCollectionSize(0, tf.GraphKeys.REGULARIZATION_LOSSES) | 1 |
PHP | PHP | add usetailwind method | bf1eef400951dcee04839a9ab7c15da1a807f89c | <ide><path>src/Illuminate/Pagination/AbstractPaginator.php
<ide> public static function defaultSimpleView($view)
<ide> static::$defaultSimpleView = $view;
<ide> }
<ide>
<add> /**
<add> * Indicate that Tailwind styling should be used for generated links.
<add> *
<add> * @return void
<add> */
<add> public static function useTailwind()
<add> {
<add> static::defaultView('pagination::tailwind');
<add> static::defaultSimpleView('pagination::simple-tailwind');
<add> }
<add>
<ide> /**
<ide> * Indicate that Bootstrap 3 styling should be used for generated links.
<ide> * | 1 |
Python | Python | fix xlnet run_classifier | 3fab0abd251488247e66ee89d34ea2e2185fa2fa | <ide><path>official/nlp/xlnet/run_classifier.py
<ide> def _run_evaluation(test_iterator):
<ide> _test_step_fn, args=(next(test_iterator),))
<ide> return logits, labels, masks
<ide>
<del> # pylint: disable=protected-access
<del> test_iterator = data_utils._get_input_iterator(test_input_fn, strategy)
<del> # pylint: enable=protected-access
<add> test_iterator = data_utils.get_input_iterator(test_input_fn, strategy)
<ide> correct = 0
<ide> total = 0
<ide> for _ in range(eval_steps): | 1 |
Python | Python | add "lovin'" to tokenizer exceptions (see ) | 123810b6ded7a0828c1c4c072fcc8b1287a0c5ed | <ide><path>spacy/lang/en/tokenizer_exceptions.py
<ide> {ORTH: "Ma'am", LEMMA: "madam", NORM: "madam"},
<ide> {ORTH: "o'clock", LEMMA: "o'clock", NORM: "o'clock"},
<ide> {ORTH: "O'clock", LEMMA: "o'clock", NORM: "o'clock"},
<add> {ORTH: "lovin'", LEMMA: "love", NORM: "loving"},
<add> {ORTH: "Lovin'", LEMMA: "love", NORM: "loving"},
<ide>
<ide> {ORTH: "Mt.", LEMMA: "Mount", NORM: "Mount"},
<ide> {ORTH: "Ak.", LEMMA: "Alaska", NORM: "Alaska"}, | 1 |
Java | Java | add debug statements to uimanager | 950cefa2d669c30bac92dee948c597f87bdcfb5b | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/UIManagerModule.java
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<add>import com.facebook.common.logging.FLog;
<ide> import com.facebook.react.animation.Animation;
<ide> import com.facebook.react.bridge.Callback;
<ide> import com.facebook.react.bridge.LifecycleEventListener;
<ide> import com.facebook.react.bridge.ReactMethod;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<del>import com.facebook.react.uimanager.DisplayMetricsHolder;
<add>import com.facebook.react.common.ReactConstants;
<ide> import com.facebook.react.uimanager.debug.NotThreadSafeViewHierarchyUpdateDebugListener;
<ide> import com.facebook.react.uimanager.events.EventDispatcher;
<ide> import com.facebook.systrace.Systrace;
<ide> public class UIManagerModule extends ReactContextBaseJavaModule implements
<ide> // Keep in sync with ReactIOSTagHandles JS module - see that file for an explanation on why the
<ide> // increment here is 10
<ide> private static final int ROOT_VIEW_TAG_INCREMENT = 10;
<add> private static final boolean DEBUG = false;
<ide>
<ide> private final EventDispatcher mEventDispatcher;
<ide> private final Map<String, Object> mModuleConstants;
<ide> public int addMeasuredRootView(final SizeMonitoringFrameLayout rootView) {
<ide> mUIImplementation.registerRootView(rootView, tag, width, height, themedRootContext);
<ide>
<ide> rootView.setOnSizeChangedListener(
<del> new SizeMonitoringFrameLayout.OnSizeChangedListener() {
<del> @Override
<del> public void onSizeChanged(final int width, final int height, int oldW, int oldH) {
<del> getReactApplicationContext().runOnNativeModulesQueueThread(
<del> new Runnable() {
<del> @Override
<del> public void run() {
<del> updateRootNodeSize(tag, width, height);
<del> }
<del> });
<del> }
<del> });
<add> new SizeMonitoringFrameLayout.OnSizeChangedListener() {
<add> @Override
<add> public void onSizeChanged(final int width, final int height, int oldW, int oldH) {
<add> getReactApplicationContext().runOnNativeModulesQueueThread(
<add> new Runnable() {
<add> @Override
<add> public void run() {
<add> updateRootNodeSize(tag, width, height);
<add> }
<add> });
<add> }
<add> });
<ide>
<ide> return tag;
<ide> }
<ide> private void updateRootNodeSize(int rootViewTag, int newWidth, int newHeight) {
<ide>
<ide> @ReactMethod
<ide> public void createView(int tag, String className, int rootViewTag, ReadableMap props) {
<add> if (DEBUG) {
<add> FLog.d(
<add> ReactConstants.TAG,
<add> "(UIManager.createView) tag: " + tag + ", class: " + className + ", props: " + props);
<add> }
<ide> mUIImplementation.createView(tag, className, rootViewTag, props);
<ide> }
<ide>
<ide> @ReactMethod
<ide> public void updateView(int tag, String className, ReadableMap props) {
<add> if (DEBUG) {
<add> FLog.d(
<add> ReactConstants.TAG,
<add> "(UIManager.updateView) tag: " + tag + ", class: " + className + ", props: " + props);
<add> }
<ide> mUIImplementation.updateView(tag, className, props);
<ide> }
<ide>
<ide> public void manageChildren(
<ide> @Nullable ReadableArray addChildTags,
<ide> @Nullable ReadableArray addAtIndices,
<ide> @Nullable ReadableArray removeFrom) {
<add> if (DEBUG) {
<add> FLog.d(
<add> ReactConstants.TAG,
<add> "(UIManager.manageChildren) tag: " + viewTag +
<add> ", moveFrom: " + moveFrom +
<add> ", moveTo: " + moveTo +
<add> ", addTags: " + addChildTags +
<add> ", atIndices: " + addAtIndices +
<add> ", removeFrom: " + removeFrom);
<add> }
<ide> mUIImplementation.manageChildren(
<ide> viewTag,
<ide> moveFrom,
<ide> public void manageChildren(
<ide> public void setChildren(
<ide> int viewTag,
<ide> ReadableArray childrenTags) {
<add> FLog.d(
<add> ReactConstants.TAG,
<add> "(UIManager.setChildren) tag: " + viewTag + ", children: " + childrenTags);
<ide> mUIImplementation.setChildren(viewTag, childrenTags);
<ide> }
<ide>
<ide> public void findSubviewIn(
<ide> final ReadableArray point,
<ide> final Callback callback) {
<ide> mUIImplementation.findSubviewIn(
<del> reactTag,
<del> Math.round(PixelUtil.toPixelFromDIP(point.getDouble(0))),
<del> Math.round(PixelUtil.toPixelFromDIP(point.getDouble(1))),
<del> callback);
<add> reactTag,
<add> Math.round(PixelUtil.toPixelFromDIP(point.getDouble(0))),
<add> Math.round(PixelUtil.toPixelFromDIP(point.getDouble(1))),
<add> callback);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix alphabetical order | 9051a027c56a415e81063ad587a143b276956ad9 | <ide><path>resources/lang/en/validation.php
<ide> 'ip' => 'The :attribute must be a valid IP address.',
<ide> 'ipv4' => 'The :attribute must be a valid IPv4 address.',
<ide> 'ipv6' => 'The :attribute must be a valid IPv6 address.',
<del> 'mac_address' => 'The :attribute must be a valid MAC address.',
<ide> 'json' => 'The :attribute must be a valid JSON string.',
<ide> 'lt' => [
<ide> 'numeric' => 'The :attribute must be less than :value.',
<ide> 'string' => 'The :attribute must be less than or equal to :value characters.',
<ide> 'array' => 'The :attribute must not have more than :value items.',
<ide> ],
<add> 'mac_address' => 'The :attribute must be a valid MAC address.',
<ide> 'max' => [
<ide> 'numeric' => 'The :attribute must not be greater than :max.',
<ide> 'file' => 'The :attribute must not be greater than :max kilobytes.', | 1 |
Python | Python | add tests for initializations | eda1a9e0a4eb786128a117409f26c5bf072ea172 | <ide><path>keras/initializations.py
<ide> def uniform(shape, scale=0.05):
<ide>
<ide>
<ide> def normal(shape, scale=0.05):
<del> return K.variable(np.random.randn(*shape) * scale)
<add> return K.variable(np.random.normal(loc=0.0, scale=scale, size=shape))
<ide>
<ide>
<ide> def lecun_uniform(shape):
<ide> def orthogonal(shape, scale=1.1):
<ide>
<ide> def identity(shape, scale=1):
<ide> if len(shape) != 2 or shape[0] != shape[1]:
<del> raise Exception("Identity matrix initialization can only be used for 2D square matrices")
<add> raise Exception('Identity matrix initialization can only be used '
<add> 'for 2D square matrices')
<ide> else:
<ide> return K.variable(scale * np.identity(shape[0]))
<ide>
<ide><path>tests/keras/test_initializations.py
<add>import pytest
<add>import numpy as np
<add>
<add>from keras import initializations
<add>from keras import backend as K
<add>
<add>SHAPE = (100, 100)
<add>
<add>
<add>def _runner(init, shape, target_mean=None, target_std=None,
<add> target_max=None, target_min=None):
<add> variable = init(shape)
<add> output = K.get_value(variable)
<add> print target_std
<add> print output.std()
<add> print output.mean()
<add> lim = 1e-2
<add> if target_std is not None:
<add> assert abs(output.std() - target_std) < lim
<add> if target_mean is not None:
<add> assert abs(output.mean() - target_mean) < lim
<add> if target_max is not None:
<add> assert abs(output.max() - target_max) < lim
<add> if target_min is not None:
<add> assert abs(output.min() - target_min) < lim
<add>
<add>
<add>def test_uniform():
<add> _runner(initializations.uniform, SHAPE, target_mean=0.,
<add> target_max=0.05, target_min=-0.05)
<add>
<add>
<add>def test_normal():
<add> _runner(initializations.normal, SHAPE, target_mean=0., target_std=0.05)
<add>
<add>
<add>def test_lecun_uniform():
<add> scale = np.sqrt(3. / SHAPE[0])
<add> _runner(initializations.lecun_uniform, SHAPE,
<add> target_mean=0., target_max=scale, target_min=-scale)
<add>
<add>
<add>def test_glorot_uniform():
<add> scale = np.sqrt(6. / (SHAPE[0] + SHAPE[1]))
<add> _runner(initializations.glorot_uniform, SHAPE, target_mean=0.,
<add> target_max=scale, target_min=-scale)
<add>
<add>
<add>def test_glorot_normal():
<add> scale = np.sqrt(2. / (SHAPE[0] + SHAPE[1]))
<add> _runner(initializations.glorot_normal, SHAPE,
<add> target_mean=0., target_std=scale)
<add>
<add>
<add>def test_he_uniform():
<add> scale = np.sqrt(6. / SHAPE[0])
<add> _runner(initializations.he_uniform, SHAPE, target_mean=0.,
<add> target_max=scale, target_min=-scale)
<add>
<add>
<add>def test_he_normal():
<add> scale = np.sqrt(2. / SHAPE[0])
<add> _runner(initializations.he_normal, SHAPE,
<add> target_mean=0., target_std=scale)
<add>
<add>
<add>def test_orthogonal():
<add> _runner(initializations.orthogonal, SHAPE,
<add> target_mean=0.)
<add>
<add>
<add>def test_identity():
<add> _runner(initializations.identity, SHAPE,
<add> target_mean=1./SHAPE[0], target_max=1.)
<add>
<add>
<add>def test_zero():
<add> _runner(initializations.zero, SHAPE,
<add> target_mean=0., target_max=0.)
<add>
<add>
<add>def test_one():
<add> _runner(initializations.one, SHAPE,
<add> target_mean=1., target_max=1.)
<add>
<add>
<add>if __name__ == '__main__':
<add> pytest.main([__file__]) | 2 |
Python | Python | fix linting errors | 6326f9820eb785ce521c7d376825a4d3e36c8f95 | <ide><path>libcloud/common/base.py
<ide> def request(self, action, params=None, data=None, headers=None,
<ide> url = '?'.join((action, urlencode(params, doseq=True)))
<ide> else:
<ide> url = action
<del>
<add>
<ide> # IF connection has not yet been established
<ide> if self.connection is None:
<ide> self.connect()
<ide><path>libcloud/httplib_ssl.py
<ide> class LibcloudConnection(LibcloudBaseConnection):
<ide> host = None
<ide> response = None
<ide>
<del> def __init__(self, host, port, **kwargs):
<add> def __init__(self, host, port, **kwargs):
<ide> self.host = '{}://{}'.format(
<ide> 'https' if port == 443 else 'http',
<ide> host | 2 |
Javascript | Javascript | fix input type in examples | bd41bd594cb9646c5090c54de0bbb144ac3e46b5 | <ide><path>src/ng/filter/limitTo.js
<ide> }]);
<ide> </script>
<ide> <div ng-controller="ExampleController">
<del> Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
<add> Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
<ide> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
<del> Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
<add> Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
<ide> <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
<ide> Limit {{longNumber}} to: <input type="integer" ng-model="longNumberLimit">
<ide> <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p> | 1 |
Text | Text | use "repository" in maintaining-v8 doc | b11d3f15b31e7a39d3f6a6e0d3f59f021144e813 | <ide><path>doc/guides/maintaining-V8.md
<ide> Refs: https://github.com/v8/v8/commit/a51f429772d1e796744244128c9feeab4c26a854
<ide> PR-URL: https://github.com/nodejs/node/pull/7833
<ide> ```
<ide>
<del>* Open a PR against the `v6.x-staging` branch in the Node.js repo. Launch the
<del> normal and [V8 CI][] using the Node.js CI system. We only needed to backport
<del> to `v6.x` as the other LTS branches weren't affected by this bug.
<add>* Open a PR against the `v6.x-staging` branch in the Node.js repository. Launch
<add> the normal and [V8 CI][] using the Node.js CI system. We only needed to
<add> backport to `v6.x` as the other LTS branches weren't affected by this bug.
<ide>
<ide> ### Backports identified by the V8 team
<ide>
<ide> git node v8 major --branch=5.1-lkgr
<ide>
<ide> This should be followed up with manual refloating of all relevant patches.
<ide>
<del>## Proposal: using a fork repo to track upstream V8
<add>## Proposal: Using a fork repository to track upstream V8
<ide>
<ide> The fact that Node.js keeps a vendored, potentially edited copy of V8 in deps/
<ide> makes the above processes a bit complicated. An alternative proposal would be to | 1 |
Java | Java | update genericwac to implement configurablewac | fb9fb00c04143480aa39b6538f4d71aba461571b | <ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java
<ide> /*
<del> * Copyright 2002-2009 the original author or authors.
<add> * Copyright 2002-2011 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.web.context.support;
<ide>
<add>import javax.servlet.ServletConfig;
<ide> import javax.servlet.ServletContext;
<ide>
<ide> import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.ui.context.Theme;
<ide> import org.springframework.ui.context.ThemeSource;
<ide> import org.springframework.ui.context.support.UiApplicationContextUtils;
<add>import org.springframework.util.ObjectUtils;
<add>import org.springframework.util.StringUtils;
<add>import org.springframework.web.context.ConfigurableWebApplicationContext;
<ide> import org.springframework.web.context.ServletContextAware;
<del>import org.springframework.web.context.WebApplicationContext;
<ide>
<ide> /**
<ide> * Subclass of {@link GenericApplicationContext}, suitable for web environments.
<ide> *
<del> * <p>Implements the {@link WebApplicationContext} interface, but not
<add> * <p>Implements the
<ide> * {@link org.springframework.web.context.ConfigurableWebApplicationContext},
<del> * as it is not intended for declarative setup in <code>web.xml</code>. Instead,
<del> * it is designed for programmatic setup, for example for building nested contexts.
<add> * but is not intended for declarative setup in <code>web.xml</code>. Instead,
<add> * it is designed for programmatic setup, for example for building nested contexts or
<add> * for use within Spring 3.1 {@link org.springframework.web.WebApplicationInitializer}s.
<ide> *
<ide> * <p><b>If you intend to implement a WebApplicationContext that reads bean definitions
<ide> * from configuration files, consider deriving from AbstractRefreshableWebApplicationContext,
<ide> * this class detects a ThemeSource bean in the context, with the name "themeSource".
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Chris Beams
<ide> * @since 1.2
<ide> */
<ide> public class GenericWebApplicationContext extends GenericApplicationContext
<del> implements WebApplicationContext, ThemeSource {
<add> implements ConfigurableWebApplicationContext, ThemeSource {
<ide>
<ide> private ServletContext servletContext;
<ide>
<ide> public Theme getTheme(String themeName) {
<ide> return this.themeSource.getTheme(themeName);
<ide> }
<ide>
<add>
<add> // ---------------------------------------------------------------------
<add> // Pseudo-implementation of ConfigurableWebApplicationContext
<add> // ---------------------------------------------------------------------
<add>
<add> public void setServletConfig(ServletConfig servletConfig) {
<add> // no-op
<add> }
<add>
<add> public ServletConfig getServletConfig() {
<add> throw new UnsupportedOperationException();
<add> }
<add>
<add> public void setNamespace(String namespace) {
<add> // no-op
<add> }
<add>
<add> public String getNamespace() {
<add> throw new UnsupportedOperationException();
<add> }
<add>
<add> public void setConfigLocation(String configLocation) {
<add> if (StringUtils.hasText(configLocation)) {
<add> throw new UnsupportedOperationException(
<add> "GenericWebApplicationContext does not support configLocation. Do " +
<add> "you still have an 'contextConfigLocations' init-param set?");
<add> }
<add> }
<add>
<add> public void setConfigLocations(String[] configLocations) {
<add> if (!ObjectUtils.isEmpty(configLocations)) {
<add> throw new UnsupportedOperationException(
<add> "GenericWebApplicationContext does not support configLocations. Do " +
<add> "you still have an 'contextConfigLocations' init-param set?");
<add> }
<add> }
<add>
<add> public String[] getConfigLocations() {
<add> throw new UnsupportedOperationException();
<add> }
<add>
<ide> } | 1 |
Text | Text | fix broken link | acab4c5f70c213d628bc90619de816ee593c3d72 | <ide><path>docs/basics/DataFlow.md
<ide> Redux architecture revolves around a **strict unidirectional data flow**.
<ide>
<ide> This means that all data in an application follows the same lifecycle pattern, making the logic of your app more predictable and easier to understand. It also encourages data normalization, so that you don't end up with multiple, independent copies of the same data that are unaware of one another.
<ide>
<del>If you're still not convinced, read [Motivation](../introduction/Motivation.md) and [The Case for Flux](https://medium.com/@dan_abramov/the-case-for-flux-379b7d1982c6) for a compelling argument in favor of unidirectional data flow. Although [Redux is not exactly Flux](../introduction/Relation to Other Libraries.md), it shares the same key benefits.
<add>If you're still not convinced, read [Motivation](../introduction/Motivation.md) and [The Case for Flux](https://medium.com/@dan_abramov/the-case-for-flux-379b7d1982c6) for a compelling argument in favor of unidirectional data flow. Although [Redux is not exactly Flux](../introduction/PriorArt.md), it shares the same key benefits.
<ide>
<ide> The data lifecycle in any Redux app follows these 4 steps:
<ide> | 1 |
Ruby | Ruby | convert uninstall_postflight test to spec | 0a4bc0e3b4526dacf2045b12741c1359b43607bc | <add><path>Library/Homebrew/cask/spec/cask/dsl/uninstall_postflight_spec.rb
<del><path>Library/Homebrew/cask/test/cask/dsl/uninstall_postflight_test.rb
<del>require "test_helper"
<add>require "spec_helper"
<ide>
<ide> describe Hbc::DSL::UninstallPostflight do
<ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/basic-cask.rb") } | 1 |
Java | Java | add webclient.filter method | 9e720330366bafa3ebeaed3cd99e5bca710308d5 | <ide><path>spring-web/src/main/java/org/springframework/web/client/reactive/DefaultWebClientBuilder.java
<ide> private Mono<ClientResponse> exchangeInternal(ClientRequest<?> request) {
<ide> this.strategies));
<ide> }
<ide>
<add> @Override
<add> public WebClient filter(ExchangeFilterFunction filter) {
<add> Assert.notNull(filter, "'filter' must not be null");
<add>
<add> ExchangeFilterFunction composedFilter = filter.andThen(this.filter);
<add>
<add> return new DefaultWebClient(this.clientHttpConnector, this.strategies, composedFilter);
<add> }
<ide> }
<ide>
<ide> private class NoOpFilter implements ExchangeFilterFunction {
<ide><path>spring-web/src/main/java/org/springframework/web/client/reactive/WebClient.java
<ide> public interface WebClient extends ExchangeFunction {
<ide> @Override
<ide> Mono<ClientResponse> exchange(ClientRequest<?> request);
<ide>
<add> /**
<add> * Filters this client with the given {@code ExchangeFilterFunction}, resulting in a filtered
<add> * {@code WebClient}.
<add> * @param filterFunction the filter to apply to this client
<add> * @return the filtered client
<add> * @see ExchangeFilterFunction#apply(ExchangeFunction)
<add> */
<add> WebClient filter(ExchangeFilterFunction filterFunction);
<add>
<ide>
<ide> /**
<ide> * Create a new instance of {@code WebClient} with the given connector. This method uses
<ide><path>spring-web/src/test/java/org/springframework/web/client/reactive/WebClientIntegrationTests.java
<ide> public void notFound() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void filter() throws Exception {
<add> public void buildFilter() throws Exception {
<ide> HttpUrl baseUrl = server.url("/greeting?name=Spring");
<ide> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<ide>
<ide> public void filter() throws Exception {
<ide>
<ide> }
<ide>
<add> @Test
<add> public void filter() throws Exception {
<add> HttpUrl baseUrl = server.url("/greeting?name=Spring");
<add> this.server.enqueue(new MockResponse().setHeader("Content-Type", "text/plain").setBody("Hello Spring!"));
<add>
<add> ExchangeFilterFunction filter = (request, next) -> {
<add> ClientRequest<?> filteredRequest = ClientRequest.from(request)
<add> .header("foo", "bar").build();
<add> return next.exchange(filteredRequest);
<add> };
<add> WebClient client = WebClient.create(new ReactorClientHttpConnector());
<add> WebClient filteredClient = client.filter(filter);
<add>
<add> ClientRequest<Void> request = ClientRequest.GET(baseUrl.toString()).build();
<add>
<add> Mono<String> result = filteredClient.exchange(request)
<add> .then(response -> response.body(toMono(String.class)));
<add>
<add> StepVerifier.create(result)
<add> .expectNext("Hello Spring!")
<add> .expectComplete()
<add> .verify();
<add>
<add> RecordedRequest recordedRequest = server.takeRequest();
<add> assertEquals(1, server.getRequestCount());
<add> assertEquals("bar", recordedRequest.getHeader("foo"));
<add>
<add> }
<add>
<ide> @After
<ide> public void tearDown() throws Exception {
<ide> this.server.shutdown(); | 3 |
PHP | PHP | fix undefined variables | f7f7cfdf3c81dd3d38a70388f0328ef354da187d | <ide><path>src/Routing/RouteCollection.php
<ide> public function parse($url, $method = '')
<ide> */
<ide> public function parseRequest(ServerRequestInterface $request)
<ide> {
<del> $method = $request->getMethod();
<ide> $uri = $request->getUri();
<add> $method = $request->getMethod();
<ide> $urlPath = $uri->getPath();
<ide> foreach (array_keys($this->_paths) as $path) {
<ide> if (strpos($urlPath, $path) !== 0) {
<ide> public function parseRequest(ServerRequestInterface $request)
<ide> return $r;
<ide> }
<ide> }
<del> throw new MissingRouteException(['url' => $url]);
<add> throw new MissingRouteException(['url' => $uri]);
<ide> }
<ide>
<ide> /** | 1 |
Mixed | Python | change provider configuration keys for oauth | f0727b379e6c954a48d4c0b52b0539cf57bffb3f | <ide><path>UPDATING.md
<ide> All changes made are backward compatible, but if you use the old import paths yo
<ide> see a deprecation warning. The old import paths can be abandoned in the future.
<ide>
<ide>
<add>### Breaking Change in OAuth
<add>
<add>The flask-ouathlib has been replaced with authlib because flask-outhlib has
<add>been deprecated in favour of authlib.
<add>The Old and New provider configuration keys that have changed are as follows
<add>
<add>| Old Keys | New keys |
<add>|---------------------|-------------------|
<add>| consumer_key | client_id |
<add>| consumer_secret | client_secret |
<add>| base_url | api_base_url |
<add>| request_token_params| client_kwargs |
<add>
<add>For more information, visit https://flask-appbuilder.readthedocs.io/en/latest/security.html#authentication-oauth
<add>
<ide> ### Migration Guide from Experimental API to Stable API v1
<ide> In Airflow 2.0, we added the new REST API. Experimental API still works, but support may be dropped in the future.
<ide> If your application is still using the experimental API, you should consider migrating to the stable API.
<ide><path>airflow/config_templates/default_webserver_config.py
<ide> # 'token_key':'access_token',
<ide> # 'icon':'fa-google',
<ide> # 'remote_app': {
<del># 'base_url':'https://www.googleapis.com/oauth2/v2/',
<del># 'request_token_params':{
<add># 'api_base_url':'https://www.googleapis.com/oauth2/v2/',
<add># 'client_kwargs':{
<ide> # 'scope': 'email profile'
<ide> # },
<ide> # 'access_token_url':'https://accounts.google.com/o/oauth2/token',
<ide> # 'authorize_url':'https://accounts.google.com/o/oauth2/auth',
<ide> # 'request_token_url': None,
<del># 'consumer_key': CONSUMER_KEY,
<del># 'consumer_secret': SECRET_KEY,
<add># 'client_id': GOOGLE_KEY,
<add># 'client_secret': GOOGLE_SECRET_KEY,
<ide> # }
<ide> # }]
<ide> | 2 |
Python | Python | drop default 'utf-8' to .encode()/.decode() | 513a49d63b6332e373c89fb0737a0745c1f0a734 | <ide><path>rest_framework/fields.py
<ide> def to_internal_value(self, data):
<ide> try:
<ide> if self.binary or getattr(data, 'is_json_string', False):
<ide> if isinstance(data, bytes):
<del> data = data.decode('utf-8')
<add> data = data.decode()
<ide> return json.loads(data)
<ide> else:
<ide> json.dumps(data)
<ide> def to_internal_value(self, data):
<ide> def to_representation(self, value):
<ide> if self.binary:
<ide> value = json.dumps(value)
<del> # On python 2.x the return type for json.dumps() is underspecified.
<del> # On python 3.x json.dumps() returns unicode strings.
<del> if isinstance(value, str):
<del> value = bytes(value.encode('utf-8'))
<add> value = value.encode()
<ide> return value
<ide>
<ide>
<ide><path>rest_framework/management/commands/generateschema.py
<ide> def handle(self, *args, **options):
<ide>
<ide> renderer = self.get_renderer(options['format'])
<ide> output = renderer.render(schema, renderer_context={})
<del> self.stdout.write(output.decode('utf-8'))
<add> self.stdout.write(output.decode())
<ide>
<ide> def get_renderer(self, format):
<ide> renderer_cls = {
<ide><path>rest_framework/parsers.py
<ide> def get_filename(self, stream, media_type, parser_context):
<ide>
<ide> try:
<ide> meta = parser_context['request'].META
<del> disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode('utf-8'))
<add> disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode())
<ide> filename_parm = disposition[1]
<ide> if 'filename*' in filename_parm:
<ide> return self.get_encoded_filename(filename_parm)
<ide><path>rest_framework/renderers.py
<ide> def render(self, data, accepted_media_type=None, renderer_context=None):
<ide> allow_nan=not self.strict, separators=separators
<ide> )
<ide>
<del> # On python 2.x json.dumps() returns bytestrings if ensure_ascii=True,
<del> # but if ensure_ascii=False, the return type is underspecified,
<del> # and may (or may not) be unicode.
<del> # On python 3.x json.dumps() returns unicode strings.
<del> if isinstance(ret, str):
<del> # We always fully escape \u2028 and \u2029 to ensure we output JSON
<del> # that is a strict javascript subset. If bytes were returned
<del> # by json.dumps() then we don't have these characters in any case.
<del> # See: http://timelessrepo.com/json-isnt-a-javascript-subset
<del> ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
<del> return bytes(ret.encode('utf-8'))
<del> return ret
<add> # We always fully escape \u2028 and \u2029 to ensure we output JSON
<add> # that is a strict javascript subset.
<add> # See: http://timelessrepo.com/json-isnt-a-javascript-subset
<add> ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
<add> return ret.encode()
<ide>
<ide>
<ide> class TemplateHTMLRenderer(BaseRenderer):
<ide> def get_raw_data_form(self, data, view, method, request):
<ide> data.pop(name, None)
<ide> content = renderer.render(data, accepted, context)
<ide> # Renders returns bytes, but CharField expects a str.
<del> content = content.decode('utf-8')
<add> content = content.decode()
<ide> else:
<ide> content = None
<ide>
<ide> def __init__(self):
<ide>
<ide> def render(self, data, media_type=None, renderer_context=None):
<ide> structure = self.get_structure(data)
<del> return yaml.dump(structure, default_flow_style=False).encode('utf-8')
<add> return yaml.dump(structure, default_flow_style=False).encode()
<ide>
<ide>
<ide> class JSONOpenAPIRenderer(_BaseOpenAPIRenderer):
<ide> def __init__(self):
<ide>
<ide> def render(self, data, media_type=None, renderer_context=None):
<ide> structure = self.get_structure(data)
<del> return json.dumps(structure, indent=4).encode('utf-8')
<add> return json.dumps(structure, indent=4).encode()
<ide><path>rest_framework/utils/encoders.py
<ide> def default(self, obj):
<ide> return tuple(obj)
<ide> elif isinstance(obj, bytes):
<ide> # Best-effort for binary blobs. See #4187.
<del> return obj.decode('utf-8')
<add> return obj.decode()
<ide> elif hasattr(obj, 'tolist'):
<ide> # Numpy arrays and array scalars.
<ide> return obj.tolist()
<ide><path>tests/authentication/test_authentication.py
<ide> def test_login_view_renders_on_get(self):
<ide> cf. [#1810](https://github.com/encode/django-rest-framework/pull/1810)
<ide> """
<ide> response = self.csrf_client.get('/auth/login/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert '<label for="id_username">Username:</label>' in content
<ide>
<ide> def test_post_form_session_auth_failing_csrf(self):
<ide><path>tests/browsable_api/test_browsable_api.py
<ide> def tearDown(self):
<ide> def test_name_shown_when_logged_in(self):
<ide> self.client.login(username=self.username, password=self.password)
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert 'john' in content
<ide>
<ide> def test_logout_shown_when_logged_in(self):
<ide> self.client.login(username=self.username, password=self.password)
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert '>Log out<' in content
<ide>
<ide> def test_login_shown_when_logged_out(self):
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert '>Log in<' in content
<ide>
<ide>
<ide> def tearDown(self):
<ide> def test_name_shown_when_logged_in(self):
<ide> self.client.login(username=self.username, password=self.password)
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert 'john' in content
<ide>
<ide> def test_dropdown_not_shown_when_logged_in(self):
<ide> self.client.login(username=self.username, password=self.password)
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert '<li class="dropdown">' not in content
<ide>
<ide> def test_dropdown_not_shown_when_logged_out(self):
<ide> response = self.client.get('/')
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert '<li class="dropdown">' not in content
<ide><path>tests/browsable_api/test_browsable_nested_api.py
<ide> class DropdownWithAuthTests(TestCase):
<ide> def test_login(self):
<ide> response = self.client.get('/api/')
<ide> assert 200 == response.status_code
<del> content = response.content.decode('utf-8')
<add> content = response.content.decode()
<ide> assert 'form action="/api/"' in content
<ide> assert 'input name="nested.one"' in content
<ide> assert 'input name="nested.two"' in content
<ide><path>tests/test_generics.py
<ide> def test_post_error_root_view(self):
<ide> request = factory.post('/', data, HTTP_ACCEPT='text/html')
<ide> response = self.view(request).render()
<ide> expected_error = '<span class="help-block">Ensure this field has no more than 100 characters.</span>'
<del> assert expected_error in response.rendered_content.decode('utf-8')
<add> assert expected_error in response.rendered_content.decode()
<ide>
<ide>
<ide> EXPECTED_QUERIES_FOR_PUT = 2
<ide> def test_put_error_instance_view(self):
<ide> request = factory.put('/', data, HTTP_ACCEPT='text/html')
<ide> response = self.view(request, pk=1).render()
<ide> expected_error = '<span class="help-block">Ensure this field has no more than 100 characters.</span>'
<del> assert expected_error in response.rendered_content.decode('utf-8')
<add> assert expected_error in response.rendered_content.decode()
<ide>
<ide>
<ide> class TestFKInstanceView(TestCase):
<ide> def test_dynamic_serializer_form_in_browsable_api(self):
<ide> view = DynamicSerializerView.as_view()
<ide> request = factory.get('/')
<ide> response = view(request).render()
<del> content = response.content.decode('utf8')
<add> content = response.content.decode()
<ide> assert 'field_b' in content
<ide> assert 'field_a' not in content
<ide>
<ide><path>tests/test_parsers.py
<ide> class TestFileUploadParser(TestCase):
<ide> def setUp(self):
<ide> class MockRequest:
<ide> pass
<del> self.stream = io.BytesIO(
<del> "Test text file".encode('utf-8')
<del> )
<add> self.stream = io.BytesIO(b"Test text file")
<ide> request = MockRequest()
<ide> request.upload_handlers = (MemoryFileUploadHandler(),)
<ide> request.META = {
<ide> def __replace_content_disposition(self, disposition):
<ide>
<ide> class TestJSONParser(TestCase):
<ide> def bytes(self, value):
<del> return io.BytesIO(value.encode('utf-8'))
<add> return io.BytesIO(value.encode())
<ide>
<ide> def test_float_strictness(self):
<ide> parser = JSONParser()
<ide><path>tests/test_renderers.py
<ide> def test_render_queryset_values(self):
<ide> o = DummyTestModel.objects.create(name='dummy')
<ide> qs = DummyTestModel.objects.values('id', 'name')
<ide> ret = JSONRenderer().render(qs)
<del> data = json.loads(ret.decode('utf-8'))
<add> data = json.loads(ret.decode())
<ide> self.assertEqual(data, [{'id': o.id, 'name': o.name}])
<ide>
<ide> def test_render_queryset_values_list(self):
<ide> o = DummyTestModel.objects.create(name='dummy')
<ide> qs = DummyTestModel.objects.values_list('id', 'name')
<ide> ret = JSONRenderer().render(qs)
<del> data = json.loads(ret.decode('utf-8'))
<add> data = json.loads(ret.decode())
<ide> self.assertEqual(data, [[o.id, o.name]])
<ide>
<ide> def test_render_dict_abc_obj(self):
<ide> def keys(self):
<ide> x['key'] = 'string value'
<ide> x[2] = 3
<ide> ret = JSONRenderer().render(x)
<del> data = json.loads(ret.decode('utf-8'))
<add> data = json.loads(ret.decode())
<ide> self.assertEqual(data, {'key': 'string value', '2': 3})
<ide>
<ide> def test_render_obj_with_getitem(self):
<ide> def test_without_content_type_args(self):
<ide> renderer = JSONRenderer()
<ide> content = renderer.render(obj, 'application/json')
<ide> # Fix failing test case which depends on version of JSON library.
<del> self.assertEqual(content.decode('utf-8'), _flat_repr)
<add> self.assertEqual(content.decode(), _flat_repr)
<ide>
<ide> def test_with_content_type_args(self):
<ide> """
<ide> def test_with_content_type_args(self):
<ide> obj = {'foo': ['bar', 'baz']}
<ide> renderer = JSONRenderer()
<ide> content = renderer.render(obj, 'application/json; indent=2')
<del> self.assertEqual(strip_trailing_whitespace(content.decode('utf-8')), _indented_repr)
<add> self.assertEqual(strip_trailing_whitespace(content.decode()), _indented_repr)
<ide>
<ide>
<ide> class UnicodeJSONRendererTests(TestCase):
<ide> def test_proper_encoding(self):
<ide> obj = {'countries': ['United Kingdom', 'France', 'España']}
<ide> renderer = JSONRenderer()
<ide> content = renderer.render(obj, 'application/json')
<del> self.assertEqual(content, '{"countries":["United Kingdom","France","España"]}'.encode('utf-8'))
<add> self.assertEqual(content, '{"countries":["United Kingdom","France","España"]}'.encode())
<ide>
<ide> def test_u2028_u2029(self):
<ide> # The \u2028 and \u2029 characters should be escaped,
<ide> def test_u2028_u2029(self):
<ide> obj = {'should_escape': '\u2028\u2029'}
<ide> renderer = JSONRenderer()
<ide> content = renderer.render(obj, 'application/json')
<del> self.assertEqual(content, '{"should_escape":"\\u2028\\u2029"}'.encode('utf-8'))
<add> self.assertEqual(content, '{"should_escape":"\\u2028\\u2029"}'.encode())
<ide>
<ide>
<ide> class AsciiJSONRendererTests(TestCase):
<ide> class AsciiJSONRenderer(JSONRenderer):
<ide> obj = {'countries': ['United Kingdom', 'France', 'España']}
<ide> renderer = AsciiJSONRenderer()
<ide> content = renderer.render(obj, 'application/json')
<del> self.assertEqual(content, '{"countries":["United Kingdom","France","Espa\\u00f1a"]}'.encode('utf-8'))
<add> self.assertEqual(content, '{"countries":["United Kingdom","France","Espa\\u00f1a"]}'.encode())
<ide>
<ide>
<ide> # Tests for caching issue, #346
<ide> class DummyView:
<ide>
<ide> def test_extra_actions_dropdown(self):
<ide> resp = self.client.get('/api/examples/', HTTP_ACCEPT='text/html')
<del> assert 'id="extra-actions-menu"' in resp.content.decode('utf-8')
<del> assert '/api/examples/list_action/' in resp.content.decode('utf-8')
<del> assert '>Extra list action<' in resp.content.decode('utf-8')
<add> assert 'id="extra-actions-menu"' in resp.content.decode()
<add> assert '/api/examples/list_action/' in resp.content.decode()
<add> assert '>Extra list action<' in resp.content.decode()
<ide>
<ide>
<ide> class AdminRendererTests(TestCase):
<ide><path>tests/test_routers.py
<ide> class TestEmptyPrefix(URLPatternsTestCase, TestCase):
<ide> def test_empty_prefix_list(self):
<ide> response = self.client.get('/empty-prefix/')
<ide> assert response.status_code == 200
<del> assert json.loads(response.content.decode('utf-8')) == [{'uuid': '111', 'text': 'First'},
<del> {'uuid': '222', 'text': 'Second'}]
<add> assert json.loads(response.content.decode()) == [{'uuid': '111', 'text': 'First'},
<add> {'uuid': '222', 'text': 'Second'}]
<ide>
<ide> def test_empty_prefix_detail(self):
<ide> response = self.client.get('/empty-prefix/1/')
<ide> assert response.status_code == 200
<del> assert json.loads(response.content.decode('utf-8')) == {'uuid': '111', 'text': 'First'}
<add> assert json.loads(response.content.decode()) == {'uuid': '111', 'text': 'First'}
<ide>
<ide>
<ide> class TestRegexUrlPath(URLPatternsTestCase, TestCase):
<ide> def test_regex_url_path_list(self):
<ide> kwarg = '1234'
<ide> response = self.client.get('/regex/list/{}/'.format(kwarg))
<ide> assert response.status_code == 200
<del> assert json.loads(response.content.decode('utf-8')) == {'kwarg': kwarg}
<add> assert json.loads(response.content.decode()) == {'kwarg': kwarg}
<ide>
<ide> def test_regex_url_path_detail(self):
<ide> pk = '1'
<ide> kwarg = '1234'
<ide> response = self.client.get('/regex/{}/detail/{}/'.format(pk, kwarg))
<ide> assert response.status_code == 200
<del> assert json.loads(response.content.decode('utf-8')) == {'pk': pk, 'kwarg': kwarg}
<add> assert json.loads(response.content.decode()) == {'pk': pk, 'kwarg': kwarg}
<ide>
<ide>
<ide> class TestViewInitkwargs(URLPatternsTestCase, TestCase):
<ide><path>tests/test_templates.py
<ide> def test_base_template_with_context():
<ide> context = {'request': True, 'csrf_token': 'TOKEN'}
<ide> result = render({}, 'rest_framework/base.html', context=context)
<del> assert re.search(r'\bcsrfToken: "TOKEN"', result.content.decode('utf-8'))
<add> assert re.search(r'\bcsrfToken: "TOKEN"', result.content.decode())
<ide>
<ide>
<ide> def test_base_template_with_no_context():
<ide> # base.html should be renderable with no context,
<ide> # so it can be easily extended.
<ide> result = render({}, 'rest_framework/base.html')
<ide> # note that this response will not include a valid CSRF token
<del> assert re.search(r'\bcsrfToken: ""', result.content.decode('utf-8'))
<add> assert re.search(r'\bcsrfToken: ""', result.content.decode()) | 13 |
PHP | PHP | expand doc blocks | b811bbc50dc1c341300f737560a16abb8eaa2ed7 | <ide><path>Cake/ORM/Behavior.php
<ide> * ### Mixin methods
<ide> *
<ide> * Behaviors can provide mixin like features by declaring public
<del> * methods. These methods should expect the Table instance to be
<del> * shifted onto the parameter list.
<add> * methods. These methods will be accessible on the tables the
<add> * behavior has been added to.
<ide> *
<ide> * {{{
<del> * function doSomething(Table $table, $arg1, $arg2) {
<del> * //do something
<add> * function doSomething($arg1, $arg2) {
<add> * // do something
<ide> * }
<ide> * }}}
<ide> *
<ide> * Would be called like `$this->Table->doSomething($arg1, $arg2);`.
<ide> *
<ide> * ## Callback methods
<ide> *
<add> * Behaviors can listen to any events fired on a Table. By default
<add> * CakePHP provides a number of lifecycle events your behaviors can
<add> * listen to:
<add> *
<add> * - `beforeFind(Event $event, Query $query)`
<add> * Fired before a query is converted into SQL.
<add> *
<add> * - `beforeDelete(Event $event, Entity $entity)`
<add> * Fired before an entity is deleted.
<add> *
<add> * - `afterDelete(Event $event, Entity $entity)`
<add> * Fired after an entity has been deleted. The entity parameter
<add> * will contain the entity state from before it was deleted.
<add> *
<add> * - `beforeSave(Event $event, Entity $entity)`
<add> * Fired before an entity is saved. In the case where
<add> * multiple entities are being saved, one event will be fired
<add> * for each entity.
<add> *
<add> * - `afterSave(Event $event, Entity $entity)`
<add> * Fired after an entity is saved. The saved entity will be provided
<add> * as a parameter.
<add> *
<add> * In addition to the core events, behaviors can respond to any
<add> * event fired from your Table classes including custom application
<add> * specific ones.
<add> *
<add> * ## Finder methods
<add> *
<add> * Behaviors can provide finder methods that hook into a Table's
<add> * find() method. Custom finders are a great way to provide preset
<add> * queries that relate to your behavior. For example a SluggableBehavior
<add> * could provide a find('slugged') finder. Behavior finders
<add> * are implemented the same as other finders. Any method
<add> * starting with `find` will be setup as a finder. Your finder
<add> * methods should expect the following arguments:
<add> *
<add> * {{{
<add> * findSlugged(Query $query, array $options = [])
<add> * }}}
<add> *
<add> *
<add> * @see Cake\ORM\Table::addBehavior()
<ide> */
<ide> class Behavior implements EventListener {
<ide>
<ide><path>Cake/ORM/Table.php
<ide> public function entityClass($name = null) {
<ide> * $this->addBehavior('Tree', ['parent' => 'parentId']);
<ide> * }}}
<ide> *
<add> * Behaviors are generally loaded during Table::initialize().
<add> *
<ide> * @param string $name The name of the behavior. Can be a short class reference.
<ide> * @param array $options The options for the behavior to use.
<ide> * @return null | 2 |
Go | Go | fix linting errors | d43bcc8974122faed16ac34cfe2b5da400948d3e | <ide><path>daemon/logger/journald/read.go
<ide> func (s *journald) Close() error {
<ide> return nil
<ide> }
<ide>
<del>// convert error code returned from a sd_journal_* function
<add>// CErr converts error code returned from a sd_journal_* function
<ide> // (which returns -errno) to a string
<ide> func CErr(ret C.int) string {
<del> return C.GoString(C.strerror(C.int(-ret)))
<add> return C.GoString(C.strerror(-ret))
<ide> }
<ide>
<ide> func (s *journald) drainJournal(logWatcher *logger.LogWatcher, j *C.sd_journal, oldCursor *C.char, untilUnixMicro uint64) (*C.char, bool, int) {
<ide> func (s *journald) readLogs(logWatcher *logger.LogWatcher, config logger.ReadCon
<ide> }
<ide>
<ide> C.free(unsafe.Pointer(cursor))
<del> return
<ide> }
<ide>
<ide> func (s *journald) ReadLogs(config logger.ReadConfig) *logger.LogWatcher { | 1 |
Text | Text | fix typo in actioncontroller overview | 742b57475adfc6ad9e1ff7a6c37c83e63fb6803c | <ide><path>guides/source/action_controller_overview.md
<ide> Rails keeps a log file for each environment in the `log` folder. These are extre
<ide>
<ide> ### Parameters Filtering
<ide>
<del>You can filter certain request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
<add>You can filter out sensitive request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
<ide>
<ide> ```ruby
<ide> config.filter_parameters << :password
<ide> ```
<ide>
<ide> ### Redirects Filtering
<ide>
<del>Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to.
<add>Sometimes it's desirable to filter out from log files some sensitive locations your application is redirecting to.
<ide> You can do that by using the `config.filter_redirect` configuration option:
<ide>
<ide> ```ruby | 1 |
Javascript | Javascript | fix style in readline | 2d09ef854118692eefd6f04dbd8354811f8a78be | <ide><path>lib/readline.js
<ide> Interface.prototype._ttyWrite = function (b) {
<ide>
<ide> case 27: /* escape sequence */
<ide> var next_word, next_non_word, previous_word, previous_non_word;
<del> if (b[1] === 98 && this.cursor > 0) { // meta-b - backward word
<del> previous_word = this.line.slice(0, this.cursor)
<del> .split('').reverse().join('')
<del> .search(/\w/);
<del> if (previous_word !== -1) {
<del> previous_non_word = this.line.slice(0, this.cursor - previous_word)
<del> .split('').reverse().join('')
<del> .search(/\W/);
<del> if (previous_non_word !== -1) {
<del> this.cursor -= previous_word + previous_non_word;
<del> this._refreshLine();
<del> break;
<del> }
<del> }
<del> this.cursor = 0;
<del> this._refreshLine();
<del> } else if (b[1] === 102 && this.cursor < this.line.length) { // meta-f - forward word
<del> next_word = this.line.slice(this.cursor, this.line.length)
<del> .search(/\w/);
<del> if (next_word !== -1) {
<del> next_non_word = this.line.slice(this.cursor + next_word, this.line.length)
<del> .search(/\W/);
<del> if (next_non_word !== -1) {
<del> this.cursor += next_word + next_non_word;
<del> this._refreshLine();
<del> break;
<del> }
<del> }
<del> this.cursor = this.line.length;
<del> this._refreshLine();
<del> } else if (b[1] === 100 && this.cursor < this.line.length) { // meta-d delete forward word
<del> next_word = this.line.slice(this.cursor, this.line.length)
<del> .search(/\w/);
<del> if (next_word !== -1) {
<del> next_non_word = this.line.slice(this.cursor + next_word, this.line.length)
<del> .search(/\W/);
<del> if (next_non_word !== -1) {
<del> this.line = this.line.slice(this.cursor + next_word + next_non_word);
<del> this.cursor = 0;
<del> this._refreshLine();
<del> break;
<del> }
<del> }
<del> this.line = '';
<del> this.cursor = 0;
<del> this._refreshLine();
<del> } else if (b[1] === 91 && b[2] === 68) { // left arrow
<add>
<add> if (b[1] === 98 && this.cursor > 0) {
<add> // meta-b - backward word
<add> previous_word = this.line.slice(0, this.cursor)
<add> .split('').reverse().join('')
<add> .search(/\w/);
<add> if (previous_word !== -1) {
<add> previous_non_word = this.line.slice(0, this.cursor - previous_word)
<add> .split('').reverse().join('')
<add> .search(/\W/);
<add> if (previous_non_word !== -1) {
<add> this.cursor -= previous_word + previous_non_word;
<add> this._refreshLine();
<add> break;
<add> }
<add> }
<add> this.cursor = 0;
<add> this._refreshLine();
<add>
<add> } else if (b[1] === 102 && this.cursor < this.line.length) {
<add> // meta-f - forward word
<add> next_word = this.line.slice(this.cursor, this.line.length).search(/\w/);
<add> if (next_word !== -1) {
<add> next_non_word =
<add> this.line.slice(this.cursor + next_word, this.line.length)
<add> .search(/\W/);
<add> if (next_non_word !== -1) {
<add> this.cursor += next_word + next_non_word;
<add> this._refreshLine();
<add> break;
<add> }
<add> }
<add> this.cursor = this.line.length;
<add> this._refreshLine();
<add>
<add> } else if (b[1] === 100 && this.cursor < this.line.length) {
<add> // meta-d delete forward word
<add> next_word = this.line.slice(this.cursor, this.line.length).search(/\w/);
<add> if (next_word !== -1) {
<add> next_non_word =
<add> this.line.slice(this.cursor + next_word, this.line.length)
<add> .search(/\W/);
<add> if (next_non_word !== -1) {
<add> this.line =
<add> this.line.slice(this.cursor + next_word + next_non_word);
<add> this.cursor = 0;
<add> this._refreshLine();
<add> break;
<add> }
<add> }
<add> this.line = '';
<add> this.cursor = 0;
<add> this._refreshLine();
<add>
<add> } else if (b[1] === 91 && b[2] === 68) {
<add> // left arrow
<ide> if (this.cursor > 0) {
<ide> this.cursor--;
<ide> this.output.write('\x1b[0D');
<ide> }
<del> } else if (b[1] === 91 && b[2] === 67) { // right arrow
<add>
<add> } else if (b[1] === 91 && b[2] === 67) {
<add> // right arrow
<ide> if (this.cursor != this.line.length) {
<ide> this.cursor++;
<ide> this.output.write('\x1b[0C');
<ide> }
<add>
<ide> } else if ((b[1] === 91 && b[2] === 72) ||
<ide> (b[1] === 79 && b[2] === 72) ||
<ide> (b[1] === 91 && b[2] === 55) ||
<del> (b[1] === 91 && b[2] === 49 && (b[3] && b[3] === 126))) { // home
<add> (b[1] === 91 && b[2] === 49 && (b[3] && b[3] === 126))) {
<add> // home
<ide> this.cursor = 0;
<ide> this._refreshLine();
<ide> } else if ((b[1] === 91 && b[2] === 70) ||
<ide> (b[1] === 79 && b[2] === 70) ||
<ide> (b[1] === 91 && b[2] === 56) ||
<del> (b[1] === 91 && b[2] === 52 && (b[3] && b[3] === 126))) { // end
<add> (b[1] === 91 && b[2] === 52 && (b[3] && b[3] === 126))) {
<add> // end
<ide> this.cursor = this.line.length;
<ide> this._refreshLine();
<del> } else if (b[1] === 91 && b[2] === 65) { // up arrow
<add>
<add> } else if (b[1] === 91 && b[2] === 65) {
<add> // up arrow
<ide> this._historyPrev();
<del> } else if (b[1] === 91 && b[2] === 66) { // down arrow
<add>
<add> } else if (b[1] === 91 && b[2] === 66) {
<add> // down arrow
<ide> this._historyNext();
<del> } else if (b[1] === 91 && b[2] === 51 && this.cursor < this.line.length) { // delete right
<add>
<add> } else if (b[1] === 91 && b[2] === 51 && this.cursor < this.line.length) {
<add> // delete right
<ide> this.line = this.line.slice(0, this.cursor) +
<ide> this.line.slice(this.cursor+1, this.line.length);
<ide> this._refreshLine();
<add>
<ide> }
<ide> break;
<ide> | 1 |
Javascript | Javascript | improve challenge logs | 688a3dcc7b4a7c3d111e1c9c9be25160033a1f2b | <ide><path>client/src/client/workers/test-evaluator.js
<ide> const __utils = (() => {
<ide> self.postMessage(data);
<ide> }
<ide>
<del> function log(msg) {
<del> if (!(msg instanceof chai.AssertionError)) {
<add> function log(...msgs) {
<add> if (msgs && msgs[0] && !(msgs[0] instanceof chai.AssertionError)) {
<ide> // discards the stack trace via toString as it only useful to debug the
<ide> // site, not a specific challenge.
<del> console.log(msg.toString());
<add> console.log(...msgs.map(msg => msg.toString()));
<ide> }
<ide> }
<ide>
<ide> ${e.data.testString}`);
<ide> // rethrow error, since test failed.
<ide> throw err;
<ide> }
<del> // log build errors
<del> __utils.log(err);
<add> // log build errors unless they're related to import/export/require (there
<add> // are challenges that use them and they should not trigger warnings)
<add> if (
<add> err.name !== 'ReferenceError' ||
<add> (err.message !== 'require is not defined' &&
<add> err.message !== 'exports is not defined')
<add> ) {
<add> __utils.log(err);
<add> }
<ide> // the tests may not require working code, so they are evaluated even if
<ide> // the user code does not get executed.
<ide> testResult = eval(e.data.testString); | 1 |
Text | Text | fix a typo in the sliced reducer | bd6ddd840d19e2a4ac0006ec12799abf9f2bc2ea | <ide><path>docs/tutorials/fundamentals/part-3-state-actions-reducers.md
<ide> export default function todosReducer(state = initialState, action) {
<ide> return [
<ide> ...state,
<ide> {
<del> id: nextTodoId(state.todos),
<add> id: nextTodoId(state),
<ide> text: action.payload,
<ide> completed: false
<ide> } | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.