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 |
|---|---|---|---|---|---|
Go | Go | remove unused function params | 587823af2723801ffdb6841b6e2c3d7d73ff10db | <ide><path>daemon/container_unix.go
<ide> func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, e
<ide> return sboxOptions, nil
<ide> }
<ide>
<del>func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
<add>func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
<ide> if ep == nil {
<ide> return nil, fmt.Errorf("invalid endpoint while building port map info")
<ide> }
<ide> func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork
<ide> return networkSettings, nil
<ide> }
<ide>
<del>func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
<add>func (container *Container) buildEndpointInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
<ide> if ep == nil {
<ide> return nil, fmt.Errorf("invalid endpoint while building port map info")
<ide> }
<ide> func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
<ide> func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
<ide> networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
<ide>
<del> networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
<add> networkSettings, err := container.buildPortMapInfo(ep, networkSettings)
<ide> if err != nil {
<ide> return err
<ide> }
<ide>
<del> networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
<add> networkSettings, err = container.buildEndpointInfo(ep, networkSettings)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) load(id string) (*Container, error) {
<ide> }
<ide>
<ide> // Register makes a container object usable by the daemon as <container.ID>
<del>// This is a wrapper for register
<ide> func (daemon *Daemon) Register(container *Container) error {
<del> return daemon.register(container, true)
<del>}
<del>
<del>// register makes a container object usable by the daemon as <container.ID>
<del>func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error {
<ide> if container.daemon != nil || daemon.Exists(container.ID) {
<ide> return fmt.Errorf("Container is already loaded")
<ide> }
<ide> func (daemon *Daemon) restore() error {
<ide> }
<ide> }
<ide>
<del> if err := daemon.register(container, false); err != nil {
<add> if err := daemon.Register(container); err != nil {
<ide> logrus.Debugf("Failed to register container %s: %s", container.ID, err)
<ide> }
<ide>
<ide><path>daemon/volumes_linux_unit_test.go
<ide> func TestGetVolumeDriver(t *testing.T) {
<ide>
<ide> func TestParseBindMount(t *testing.T) {
<ide> cases := []struct {
<del> bind string
<del> driver string
<del> expDest string
<del> expSource string
<del> expName string
<del> expDriver string
<del> mountLabel string
<del> expRW bool
<del> fail bool
<add> bind string
<add> driver string
<add> expDest string
<add> expSource string
<add> expName string
<add> expDriver string
<add> expRW bool
<add> fail bool
<ide> }{
<del> {"/tmp:/tmp", "", "/tmp", "/tmp", "", "", "", true, false},
<del> {"/tmp:/tmp:ro", "", "/tmp", "/tmp", "", "", "", false, false},
<del> {"/tmp:/tmp:rw", "", "/tmp", "/tmp", "", "", "", true, false},
<del> {"/tmp:/tmp:foo", "", "/tmp", "/tmp", "", "", "", false, true},
<del> {"name:/tmp", "", "/tmp", "", "name", "local", "", true, false},
<del> {"name:/tmp", "external", "/tmp", "", "name", "external", "", true, false},
<del> {"name:/tmp:ro", "local", "/tmp", "", "name", "local", "", false, false},
<del> {"local/name:/tmp:rw", "", "/tmp", "", "local/name", "local", "", true, false},
<del> {"/tmp:tmp", "", "", "", "", "", "", true, true},
<add> {"/tmp:/tmp", "", "/tmp", "/tmp", "", "", true, false},
<add> {"/tmp:/tmp:ro", "", "/tmp", "/tmp", "", "", false, false},
<add> {"/tmp:/tmp:rw", "", "/tmp", "/tmp", "", "", true, false},
<add> {"/tmp:/tmp:foo", "", "/tmp", "/tmp", "", "", false, true},
<add> {"name:/tmp", "", "/tmp", "", "name", "local", true, false},
<add> {"name:/tmp", "external", "/tmp", "", "name", "external", true, false},
<add> {"name:/tmp:ro", "local", "/tmp", "", "name", "local", false, false},
<add> {"local/name:/tmp:rw", "", "/tmp", "", "local/name", "local", true, false},
<add> {"/tmp:tmp", "", "", "", "", "", true, true},
<ide> }
<ide>
<ide> for _, c := range cases {
<del> m, err := parseBindMount(c.bind, c.mountLabel, c.driver)
<add> m, err := parseBindMount(c.bind, c.driver)
<ide> if c.fail {
<ide> if err == nil {
<ide> t.Fatalf("Expected error, was nil, for spec %s\n", c.bind)
<ide><path>daemon/volumes_unix.go
<ide> func (container *Container) setupMounts() ([]execdriver.Mount, error) {
<ide> }
<ide>
<ide> // parseBindMount validates the configuration of mount information in runconfig is valid.
<del>func parseBindMount(spec, mountLabel, volumeDriver string) (*mountPoint, error) {
<add>func parseBindMount(spec, volumeDriver string) (*mountPoint, error) {
<ide> bind := &mountPoint{
<ide> RW: true,
<ide> }
<ide> func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runc
<ide> // 3. Read bind mounts
<ide> for _, b := range hostConfig.Binds {
<ide> // #10618
<del> bind, err := parseBindMount(b, container.MountLabel, hostConfig.VolumeDriver)
<add> bind, err := parseBindMount(b, hostConfig.VolumeDriver)
<ide> if err != nil {
<ide> return err
<ide> } | 4 |
Ruby | Ruby | use new tapioca command | d00b387bc244bfaff854f7c728463f6114bbdf14 | <ide><path>Library/Homebrew/dev-cmd/typecheck.rb
<ide> def typecheck
<ide> ]
<ide>
<ide> ohai "Updating Tapioca RBI files..."
<del> system "bundle", "exec", "tapioca", "sync", "--exclude", *excluded_gems
<add> system "bundle", "exec", "tapioca", "gem", "--exclude", *excluded_gems
<ide> system "bundle", "exec", "parlour"
<ide> system "bundle", "exec", "srb", "rbi", "hidden-definitions"
<ide> system "bundle", "exec", "srb", "rbi", "todo" | 1 |
Text | Text | fix minor mistake | c96e6f54b54594718635bb6d0fc46aa6905394dd | <ide><path>README.md
<ide> When data is passed from above rather than being subscribed to, and you're only
<ide> interested in doing work when something has changed, you can use equality.
<ide>
<ide> Immutable collections should be treated as *values* rather than *objects*. While
<del>objects represents some thing which could change over time, a value represents
<add>objects represent some thing which could change over time, a value represents
<ide> the state of that thing at a particular instance of time. This principle is most
<ide> important to understanding the appropriate use of immutable data. In order to
<ide> treat Immutable.js collections as values, it's important to use the | 1 |
Text | Text | fix links and ids for tips in docs | 2ec2d8f7f75f0441c51e0fea743be82a3d1dde4f | <ide><path>docs/tips/02-inline-styles.ru-RU.md
<ide> ---
<del>id: inline-styles
<add>id: inline-styles-ru-RU
<ide> title: Встроенные стили
<ide> layout: tips
<ide> permalink: tips/inline-styles-ru-RU.html
<ide><path>docs/tips/03-if-else-in-JSX.ru-RU.md
<ide> ---
<del>id: if-else-in-JSX
<add>id: if-else-in-JSX-ru-RU
<ide> title: If-Else в JSX
<ide> layout: tips
<ide> permalink: tips/if-else-in-JSX-ru-RU.html
<ide> prev: inline-styles-ru-RU.html
<del>next: self-closing-tag.html
<add>next: self-closing-tag-ru-RU.html
<ide> ---
<ide>
<ide> Некоторые конструкции, такие как `if-else`, нельзя использовать внутри JSX, так как JSX в результате преобразуется в вызов функции JS, как показано в примере:
<ide><path>docs/tips/04-self-closing-tag.ru-RU.md
<ide> ---
<del>id: self-closing-tag
<add>id: self-closing-tag-ru-RU
<ide> title: Одиночный тег
<ide> layout: tips
<ide> permalink: tips/self-closing-tag-ru-RU.html
<ide><path>docs/tips/05-maximum-number-of-jsx-root-nodes.ru-RU.md
<ide> ---
<del>id: maximum-number-of-jsx-root-nodes
<add>id: maximum-number-of-jsx-root-nodes-ru-RU
<ide> title: Максимальное количество корневых JSX-узлов
<ide> layout: tips
<ide> permalink: tips/maximum-number-of-jsx-root-nodes-ru-RU.html
<ide> prev: self-closing-tag-ru-RU.html
<del>next: style-props-value-px.html
<add>next: style-props-value-px-ru-RU.html
<ide> ---
<ide>
<ide> Из метода `render` компонента пока что можно вернуть только один узел. Если нужно вернуть, например, несколько `div`, оберните их в `div`, `span` или любой другой компонент.
<ide><path>docs/tips/06-style-props-value-px.ru-RU.md
<ide> ---
<del>id: style-props-value-px
<add>id: style-props-value-px-ru-RU
<ide> title: Краткая форма значений в пикселях для атрибута style
<ide> layout: tips
<ide> permalink: tips/style-props-value-px-ru-RU.html | 5 |
Python | Python | rearrange multi-task learning | e6cc927ab17e052f09f62c7c57b10e9d0abdb41c | <ide><path>spacy/language.py
<ide> import numpy
<ide> from thinc.neural import Model
<ide> from thinc.neural.ops import NumpyOps, CupyOps
<del>from thinc.neural.optimizers import Adam
<add>from thinc.neural.optimizers import Adam, SGD
<add>import random
<ide>
<ide> from .tokenizer import Tokenizer
<ide> from .vocab import Vocab
<ide> def __call__(self, text, **disabled):
<ide> proc(doc)
<ide> return doc
<ide>
<del> def update(self, docs, golds, drop=0., sgd=None):
<add> def update(self, docs, golds, drop=0., sgd=None, losses=None):
<ide> """Update the models in the pipeline.
<ide>
<ide> docs (iterable): A batch of `Doc` objects.
<ide> def update(self, docs, golds, drop=0., sgd=None):
<ide> """
<ide> tok2vec = self.pipeline[0]
<ide> feats = tok2vec.doc2feats(docs)
<del> for proc in self.pipeline[1:]:
<add> procs = list(self.pipeline[1:])
<add> random.shuffle(procs)
<add> grads = {}
<add> def get_grads(W, dW, key=None):
<add> grads[key] = (W, dW)
<add> for proc in procs:
<ide> if not hasattr(proc, 'update'):
<ide> continue
<ide> tokvecses, bp_tokvecses = tok2vec.model.begin_update(feats, drop=drop)
<del> d_tokvecses = proc.update((docs, tokvecses), golds, sgd=sgd, drop=drop)
<add> d_tokvecses = proc.update((docs, tokvecses), golds,
<add> drop=drop, sgd=sgd, losses=losses)
<ide> bp_tokvecses(d_tokvecses, sgd=sgd)
<add> for key, (W, dW) in grads.items():
<add> sgd(W, dW, key=key)
<ide> # Clear the tensor variable, to free GPU memory.
<ide> # If we don't do this, the memory leak gets pretty
<ide> # bad, because we may be holding part of a batch. | 1 |
Javascript | Javascript | handle dataset type per chart | f3457c99417e3e87f67b8b673c6d9ca046b3bc46 | <ide><path>src/controllers/controller.bar.js
<ide> module.exports = function(Chart) {
<ide> Chart.DatasetController.prototype.initialize.call(this, chart, datasetIndex);
<ide>
<ide> // Use this to indicate that this is a bar dataset.
<del> this.getDataset().bar = true;
<add> this.getMeta().bar = true;
<ide> },
<ide> // Get the number of datasets that display bars. We use this to correctly calculate the bar width
<ide> getBarCount: function getBarCount() {
<ide> var barCount = 0;
<del> helpers.each(this.chart.data.datasets, function(dataset) {
<del> if (helpers.isDatasetVisible(dataset) && dataset.bar) {
<add> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<add> var meta = this.chart.getDatasetMeta(datasetIndex);
<add> if (meta.bar && helpers.isDatasetVisible(dataset)) {
<ide> ++barCount;
<ide> }
<del> });
<add> }, this);
<ide> return barCount;
<ide> },
<ide>
<ide> module.exports = function(Chart) {
<ide> for (var i = 0; i < datasetIndex; i++) {
<ide> var negDS = this.chart.data.datasets[i];
<ide> var negDSMeta = this.chart.getDatasetMeta(i);
<del> if (helpers.isDatasetVisible(negDS) && negDSMeta.yAxisID === yScale.id && negDS.bar) {
<add> if (negDSMeta.bar && negDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(negDS)) {
<ide> base += negDS.data[index] < 0 ? negDS.data[index] : 0;
<ide> }
<ide> }
<ide> } else {
<ide> for (var j = 0; j < datasetIndex; j++) {
<ide> var posDS = this.chart.data.datasets[j];
<ide> var posDSMeta = this.chart.getDatasetMeta(j);
<del> if (helpers.isDatasetVisible(posDS) && posDSMeta.yAxisID === yScale.id && posDS.bar) {
<add> if (posDSMeta.bar && posDSMeta.yAxisID === yScale.id && helpers.isDatasetVisible(posDS)) {
<ide> base += posDS.data[index] > 0 ? posDS.data[index] : 0;
<ide> }
<ide> }
<ide> module.exports = function(Chart) {
<ide> // Get bar index from the given dataset index accounting for the fact that not all bars are visible
<ide> getBarIndex: function(datasetIndex) {
<ide> var barIndex = 0;
<add> var meta, j;
<ide>
<del> for (var j = 0; j < datasetIndex; ++j) {
<del> if (helpers.isDatasetVisible(this.chart.data.datasets[j]) && this.chart.data.datasets[j].bar) {
<add> for (j = 0; j < datasetIndex; ++j) {
<add> meta = this.chart.getDatasetMeta(j);
<add> if (meta.bar && helpers.isDatasetVisible(this.chart.data.datasets[j])) {
<ide> ++barIndex;
<ide> }
<ide> }
<ide> module.exports = function(Chart) {
<ide> for (var i = 0; i < datasetIndex; i++) {
<ide> var ds = this.chart.data.datasets[i];
<ide> var dsMeta = this.chart.getDatasetMeta(i);
<del> if (helpers.isDatasetVisible(ds) && ds.bar && dsMeta.yAxisID === yScale.id) {
<add> if (dsMeta.bar && dsMeta.yAxisID === yScale.id && helpers.isDatasetVisible(ds)) {
<ide> if (ds.data[index] < 0) {
<ide> sumNeg += ds.data[index] || 0;
<ide> } else {
<ide><path>src/controllers/controller.line.js
<ide> module.exports = function(Chart) {
<ide>
<ide> for (var i = 0; i < datasetIndex; i++) {
<ide> var ds = this.chart.data.datasets[i];
<del> if (ds.type === 'line' && helpers.isDatasetVisible(ds)) {
<add> var dsMeta = this.chart.getDatasetMeta(i);
<add> if (dsMeta.type === 'line' && helpers.isDatasetVisible(ds)) {
<ide> if (ds.data[index] < 0) {
<ide> sumNeg += ds.data[index] || 0;
<ide> } else {
<ide><path>src/core/core.controller.js
<ide> module.exports = function(Chart) {
<ide> var newControllers = [];
<ide>
<ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) {
<del> if (!dataset.type) {
<del> dataset.type = this.config.type;
<add> var meta = this.getDatasetMeta(datasetIndex);
<add> if (!meta.type) {
<add> meta.type = dataset.type || this.config.type;
<ide> }
<ide>
<del> var meta = this.getDatasetMeta(datasetIndex);
<del> var type = dataset.type;
<del> types.push(type);
<add> types.push(meta.type);
<ide>
<ide> if (meta.controller) {
<ide> meta.controller.updateIndex(datasetIndex);
<ide> } else {
<del> meta.controller = new Chart.controllers[type](this, datasetIndex);
<add> meta.controller = new Chart.controllers[meta.type](this, datasetIndex);
<ide> newControllers.push(meta.controller);
<ide> }
<ide> }, this);
<ide> module.exports = function(Chart) {
<ide> var elementsArray = [];
<ide>
<ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) {
<del> var meta = this.getDatasetMeta(datasetIndex);
<add> var meta = this.getDatasetMeta(datasetIndex);
<ide> if (helpers.isDatasetVisible(dataset)) {
<ide> helpers.each(meta.data, function(element, index) {
<ide> if (element.inRange(eventPosition.x, eventPosition.y)) {
<ide> module.exports = function(Chart) {
<ide> }
<ide> }
<ide> }
<del> };
<add> }
<ide> }
<ide> }).call(this);
<ide>
<ide> module.exports = function(Chart) {
<ide> }
<ide>
<ide> helpers.each(this.data.datasets, function(dataset, datasetIndex) {
<del> var meta = this.getDatasetMeta(datasetIndex);
<add> var meta = this.getDatasetMeta(datasetIndex);
<ide> if (helpers.isDatasetVisible(dataset)) {
<ide> elementsArray.push(meta.data[found._index]);
<ide> }
<ide> module.exports = function(Chart) {
<ide> var meta = dataset._meta[this.id];
<ide> if (!meta) {
<ide> meta = dataset._meta[this.id] = {
<del> data: [],
<del> dataset: null,
<del> controller: null,
<del> xAxisID: null,
<del> yAxisID: null
<del> };
<add> type: null,
<add> data: [],
<add> dataset: null,
<add> controller: null,
<add> xAxisID: null,
<add> yAxisID: null
<add> };
<ide> }
<ide>
<ide> return meta;
<ide><path>src/scales/scale.linear.js
<ide> module.exports = function(Chart) {
<ide>
<ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<ide> var meta = this.chart.getDatasetMeta(datasetIndex);
<del> if (valuesPerType[dataset.type] === undefined) {
<del> valuesPerType[dataset.type] = {
<add> if (valuesPerType[meta.type] === undefined) {
<add> valuesPerType[meta.type] = {
<ide> positiveValues: [],
<ide> negativeValues: []
<ide> };
<ide> }
<ide>
<ide> // Store these per type
<del> var positiveValues = valuesPerType[dataset.type].positiveValues;
<del> var negativeValues = valuesPerType[dataset.type].negativeValues;
<add> var positiveValues = valuesPerType[meta.type].positiveValues;
<add> var negativeValues = valuesPerType[meta.type].negativeValues;
<ide>
<ide> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<ide> helpers.each(dataset.data, function(rawValue, index) {
<ide><path>src/scales/scale.logarithmic.js
<ide> module.exports = function(Chart) {
<ide> helpers.each(this.chart.data.datasets, function(dataset, datasetIndex) {
<ide> var meta = this.chart.getDatasetMeta(datasetIndex);
<ide> if (helpers.isDatasetVisible(dataset) && (this.isHorizontal() ? meta.xAxisID === this.id : meta.yAxisID === this.id)) {
<del> if (valuesPerType[dataset.type] === undefined) {
<del> valuesPerType[dataset.type] = [];
<add> if (valuesPerType[meta.type] === undefined) {
<add> valuesPerType[meta.type] = [];
<ide> }
<ide>
<ide> helpers.each(dataset.data, function(rawValue, index) {
<del> var values = valuesPerType[dataset.type];
<add> var values = valuesPerType[meta.type];
<ide> var value = +this.getRightValue(rawValue);
<ide> if (isNaN(value)) {
<ide> return; | 5 |
Python | Python | fix unicode default input on py3 | 1ea96acaf56acee692fe6f5668644962231be5e1 | <ide><path>django/db/migrations/questioner.py
<ide> import sys
<ide>
<ide> from django.apps import apps
<del>from django.utils import datetime_safe
<add>from django.utils import datetime_safe, six
<ide> from django.utils.six.moves import input
<ide>
<ide> from .loader import MIGRATIONS_MODULE_NAME
<ide> def ask_not_null_addition(self, field_name, model_name):
<ide> print("Please enter the default value now, as valid Python")
<ide> print("The datetime module is available, so you can do e.g. datetime.date.today()")
<ide> while True:
<del> code = input(">>> ").decode(sys.stdin.encoding)
<add> if six.PY3:
<add> # Six does not correctly abstract over the fact that
<add> # py3 input returns a unicode string, while py2 raw_input
<add> # returns a bytestring.
<add> code = input(">>> ")
<add> else:
<add> code = input(">>> ").decode(sys.stdin.encoding)
<ide> if not code:
<ide> print("Please enter some code, or 'exit' (with no quotes) to exit.")
<ide> elif code == "exit": | 1 |
Java | Java | expose getters for the configured handlermapping's | 819ca0dbd40cccd4eae0353ff0b9aeaf248d3ab6 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/DispatcherHandler.java
<ide> public DispatcherHandler(ApplicationContext applicationContext) {
<ide> }
<ide>
<ide>
<add> /**
<add> * Return all {@link HandlerMapping} beans detected by type in the
<add> * {@link #setApplicationContext injected context} and also
<add> * {@link AnnotationAwareOrderComparator#sort(List) sorted}.
<add> * @return immutable list with the configured mappings
<add> */
<add> public List<HandlerMapping> getHandlerMappings() {
<add> return this.handlerMappings;
<add> }
<add>
<ide> @Override
<ide> public void setApplicationContext(ApplicationContext applicationContext) {
<ide> initStrategies(applicationContext);
<ide> }
<ide>
<add>
<ide> protected void initStrategies(ApplicationContext context) {
<ide> Map<String, HandlerMapping> mappingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
<ide> context, HandlerMapping.class, true, false);
<ide>
<del> this.handlerMappings = new ArrayList<>(mappingBeans.values());
<add> ArrayList<HandlerMapping> mappings = new ArrayList<>(mappingBeans.values());
<ide> AnnotationAwareOrderComparator.sort(this.handlerMappings);
<add> this.handlerMappings = Collections.unmodifiableList(mappings);
<ide>
<ide> Map<String, HandlerAdapter> adapterBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
<ide> context, HandlerAdapter.class, true, false);
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java
<ide> private void initFlashMapManager(ApplicationContext context) {
<ide> }
<ide> }
<ide>
<add> /**
<add> * Return the configured {@link HandlerMapping} beans that were detected by
<add> * type in the {@link WebApplicationContext} or initialized based on the
<add> * default set of strategies from {@literal DispatcherServlet.properties}.
<add> * @return immutable list with the configured mappings or an empty list
<add> * @since 5.0
<add> */
<add> public List<HandlerMapping> getHandlerMappings() {
<add> return this.handlerMappings != null ?
<add> Collections.unmodifiableList(this.handlerMappings) :
<add> Collections.emptyList();
<add> }
<add>
<ide> /**
<ide> * Return this servlet's ThemeSource, if any; else return {@code null}.
<ide> * <p>Default is to return the WebApplicationContext as ThemeSource, | 2 |
PHP | PHP | display no failed jobs | 7dfc1025ccf79046eaeb611f50d200edfae33b49 | <ide><path>src/Illuminate/Queue/Console/ListFailedCommand.php
<ide> public function fire()
<ide> $rows[] = array_values(array_except((array) $failed, array('payload')));
<ide> }
<ide>
<add> if (count($rows) == 0)
<add> {
<add> return $this->info('Awesome! No failed jobs!');
<add> }
<add>
<ide> $table = $this->getHelperSet()->get('table');
<ide>
<ide> $table->setHeaders(array('ID', 'Connection', 'Queue', 'Failed At')) | 1 |
Python | Python | fix pickle during train | e920885676c6e7019fdd2891b2173aa630d54c6b | <ide><path>spacy/cli/train.py
<ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> n_train_words = corpus.count_train()
<ide>
<ide> optimizer = nlp.begin_training(lambda: corpus.train_tuples, device=use_gpu)
<add> nlp._optimizer = None
<ide>
<ide> print("Itn.\tLoss\tUAS\tNER P.\tNER R.\tNER F.\tTag %\tToken %")
<ide> try: | 1 |
Javascript | Javascript | register touches properly when jquery is used | 06a9f0a95f0e72fa2e9879fe8a49e9bf69986a5f | <ide><path>src/ngScenario/browserTrigger.js
<ide> evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0);
<ide> }
<ide> }
<add> } else if (/touch/.test(eventType) && supportsTouchEvents()) {
<add> evnt = createTouchEvent(element, eventType, x, y);
<ide> } else {
<ide> evnt = document.createEvent('MouseEvents');
<ide> x = x || 0;
<ide>
<ide> return finalProcessDefault;
<ide> };
<add>
<add> function supportsTouchEvents() {
<add> if ('_cached' in supportsTouchEvents) {
<add> return supportsTouchEvents._cached;
<add> }
<add> if (!document.createTouch || !document.createTouchList) {
<add> supportsTouchEvents._cached = false;
<add> return false;
<add> }
<add> try {
<add> document.createEvent('TouchEvent');
<add> } catch (e) {
<add> supportsTouchEvents._cached = false;
<add> return false;
<add> }
<add> supportsTouchEvents._cached = true;
<add> return true;
<add> }
<add>
<add> function createTouchEvent(element, eventType, x, y) {
<add> var evnt = document.createEvent('TouchEvent');
<add> x = x || 0;
<add> y = y || 0;
<add>
<add> var touch = document.createTouch(window, element, Date.now(), x, y, x, y);
<add> var touches = document.createTouchList(touch);
<add> var targetTouches = document.createTouchList(touch);
<add> var changedTouches = document.createTouchList(touch);
<add>
<add> evnt.initTouchEvent(eventType, true, true, window, null, 0, 0, 0, 0, false, false, false, false,
<add> touches, targetTouches, changedTouches, 1, 0);
<add> return evnt;
<add> }
<ide> }());
<ide><path>src/ngTouch/directive/ngClick.js
<ide> ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
<ide>
<ide> startTime = Date.now();
<ide>
<del> var touches = event.touches && event.touches.length ? event.touches : [event];
<del> var e = touches[0].originalEvent || touches[0];
<add> // Use jQuery originalEvent
<add> var originalEvent = event.originalEvent || event;
<add> var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
<add> var e = touches[0];
<ide> touchStartX = e.clientX;
<ide> touchStartY = e.clientY;
<ide> });
<ide> ngTouch.directive('ngClick', ['$parse', '$timeout', '$rootElement',
<ide> element.on('touchend', function(event) {
<ide> var diff = Date.now() - startTime;
<ide>
<del> var touches = (event.changedTouches && event.changedTouches.length) ? event.changedTouches :
<del> ((event.touches && event.touches.length) ? event.touches : [event]);
<del> var e = touches[0].originalEvent || touches[0];
<add> // Use jQuery originalEvent
<add> var originalEvent = event.originalEvent || event;
<add> var touches = (originalEvent.changedTouches && originalEvent.changedTouches.length) ?
<add> originalEvent.changedTouches :
<add> ((originalEvent.touches && originalEvent.touches.length) ? originalEvent.touches : [originalEvent]);
<add> var e = touches[0];
<ide> var x = e.clientX;
<ide> var y = e.clientY;
<ide> var dist = Math.sqrt(Math.pow(x - touchStartX, 2) + Math.pow(y - touchStartY, 2));
<ide><path>src/ngTouch/swipe.js
<ide> ngTouch.factory('$swipe', [function() {
<ide> };
<ide>
<ide> function getCoordinates(event) {
<del> var touches = event.touches && event.touches.length ? event.touches : [event];
<del> var e = (event.changedTouches && event.changedTouches[0]) ||
<del> (event.originalEvent && event.originalEvent.changedTouches &&
<del> event.originalEvent.changedTouches[0]) ||
<del> touches[0].originalEvent || touches[0];
<add> var originalEvent = event.originalEvent || event;
<add> var touches = originalEvent.touches && originalEvent.touches.length ? originalEvent.touches : [originalEvent];
<add> var e = (originalEvent.changedTouches && originalEvent.changedTouches[0]) || touches[0];
<ide>
<ide> return {
<ide> x: e.clientX,
<ide><path>test/ngTouch/directive/ngClickSpec.js
<ide> describe('ngClick (touch)', function() {
<ide>
<ide> // TODO(braden): Once we have other touch-friendly browsers on CI, allow them here.
<ide> // Currently Firefox and IE refuse to fire touch events.
<del> var chrome = /chrome/.test(navigator.userAgent.toLowerCase());
<del> if (!chrome) {
<add> // Enable iPhone for manual testing.
<add> if (!/chrome|iphone/i.test(navigator.userAgent)) {
<ide> return;
<ide> }
<ide>
<ide> describe('ngClick (touch)', function() {
<ide> expect($rootScope.event).toBeDefined();
<ide> }));
<ide>
<add> if (window.jQuery) {
<add> it('should not unwrap a jQuery-wrapped event object on click', inject(function($rootScope, $compile) {
<add> element = $compile('<div ng-click="event = $event"></div>')($rootScope);
<add> $rootScope.$digest();
<add>
<add> browserTrigger(element, 'click', {
<add> keys: [],
<add> x: 10,
<add> y: 10
<add> });
<add> expect($rootScope.event.originalEvent).toBeDefined();
<add> expect($rootScope.event.originalEvent.clientX).toBe(10);
<add> expect($rootScope.event.originalEvent.clientY).toBe(10);
<add> }));
<add>
<add> it('should not unwrap a jQuery-wrapped event object on touchstart/touchend',
<add> inject(function($rootScope, $compile, $rootElement) {
<add> element = $compile('<div ng-click="event = $event"></div>')($rootScope);
<add> $rootElement.append(element);
<add> $rootScope.$digest();
<add>
<add> browserTrigger(element, 'touchstart');
<add> browserTrigger(element, 'touchend');
<add>
<add> expect($rootScope.event.originalEvent).toBeDefined();
<add> }));
<add> }
<add>
<ide>
<ide> it('should not click if the touch is held too long', inject(function($rootScope, $compile, $rootElement) {
<ide> element = $compile('<div ng-click="count = count + 1"></div>')($rootScope);
<ide> describe('ngClick (touch)', function() {
<ide>
<ide> expect($rootScope.selection).toBe('initial');
<ide> });
<add>
<add>
<add> it('should blur the other element on click', function() {
<add> var blurSpy = spyOn(otherElement, 'blur');
<add> touch(otherElement, 10, 10);
<add>
<add> time = 500;
<add> click(label, 10, 10);
<add>
<add> expect(blurSpy).toHaveBeenCalled();
<add> });
<ide> });
<ide> });
<ide>
<ide><path>test/ngTouch/swipeSpec.js
<ide> describe('$swipe', function() {
<ide> if (restrictBrowsers) {
<ide> // TODO(braden): Once we have other touch-friendly browsers on CI, allow them here.
<ide> // Currently Firefox and IE refuse to fire touch events.
<del> var chrome = /chrome/.test(navigator.userAgent.toLowerCase());
<del> if (!chrome) {
<add> // Enable iPhone for manual testing.
<add> if (!/chrome|iphone/i.test(navigator.userAgent)) {
<ide> return;
<ide> }
<ide> } | 5 |
Go | Go | add "iswindows" const | 05469b5fa2b48cf20cd0137ca8c45645b63049ff | <ide><path>daemon/changes.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide>
<ide> import (
<ide> "errors"
<del> "runtime"
<ide> "time"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<ide> func (daemon *Daemon) ContainerChanges(name string) ([]archive.Change, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if runtime.GOOS == "windows" && container.IsRunning() {
<add> if isWindows && container.IsRunning() {
<ide> return nil, errors.New("Windows does not support diff of a running container")
<ide> }
<ide>
<ide><path>daemon/cluster/cluster.go
<ide> import (
<ide> "net"
<ide> "os"
<ide> "path/filepath"
<add> "runtime"
<ide> "sync"
<ide> "time"
<ide>
<ide> import (
<ide> "google.golang.org/grpc"
<ide> )
<ide>
<del>const swarmDirName = "swarm"
<del>const controlSocket = "control.sock"
<del>const swarmConnectTimeout = 20 * time.Second
<del>const swarmRequestTimeout = 20 * time.Second
<del>const stateFile = "docker-state.json"
<del>const defaultAddr = "0.0.0.0:2377"
<del>
<ide> const (
<add> swarmDirName = "swarm"
<add> controlSocket = "control.sock"
<add> swarmConnectTimeout = 20 * time.Second
<add> swarmRequestTimeout = 20 * time.Second
<add> stateFile = "docker-state.json"
<add> defaultAddr = "0.0.0.0:2377"
<add> isWindows = runtime.GOOS == "windows"
<ide> initialReconnectDelay = 100 * time.Millisecond
<ide> maxReconnectDelay = 30 * time.Second
<ide> contextPrefix = "com.docker.swarm"
<ide><path>daemon/cluster/noderunner.go
<ide> import (
<ide> "context"
<ide> "fmt"
<ide> "path/filepath"
<del> "runtime"
<ide> "strings"
<ide> "sync"
<ide> "time"
<ide> func (n *nodeRunner) Start(conf nodeStartConfig) error {
<ide>
<ide> func (n *nodeRunner) start(conf nodeStartConfig) error {
<ide> var control string
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> control = `\\.\pipe\` + controlSocket
<ide> } else {
<ide> control = filepath.Join(n.cluster.runtimeRoot, controlSocket)
<ide><path>daemon/commit.go
<ide> func merge(userConf, imageConf *containertypes.Config) error {
<ide> imageEnvKey := strings.Split(imageEnv, "=")[0]
<ide> for _, userEnv := range userConf.Env {
<ide> userEnvKey := strings.Split(userEnv, "=")[0]
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> // Case insensitive environment variables on Windows
<ide> imageEnvKey = strings.ToUpper(imageEnvKey)
<ide> userEnvKey = strings.ToUpper(userEnvKey)
<ide> func (daemon *Daemon) CreateImageFromContainer(name string, c *backend.CreateIma
<ide> }
<ide>
<ide> // It is not possible to commit a running container on Windows
<del> if (runtime.GOOS == "windows") && container.IsRunning() {
<add> if isWindows && container.IsRunning() {
<ide> return "", errors.Errorf("%+v does not support commit of a running container", runtime.GOOS)
<ide> }
<ide>
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) containerCreate(opts createOpts) (containertypes.Container
<ide> } else {
<ide> // This mean scratch. On Windows, we can safely assume that this is a linux
<ide> // container. On other platforms, it's the host OS (which it already is)
<del> if runtime.GOOS == "windows" && system.LCOWSupported() {
<add> if isWindows && system.LCOWSupported() {
<ide> os = "linux"
<ide> }
<ide> }
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide> os = img.OS
<ide> } else {
<ide> // default to the host OS except on Windows with LCOW
<del> if runtime.GOOS == "windows" && system.LCOWSupported() {
<add> if isWindows && system.LCOWSupported() {
<ide> os = "linux"
<ide> }
<ide> }
<ide> imgID = img.ID()
<ide>
<del> if runtime.GOOS == "windows" && img.OS == "linux" && !system.LCOWSupported() {
<add> if isWindows && img.OS == "linux" && !system.LCOWSupported() {
<ide> return nil, errors.New("operating system on which parent image was created is not Windows")
<ide> }
<ide> } else {
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> os = "linux" // 'scratch' case.
<ide> }
<ide> }
<ide> func (daemon *Daemon) create(opts createOpts) (retC *container.Container, retErr
<ide> // Merge the daemon's storage options if they aren't already present. We only
<ide> // do this on Windows as there's no effective sandbox size limit other than
<ide> // physical on Linux.
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> if container.HostConfig.StorageOpt == nil {
<ide> container.HostConfig.StorageOpt = make(map[string]string)
<ide> }
<ide><path>daemon/daemon.go
<ide> import (
<ide> )
<ide>
<ide> // ContainersNamespace is the name of the namespace used for users containers
<del>const ContainersNamespace = "moby"
<add>const (
<add> ContainersNamespace = "moby"
<add>)
<ide>
<ide> var (
<ide> errSystemNotSupported = errors.New("the Docker daemon is not supported on this platform")
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> if err != nil {
<ide> return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
<ide> }
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> if _, err := os.Stat(realTmp); err != nil && os.IsNotExist(err) {
<ide> if err := system.MkdirAll(realTmp, 0700); err != nil {
<ide> return nil, fmt.Errorf("Unable to create the TempDir (%s): %s", realTmp, err)
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> return nil, err
<ide> }
<ide>
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> if err := system.MkdirAll(filepath.Join(config.Root, "credentialspecs"), 0); err != nil {
<ide> return nil, err
<ide> }
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> // initialization of the layerstore through driver priority order for example.
<ide> d.graphDrivers = make(map[string]string)
<ide> layerStores := make(map[string]layer.Store)
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> d.graphDrivers[runtime.GOOS] = "windowsfilter"
<ide> if system.LCOWSupported() {
<ide> d.graphDrivers["linux"] = "lcow"
<ide><path>daemon/daemon_unix.go
<ide> import (
<ide> )
<ide>
<ide> const (
<add> isWindows = false
<add>
<ide> // DefaultShimBinary is the default shim to be used by containerd if none
<ide> // is specified
<ide> DefaultShimBinary = "containerd-shim"
<ide><path>daemon/daemon_windows.go
<ide> import (
<ide> )
<ide>
<ide> const (
<add> isWindows = true
<ide> defaultNetworkSpace = "172.16.0.0/12"
<ide> platformSupported = true
<ide> windowsMinCPUShares = 1
<ide><path>daemon/export.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide> import (
<ide> "fmt"
<ide> "io"
<del> "runtime"
<ide>
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/errdefs"
<ide> func (daemon *Daemon) ContainerExport(name string, out io.Writer) error {
<ide> return err
<ide> }
<ide>
<del> if runtime.GOOS == "windows" && container.OS == "windows" {
<add> if isWindows && container.OS == "windows" {
<ide> return fmt.Errorf("the daemon on this operating system does not support exporting Windows containers")
<ide> }
<ide>
<ide><path>daemon/monitor.go
<ide> package daemon // import "github.com/docker/docker/daemon"
<ide>
<ide> import (
<ide> "context"
<del> "runtime"
<ide> "strconv"
<ide> "time"
<ide>
<ide> func (daemon *Daemon) ProcessEvent(id string, e libcontainerdtypes.EventType, ei
<ide> switch e {
<ide> case libcontainerdtypes.EventOOM:
<ide> // StateOOM is Linux specific and should never be hit on Windows
<del> if runtime.GOOS == "windows" {
<add> if isWindows {
<ide> return errors.New("received StateOOM from libcontainerd on Windows. This should never happen")
<ide> }
<ide>
<ide><path>daemon/stats.go
<ide> func (daemon *Daemon) ContainerStats(ctx context.Context, prefixOrName string, c
<ide> // Engine API version (used for backwards compatibility)
<ide> apiVersion := config.Version
<ide>
<del> if runtime.GOOS == "windows" && versions.LessThan(apiVersion, "1.21") {
<add> if isWindows && versions.LessThan(apiVersion, "1.21") {
<ide> return errors.New("API versions pre v1.21 do not support stats on Windows")
<ide> }
<ide> | 11 |
Go | Go | fix remaining issues with checker.not | 40f1950e8ea84a8518c7378d0e8cbe9142e3b0cf | <ide><path>integration-cli/docker_cli_prune_unix_test.go
<ide> func pruneNetworkAndVerify(c *testing.T, d *daemon.Daemon, kept, pruned []string
<ide> out, err := d.Cmd("network", "ls", "--format", "{{.Name}}")
<ide> assert.NilError(c, err)
<ide> return out, ""
<del> }, checker.Not(checker.Contains(s))()), poll.WithTimeout(defaultReconciliationTimeout))
<del>
<add> }, checker.Not(checker.Contains(s))), poll.WithTimeout(defaultReconciliationTimeout))
<ide> }
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_swarm_test.go
<ide> func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *testing.T) {
<ide> return out, ""
<ide> }
<ide>
<del> poll.WaitOn(c, pollCheck(c, checkNetwork, checker.Not(checker.Contains("testnet"))()), poll.WithTimeout(3*time.Second))
<add> poll.WaitOn(c, pollCheck(c, checkNetwork, checker.Not(checker.Contains("testnet"))), poll.WithTimeout(3*time.Second))
<ide> }
<ide>
<ide> func (s *DockerSwarmSuite) TestOverlayAttachable(c *testing.T) {
<ide><path>pkg/discovery/discovery_test.go
<ide> package discovery // import "github.com/docker/docker/pkg/discovery"
<ide> import (
<ide> "testing"
<ide>
<del> "github.com/docker/docker/integration-cli/checker"
<ide> "gotest.tools/assert"
<ide> )
<ide>
<ide> func (s *DiscoverySuite) TestEntriesEquality(c *testing.T) {
<ide> assert.Assert(c, entries.Equals(Entries{
<ide> &Entry{Host: "127.0.0.1", Port: "2375"},
<ide> &Entry{Host: "127.0.0.2", Port: "2375"},
<del> }), checker.Equals, true)
<add> }))
<ide>
<ide> // Different size
<del> assert.Assert(c, entries.Equals(Entries{
<add> assert.Assert(c, !entries.Equals(Entries{
<ide> &Entry{Host: "127.0.0.1", Port: "2375"},
<ide> &Entry{Host: "127.0.0.2", Port: "2375"},
<ide> &Entry{Host: "127.0.0.3", Port: "2375"},
<del> }), checker.Equals, false)
<add> }))
<ide>
<ide> // Different content
<del> assert.Assert(c, entries.Equals(Entries{
<add> assert.Assert(c, !entries.Equals(Entries{
<ide> &Entry{Host: "127.0.0.1", Port: "2375"},
<ide> &Entry{Host: "127.0.0.42", Port: "2375"},
<del> }), checker.Equals, false)
<add> }))
<ide>
<ide> }
<ide> | 3 |
Ruby | Ruby | remove extra white spaces on activemodel docs | 2a4b780ab1b97b939524f3240b6886c2b77979d2 | <ide><path>activemodel/lib/active_model/callbacks.rb
<ide> def self.extended(base)
<ide> # define_model_callbacks :initializer, :only => :after
<ide> #
<ide> # Note, the <tt>:only => <type></tt> hash will apply to all callbacks defined on
<del> # that method call. To get around this you can call the define_model_callbacks
<add> # that method call. To get around this you can call the define_model_callbacks
<ide> # method as many times as you need.
<ide> #
<ide> # define_model_callbacks :create, :only => :after
<ide><path>activemodel/lib/active_model/errors.rb
<ide> module ActiveModel
<ide> #
<ide> # The last three methods are required in your object for Errors to be
<ide> # able to generate error messages correctly and also handle multiple
<del> # languages. Of course, if you extend your object with ActiveModel::Translations
<del> # you will not need to implement the last two. Likewise, using
<add> # languages. Of course, if you extend your object with ActiveModel::Translations
<add> # you will not need to implement the last two. Likewise, using
<ide> # ActiveModel::Validations will handle the validation related methods
<ide> # for you.
<ide> #
<ide> def []=(attribute, error)
<ide> end
<ide>
<ide> # Iterates through each error key, value pair in the error messages hash.
<del> # Yields the attribute and the error for that attribute. If the attribute
<add> # Yields the attribute and the error for that attribute. If the attribute
<ide> # has more than one error message, yields once for each error message.
<ide> #
<ide> # p.errors.add(:name, "can't be blank")
<ide><path>activemodel/lib/active_model/observer_array.rb
<ide> def disabled_for?(observer)
<ide> disabled_observers.include?(observer.class)
<ide> end
<ide>
<del> # Disables one or more observers. This supports multiple forms:
<add> # Disables one or more observers. This supports multiple forms:
<ide> #
<ide> # ORM.observers.disable :user_observer
<ide> # # => disables the UserObserver
<ide> def disable(*observers, &block)
<ide> set_enablement(false, observers, &block)
<ide> end
<ide>
<del> # Enables one or more observers. This supports multiple forms:
<add> # Enables one or more observers. This supports multiple forms:
<ide> #
<ide> # ORM.observers.enable :user_observer
<ide> # # => enables the UserObserver
<ide> def disable(*observers, &block)
<ide> # # just the duration of the block
<ide> # end
<ide> #
<del> # Note: all observers are enabled by default. This method is only
<add> # Note: all observers are enabled by default. This method is only
<ide> # useful when you have previously disabled one or more observers.
<ide> def enable(*observers, &block)
<ide> set_enablement(true, observers, &block)
<ide><path>activemodel/lib/active_model/serialization.rb
<ide> module ActiveModel
<ide> # you want to serialize and their current value.
<ide> #
<ide> # Most of the time though, you will want to include the JSON or XML
<del> # serializations. Both of these modules automatically include the
<add> # serializations. Both of these modules automatically include the
<ide> # ActiveModel::Serialization module, so there is no need to explicitly
<ide> # include it.
<ide> #
<ide><path>activemodel/lib/active_model/serializers/xml.rb
<ide> def initialize(serializable, options = nil)
<ide> end
<ide>
<ide> # To replicate the behavior in ActiveRecord#attributes, <tt>:except</tt>
<del> # takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
<add> # takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
<ide> # for a N level model but is set for the N+1 level models,
<ide> # then because <tt>:except</tt> is set to a default value, the second
<del> # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
<add> # level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
<ide> # <tt>:only</tt> is set, always delete <tt>:except</tt>.
<ide> def attributes_hash
<ide> attributes = @serializable.attributes
<ide><path>activemodel/lib/active_model/validations.rb
<ide> module ClassMethods
<ide> # proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<ide> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or
<del> # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_each(*attr_names, &block)
<ide> options = attr_names.extract_options!.symbolize_keys
<ide><path>activemodel/lib/active_model/validations/acceptance.rb
<ide> module HelperMethods
<ide> # before validation.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
<ide> # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
<del> # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false
<ide> # value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to
<ide><path>activemodel/lib/active_model/validations/confirmation.rb
<ide> module HelperMethods
<ide> # and <tt>:update</tt>.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine
<ide> # if the validation should occur (e.g. <tt>:if => :allow_validation</tt>,
<del> # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false
<ide> # value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to
<ide><path>activemodel/lib/active_model/validations/exclusion.rb
<ide> module HelperMethods
<ide> # validation contexts by default (+nil+), other options are <tt>:create</tt>
<ide> # and <tt>:update</tt>.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_exclusion_of(*attr_names)
<ide> validates_with ExclusionValidator, _merge_attributes(attr_names)
<ide><path>activemodel/lib/active_model/validations/format.rb
<ide> module HelperMethods
<ide> # validation contexts by default (+nil+), other options are <tt>:create</tt>
<ide> # and <tt>:update</tt>.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_format_of(*attr_names)
<ide> validates_with FormatValidator, _merge_attributes(attr_names)
<ide><path>activemodel/lib/active_model/validations/inclusion.rb
<ide> module HelperMethods
<ide> # validation contexts by default (+nil+), other options are <tt>:create</tt>
<ide> # and <tt>:update</tt>.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> def validates_inclusion_of(*attr_names)
<ide> validates_with InclusionValidator, _merge_attributes(attr_names)
<ide><path>activemodel/lib/active_model/validations/length.rb
<ide> module HelperMethods
<ide> # * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %{count} characters)").
<ide> # * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %{count} characters)").
<ide> # * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %{count} characters)").
<del> # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
<add> # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
<ide> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
<ide> # validation contexts by default (+nil+), other options are <tt>:create</tt>
<ide> # and <tt>:update</tt>.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. (e.g. <tt>:tokenizer => lambda {|str| str.scan(/\w+/)}</tt> to
<ide> # count words as in above example.)
<ide><path>activemodel/lib/active_model/validations/numericality.rb
<ide> module HelperMethods
<ide> # * <tt>:odd</tt> - Specifies the value must be an odd number.
<ide> # * <tt>:even</tt> - Specifies the value must be an even number.
<ide> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<add> # occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
<del> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<add> # not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
<ide> # method, proc or string should return or evaluate to a true or false value.
<ide> #
<ide> # The following checks can also be supplied with a proc or a symbol which corresponds to a method: | 13 |
Javascript | Javascript | use util.inspect() to create error messages | 40e29dcbbf33d919f5cc0cbab5fa65a282adb04b | <ide><path>lib/assert.js
<ide> assert.AssertionError = function AssertionError(options) {
<ide> // assert.AssertionError instanceof Error
<ide> util.inherits(assert.AssertionError, Error);
<ide>
<del>function replacer(key, value) {
<del> if (util.isUndefined(value)) {
<del> return '' + value;
<del> }
<del> if (util.isNumber(value) && !isFinite(value)) {
<del> return value.toString();
<del> }
<del> if (util.isFunction(value) || util.isRegExp(value)) {
<del> return value.toString();
<del> }
<del> return value;
<del>}
<del>
<ide> function truncate(s, n) {
<ide> if (util.isString(s)) {
<ide> return s.length < n ? s : s.slice(0, n);
<ide> function truncate(s, n) {
<ide> }
<ide>
<ide> function getMessage(self) {
<del> return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
<add> return truncate(util.inspect(self.actual), 128) + ' ' +
<ide> self.operator + ' ' +
<del> truncate(JSON.stringify(self.expected, replacer), 128);
<add> truncate(util.inspect(self.expected), 128);
<ide> }
<ide>
<ide> // At present only the three keys mentioned above are used and
<ide><path>test/parallel/test-assert.js
<ide> a.throws(makeBlock(a.deepEqual, args, []));
<ide> assert.ok(gotError);
<ide>
<ide>
<del>// #217
<add>var circular = {y: 1};
<add>circular.x = circular;
<add>
<ide> function testAssertionMessage(actual, expected) {
<ide> try {
<ide> assert.equal(actual, '');
<ide> } catch (e) {
<ide> assert.equal(e.toString(),
<del> ['AssertionError:', expected, '==', '""'].join(' '));
<add> ['AssertionError:', expected, '==', '\'\''].join(' '));
<ide> assert.ok(e.generatedMessage, "Message not marked as generated");
<ide> }
<ide> }
<del>testAssertionMessage(undefined, '"undefined"');
<add>
<add>testAssertionMessage(undefined, 'undefined');
<ide> testAssertionMessage(null, 'null');
<ide> testAssertionMessage(true, 'true');
<ide> testAssertionMessage(false, 'false');
<ide> testAssertionMessage(0, '0');
<ide> testAssertionMessage(100, '100');
<del>testAssertionMessage(NaN, '"NaN"');
<del>testAssertionMessage(Infinity, '"Infinity"');
<del>testAssertionMessage(-Infinity, '"-Infinity"');
<add>testAssertionMessage(NaN, 'NaN');
<add>testAssertionMessage(Infinity, 'Infinity');
<add>testAssertionMessage(-Infinity, '-Infinity');
<ide> testAssertionMessage('', '""');
<del>testAssertionMessage('foo', '"foo"');
<add>testAssertionMessage('foo', '\'foo\'');
<ide> testAssertionMessage([], '[]');
<del>testAssertionMessage([1, 2, 3], '[1,2,3]');
<del>testAssertionMessage(/a/, '"/a/"');
<del>testAssertionMessage(/abc/gim, '"/abc/gim"');
<del>testAssertionMessage(function f() {}, '"function f() {}"');
<add>testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]');
<add>testAssertionMessage(/a/, '/a/');
<add>testAssertionMessage(/abc/gim, '/abc/gim');
<add>testAssertionMessage(function f() {}, '[Function: f]');
<add>testAssertionMessage(function () {}, '[Function]');
<ide> testAssertionMessage({}, '{}');
<del>testAssertionMessage({a: undefined, b: null}, '{"a":"undefined","b":null}');
<add>testAssertionMessage(circular, '{ y: 1, x: [Circular] }');
<add>testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }');
<ide> testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
<del> '{"a":"NaN","b":"Infinity","c":"-Infinity"}');
<add> '{ a: NaN, b: Infinity, c: -Infinity }');
<ide>
<ide> // #2893
<ide> try { | 2 |
Ruby | Ruby | fix dangling klass reference | ffc45f3e7128f0ef1efca0f39d4717447c15f5b8 | <ide><path>railties/test/generators_test.rb
<ide> class NewGenerator < Rails::Generators::Base
<ide>
<ide> assert_equal false, NewGenerator.class_options[:generate].default
<ide> ensure
<del> Rails::Generators.subclasses.delete(klass)
<add> Rails::Generators.subclasses.delete(NewGenerator)
<ide> end
<ide>
<ide> def test_load_generators_from_railties | 1 |
Text | Text | expand entries for isip(), isipv4(), and isipv6() | 97b8eb62fe7ad7722e7f27d658b3519c0e5f2110 | <ide><path>doc/api/net.md
<ide> added: v0.3.0
<ide> * `input` {string}
<ide> * Returns: {integer}
<ide>
<del>Tests if input is an IP address. Returns `0` for invalid strings,
<del>returns `4` for IP version 4 addresses, and returns `6` for IP version 6
<del>addresses.
<add>Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4
<add>address in [dot-decimal notation][] with no leading zeroes. Otherwise, returns
<add>`0`.
<add>
<add>```js
<add>net.isIP('::1'); // returns 6
<add>net.isIP('127.0.0.1'); // returns 4
<add>net.isIP('127.000.000.001'); // returns 0
<add>net.isIP('127.0.0.1/24'); // returns 0
<add>net.isIP('fhqwhgads'); // returns 0
<add>```
<ide>
<ide> ## `net.isIPv4(input)`
<ide>
<ide> added: v0.3.0
<ide> * `input` {string}
<ide> * Returns: {boolean}
<ide>
<del>Returns `true` if input is a version 4 IP address, otherwise returns `false`.
<add>Returns `true` if `input` is an IPv4 address in [dot-decimal notation][] with no
<add>leading zeroes. Otherwise, returns `false`.
<add>
<add>```js
<add>net.isIPv4('127.0.0.1'); // returns true
<add>net.isIPv4('127.000.000.001'); // returns false
<add>net.isIPv4('127.0.0.1/24'); // returns false
<add>net.isIPv4('fhqwhgads'); // returns false
<add>```
<ide>
<ide> ## `net.isIPv6(input)`
<ide>
<ide> added: v0.3.0
<ide> * `input` {string}
<ide> * Returns: {boolean}
<ide>
<del>Returns `true` if input is a version 6 IP address, otherwise returns `false`.
<add>Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`.
<add>
<add>```js
<add>net.isIPv6('::1'); // returns true
<add>net.isIPv6('fhqwhgads'); // returns false
<add>```
<ide>
<ide> [IPC]: #ipc-support
<ide> [Identifying paths for IPC connections]: #identifying-paths-for-ipc-connections
<ide> Returns `true` if input is a version 6 IP address, otherwise returns `false`.
<ide> [`writable.destroyed`]: stream.md#writabledestroyed
<ide> [`writable.end()`]: stream.md#writableendchunk-encoding-callback
<ide> [`writable.writableLength`]: stream.md#writablewritablelength
<add>[dot-decimal notation]: https://en.wikipedia.org/wiki/Dot-decimal_notation
<ide> [half-closed]: https://tools.ietf.org/html/rfc1122
<ide> [stream_writable_write]: stream.md#writablewritechunk-encoding-callback
<ide> [unspecified IPv4 address]: https://en.wikipedia.org/wiki/0.0.0.0 | 1 |
Go | Go | improve error message for enotdir errors | 83ae501f1d216600eebf182e7dc29e285c4b10bc | <ide><path>daemon/start.go
<ide> func (daemon *Daemon) containerStart(container *container.Container) (err error)
<ide> container.SetExitCode(126)
<ide> }
<ide>
<add> // attempted to mount a file onto a directory, or a directory onto a file, maybe from user specified bind mounts
<add> if strings.Contains(errDesc, syscall.ENOTDIR.Error()) {
<add> errDesc += ": Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type"
<add> container.SetExitCode(127)
<add> }
<add>
<ide> container.Reset(false)
<ide>
<ide> return fmt.Errorf("%s", errDesc) | 1 |
Text | Text | fix comment text in async_hooks example | 85f679fff101e86051dab5ab21359399b3dde9ae | <ide><path>doc/api/async_hooks.md
<ide> asyncHook.disable();
<ide> // The following are the callbacks that can be passed to createHook().
<ide> //
<ide>
<del>// init is called during object construction. The resource may not have
<del>// completed construction when this callback runs, therefore all fields of the
<add>// init() is called during object construction. The resource may not have
<add>// completed construction when this callback runs. Therefore, all fields of the
<ide> // resource referenced by "asyncId" may not have been populated.
<ide> function init(asyncId, type, triggerAsyncId, resource) { }
<ide>
<del>// Before is called just before the resource's callback is called. It can be
<add>// before() is called just before the resource's callback is called. It can be
<ide> // called 0-N times for handles (such as TCPWrap), and will be called exactly 1
<ide> // time for requests (such as FSReqCallback).
<ide> function before(asyncId) { }
<ide>
<del>// After is called just after the resource's callback has finished.
<add>// after() is called just after the resource's callback has finished.
<ide> function after(asyncId) { }
<ide>
<del>// Destroy is called when the resource is destroyed.
<add>// destroy() is called when the resource is destroyed.
<ide> function destroy(asyncId) { }
<ide>
<del>// promiseResolve is called only for promise resources, when the
<del>// `resolve` function passed to the `Promise` constructor is invoked
<add>// promiseResolve() is called only for promise resources, when the
<add>// resolve() function passed to the Promise constructor is invoked
<ide> // (either directly or through other means of resolving a promise).
<ide> function promiseResolve(asyncId) { }
<ide> ```
<ide> asyncHook.disable();
<ide> // The following are the callbacks that can be passed to createHook().
<ide> //
<ide>
<del>// init is called during object construction. The resource may not have
<del>// completed construction when this callback runs, therefore all fields of the
<add>// init() is called during object construction. The resource may not have
<add>// completed construction when this callback runs. Therefore, all fields of the
<ide> // resource referenced by "asyncId" may not have been populated.
<ide> function init(asyncId, type, triggerAsyncId, resource) { }
<ide>
<del>// Before is called just before the resource's callback is called. It can be
<add>// before() is called just before the resource's callback is called. It can be
<ide> // called 0-N times for handles (such as TCPWrap), and will be called exactly 1
<ide> // time for requests (such as FSReqCallback).
<ide> function before(asyncId) { }
<ide>
<del>// After is called just after the resource's callback has finished.
<add>// after() is called just after the resource's callback has finished.
<ide> function after(asyncId) { }
<ide>
<del>// Destroy is called when the resource is destroyed.
<add>// destroy() is called when the resource is destroyed.
<ide> function destroy(asyncId) { }
<ide>
<del>// promiseResolve is called only for promise resources, when the
<del>// `resolve` function passed to the `Promise` constructor is invoked
<add>// promiseResolve() is called only for promise resources, when the
<add>// resolve() function passed to the Promise constructor is invoked
<ide> // (either directly or through other means of resolving a promise).
<ide> function promiseResolve(asyncId) { }
<ide> ``` | 1 |
Python | Python | log traceback in trigger excs | 4ad21f5f7c2d416cf813a860564bc2bf3e161d46 | <ide><path>airflow/__init__.py
<ide> isort:skip_file
<ide> """
<ide>
<add>
<ide> # flake8: noqa: F401
<ide>
<ide> import sys
<ide><path>airflow/jobs/triggerer_job.py
<ide> def handle_failed_triggers(self):
<ide> """
<ide> while self.runner.failed_triggers:
<ide> # Tell the model to fail this trigger's deps
<del> trigger_id = self.runner.failed_triggers.popleft()
<del> Trigger.submit_failure(trigger_id=trigger_id)
<add> trigger_id, saved_exc = self.runner.failed_triggers.popleft()
<add> Trigger.submit_failure(trigger_id=trigger_id, exc=saved_exc)
<ide> # Emit stat event
<ide> Stats.incr('triggers.failed')
<ide>
<ide> class TriggerRunner(threading.Thread, LoggingMixin):
<ide> events: Deque[Tuple[int, TriggerEvent]]
<ide>
<ide> # Outbound queue of failed triggers
<del> failed_triggers: Deque[int]
<add> failed_triggers: Deque[Tuple[int, BaseException]]
<ide>
<ide> # Should-we-stop flag
<ide> stop: bool = False
<ide> async def cleanup_finished_triggers(self):
<ide> for trigger_id, details in list(self.triggers.items()):
<ide> if details["task"].done():
<ide> # Check to see if it exited for good reasons
<add> saved_exc = None
<ide> try:
<ide> result = details["task"].result()
<ide> except (asyncio.CancelledError, SystemExit, KeyboardInterrupt):
<ide> async def cleanup_finished_triggers(self):
<ide> continue
<ide> except BaseException as e:
<ide> # This is potentially bad, so log it.
<del> self.log.error("Trigger %s exited with error %s", details["name"], e)
<add> self.log.exception("Trigger %s exited with error %s", details["name"], e)
<add> saved_exc = e
<ide> else:
<ide> # See if they foolishly returned a TriggerEvent
<ide> if isinstance(result, TriggerEvent):
<ide> async def cleanup_finished_triggers(self):
<ide> "Trigger %s exited without sending an event. Dependent tasks will be failed.",
<ide> details["name"],
<ide> )
<del> self.failed_triggers.append(trigger_id)
<add> self.failed_triggers.append((trigger_id, saved_exc))
<ide> del self.triggers[trigger_id]
<ide> await asyncio.sleep(0)
<ide>
<ide> def update_triggers(self, requested_trigger_ids: Set[int]):
<ide> running_trigger_ids.union(x[0] for x in self.events)
<ide> .union(self.to_cancel)
<ide> .union(x[0] for x in self.to_create)
<del> .union(self.failed_triggers)
<add> .union(trigger[0] for trigger in self.failed_triggers)
<ide> )
<ide> # Work out the two difference sets
<ide> new_trigger_ids = requested_trigger_ids - known_trigger_ids
<ide> def update_triggers(self, requested_trigger_ids: Set[int]):
<ide> # Resolve trigger record into an actual class instance
<ide> try:
<ide> trigger_class = self.get_trigger_by_classpath(new_triggers[new_id].classpath)
<del> except BaseException:
<add> except BaseException as e:
<ide> # Either the trigger code or the path to it is bad. Fail the trigger.
<del> self.failed_triggers.append(new_id)
<add> self.failed_triggers.append((new_id, e))
<ide> continue
<ide> self.to_create.append((new_id, trigger_class(**new_triggers[new_id].kwargs)))
<ide> # Enqueue orphaned triggers for cancellation
<ide><path>airflow/models/taskinstance.py
<ide> def _execute_task(self, context, task_copy):
<ide> # this task was scheduled specifically to fail.
<ide> if self.next_method == "__fail__":
<ide> next_kwargs = self.next_kwargs or {}
<add> traceback = self.next_kwargs.get("traceback")
<add> if traceback is not None:
<add> self.log.error("Trigger failed:\n%s", "\n".join(traceback))
<ide> raise TaskDeferralError(next_kwargs.get("error", "Unknown"))
<ide> # Grab the callable off the Operator/Task and add in any kwargs
<ide> execute_callable = getattr(task_copy, self.next_method)
<ide><path>airflow/models/trigger.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> import datetime
<add>from traceback import format_exception
<ide> from typing import Any, Dict, Iterable, Optional
<ide>
<ide> from sqlalchemy import Column, Integer, String, func, or_
<ide> def submit_event(cls, trigger_id, event, session=None):
<ide>
<ide> @classmethod
<ide> @provide_session
<del> def submit_failure(cls, trigger_id, session=None):
<add> def submit_failure(cls, trigger_id, exc=None, session=None):
<ide> """
<ide> Called when a trigger has failed unexpectedly, and we need to mark
<ide> everything that depended on it as failed. Notably, we have to actually
<ide> def submit_failure(cls, trigger_id, session=None):
<ide> TaskInstance.trigger_id == trigger_id, TaskInstance.state == State.DEFERRED
<ide> ):
<ide> # Add the error and set the next_method to the fail state
<add> traceback = format_exception(type(exc), exc, exc.__traceback__) if exc else None
<ide> task_instance.next_method = "__fail__"
<del> task_instance.next_kwargs = {"error": "Trigger failure"}
<add> task_instance.next_kwargs = {"error": "Trigger failure", "traceback": traceback}
<ide> # Remove ourselves as its trigger
<ide> task_instance.trigger_id = None
<ide> # Finally, mark it as scheduled so it gets re-queued
<ide><path>tests/jobs/test_triggerer_job.py
<ide> def test_trigger_failing(session):
<ide> # Wait for up to 3 seconds for it to fire and appear in the event queue
<ide> for _ in range(30):
<ide> if job.runner.failed_triggers:
<del> assert list(job.runner.failed_triggers) == [1]
<add> assert len(job.runner.failed_triggers) == 1
<add> trigger_id, exc = list(job.runner.failed_triggers)[0]
<add> assert trigger_id == 1
<add> assert isinstance(exc, ValueError)
<add> assert exc.args[0] == "Deliberate trigger failure"
<ide> break
<ide> time.sleep(0.1)
<ide> else:
<ide> def test_invalid_trigger(session, dag_maker):
<ide> job.load_triggers()
<ide>
<ide> # Make sure it turned up in the failed queue
<del> assert list(job.runner.failed_triggers) == [1]
<add> assert len(job.runner.failed_triggers) == 1
<ide>
<ide> # Run the failed trigger handler
<ide> job.handle_failed_triggers()
<ide> def test_invalid_trigger(session, dag_maker):
<ide> task_instance.refresh_from_db()
<ide> assert task_instance.state == TaskInstanceState.SCHEDULED
<ide> assert task_instance.next_method == "__fail__"
<del> assert task_instance.next_kwargs == {'error': 'Trigger failure'}
<add> assert task_instance.next_kwargs['error'] == 'Trigger failure'
<add> assert task_instance.next_kwargs['traceback'][-1] == "ModuleNotFoundError: No module named 'fake'\n" | 5 |
Text | Text | use a details tag for completed initiatves | 284dec77bdfbcae24022b4ed06d2115b81ebf8a4 | <ide><path>doc/guides/strategic-initiatives.md
<ide> are active and have the support needed.
<ide> | Startup performance | [Joyee Cheung][joyeecheung] | <https://github.com/nodejs/node/issues/17058> <https://github.com/nodejs/node/issues/21563> |
<ide> | V8 Currency | [Michaël Zasso][targos] | |
<ide>
<del>## Completed
<add><details>
<add><summary>List of completed initiatives</summary>
<add>
<add>## Completed initiatives
<ide>
<ide> | Initiative | Champion | Links |
<ide> |--------------------|----------------------------|--------------------------------------------------|
<ide> are active and have the support needed.
<ide> | VM module fix | Franziska Hinkelmann | <https://github.com/nodejs/node/issues/6283> |
<ide> | Workers | Anna Henningsen | <https://github.com/nodejs/worker> |
<ide>
<add></details>
<add>
<ide> [jasnell]: https://github.com/jasnell
<ide> [joyeecheung]: https://github.com/joyeecheung
<ide> [mcollina]: https://github.com/mcollina | 1 |
PHP | PHP | apply fixes from styleci | 81a0b9f667a288ce6bf2472c9783407367e15ca6 | <ide><path>src/Illuminate/View/Compilers/Concerns/CompilesConditionals.php
<ide> protected function compileEndAuth()
<ide> {
<ide> return '<?php endif; ?>';
<ide> }
<del>
<add>
<ide> /**
<ide> * Compile the if-guest statements into valid PHP.
<ide> * | 1 |
Text | Text | fix todostore syntax | aaeb107e008bb7b51c9746f78c95641c6725d3d2 | <ide><path>docs/docs/flux-todo-list.md
<ide> var TodoStore = merge(EventEmitter.prototype, {
<ide> */
<ide> removeChangeListener: function(callback) {
<ide> this.removeListener(CHANGE_EVENT, callback);
<del> }
<add> },
<ide>
<ide> dispatcherIndex: AppDispatcher.register(function(payload) {
<ide> var action = payload.action; | 1 |
Ruby | Ruby | add support for custom csrf strategies | f40405c138af28ef6f571d77312373382e0dc744 | <ide><path>actionpack/lib/action_controller/metal/request_forgery_protection.rb
<ide> module ClassMethods
<ide> # If you need to add verification to the beginning of the callback chain, use <tt>prepend: true</tt>.
<ide> # * <tt>:with</tt> - Set the method to handle unverified request.
<ide> #
<del> # Valid unverified request handling methods are:
<add> # Built-in unverified request handling methods are:
<ide> # * <tt>:exception</tt> - Raises ActionController::InvalidAuthenticityToken exception.
<ide> # * <tt>:reset_session</tt> - Resets the session.
<ide> # * <tt>:null_session</tt> - Provides an empty session during request but doesn't reset it completely. Used as default if <tt>:with</tt> option is not specified.
<add> #
<add> # You can also implement custom strategy classes for unverified request handling:
<add> #
<add> # class CustomStrategy
<add> # def initialize(controller)
<add> # @controller = controller
<add> # end
<add> #
<add> # def handle_unverified_request
<add> # # Custom behaviour for unverfied request
<add> # end
<add> # end
<add> #
<add> # class ApplicationController < ActionController:x:Base
<add> # protect_from_forgery with: CustomStrategy
<add> # end
<ide> def protect_from_forgery(options = {})
<ide> options = options.reverse_merge(prepend: false)
<ide>
<ide> def skip_forgery_protection(options = {})
<ide>
<ide> private
<ide> def protection_method_class(name)
<del> ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
<del> rescue NameError
<del> raise ArgumentError, "Invalid request forgery protection method, use :null_session, :exception, or :reset_session"
<add> return name if name.is_a?(Class)
<add>
<add> case name
<add> when :null_session
<add> ProtectionMethods::NullSession
<add> when :reset_session
<add> ProtectionMethods::ResetSession
<add> when :exception
<add> ProtectionMethods::Exception
<add> else
<add> raise ArgumentError, "Invalid request forgery protection method, use :null_session, :exception, :reset_session, or a custom forgery protection class."
<add> end
<ide> end
<ide> end
<ide>
<ide><path>actionpack/test/controller/request_forgery_protection_test.rb
<ide> def try_to_reset_session
<ide> end
<ide> end
<ide>
<add>class RequestForgeryProtectionControllerUsingCustomStrategy < ActionController::Base
<add> include RequestForgeryProtectionActions
<add>
<add> class FakeException < Exception; end
<add>
<add> class CustomStrategy
<add> def initialize(controller)
<add> @controller = controller
<add> end
<add>
<add> def handle_unverified_request
<add> raise FakeException, "Raised a fake exception."
<add> end
<add> end
<add>
<add> protect_from_forgery only: %w(index meta same_origin_js negotiate_same_origin), with: CustomStrategy
<add>end
<add>
<ide> class PrependProtectForgeryBaseController < ActionController::Base
<ide> before_action :custom_action
<ide> attr_accessor :called_callbacks
<ide> def setup
<ide>
<ide> class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase
<ide> include RequestForgeryProtectionTests
<add>
<ide> def assert_blocked(&block)
<ide> assert_raises(ActionController::InvalidAuthenticityToken, &block)
<ide> end
<ide> def test_raised_exception_message_explains_why_it_occurred
<ide> end
<ide> end
<ide>
<add>class RequestForgeryProtectionControllerUsingCustomStrategyTest < ActionController::TestCase
<add> include RequestForgeryProtectionTests
<add>
<add> def assert_blocked(&block)
<add> assert_raises(RequestForgeryProtectionControllerUsingCustomStrategy::FakeException, &block)
<add> end
<add>end
<add>
<ide> class PrependProtectForgeryBaseControllerTest < ActionController::TestCase
<ide> PrependTrueController = Class.new(PrependProtectForgeryBaseController) do
<ide> protect_from_forgery prepend: true | 2 |
Javascript | Javascript | add optional allornothing param | c2362e3f45e732a9defdb0ea59ce4ec5236fcd3a | <ide><path>src/ng/interpolate.js
<ide> function $InterpolateProvider() {
<ide> * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
<ide> * ```
<ide> *
<add> * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
<add> * `true`, the interpolation function will return `undefined` unless all embedded expressions
<add> * evaluate to a value other than `undefined`.
<add> *
<add> * ```js
<add> * var $interpolate = ...; // injected
<add> * var context = {greeting: 'Hey', name: undefined };
<add> *
<add> * // default "forgiving" mode
<add> * var exp = $interpolate('{{greeting}} {{name}}!');
<add> * expect(exp(context)).toEqual('Hello !');
<add> *
<add> * // "allOrNothing" mode
<add> * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
<add> * expect(exp(context, true)).toBeUndefined();
<add> * context.name = 'Angular';
<add> * expect(exp(context, true)).toEqual('Hello Angular!');
<add> * ```
<add> *
<add> * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
<ide> *
<ide> * @param {string} text The text with markup to interpolate.
<ide> * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
<ide> function $InterpolateProvider() {
<ide> * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
<ide> * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
<ide> * provides Strict Contextual Escaping for details.
<add> * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
<add> * unless all embedded expressions evaluate to a value other than `undefined`.
<ide> * @returns {function(context)} an interpolation function which is used to compute the
<ide> * interpolated string. The function has these parameters:
<ide> *
<ide> * - `context`: evaluation context for all expressions embedded in the interpolated text
<ide> */
<del> function $interpolate(text, mustHaveExpression, trustedContext) {
<add> function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
<add> allOrNothing = !!allOrNothing;
<ide> var startIndex,
<ide> endIndex,
<ide> index = 0,
<ide> function $InterpolateProvider() {
<ide> return concat.join('');
<ide> };
<ide>
<del> var stringify = function (value) {
<add> var getValue = function (value) {
<ide> if (trustedContext) {
<ide> value = $sce.getTrusted(trustedContext, value);
<ide> } else {
<ide> value = $sce.valueOf(value);
<ide> }
<ide>
<del> if (value === null || isUndefined(value)) {
<add> return value;
<add> };
<add>
<add> var stringify = function (value) {
<add> if (isUndefined(value) || value === null) {
<ide> value = '';
<del> } else if (typeof value != 'string') {
<add> }
<add> if (typeof value != 'string') {
<ide> value = toJson(value);
<ide> }
<ide>
<ide> function $InterpolateProvider() {
<ide>
<ide> try {
<ide> for (; i < ii; i++) {
<del> val = stringify(parseFns[i](context));
<add> val = getValue(parseFns[i](context));
<add> if (allOrNothing && isUndefined(val)) {
<add> return;
<add> }
<add> val = stringify(val);
<ide> if (val !== lastValues[i]) {
<ide> inputsChanged = true;
<ide> }
<ide><path>test/ng/interpolateSpec.js
<ide> describe('$interpolate', function() {
<ide> expect($interpolate('some text', true)).toBeUndefined();
<ide> }));
<ide>
<add> it('should return undefined when there are bindings and strict is set to true',
<add> inject(function($interpolate) {
<add> expect($interpolate('test {{foo}}', false, null, true)({})).toBeUndefined();
<add> }));
<add>
<ide> it('should suppress falsy objects', inject(function($interpolate) {
<ide> expect($interpolate('{{undefined}}')({})).toEqual('');
<ide> expect($interpolate('{{null}}')({})).toEqual(''); | 2 |
Javascript | Javascript | replace fixturesdir with common.fixtures | 1d7fbabaefb08c108b42f5d4a9583a77865129a4 | <ide><path>test/parallel/test-tls-honorcipherorder.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>const fixtures = require('../common/fixtures');
<ide> if (!common.hasCrypto)
<ide> common.skip('missing crypto');
<ide>
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<del>const fs = require('fs');
<ide>
<ide> let nconns = 0;
<ide>
<ide> process.on('exit', function() {
<ide> function test(honorCipherOrder, clientCipher, expectedCipher, cb) {
<ide> const soptions = {
<ide> secureProtocol: SSL_Method,
<del> key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`),
<del> cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`),
<add> key: fixtures.readKey('agent2-key.pem'),
<add> cert: fixtures.readKey('agent2-cert.pem'),
<ide> ciphers: 'AES256-SHA256:AES128-GCM-SHA256:AES128-SHA256:' +
<ide> 'ECDHE-RSA-AES128-GCM-SHA256',
<ide> honorCipherOrder: !!honorCipherOrder | 1 |
PHP | PHP | update doc block | 2f51de56f1a4d207c3bd82984a96882f9da606fe | <ide><path>src/Illuminate/Database/Connection.php
<ide> public function selectOne($query, $bindings = [], $useReadPdo = true)
<ide> * @param bool $useReadPdo
<ide> * @return mixed
<ide> *
<del> * @throws MultipleColumnsSelectedException
<add> * @throws \Illuminate\Database\MultipleColumnsSelectedException
<ide> */
<ide> public function scalar($query, $bindings = [], $useReadPdo = true)
<ide> { | 1 |
PHP | PHP | add index => viewany to resourceabilitymap | c9f957a8b07011b2a9d88cee24f5b0e4ed905e15 | <ide><path>src/Illuminate/Foundation/Auth/Access/AuthorizesRequests.php
<ide> public function authorizeResource($model, $parameter = null, array $options = []
<ide> protected function resourceAbilityMap()
<ide> {
<ide> return [
<add> 'index' => 'viewAny',
<ide> 'show' => 'view',
<ide> 'create' => 'create',
<ide> 'store' => 'create', | 1 |
Python | Python | fix usage of asciiart | 0b78001f8419a2197fcf0cf8293d5b419e6e701e | <ide><path>airflow/jobs.py
<ide> from airflow.utils.db import provide_session, pessimistic_connection_handling
<ide> from airflow.utils.email import send_email
<ide> from airflow.utils.logging import LoggingMixin
<del>
<add>from airflow.utils import asciiart
<ide>
<ide> Base = models.Base
<ide> ID_LEN = models.ID_LEN
<ide> def manage_slas(self, dag, session=None):
<ide> Here's a list of tasks thas missed their SLAs:
<ide> <pre><code>{task_list}\n<code></pre>
<ide> Blocking tasks:
<del> <pre><code>{blocking_task_list}\n{asciiart.bug}<code></pre>
<del> """.format(**locals())
<add> <pre><code>{blocking_task_list}\n{bug}<code></pre>
<add> """.format(bug=asciiart.bug, **locals())
<ide> emails = []
<ide> for t in dag.tasks:
<ide> if t.email: | 1 |
Text | Text | fix broken link | f7f1d71e0ed5f3d9ae89b6533d50d853de2e65f3 | <ide><path>docs/NativeModulesIOS.md
<ide> title: Native Modules (iOS)
<ide> layout: docs
<ide> category: Guides
<ide> permalink: docs/nativemodulesios.html
<del>next: libraries
<add>next: linking-libraries
<ide> ---
<ide>
<ide> Sometimes an app needs access to platform API, and React Native doesn't have a corresponding wrapper yet. Maybe you want to reuse some existing Objective-C or C++ code without having to reimplement it in JavaScript. Or write some high performance, multi-threaded code such as image processing, network stack, database or rendering. | 1 |
Python | Python | replace validation_fn and fn_alt with allow_zero | d8c81998185b67e409fd0d31a07bbe9d1d61122f | <ide><path>keras/layers/convolutional.py
<ide> def __init__(self,
<ide> self.kernel_size = conv_utils.normalize_tuple(
<ide> kernel_size, rank, 'kernel_size')
<ide> self.strides = conv_utils.normalize_tuple(
<del> strides, rank, 'strides', lambda x: x >= 0, '>=0')
<add> strides, rank, 'strides', allow_zero=True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.dilation_rate = conv_utils.normalize_tuple(
<ide> def __init__(self,
<ide> self.output_padding = output_padding
<ide> if self.output_padding is not None:
<ide> self.output_padding = conv_utils.normalize_tuple(
<del> self.output_padding, 1, 'output_padding', lambda x: x >= 0, '>=0')
<add> self.output_padding, 1, 'output_padding', allow_zero=True)
<ide> for stride, out_pad in zip(self.strides, self.output_padding):
<ide> if out_pad >= stride:
<ide> raise ValueError('Strides must be greater than output padding. '
<ide> def __init__(self,
<ide> self.output_padding = output_padding
<ide> if self.output_padding is not None:
<ide> self.output_padding = conv_utils.normalize_tuple(
<del> self.output_padding, 2, 'output_padding', lambda x: x >= 0, '>=0')
<add> self.output_padding, 2, 'output_padding', allow_zero=True)
<ide> for stride, out_pad in zip(self.strides, self.output_padding):
<ide> if out_pad >= stride:
<ide> raise ValueError('Strides must be greater than output padding. '
<ide> def __init__(self,
<ide> self.output_padding = output_padding
<ide> if self.output_padding is not None:
<ide> self.output_padding = conv_utils.normalize_tuple(
<del> self.output_padding, 3, 'output_padding', lambda x: x >= 0, '>=0')
<add> self.output_padding, 3, 'output_padding', allow_zero=True)
<ide> for stride, out_pad in zip(self.strides, self.output_padding):
<ide> if out_pad >= stride:
<ide> raise ValueError('Strides must be greater than output padding. '
<ide> class ZeroPadding1D(Layer):
<ide>
<ide> def __init__(self, padding=1, **kwargs):
<ide> super(ZeroPadding1D, self).__init__(**kwargs)
<del> self.padding = conv_utils.normalize_tuple(padding, 2, 'padding', lambda x: x >= 0, '>=0')
<add> self.padding = conv_utils.normalize_tuple(padding, 2, 'padding', allow_zero=True)
<ide> self.input_spec = InputSpec(ndim=3)
<ide>
<ide> def compute_output_shape(self, input_shape):
<ide> def __init__(self, padding=(1, 1), data_format=None, **kwargs):
<ide> raise ValueError('`padding` should have two elements. '
<ide> f'Received: {padding}.')
<ide> height_padding = conv_utils.normalize_tuple(padding[0], 2,
<del> '1st entry of padding', lambda x: x >= 0, '>=0')
<add> '1st entry of padding', allow_zero=True)
<ide> width_padding = conv_utils.normalize_tuple(padding[1], 2,
<del> '2nd entry of padding', lambda x: x >= 0, '>=0')
<add> '2nd entry of padding', allow_zero=True)
<ide> self.padding = (height_padding, width_padding)
<ide> else:
<ide> raise ValueError('`padding` should be either an int, '
<ide> def __init__(self, padding=(1, 1, 1), data_format=None, **kwargs):
<ide> f'Received: {padding}.')
<ide> dim1_padding = conv_utils.normalize_tuple(padding[0], 2,
<ide> '1st entry of padding',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> dim2_padding = conv_utils.normalize_tuple(padding[1], 2,
<ide> '2nd entry of padding',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> dim3_padding = conv_utils.normalize_tuple(padding[2], 2,
<ide> '3rd entry of padding',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> self.padding = (dim1_padding, dim2_padding, dim3_padding)
<ide> else:
<ide> raise ValueError(
<ide> class Cropping1D(Layer):
<ide>
<ide> def __init__(self, cropping=(1, 1), **kwargs):
<ide> super(Cropping1D, self).__init__(**kwargs)
<del> self.cropping = conv_utils.normalize_tuple(
<del> cropping, 2, 'cropping', lambda x: x >= 0, '>=0')
<add> self.cropping = conv_utils.normalize_tuple(cropping, 2, 'cropping',
<add> allow_zero=True)
<ide> self.input_spec = InputSpec(ndim=3)
<ide>
<ide> def compute_output_shape(self, input_shape):
<ide> def __init__(self, cropping=((0, 0), (0, 0)), data_format=None, **kwargs):
<ide> f'Received: {cropping}.')
<ide> height_cropping = conv_utils.normalize_tuple(cropping[0], 2,
<ide> '1st entry of cropping',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> width_cropping = conv_utils.normalize_tuple(cropping[1], 2,
<ide> '2nd entry of cropping',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> self.cropping = (height_cropping, width_cropping)
<ide> else:
<ide> raise ValueError('`cropping` should be either an int, '
<ide> def __init__(self,
<ide> f'Received: {cropping}.')
<ide> dim1_cropping = conv_utils.normalize_tuple(cropping[0], 2,
<ide> '1st entry of cropping',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> dim2_cropping = conv_utils.normalize_tuple(cropping[1], 2,
<ide> '2nd entry of cropping',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> dim3_cropping = conv_utils.normalize_tuple(cropping[2], 2,
<ide> '3rd entry of cropping',
<del> lambda x: x >= 0, '>=0')
<add> allow_zero=True)
<ide> self.cropping = (dim1_cropping, dim2_cropping, dim3_cropping)
<ide> else:
<ide> raise ValueError(
<ide><path>keras/layers/convolutional_recurrent.py
<ide> def __init__(self,
<ide> self.kernel_size = conv_utils.normalize_tuple(
<ide> kernel_size, self.rank, 'kernel_size')
<ide> self.strides = conv_utils.normalize_tuple(
<del> strides, self.rank, 'strides', lambda x: x >= 0, '>=0')
<add> strides, self.rank, 'strides', allow_zero=True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.dilation_rate = conv_utils.normalize_tuple(
<ide> def input_conv(self, x, w, b=None, padding='valid'):
<ide> return conv_out
<ide>
<ide> def recurrent_conv(self, x, w):
<del> strides = conv_utils.normalize_tuple(1, self.rank, 'strides', lambda s: s >= 0, '>=0')
<add> strides = conv_utils.normalize_tuple(1, self.rank, 'strides', True)
<ide> conv_out = self._conv_func(
<ide> x, w, strides=strides, padding='same', data_format=self.data_format)
<ide> return conv_out
<ide><path>keras/layers/local.py
<ide> def __init__(self,
<ide> super(LocallyConnected1D, self).__init__(**kwargs)
<ide> self.filters = filters
<ide> self.kernel_size = conv_utils.normalize_tuple(kernel_size, 1, 'kernel_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', lambda x: x >= 0, '>=0')
<add> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> if self.padding != 'valid' and implementation == 1:
<ide> raise ValueError('Invalid border mode for LocallyConnected1D '
<ide> def __init__(self,
<ide> super(LocallyConnected2D, self).__init__(**kwargs)
<ide> self.filters = filters
<ide> self.kernel_size = conv_utils.normalize_tuple(kernel_size, 2, 'kernel_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', lambda x: x >= 0, '>=0')
<add> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> if self.padding != 'valid' and implementation == 1:
<ide> raise ValueError('Invalid border mode for LocallyConnected2D '
<ide><path>keras/layers/pooling.py
<ide> def __init__(self, pool_function, pool_size, strides,
<ide> strides = pool_size
<ide> self.pool_function = pool_function
<ide> self.pool_size = conv_utils.normalize_tuple(pool_size, 1, 'pool_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', lambda x: x >= 0, '>=0')
<add> self.strides = conv_utils.normalize_tuple(strides, 1, 'strides', True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.input_spec = InputSpec(ndim=3)
<ide> def __init__(self, pool_function, pool_size, strides,
<ide> strides = pool_size
<ide> self.pool_function = pool_function
<ide> self.pool_size = conv_utils.normalize_tuple(pool_size, 2, 'pool_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', lambda x: x >= 0, '>=0')
<add> self.strides = conv_utils.normalize_tuple(strides, 2, 'strides', True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.input_spec = InputSpec(ndim=4)
<ide> def __init__(self, pool_function, pool_size, strides,
<ide> strides = pool_size
<ide> self.pool_function = pool_function
<ide> self.pool_size = conv_utils.normalize_tuple(pool_size, 3, 'pool_size')
<del> self.strides = conv_utils.normalize_tuple(strides, 3, 'strides', lambda x: x >= 0, '>=0')
<add> self.strides = conv_utils.normalize_tuple(strides, 3, 'strides', allow_zero=True)
<ide> self.padding = conv_utils.normalize_padding(padding)
<ide> self.data_format = conv_utils.normalize_data_format(data_format)
<ide> self.input_spec = InputSpec(ndim=5)
<ide><path>keras/utils/conv_utils.py
<ide> def convert_data_format(data_format, ndim):
<ide> 'Expected values are ["channels_first", "channels_last"]')
<ide>
<ide>
<del>def normalize_tuple(value, n, name, validation_fn=lambda x: x > 0, fn_alt='>0'):
<add>def normalize_tuple(value, n, name, allow_zero=False):
<ide> """Transforms a single integer or iterable of integers into an integer tuple.
<ide>
<ide> Args:
<ide> def normalize_tuple(value, n, name, validation_fn=lambda x: x > 0, fn_alt='>0'):
<ide> n: The size of the tuple to be returned.
<ide> name: The name of the argument being validated, e.g. "strides" or
<ide> "kernel_size". This is only used to format error messages.
<del> validation_fn: the function used to filter out unqualified values.
<del> fn_alt: alternative text for validation_fn.
<add> allow_zero: Whether the function will accept zero values.
<ide> Returns:
<ide> A tuple of n integers.
<ide>
<ide> def normalize_tuple(value, n, name, validation_fn=lambda x: x > 0, fn_alt='>0'):
<ide> f'type {type(single_value)}')
<ide> raise ValueError(error_msg)
<ide>
<del> unqualified_values = [v for v in value_tuple if validation_fn and (not validation_fn(v))]
<add> if allow_zero:
<add> qualified_values = list(filter(lambda x: x >= 0, value_tuple))
<add> req_msg = '>=0'
<add> else:
<add> qualified_values = list(filter(lambda x: x > 0, value_tuple))
<add> req_msg = '>0'
<ide>
<del> if len(unqualified_values) > 0:
<del> error_msg += (f' including {unqualified_values}'
<del> f' that does not satisfy the requirement {fn_alt}.')
<add> if len(qualified_values) < len(value_tuple):
<add> error_msg += (f' including {qualified_values}'
<add> f' that does not satisfy the requirement {req_msg}.')
<ide> raise ValueError(error_msg)
<ide>
<ide> return value_tuple
<ide><path>keras/utils/conv_utils_test.py
<ide> def test_convert_data_format(self):
<ide> conv_utils.convert_data_format('invalid', 2)
<ide>
<ide> def test_normalize_tuple(self):
<del> self.assertEqual((2, 2, 2),
<del> conv_utils.normalize_tuple(2,
<del> n=3, name='strides', validation_fn=lambda x: x >= 0, fn_alt='>=0'))
<del> self.assertEqual((2, 1, 2),
<del> conv_utils.normalize_tuple((2, 1, 2),
<del> n=3, name='strides', validation_fn=lambda x: x >= 0, fn_alt='>=0'))
<del> self.assertEqual((1, 2, 3,),
<del> conv_utils.normalize_tuple((1, 2, 3), n=3, name='pool_size'))
<del> self.assertEqual((3, 3, 3),
<del> conv_utils.normalize_tuple(3, n=3, name='pool_size'))
<del> self.assertEqual((3, -1, 3),
<del> conv_utils.normalize_tuple((3, -1, 3),
<del> n=3, name='negative_size', validation_fn=None, fn_alt=None))
<add> self.assertEqual((2, 2, 2), conv_utils.normalize_tuple(
<add> 2, n=3, name='strides', allow_zero=True))
<add> self.assertEqual((2, 1, 2), conv_utils.normalize_tuple(
<add> (2, 1, 2), n=3, name='strides', allow_zero=True))
<add> self.assertEqual((1, 2, 3,), conv_utils.normalize_tuple(
<add> (1, 2, 3), n=3, name='pool_size'))
<add> self.assertEqual((3, 3, 3), conv_utils.normalize_tuple(
<add> 3, n=3, name='pool_size'))
<add> self.assertEqual((3, -1, 3), conv_utils.normalize_tuple(
<add> (3, -1, 3), n=3, name='negative_size', allow_zero=True))
<ide>
<ide> with self.assertRaises(ValueError) as ctx:
<del> conv_utils.normalize_tuple((2, 1), n=3, name='strides', validation_fn=lambda x: x >= 0, fn_alt='>=0')
<add> conv_utils.normalize_tuple((2, 1), n=3, name='strides', allow_zero=True)
<ide> self.assertIn('The `strides` argument must be a tuple of 3', str(ctx.exception))
<ide>
<ide> with self.assertRaises(ValueError) as ctx:
<ide> conv_utils.normalize_tuple(None, n=3, name='kernel_size')
<ide> self.assertIn('The `kernel_size` argument must be a tuple of 3', str(ctx.exception))
<ide>
<ide> with self.assertRaises(ValueError) as ctx:
<del> conv_utils.normalize_tuple(-4, n=3, name='strides', validation_fn=lambda x: x >= 0, fn_alt='>=0')
<add> conv_utils.normalize_tuple(-4, n=3, name='strides', allow_zero=True)
<ide> self.assertIn('that does not satisfy the requirement >=0', str(ctx.exception))
<ide>
<ide> with self.assertRaises(ValueError) as ctx: | 6 |
Text | Text | replace dead link in v8 module | 7bc666be1752fbb18fdfb67c46dc4995f6eb5f0a | <ide><path>doc/api/v8.md
<ide> A subclass of [`Deserializer`][] corresponding to the format written by
<ide> [V8]: https://developers.google.com/v8/
<ide> [`vm.Script`]: vm.html#vm_new_vm_script_code_options
<ide> [here]: https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md
<del>[`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-5.0/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4
<add>[`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-8.0/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4 | 1 |
Text | Text | fix performanceentry.flags style format | bcb196456079326e073567d0b00bb6998b9334b0 | <ide><path>doc/api/perf_hooks.md
<ide> The type of the performance entry. It may be one of:
<ide> * `'http2'` (Node.js only)
<ide> * `'http'` (Node.js only)
<ide>
<del>### performanceEntry.flags
<add>### `performanceEntry.flags`
<ide> <!-- YAML
<ide> added:
<ide> - v13.9.0 | 1 |
Javascript | Javascript | remove unused parameters | e62d5964def23a619048237490f27ac781fb09ab | <ide><path>lib/buffer.js
<ide> Buffer.prototype.readUInt16BE = function(offset, noAssert) {
<ide> };
<ide>
<ide>
<del>function readUInt32(buffer, offset, isBigEndian, noAssert) {
<add>function readUInt32(buffer, offset, isBigEndian) {
<ide> var val = 0;
<ide> if (isBigEndian) {
<ide> val = buffer[offset + 1] << 16;
<ide> Buffer.prototype.readUInt32LE = function(offset, noAssert) {
<ide> offset = ~~offset;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<del> return readUInt32(this, offset, false, noAssert);
<add> return readUInt32(this, offset, false);
<ide> };
<ide>
<ide>
<ide> Buffer.prototype.readUInt32BE = function(offset, noAssert) {
<ide> offset = ~~offset;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<del> return readUInt32(this, offset, true, noAssert);
<add> return readUInt32(this, offset, true);
<ide> };
<ide>
<ide> | 1 |
Text | Text | add richard lau to tsc list in readme.md | d274347e380e525988764722e7eff27ab0457aa5 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Mary Marchini** \<oss@mmarchini.me> (she/her)
<ide> * [MylesBorins](https://github.com/MylesBorins) -
<ide> **Myles Borins** \<myles.borins@gmail.com> (he/him)
<add>* [richardlau](https://github.com/richardlau) -
<add> **Richard Lau** \<rlau@redhat.com>
<ide> * [ronag](https://github.com/ronag) -
<ide> **Robert Nagy** \<ronagy@icloud.com>
<ide> * [targos](https://github.com/targos) - | 1 |
Python | Python | add support for request.auth | b7062c5b01fbcd1fecb9ad2cd9a73eba77bd7632 | <ide><path>djangorestframework/authentication.py
<ide> def authenticate(self, request):
<ide> return None
<ide>
<ide> return self.authenticate_credentials(userid, password)
<del> return None
<ide>
<ide> def authenticate_credentials(self, userid, password):
<ide> """
<ide> def authenticate_credentials(self, userid, password):
<ide> """
<ide> user = authenticate(username=userid, password=password)
<ide> if user is not None and user.is_active:
<del> return user
<add> return (user, None)
<ide>
<ide>
<ide> class SessionAuthentication(BaseAuthentication):
<ide> def authenticate(self, request):
<ide> resp = CsrfViewMiddleware().process_view(request, None, (), {})
<ide>
<ide> if resp is None: # csrf passed
<del> return user
<del> return None
<add> return (user, None)
<ide>
<ide>
<ide> # TODO: TokenAuthentication, DigestAuthentication, OAuthAuthentication
<ide><path>djangorestframework/request.py
<ide>
<ide> from django.contrib.auth.models import AnonymousUser
<ide>
<del>from djangorestframework.exceptions import UnsupportedMediaType
<add>from djangorestframework import exceptions
<ide> from djangorestframework.utils.mediatypes import is_form_media_type
<ide>
<ide>
<ide> def DATA(self):
<ide> """
<ide> Parses the request body and returns the data.
<ide>
<del> Similar to ``request.POST``, except that it handles arbitrary parsers,
<del> and also works on methods other than POST (eg PUT).
<add> Similar to usual behaviour of `request.POST`, except that it handles
<add> arbitrary parsers, and also works on methods other than POST (eg PUT).
<ide> """
<ide> if not _hasattr(self, '_data'):
<ide> self._load_data_and_files()
<ide> def DATA(self):
<ide> @property
<ide> def FILES(self):
<ide> """
<del> Parses the request body and returns the files.
<del> Similar to ``request.FILES``, except that it handles arbitrary parsers,
<del> and also works on methods other than POST (eg PUT).
<add> Parses the request body and returns any files uploaded in the request.
<add>
<add> Similar to usual behaviour of `request.FILES`, except that it handles
<add> arbitrary parsers, and also works on methods other than POST (eg PUT).
<ide> """
<ide> if not _hasattr(self, '_files'):
<ide> self._load_data_and_files()
<ide> def FILES(self):
<ide> @property
<ide> def user(self):
<ide> """
<del> Returns the :obj:`user` for the current request, authenticated
<del> with the set of :class:`authentication` instances applied to the :class:`Request`.
<add> Returns the user associated with the current request, as authenticated
<add> by the authentication classes provided to the request.
<ide> """
<ide> if not hasattr(self, '_user'):
<del> self._user = self._authenticate()
<add> self._user, self._auth = self._authenticate()
<ide> return self._user
<ide>
<add> @property
<add> def auth(self):
<add> """
<add> Returns any non-user authentication information associated with the
<add> request, such as an authentication token.
<add> """
<add> if not hasattr(self, '_auth'):
<add> self._user, self._auth = self._authenticate()
<add> return self._auth
<add>
<ide> def _load_data_and_files(self):
<ide> """
<ide> Parses the request content into self.DATA and self.FILES.
<ide> def _load_method_and_content_type(self):
<ide> self._method = self._request.method
<ide>
<ide> def _load_stream(self):
<add> """
<add> Return the content body of the request, as a stream.
<add> """
<ide> try:
<ide> content_length = int(self.META.get('CONTENT_LENGTH',
<ide> self.META.get('HTTP_CONTENT_LENGTH')))
<ide> def _parse(self):
<ide> except AttributeError:
<ide> return (parsed, None)
<ide>
<del> raise UnsupportedMediaType(self._content_type)
<add> raise exceptions.UnsupportedMediaType(self._content_type)
<ide>
<ide> def _authenticate(self):
<ide> """
<ide> Attempt to authenticate the request using each authentication instance in turn.
<del> Returns a ``User`` object, which may be ``AnonymousUser``.
<add> Returns a two-tuple of (user, authtoken).
<ide> """
<ide> for authentication in self.get_authentications():
<del> user = authentication.authenticate(self)
<del> if user:
<del> return user
<add> user_auth_tuple = authentication.authenticate(self)
<add> if not user_auth_tuple is None:
<add> return user_auth_tuple
<ide> return self._not_authenticated()
<ide>
<ide> def _not_authenticated(self):
<del> return AnonymousUser()
<add> return (AnonymousUser(), None)
<ide>
<ide> def __getattr__(self, name):
<ide> """ | 2 |
Python | Python | move import at the top of the file | 3a3b5e09f0a1bf311d9e3ca18cca411694debc27 | <ide><path>numpy/distutils/command/scons.py
<ide> from distutils.errors import DistutilsExecError, DistutilsSetupError
<ide>
<ide> from numpy.distutils.command.build_ext import build_ext as old_build_ext
<del>from numpy.distutils.ccompiler import CCompiler
<del>from numpy.distutils.fcompiler import FCompiler
<add>from numpy.distutils.ccompiler import CCompiler, new_compiler
<add>from numpy.distutils.fcompiler import FCompiler, new_fcompiler
<ide> from numpy.distutils.exec_command import find_executable
<ide> from numpy.distutils import log
<ide> from numpy.distutils.misc_util import is_bootstrapping, get_cmd
<ide> def finalize_options(self):
<ide> compiler_type = self.compiler
<ide> if compiler_type == 'msvc':
<ide> self._bypass_distutils_cc = True
<del> from numpy.distutils.ccompiler import new_compiler
<ide> try:
<ide> distutils_compiler = new_compiler(compiler=compiler_type,
<ide> verbose=self.verbose,
<ide> def finalize_options(self):
<ide> raise e
<ide> else:
<ide> self.scons_compiler = compiler_type
<add> except Exception, e:
<add> print type(e)
<ide>
<ide> # We do the same for the fortran compiler ...
<ide> fcompiler_type = self.fcompiler
<del> from numpy.distutils.fcompiler import new_fcompiler
<ide> self.fcompiler = new_fcompiler(compiler = fcompiler_type,
<ide> verbose = self.verbose,
<ide> dry_run = self.dry_run, | 1 |
Java | Java | add marble diagram for single.hide operator | d4c1da01b157262b326b21cd97a844fcdedc7c6e | <ide><path>src/main/java/io/reactivex/Single.java
<ide> public final <R> R as(@NonNull SingleConverter<T, ? extends R> converter) {
<ide> /**
<ide> * Hides the identity of the current Single, including the Disposable that is sent
<ide> * to the downstream via {@code onSubscribe()}.
<add> * <p>
<add> * <img width="640" height="458" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.hide.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code hide} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
PHP | PHP | fix columns parameter on paginate method | 94403f69515978bdf68a1280f706ee30c473d28b | <ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $p
<ide> {
<ide> $page = $page ?: Paginator::resolveCurrentPage($pageName);
<ide>
<del> $total = $this->getCountForPagination($columns);
<add> $total = $this->getCountForPagination();
<ide>
<ide> $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect();
<ide>
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testPaginate()
<ide>
<ide> $results = collect([['test' => 'foo'], ['test' => 'bar']]);
<ide>
<del> $builder->shouldReceive('getCountForPagination')->once()->with($columns)->andReturn(2);
<add> $builder->shouldReceive('getCountForPagination')->once()->andReturn(2);
<ide> $builder->shouldReceive('forPage')->once()->with($page, $perPage)->andReturnSelf();
<ide> $builder->shouldReceive('get')->once()->andReturn($results);
<ide>
<ide> public function testPaginateWithDefaultArguments()
<ide>
<ide> $results = collect([['test' => 'foo'], ['test' => 'bar']]);
<ide>
<del> $builder->shouldReceive('getCountForPagination')->once()->with($columns)->andReturn(2);
<add> $builder->shouldReceive('getCountForPagination')->once()->andReturn(2);
<ide> $builder->shouldReceive('forPage')->once()->with($page, $perPage)->andReturnSelf();
<ide> $builder->shouldReceive('get')->once()->andReturn($results);
<ide>
<ide> public function testPaginateWhenNoResults()
<ide>
<ide> $results = [];
<ide>
<del> $builder->shouldReceive('getCountForPagination')->once()->with($columns)->andReturn(0);
<add> $builder->shouldReceive('getCountForPagination')->once()->andReturn(0);
<ide> $builder->shouldNotReceive('forPage');
<ide> $builder->shouldNotReceive('get');
<ide>
<ide> public function testPaginateWhenNoResults()
<ide> ]), $result);
<ide> }
<ide>
<add> public function testPaginateWithSpecificColumns()
<add> {
<add> $perPage = 16;
<add> $columns = ['id', 'name'];
<add> $pageName = 'page-name';
<add> $page = 1;
<add> $builder = $this->getMockQueryBuilder();
<add> $path = 'http://foo.bar?page=3';
<add>
<add> $results = collect([['id' => 3, 'name' => 'Taylor'], ['id' => 5, 'name' => 'Mohamed']]);
<add>
<add> $builder->shouldReceive('getCountForPagination')->once()->andReturn(2);
<add> $builder->shouldReceive('forPage')->once()->with($page, $perPage)->andReturnSelf();
<add> $builder->shouldReceive('get')->once()->andReturn($results);
<add>
<add> Paginator::currentPathResolver(function () use ($path) {
<add> return $path;
<add> });
<add>
<add> $result = $builder->paginate($perPage, $columns, $pageName, $page);
<add>
<add> $this->assertEquals(new LengthAwarePaginator($results, 2, $perPage, $page, [
<add> 'path' => $path,
<add> 'pageName' => $pageName,
<add> ]), $result);
<add> }
<add>
<ide> public function testWhereRowValues()
<ide> {
<ide> $builder = $this->getBuilder();
<ide><path>tests/Integration/Database/QueryBuilderTest.php
<ide> use Illuminate\Support\Facades\DB;
<ide> use Illuminate\Support\Facades\Schema;
<ide> use Illuminate\Database\Schema\Blueprint;
<add>use Illuminate\Contracts\Pagination\LengthAwarePaginator;
<ide> use Illuminate\Tests\Integration\Database\DatabaseTestCase;
<ide>
<ide> /**
<ide> protected function setUp(): void
<ide> parent::setUp();
<ide>
<ide> Schema::create('posts', function (Blueprint $table) {
<add> $table->string('title');
<add> $table->text('content');
<ide> $table->timestamp('created_at');
<ide> });
<ide>
<ide> DB::table('posts')->insert([
<del> ['created_at' => new Carbon('2017-11-12 13:14:15')],
<del> ['created_at' => new Carbon('2018-01-02 03:04:05')],
<add> ['title' => 'Foo Post', 'content' => 'Lorem Ipsum.', 'created_at' => new Carbon('2017-11-12 13:14:15')],
<add> ['title' => 'Bar Post', 'content' => 'Lorem Ipsum.', 'created_at' => new Carbon('2018-01-02 03:04:05')],
<ide> ]);
<ide> }
<ide>
<ide> public function testWhereTime()
<ide> $this->assertSame(1, DB::table('posts')->whereTime('created_at', '03:04:05')->count());
<ide> $this->assertSame(1, DB::table('posts')->whereTime('created_at', new Carbon('2018-01-02 03:04:05'))->count());
<ide> }
<add>
<add> public function testPaginateWithSpecificColumns()
<add> {
<add> $result = DB::table('posts')->paginate(5, ['title', 'content']);
<add>
<add> $this->assertInstanceOf(LengthAwarePaginator::class, $result);
<add> $this->assertEquals($result->items(), [
<add> (object) ['title' => 'Foo Post', 'content' => 'Lorem Ipsum.'],
<add> (object) ['title' => 'Bar Post', 'content' => 'Lorem Ipsum.'],
<add> ]);
<add> }
<ide> } | 3 |
Python | Python | add unit tests for special values for csqrt | 897175751927b3c69e0fe7faf247e0eb5fad20d0 | <ide><path>numpy/core/tests/test_umath_complex.py
<ide> def test_special_values(self):
<ide> for i in range(len(xa)):
<ide> assert_almost_equal_spec(np.log(np.conj(xa[i])), np.conj(np.log(xa[i])))
<ide>
<add>class TestCsqrt(object):
<add> def test_simple(self):
<add> # sqrt(1)
<add> yield check_complex_value, np.sqrt, 1, 0, 1, 0
<add>
<add> # sqrt(1i)
<add> yield check_complex_value, np.sqrt, 0, 1, 0.5*np.sqrt(2), 0.5*np.sqrt(2), False
<add>
<add> # sqrt(-1)
<add> yield check_complex_value, np.sqrt, -1, 0, 0, 1
<add>
<add> def test_simple_conjugate(self):
<add> ref = np.conj(np.sqrt(np.complex(1, 1)))
<add> def f(z):
<add> return np.sqrt(np.conj(z))
<add> yield check_complex_value, f, 1, 1, ref.real, ref.imag, False
<add>
<add> #def test_branch_cut(self):
<add> # _check_branch_cut(f, -1, 0, 1, -1)
<add>
<add> def test_special_values(self):
<add> check = check_complex_value
<add> f = np.sqrt
<add>
<add> # C99: Sec G 6.4.2
<add> x, y = [], []
<add>
<add> # csqrt(+-0 + 0i) is 0 + 0i
<add> yield check, f, np.PZERO, 0, 0, 0
<add> yield check, f, np.NZERO, 0, 0, 0
<add>
<add> # csqrt(x + infi) is inf + infi for any x (including NaN)
<add> yield check, f, 1, np.inf, np.inf, np.inf
<add> yield check, f, -1, np.inf, np.inf, np.inf
<add>
<add> yield check, f, np.PZERO, np.inf, np.inf, np.inf
<add> yield check, f, np.NZERO, np.inf, np.inf, np.inf
<add> yield check, f, np.inf, np.inf, np.inf, np.inf
<add> yield check, f, -np.inf, np.inf, np.inf, np.inf
<add> yield check, f, -np.nan, np.inf, np.inf, np.inf
<add>
<add> # csqrt(x + nani) is nan + nani for any finite x
<add> yield check, f, 1, np.nan, np.nan, np.nan
<add> yield check, f, -1, np.nan, np.nan, np.nan
<add> yield check, f, 0, np.nan, np.nan, np.nan
<add>
<add> # csqrt(-inf + yi) is +0 + infi for any finite y > 0
<add> yield check, f, -np.inf, 1, np.PZERO, np.inf
<add>
<add> # csqrt(inf + yi) is +inf + 0i for any finite y > 0
<add> yield check, f, np.inf, 1, np.inf, np.PZERO
<add>
<add> # csqrt(-inf + nani) is nan +- infi (both +i infi are valid)
<add> def _check_ninf_nan(dummy):
<add> z = np.sqrt(np.array(np.complex(-np.inf, np.nan)))
<add> if not np.isnan(z.real) or not np.isinf(z.imag):
<add> raise AssertionError(
<add> "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" \
<add> % (z.real, z.imag))
<add>
<add> yield _check_ninf_nan, None
<add>
<add> # csqrt(+inf + nani) is inf + nani
<add> yield check, f, np.inf, np.nan, np.inf, np.nan
<add>
<add> # csqrt(nan + yi) is nan + nani for any y
<add> yield check, f, np.nan, 0, np.nan, np.nan
<add> yield check, f, np.nan, 1, np.nan, np.nan
<add> yield check, f, np.nan, np.nan, np.nan, np.nan
<add> yield check, f, np.nan, np.inf, np.nan, np.nan
<add> yield check, f, np.nan, -np.inf, np.nan, np.nan
<add>
<add> # XXX: check for conj(csqrt(z)) == csqrt(conj(z)) (need to fix branch
<add> # cuts first)
<add>
<ide> class TestCpow(TestCase):
<ide> def test_simple(self):
<ide> x = np.array([1+1j, 0+2j, 1+2j, np.inf, np.nan]) | 1 |
Javascript | Javascript | update function keywords to fat arrows | 98f170fb8665aa9a94c47cabb4a7107440f4dbfe | <ide><path>test/parallel/test-event-emitter-no-error-provided-to-error-event.js
<ide> const domain = require('domain');
<ide> const e = new events.EventEmitter();
<ide> const d = domain.create();
<ide> d.add(e);
<del> d.on('error', common.mustCall(function(er) {
<add> d.on('error', common.mustCall((er) => {
<ide> assert(er instanceof Error, 'error created');
<ide> }));
<ide> e.emit('error');
<ide> for (const arg of [false, null, undefined]) {
<ide> const e = new events.EventEmitter();
<ide> const d = domain.create();
<ide> d.add(e);
<del> d.on('error', common.mustCall(function(er) {
<add> d.on('error', common.mustCall((er) => {
<ide> assert(er instanceof Error, 'error created');
<ide> }));
<ide> e.emit('error', arg);
<ide> for (const arg of [42, 'fortytwo', true]) {
<ide> const e = new events.EventEmitter();
<ide> const d = domain.create();
<ide> d.add(e);
<del> d.on('error', common.mustCall(function(er) {
<add> d.on('error', common.mustCall((er) => {
<ide> assert.strictEqual(er, arg);
<ide> }));
<ide> e.emit('error', arg); | 1 |
Text | Text | add docs page for accessibility support | 5921f5f702bc05cfe568fa8495f06af97c689635 | <ide><path>docs/Accessibility.md
<add>---
<add>id: accesibility
<add>title: Accessibility
<add>layout: docs
<add>category: Guides
<add>permalink: docs/accessibility.html
<add>next: nativemodulesios
<add>---
<add>
<add># Accessibility
<add>
<add>Accessibility on iOS encompasses many topics, but for many, accessibility is synonymous with VoiceOver, a technology available since iOS 3.0. It acts as a screen reader, allowing people with visual impairments to use their iOS devices. Click [here](https://developer.apple.com/accessibility/ios/) to learn more.
<add>
<add>## Making Accessible Apps
<add>
<add>### Coding Accessibly
<add>
<add>#### accessible
<add>
<add>When true, indicates that the view is an accessibility element. When a view is an accessibility element, it groups its children into a single selectable component. By default, all touchable elements are accessible.
<add>
<add>#### accessibilityLabel
<add>
<add>When a view is marked as accessible, it is a good practice to set an accessibilityLabel on the view, so that people who use VoiceOver know what element they have selected. VoiceOver will read this string when a user selects the associated element.
<add>
<add>To use, simply set the `accessibilityLabel` property to a custom string on your View:
<add>
<add>```javascript
<add><TouchableOpacity accessible={true} accessibilityLabel={'Tap me!'} onPress={this._onPress}>
<add> <View style={styles.button}>
<add> <Text style={styles.buttonText}>Press me!</Text>
<add> </View>
<add></TouchableOpacity>```
<add>
<add>In the above example, the `accessibilityLabel` on the TouchableOpacity element would default to "Press me!". The label is constructed by concatenating all Text node children separated by spaces.
<add>
<add>#### accessibilityTraits
<add>
<add>Accessibility traits tell a person using VoiceOver what kind of element they have selected. Is this element a label? A button? A header? These questions are answered by `accessibilityTraits`.
<add>
<add>To use, set the `accessibilityTraits` property to one of (or an array of) accessibility trait strings:
<add>
<add>* **none** Used when the element has no traits.
<add>* **button** Used when the element should be treated as a button.
<add>* **link** Used when the element should be treated as a link.
<add>* **header** Used when an element acts as a header for a content section (e.g. the title of a navigation bar).
<add>* **search** Used when the text field element should also be treated as a search field.
<add>* **image** Used when the element should be treated as an image. Can be combined with button or link, for example.
<add>* **selected** Used when the element is selected. For example, a selected row in a table or a selected button within a segmented control.
<add>* **plays** Used when the element plays its own sound when activated.
<add>* **key** Used when the element acts as a keyboard key.
<add>* **text** Used when the element should be treated as static text that cannot change.
<add>* **summary** Used when an element can be used to provide a quick summary of current conditions in the app when the app first launches. For example, when Weather first launches, the element with today's weather conditions is marked with this trait.
<add>* **disabled** Used when the control is not enabled and does not respond to user input.
<add>* **frequentUpdates** Used when the element frequently updates its label or value, but too often to send notifications. Allows an accessibility client to poll for changes. A stopwatch would be an example.
<add>* **startsMedia** Used when activating an element starts a media session (e.g. playing a movie, recording audio) that should not be interrupted by output from an assistive technology, like VoiceOver.
<add>* **adjustable** Used when an element can be "adjusted" (e.g. a slider).
<add>* **allowsDirectInteraction** Used when an element allows direct touch interaction for VoiceOver users (for example, a view representing a piano keyboard).
<add>* **pageTurn** Informs VoiceOver that it should scroll to the next page when it finishes reading the contents of the element.
<add>
<add>#### onAccessibilityTap
<add>
<add>Use this property to assign a custom function to be called when someone activates an accessible element by double tapping on it while it's selected.
<add>
<add>#### onMagicTap
<add>
<add>Assign this property to a custom function which will be called when someone performs the "magic tap" gesture, which is a double-tap with two fingers. A magic tap function should perform the most relevant action a user could take on a component. In the Phone app on iPhone, a magic tap answers a phone call, or ends the current one.
<add>
<add>### Testing VoiceOver Support
<add>
<add>To enable VoiceOver, go to the Settings app on your iOS device. Tap General, then Accessibility. There you will find many tools that people use to use to make their devices more usable, such as bolder text, increased contrast, and VoiceOver.
<add>
<add>To enable VoiceOver, tap on VoiceOver under "Vision" and toggle the switch that appears at the top.
<add>
<add>At the very bottom of the Accessibility settings, there is an "Accessibility Shortcut". You can use this to toggle VoiceOver by triple clicking the Home button.
<ide><path>docs/Animations.md
<ide> title: Animations
<ide> layout: docs
<ide> category: Guides
<ide> permalink: docs/animations.html
<del>next: nativemodulesios
<add>next: accessibility
<ide> ---
<ide>
<ide> Fluid, meaningful animations are essential to the mobile user | 2 |
Javascript | Javascript | remove confusing references to player in a tech | d69551ac8032bae333a2df07e65ebd0531e75a76 | <ide><path>src/js/tech/html5.js
<ide> class Html5 extends Tech {
<ide> if (this.el_.duration === Infinity) {
<ide> this.trigger('durationchange');
<ide> }
<del> this.off(this.player_, 'timeupdate', checkProgress);
<add> this.off('timeupdate', checkProgress);
<ide> }
<ide> };
<ide>
<del> this.on(this.player_, 'timeupdate', checkProgress);
<add> this.on('timeupdate', checkProgress);
<ide> return NaN;
<ide> }
<ide> } | 1 |
Text | Text | add pandas installation method | b1859e62d82689b5fc211c36ffa1e9c96c1ee206 | <ide><path>guide/english/data-science-tools/pandas/index.md
<ide> title: pandas
<ide> ## pandas
<ide> [pandas](http://pandas.pydata.org/) is a Python library for data analysis using data frames. The name `pandas` comes from *panel data*, i.e. a multi-dimensional data measured over time. Data frames are tables of data, which may conceptually be compared to a spreadsheet. Data scientists familiar with R will feel at home here. pandas is often used along with numpy, scipy, pyplot, seaborn and scikit-learn.
<ide>
<add>### Installing pandas
<add>#### Installing via Anaconda (__Recommended__):
<add>Pandas and the other Data Science Stack (Scipy, Numpy, Scikit, etc) are included when installing Anaconda. For more information about installing Anaconda, please refer to this [site](http://docs.continuum.io/anaconda/install/).
<add>
<add>#### Installing via pip:
<add>If you want to install pandas using default python package manager (pip), here is the command:
<add>```
<add>pip install pandas
<add>```
<add>
<ide> ### Importing pandas
<ide> It is a widely used convention to import the pandas library using the alias `pd`:
<ide> ```python | 1 |
PHP | PHP | apply fixes from styleci | b787ac38e70b33e567bd82dd8c086f203141f89d | <ide><path>src/Illuminate/Routing/Controller.php
<ide> namespace Illuminate\Routing;
<ide>
<ide> use BadMethodCallException;
<del>use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
<ide>
<ide> abstract class Controller
<ide> { | 1 |
Javascript | Javascript | remove un-needed context preservation | 0b966fd1628f107f24cf7b545568e309c0caf346 | <ide><path>packages/ember-routing/lib/system/router.js
<ide> Ember.Router = Ember.Object.extend({
<ide> handleURL: function(url) {
<ide> scheduleLoadingStateEntry(this);
<ide>
<del> var self = this;
<del>
<del> return this.router.handleURL(url).then(function() {
<del> transitionCompleted(self);
<del> });
<add> return this.router.handleURL(url).then(transitionCompleted);
<ide> },
<ide>
<ide> transitionTo: function() {
<ide> function doTransition(router, method, args) {
<ide> scheduleLoadingStateEntry(router);
<ide>
<ide> var transitionPromise = router.router[method].apply(router.router, args);
<del> transitionPromise.then(function() {
<del> transitionCompleted(router);
<del> });
<add> transitionPromise.then(transitionCompleted);
<ide>
<ide> // We want to return the configurable promise object
<ide> // so that callers of this function can use `.method()` on it,
<ide> function exitLoadingState(router) {
<ide> router._loadingStateActive = false;
<ide> }
<ide>
<del>function transitionCompleted(router) {
<add>function transitionCompleted(route) {
<add> var router = route.router;
<ide> router.notifyPropertyChange('url');
<ide> exitLoadingState(router);
<ide> } | 1 |
Text | Text | clarify tutorial instructions | c157ce359970b51e9fb49dc00ff1f52cd32d8559 | <ide><path>docs/docs/tutorial.md
<ide> You do not have to return basic HTML. You can return a tree of components that y
<ide>
<ide> ## Composing components
<ide>
<del>Let's build skeletons for `CommentList` and `CommentForm` which will, again, be simple `<div>`s:
<add>Let's build skeletons for `CommentList` and `CommentForm` which will, again, be simple `<div>`s. Add these two components to your file, keeping the existing `CommentBox` declaration and `React.render` call:
<ide>
<ide> ```javascript
<ide> // tutorial2.js | 1 |
Javascript | Javascript | set contenthashtype to javascript | 8b9fea37909504426513f6679ed1fae3a75abcd3 | <ide><path>lib/node/RequireChunkLoadingRuntimeModule.js
<ide> class RequireChunkLoadingRuntimeModule extends RuntimeModule {
<ide> this.compilation.outputOptions.filename + "",
<ide> {
<ide> chunk,
<del> contentHashType: Object.keys(chunk.contentHash)[0]
<add> contentHashType: "javascript"
<ide> }
<ide> );
<ide> const chunkInnerDirsCount = outputName.split("/").length - 1; | 1 |
Ruby | Ruby | add match 302 http code for log in redirect_to | 9b92b1fb6d60fe61595d2e9a0c92a9d8295a49d9 | <ide><path>actionpack/test/controller/log_subscriber_test.rb
<ide> def test_redirect_to
<ide>
<ide> assert_equal 3, logs.size
<ide> assert_equal "Redirected to http://foo.bar/", logs[1]
<add> assert_match(/Completed 302/, logs.last)
<ide> end
<ide>
<ide> def test_filter_redirect_url_by_string | 1 |
Javascript | Javascript | add data-grammar to editor element | 2a1ba7f05b33eb499f5fe7f0f3f9673e07a90f1c | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> const {element} = buildComponent({placeholderText, text: ''})
<ide> expect(element.textContent).toContain(placeholderText)
<ide> })
<add>
<add> it('adds the data-grammar attribute and updates it when the grammar changes', async () => {
<add> await atom.packages.activatePackage('language-javascript')
<add>
<add> const {editor, element, component} = buildComponent()
<add> expect(element.dataset.grammar).toBe('text plain null-grammar')
<add>
<add> editor.setGrammar(atom.grammars.grammarForScopeName('source.js'))
<add> await component.getNextUpdatePromise()
<add> expect(element.dataset.grammar).toBe('source js')
<add> })
<ide> })
<ide>
<ide> describe('mini editors', () => {
<ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> className = className + ' mini'
<ide> }
<ide>
<add> const dataset = {}
<add> const grammar = model.getGrammar()
<add> if (grammar && grammar.scopeName) {
<add> dataset.grammar = grammar.scopeName.replace(/\./g, ' ')
<add> }
<add>
<ide> return $('atom-text-editor',
<ide> {
<ide> className,
<ide> style,
<ide> attributes,
<add> dataset,
<ide> tabIndex: -1,
<ide> on: {
<ide> focus: this.didFocus, | 2 |
Text | Text | update chinese translation of basic javascript | 39df9d94c912b7b4ea424ff9cc6e55ea3f576f44 | <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.chinese.md
<ide> id: 56bbb991ad1ed5201cd392ca
<ide> title: Access Array Data with Indexes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用索引访问数组数据
<add>videoUrl: 'https://scrimba.com/c/cBZQbTz'
<add>forumTopicId: 16158
<add>localeTitle: 通过索引访问数组中的数据
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们可以使用<code>indexes</code>访问数组内部的数据。数组索引使用字符串使用的相同括号表示法编写,但不是指定字符,而是指定数组中的条目。与字符串一样,数组使用<dfn>从零开始的</dfn>索引,因此数组中的第一个元素是元素<code>0</code> 。 <strong>例</strong> <blockquote> var array = [50,60,70]; <br>阵列[0]; //等于50 <br> var data = array [1]; //等于60 </blockquote> <strong>注意</strong> <br>数组名称和方括号之间不应有任何空格,如<code>array [0]</code> 。尽管JavaScript能够正确处理,但这可能会让其他程序员在阅读代码时感到困惑。 </section>
<add><section id='description'>
<add>我们可以使用索引 <code>indexes</code> 来访问数组中的数据。
<add>
<add>数组索引与字符串索引一样使用中括号,但字符串索引得到的是一个字符,而数组索引得到的是一个元素。数组索引与字符串索引一样是从 0 开始的,所以数组中第一个元素的索引编号是 0。
<add><br/>
<add><strong>示例</strong>
<add>
<add>```js
<add>var array = [50,60,70];
<add>array[0]; // equals 50
<add>var data = array[1]; // equals 60
<add>```
<add>
<add><strong>提示</strong><br>数组名称和方括号之间不应有任何空格,如<code>array [0]</code>尽管 JavaScript 能够正确处理,但可能会让看你代码的其他程序员感到困惑
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>myData</code>的变量,并使用括号表示法将其设置为等于<code>myArray</code>的第一个值。 </section>
<add><section id='instructions'>
<add>创建一个名为<code>myData</code>的变量,并把<code>myArray</code>的第一个索引上的值赋给它。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 变量<code>myData</code>应该等于<code>myArray</code>的第一个值。
<add> - text: 变量<code>myData</code>的值应该等于<code>myArray</code>的第一个值。
<ide> testString: assert((function(){if(typeof myArray !== 'undefined' && typeof myData !== 'undefined' && myArray[0] === myData){return true;}else{return false;}})());
<del> - text: 应使用括号表示法访问变量<code>myArray</code>的数据。
<add> - text: 应使用方括号访问变量<code>myArray</code>中的数据。
<ide> testString: assert((function(){if(code.match(/\s*=\s*myArray\[0\]/g)){return true;}else{return false;}})());
<ide>
<ide> ```
<ide> var myArray = [50,60,70];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined" && typeof myData !== "undefined"){(function(y,z){return 'myArray = ' + JSON.stringify(y) + ', myData = ' + JSON.stringify(z);})(myArray, myData);}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [50,60,70];
<add>var myData = myArray[0];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.chinese.md
<ide> id: 56592a60ddddeae28f7aa8e1
<ide> title: Access Multi-Dimensional Arrays With Indexes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 访问带索引的多维数组
<add>videoUrl: 'https://scrimba.com/c/ckND4Cq'
<add>forumTopicId: 16159
<add>localeTitle: 使用索引访问多维数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">考虑<dfn>多维</dfn>数组的一种方法是作为<em>数组的数组</em> 。使用括号访问数组时,第一组括号引用最外层(第一级)数组中的条目,另外一对括号引用内部的下一级条目。 <strong>例</strong> <blockquote> var arr = [ <br> [1,2,3], <br> [4,5,6] <br> [7,8,9] <br> [[10,11,12],13,14] <br> ]。 <br> ARR [3]; //等于[[10,11,12],13,14] <br> ARR [3] [0]; //等于[10,11,12] <br> ARR [3] [0] [1]; //等于11 </blockquote> <strong>注意</strong> <br>数组名称和方括号之间不应该有任何空格,如<code>array [0][0]</code> ,甚至不允许使用此<code>array [0] [0]</code> 。尽管JavaScript能够正确处理,但这可能会让其他程序员在阅读代码时感到困惑。 </section>
<add><section id='description'>
<add>可以把 <dfn>多维</dfn> 数组看作成是一个 <em>数组中的数组</em>。当使用方括号去访问数组的时候,第一个<code>[index]</code>访问的是第 N 个子数组,第二个<code>[index]</code>访问的是第 N 个子数组的第N个元素。
<add><strong>示例</strong>
<add>
<add>```js
<add>var arr = [
<add> [1,2,3],
<add> [4,5,6],
<add> [7,8,9],
<add> [[10,11,12], 13, 14]
<add>];
<add>arr[3]; // equals [[10,11,12], 13, 14]
<add>arr[3][0]; // equals [10,11,12]
<add>arr[3][0][1]; // equals 11
<add>```
<add>
<add><strong>提示</strong><br>数组名称和方括号之间不应该有任何空格,如<code>array [0][0]</code>,甚至<code>array [0] [0]</code>,都是不正确的。尽管 JavaScript 能够处理,但可能会让看你代码的其他程序员感到困惑。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用括号表示法从<code>myArray</code>选择一个元素,使<code>myData</code>等于<code>8</code> 。 </section>
<add><section id='instructions'>
<add>使用索引从<code>myArray</code>选择一个元素,使得<code>myData</code>的值为<code>8</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myData</code>应该等于<code>8</code> 。
<add> - text: <code>myData</code>应该等于<code>8</code>。
<ide> testString: assert(myData === 8);
<del> - text: 您应该使用括号表示法从<code>myArray</code>读取正确的值。
<del> testString: assert(/myData=myArray\[2\]\[1\]/.test(code.replace(/\s/g, '')));
<add> - text: 你应该使用方括号从<code>myArray</code>中取值。
<add> testString: 'assert(/myArray\[2\]\[1\]/g.test(code) && !/myData\s*=\s*(?:.*[-+*/%]|\d)/g.test(code));'
<ide>
<ide> ```
<ide>
<ide> var myData = myArray[0][0];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return "myData: " + myData + " myArray: " + JSON.stringify(myArray);})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]];
<add>var myData = myArray[2][1];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.chinese.md
<ide> id: 56533eb9ac21ba0edf2244cd
<ide> title: Accessing Nested Arrays
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cLeGDtZ'
<add>forumTopicId: 16160
<ide> localeTitle: 访问嵌套数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">正如我们在前面的示例中所看到的,对象可以包含嵌套对象和嵌套数组。与访问嵌套对象类似,可以链接数组括号表示法来访问嵌套数组。以下是如何访问嵌套数组的示例: <blockquote> var ourPets = [ <br> { <br> animalType:“猫”, <br>名称:[ <br> “Meowzer” <br> “蓬松”, <br> “洁猫” <br> ] <br> }, <br> { <br>动物类型:“狗”, <br>名称:[ <br> “点”, <br> “库巴” <br> “羊羊” <br> ] <br> } <br> ]。 <br> ourPets [0] .names [1]; //“蓬松” <br> ourPets [1] .names [0]; //“Spot” </blockquote></section>
<add><section id='description'>
<add>正如我们在前面的例子所见,对象可以嵌套对象和数组。与访问嵌套对象一样,用中括号操作符同样可以访问嵌套数组。
<add>下面是如何访问嵌套数组的例子:
<add>
<add>```js
<add>var ourPets = [
<add> {
<add> animalType: "cat",
<add> names: [
<add> "Meowzer",
<add> "Fluffy",
<add> "Kit-Cat"
<add> ]
<add> },
<add> {
<add> animalType: "dog",
<add> names: [
<add> "Spot",
<add> "Bowser",
<add> "Frankie"
<add> ]
<add> }
<add>];
<add>ourPets[0].names[1]; // "Fluffy"
<add>ourPets[1].names[0]; // "Spot"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用对象点和数组括号表示法从变量<code>myPlants</code>检索第二个树。 </section>
<add><section id='instructions'>
<add>使用点操作符和中括号操作符来检索变量<code>myPlants</code>的第二棵树。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>secondTree</code>应该等于“松树”
<add> - text: <code>secondTree</code>应该等于 "pine"。
<ide> testString: assert(secondTree === "pine");
<del> - text: 使用点和括号表示法访问<code>myPlants</code>
<add> - text: 使用点操作符和中括号操作符来检索变量<code>myPlants</code>。
<ide> testString: assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
<ide>
<ide> ```
<ide> var secondTree = ""; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(x) {
<add> if(typeof x != 'undefined') {
<add> return "secondTree = " + x;
<add> }
<add> return "secondTree is undefined";
<add>})(secondTree);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myPlants = [
<add> {
<add> type: "flowers",
<add> list: [
<add> "rose",
<add> "tulip",
<add> "dandelion"
<add> ]
<add> },
<add> {
<add> type: "trees",
<add> list: [
<add> "fir",
<add> "pine",
<add> "birch"
<add> ]
<add> }
<add>];
<add>
<add>// Only change code below this line
<add>
<add>var secondTree = myPlants[1].list[1];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.chinese.md
<ide> id: 56533eb9ac21ba0edf2244cc
<ide> title: Accessing Nested Objects
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cRnRnfa'
<add>forumTopicId: 16161
<ide> localeTitle: 访问嵌套对象
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">可以通过将点或括号表示法链接在一起来访问对象的子属性。这是一个嵌套对象: <blockquote> var ourStorage = { <br> “桌子”:{ <br> “抽屉”:“订书机” <br> }, <br> “内阁”:{ <br> “顶级抽屉”:{ <br> “folder1”:“一个文件”, <br> “folder2”:“秘密” <br> }, <br> “底部抽屉”:“苏打水” <br> } <br> }; <br> ourStorage.cabinet [“top drawer”]。folder2; //“秘密” <br> ourStorage.desk.drawer; //“订书机” </blockquote></section>
<add><section id='description'>
<add>通过串联起来的点操作符或中括号操作符来访问对象的嵌套属性。
<add>下面是一个嵌套的对象:
<add>
<add>```js
<add>var ourStorage = {
<add> "desk": {
<add> "drawer": "stapler"
<add> },
<add> "cabinet": {
<add> "top drawer": {
<add> "folder1": "a file",
<add> "folder2": "secrets"
<add> },
<add> "bottom drawer": "soda"
<add> }
<add>};
<add>ourStorage.cabinet["top drawer"].folder2; // "secrets"
<add>ourStorage.desk.drawer; // "stapler"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">访问<code>myStorage</code>对象并将<code>glove box</code>属性的内容分配给<code>gloveBoxContents</code>变量。对于名称中包含空格的属性,请使用括号表示法。 </section>
<add><section id='instructions'>
<add>读取<code>myStorage</code>对象,将<code>glove box</code>属性的内容赋值给变量<code>gloveBoxContents</code>。在适用的地方使用点操作符来访问属性,否则使用中括号操作符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>gloveBoxContents</code>应该等于“地图”
<add> - text: <code>gloveBoxContents</code>应该等于"maps"。
<ide> testString: assert(gloveBoxContents === "maps");
<del> - text: 使用点和括号表示法访问<code>myStorage</code>
<add> - text: 应使用点操作符和中括号操作符来访问<code>myStorage</code>。
<ide> testString: assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
<ide>
<ide> ```
<ide> var gloveBoxContents = undefined; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(x) {
<add> if(typeof x != 'undefined') {
<add> return "gloveBoxContents = " + x;
<add> }
<add> return "gloveBoxContents is undefined";
<add>})(gloveBoxContents);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myStorage = {
<add> "car":{
<add> "inside":{
<add> "glove box":"maps",
<add> "passenger seat":"crumbs"
<add> },
<add> "outside":{
<add> "trunk":"jack"
<add> }
<add> }
<add>};
<add>var gloveBoxContents = myStorage.car.inside["glove box"];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c8
<ide> title: Accessing Object Properties with Bracket Notation
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用括号表示法访问对象属性
<add>videoUrl: 'https://scrimba.com/c/cBvmEHP'
<add>forumTopicId: 16163
<add>localeTitle: 通过方括号访问对象属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">访问对象属性的第二种方法是括号表示法( <code>[]</code> )。如果您尝试访问的对象的属性在其名称中有空格,则需要使用括号表示法。但是,您仍然可以在没有空格的对象属性上使用括号表示法。以下是使用括号表示法读取对象属性的示例: <blockquote> var myObj = { <br> “太空名称”:“柯克”, <br> “更多空间”:“Spock”, <br> “NoSpace”:“USS Enterprise” <br> }; <br> myObj [“空间名称”]; //柯克<br> myObj ['更多空间']; // Spock <br> MyObj中[ “无空间”]; // USS Enterprise </blockquote>请注意,其中包含空格的属性名称必须使用引号(单引号或双引号)。 </section>
<add><section id='description'>
<add>第二种访问对象的方式就是中括号操作符(<code>[]</code>),如果你想访问的属性的名称有一个空格,这时你只能使用中括号操作符(<code>[]</code>)。
<add>当然,如果属性名不包含空格,也可以使用中括号操作符。
<add>这是一个使用中括号操作符(<code>[]</code>)读取对象属性的例子:
<add>
<add>```js
<add>var myObj = {
<add> "Space Name": "Kirk",
<add> "More Space": "Spock",
<add> "NoSpace": "USS Enterprise"
<add>};
<add>myObj["Space Name"]; // Kirk
<add>myObj['More Space']; // Spock
<add>myObj["NoSpace"]; // USS Enterprise
<add>```
<add>
<add>提示:属性名称中如果有空格,必须把属性名称用单引号或双引号包裹起来。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用括号表示法<code>testObj</code>属性<code>"an entree"</code> <code>testObj</code> <code>"an entree"</code>和<code>"the drink"</code>的<code>testObj</code> ,并分别将它们分配给<code>entreeValue</code>和<code>drinkValue</code> 。 </section>
<add><section id='instructions'>
<add>用中括号操作符读取对象<code>testObj</code>的<code>an entree</code>属性值和<code>the drink</code>属性值,并分别赋值给<code>entreeValue</code>和<code>drinkValue</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>entreeValue</code>应该是一个字符串
<add> - text: <code>entreeValue</code>应该是一个字符串。
<ide> testString: assert(typeof entreeValue === 'string' );
<del> - text: <code>entreeValue</code>的值应该是<code>"hamburger"</code>
<add> - text: <code>entreeValue</code>的值应该是<code>"hamburger"</code>。
<ide> testString: assert(entreeValue === 'hamburger' );
<del> - text: <code>drinkValue</code>应该是一个字符串
<add> - text: <code>drinkValue</code>应该是一个字符串。
<ide> testString: assert(typeof drinkValue === 'string' );
<del> - text: <code>drinkValue</code>的值应该是<code>"water"</code>
<add> - text: <code>drinkValue</code>的值应该是<code>"water"</code>。
<ide> testString: assert(drinkValue === 'water' );
<del> - text: 您应该使用括号表示法两次
<add> - text: 你应该使用中括号两次。
<ide> testString: assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
<ide>
<ide> ```
<ide> var testObj = {
<ide>
<ide> var entreeValue = testObj; // Change this line
<ide> var drinkValue = testObj; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var drinkValue = testObj; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b) { return "entreeValue = '" + a + "', drinkValue = '" + b + "'"; })(entreeValue,drinkValue);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var testObj = {
<add> "an entree": "hamburger",
<add> "my side": "veggies",
<add> "the drink": "water"
<add>};
<add>var entreeValue = testObj["an entree"];
<add>var drinkValue = testObj['the drink'];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c7
<ide> title: Accessing Object Properties with Dot Notation
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用点表示法访问对象属性
<add>videoUrl: 'https://scrimba.com/c/cGryJs8'
<add>forumTopicId: 16164
<add>localeTitle: 通过点符号访问对象属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有两种方法可以访问对象的属性:点表示法( <code>.</code> )和括号表示法( <code>[]</code> ),类似于数组。当您知道要提前访问的属性的名称时,使用点符号。以下是使用点表示法( <code>.</code> )读取对象属性的示例: <blockquote> var myObj = { <br> prop1:“val1”, <br> prop2:“val2” <br> }; <br> var prop1val = myObj.prop1; // val1 <br> var prop2val = myObj.prop2; // val2 </blockquote></section>
<add><section id='description'>
<add>有两种方式访问对象属性,一个是点操作符(<code>.</code>),一个是中括号操作符(<code>[]</code>)。
<add>当你知道所要读取的属性的名称的时候,使用点操作符。
<add>这是一个使用点操作符读取对象属性的例子:
<add>
<add>```js
<add>var myObj = {
<add> prop1: "val1",
<add> prop2: "val2"
<add>};
<add>var prop1val = myObj.prop1; // val1
<add>var prop2val = myObj.prop2; // val2
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用点表示法读入<code>testObj</code>的属性值。将变量<code>hatValue</code>设置为等于对象的属性<code>hat</code> ,并将变量<code>shirtValue</code>设置为等于对象的属性<code>shirt</code> 。 </section>
<add><section id='instructions'>
<add>通过点操作符读取对象<code>testObj</code>,把<code>hat</code>的属性值赋给变量<code>hatValue</code>,把<code>shirt</code>的属性值赋给<code>shirtValue</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>hatValue</code>应该是一个字符串
<add> - text: <code>hatValue</code>应该是一个字符串。
<ide> testString: assert(typeof hatValue === 'string' );
<del> - text: <code>hatValue</code>的值应该是<code>"ballcap"</code>
<add> - text: <code>hatValue</code>的值应该是<code>"ballcap"</code>。
<ide> testString: assert(hatValue === 'ballcap' );
<del> - text: <code>shirtValue</code>应该是一个字符串
<add> - text: <code>shirtValue</code>应该是一个字符串。
<ide> testString: assert(typeof shirtValue === 'string' );
<del> - text: <code>shirtValue</code>的值应该是<code>"jersey"</code>
<add> - text: <code>shirtValue</code>的值应该是<code>"jersey"</code>。
<ide> testString: assert(shirtValue === 'jersey' );
<del> - text: 你应该使用点符号两次
<add> - text: 你应该使用点操作符两次。
<ide> testString: assert(code.match(/testObj\.\w+/g).length > 1);
<ide>
<ide> ```
<ide> var testObj = {
<ide>
<ide> var hatValue = testObj; // Change this line
<ide> var shirtValue = testObj; // Change this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var shirtValue = testObj; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b) { return "hatValue = '" + a + "', shirtValue = '" + b + "'"; })(hatValue,shirtValue);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var testObj = {
<add> "hat": "ballcap",
<add> "shirt": "jersey",
<add> "shoes": "cleats"
<add>};
<add>
<add>var hatValue = testObj.hat;
<add>var shirtValue = testObj.shirt;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c9
<ide> title: Accessing Object Properties with Variables
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用变量访问对象属性
<add>videoUrl: 'https://scrimba.com/c/cnQyKur'
<add>forumTopicId: 16165
<add>localeTitle: 通过变量访问对象属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">对象的括号表示法的另一个用途是访问存储为变量值的属性。这对于迭代对象的属性或访问查找表非常有用。以下是使用变量访问属性的示例: <blockquote> var dogs = { <br> Fido:“Mutt”,Hunter:“Doberman”,Snoopie:“Beagle” <br> }; <br> var myDog =“猎人”; <br> var myBreed = dogs [myDog]; <br>的console.log(myBreed); //“杜宾犬” </blockquote>另一种可以使用此概念的方法是在程序执行期间动态收集属性的名称,如下所示: <blockquote> var someObj = { <br> propName:“约翰” <br> }; <br> function propPrefix(str){ <br> var s =“prop”; <br> return s + str; <br> } <br> var someProp = propPrefix(“Name”); // someProp现在保存值'propName' <br>的console.log(someObj中[someProp]); // “约翰” </blockquote>请注意,在使用变量名来访问属性时,我们<em>不会</em>使用引号,因为我们使用的是变量的<em>值</em> ,而不是<em>名称</em> 。 </section>
<add><section id='description'>
<add>中括号操作符的另一个使用方式是访问赋值给变量的属性。当你需要遍历对象的属性列表或访问查找表(lookup tables)时,这种方式极为有用。
<add>这有一个使用变量来访问属性的例子:
<add>
<add>```js
<add>var dogs = {
<add> Fido: "Mutt", Hunter: "Doberman", Snoopie: "Beagle"
<add>};
<add>var myDog = "Hunter";
<add>var myBreed = dogs[myDog];
<add>console.log(myBreed); // "Doberman"
<add>```
<add>
<add>使用此概念的另一种方法是在程序执行期间动态收集属性名称,如下所示:
<add>
<add>```js
<add>var someObj = {
<add> propName: "John"
<add>};
<add>function propPrefix(str) {
<add> var s = "prop";
<add> return s + str;
<add>}
<add>var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
<add>console.log(someObj[someProp]); // "John"
<add>```
<add>
<add>提示:当我们通过变量名访问属性的时候,不需要给变量名包裹引号。因为实际上我们使用的是变量的值,而不是变量的名称。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>playerNumber</code>变量使用括号表示法在<code>testObj</code>查找玩家<code>16</code> 。然后将该名称分配给<code>player</code>变量。 </section>
<add><section id='instructions'>
<add>使用变量<code>playerNumber</code>,通过中括号操作符找到<code>testObj</code>中<code>playerNumber</code>为<code>16</code>的值。然后把名字赋给变量<code>player</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>playerNumber</code>应该是一个数字
<add> - text: <code>playerNumber</code>应该是一个数字。
<ide> testString: assert(typeof playerNumber === 'number');
<del> - text: 变量<code>player</code>应该是一个字符串
<add> - text: 变量<code>player</code>应该是一个字符串。
<ide> testString: assert(typeof player === 'string');
<del> - text: <code>player</code>的价值应该是“蒙大拿”
<add> - text: <code>player</code>点值应该是 "Montana"。
<ide> testString: assert(player === 'Montana');
<del> - text: 您应该使用括号表示法来访问<code>testObj</code>
<add> - text: 你应该使用中括号访问<code>testObj</code>。
<ide> testString: assert(/testObj\s*?\[.*?\]/.test(code));
<del> - text: 您不应该直接将值<code>Montana</code>分配给变量<code>player</code> 。
<add> - text: 你不应该直接将<code>Montana</code>赋给<code>player</code>。
<ide> testString: assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
<del> - text: 您应该在括号表示法中使用变量<code>playerNumber</code>
<add> - text: 你应该在中括号中使用<code>playerNumber</code>变量。
<ide> testString: assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
<ide>
<ide> ```
<ide> var testObj = {
<ide>
<ide> var playerNumber; // Change this Line
<ide> var player = testObj; // Change this Line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var player = testObj; // Change this Line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof player !== "undefined"){(function(v){return v;})(player);}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var testObj = {
<add> 12: "Namath",
<add> 16: "Montana",
<add> 19: "Unitas"
<add>};
<add>var playerNumber = 16;
<add>var player = testObj[playerNumber];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.chinese.md
<ide> id: 56bbb991ad1ed5201cd392d2
<ide> title: Add New Properties to a JavaScript Object
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 将新属性添加到JavaScript对象
<add>videoUrl: 'https://scrimba.com/c/cQe38UD'
<add>forumTopicId: 301169
<add>localeTitle: 给对象添加新属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以像修改现有JavaScript对象一样向现有JavaScript对象添加新属性。以下是我们如何为<code>ourDog</code>添加<code>"bark"</code>属性: <code>ourDog.bark = "bow-wow";</code>或者我们的<code>ourDog["bark"] = "bow-wow";</code>现在当我们评估我们的<code>ourDog.bark</code> ,我们会得到他的吠声,“低头哇”。 </section>
<add><section id='description'>
<add>你也可以像更改属性一样给对象添加属性。
<add>看看我们是如何给<code>ourDog</code>添加<code>"bark"</code>属性:
<add><code>ourDog.bark = "bow-wow";</code>
<add>或者
<add><code>ourDog["bark"] = "bow-wow";</code>
<add>现在当我们访问<code>ourDog.bark</code>时会得到 ourDog 的 bark 值 "bow-wow".
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">向<code>myDog</code>添加<code>"bark"</code>属性并将其设置为狗声,例如“woof”。您可以使用点或括号表示法。 </section>
<add><section id='instructions'>
<add>给<code>myDog</code>添加一个<code>"bark"</code>属性,设置它的值为狗的声音,例如:"woof"。你可以使用点或中括号操作符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 将属性<code>"bark"</code>添加到<code>myDog</code> 。
<add> - text: 给<code>myDog</code>添加<code>"bark"</code>属性。
<ide> testString: assert(myDog.bark !== undefined);
<del> - text: 不要在设置部分添加<code>"bark"</code>
<del> testString: assert(!/bark[^\n]:/.test(code));
<add> - text: 不能在初始化 myDog 的时候添加<code>"bark"</code>属性。
<add> testString: 'assert(!/bark[^\n]:/.test(code));'
<ide>
<ide> ```
<ide>
<ide> var myDog = {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return z;})(myDog);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myDog = {
<add> "name": "Happy Coder",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["freeCodeCamp Campers"]
<add>};
<add>myDog.bark = "Woof Woof";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.chinese.md
<ide> id: cf1111c1c11feddfaeb3bdef
<ide> title: Add Two Numbers with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript添加两个数字
<add>videoUrl: 'https://scrimba.com/c/cM2KBAG'
<add>forumTopicId: 16650
<add>localeTitle: 加法运算
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>Number</code>是JavaScript中的数据类型,表示数字数据。现在让我们尝试使用JavaScript添加两个数字。当放置在两个数字之间时,JavaScript使用<code>+</code>符号作为加法运算。 <strong>例</strong> <blockquote> myVar = 5 + 10; //分配15 </blockquote></section>
<add><section id='description'>
<add><code>Number</code>是 JavaScript 中的一种数据类型,表示数值。
<add>现在让我们来尝试在 JavaScript 中做加法运算。
<add>JavaScript 中使用<code>+</code>号进行加法运算。
<add><strong>示例</strong>
<add>
<add>```js
<add>myVar = 5 + 10; // assigned 15
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0</code>使总和等于<code>20</code> 。 </section>
<add><section id='instructions'>
<add>改变数字<code>0</code>让变量 sum 的值为<code>20</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>sum</code>应该等于<code>20</code>
<add> - text: <code>sum</code>应该等于<code>20</code>。
<ide> testString: assert(sum === 20);
<del> - text: 使用<code>+</code>运算符
<add> - text: 要使用<code>+</code>运算符。
<ide> testString: assert(/\+/.test(code));
<ide>
<ide> ```
<ide> var sum = 10 + 0;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'sum = '+z;})(sum);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var sum = 10 + 10;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244de
<ide> title: Adding a Default Option in Switch Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 在交换机语句中添加默认选项
<add>videoUrl: 'https://scrimba.com/c/c3JvVfg'
<add>forumTopicId: 16653
<add>localeTitle: 在 Switch 语句中添加默认选项
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在<code>switch</code>语句中,您可能无法将所有可能的值指定为<code>case</code>语句。相反,您可以添加<code>default</code>语句,如果找不到匹配的<code>case</code>语句,将执行该语句。可以把它想象成<code>if/else</code>链中的最后一个<code>else</code>语句。 <code>default</code>语句应该是最后一种情况。 <blockquote> switch(num){ <br>案例值1: <br>语句1; <br>打破; <br>案例值2: <br>语句2; <br>打破; <br> ... <br>默认: <br> defaultStatement; <br>打破; <br> } </blockquote></section>
<add><section id='description'>
<add>在<code>switch</code>语句中你可能无法用 case 来指定所有情况,这时你可以添加 default 语句。当再也找不到 case 匹配的时候 default 语句会执行,非常类似于 if/else 组合中的 else 语句。
<add><code>default</code>语句应该是最后一个 case。
<add>
<add>```js
<add>switch (num) {
<add> case value1:
<add> statement1;
<add> break;
<add> case value2:
<add> statement2;
<add> break;
<add>...
<add> default:
<add> defaultStatement;
<add> break;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个switch语句来设置以下条件的<code>answer</code> : <br> <code>"a"</code> - “苹果” <br> <code>"b"</code> - “鸟” <br> <code>"c"</code> - “猫” <br> <code>default</code> - “东西” </section>
<add><section id='instructions'>
<add>写一个 switch 语句,根据下面的条件来设置<code>answer</code>的switch语句:<br><code>"a"</code> - "apple"<br><code>"b"</code> - "bird"<br><code>"c"</code> - "cat"<br><code>default</code> - "stuff"
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>switchOfStuff("a")</code>的值应为“apple”
<add> - text: <code>switchOfStuff("a")</code>应该有一个值为 "apple"。
<ide> testString: assert(switchOfStuff("a") === "apple");
<del> - text: <code>switchOfStuff("b")</code>的值应为“bird”
<add> - text: <code>switchOfStuff("b")</code>应该有一个值为 "bird"。
<ide> testString: assert(switchOfStuff("b") === "bird");
<del> - text: <code>switchOfStuff("c")</code>的值应为“cat”
<add> - text: <code>switchOfStuff("c")</code>应该有一个值为 "cat"。
<ide> testString: assert(switchOfStuff("c") === "cat");
<del> - text: <code>switchOfStuff("d")</code>的值应为“stuff”
<add> - text: <code>switchOfStuff("d")</code>应该有一个值为 "stuff"。
<ide> testString: assert(switchOfStuff("d") === "stuff");
<del> - text: <code>switchOfStuff(4)</code>的值应为“stuff”
<add> - text: <code>switchOfStuff(4)</code>应该有一个值为 "stuff"。
<ide> testString: assert(switchOfStuff(4) === "stuff");
<del> - text: 您不应该使用任何<code>if</code>或<code>else</code>语句
<add> - text: 不能使用任何<code>if</code>或<code>else</code>表达式。
<ide> testString: assert(!/else/g.test(code) || !/if/g.test(code));
<del> - text: 您应该使用<code>default</code>语句
<add> - text: 你应该有一个<code>default</code>表达式。
<ide> testString: assert(switchOfStuff("string-to-trigger-default-case") === "stuff");
<del> - text: 你应该至少有3个<code>break</code>语句
<add> - text: 你应该有至少 3 个<code>break</code>表达式。
<ide> testString: assert(code.match(/break/g).length > 2);
<ide>
<ide> ```
<ide> switchOfStuff(1);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function switchOfStuff(val) {
<add> var answer = "";
<add>
<add> switch(val) {
<add> case "a":
<add> answer = "apple";
<add> break;
<add> case "b":
<add> answer = "bird";
<add> break;
<add> case "c":
<add> answer = "cat";
<add> break;
<add> default:
<add> answer = "stuff";
<add> }
<add> return answer;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ed
<ide> title: Appending Variables to Strings
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cbQmZfa'
<add>forumTopicId: 16656
<ide> localeTitle: 将变量附加到字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">正如我们可以在字符串<dfn>文字中</dfn>构建多行的字符串一样,我们也可以使用加号等于( <code>+=</code> )运算符将变量附加到字符串。 </section>
<add><section id='description'>
<add>我们不仅可以创建出多行的字符串,还可以使用加等号(<code>+=</code>)运算符来将变量追加到字符串。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">设置<code>someAdjective</code>并使用<code>+=</code>运算符将其附加到<code>myStr</code> 。 </section>
<add><section id='instructions'>
<add>设置变量<code>someAdjective</code>的值,并使用<code>+=</code>运算符把它追加到变量<code>myStr</code>上。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>someAdjective</code>应设置为至少3个字符长的字符串
<add> - text: <code>someAdjective</code>应该是一个至少包含三个字符的字符串。
<ide> testString: assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
<del> - text: 使用<code>+=</code>运算符将<code>someAdjective</code>附加到<code>myStr</code>
<add> - text: 使用<code>+=</code>操作符把<code>someAdjective</code>追加到<code>myStr</code>的后面。
<ide> testString: assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
<ide>
<ide> ```
<ide> var myStr = "Learning to code is ";
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add> var output = [];
<add> if(typeof someAdjective === 'string') {
<add> output.push('someAdjective = "' + someAdjective + '"');
<add> } else {
<add> output.push('someAdjective is not a string');
<add> }
<add> if(typeof myStr === 'string') {
<add> output.push('myStr = "' + myStr + '"');
<add> } else {
<add> output.push('myStr is not a string');
<add> }
<add> return output.join('\n');
<add>})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var anAdjective = "awesome!";
<add>var ourStr = "freeCodeCamp is ";
<add>ourStr += anAdjective;
<add>
<add>var someAdjective = "neat";
<add>var myStr = "Learning to code is ";
<add>myStr += someAdjective;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c3
<ide> title: Assignment with a Returned Value
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 具有返回值的分配
<add>videoUrl: 'https://scrimba.com/c/ce2pEtB'
<add>forumTopicId: 16658
<add>localeTitle: 用返回值来赋值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果您从我们对<a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">使用赋值运算符存储值</a>的讨论中回忆起来<a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">,则在分配</a>值之前,将解决等号右侧的所有内容。这意味着我们可以获取函数的返回值并将其赋值给变量。假设我们预先定义了一个函数<code>sum</code> ,它将两个数字相加,然后: <code>ourSum = sum(5, 12);</code>将调用<code>sum</code>函数,它返回值<code>17</code>并将其分配给<code>ourSum</code>变量。 </section>
<add><section id='description'>
<add>如果你还记得我们在这一节<a href="/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">使用赋值运算符存储值</a>的讨论,赋值之前,先完成等号右边的操作。这意味着我们可把一个函数的返回值,赋值给一个变量。
<add>假设我们预先定义的函数<code>sum</code>其功能就是将两个数字相加,那么:
<add><code>ourSum = sum(5, 12);</code>
<add>将调用<code>sum</code>函数,返回<code>return</code>了一个数值<code>17</code>,然后把它赋值给了<code>ourSum</code>变量。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用参数<code>7</code>调用<code>processArg</code>函数,并将其返回值分配给已<code>processed</code>的变量。 </section>
<add><section id='instructions'>
<add>调用<code>processArg</code>函数并给参数一个值<code>7</code>,然后把返回的值赋值给变量<code>processed</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>processed</code>的值应为<code>2</code>
<add> - text: <code>processed</code>的值应该是<code>2</code>。
<ide> testString: assert(processed === 2);
<del> - text: 您应该将<code>processArg</code>分配给已<code>processed</code>
<del> testString: assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
<add> - text: 你应该把<code>processArg</code>的返回值赋给<code>processed</code>。
<add> testString: assert(/processed\s*=\s*processArg\(\s*7\s*\)\s*;/.test(code));
<ide>
<ide> ```
<ide>
<ide> function processArg(num) {
<ide>
<ide> // Only change code below this line
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> function processArg(num) {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){return "processed = " + processed})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var processed = 0;
<add>
<add>function processArg(num) {
<add> return (num + 3) / 5;
<add>}
<add>
<add>processed = processArg(7);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.chinese.md
<ide> id: 56bbb991ad1ed5201cd392d0
<ide> title: Build JavaScript Objects
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 构建JavaScript对象
<add>videoUrl: 'https://scrimba.com/c/cWGkbtd'
<add>forumTopicId: 16769
<add>localeTitle: 新建 JavaScript 对象
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您之前可能听说过<code>object</code>这个术语。对象类似于<code>arrays</code> ,除了不使用索引访问和修改数据,您可以通过所谓的<code>properties</code>访问对象中的数据。对象对于以结构化方式存储数据很有用,并且可以表示真实世界对象,如猫。这是一个示例cat对象: <blockquote> var cat = { <br> “名字”:“胡须”, <br> “腿”:4, <br> “尾巴”:1, <br> “敌人”:[“水”,“狗”] <br> }; </blockquote>在此示例中,所有属性都存储为字符串,例如 - <code>"name"</code> , <code>"legs"</code>和<code>"tails"</code> 。但是,您也可以使用数字作为属性。您甚至可以省略单字符串属性的引号,如下所示: <blockquote> var anotherObject = { <br>制作:“福特”, <br> 5:“五”, <br> “模特”:“焦点” <br> }; </blockquote>但是,如果您的对象具有任何非字符串属性,JavaScript将自动将它们作为字符串进行类型转换。 </section>
<add><section id='description'>
<add>你之前可能听说过对象<code>object</code>。
<add>对象和数组很相似,数组是通过索引来访问和修改数据,而对象是通过属性来访问和修改数据。
<add>对象适合用来存储结构化数据,就和真实世界的对象一模一样,比如一只猫。
<add>这是一个对象的示例:
<add>
<add>```js
<add>var cat = {
<add> "name": "Whiskers",
<add> "legs": 4,
<add> "tails": 1,
<add> "enemies": ["Water", "Dogs"]
<add>};
<add>```
<add>
<add>在这个示例中所有的属性以字符串的形式储存,例如,<code>"name"</code>、<code>"legs"</code>和<code>"tails"</code>。但是,你也可以使用数字作为属性,你甚至可以省略字符串属性的引号,如下所示:
<add>
<add>```js
<add>var anotherObject = {
<add> make: "Ford",
<add> 5: "five",
<add> "model": "focus"
<add>};
<add>```
<add>
<add>但是,如果你的对象具有任何非字符串属性,JavaScript 将自动将它们转换为字符串类型。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个代表名为<code>myDog</code>的狗的对象,其中包含属性<code>"name"</code> (字符串), <code>"legs"</code> , <code>"tails"</code>和<code>"friends"</code> 。您可以将这些对象属性设置为您想要的任何值,因为<code>"name"</code>是一个字符串, <code>"legs"</code>和<code>"tails"</code>是数字, <code>"friends"</code>是一个数组。 </section>
<add><section id='instructions'>
<add>创建一个叫做<code>myDog</code>的对象,它里面有这些属性:<code>"name"</code>、<code>"legs"</code>、<code>"tails"</code>、<code>"friends"</code>。
<add>你可以设置对象属性为任何值,只需要确保<code>"name"</code>是字符串,<code>"legs"</code>和<code>"tails"</code>是数字,<code>"friends"</code>是数组。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myDog</code>应该包含属性<code>name</code> ,它应该是一个<code>string</code> 。
<add> - text: <code>myDog</code>应该包含<code>name</code>属性,并且是一个字符串<code>string</code>。
<ide> testString: assert((function(z){if(z.hasOwnProperty("name") && z.name !== undefined && typeof z.name === "string"){return true;}else{return false;}})(myDog));
<del> - text: <code>myDog</code>应该包含属性<code>legs</code> ,它应该是一个<code>number</code> 。
<add> - text: <code>myDog</code>应该包含<code>legs</code>属性,并且是一个数字<code>number</code>。
<ide> testString: assert((function(z){if(z.hasOwnProperty("legs") && z.legs !== undefined && typeof z.legs === "number"){return true;}else{return false;}})(myDog));
<del> - text: <code>myDog</code>应该包含属性<code>tails</code> ,它应该是一个<code>number</code> 。
<add> - text: <code>myDog</code>应该包含<code>tails</code>属性,并且是一个数字<code>number</code>。
<ide> testString: assert((function(z){if(z.hasOwnProperty("tails") && z.tails !== undefined && typeof z.tails === "number"){return true;}else{return false;}})(myDog));
<del> - text: <code>myDog</code>应该包含属性<code>friends</code> ,它应该是一个<code>array</code> 。
<add> - text: <code>myDog</code>应该包含<code>friends</code>属性,并且是一个数组<code>array</code>。
<ide> testString: assert((function(z){if(z.hasOwnProperty("friends") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog));
<del> - text: <code>myDog</code>应该只包含所有给定的属性。
<add> - text: <code>myDog</code>应该只包含给出的属性。
<ide> testString: assert((function(z){return Object.keys(z).length === 4;})(myDog));
<ide>
<ide> ```
<ide> var myDog = {
<ide>
<ide>
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var myDog = {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return z;})(myDog);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myDog = {
<add> "name": "Camper",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["everything!"]
<add>};
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244dc
<ide> title: Chaining If Else Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 链接如果其他声明
<add>videoUrl: 'https://scrimba.com/c/caeJgsw'
<add>forumTopicId: 16772
<add>localeTitle: 多个 if else 语句
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>if/else</code>语句可以链接在一起以用于复杂的逻辑。这是多个链式<code>if</code> / <code>else if</code>语句的<dfn>伪代码</dfn> : <blockquote> if( <em>condition1</em> ){ <br> <em>语句1</em> <br> } else if( <em>condition2</em> ){ <br> <em>语句2</em> <br> } else if( <em>condition3</em> ){ <br> <em>声明3</em> <br> 。 。 。 <br> } else { <br> <em>statementN</em> <br> } </blockquote></section>
<add><section id='description'>
<add><code>if/else</code>语句串联在一起可以实现复杂的逻辑,这是多个<code>if/else if</code>语句串联在一起的伪代码:
<add>
<add>```js
<add>if (condition1) {
<add> statement1
<add>} else if (condition2) {
<add> statement2
<add>} else if (condition3) {
<add> statement3
<add>. . .
<add>} else {
<add> statementN
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写入链接<code>if</code> / <code>else if</code>语句以满足以下条件: <code>num < 5</code> - return“Tiny” <br> <code>num < 10</code> - 返回“Small” <br> <code>num < 15</code> - 返回“中” <br> <code>num < 20</code> - 返回“Large” <br> <code>num >= 20</code> - 返回“巨大” </section>
<add><section id='instructions'>
<add>把<code>if</code>/<code>else if</code>语句串联起来实现下面的逻辑:
<add><code>num < 5</code>- return "Tiny"<br><code>num < 10</code>- return "Small"<br><code>num < 15</code>- return "Medium"<br><code>num < 20</code>- return "Large"<br><code>num >= 20</code> - return "Huge"
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该至少有四个<code>else</code>语句
<add> - text: 你应该有至少 4 个<code>else</code>表达式。
<ide> testString: assert(code.match(/else/g).length > 3);
<del> - text: 你应该至少有四个<code>if</code>语句
<add> - text: 你应该有至少 4 个<code>if</code>表达式。
<ide> testString: assert(code.match(/if/g).length > 3);
<del> - text: 你应该至少有一个<code>return</code>语句
<add> - text: 你应该有至少 1 个<code>return</code>表达式。
<ide> testString: assert(code.match(/return/g).length >= 1);
<del> - text: <code>testSize(0)</code>应该返回“Tiny”
<add> - text: <code>testSize(0)</code>应该返回 "Tiny"。
<ide> testString: assert(testSize(0) === "Tiny");
<del> - text: <code>testSize(4)</code>应该返回“Tiny”
<add> - text: <code>testSize(4)</code>应该返回 "Tiny"。
<ide> testString: assert(testSize(4) === "Tiny");
<del> - text: <code>testSize(5)</code>应返回“Small”
<add> - text: <code>testSize(5)</code>应该返回 "Small"。
<ide> testString: assert(testSize(5) === "Small");
<del> - text: <code>testSize(8)</code>应该返回“Small”
<add> - text: <code>testSize(8)</code>应该返回 "Small"。
<ide> testString: assert(testSize(8) === "Small");
<del> - text: <code>testSize(10)</code>应该返回“Medium”
<add> - text: <code>testSize(10)</code>应该返回 "Medium"。
<ide> testString: assert(testSize(10) === "Medium");
<del> - text: <code>testSize(14)</code>应返回“Medium”
<add> - text: <code>testSize(14)</code>应该返回 "Medium"。
<ide> testString: assert(testSize(14) === "Medium");
<del> - text: <code>testSize(15)</code>应该返回“Large”
<add> - text: <code>testSize(15)</code>应该返回 "Large"。
<ide> testString: assert(testSize(15) === "Large");
<del> - text: <code>testSize(17)</code>应该返回“Large”
<add> - text: <code>testSize(17)</code>应该返回 "Large"。
<ide> testString: assert(testSize(17) === "Large");
<del> - text: <code>testSize(20)</code>应该返回“巨大”
<add> - text: <code>testSize(20)</code>应该返回 "Huge"。
<ide> testString: assert(testSize(20) === "Huge");
<del> - text: <code>testSize(25)</code>应该返回“巨大”
<add> - text: <code>testSize(25)</code>应该返回 "Huge"。
<ide> testString: assert(testSize(25) === "Huge");
<ide>
<ide> ```
<ide> function testSize(num) {
<ide>
<ide> // Change this value to test
<ide> testSize(7);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testSize(7);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testSize(num) {
<add> if (num < 5) {
<add> return "Tiny";
<add> } else if (num < 10) {
<add> return "Small";
<add> } else if (num < 15) {
<add> return "Medium";
<add> } else if (num < 20) {
<add> return "Large";
<add> } else {
<add> return "Huge";
<add> }
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.chinese.md
<ide> id: bd7123c9c441eddfaeb4bdef
<ide> title: Comment Your JavaScript Code
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 评论您的JavaScript代码
<add>videoUrl: 'https://scrimba.com/c/c7ynnTp'
<add>forumTopicId: 16783
<add>localeTitle: 给代码添加注释
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">注释是JavaScript有意忽略的代码行。注释是一种很好的方式,可以将注释留给自己和其他人,这些人稍后需要弄清楚代码的作用。在JavaScript中编写注释有两种方法:使用<code>//</code>将告诉JavaScript忽略当前行上的其余文本: <blockquote> //这是一个内嵌评论。 </blockquote>您可以使用<code>/*</code>开头并以<code>*/</code>结尾的多行注释: <blockquote> /* 这是一个<br>多行评论* / </blockquote> <strong>最佳实践</strong> <br>在编写代码时,应定期添加注释以阐明代码部分的功能。良好的评论可以帮助传达您的代码的意图 - 包括他人<em>和</em>未来的自我。 </section>
<add><section id='description'>
<add>被注释的代码块在 JavaScript 之中是不会执行的。在代码中写注释是一个非常好的方式让你自己和其他人理解代码。
<add>JavaScript 中的注释方式有以下两种:
<add>使用<code>//</code>注释掉当前行的代码
<add>
<add>```js
<add>// This is an in-line comment.
<add>```
<add>
<add>你也可以使用多行注释来注释你的代码,以<code>/*</code>开始,用<code>*/</code>来结束,就像下面这样:
<add>
<add>```js
<add>/* This is a
<add>multi-line comment */
<add>```
<add>
<add><strong>最佳实践</strong><br>写代码的时候,要定期添加注释对部分代码块进行解释。适当的注释能让别人和你自己更容易看懂代码。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">尝试创建每种评论类型之一。 </section>
<add><section id='instructions'>
<add>尝试创建这两种类型的注释。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 创建一个包含至少五个字母的<code>//</code>样式注释。
<add> - text: 创建一个<code>//</code>样式的注释, 被注释的文本至少要包含 5 个字符。
<ide> testString: assert(code.match(/(\/\/)...../g));
<del> - text: 创建包含至少五个字母的<code>/* */</code>样式注释。
<add> - text: 创建一个<code>/* */</code>样式的注释, 被注释的文本至少要包含 5 个字符。
<ide> testString: assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
<ide>
<ide> ```
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>// Fake Comment
<add>/* Another Comment */
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d0
<ide> title: Comparison with the Equality Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与平等算子的比较
<add>videoUrl: 'https://scrimba.com/c/cKyVMAL'
<add>forumTopicId: 16784
<add>localeTitle: 相等运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有很多<dfn>比较运算符</dfn>在JavaScript中。所有这些运算符都返回布尔值<code>true</code>或<code>false</code>值。最基本的运算符是等于运算符<code>==</code> 。等于运算符比较两个值,如果它们是等价的则返回<code>true</code>否则返回<code>false</code> 。请注意,相等性与赋值( <code>=</code> )不同,后者将运算符右侧的值分配给左侧的变量。 <blockquote> function equalityTest(myVal){ <br> if(myVal == 10){ <br>返回“平等”; <br> } <br>返回“不等于”; <br> } </blockquote>如果<code>myVal</code>等于<code>10</code> ,则等于运算符返回<code>true</code> ,因此大括号中的代码将执行,函数将返回<code>"Equal"</code> 。否则,该函数将返回<code>"Not Equal"</code> 。为了使JavaScript能够比较两种不同的<code>data types</code> (例如, <code>numbers</code>和<code>strings</code> ),它必须将一种类型转换为另一种类型。这被称为“类型强制”。但是,一旦它完成,它可以比较如下术语: <blockquote> 1 == 1 //是的<br> 1 == 2 //假<br> 1 =='1'//是的<br> “3”== 3 //是的</blockquote></section>
<add><section id='description'>
<add>在 JavaScript 中,有很多<dfn>相互比较的操作</dfn>。所有这些操作符都返回一个<code>true</code>或<code>false</code>值。
<add>最基本的运算符是相等运算符:<code>==</code>。相等运算符比较两个值,如果它们是同等,返回<code>true</code>,如果它们不等,返回<code>false</code>。值得注意的是相等运算符不同于赋值运算符(<code>=</code>),赋值运算符是把等号右边的值赋给左边的变量。
<add>
<add>```js
<add>function equalityTest(myVal) {
<add> if (myVal == 10) {
<add> return "Equal";
<add> }
<add> return "Not Equal";
<add>}
<add>```
<add>
<add>如果<code>myVal</code>等于<code>10</code>,相等运算符会返回<code>true</code>,因此大括号里面的代码会被执行,函数将返回<code>"Equal"</code>。否则,函数返回<code>"Not Equal"</code>。
<add>在 JavaScript 中,为了让两个不同的<code>数据类型</code>(例如<code>数字</code>和<code>字符串</code>)的值可以作比较,它必须把一种类型转换为另一种类型。然而一旦这样做,它可以像下面这样来比较:
<add>
<add>```js
<add>1 == 1 // true
<add>1 == 2 // false
<add>1 == '1' // true
<add>"3" == 3 // true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>equality operator</code>添加到指示的行,以便当<code>val</code>等于<code>12</code>时,函数将返回“Equal” </section>
<add><section id='instructions'>
<add>把<code>相等运算符</code>添加到指定的行,这样当<code>val</code>的值为<code>12</code>的时候,函数会返回"Equal"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testEqual(10)</code>应该返回“Not Equal”
<add> - text: <code>testEqual(10)</code>应该返回 "Not Equal"。
<ide> testString: assert(testEqual(10) === "Not Equal");
<del> - text: <code>testEqual(12)</code>应返回“Equal”
<add> - text: <code>testEqual(12)</code>应该返回 "Equal"。
<ide> testString: assert(testEqual(12) === "Equal");
<del> - text: <code>testEqual("12")</code>应返回“Equal”
<add> - text: <code>testEqual("12")</code>应该返回 "Equal"。
<ide> testString: assert(testEqual("12") === "Equal");
<del> - text: 您应该使用<code>==</code>运算符
<add> - text: 你应该使用<code>==</code>运算符。
<ide> testString: assert(code.match(/==/g) && !code.match(/===/g));
<ide>
<ide> ```
<ide> function testEqual(val) {
<ide>
<ide> // Change this value to test
<ide> testEqual(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testEqual(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testEqual(val) {
<add> if (val == 12) {
<add> return "Equal";
<add> }
<add> return "Not Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d4
<ide> title: Comparison with the Greater Than Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与大于运营商的比较
<add>videoUrl: 'https://scrimba.com/c/cp6GbH4'
<add>forumTopicId: 16786
<add>localeTitle: 大于运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">大于运算符( <code>></code> )比较两个数字的值。如果左边的数字大于右边的数字,则返回<code>true</code> 。否则,它返回<code>false</code> 。与等于运算符一样,大于运算符将在比较时转换数据类型的值。 <strong>例子</strong> <blockquote> 5> 3 //是的<br> 7>'3'//是的<br> 2> 3 //假<br> '1'> 9 //假</blockquote></section>
<add><section id='description'>
<add>使用大于运算符(<code>></code>)来比较两个数字。如果大于运算符左边的数字大于右边的数字,将会返回<code>true</code>。否则,它返回<code>false</code>。
<add>与相等运算符一样,大于运算符在比较的时候,会转换值的数据类型。
<add><strong>例如</strong>
<add>
<add>```js
<add>5 > 3 // true
<add>7 > '3' // true
<add>2 > 3 // false
<add>'1' > 9 // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>greater than</code>运算符添加到指示的行,以便返回语句有意义。 </section>
<add><section id='instructions'>
<add>添加<code>大于</code>运算符到指定的行,使得返回的语句是有意义的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testGreaterThan(0)</code>应返回“10或Under”
<add> - text: <code>testGreaterThan(0)</code>应该返回 "10 or Under"。
<ide> testString: assert(testGreaterThan(0) === "10 or Under");
<del> - text: <code>testGreaterThan(10)</code>应返回“10或Under”
<add> - text: <code>testGreaterThan(10)</code>应该返回 "10 or Under"。
<ide> testString: assert(testGreaterThan(10) === "10 or Under");
<del> - text: <code>testGreaterThan(11)</code>应该返回“Over 10”
<add> - text: <code>testGreaterThan(11)</code>应该返回 "Over 10"。
<ide> testString: assert(testGreaterThan(11) === "Over 10");
<del> - text: <code>testGreaterThan(99)</code>应该返回“Over 10”
<add> - text: <code>testGreaterThan(99)</code>应该返回 "Over 10"。
<ide> testString: assert(testGreaterThan(99) === "Over 10");
<del> - text: <code>testGreaterThan(100)</code>应该返回“Over 10”
<add> - text: <code>testGreaterThan(100)</code>应该返回 "Over 10"。
<ide> testString: assert(testGreaterThan(100) === "Over 10");
<del> - text: <code>testGreaterThan(101)</code>应返回“超过100”
<add> - text: <code>testGreaterThan(101)</code>应该返回 "Over 100"。
<ide> testString: assert(testGreaterThan(101) === "Over 100");
<del> - text: <code>testGreaterThan(150)</code>应该返回“超过100”
<add> - text: <code>testGreaterThan(150)</code>应该返回 "Over 100"。
<ide> testString: assert(testGreaterThan(150) === "Over 100");
<del> - text: 您应该至少使用<code>></code>运算符两次
<add> - text: 你应该使用<code>></code>运算符至少两次。
<ide> testString: assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
<ide>
<ide> ```
<ide> function testGreaterThan(val) {
<ide>
<ide> // Change this value to test
<ide> testGreaterThan(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testGreaterThan(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testGreaterThan(val) {
<add> if (val > 100) { // Change this line
<add> return "Over 100";
<add> }
<add> if (val > 10) { // Change this line
<add> return "Over 10";
<add> }
<add> return "10 or Under";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d5
<ide> title: Comparison with the Greater Than Or Equal To Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与大于或等于运算符的比较
<add>videoUrl: 'https://scrimba.com/c/c6KBqtV'
<add>forumTopicId: 16785
<add>localeTitle: 大于或等于运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>greater than or equal to</code>运算符( <code>>=</code> )比较两个数字的值。如果左边的数字大于或等于右边的数字,则返回<code>true</code> 。否则,它返回<code>false</code> 。与等于运算符一样, <code>greater than or equal to</code>运算符将在比较时转换数据类型。 <strong>例子</strong> <blockquote> 6> = 6 //是的<br> 7> ='3'//是的<br> 2> = 3 //假<br> '7'> = 9 //假</blockquote></section>
<add><section id='description'>
<add>使用<code>大于等于</code>运算符(<code>>=</code>)来比较两个数字的大小。如果大于等于运算符左边的数字比右边的数字大或者相等,它会返回<code>true</code>。否则,它会返回<code>false</code>。
<add>与相等运算符相似,<code>大于等于</code>运算符在比较的时候会转换值的数据类型。
<add><strong>例如</strong>
<add>
<add>```js
<add>6 >= 6 // true
<add>7 >= '3' // true
<add>2 >= 3 // false
<add>'7' >= 9 // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>greater than or equal to</code>运算符添加到指示的行,以便返回语句有意义。 </section>
<add><section id='instructions'>
<add>添加<code>大于等于</code>运算符到指定行,使得函数的返回语句有意义。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testGreaterOrEqual(0)</code>应返回“小于10”
<add> - text: <code>testGreaterOrEqual(0)</code>应该返回 "Less than 10"。
<ide> testString: assert(testGreaterOrEqual(0) === "Less than 10");
<del> - text: <code>testGreaterOrEqual(9)</code>应返回“小于10”
<add> - text: <code>testGreaterOrEqual(9)</code>应该返回 "Less than 10"。
<ide> testString: assert(testGreaterOrEqual(9) === "Less than 10");
<del> - text: <code>testGreaterOrEqual(10)</code>应返回“10或Over”
<add> - text: <code>testGreaterOrEqual(10)</code>应该返回 "10 or Over"。
<ide> testString: assert(testGreaterOrEqual(10) === "10 or Over");
<del> - text: <code>testGreaterOrEqual(11)</code>应返回“10或Over”
<add> - text: <code>testGreaterOrEqual(11)</code>应该返回 "10 or Over"。
<ide> testString: assert(testGreaterOrEqual(11) === "10 or Over");
<del> - text: <code>testGreaterOrEqual(19)</code>应返回“10或Over”
<add> - text: <code>testGreaterOrEqual(19)</code>应该返回 "10 or Over"。
<ide> testString: assert(testGreaterOrEqual(19) === "10 or Over");
<del> - text: <code>testGreaterOrEqual(100)</code>应该返回“20或Over”
<add> - text: <code>testGreaterOrEqual(100)</code>应该返回 "20 or Over"。
<ide> testString: assert(testGreaterOrEqual(100) === "20 or Over");
<del> - text: <code>testGreaterOrEqual(21)</code>应返回“20或Over”
<add> - text: <code>testGreaterOrEqual(21)</code>应该返回 "20 or Over"。
<ide> testString: assert(testGreaterOrEqual(21) === "20 or Over");
<del> - text: 您应该使用<code>>=</code>运算符至少两次
<add> - text: 你应该使用<code>>=</code>运算符至少两次。
<ide> testString: assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
<ide>
<ide> ```
<ide> function testGreaterOrEqual(val) {
<ide>
<ide> // Change this value to test
<ide> testGreaterOrEqual(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testGreaterOrEqual(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testGreaterOrEqual(val) {
<add> if (val >= 20) { // Change this line
<add> return "20 or Over";
<add> }
<add>
<add> if (val >= 10) { // Change this line
<add> return "10 or Over";
<add> }
<add>
<add> return "Less than 10";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d2
<ide> title: Comparison with the Inequality Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与不等式算子的比较
<add>videoUrl: 'https://scrimba.com/c/cdBm9Sr'
<add>forumTopicId: 16787
<add>localeTitle: 不等运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">不等运算符( <code>!=</code> )与等于运算符相反。它意味着“不等于”并返回<code>false</code> ,其中相等性将返回<code>true</code> , <em>反之亦然</em> 。与等式运算符一样,不等式运算符将在比较时转换数据类型的值。 <strong>例子</strong> <blockquote> 1!= 2 //是的<br> 1!=“1”//假<br> 1!='1'//假<br> 1!= true // false <br> 0!= false // false </blockquote></section>
<add><section id='description'>
<add>不相等运算符(<code>!=</code>)与相等运算符是相反的。这意味着不相等运算符中,如果“不为真”并且返回<code>false</code>的地方,在相等运算符中会返回<code>true</code>,<em>反之亦然</em>。与相等运算符类似,不相等运算符在比较的时候也会转换值的数据类型。
<add><strong>例如</strong>
<add>
<add>```js
<add>1 != 2 // true
<add>1 != "1" // false
<add>1 != '1' // false
<add>1 != true // false
<add>0 != false // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>if</code>语句中添加不等式运算符<code>!=</code> ,以便当<code>val</code>不等于<code>99</code>时函数将返回“Not Equal” </section>
<add><section id='instructions'>
<add>在<code>if</code>语句中,添加不相等运算符<code>!=</code>,这样函数在当<code>val</code>不等于 <code>99</code>的时候,会返回 "Not Equal"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testNotEqual(99)</code>应返回“Equal”
<add> - text: <code>testNotEqual(99)</code>应该返回 "Equal"。
<ide> testString: assert(testNotEqual(99) === "Equal");
<del> - text: <code>testNotEqual("99")</code>应该返回“Equal”
<add> - text: <code>testNotEqual("99")</code>应该返回 "Equal"。
<ide> testString: assert(testNotEqual("99") === "Equal");
<del> - text: <code>testNotEqual(12)</code>应该返回“Not Equal”
<add> - text: <code>testNotEqual(12)</code>应该返回 "Not Equal"。
<ide> testString: assert(testNotEqual(12) === "Not Equal");
<del> - text: <code>testNotEqual("12")</code>应该返回“Not Equal”
<add> - text: <code>testNotEqual("12")</code>应该返回 "Not Equal"。
<ide> testString: assert(testNotEqual("12") === "Not Equal");
<del> - text: <code>testNotEqual("bob")</code>应返回“Not Equal”
<add> - text: <code>testNotEqual("bob")</code>应该返回 "Not Equal"。
<ide> testString: assert(testNotEqual("bob") === "Not Equal");
<del> - text: 你应该使用<code>!=</code>运算符
<add> - text: 你应该使用<code>!=</code>运算符。
<ide> testString: assert(code.match(/(?!!==)!=/));
<ide>
<ide> ```
<ide> function testNotEqual(val) {
<ide>
<ide> // Change this value to test
<ide> testNotEqual(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testNotEqual(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testNotEqual(val) {
<add> if (val != 99) {
<add> return "Not Equal";
<add> }
<add> return "Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d6
<ide> title: Comparison with the Less Than Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与小于算子的比较
<add>videoUrl: 'https://scrimba.com/c/cNVRWtB'
<add>forumTopicId: 16789
<add>localeTitle: 小于运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>小于</dfn>运算符( <code><</code> )比较两个数字的值。如果左边的数字小于右边的数字,则返回<code>true</code> 。否则,它返回<code>false</code> 。与等于运算符一样, <dfn>少于</dfn>运算符在比较时转换数据类型。 <strong>例子</strong> <blockquote> 2 <5 //是的<br> '3'<7 //是的<br> 5 <5 //假<br> 3 <2 //假<br> '8'<4 //假</blockquote></section>
<add><section id='description'>
<add>使用<dfn>小于</dfn>运算符(<code><</code>)比较两个数字的大小。如果小于运算符左边的数字比右边的数字小,它会返回<code>true</code>。否则会返回<code>false</code>。与相等运算符类似,<dfn>小于</dfn> 运算符在做比较的时候会转换值的数据类型。
<add><strong>例如</strong>
<add>
<add>```js
<add>2 < 5 // true
<add>'3' < 7 // true
<add>5 < 5 // false
<add>3 < 2 // false
<add>'8' < 4 // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>less than</code>运算符添加到指示的行,以便返回语句有意义。 </section>
<add><section id='instructions'>
<add>添加<code>小于</code>运算符到指定行,使得函数的返回语句有意义。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testLessThan(0)</code>应该返回“25岁以下”
<add> - text: <code>testLessThan(0)</code>应该返回 "Under 25"。
<ide> testString: assert(testLessThan(0) === "Under 25");
<del> - text: <code>testLessThan(24)</code>应该返回“25岁以下”
<add> - text: <code>testLessThan(24)</code>应该返回 "Under 25"。
<ide> testString: assert(testLessThan(24) === "Under 25");
<del> - text: <code>testLessThan(25)</code>应该返回“55岁以下”
<add> - text: <code>testLessThan(25)</code>应该返回 "Under 55"。
<ide> testString: assert(testLessThan(25) === "Under 55");
<del> - text: <code>testLessThan(54)</code>应该返回“55岁以下”
<add> - text: <code>testLessThan(54)</code>应该返回 "Under 55"。
<ide> testString: assert(testLessThan(54) === "Under 55");
<del> - text: <code>testLessThan(55)</code>应返回“55或以上”
<add> - text: <code>testLessThan(55)</code>应该返回 "55 or Over"。
<ide> testString: assert(testLessThan(55) === "55 or Over");
<del> - text: <code>testLessThan(99)</code>应返回“55或以上”
<add> - text: <code>testLessThan(99)</code>应该返回 "55 or Over"。
<ide> testString: assert(testLessThan(99) === "55 or Over");
<del> - text: 您应该至少使用<code><</code>运算符两次
<add> - text: 你应该使用<code><</code>运算符至少两次。
<ide> testString: assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
<ide>
<ide> ```
<ide> function testLessThan(val) {
<ide>
<ide> // Change this value to test
<ide> testLessThan(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testLessThan(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testLessThan(val) {
<add> if (val < 25) { // Change this line
<add> return "Under 25";
<add> }
<add>
<add> if (val < 55) { // Change this line
<add> return "Under 55";
<add> }
<add>
<add> return "55 or Over";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d7
<ide> title: Comparison with the Less Than Or Equal To Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与小于或等于运算符的比较
<add>videoUrl: 'https://scrimba.com/c/cNVR7Am'
<add>forumTopicId: 16788
<add>localeTitle: 小于或等于运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>less than or equal to</code>运算符( <code><=</code> )比较两个数字的值。如果左边的数字小于或等于右边的数字,则返回<code>true</code> 。如果左侧的数字大于右侧的数字,则返回<code>false</code> 。与等于运算符一样, <code>less than or equal to</code>转换数据类型。 <strong>例子</strong> <blockquote> 4 <= 5 //是的<br> '7'<= 7 //是的<br> 5 <= 5 //是的<br> 3 <= 2 //假<br> '8'<= 4 //假</blockquote></section>
<add><section id='description'>
<add>使用<code>小于等于</code>运算符(<code><=</code>)比较两个数字的大小。如果在小于等于运算符左边的数字小于或者等于右边的数字,它会返回<code>true</code>。如果在小于等于运算符左边的数字大于右边的数字,它会返回<code>false</code>。与相等运算符类似,<code>小于等于</code>运算符会转换数据类型。
<add><strong>例如</strong>
<add>
<add>```js
<add>4 <= 5 // true
<add>'7' <= 7 // true
<add>5 <= 5 // true
<add>3 <= 2 // false
<add>'8' <= 4 // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>less than or equal to</code>运算符添加到指示的行,以便返回语句有意义。 </section>
<add><section id='instructions'>
<add>添加<code>小于等于</code>运算符到指定行,使得函数的返回语句有意义。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testLessOrEqual(0)</code>应该返回“小于或等于12”
<add> - text: <code>testLessOrEqual(0)</code>应该返回 "Smaller Than or Equal to 12"。
<ide> testString: assert(testLessOrEqual(0) === "Smaller Than or Equal to 12");
<del> - text: <code>testLessOrEqual(11)</code>应返回“小于或等于12”
<add> - text: <code>testLessOrEqual(11)</code>应该返回 "Smaller Than or Equal to 12"。
<ide> testString: assert(testLessOrEqual(11) === "Smaller Than or Equal to 12");
<del> - text: <code>testLessOrEqual(12)</code>应返回“小于或等于12”
<add> - text: <code>testLessOrEqual(12)</code>应该返回 "Smaller Than or Equal to 12"。
<ide> testString: assert(testLessOrEqual(12) === "Smaller Than or Equal to 12");
<del> - text: <code>testLessOrEqual(23)</code>应返回“小于或等于24”
<add> - text: <code>testLessOrEqual(23)</code>应该返回 "Smaller Than or Equal to 24"。
<ide> testString: assert(testLessOrEqual(23) === "Smaller Than or Equal to 24");
<del> - text: <code>testLessOrEqual(24)</code>应返回“小于或等于24”
<add> - text: <code>testLessOrEqual(24)</code>应该返回 "Smaller Than or Equal to 24"。
<ide> testString: assert(testLessOrEqual(24) === "Smaller Than or Equal to 24");
<del> - text: <code>testLessOrEqual(25)</code>应该返回“超过24”
<add> - text: <code>testLessOrEqual(25)</code>应该返回 "More Than 24"。
<ide> testString: assert(testLessOrEqual(25) === "More Than 24");
<del> - text: <code>testLessOrEqual(55)</code>应该返回“超过24”
<add> - text: <code>testLessOrEqual(55)</code>应该返回 "More Than 24"。
<ide> testString: assert(testLessOrEqual(55) === "More Than 24");
<del> - text: 你应该至少使用<code><=</code>运算符两次
<add> - text: 你应该使用<code><=</code>运算符至少两。
<ide> testString: assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
<ide>
<ide> ```
<ide> testLessOrEqual(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testLessOrEqual(val) {
<add> if (val <= 12) { // Change this line
<add> return "Smaller Than or Equal to 12";
<add> }
<add>
<add> if (val <= 24) { // Change this line
<add> return "Smaller Than or Equal to 24";
<add> }
<add>
<add> return "More Than 24";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d1
<ide> title: Comparison with the Strict Equality Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与严格平等算子的比较
<add>videoUrl: 'https://scrimba.com/c/cy87atr'
<add>forumTopicId: 16790
<add>localeTitle: 严格相等运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">严格相等( <code>===</code> )是相等运算符( <code>==</code> )的对应物。但是,与尝试将两个值转换为常见类型的等式运算符不同,严格相等运算符不执行类型转换。如果要比较的值具有不同的类型,则认为它们不相等,并且严格相等运算符将返回false。 <strong>例子</strong> <blockquote> 3 === 3 //是的<br> 3 ==='3'//假</blockquote>在第二个示例中, <code>3</code>是<code>Number</code>类型, <code>'3'</code>是<code>String</code>类型。 </section>
<add><section id='description'>
<add>严格相等运算符(<code>===</code>)是相对相等操作符(<code>==</code>)的另一种比较操作符。与相等操作符不同的是,它会同时比较元素的值和<code>数据类型</code>。
<add>如果比较的值类型不同,那么在严格相等运算符比较下它们是不相等的,会返回 false 。
<add><strong>示例</strong>
<add>
<add>```js
<add>3 === 3 // true
<add>3 === '3' // false
<add>```
<add>
<add><code>3</code>是一个<code>数字</code>类型的,而<code>'3'</code>是一个<code>字符串</code>类型的,所以 3 不全等于 '3'。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>if</code>语句中使用strict equality运算符,因此当<code>val</code>严格等于<code>7</code>时,函数将返回“Equal” </section>
<add><section id='instructions'>
<add>在<code>if</code>语句值使用严格相等运算符,这样当<code>val</code>严格等于7的时候,函数会返回"Equal"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testStrict(10)</code>应返回“Not Equal”
<add> - text: <code>testStrict(10)</code>应该返回 "Not Equal"。
<ide> testString: assert(testStrict(10) === "Not Equal");
<del> - text: <code>testStrict(7)</code>应返回“Equal”
<add> - text: <code>testStrict(7)</code>应该返回 "Equal"。
<ide> testString: assert(testStrict(7) === "Equal");
<del> - text: <code>testStrict("7")</code>应返回“Not Equal”
<add> - text: <code>testStrict("7")</code>应该返回 "Not Equal"。
<ide> testString: assert(testStrict("7") === "Not Equal");
<del> - text: 您应该使用<code>===</code>运算符
<add> - text: 你应该使用<code>===</code>运算符。
<ide> testString: assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
<ide>
<ide> ```
<ide> function testStrict(val) {
<ide>
<ide> // Change this value to test
<ide> testStrict(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testStrict(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testStrict(val) {
<add> if (val === 7) {
<add> return "Equal";
<add> }
<add> return "Not Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-inequality-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d3
<ide> title: Comparison with the Strict Inequality Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与严格不等式算子的比较
<add>videoUrl: 'https://scrimba.com/c/cKekkUy'
<add>forumTopicId: 16791
<add>localeTitle: 严格不等运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">严格不等式运算符( <code>!==</code> )与严格相等运算符的逻辑相反。它意味着“严格不等于”并返回<code>false</code> ,其中严格相等将返回<code>true</code> , <em>反之亦然</em> 。严格的不等式不会转换数据类型。 <strong>例子</strong> <blockquote> 3!== 3 //假<br> 3!=='3'//是的<br> 4!== 3 //是的</blockquote></section>
<add><section id='description'>
<add>严格不相等运算符(<code>!==</code>)与全等运算符是相反的。这意味着严格不相等并返回<code>false</code>的地方,用严格相等运算符会返回<code>true</code>,<em>反之亦然</em>。严格不相等运算符不会转换值的数据类型。
<add><strong>示例</strong>
<add>
<add>```js
<add>3 !== 3 // false
<add>3 !== '3' // true
<add>4 !== 3 // true
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>strict inequality operator</code>添加到<code>if</code>语句,以便当<code>val</code>不严格等于<code>17</code>时,函数将返回“Not Equal” </section>
<add><section id='instructions'>
<add>在<code>if</code>语句中,添加严格不相等运算符<code>!==</code>,这样如果<code>val</code>与<code>17</code>严格不相等的时候,函数会返回 "Not Equal"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>testStrictNotEqual(17)</code>应返回“Equal”
<add> - text: <code>testStrictNotEqual(17)</code>应该返回 "Equal"。
<ide> testString: assert(testStrictNotEqual(17) === "Equal");
<del> - text: <code>testStrictNotEqual("17")</code>应返回“Not Equal”
<add> - text: <code>testStrictNotEqual("17")</code>应该返回 "Not Equal"。
<ide> testString: assert(testStrictNotEqual("17") === "Not Equal");
<del> - text: <code>testStrictNotEqual(12)</code>应该返回“Not Equal”
<add> - text: <code>testStrictNotEqual(12)</code>应该返回 "Not Equal"。
<ide> testString: assert(testStrictNotEqual(12) === "Not Equal");
<del> - text: <code>testStrictNotEqual("bob")</code>应返回“Not Equal”
<add> - text: <code>testStrictNotEqual("bob")</code>应该返回 "Not Equal"。
<ide> testString: assert(testStrictNotEqual("bob") === "Not Equal");
<del> - text: 你应该使用<code>!==</code>运算符
<add> - text: 应该使用 <code>!==</code> 运算符。
<ide> testString: assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> // Setup
<ide> function testStrictNotEqual(val) {
<del> // Only Change Code Below this Line
<del>
<del> if (val) {
<del>
<del> // Only Change Code Above this Line
<del>
<add> if (val) { // Change this line
<ide> return "Not Equal";
<ide> }
<ide> return "Equal";
<ide> }
<ide>
<ide> // Change this value to test
<ide> testStrictNotEqual(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testStrictNotEqual(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testStrictNotEqual(val) {
<add> if (val !== 17) {
<add> return "Not Equal";
<add> }
<add> return "Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d8
<ide> title: Comparisons with the Logical And Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与逻辑和运算符的比较
<add>videoUrl: 'https://scrimba.com/c/cvbRVtr'
<add>forumTopicId: 16799
<add>localeTitle: 逻辑与运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时你需要一次测试多个东西。当且仅当其左侧和右侧的<dfn>操作数</dfn>为<code>true</code>时, <dfn>逻辑和</dfn>运算符( <code>&&</code> )才返回true。如果将if语句嵌套在另一个语句中,则可以实现相同的效果: <blockquote> if(num> 5){ <br> if(num <10){ <br>返回“是”; <br> } <br> } <br>返回“否”; </blockquote>如果<code>num</code>大于<code>5</code>且小于<code>10</code>则仅返回“Yes”。相同的逻辑可以写成: <blockquote> if(num> 5 && num <10){ <br>返回“是”; <br> } <br>返回“否”; </blockquote></section>
<add><section id='description'>
<add>有时你需要在一次判断中做多个操作。当且仅当运算符的左边和右边都是<code>true</code>,<dfn>逻辑与</dfn> 运算符(<code>&&</code>)才会返回<code>true</code>。
<add>同样的效果可以通过 if 语句的嵌套来实现:
<add>
<add>```js
<add>if (num > 5) {
<add> if (num < 10) {
<add> return "Yes";
<add> }
<add>}
<add>return "No";
<add>```
<add>
<add>只有当<code>num</code>的值在 6 和 9 之间(包括 6 和 9)才会返回 "Yes"。相同的逻辑可被写为:
<add>
<add>```js
<add>if (num > 5 && num < 10) {
<add> return "Yes";
<add>}
<add>return "No";
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将两个if语句合并为一个语句,如果<code>val</code>小于或等于<code>50</code>且大于或等于<code>25</code> ,则返回<code>"Yes"</code> 。否则,将返回<code>"No"</code> 。 </section>
<add><section id='instructions'>
<add>请使用逻辑与运算符把两个 if 语句合并为一个 if 语句,如果<code>val</code>小于或等于<code>50</code>并且大于或等于<code>25</code>,返回<code>"Yes"</code>。否则,将返回<code>"No"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该使用一次<code>&&</code>运算符
<del> testString: assert(code.match(/&&/g).length === 1);
<del> - text: 你应该只有一个<code>if</code>语句
<add> - text: 你应该使用<code>&&</code>运算符一次。
<add> testString: assert(code.match(/&&/g).length === 1,);
<add> - text: 你应该只有一个<code>if</code>表达式。
<ide> testString: assert(code.match(/if/g).length === 1);
<del> - text: <code>testLogicalAnd(0)</code>应返回“否”
<add> - text: <code>testLogicalAnd(0)</code>应该返回 "No"。
<ide> testString: assert(testLogicalAnd(0) === "No");
<del> - text: <code>testLogicalAnd(24)</code>应返回“否”
<add> - text: <code>testLogicalAnd(24)</code>应该返回 "No"。
<ide> testString: assert(testLogicalAnd(24) === "No");
<del> - text: <code>testLogicalAnd(25)</code>应返回“是”
<add> - text: <code>testLogicalAnd(25)</code>应该返回 "Yes"。
<ide> testString: assert(testLogicalAnd(25) === "Yes");
<del> - text: <code>testLogicalAnd(30)</code>应该返回“是”
<add> - text: <code>testLogicalAnd(30)</code>应该返回 "Yes"。
<ide> testString: assert(testLogicalAnd(30) === "Yes");
<del> - text: <code>testLogicalAnd(50)</code>应该返回“是”
<add> - text: <code>testLogicalAnd(50)</code>应该返回 "Yes"。
<ide> testString: assert(testLogicalAnd(50) === "Yes");
<del> - text: <code>testLogicalAnd(51)</code>应返回“否”
<add> - text: <code>testLogicalAnd(51)</code>应该返回 "No"。
<ide> testString: assert(testLogicalAnd(51) === "No");
<del> - text: <code>testLogicalAnd(75)</code>应返回“否”
<add> - text: <code>testLogicalAnd(75)</code>应该返回 "No"。
<ide> testString: assert(testLogicalAnd(75) === "No");
<del> - text: <code>testLogicalAnd(80)</code>应返回“否”
<add> - text: <code>testLogicalAnd(80)</code>应该返回 "No"。
<ide> testString: assert(testLogicalAnd(80) === "No");
<ide>
<ide> ```
<ide> function testLogicalAnd(val) {
<ide>
<ide> // Change this value to test
<ide> testLogicalAnd(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testLogicalAnd(10);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testLogicalAnd(val) {
<add> if (val >= 25 && val <= 50) {
<add> return "Yes";
<add> }
<add> return "No";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244d9
<ide> title: Comparisons with the Logical Or Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 与逻辑或运算符的比较
<add>videoUrl: 'https://scrimba.com/c/cEPrGTN'
<add>forumTopicId: 16800
<add>localeTitle: 逻辑或运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>逻辑OR</dfn>运算符( <code>||</code> )返回<code>true</code> ,如果任一<dfn>操作数</dfn>为<code>true</code> 。否则,它返回<code>false</code> 。 <dfn>逻辑或</dfn>运算符由两个管道符号( <code>|</code> )组成。这通常可以在Backspace和Enter键之间找到。以下模式应该从以前的方法点看起来很熟悉: <blockquote> if(num> 10){ <br>返回“否”; <br> } <br> if(num <5){ <br>返回“否”; <br> } <br>返回“是”; </blockquote>仅当<code>num</code>介于<code>5</code>和<code>10</code>之间(包括5和10)时,才会返回“Yes”。相同的逻辑可以写成: <blockquote> if(num> 10 || num <5){ <br>返回“否”; <br> } <br>返回“是”; </blockquote></section>
<add><section id='description'>
<add>只要<dfn>逻辑或</dfn>运算符<code>||</code>两边任何一个为<code>true</code>,那么它就返回<code>true</code>;否则返回<code>false</code>。
<add><dfn>逻辑或</dfn>运算符由两个管道符号(|)组成。这个按键位于退格键和回车键之间。
<add>下面这样的语句你应该很熟悉:
<add>
<add>```js
<add>if (num > 10) {
<add> return "No";
<add>}
<add>if (num < 5) {
<add> return "No";
<add>}
<add>return "Yes";
<add>```
<add>
<add>只有当<code>num</code>大于等于 5 或小于等于 10 时,函数返回"Yes"。相同的逻辑可以简写成:
<add>
<add>```js
<add>if (num > 10 || num < 5) {
<add> return "No";
<add>}
<add>return "Yes";
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将两个<code>if</code>语句组合成一个语句,如果<code>val</code>不在<code>10</code>和<code>20</code>之间(包括<code>10</code>和<code>20</code> ,则返回<code>"Outside"</code> 。否则,返回<code>"Inside"</code> 。 </section>
<add><section id='instructions'>
<add>请使用逻辑或运算符把两个 if 语句合并为一个 if 语句,如果<code>val</code>不在 10 和 20 之间(包括 10 和 20),返回<code>"Outside"</code>。反之,返回<code>"Inside"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该使用<code>||</code>操作员一次
<add> - text: 你应该使用一次<code>||</code>操作符。
<ide> testString: assert(code.match(/\|\|/g).length === 1);
<del> - text: 你应该只有一个<code>if</code>语句
<add> - text: 你应该只有一个<code>if</code>表达式。
<ide> testString: assert(code.match(/if/g).length === 1);
<del> - text: <code>testLogicalOr(0)</code>应返回“Outside”
<add> - text: <code>testLogicalOr(0)</code>应该返回 "Outside"。
<ide> testString: assert(testLogicalOr(0) === "Outside");
<del> - text: <code>testLogicalOr(9)</code>应返回“Outside”
<add> - text: <code>testLogicalOr(9)</code>应该返回 "Outside"。
<ide> testString: assert(testLogicalOr(9) === "Outside");
<del> - text: <code>testLogicalOr(10)</code>应返回“Inside”
<add> - text: <code>testLogicalOr(10)</code>应该返回 "Inside"。
<ide> testString: assert(testLogicalOr(10) === "Inside");
<del> - text: <code>testLogicalOr(15)</code>应返回“Inside”
<add> - text: <code>testLogicalOr(15)</code>应该返回 "Inside"。
<ide> testString: assert(testLogicalOr(15) === "Inside");
<del> - text: <code>testLogicalOr(19)</code>应该返回“Inside”
<add> - text: <code>testLogicalOr(19)</code>应该返回 "Inside"。
<ide> testString: assert(testLogicalOr(19) === "Inside");
<del> - text: <code>testLogicalOr(20)</code>应该返回“Inside”
<add> - text: <code>testLogicalOr(20)</code>应该返回 "Inside"。
<ide> testString: assert(testLogicalOr(20) === "Inside");
<del> - text: <code>testLogicalOr(21)</code>应该返回“Outside”
<add> - text: <code>testLogicalOr(21)</code>应该返回 "Outside"。
<ide> testString: assert(testLogicalOr(21) === "Outside");
<del> - text: <code>testLogicalOr(25)</code>应返回“Outside”
<add> - text: <code>testLogicalOr(25)</code>应该返回 "Outside"。
<ide> testString: assert(testLogicalOr(25) === "Outside");
<ide>
<ide> ```
<ide> function testLogicalOr(val) {
<ide>
<ide> // Change this value to test
<ide> testLogicalOr(15);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> testLogicalOr(15);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testLogicalOr(val) {
<add> if (val < 10 || val > 20) {
<add> return "Outside";
<add> }
<add> return "Inside";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.chinese.md
<ide> id: 56533eb9ac21ba0edf2244af
<ide> title: Compound Assignment With Augmented Addition
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 具有增强加法的复合赋值
<add>videoUrl: 'https://scrimba.com/c/cDR6LCb'
<add>forumTopicId: 16661
<add>localeTitle: 复合赋值之 +=
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在编程中,通常使用赋值来修改变量的内容。请记住,首先评估等号右侧的所有内容,因此我们可以说: <code>myVar = myVar + 5;</code>添加<code>5</code>到<code>myVar</code> 。由于这是一种常见的模式,因此存在一步完成数学运算和赋值的运算符。一个这样的运算符是<code>+=</code>运算符。 <blockquote> var myVar = 1; <br> myVar + = 5; <br>的console.log(myVar的); //返回6 </blockquote></section>
<add><section id='description'>
<add>在编程当中,通常通过赋值来修改变量的内容。记住,赋值时 Javascript 会先计算<code>=</code>右边的内容,所以我们可以写这样的语句:
<add><code>myVar = myVar + 5;</code>
<add>以上是最常见的运算赋值语句,即先运算、再赋值。还有一类操作符是一步到位既做运算也赋值的。
<add>其中一种就是<code>+=</code>运算符。
<add>
<add>```js
<add>var myVar = 1;
<add>myVar += 5;
<add>console.log(myVar); // Returns 6
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">转换<code>a</code> , <code>b</code>和<code>c</code>的赋值以使用<code>+=</code>运算符。 </section>
<add><section id='instructions'>
<add>使用<code>+=</code>操作符实现同样的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>a</code>应该等于<code>15</code>
<add> - text: <code>a</code>应该等于<code>15</code>。
<ide> testString: assert(a === 15);
<del> - text: <code>b</code>应该等于<code>26</code>
<add> - text: <code>b</code>应该等于<code>26</code>。
<ide> testString: assert(b === 26);
<del> - text: <code>c</code>应该等于<code>19</code>
<add> - text: <code>c</code>应该等于<code>19</code>。
<ide> testString: assert(c === 19);
<del> - text: 您应该为每个变量使用<code>+=</code>运算符
<add> - text: 你应该对每个变量使用<code>+=</code>操作符。
<ide> testString: assert(code.match(/\+=/g).length === 3);
<del> - text: 不要修改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code));
<ide>
<ide> ```
<ide> c = c + 7;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 3;
<add>var b = 17;
<add>var c = 12;
<add>
<add>a += 12;
<add>b += 9;
<add>c += 7;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-division.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b2
<ide> title: Compound Assignment With Augmented Division
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 具有增广划分的复合赋值
<add>videoUrl: 'https://scrimba.com/c/c2QvKT2'
<add>forumTopicId: 16659
<add>localeTitle: 复合赋值之 /=
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>/=</code>运算符将变量除以另一个数字。 <code>myVar = myVar / 5;</code>将<code>myVar</code>除以<code>5</code> 。这可以改写为: <code>myVar /= 5;</code> </section>
<add><section id='description'>
<add><code>/=</code>操作符是让变量与另一个数相除并赋值。
<add><code>myVar = myVar / 5;</code>
<add>变量<code>myVar</code>等于自身除以<code>5</code>的值。等价于:
<add><code>myVar /= 5;</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">转换<code>a</code> , <code>b</code>和<code>c</code>的赋值以使用<code>/=</code>运算符。 </section>
<add><section id='instructions'>
<add>使用<code>/=</code>操作符实现同样的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>a</code>应该等于<code>4</code>
<add> - text: <code>a</code>应该等于<code>4</code>。
<ide> testString: assert(a === 4);
<del> - text: <code>b</code>应该等于<code>27</code>
<add> - text: <code>b</code>应该等于<code>27</code>。
<ide> testString: assert(b === 27);
<del> - text: <code>c</code>应该等于<code>3</code>
<add> - text: <code>c</code>应该等于<code>3</code>。
<ide> testString: assert(c === 3);
<del> - text: 您应该为每个变量使用<code>/=</code>运算符
<add> - text: 应该对每个变量使用<code>/=</code>操作符。
<ide> testString: assert(code.match(/\/=/g).length === 3);
<del> - text: 不要修改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code));
<ide>
<ide> ```
<ide> c = c / 11;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 48;
<add>var b = 108;
<add>var c = 33;
<add>
<add>a /= 12;
<add>b /= 4;
<add>c /= 11;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-multiplication.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b1
<ide> title: Compound Assignment With Augmented Multiplication
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 具有增广乘法的复合赋值
<add>videoUrl: 'https://scrimba.com/c/c83vrfa'
<add>forumTopicId: 16662
<add>localeTitle: 复合赋值之 *=
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>*=</code>运算符将变量乘以数字。 <code>myVar = myVar * 5;</code>将<code>myVar</code>乘以<code>5</code> 。这可以改写为: <code>myVar *= 5;</code> </section>
<add><section id='description'>
<add><code>*=</code>操作符是让变量与一个数相乘并赋值。
<add><code>myVar = myVar * 5;</code>
<add>变量<code>myVar</code>等于自身与数值<code>5</code>相乘的值。也可以写作这样的形式:
<add><code>myVar *= 5;</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">转换<code>a</code> , <code>b</code>和<code>c</code>的赋值以使用<code>*=</code>运算符。 </section>
<add><section id='instructions'>
<add>使用<code>*=</code>操作符实现同样的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>a</code>应该等于<code>25</code>
<add> - text: <code>a</code>应该等于<code>25</code>。
<ide> testString: assert(a === 25);
<del> - text: <code>b</code>应该等于<code>36</code>
<add> - text: <code>b</code>应该等于<code>36</code>。
<ide> testString: assert(b === 36);
<del> - text: <code>c</code>应该等于<code>46</code>
<add> - text: <code>c</code>应该等于<code>46</code>。
<ide> testString: assert(c === 46);
<del> - text: 您应该为每个变量使用<code>*=</code>运算符
<add> - text: 应该对每个变量使用<code>*=</code>操作符。
<ide> testString: assert(code.match(/\*=/g).length === 3);
<del> - text: 不要修改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\.6;/.test(code));
<ide>
<ide> ```
<ide> a = a * 5;
<ide> b = 3 * b;
<ide> c = c * 10;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> c = c * 10;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 5;
<add>var b = 12;
<add>var c = 4.6;
<add>
<add>a *= 5;
<add>b *= 3;
<add>c *= 10;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-subtraction.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b0
<ide> title: Compound Assignment With Augmented Subtraction
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 具有增广减法的复合赋值
<add>videoUrl: 'https://scrimba.com/c/c2Qv7AV'
<add>forumTopicId: 16660
<add>localeTitle: 复合赋值之 -=
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">与<code>+=</code>运算符一样, <code>-=</code>从变量中减去一个数字。 <code>myVar = myVar - 5;</code>将从<code>myVar</code>减去<code>5</code> 。这可以改写为: <code>myVar -= 5;</code> </section>
<add><section id='description'>
<add>与<code>+=</code>操作符类似,<code>-=</code>操作符用来对一个变量进行减法赋值操作。
<add><code>myVar = myVar - 5;</code>
<add>变量<code>myVar</code>等于自身减去<code>5</code>的值。也可以写成这种形式:
<add><code>myVar -= 5;</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">转换<code>a</code> , <code>b</code>和<code>c</code>的赋值以使用<code>-=</code>运算符。 </section>
<add><section id='instructions'>
<add>使用<code>-=</code>操作符实现同样的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>a</code>应该等于<code>5</code>
<add> - text: <code>a</code>应该等于<code>5</code>。
<ide> testString: assert(a === 5);
<del> - text: <code>b</code>应该等于<code>-6</code>
<add> - text: <code>b</code>应该等于<code>-6</code>。
<ide> testString: assert(b === -6);
<del> - text: <code>c</code>应该等于<code>2</code>
<add> - text: <code>c</code>应该等于<code>2</code>。
<ide> testString: assert(c === 2);
<del> - text: 您应该为每个变量使用<code>-=</code>运算符
<add> - text: 应该对每个变量使用<code>-=</code>操作符。
<ide> testString: assert(code.match(/-=/g).length === 3);
<del> - text: 不要修改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code));
<ide>
<ide> ```
<ide> a = a - 6;
<ide> b = b - 15;
<ide> c = c - 1;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> c = c - 1;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = " + c; })(a,b,c);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 11;
<add>var b = 9;
<add>var c = 3;
<add>
<add>a -= 6;
<add>b -= 15;
<add>c -= 1;
<add>
<add>
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b7
<ide> title: Concatenating Strings with Plus Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 用Plus运算符连接字符串
<add>videoUrl: 'https://scrimba.com/c/cNpM8AN'
<add>forumTopicId: 16802
<add>localeTitle: 用加号运算符连接字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中,当<code>+</code>运算符与<code>String</code>值一起使用时,它被称为<dfn>连接</dfn>运算符。您可以通过<dfn>将</dfn>它们<dfn>连接</dfn>在一起来构建其他字符串中的新字符串。 <strong>例</strong> <blockquote> “我叫艾伦,'+'我连接起来。” </blockquote> <strong>注意</strong> <br>留意空间。连接不会在连接字符串之间添加空格,因此您需要自己添加它们。 </section>
<add><section id='description'>
<add>在 JavaScript 中,当对一个<code>String</code>类型的值使用<code>+</code>操作符的时候,它被称作 <dfn>拼接操作符</dfn>。你可以通过<dfn>拼接</dfn>其他字符串来创建一个新的字符串。
<add><strong>示例</strong>
<add>
<add>```js
<add>'My name is Alan,' + ' I concatenate.'
<add>```
<add>
<add><strong>提示</strong><br>注意空格。拼接操作不会在两个字符串之间添加空格,所以想加上空格的话,你需要自己在字符串里面添加。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">从字符串构建<code>myStr</code> <code>"This is the start. "</code>和<code>"This is the end."</code>使用<code>+</code>运算符。 </section>
<add><section id='instructions'>
<add>使用<code>+</code>操作符,把字符串<code>"This is the start. "</code>和<code>"This is the end."</code>连接起来并赋值给变量<code>myStr</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myStr</code>应该有一个值<code>This is the start. This is the end.</code>
<add> - text: <code>myStr</code>的值应该是<code>This is the start. This is the end.</code>。
<ide> testString: assert(myStr === "This is the start. This is the end.");
<del> - text: 使用<code>+</code>运算符构建<code>myStr</code>
<add> - text: 使用<code>+</code>操作符构建<code>myStr</code>。
<ide> testString: assert(code.match(/(["']).*(["'])\s*\+\s*(["']).*(["'])/g).length > 1);
<del> - text: 应使用<code>var</code>关键字创建<code>myStr</code> 。
<add> - text: <code>myStr</code>应该被<code>var</code>关键字声明。
<ide> testString: assert(/var\s+myStr/.test(code));
<del> - text: 确保将结果分配给<code>myStr</code>变量。
<add> - text: 确保有给<code>myStr</code>赋值。
<ide> testString: assert(/myStr\s*=/.test(code));
<ide>
<ide> ```
<ide> var ourStr = "I come first. " + "I come second.";
<ide>
<ide> var myStr;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add> if(typeof myStr === 'string') {
<add> return 'myStr = "' + myStr + '"';
<add> } else {
<add> return 'myStr is not a string';
<add> }
<add>})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourStr = "I come first. " + "I come second.";
<add>var myStr = "This is the start. " + "This is the end.";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b8
<ide> title: Concatenating Strings with the Plus Equals Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用Plus Equals运算符连接字符串
<add>videoUrl: 'https://scrimba.com/c/cbQmmC4'
<add>forumTopicId: 16803
<add>localeTitle: 用 += 运算符连接字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们还可以使用<code>+=</code>运算符将字符串<dfn>连接</dfn>到现有字符串变量的末尾。这对于在多行上打破长字符串非常有帮助。 <strong>注意</strong> <br>留意空间。连接不会在连接字符串之间添加空格,因此您需要自己添加它们。 </section>
<add><section id='description'>
<add>我们还可以使用<code>+=</code>运算符来<dfn>concatenate</dfn>(拼接)字符串到现有字符串的结尾。对于那些被分割成几段的长的字符串来说,这一操作是非常有用的。
<add><strong>提示</strong><br>注意空格。拼接操作不会在两个字符串之间添加空格,所以如果想要加上空格的话,你需要自己在字符串里面添加。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">通过连接这两个字符串来构建<code>myStr</code>几行: <code>"This is the first sentence. "</code>和<code>"This is the second sentence."</code>使用<code>+=</code>运算符。使用<code>+=</code>运算符,类似于它在编辑器中的显示方式。首先将第一个字符串分配给<code>myStr</code> ,然后添加第二个字符串。 </section>
<add><section id='instructions'>
<add>通过使用<code>+=</code>操作符来连接这两个字符串:<br><code>"This is the first sentence. "</code>和<code>"This is the second sentence."</code>并赋给变量<code>myStr</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myStr</code>应该有一个值<code>This is the first sentence. This is the second sentence.</code>
<add> - text: <code>myStr</code>的值应该是<code>This is the first sentence. This is the second sentence.</code>。
<ide> testString: assert(myStr === "This is the first sentence. This is the second sentence.");
<del> - text: 使用<code>+=</code>运算符构建<code>myStr</code>
<add> - text: 使用<code>+=</code>操作符创建<code>myStr</code>变量。
<ide> testString: assert(code.match(/\w\s*\+=\s*["']/g).length > 1 && code.match(/\w\s*\=\s*["']/g).length > 1);
<ide>
<ide> ```
<ide> ourStr += "I come second.";
<ide>
<ide> var myStr;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add> if(typeof myStr === 'string') {
<add> return 'myStr = "' + myStr + '"';
<add> } else {
<add> return 'myStr is not a string';
<add> }
<add>})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourStr = "I come first. ";
<add>ourStr += "I come second.";
<add>
<add>var myStr = "This is the first sentence. ";
<add>myStr += "This is the second sentence.";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b9
<ide> title: Constructing Strings with Variables
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cqk8rf4'
<add>forumTopicId: 16805
<ide> localeTitle: 用变量构造字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时您需要构建一个字符串, <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a>样式。通过使用连接运算符( <code>+</code> ),您可以将一个或多个变量插入到正在构建的字符串中。 </section>
<add><section id='description'>
<add>有时候你需要创建一个类似<a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">Mad Libs</a>(填词游戏)风格的字符串。通过使用连接运算符<code> + </code>,你可以插入一个或多个变量来组成一个字符串。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>myName</code>设置为等于您的名字的字符串,并在字符串<code>"My name is "</code>和<code>" and I am well!"</code>之间用<code>myName</code>构建<code>myStr</code> <code>" and I am well!"</code> </section>
<add><section id='instructions'>
<add>把你的名字赋值给变量<code>myName</code>,然后把变量<code>myName</code>插入到字符串<code>"My name is "</code>和<code>" and I am well!"</code>之间,并把连接后的结果赋值给变量<code>myStr</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myName</code>应设置为至少3个字符长的字符串
<add> - text: <code>myName</code>至少要包含三个字符。
<ide> testString: assert(typeof myName !== 'undefined' && myName.length > 2);
<del> - text: 使用两个<code>+</code>运算符在其中构建<code>myStr</code> with <code>myName</code>
<add> - text: 使用两个<code>+</code>操作符创建包含<code>myName</code>的<code>myStr</code>变量。
<ide> testString: assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
<ide>
<ide> ```
<ide> var ourStr = "Hello, our name is " + ourName + ", how are you?";
<ide> var myName;
<ide> var myStr;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add> var output = [];
<add> if(typeof myName === 'string') {
<add> output.push('myName = "' + myName + '"');
<add> } else {
<add> output.push('myName is not a string');
<add> }
<add> if(typeof myStr === 'string') {
<add> output.push('myStr = "' + myStr + '"');
<add> } else {
<add> output.push('myStr is not a string');
<add> }
<add> return output.join('\n');
<add>})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myName = "Bob";
<add>var myStr = "My name is " + myName + " and I am well!";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.chinese.md
<ide> id: 56105e7b514f539506016a5e
<ide> title: Count Backwards With a For Loop
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 用For循环向后计数
<add>videoUrl: 'https://scrimba.com/c/c2R6BHa'
<add>forumTopicId: 16808
<add>localeTitle: 使用 For 循环反向遍历数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">只要我们可以定义正确的条件,for循环也可以向后计数。为了向后计数两次,我们需要更改<code>initialization</code> , <code>condition</code>和<code>final-expression</code> 。我们将从<code>i = 10</code>开始并在<code>i > 0</code>循环。我们将递减<code>i</code> 2每个回路与<code>i -= 2</code> 。 <blockquote> var ourArray = []; <br> for(var i = 10; i> 0; i- = 2){ <br> ourArray.push(ⅰ); <br> } </blockquote> <code>ourArray</code>现在包含<code>[10,8,6,4,2]</code> 。让我们改变<code>initialization</code>和<code>final-expression</code>这样我们就可以向后计数两位奇数。 </section>
<add><section id='description'>
<add>for循环也可以逆向迭代,只要我们定义好合适的条件。
<add>为了让每次倒数递减 2,我们需要改变我们的<code>初始化</code>,<code>条件判断</code>和<code>计数器</code>。
<add>我们让<code>i = 10</code>,并且当<code>i > 0</code>的时候才继续循环。我们使用<code>i -= 2</code>来让<code>i</code>每次循环递减 2。
<add>
<add>```js
<add>var ourArray = [];
<add>for (var i=10; i > 0; i-=2) {
<add> ourArray.push(i);
<add>}
<add>```
<add>
<add>循环结束后,<code>ourArray</code>的值为<code>[10,8,6,4,2]</code>。
<add>让我们改变<code>初始化</code>和<code>计数器</code>,这样我们就可以按照奇数从后往前两两倒着数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>for</code>循环将奇数从9到1推送到<code>myArray</code> 。 </section>
<add><section id='instructions'>
<add>使用一个<code>for</code>循环,把 9 到 1 的奇数添加进<code>myArray</code>。
<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\s*\(/g).length > 1);
<del> - text: 你应该使用数组方法<code>push</code> 。
<add> - text: 你应该使用数组方法<code>push</code>。
<ide> testString: assert(code.match(/myArray.push/));
<del> - text: '<code>myArray</code>应该等于<code>[9,7,5,3,1]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[9,7,5,3,1]</code>。
<ide> testString: assert.deepEqual(myArray, [9,7,5,3,1]);
<ide>
<ide> ```
<ide> var myArray = [];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourArray = [];
<add>for (var i = 10; i > 0; i -= 2) {
<add> ourArray.push(i);
<add>}
<add>var myArray = [];
<add>for (var i = 9; i > 0; i -= 2) {
<add> myArray.push(i);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.chinese.md
<ide> id: 565bbe00e9cc8ac0725390f4
<ide> title: Counting Cards
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 计数卡
<add>videoUrl: 'https://scrimba.com/c/c6KE7ty'
<add>forumTopicId: 16809
<add>localeTitle: 21点游戏
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在赌场游戏Blackjack中,玩家可以通过跟踪牌组中剩余的高牌和低牌的相对数量来获得优势。这称为<a href="https://en.wikipedia.org/wiki/Card_counting" target="_blank">卡计数</a> 。在牌组中剩下更多高牌有利于玩家。根据下表为每张卡分配一个值。当计数为正数时,玩家应该下注。当计数为零或负数时,玩家应该下注低。 <table class="table table-striped"><thead><tr><th>计数变化</th><th>牌</th></tr></thead><tbody><tr><td> +1 </td><td> 2,3,4,5,6 </td></tr><tr><td> 0 </td><td> 7,8,9 </td></tr><tr><td> -1 </td><td> 10,'J','Q','K','A' </td></tr></tbody></table>你会写一个卡计数功能。它将接收一个<code>card</code>参数,可以是数字或字符串,并根据卡的值递增或递减全局<code>count</code>变量(参见表格)。然后,该函数将返回一个包含当前计数的字符串,如果计数为正则返回字符串<code>Bet</code> ,如果计数为零或为负,则返回<code>Hold</code> 。当前计数和玩家的决定( <code>Bet</code>或<code>Hold</code> )应该由一个空格分隔。 <strong>示例输出</strong> <br> <code>-3 Hold</code> <br> <code>5 Bet</code> <strong>提示</strong> <br>当值为7,8或9时,请勿将<code>count</code>重置为0。 <br>不要返回数组。 <br>不要在输出中包含引号(单引号或双引号)。 </section>
<add><section id='description'>
<add>在赌场 21 点游戏中,玩家可以通过计算牌桌上已经发放的卡牌的高低值来让自己在游戏中保持优势,这就叫<a href='https://www.douban.com/note/273781969/' target='_blank'> 21 点算法</a>。
<add>根据下面的表格,每张卡牌都分配了一个值。如果卡牌的值<count>大于 0,那么玩家应该追加赌注。反之,追加少许赌注甚至不追加赌注。
<add><table class="table table-striped"><thead><tr><th>Count Change</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
<add>你需要写一个函数实现 21 点算法,它根据参数<code>card</code>的值来递增或递减变量<code>count</code>,函数返回一个由当前<code>count</code>和<code>Bet</code>(<code>count>0</code>)或<code>Hold</code>(<code>count<=0</code>)拼接的字符串。注意<code>count</code>和<code>"Bet"</code>或<code>Hold</code>应该用空格分开。
<add>
<add><strong>例如:</strong><br><code>-3 Hold<br>5 Bet</code>
<add>
<add><strong>提示</strong><br>既然 card 的值为 7、8、9 时,count 值不变,那我们就可以忽略这种情况。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 牌序列<code>5 Bet</code>应该返回<code>5 Bet</code>
<add> - text: Cards Sequence 2, 3, 4, 5, 6 应该返回<code>5 Bet</code>。
<ide> testString: assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === "5 Bet") {return true;} return false; })());
<del> - text: '卡片序列7,8,9应返回<code>0 Hold</code>'
<add> - text: Cards Sequence 7, 8, 9 应该返回 <code>0 Hold</code>。
<ide> testString: assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === "0 Hold") {return true;} return false; })());
<del> - text: 卡序列10,J,Q,K,A应返回<code>-5 Hold</code>
<add> - text: Cards Sequence 10, J, Q, K, A 应该返回 <code>-5 Hold</code>。
<ide> testString: assert((function(){ count = 0; cc(10);cc('J');cc('Q');cc('K');var out = cc('A'); if(out === "-5 Hold") {return true;} return false; })());
<del> - text: '卡序列3,7,Q,8,A应返回<code>-1 Hold</code>'
<add> - text: Cards Sequence 3, 7, Q, 8, A 应该返回 <code>-1 Hold</code>。
<ide> testString: assert((function(){ count = 0; cc(3);cc(7);cc('Q');cc(8);var out = cc('A'); if(out === "-1 Hold") {return true;} return false; })());
<del> - text: 牌序列2,J, <code>1 Bet</code>应该返回<code>1 Bet</code>
<add> - text: Cards Sequence 2, J, 9, 2, 7 应该返回 <code>1 Bet</code>。
<ide> testString: assert((function(){ count = 0; cc(2);cc('J');cc(9);cc(2);var out = cc(7); if(out === "1 Bet") {return true;} return false; })());
<del> - text: 牌序列<code>1 Bet</code>应该返回<code>1 Bet</code>
<add> - text: Cards Sequence 2, 2, 10 应该返回 <code>1 Bet</code>。
<ide> testString: assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === "1 Bet") {return true;} return false; })());
<del> - text: '卡序列3,2,A,10,K应返回<code>-1 Hold</code>'
<add> - text: Cards Sequence 3, 2, A, 10, K 应该返回 <code>-1 Hold</code>。
<ide> testString: assert((function(){ count = 0; cc(3);cc(2);cc('A');cc(10);var out = cc('K'); if(out === "-1 Hold") {return true;} return false; })());
<ide>
<ide> ```
<ide> function cc(card) {
<ide> // Add/remove calls to test your function.
<ide> // Note: Only the last will display
<ide> cc(2); cc(3); cc(7); cc('K'); cc('A');
<del>
<ide> ```
<ide>
<ide> </div>
<ide> cc(2); cc(3); cc(7); cc('K'); cc('A');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var count = 0;
<add>function cc(card) {
<add> switch(card) {
<add> case 2:
<add> case 3:
<add> case 4:
<add> case 5:
<add> case 6:
<add> count++;
<add> break;
<add> case 10:
<add> case 'J':
<add> case 'Q':
<add> case 'K':
<add> case 'A':
<add> count--;
<add> }
<add> if(count > 0) {
<add> return count + " Bet";
<add> } else {
<add> return count + " Hold";
<add> }
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.chinese.md
<ide> id: cf1391c1c11feddfaeb4bdef
<ide> title: Create Decimal Numbers with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript创建十进制数
<add>videoUrl: 'https://scrimba.com/c/ca8GEuW'
<add>forumTopicId: 16826
<add>localeTitle: 创建一个小数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们也可以在变量中存储十进制数。十进制数有时称为<dfn>浮点数</dfn>或<dfn>浮点数</dfn> 。 <strong>注意</strong> <br>并非所有实数都可以准确地以<dfn>浮点</dfn>表示。这可能导致舍入错误。 <a href="https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" target="_blank">细节在这里</a> 。 </section>
<add><section id='description'>
<add>我们也可以把小数存储到变量中。小数也被称作<dfn>浮点数</dfn> 。
<add><strong>提示</strong><br>不是所有的实数都可以用 <dfn>浮点数</dfn> 来表示。因为可能存在四舍五入的错误,<a href="https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems" target="_blank">详情查看</a>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个变量<code>myDecimal</code>并给它一个带小数部分的十进制值(例如<code>5.7</code> )。 </section>
<add><section id='instructions'>
<add>创建一个变量<code>myDecimal</code>并给它赋值一个浮点数。(例如<code>5.21</code>)。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 使用JavaScript创建十进制数
<ide> tests:
<ide> - text: <code>myDecimal</code>应该是一个数字。
<ide> testString: assert(typeof myDecimal === "number");
<del> - text: <code>myDecimal</code>应该有一个小数点
<del> testString: assert(myDecimal % 1 != 0);
<add> - text: <code>myDecimal</code>应该包含小数点。
<add> testString: assert(myDecimal % 1 != 0);
<ide>
<ide> ```
<ide>
<ide> var ourDecimal = 5.7;
<ide>
<ide> // Only change code below this line
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var ourDecimal = 5.7;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){if(typeof myDecimal !== "undefined"){return myDecimal;}})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myDecimal = 9.9;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.chinese.md
<ide> id: bd7123c9c443eddfaeb5bdef
<ide> title: Declare JavaScript Variables
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 声明JavaScript变量
<add>videoUrl: 'https://scrimba.com/c/cNanrHq'
<add>forumTopicId: 17556
<add>localeTitle: 声明变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在计算机科学中, <dfn>数据</dfn>是对计算机有意义的任何东西。 JavaScript提供了七种不同的<dfn>数据类型</dfn> ,它们是<code>undefined</code> , <code>null</code> , <code>boolean</code> , <code>string</code> , <code>symbol</code> , <code>number</code>和<code>object</code> 。例如,计算机区分数字(例如数字<code>12</code> )和<code>strings</code> (例如<code>"12"</code> , <code>"dog"</code>或<code>"123 cats"</code> ,它们是字符集合。计算机可以对数字执行数学运算,但不能对字符串执行数学运算。 <dfn>变量</dfn>允许计算机以动态方式存储和操作数据。他们通过使用“标签”指向数据而不是使用数据本身来做到这一点。七种数据类型中的任何一种都可以存储在变量中。 <code>Variables</code>类似于您在数学中使用的x和y变量,这意味着它们是表示我们想要引用的数据的简单名称。计算机<code>variables</code>与数学<code>variables</code>不同之处在于它们可以在不同时间存储不同的值。我们告诉JavaScript通过将关键字<code>var</code>放在它前面来创建或<dfn>声明</dfn>变量,如下所示: <blockquote> var ourName; </blockquote>创建一个名为<code>ourName</code>的<code>variable</code> 。在JavaScript中,我们以分号结束语句。 <code>Variable</code>名可以由数字,字母和<code>$</code>或<code>_</code> ,但不能包含空格或以数字开头。 </section>
<add><section id='description'>
<add>在计算机科学中,<dfn>数据</dfn>就是一切,它对于计算机意义重大。JavaScript 提供七种不同的<dfn>数据类型</dfn>,它们是<code>undefined</code>(未定义), <code>null</code>(空),<code>boolean</code>(布尔型),<code>string</code>(字符串),<code>symbol</code>(符号),<code>number</code>(数字),和<code>object</code>(对象)。
<add>例如,计算机区分数字和字符集合的字符串,例如数字<code>12</code>和字符串<code>"12"</code>,<code>"dog"</code>或<code>"123 cats"</code>。计算机可以对数字执行数学运算,但不能对字符串执行数学运算。
<add><dfn>变量</dfn>允许计算机以一种动态的形式来存储和操作数据,通过操作指向数据的指针而不是数据本身来避免了内存泄露,以上的七种数据类型都可以存储到一个变量中。
<add><code>变量</code>非常类似于你在数学中使用的 x,y 变量,都是以一个简单命名的名称来代替我们赋值给它的数据。计算机中的<code>变量</code>与数学中的变量不同的是,计算机可以在不同的时间存储不同类型的变量。
<add>通过在变量的前面使用关键字<code>var</code>,声明一个变量,例如:
<add>
<add>```js
<add>var ourName;
<add>```
<add>
<add>上面代码的意思是创建一个名为<code>ourName</code>的<code>变量</code>,在 JavaScript 中我们以分号结束语句。
<add><code>变量</code>名称可以由数字、字母、美元符号<code>$</code> 或者 下划线<code>_</code>组成,但是不能包含空格或者以数字为开头。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>var</code>关键字创建名为<code>myName</code>的变量。 <strong>暗示</strong> <br>如果你遇到<code>ourName</code>查看我们的<code>ourName</code>示例。 </section>
<add><section id='instructions'>
<add>使用<code>var</code> 关键字来创建一个名为<code>myName</code>的变量。
<add><strong>提示</strong><br>如果遇到困难了,请看下<code>ourName</code>的例子是怎么写的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该使用<code>var</code>关键字声明<code>myName</code> ,以分号结尾
<del> testString: assert(/var\s+myName\s*;/.test(code));
<add> - text: 你需要使用<code>var</code>关键字定义一个变量<code>myName</code>,并使用分号结尾。
<add> testString: assert(/var\s+myName\s*;/.test(code), '你需要使用<code>var</code>关键字定义一个变量<code>myName</code>。并使用分号结尾。');
<ide>
<ide> ```
<ide>
<ide> var ourName;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myName !== "undefined"){(function(v){return v;})(myName);}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myName;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.chinese.md
<ide> id: bd7123c9c444eddfaeb5bdef
<ide> title: Declare String Variables
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/c2QvWU6'
<add>forumTopicId: 17557
<ide> localeTitle: 声明字符串变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">以前我们使用过代码<code>var myName = "your name";</code> <code>"your name"</code>被称为<dfn>字符串</dfn> <dfn>文字</dfn> 。它是一个字符串,因为它是用单引号或双引号括起来的一系列零个或多个字符。 </section>
<add><section id='description'>
<add>之前我们写过这样的代码:
<add><code>var myName = "your name";</code>
<add><code>"your name"</code>被称作<dfn>字符串变量</dfn>。字符串是用单引号或双引号包裹起来的一连串的零个或多个字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建两个新的<code>string</code>变量: <code>myFirstName</code>和<code>myLastName</code>并分别为它们分配<code>myFirstName</code>和<code>myLastName</code>的值。 </section>
<add><section id='instructions'>
<add>创建两个新的<code>字符串变量</code>:<code>myFirstName</code>和<code>myLastName</code>,并用你的姓和名分别为它们赋值。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myFirstName</code>应该是一个至少包含一个字符的字符串。
<add> - text: <code>myFirstName</code>应该是一个字符串,并且至少包含一个字符。
<ide> testString: assert((function(){if(typeof myFirstName !== "undefined" && typeof myFirstName === "string" && myFirstName.length > 0){return true;}else{return false;}})());
<del> - text: <code>myLastName</code>应该是一个至少包含一个字符的字符串。
<add> - text: <code>myLastName</code>应该是一个字符串,并且至少包含一个字符。
<ide> testString: assert((function(){if(typeof myLastName !== "undefined" && typeof myLastName === "string" && myLastName.length > 0){return true;}else{return false;}})());
<ide>
<ide> ```
<ide> var lastName = "Turing";
<ide>
<ide> // Only change code below this line
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var lastName = "Turing";
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myFirstName !== "undefined" && typeof myLastName !== "undefined"){(function(){return myFirstName + ', ' + myLastName;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myFirstName = "Alan";
<add>var myLastName = "Turing";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ad
<ide> title: Decrement a Number with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript减少数字
<add>videoUrl: 'https://scrimba.com/c/cM2KeS2'
<add>forumTopicId: 17558
<add>localeTitle: 数字递减
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用<code>--</code>运算符轻松地将变量<dfn>减1</dfn>或减1。 <code>i--;</code>相当于<code>i = i - 1;</code> <strong>注意</strong> <br>整条线变成了<code>i--;</code> ,消除了对等号的需要。 </section>
<add><section id='description'>
<add>使用自减符号<code>--</code>,你可以很方便地对一个变量执行<dfn>自减</dfn>或者<code>-1</code>运算。
<add><code>i--;</code>
<add>等效于
<add><code>i = i - 1;</code>
<add><strong>提示</strong><br><code>i--;</code>这种写法,省去了书写<code>=</code>符号的必要。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改代码以在<code>myVar</code>上使用<code>--</code>运算符。 </section>
<add><section id='instructions'>
<add>重写代码,使用<code>--</code>符号对<code>myVar</code>执行自减操作。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myVar</code>应该等于<code>10</code>
<add> - text: <code>myVar</code>应该等于<code>10</code>。
<ide> testString: assert(myVar === 10);
<del> - text: <code>myVar = myVar - 1;</code>应该改变
<add> - text: <code>myVar = myVar - 1;</code>语句应该被修改。
<ide> testString: assert(/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code));
<del> - text: 在<code>myVar</code>上使用<code>--</code>运算符
<add> - text: 对<code>myVar</code>使用<code>--</code>运算符。
<ide> testString: assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
<del> - text: 不要更改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/var myVar = 11;/.test(code));
<ide>
<ide> ```
<ide> myVar = myVar - 1;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'myVar = ' + z;})(myVar);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myVar = 11;
<add>myVar--;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.chinese.md
<ide> id: 56bbb991ad1ed5201cd392d3
<ide> title: Delete Properties from a JavaScript Object
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 从JavaScript对象中删除属性
<add>videoUrl: 'https://scrimba.com/c/cDqKdTv'
<add>forumTopicId: 17560
<add>localeTitle: 删除对象的属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们还可以删除对象中的属性,如下所示: <code>delete ourDog.bark;</code> </section>
<add><section id='description'>
<add>我们同样可以删除对象的属性,例如:
<add><code>delete ourDog.bark;</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">从<code>myDog</code>删除<code>"tails"</code>属性。您可以使用点或括号表示法。 </section>
<add><section id='instructions'>
<add>删除<code>myDog</code>对象的<code>"tails"</code>属性。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 从<code>myDog</code>删除属性<code>"tails"</code> 。
<add> - text: 从<code>myDog</code>中删除<code>"tails"</code>属性。
<ide> testString: assert(typeof myDog === "object" && myDog.tails === undefined);
<del> - text: 不要修改<code>myDog</code>设置
<add> - text: 不要修改<code>myDog</code>的初始化。
<ide> testString: 'assert(code.match(/"tails": 1/g).length > 1);'
<ide>
<ide> ```
<ide> var myDog = {
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myDog = {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return z;})(myDog);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourDog = {
<add> "name": "Camper",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["everything!"],
<add> "bark": "bow-wow"
<add>};
<add>var myDog = {
<add> "name": "Happy Coder",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["freeCodeCamp Campers"],
<add> "bark": "woof"
<add>};
<add>delete myDog.tails;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-decimal-by-another-with-javascript.chinese.md
<ide> id: bd7993c9ca9feddfaeb7bdef
<ide> title: Divide One Decimal by Another with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript将另一个十进制除以另一个
<add>videoUrl: 'https://scrimba.com/c/cBZe9AW'
<add>forumTopicId: 18255
<add>localeTitle: 两个小数相除
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在让我们将一位小数除以另一位小数。 </section>
<add><section id='description'>
<add>现在让我们将一个小数除以另一个小数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0.0</code>使<code>quotient</code>等于<code>2.2</code> 。 </section>
<add><section id='instructions'>
<add>改变数值<code>0.0</code>的值让变量<code>quotient</code>的值等于<code>2.2</code>.
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 变<code>quotient</code>应该等于<code>2.2</code>
<add> - text: <code>quotient</code>的值应该等于<code>2.2</code>。
<ide> testString: assert(quotient === 2.2);
<del> - text: 您应该使用<code>/</code>运算符将4.4除以2
<add> - text: 使用<code>/</code>运算符将 4.4 除以 2。
<ide> testString: assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
<del> - text: 商数变量只应分配一次
<add> - text: quotient 变量应该只被赋值一次。
<ide> testString: assert(code.match(/quotient/g).length === 1);
<ide>
<ide> ```
<ide> tests:
<ide>
<ide> ```js
<ide> var quotient = 0.0 / 2.0; // Fix this line
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var quotient = 0.0 / 2.0; // Fix this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y){return 'quotient = '+y;})(quotient);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>var quotient = 4.4 / 2.0;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.chinese.md
<ide> id: cf1111c1c11feddfaeb6bdef
<ide> title: Divide One Number by Another with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 用JavaScript划分一个号码
<add>videoUrl: 'https://scrimba.com/c/cqkbdAr'
<add>forumTopicId: 17566
<add>localeTitle: 除法运算
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们也可以将一个数字除以另一个数字。 JavaScript使用<code>/</code>符号进行除法。 <p> <strong>例</strong> </p><blockquote> myVar = 16/2; //分配8 </blockquote></section>
<add><section id='description'>
<add>我们可以在 JavaScript 中做除法运算。
<add>JavaScript 中使用<code>/</code>符号做除法运算。
<add>
<add><strong>示例</strong>
<add>
<add>```js
<add>myVar = 16 / 2; // assigned 8
<add>```
<add>
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0</code> ,使<code>quotient</code>等于<code>2</code> 。 </section>
<add><section id='instructions'>
<add>改变数值<code>0</code>来让变量<code>quotient</code>的值等于<code>2</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 使变量<code>quotient</code>等于2。
<add> - text: 要使<code>quotient</code>的值等于 2。
<ide> testString: assert(quotient === 2);
<del> - text: 使用<code>/</code>运算符
<add> - text: 使用<code>/</code>运算符。
<ide> testString: assert(/\d+\s*\/\s*\d+/.test(code));
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> var quotient = 66 / 0;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var quotient = 66 / 0;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'quotient = '+z;})(quotient);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var quotient = 66 / 33;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b6
<ide> title: Escape Sequences in Strings
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cvmqRh6'
<add>forumTopicId: 17567
<ide> localeTitle: 字符串中的转义序列
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">引号不是可以在字符串中<dfn>转义</dfn>的唯一字符。使用转义字符有两个原因:首先是允许您使用您可能无法输入的字符,例如退格。其次是允许你在一个字符串中表示多个引号,而不会误解你的意思。我们在之前的挑战中学到了这一点。 <table class="table table-striped"><thead><tr><th>码</th><th>产量</th></tr></thead><tbody><tr><td> <code>\'</code> </td> <td>单引号</td></tr><tr><td> <code>\"</code> </td> <td>双引号</td></tr><tr><td> <code>\\</code> </td> <td>反斜线</td></tr><tr><td> <code>\n</code> </td> <td>新队</td></tr><tr><td> <code>\r</code> </td> <td>回车</td></tr><tr><td> <code>\t</code> </td> <td>标签</td></tr><tr><td> <code>\b</code> </td> <td>退格</td></tr><tr><td> <code>\f</code> </td> <td>形式饲料</td></tr></tbody></table> <em>请注意,必须对反斜杠本身进行转义才能显示为反斜杠。</em> </section>
<add><section id='description'>
<add>引号不是字符串中唯一可以被<dfn>转义</dfn>的字符。使用转义字符有两个原因:首先是可以让你使用无法输入的字符,例如退格。其次是可以让你在一个字符串中表示多个引号,而不会出错。我们在之前的挑战中学到了这个。
<add><table class="table table-striped"><thead><tr><th>代码</th><th>输出</th></tr></thead><tbody><tr><td><code>\'</code></td><td>单引号</td></tr><tr><td><code>\"</code></td><td>双引号</td></tr><tr><td><code>\\</code></td><td>反斜杠</td></tr><tr><td><code>\n</code></td><td>换行符</td></tr><tr><td><code>\r</code></td><td>回车符</td></tr><tr><td><code>\t</code></td><td>制表符</td></tr><tr><td><code>\b</code></td><td>退格</td></tr><tr><td><code>\f</code></td><td>换页符</td></tr></tbody></table>
<add><em>请注意,必须对反斜杠本身进行转义才能显示为反斜杠。</em>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用转义序列将以下三行文本分配到单个变量<code>myStr</code> 。 <blockquote>第一行<br> \第二行<br> ThirdLine </blockquote>您将需要使用转义序列正确插入特殊字符。您还需要按照上面的间距来跟踪,在转义序列或单词之间没有空格。这是写出转义序列的文本。 <q>FirstLine <code>newline</code> <code>tab</code> <code>backslash</code> SecondLine <code>newline</code> ThirdLine</q> </section>
<add><section id='instructions'>
<add>使用转义字符将下面三行文本字符串赋给变量<code>myStr</code>。
<add><blockquote>FirstLine<br/> \SecondLine<br/>ThirdLine</blockquote>
<add>你需要使用转义字符正确地插入特殊字符,确保间距与上面文本一致并且单词或转义字符之间没有空格。
<add>像这样用转义字符写出来:
<add><q>FirstLine<code>换行符</code><code>制表符</code><code>反斜杠</code>SecondLine<code>换行符</code>ThirdLine</q>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myStr</code>不应包含任何空格
<del> testString: 'assert(!/ /.test(myStr), "<code>myStr</code> should not contain any spaces");'
<del> - text: <code>myStr</code>应包含的字符串<code>FirstLine</code> , <code>SecondLine</code>和<code>ThirdLine</code> (记住区分大小写)
<del> testString: 'assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), "<code>myStr</code> should contain the strings <code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (remember case sensitivity)");'
<del> - text: <code>FirstLine</code>后面应跟换行符<code>\n</code>
<del> testString: 'assert(/FirstLine\n/.test(myStr), "<code>FirstLine</code> should be followed by the newline character <code>\n</code>");'
<del> - text: <code>myStr</code>应该包含一个制表字符<code>\t</code> ,它跟在换行符后面
<del> testString: 'assert(/\n\t/.test(myStr), "<code>myStr</code> should contain a tab character <code>\t</code> which follows a newline character");'
<del> - text: <code>SecondLine</code>应该以反斜杠字符<code>\\</code>开头
<del> testString: 'assert(/\SecondLine/.test(myStr), "<code>SecondLine</code> should be preceded by the backslash character <code>\\</code>");'
<del> - text: <code>SecondLine</code>和<code>ThirdLine</code>之间应该有换行符
<del> testString: 'assert(/SecondLine\nThirdLine/.test(myStr), "There should be a newline character between <code>SecondLine</code> and <code>ThirdLine</code>");'
<add> - text: <code>myStr</code>不能包含空格。
<add> testString: assert(!/ /.test(myStr));
<add> - text: <code>myStr</code>应该包含字符串<code>FirstLine</code>, <code>SecondLine</code> and <code>ThirdLine</code> (记得区分大小写)。
<add> testString: assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr));
<add> - text: <code>FirstLine</code>后面应该是一个新行<code>\n</code>。
<add> testString: assert(/FirstLine\n/.test(myStr));
<add> - text: <code>myStr</code>应该包含制表符<code>\t</code>并且制表符要在换行符后面。
<add> testString: assert(/\n\t/.test(myStr));
<add> - text: <code>SecondLine</code>前面应该是反斜杠<code>\\</code>。
<add> testString: assert(/\SecondLine/.test(myStr));
<add> - text: <code>SecondLine</code>和<code>ThirdLine</code>之间应该是换行符。
<add> testString: assert(/SecondLine\nThirdLine/.test(myStr));
<add> - text: <code>myStr</code> 应该只包含介绍里面展示的字符串。
<add> testString: assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```js
<ide> var myStr; // Change this line
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add>if (myStr !== undefined){
<add>console.log('myStr:\n' + myStr);}})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myStr = "FirstLine\n\t\\SecondLine\nThirdLine";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b5
<ide> title: Escaping Literal Quotes in Strings
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 逃避字符串中的字面引用
<add>videoUrl: 'https://scrimba.com/c/c2QvgSr'
<add>forumTopicId: 17568
<add>localeTitle: 转义字符串中的引号
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在定义字符串时,必须以单引号或双引号开头和结尾。当你需要一个文字报价会发生什么: <code>"</code>还是<code>'</code> ?你的字符串里面在JavaScript中,你可以放置一个<dfn>反斜杠</dfn> (从考虑到它作为字符串报价的最终<dfn>逃脱</dfn>报价<code>\</code>在引号前)。 <code>var sampleStr = "Alan said, \"Peter is learning JavaScript\".";</code>这告诉JavaScript,以下引用不是字符串的结尾,而是应该出现在字符串中。所以如果要将它打印到控制台,你会得到: <code>Alan said, "Peter is learning JavaScript".</code> </section>
<add><section id='description'>
<add>定义一个字符串必须要用单引号或双引号来包裹它。那么当你的字符串里面包含:<code>"</code>或者<code>'</code>时该怎么办呢?
<add>在 JavaScript 中,你可以通过在引号前面使用<dfn>反斜杠</dfn>(<code>\</code>)来转义引号。
<add><code>var sampleStr = "Alan said, \"Peter is learning JavaScript\".";</code>
<add>有了转义符号,JavaScript 就知道这个单引号或双引号并不是字符串的结尾,而是字符串内的字符。所以,上面的字符串打印到控制台的结果为:
<add><code>Alan said, "Peter is learning JavaScript".</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<dfn>反斜杠</dfn>将字符串分配给<code>myStr</code>变量,这样如果要将其打印到控制台,您会看到: <code>I am a "double quoted" string inside "double quotes".</code> </section>
<add><section id='instructions'>
<add>使用<dfn>反斜杠</dfn>将一个字符串赋值给变量<code>myStr</code>,打印到控制台,输出为:
<add><code>I am a "double quoted" string inside "double quotes".</code>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该使用两个双引号( <code>"</code> )和四个转义双引号( <code>\"</code> )。
<add> - text: 你的代码中应该包含两个双引号 (<code>"</code>) 以及四个转义的双引 (<code>\"</code>)。
<ide> testString: assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
<del> - text: 变量myStr应该包含字符串: <code>I am a "double quoted" string inside "double quotes".</code>
<del> testString: 'assert(myStr === "I am a \"double quoted\" string inside \"double quotes\".");'
<add> - text: 变量 myStr 应该包含字符串<code>I am a "double quoted" string inside "double quotes".</code>。
<add> testString: assert(myStr === "I am a \"double quoted\" string inside \"double quotes\".");
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```js
<ide> var myStr = ""; // Change this line
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr = ""; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){
<add> if(typeof myStr === 'string') {
<add> console.log("myStr = \"" + myStr + "\"");
<add> } else {
<add> console.log("myStr is undefined");
<add> }
<add>})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myStr = "I am a \"double quoted\" string inside \"double quotes\".";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.chinese.md
<ide> id: bd7123c9c448eddfaeb5bdef
<ide> title: Find the Length of a String
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 找到字符串的长度
<add>videoUrl: 'https://scrimba.com/c/cvmqEAd'
<add>forumTopicId: 18182
<add>localeTitle: 查找字符串的长度
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以通过在字符串变量或字符串文字后面写<code>.length</code>来查找<code>String</code>值的长度。 <code>"Alan Peter".length; // 10</code>例如,如果我们创建了一个变量<code>var firstName = "Charles"</code> ,我们可以通过使用<code>firstName.length</code>属性找出字符串<code>"Charles"</code>长度。 </section>
<add><section id='description'>
<add>你可以通过在字符串变量或字符串后面写上<code>.length</code>来获得字符串变量值的长度。
<add><code>"Alan Peter".length; // 10</code>
<add>例如,我们创建了一个变量<code>var firstName = "Charles"</code>,我们就可以通过使用<code>firstName.length</code>来获得<code>"Charles"</code>字符串的长度。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>.length</code>属性计算<code>lastName</code>变量中的字符数,并将其分配给<code>lastNameLength</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>.length</code>属性来获得变量<code>lastName</code>的长度,并把它赋值给变量<code>lastNameLength</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>lastNameLength</code>应该等于8。
<del> testString: 'assert((function(){if(typeof lastNameLength !== "undefined" && typeof lastNameLength === "number" && lastNameLength === 8){return true;}else{return false;}})(), "<code>lastNameLength</code> should be equal to eight.");'
<del> - text: 您应该使用<code>.length</code>来获取<code>lastName</code>的长度,如下所示: <code>lastName.length</code> 。
<del> testString: 'assert((function(){if(code.match(/\.length/gi) && code.match(/\.length/gi).length >= 2 && code.match(/var lastNameLength \= 0;/gi) && code.match(/var lastNameLength \= 0;/gi).length >= 1){return true;}else{return false;}})(), "You should be getting the length of <code>lastName</code> by using <code>.length</code> like this: <code>lastName.length</code>.");'
<add> - text: 不能改变 <code>// Setup</code> 部分声明的变量。
<add> testString: assert(code.match(/var lastNameLength = 0;/) && code.match(/var lastName = "Lovelace";/));
<add> - text: <code>lastNameLength</code>应该等于 8。
<add> testString: assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
<add> - text: 你应该使用 <code>.length</code> 获取 <code>lastName</code> 的长度,像这样 <code>lastName.length</code>。
<add> testString: assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
<ide>
<ide> ```
<ide>
<ide> var lastName = "Lovelace";
<ide>
<ide> lastNameLength = lastName;
<ide>
<del>```
<del>
<del></div>
<del>
<ide>
<del>### After Test
<del><div id='js-teardown'>
<del>
<del>```js
<del>console.info('after the test');
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var firstNameLength = 0;
<add>var firstName = "Ada";
<add>firstNameLength = firstName.length;
<add>
<add>var lastNameLength = 0;
<add>var lastName = "Lovelace";
<add>lastNameLength = lastName.length;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ae
<ide> title: Finding a Remainder in JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 在JavaScript中查找剩余内容
<add>videoUrl: 'https://scrimba.com/c/cWP24Ub'
<add>forumTopicId: 18184
<add>localeTitle: 求余运算
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>余数</dfn>运算符<code>%</code>给出了两个数的除法的余数。 <strong>例</strong> <blockquote> 5%2 = 1因为<br> Math.floor(5/2)= 2(商数) <br> 2 * 2 = 4 <br> 5 - 4 = 1(剩余) </blockquote> <strong>用法</strong> <br>在数学中,通过检查数字除以<code>2</code>的余数,可以检查数字是偶数还是奇数。 <blockquote> 17%2 = 1(17为奇数) <br> 48%2 = 0(48为偶数) </blockquote> <strong>注意</strong> <br> <dfn>余数</dfn>运算符有时被错误地称为“模数”运算符。它与模数非常相似,但在负数下不能正常工作。 </section>
<add><section id='description'>
<add><dfn>remainder</dfn>求余运算符<code>%</code>返回两个数相除得到的余数
<add><strong>示例</strong>
<add><blockquote>5 % 2 = 1 因为<br>Math.floor(5 / 2) = 2 (商)<br>2 * 2 = 4<br>5 - 4 = 1 (余数)</blockquote>
<add><strong>用法</strong><br>在数学中,判断一个数是奇数还是偶数,只需要判断这个数除以 2 得到的余数是 0 还是 1。
<add><blockquote>17 % 2 = 1(17 是奇数)<br>48 % 2 = 0(48 是偶数)</blockquote>
<add><strong>提示<strong><br>余数运算符(<dfn>remainder</dfn>)有时被错误地称为“模数”运算符。它与模数非常相似,但不能用于负数的运算。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<dfn>余数</dfn> ( <code>%</code> )运算符将<code>remainder</code>设置为等于<code>11</code>的余数除以<code>3</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>%</code>运算符,计算 11 除以 3 的余数,并把余数赋给变量 remainder。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 应该初始化变量<code>remainder</code>
<add> - text: 变量<code>remainder</code>应该被初始化。
<ide> testString: assert(/var\s+?remainder/.test(code));
<del> - text: <code>remainder</code>的值应为<code>2</code>
<add> - text: <code>remainder</code>的值应该等于<code>2</code>。
<ide> testString: assert(remainder === 2);
<del> - text: 您应该使用<code>%</code>运算符
<add> - text: 你应该使用<code>%</code>运算符。
<ide> testString: assert(/\s+?remainder\s*?=\s*?.*%.*;/.test(code));
<ide>
<ide> ```
<ide> var remainder;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y){return 'remainder = '+y;})(remainder);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var remainder = 11 % 3;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.chinese.md
<ide> id: cf1111c1c11feddfaeb9bdef
<ide> title: Generate Random Fractions with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript生成随机分数
<add>videoUrl: 'https://scrimba.com/c/cyWJJs3'
<add>forumTopicId: 18185
<add>localeTitle: 使用 JavaScript 生成随机分数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">随机数对于创建随机行为很有用。 JavaScript有一个<code>Math.random()</code>函数,它生成一个介于<code>0</code> (含)和不高达<code>1</code> (独占)之间的随机十进制数。因此<code>Math.random()</code>可以返回<code>0</code>但永远不会返回<code>1</code> <strong>Note</strong> <br> <a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">与使用Equal运算符存储值</a>一样,所有函数调用将在<code>return</code>执行之前解析,因此我们可以<code>return</code> <code>Math.random()</code>函数的值。 </section>
<add><section id='description'>
<add>随机数非常适合用来创建随机行为。
<add><code>Math.random()</code>用来生成一个在<code>0</code>(包括 0)到<code>1</code>(不包括 1)之间的随机小数,因此<code>Math.random()</code>可能返回 0 但绝不会返回 1。
<add><strong>提示</strong><br><a href='storing-values-with-the-assignment-operator' target='_blank'>使用赋值运算符存储值</a>这一节讲过,所有函数调用将在<code>return</code>执行之前解析,因此我们可以返回<code>Math.random()</code>函数的值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>randomFraction</code>以返回随机数而不是返回<code>0</code> 。 </section>
<add><section id='instructions'>
<add>更改<code>randomFraction</code>使其返回一个随机数而不是<code>0</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 使用JavaScript生成随机分数
<ide> tests:
<ide> - text: <code>randomFraction</code>应该返回一个随机数。
<ide> testString: assert(typeof randomFraction() === "number");
<del> - text: <code>randomFraction</code>返回的<code>randomFraction</code>应该是小数。
<add> - text: <code>randomFraction</code>应该返回一个小数。
<ide> testString: assert((randomFraction()+''). match(/\./g));
<del> - text: 您应该使用<code>Math.random</code>来生成随机十进制数。
<add> - text: 需要使用<code>Math.random</code>生成随机的小数。
<ide> testString: assert(code.match(/Math\.random/g).length >= 0);
<ide>
<ide> ```
<ide> function randomFraction() {
<ide>
<ide> // Only change code above this line.
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function randomFraction() {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){return randomFraction();})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function randomFraction() {
<add> return Math.random();
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript.chinese.md
<ide> id: cf1111c1c12feddfaeb1bdef
<ide> title: Generate Random Whole Numbers with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript生成随机整数
<add>videoUrl: 'https://scrimba.com/c/cRn6bfr'
<add>forumTopicId: 18186
<add>localeTitle: 使用 JavaScript 生成随机整数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们可以生成随机十进制数很好,但如果我们用它来生成随机整数,它会更有用。 <ol><li>使用<code>Math.random()</code>生成随机小数。 </li><li>将随机小数乘以<code>20</code> 。 </li><li>使用另一个函数<code>Math.floor()</code>将数字向下舍入到最接近的整数。 </li></ol>请记住, <code>Math.random()</code>永远不会返回<code>1</code> ,因为我们正在向下舍入,实际上不可能得到<code>20</code> 。这项技术将给我们一个<code>0</code>到<code>19</code>之间的整数。将所有内容放在一起,这就是我们的代码: <code>Math.floor(Math.random() * 20);</code>我们调用<code>Math.random()</code> ,将结果乘以20,然后将值传递给<code>Math.floor()</code>函数,将值向下舍入到最接近的整数。 </section>
<add><section id='description'>
<add>生成随机小数很棒,但随机数更有用的地方在于生成随机整数。
<add><ol><li>用<code>Math.random()</code>生成一个随机小数。</li><li>把这个随机小数乘以<code>20</code>。</li><li>用<code>Math.floor()</code>向下取整 获得它最近的整数。</li></ol>
<add>记住<code>Math.random()</code>永远不会返回<code>1</code>。同时因为我们是在用<code>Math.floor()</code>向下取整,所以最终我们获得的结果不可能有<code>20</code>。这确保了我们获得了一个在0到19之间的整数。
<add>把操作连缀起来,代码类似于下面:
<add><code>Math.floor(Math.random() * 20);</code>
<add>我们先调用<code>Math.random()</code>,把它的结果乘以20,然后把上一步的结果传给<code>Math.floor()</code>,最终通过向下取整获得最近的整数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用此技术生成并返回<code>0</code>到<code>9</code>之间的随机整数。 </section>
<add><section id='instructions'>
<add>生成一个<code>0</code>到<code>9</code>之间的随机整数。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>randomWholeNum</code>的结果应该是整数。
<add> - text: <code>myFunction</code>的结果应该是一个整数。
<ide> testString: assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})());
<del> - text: 您应该使用<code>Math.random</code>来生成随机数。
<add> - text: 需要使用<code>Math.random</code>生成随机数字。
<ide> testString: assert(code.match(/Math.random/g).length > 1);
<del> - text: 您应该将<code>Math.random</code>的结果乘以10,使其成为介于0和9之间的数字。
<add> - text: 你应该将<code>Math.random</code>的结果乘以 10 来生成 0 到 9 之间的随机数。
<ide> testString: assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g));
<del> - text: 您应该使用<code>Math.floor</code>删除数字的小数部分。
<add> - text: 你需要使用<code>Math.floor</code>移除数字中的小数部分。
<ide> testString: assert(code.match(/Math.floor/g).length > 1);
<ide>
<ide> ```
<ide> function randomWholeNum() {
<ide>
<ide> return Math.random();
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function randomWholeNum() {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){return randomWholeNum();})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
<add>function randomWholeNum() {
<add> return Math.floor(Math.random() * 10);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range.chinese.md
<ide> id: cf1111c1c12feddfaeb2bdef
<ide> title: Generate Random Whole Numbers within a Range
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 生成范围内的随机整数
<add>videoUrl: 'https://scrimba.com/c/cm83yu6'
<add>forumTopicId: 18187
<add>localeTitle: 生成某个范围内的随机整数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们可以生成一个落在两个特定数字范围内的随机数,而不是像我们之前那样在零和给定数字之间生成一个随机数。为此,我们将定义最小数量<code>min</code>和最大数量<code>max</code> 。这是我们将使用的公式。花一点时间阅读它并尝试理解这段代码在做什么: <code>Math.floor(Math.random() * (max - min + 1)) + min</code> </section>
<add><section id='description'>
<add>我们之前生成的随机数是在0到某个数之间,现在我们要生成的随机数是在两个指定的数之间。
<add>我们需要定义一个最小值和一个最大值。
<add>下面是我们将要使用的方法,仔细看看并尝试理解这行代码到底在干嘛:
<add><code>Math.floor(Math.random() * (max - min + 1)) + min</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>randomRange</code>的函数,它接受一个范围<code>myMin</code>和<code>myMax</code>并返回一个大于或等于<code>myMin</code>的随机数,并且小于或等于<code>myMax</code> (包括<code>myMax</code> )。 </section>
<add><section id='instructions'>
<add>创建一个叫<code>randomRange</code>的函数,参数为 myMin 和 myMax,返回一个在<code>myMin</code>(包括 myMin)和<code>myMax</code>(包括 myMax)之间的随机数。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>randomRange</code>可以生成的最低随机数应该等于你的最小数量<code>myMin</code> 。
<add> - text: <code>randomRange</code>返回的随机数应该大于或等于<code>myMin</code>。
<ide> testString: assert(calcMin === 5);
<del> - text: <code>randomRange</code>可以生成的最高随机数应该等于最大数量<code>myMax</code> 。
<add> - text: <code>randomRange</code>返回的随机数应该小于或等于<code>myMax</code>。
<ide> testString: assert(calcMax === 15);
<del> - text: <code>randomRange</code>生成的随机数应该是整数,而不是小数。
<add> - text: <code>randomRange</code>应该返回一个随机整数, 而不是小数。
<ide> testString: assert(randomRange(0,1) % 1 === 0 );
<del> - text: <code>randomRange</code>应该同时使用<code>myMax</code>和<code>myMin</code> ,并在你的范围内返回一个随机数。
<add> - text: <code>randomRange</code>应该使用<code>myMax</code>和<code>myMin</code>, 并且返回两者之间的随机数。
<ide> testString: assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})());
<ide>
<ide> ```
<ide> function randomRange(myMin, myMax) {
<ide>
<ide> // Change these values to test your function
<ide> var myRandom = randomRange(5, 15);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var myRandom = randomRange(5, 15);
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>var calcMin = 100;
<add>var calcMax = -100;
<add>for(var i = 0; i < 100; i++) {
<add> var result = randomRange(5,15);
<add> calcMin = Math.min(calcMin, result);
<add> calcMax = Math.max(calcMax, result);
<add>}
<add>(function(){
<add> if(typeof myRandom === 'number') {
<add> return "myRandom = " + myRandom;
<add> } else {
<add> return "myRandom undefined";
<add> }
<add>})()
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function randomRange(myMin, myMax) {
<add> return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.chinese.md
<ide> id: 56533eb9ac21ba0edf2244be
<ide> title: Global Scope and Functions
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 全球范围和职能
<add>videoUrl: 'https://scrimba.com/c/cQM7mCN'
<add>forumTopicId: 18193
<add>localeTitle: 全局作用域和函数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中, <dfn>范围</dfn>是指变量的可见性。在功能块之外定义的变量具有<dfn>全局</dfn>范围。这意味着,它们可以在JavaScript代码中随处可见。在没有<code>var</code>关键字的情况下使用的变量将在<code>global</code>范围内自动创建。这可能会在代码中的其他位置或再次运行函数时产生意外后果。您应该始终使用<code>var</code>声明变量。 </section>
<add><section id='description'>
<add>在 JavaScript 中,<dfn>作用域</dfn>涉及到变量的作用范围。在函数外定义的变量具有 <dfn>全局</dfn> 作用域。这意味着,具有全局作用域的变量可以在代码的任何地方被调用。
<add>这些没有使用<code>var</code>关键字定义的变量,会被自动创建在全局作用域中,形成全局变量。当在代码其他地方无意间定义了一个变量,刚好变量名与全局变量相同,这时会产生意想不到的后果。因此你应该总是使用var关键字来声明你的变量。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>var</code> ,在任何函数之外声明一个<code>global</code>变量<code>myGlobal</code> 。使用值<code>10</code>初始化它。在函数<code>fun1</code>内部,在<strong><em>不</em></strong>使用<code>var</code>关键字的<strong><em>情况下</em></strong>为<code>oopsGlobal</code>分配<code>5</code> 。 </section>
<add><section id='instructions'>
<add>在函数外声明一个<code>全局</code>变量<code>myGlobal</code>,并给它一个初始值<code>10</code>
<add>在函数<code>fun1</code>的内部,<strong>不</strong>使用<code>var</code>关键字来声明<code>oopsGlobal</code>,并赋值为<code>5</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 应该定义<code>myGlobal</code>
<add> - text: 应定义<code>myGlobal</code>。
<ide> testString: assert(typeof myGlobal != "undefined");
<del> - text: <code>myGlobal</code>的值应为<code>10</code>
<add> - text: <code>myGlobal</code>的值应为<code>10</code>。
<ide> testString: assert(myGlobal === 10);
<del> - text: 应使用<code>var</code>关键字声明<code>myGlobal</code>
<add> - text: 应使用<code>var</code>关键字定义<code>myGlobal</code>。
<ide> testString: assert(/var\s+myGlobal/.test(code));
<del> - text: <code>oopsGlobal</code>应该是一个全局变量,其值为<code>5</code>
<add> - text: <code>oopsGlobal</code>应为全局变量且值为<code>5</code>。
<ide> testString: assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5);
<ide>
<ide> ```
<ide> function fun2() {
<ide> }
<ide> console.log(output);
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function uncapture() {
<ide> }
<ide> var oopsGlobal;
<ide> capture();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> capture();
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>fun1();
<add>fun2();
<add>uncapture();
<add>(function() { return logOutput || "console.log never called"; })();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>// Declare your variable here
<add>var myGlobal = 10;
<add>
<add>function fun1() {
<add> // Assign 5 to oopsGlobal Here
<add> oopsGlobal = 5;
<add>}
<add>
<add>// Only change code above this line
<add>function fun2() {
<add> var output = "";
<add> if(typeof myGlobal != "undefined") {
<add> output += "myGlobal: " + myGlobal;
<add> }
<add> if(typeof oopsGlobal != "undefined") {
<add> output += " oopsGlobal: " + oopsGlobal;
<add> }
<add> console.log(output);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c0
<ide> title: Global vs. Local Scope in Functions
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 功能中的全局与局部范围
<add>videoUrl: 'https://scrimba.com/c/c2QwKH2'
<add>forumTopicId: 18194
<add>localeTitle: 函数中的全局作用域和局部作用域
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">可以使<dfn>本地</dfn>变量和<dfn>全局</dfn>变量具有相同的名称。执行此操作时, <code>local</code>变量优先于<code>global</code>变量。在这个例子中: <blockquote> var someVar =“帽子”; <br> function myFun(){ <br> var someVar =“Head”; <br>返回someVar; <br> } </blockquote>函数<code>myFun</code>将返回<code>"Head"</code>因为存在变量的<code>local</code>版本。 </section>
<add><section id='description'>
<add>一个程序中有可能具有相同名称的<dfn>局部</dfn>变量 和<dfn>全局</dfn>变量。在这种情况下,<code>局部</code>变量将会优先于<code>全局</code>变量。
<add>下面为例:
<add>
<add>```js
<add>var someVar = "Hat";
<add>function myFun() {
<add> var someVar = "Head";
<add> return someVar;
<add>}
<add>```
<add>
<add>函数<code>myFun</code>将会返回<code>"Head"</code>,因为<code>局部变量</code>优先级更高。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将一个局部变量添加到<code>myOutfit</code>函数,以使用<code>"sweater"</code>覆盖<code>outerWear</code>的值。 </section>
<add><section id='instructions'>
<add>给<code>myOutfit</code>添加一个局部变量来覆盖<code>outerWear</code>的值为<code>"sweater"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 不要更改全局<code>outerWear</code>的值
<add> - text: 不要修改全局变量<code>outerWear</code>的值。
<ide> testString: assert(outerWear === "T-Shirt");
<del> - text: <code>myOutfit</code>应该返回<code>"sweater"</code>
<add> - text: <code>myOutfit</code>应该返回<code>"sweater"</code>。
<ide> testString: assert(myOutfit() === "sweater");
<del> - text: 不要更改return语句
<add> - text: 不要修改<code>return</code>语句。
<ide> testString: assert(/return outerWear/.test(code));
<ide>
<ide> ```
<ide> function myOutfit() {
<ide> }
<ide>
<ide> myOutfit();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> myOutfit();
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var outerWear = "T-Shirt";
<add>function myOutfit() {
<add> var outerWear = "sweater";
<add> return outerWear;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.chinese.md
<ide> id: 5664820f61c48e80c9fa476c
<ide> title: Golf Code
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 高尔夫码
<add>videoUrl: 'https://scrimba.com/c/c9ykNUR'
<add>forumTopicId: 18195
<add>localeTitle: 高尔夫代码
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在<a href="https://en.wikipedia.org/wiki/Golf" target="_blank">高尔夫</a>比赛中,每个洞都具有<code>par</code>意义,即高尔夫球手为了将球沉入洞中以完成比赛所期望的平均<code>strokes</code>次数。根据你的<code>strokes</code>高出或低于<code>par</code>的距离,有一个不同的昵称。您的函数将通过<code>par</code>和<code>strokes</code>参数。根据此表返回正确的字符串,该表按优先级顺序列出笔划;顶部(最高)到底部(最低): <table class="table table-striped"><thead><tr><th>笔画</th><th>返回</th></tr></thead><tbody><tr><td> 1 </td><td> “一杆进洞!” </td></tr><tr><td> <= par - 2 </td><td> “鹰” </td></tr><tr><td> par - 1 </td><td> “小鸟” </td></tr><tr><td>平价</td><td> “相提并论” </td></tr><tr><td> par + 1 </td><td> “柏忌” </td></tr><tr><td> par + 2 </td><td> “双柏忌” </td></tr><tr><td> > = par + 3 </td><td> “回家!” </td></tr></tbody></table> <code>par</code>和<code>strokes</code>将始终为数字和正数。为方便起见,我们添加了所有名称的数组。 </section>
<add><section id='description'>
<add>在高尔夫<a href="https://en.wikipedia.org/wiki/Golf" target="_blank">golf</a>游戏中,每个洞都有自己的标准杆数<code>par</code>,代表着距离。根据你把球打进洞所挥杆的次数<code>strokes</code>,可以计算出你的高尔夫水平。
<add>函数将会传送 2 个参数,分别是标准杆数<code>par</code>和挥杆次数<code>strokes</code>,根据下面的表格返回正确的水平段位。
<add><table class="table table-striped"><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
<add><code>par</code>和<code>strokes</code>必须是数字而且是正数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>golfScore(4, 1)</code>应该返回“Hole-in-one!”'
<add> - text: <code>golfScore(4, 1)</code>应该返回 "Hole-in-one!"。
<ide> testString: assert(golfScore(4, 1) === "Hole-in-one!");
<del> - text: '<code>golfScore(4, 2)</code>应该返回“Eagle”'
<add> - text: <code>golfScore(4, 2)</code>应该返回 "Eagle"。
<ide> testString: assert(golfScore(4, 2) === "Eagle");
<del> - text: '<code>golfScore(5, 2)</code>应该返回“Eagle”'
<add> - text: <code>golfScore(5, 2)</code>应该返回 "Eagle"。
<ide> testString: assert(golfScore(5, 2) === "Eagle");
<del> - text: '<code>golfScore(4, 3)</code>应该返回“Birdie”'
<add> - text: <code>golfScore(4, 3)</code>应该返回 "Birdie"。
<ide> testString: assert(golfScore(4, 3) === "Birdie");
<del> - text: '<code>golfScore(4, 4)</code>应该返回“Par”'
<add> - text: <code>golfScore(4, 4)</code>应该返回 "Par"。
<ide> testString: assert(golfScore(4, 4) === "Par");
<del> - text: '<code>golfScore(1, 1)</code>应该返回“Hole-in-one!”'
<add> - text: <code>golfScore(1, 1)</code>应该返回 "Hole-in-one!"。
<ide> testString: assert(golfScore(1, 1) === "Hole-in-one!");
<del> - text: '<code>golfScore(5, 5)</code>应该返回“Par”'
<add> - text: <code>golfScore(5, 5)</code>应该返回 "Par"。
<ide> testString: assert(golfScore(5, 5) === "Par");
<del> - text: '<code>golfScore(4, 5)</code>应该返回“Bogey”'
<add> - text: <code>golfScore(4, 5)</code>应该返回 "Bogey"。
<ide> testString: assert(golfScore(4, 5) === "Bogey");
<del> - text: '<code>golfScore(4, 6)</code>应该返回“Double Bogey”'
<add> - text: <code>golfScore(4, 6)</code>应该返回 "Double Bogey"。
<ide> testString: assert(golfScore(4, 6) === "Double Bogey");
<del> - text: '<code>golfScore(4, 7)</code>应该返回“Go Home!”'
<add> - text: <code>golfScore(4, 7)</code>应该返回 "Go Home!"。
<ide> testString: assert(golfScore(4, 7) === "Go Home!");
<del> - text: '<code>golfScore(5, 9)</code>应该返回“Go Home!”'
<add> - text: <code>golfScore(5, 9)</code>应该返回 "Go Home!"。
<ide> testString: assert(golfScore(5, 9) === "Go Home!");
<ide>
<ide> ```
<ide> function golfScore(par, strokes) {
<ide>
<ide> // Change these values to test
<ide> golfScore(5, 4);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> golfScore(5, 4);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function golfScore(par, strokes) {
<add> if (strokes === 1) {
<add> return "Hole-in-one!";
<add> }
<add>
<add> if (strokes <= par - 2) {
<add> return "Eagle";
<add> }
<add>
<add> if (strokes === par - 1) {
<add> return "Birdie";
<add> }
<add>
<add> if (strokes === par) {
<add> return "Par";
<add> }
<add>
<add> if (strokes === par + 1) {
<add> return "Bogey";
<add> }
<add>
<add> if(strokes === par + 2) {
<add> return "Double Bogey";
<add> }
<add>
<add> return "Go Home!";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ac
<ide> title: Increment a Number with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript增加数字
<add>videoUrl: 'https://scrimba.com/c/ca8GLT9'
<add>forumTopicId: 18201
<add>localeTitle: 数字递增
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以轻松地<dfn>增加</dfn>或添加一个变量与<code>++</code>运算符。 <code>i++;</code>相当于<code>i = i + 1;</code> <strong>注意</strong> <br>整行成为<code>i++;</code> ,消除了对等号的需要。 </section>
<add><section id='description'>
<add>使用<code>++</code>,我们可以很容易地对变量进行自增或者<code>+1</code>运算。
<add><code>i++;</code>
<add>等效于
<add><code>i = i + 1;</code>
<add><strong>注意</strong><br><code>i++;</code>这种写法,省去了书写<code>=</code>符号的必要。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改代码以在<code>myVar</code>上使用<code>++</code>运算符。 <strong>暗示</strong> <br>了解有关<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()" target="_blank">算术运算符的</a>更多信息<a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()" target="_blank">- 增量(++)</a> 。 </section>
<add><section id='instructions'>
<add>重写代码,使用<code>++</code>来对变量<code>myVar</code>进行自增操作。
<add><strong>提示</strong><br>了解更多关于<code>++</code>运算符<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#%E9%80%92%E5%A2%9E_()" target="_blank">Arithmetic operators - Increment (++)</a>.
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myVar</code>应该等于<code>88</code>
<add> - text: <code>myVar</code>应该等于<code>88</code>。
<ide> testString: assert(myVar === 88);
<del> - text: <code>myVar = myVar + 1;</code>应该改变
<del> testString: assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code));
<del> - text: 使用<code>++</code>运算符
<add> - text: <code>myVar = myVar + 1;</code>语句应该被修改。
<add> testString: assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*myVar\+\+;/.test(code));
<add> - text: 使用<code>++</code>运算符。
<ide> testString: assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
<del> - text: 不要更改行上方的代码
<add> - text: 不要修改注释上方的代码。
<ide> testString: assert(/var myVar = 87;/.test(code));
<ide>
<ide> ```
<ide> myVar = myVar + 1;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'myVar = ' + z;})(myVar);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myVar = 87;
<add>myVar++;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244a9
<ide> title: Initializing Variables with the Assignment Operator
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
<add>forumTopicId: 301171
<ide> localeTitle: 使用赋值运算符初始化变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">通常将变量<dfn>初始化</dfn>为与声明的同一行中的初始值。 <code>var myVar = 0;</code>创建一个名为<code>myVar</code>的新变量,并为其指定初始值<code>0</code> 。 </section>
<add><section id='description'>
<add>通常在声明变量的时候会给变量<dfn>初始化</dfn>一个初始值。
<add><code>var myVar = 0;</code>
<add>创建一个名为<code>myVar</code>的变量并指定一个初始值<code>0</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>var</code>定义变量<code>a</code>并将其初始化为值<code>9</code> 。 </section>
<add><section id='instructions'>
<add>通过关键字<code>var</code>定义一个变量<code>a</code>并且给它一个初始值<code>9</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 将<code>a</code>初始化为值<code>9</code>
<add> - text: 你需要初始化<code>a</code>的值为<code>9</code>。
<ide> testString: assert(/var\s+a\s*=\s*9\s*/.test(code));
<ide>
<ide> ```
<ide> var ourVar = 19;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof a !== 'undefined') {(function(a){return "a = " + a;})(a);} else { (function() {return 'a is undefined';})(); }
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 9;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244db
<ide> title: Introducing Else If Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 如果声明引入Else
<add>videoUrl: 'https://scrimba.com/c/caeJ2hm'
<add>forumTopicId: 18206
<add>localeTitle: 介绍 else if 语句
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果您有多个需要解决的条件,可以将<code>if</code>语句与<code>else if</code>语句链接在一起。 <blockquote> if(num> 15){ <br>返回“大于15”; <br> } else if(num <5){ <br>返回“小于5”; <br> } else { <br>返回“5到15之间”; <br> } </blockquote></section>
<add><section id='description'>
<add>如果你有多个条件语句,你可以通过<code>else if</code>语句把<code>if</code>语句链起来。
<add>
<add>```js
<add>if (num > 15) {
<add> return "Bigger than 15";
<add>} else if (num < 5) {
<add> return "Smaller than 5";
<add>} else {
<add> return "Between 5 and 15";
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">转换逻辑以使用<code>else if</code>语句。 </section>
<add><section id='instructions'>
<add>使用<code>if else</code>实现同样的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你应该至少有两个<code>else</code>语句
<add> - text: 你应该至少有两个<code>else</code>表达式。
<ide> testString: assert(code.match(/else/g).length > 1);
<del> - text: 你应该至少有两个<code>if</code>语句
<add> - text: 你应该至少有两个<code>if</code>表达式。
<ide> testString: assert(code.match(/if/g).length > 1);
<del> - text: 您应该为每个条件关闭并打开花括号
<del> testString: assert(code.match(/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/));
<del> - text: <code>testElseIf(0)</code>应返回“小于5”
<add> - text: <code>testElseIf(0)</code>应该返回 "Smaller than 5"。
<ide> testString: assert(testElseIf(0) === "Smaller than 5");
<del> - text: <code>testElseIf(5)</code>应该返回“5到10之间”
<add> - text: <code>testElseIf(5)</code>应该返回 "Between 5 and 10"。
<ide> testString: assert(testElseIf(5) === "Between 5 and 10");
<del> - text: <code>testElseIf(7)</code>应返回“5到10之间”
<add> - text: <code>testElseIf(7)</code>应该返回 "Between 5 and 10"。
<ide> testString: assert(testElseIf(7) === "Between 5 and 10");
<del> - text: <code>testElseIf(10)</code>应返回“5到10之间”
<add> - text: <code>testElseIf(10)</code>应该返回 "Between 5 and 10"。
<ide> testString: assert(testElseIf(10) === "Between 5 and 10");
<del> - text: <code>testElseIf(12)</code>应返回“大于10”
<add> - text: <code>testElseIf(12)</code>应该返回 "Greater than 10"。
<add> testString: assert(testElseIf(12) === "Greater than 10");
<add> - text: <code>testElseIf(12)</code> 应该返回 "Greater than 10"。
<ide> testString: assert(testElseIf(12) === "Greater than 10");
<ide>
<ide> ```
<ide> testElseIf(7);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testElseIf(val) {
<add> if(val > 10) {
<add> return "Greater than 10";
<add> } else if(val < 5) {
<add> return "Smaller than 5";
<add> } else {
<add> return "Between 5 and 10";
<add> }
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244da
<ide> title: Introducing Else Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 介绍其他声明
<add>videoUrl: 'https://scrimba.com/c/cek4Efq'
<add>forumTopicId: 18207
<add>localeTitle: 介绍 else 语句
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">当<code>if</code>语句的条件为真时,将执行其后面的代码块。当那个条件是假的时候怎么办?通常什么都不会发生。使用<code>else</code>语句,可以执行备用代码块。 <blockquote> if(num> 10){ <br>返回“大于10”; <br> } else { <br>返回“10或更少”; <br> } </blockquote></section>
<add><section id='description'>
<add>当<code>if</code>语句的条件为真,大括号里的代码执行,那如果条件为假呢?正常情况下什么也不会发生。使用else语句,可以执行当条件为假时相应的代码。
<add>
<add>```js
<add>if (num > 10) {
<add> return "Bigger than 10";
<add>} else {
<add> return "10 or Less";
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>if</code>语句组合到单个<code>if/else</code>语句中。 </section>
<add><section id='instructions'>
<add>请把多个<code>if</code>语句合并为一个<code>if/else</code>语句。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您应该只在编辑器中有一个<code>if</code>语句
<add> - text: 你应该只有一个<code>if</code>表达式。
<ide> testString: assert(code.match(/if/g).length === 1);
<del> - text: 你应该使用<code>else</code>语句
<add> - text: 你应该使用一个<code>else</code>表达式。
<ide> testString: assert(/else/g.test(code));
<del> - text: <code>testElse(4)</code>应返回“5或更小”
<add> - text: <code>testElse(4)</code>应该返回 "5 or Smaller"。
<ide> testString: assert(testElse(4) === "5 or Smaller");
<del> - text: <code>testElse(5)</code>应返回“5或更小”
<add> - text: <code>testElse(5)</code>应该返回 "5 or Smaller"。
<ide> testString: assert(testElse(5) === "5 or Smaller");
<del> - text: <code>testElse(6)</code>应该返回“大于5”
<add> - text: <code>testElse(6)</code>应该返回 "Bigger than 5"。
<ide> testString: assert(testElse(6) === "Bigger than 5");
<del> - text: <code>testElse(10)</code>应该返回“大于5”
<add> - text: <code>testElse(10)</code>应该返回 "Bigger than 5"。
<ide> testString: assert(testElse(10) === "Bigger than 5");
<del> - text: 请勿更改行上方或下方的代码。
<add> - text: 不要修改上面和下面的代码。
<ide> testString: assert(/var result = "";/.test(code) && /return result;/.test(code));
<ide>
<ide> ```
<ide> testElse(4);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function testElse(val) {
<add> var result = "";
<add> if(val > 5) {
<add> result = "Bigger than 5";
<add> } else {
<add> result = "5 or Smaller";
<add> }
<add> return result;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.chinese.md
<ide> id: 56104e9e514f539506016a5c
<ide> title: Iterate Odd Numbers With a For Loop
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用For循环迭代奇数
<add>videoUrl: 'https://scrimba.com/c/cm8n7T9'
<add>forumTopicId: 18212
<add>localeTitle: 使用 For 循环遍历数组的奇数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> For循环不必一次迭代一个循环。通过改变我们的<code>final-expression</code> ,我们可以计算偶数。我们将从<code>i = 0</code>开始并在<code>i < 10</code>循环。我们会增加<code>i</code>的2每个回路与<code>i += 2</code> 。 <blockquote> var ourArray = []; <br> for(var i = 0; i <10; i + = 2){ <br> ourArray.push(ⅰ); <br> } </blockquote> <code>ourArray</code>现在包含<code>[0,2,4,6,8]</code> 。让我们改变<code>initialization</code>这样我们就可以用奇数来计算。 </section>
<add><section id='description'>
<add>for循环可以按照我们指定的顺序来迭代,通过更改我们的<code>计数器</code>,我们可以按照偶数顺序来迭代。
<add>初始化<code>i = 0</code>,当<code>i < 10</code>的时候继续循环。
<add><code>i += 2</code>让<code>i</code>每次循环之后增加2。
<add>
<add>```js
<add>var ourArray = [];
<add>for (var i = 0; i < 10; i += 2) {
<add> ourArray.push(i);
<add>}
<add>```
<add>
<add>循环结束后,<code>ourArray</code>的值为<code>[0,2,4,6,8]</code>。
<add>改变<code>计数器</code>,这样我们可以用奇数来数。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>for</code>循环将奇数从1到9推送到<code>myArray</code> 。 </section>
<add><section id='instructions'>
<add>写一个<code>for</code>循环,把从 1 到 9 的奇数添加到<code>myArray</code>。
<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\s*\(/g).length > 1);
<del> - text: '<code>myArray</code>应该等于<code>[1,3,5,7,9]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[1,3,5,7,9]</code>。
<ide> testString: assert.deepEqual(myArray, [1,3,5,7,9]);
<ide>
<ide> ```
<ide> var myArray = [];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourArray = [];
<add>for (var i = 0; i < 10; i += 2) {
<add> ourArray.push(i);
<add>}
<add>var myArray = [];
<add>for (var i = 1; i < 10; i += 2) {
<add> myArray.push(i);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.chinese.md
<ide> id: 5675e877dbd60be8ad28edc6
<ide> title: Iterate Through an Array with a For Loop
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用For循环遍历数组
<add>videoUrl: 'https://scrimba.com/c/caeR3HB'
<add>forumTopicId: 18216
<add>localeTitle: 使用 For 循环遍历数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> JavaScript中的一个常见任务是遍历数组的内容。一种方法是使用<code>for</code>循环。此代码将数组<code>arr</code>每个元素输出到控制台: <blockquote> var arr = [10,9,8,7,6]; <br> for(var i = 0; i <arr.length; i ++){ <br> (ARR [I])的console.log; <br> } </blockquote>请记住,数组具有从零开始的编号,这意味着数组的最后一个索引是长度 - 1.我们对此循环的<dfn>条件</dfn>是<code>i < arr.length</code> ,当<code>i</code>长度为1时停止。 </section>
<add><section id='description'>
<add>迭代输出一个数组的每个元素是 JavaScript 中的常见需求,<code>for</code>循环可以做到这一点。下面的代码将输出数组 <code>arr</code>的每个元素到控制台:
<add>
<add>```js
<add>var arr = [10, 9, 8, 7, 6];
<add>for (var i = 0; i < arr.length; i++) {
<add> console.log(arr[i]);
<add>}
<add>```
<add>
<add>记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:数组的长度 -1。我们这个循环的 <dfn>条件</dfn>是<code>i < arr.length</code>,当<code>i</code>的值为 长度 -1 的时候循环就停止了。在这个例子中,最后一个循环是 i === 4,也就是说,当i的值等于arr.length时,结果输出 6。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">声明并将变量<code>total</code>初始化为<code>0</code> 。使用<code>for</code>循环将<code>myArr</code>数组的每个元素的值添加到<code>total</code> 。 </section>
<add><section id='instructions'>
<add>声明并初始化一个变量<code>total</code>为<code>0</code>。使用<code>for</code>循环,使得<code>total</code>的值为<code>myArr</code>的数组中的每个元素的值的总和。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 应声明<code>total</code>并初始化为0
<del> testString: assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
<del> - text: <code>total</code>应该等于20
<add> - text: <code>total</code>应该被声明, 并且初始化值为 0。
<add> testString: assert(code.match(/var.*?total\s*=\s*0.*?;/));
<add> - text: <code>total</code>应该等于 20。
<ide> testString: assert(total === 20);
<del> - text: 您应该使用<code>for</code>循环来遍历<code>myArr</code>
<add> - text: 你应该使用<code>for</code>循环在<code>myArr</code>中遍历。
<ide> testString: assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/));
<del> - text: 不要直接将<code>total</code>设置为20
<del> testString: assert(!code.replace(/\s/g, '').match(/total[=+-]0*[1-9]+/gm));
<del>
<add> - text: 不能直接把<code>total</code>设置成 20。
<add> testString: assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g));
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<ide> <section id='challengeSeed'>
<del>
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<ide> var myArr = [ 2, 3, 4, 5, 6];
<ide>
<ide> </div>
<ide>
<del>
<ide> ### After Test
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(){if(typeof total !== 'undefined') { return "total = " + total; } else { return "total is undefined";}})()
<add>
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>var ourArr = [ 9, 10, 11, 12];
<add>var ourTotal = 0;
<add>
<add>for (var i = 0; i < ourArr.length; i++) {
<add> ourTotal += ourArr[i];
<add>}
<add>
<add>var myArr = [ 2, 3, 4, 5, 6];
<add>var total = 0;
<add>
<add>for (var i = 0; i < myArr.length; i++) {
<add> total += myArr[i];
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.chinese.md
<ide> id: 5a2efd662fb457916e1fe604
<ide> title: Iterate with JavaScript Do...While Loops
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript迭代...循环
<add>videoUrl: 'https://scrimba.com/c/cDqWGcp'
<add>forumTopicId: 301172
<add>localeTitle: do...while 循环
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用循环多次运行相同的代码。你将学习的下一个类型的循环称为“ <code>do...while</code> ”循环,因为它首先将“ <code>do</code> ”循环内部代码的一次传递,无论如何,然后它运行“ <code>while</code> ”指定条件为真一旦这种情况不再真实就停止。我们来看一个例子。 <blockquote> var ourArray = []; <br> var i = 0; <br>做{ <br> ourArray.push(ⅰ); <br>我++; <br> } while(i <5); </blockquote>这与任何其他类型的循环一样正常,结果数组看起来像<code>[0, 1, 2, 3, 4]</code> 。然而,什么使得<code>do...while</code>与其他循环不同,但是当条件在第一次检查时失败时它的行为如何。让我们看看这个在行动。这是一个常规的while循环,只要<code>i < 5</code> ,它就会在循环中运行代码。 <blockquote> var ourArray = []; <br> var i = 5; <br>而(i <5){ <br> ourArray.push(ⅰ); <br>我++; <br> } </blockquote>请注意,我们将<code>i</code>的值初始化为5.当我们执行下一行时,我们注意到<code>i</code>不小于5.所以我们不执行循环内的代码。结果是<code>ourArray</code>最终没有添加任何内容,因此当上面示例中的所有代码完成运行时,它仍然看起来像这个<code>[]</code> 。现在,看一下<code>do...while</code>循环。 <blockquote> var ourArray = []; <br> var i = 5; <br>做{ <br> ourArray.push(ⅰ); <br>我++; <br> } while(i <5); </blockquote>在这种情况下,我们将<code>i</code>的值初始化为5,就像我们使用while循环一样。当我们到达下一行时,没有检查<code>i</code>的值,所以我们转到花括号内的代码并执行它。我们将在数组中添加一个元素并在进行条件检查之前递增<code>i</code> 。然后,当我们检查<code>i < 5</code>看到<code>i</code>现在是6,这不符合条件检查。所以我们退出循环并完成。在上面的例子的末尾, <code>ourArray</code>的值是<code>[5]</code> 。本质上, <code>do...while</code>循环确保循环内的代码至少运行一次。让我们尝试通过将值推送到数组来实现<code>do...while</code>循环。 </section>
<add><section id='description'>
<add>这一节我们将要学习的是<code>do...while</code>循环,它会先执行<code>do</code>里面的代码,如果<code>while</code>表达式为真则重复执行,反之则停止执行。我们来看一个例子。
<add>
<add>```js
<add>var ourArray = [];
<add>var i = 0;
<add>do {
<add> ourArray.push(i);
<add> i++;
<add>} while (i < 5);
<add>```
<add>
<add>这看起来和其他循环语句差不多,返回的结果是<code>[0, 1, 2, 3, 4]</code>,<code>do...while</code>与其他循环不同点在于,初始条件为假时的表现,让我们通过实际的例子来看看。
<add>这是一个普通的 while 循环,只要<code>i < 5</code>,它就会在循环中运行代码。
<add>
<add>```js
<add>var ourArray = [];
<add>var i = 5;
<add>while (i < 5) {
<add> ourArray.push(i);
<add> i++;
<add>}
<add>```
<add>
<add>注意,我们首先将<code>i</code>的值初始化为 5。执行下一行时,注意到<code>i</code>不小于 5,循环内的代码将不会执行。所以<code>ourArray</code>最终没有添加任何内容,因此示例中的所有代码执行完时,<code>ourArray</code>仍然是<code>[]</code>。
<add>现在,看一下<code>do...while</code>循环。
<add>
<add>```js
<add>var ourArray = [];
<add>var i = 5;
<add>do {
<add> ourArray.push(i);
<add> i++;
<add>} while (i < 5);
<add>```
<add>
<add>在这里,和使用 while 循环时一样,我们将<code>i</code>的值初始化为 5。执行下一行时,没有检查<code>i</code>的值,直接执行花括号内的代码。数组会添加一个元素,并在进行条件检查之前递增<code>i</code>。然后,在条件检查时因为<code>i</code>等于 6 不符合条件<code>i < 5</code>,所以退出循环。最终<code>ourArray</code>的值是<code>[5]</code>。
<add>本质上,<code>do...while</code>循环确保循环内的代码至少运行一次。
<add>让我们通过<code>do...while</code>循环将值添加到数组中。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将代码中的<code>while</code>循环更改为<code>do...while</code>循环,以便循环将数字10推送到<code>myArray</code> ,当代码完成运行时, <code>i</code>将等于<code>11</code> 。 </section>
<add><section id='instructions'>
<add>将代码中的<code>while</code>循环更改为<code>do...while</code>循环,实现数字 10 添加到<code>myArray</code>中,代码执行完时,<code>i</code>等于<code>11</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 使用JavaScript迭代...循环
<ide> tests:
<ide> - text: 你应该使用<code>do...while</code>循环。
<ide> testString: assert(code.match(/do/g));
<del> - text: '<code>myArray</code>应该等于<code>[10]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[10]</code>。
<ide> testString: assert.deepEqual(myArray, [10]);
<del> - text: <code>i</code>应该等于<code>11</code>
<del> testString: assert.equal(i, 11);
<del>
<add> - text: <code>i</code>应该等于<code>11</code>。
<add> testString: assert.deepEqual(i, 11);
<ide> ```
<ide>
<ide> </section>
<ide> tests:
<ide> var myArray = [];
<ide> var i = 10;
<ide>
<del>// Only change code below this line.
<del>
<add>// Only change code below this line
<ide> while (i < 5) {
<ide> myArray.push(i);
<ide> i++;
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> while (i < 5) {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [];
<add>var i = 10;
<add>do {
<add> myArray.push(i);
<add> i++;
<add>} while (i < 5)
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.chinese.md
<ide> id: cf1111c1c11feddfaeb5bdef
<ide> title: Iterate with JavaScript For Loops
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript迭代循环
<add>videoUrl: 'https://scrimba.com/c/c9yNVCe'
<add>forumTopicId: 18219
<add>localeTitle: for 循环
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用循环多次运行相同的代码。最常见的JavaScript循环类型称为“ <code>for loop</code> ”,因为它“运行”特定次数。 For循环用三个可选表达式声明,用分号分隔: <code>for ([initialization]; [condition]; [final-expression])</code> <code>initialization</code>语句仅在循环开始之前执行一次。它通常用于定义和设置循环变量。 <code>condition</code>语句在每次循环迭代开始时进行计算,并且只要计算结果为<code>true</code>就会继续。当迭代开始时<code>condition</code>为<code>false</code>时,循环将停止执行。这意味着如果<code>condition</code>以<code>false</code>开头,则循环将永远不会执行。 <code>final-expression</code>在每次循环迭代结束时执行,在下一次<code>condition</code>检查之前执行,通常用于递增或递减循环计数器。在下面的示例中,我们使用<code>i = 0</code>初始化并迭代,而条件<code>i < 5</code>为真。我们将在每个循环迭代中将<code>i</code>递增<code>1</code> ,并使用<code>i++</code>作为<code>final-expression</code> 。 <blockquote> var ourArray = []; <br> for(var i = 0; i <5; i ++){ <br> ourArray.push(ⅰ); <br> } </blockquote> <code>ourArray</code>现在包含<code>[0,1,2,3,4]</code> 。 </section>
<add><section id='description'>
<add>你可以使用循环多次执行相同的代码。
<add>JavaScript 中最常见的循环就是 “<code>for循环</code>”。
<add>for循环中的三个表达式用分号隔开:
<add><code>for ([初始化]; [条件判断]; [计数器])</code>
<add><code>初始化</code>语句只会在执行循环开始之前执行一次。它通常用于定义和设置你的循环变量。
<add><code>条件判断</code>语句会在每一轮循环的开始执行,只要条件判断为<code>true</code>就会继续执行循环。当条件为<code>false</code>的时候,循环将停止执行。这意味着,如果条件在一开始就为<code>false</code>,这个循环将不会执行。
<add><code>计数器</code>是在每一轮循环结束时执行,通常用于递增或递减。
<add>在下面的例子中,先初始化<code>i = 0</code>,条件<code>i < 5</code>为真,进入第一次循环,执行大括号里的代码,第一次循环结束。递增<code>i</code>的值,条件判断,就这样依次执行下去,直到条件判断为假,整个循环结束。
<add>
<add>```js
<add>var ourArray = [];
<add>for (var i = 0; i < 5; i++) {
<add> ourArray.push(i);
<add>}
<add>```
<add>
<add>最终<code>ourArray</code>的值为<code>[0,1,2,3,4]</code>.
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>for</code>循环将值1到5推送到<code>myArray</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>for</code>循环把从 1 到 5 添加进<code>myArray</code>中。
<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\s*\(/g).length > 1);
<del> - text: '<code>myArray</code>应该等于<code>[1,2,3,4,5]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[1,2,3,4,5]</code>。
<ide> testString: assert.deepEqual(myArray, [1,2,3,4,5]);
<ide>
<ide> ```
<ide> var myArray = [];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if (typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var ourArray = [];
<add>for (var i = 0; i < 5; i++) {
<add> ourArray.push(i);
<add>}
<add>var myArray = [];
<add>for (var i = 1; i < 6; i++) {
<add> myArray.push(i);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.chinese.md
<ide> id: cf1111c1c11feddfaeb1bdef
<ide> title: Iterate with JavaScript While Loops
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 在循环时使用JavaScript进行迭代
<add>videoUrl: 'https://scrimba.com/c/c8QbnCM'
<add>forumTopicId: 18220
<add>localeTitle: while 循环
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用循环多次运行相同的代码。我们将学习的第一种类型的循环称为“ <code>while</code> ”循环,因为它在“while”运行时指定的条件为true,并且一旦该条件不再为真就停止。 <blockquote> var ourArray = []; <br> var i = 0; <br>而(i <5){ <br> ourArray.push(ⅰ); <br>我++; <br> } </blockquote>让我们尝试通过将值推送到数组来实现while循环。 </section>
<add><section id='description'>
<add>你可以使用循环多次执行相同的代码。
<add>我们将学习的第一种类型的循环称为 "<code>while</code>" 循环,因为它规定,当 "while" 条件为真,循环才会执行,反之不执行。
<add>
<add>```js
<add>var ourArray = [];
<add>var i = 0;
<add>while(i < 5) {
<add> ourArray.push(i);
<add> i++;
<add>}
<add>```
<add>
<add>在上面的代码里,<code>while</code> 循环执行 5 次把 0 到 4 的数字添加到 <code>ourArray</code> 数组里。
<add>
<add>让我们通过 while 循环将值添加到数组中。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>while</code>循环将数字0到4推送到<code>myArray</code> 。 </section>
<add><section id='instructions'>
<add>通过一个<code>while</code>循环,把从 0 到 4 的值添加到<code>myArray</code>中。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 在循环时使用JavaScript进行迭代
<ide> tests:
<ide> - text: 你应该使用<code>while</code>循环。
<ide> testString: assert(code.match(/while/g));
<del> - text: '<code>myArray</code>应该等于<code>[0,1,2,3,4]</code> 。'
<del> testString: assert.deepEqual(myArray, [5,4,3,2,1,0]);
<add> - text: <code>myArray</code>应该等于<code>[0,1,2,3,4]</code>。
<add> testString: assert.deepEqual(myArray, [0,1,2,3,4]);
<ide>
<ide> ```
<ide>
<ide> var myArray = [];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [];
<add>var i = 5;
<add>while(i >= 0) {
<add> myArray.push(i);
<add> i--;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.chinese.md
<ide> id: 56533eb9ac21ba0edf2244bf
<ide> title: Local Scope and Functions
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 本地范围和功能
<add>videoUrl: 'https://scrimba.com/c/cd62NhM'
<add>forumTopicId: 18227
<add>localeTitle: 局部作用域和函数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在函数内声明的变量,以及函数参数都具有<dfn>局部</dfn>范围。这意味着,它们仅在该功能中可见。这是一个函数<code>myTest</code>带有一个名为<code>loc</code>的局部变量。 <blockquote> function myTest(){ <br> var loc =“foo”; <br>的console.log(LOC); <br> } <br> MYTEST(); //记录“foo” <br>的console.log(LOC); // loc未定义</blockquote> <code>loc</code>未在函数外定义。 </section>
<add><section id='description'>
<add>在一个函数内声明的变量,以及该函数的参数都是局部变量,意味着它们只在该函数内可见。
<add>这是在函数<code>myTest</code>内声明局部变量<code>loc</code>的例子:
<add>
<add>```js
<add>function myTest() {
<add> var loc = "foo";
<add> console.log(loc);
<add>}
<add>myTest(); // logs "foo"
<add>console.log(loc); // loc is not defined
<add>```
<add>
<add>在函数外,<code>loc</code>是未定义的。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>myLocalScope</code>声明一个局部变量<code>myVar</code> 。运行测试,然后按照编辑器中注释的说明进行操作。 <strong>暗示</strong> <br>如果您遇到问题,刷新页面可能会有所帮助。 </section>
<add><section id='instructions'>
<add>在函数<code>myFunction</code>内部声明一个局部变量<code>myVar</code>,并删除外部的 console.log。
<add><strong>提示:</strong><br>如果你遇到了问题,可以先尝试刷新页面。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 没有全局<code>myVar</code>变量
<add> - text: 未找到全局的<code>myVar</code>变量。
<ide> testString: assert(typeof myVar === 'undefined');
<del> - text: 添加本地<code>myVar</code>变量
<del> testString: assert(/function\s+myLocalScope\s*\(\s*\)\s*\{\s[\s\S]+\s*var\s*myVar\s*(\s*|=[\s\S]+)\s*;[\s\S]+}/.test(code));
<add> - text: 需要定义局部的<code>myVar</code>变量。
<add> testString: assert(/var\s+myVar/.test(code));
<add>
<ide>
<ide> ```
<ide>
<ide> function uncapture() {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>typeof myLocalScope === 'function' && (capture(), myLocalScope(), uncapture());
<add>(function() { return logOutput || "console.log never called"; })();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function myLocalScope() {
<add> 'use strict';
<add>
<add> var myVar;
<add> console.log(myVar);
<add>}
<add>myLocalScope();
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.chinese.md
<ide> id: 5690307fddb111c6084545d7
<ide> title: Logical Order in If Else Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 如果其他陈述中的逻辑顺序
<add>videoUrl: 'https://scrimba.com/c/cwNvMUV'
<add>forumTopicId: 18228
<add>localeTitle: if else 语句中的逻辑顺序
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">订单在<code>if</code> , <code>else if</code>语句中很重要。该函数从上到下执行,因此您需要注意首先出现的语句。以这两个函数为例。这是第一个: <blockquote> function foo(x){ <br> if(x <1){ <br>返回“少于一个”; <br> } else if(x <2){ <br>返回“少于两个”; <br> } else { <br>返回“大于或等于2”; <br> } <br> } </blockquote>第二个只是切换语句的顺序: <blockquote>功能栏(x){ <br> if(x <2){ <br>返回“少于两个”; <br> } else if(x <1){ <br>返回“少于一个”; <br> } else { <br>返回“大于或等于2”; <br> } <br> } </blockquote>虽然如果我们将数字传递给两者,这两个函数看起来几乎相同但我们得到不同的输出。 <blockquote> foo(0)//“不到一个” <br> bar(0)//“少于两个” </blockquote></section>
<add><section id='description'>
<add><code>if</code>、<code>else if</code>语句中代码的执行顺序是很重要的。
<add>在条件判断语句中,代码的执行顺序是从上到下,所以你需要考虑清楚先执行哪一句,后执行哪一句。
<add>这有两个例子。
<add>第一个例子:
<add>
<add>```js
<add>function foo(x) {
<add> if (x < 1) {
<add> return "Less than one";
<add> } else if (x < 2) {
<add> return "Less than two";
<add> } else {
<add> return "Greater than or equal to two";
<add> }
<add>}
<add>```
<add>
<add>第二个例子更改了代码的执行顺序:
<add>
<add>```js
<add>function bar(x) {
<add> if (x < 2) {
<add> return "Less than two";
<add> } else if (x < 1) {
<add> return "Less than one";
<add> } else {
<add> return "Greater than or equal to two";
<add> }
<add>}
<add>```
<add>
<add>这两个函数看起来几乎一模一样,我们传一个值进去看看它们有什么区别。
<add>
<add>```js
<add>foo(0) // "Less than one"
<add>bar(0) // "Less than two"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改函数中的逻辑顺序,以便在所有情况下都返回正确的语句。 </section>
<add><section id='instructions'>
<add>更改函数的逻辑顺序以便通过所有的测试用例。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>orderMyLogic(4)</code>应返回“小于5”
<add> - text: <code>orderMyLogic(4)</code>应该返回 "Less than 5"。
<ide> testString: assert(orderMyLogic(4) === "Less than 5");
<del> - text: <code>orderMyLogic(6)</code>应该返回“少于10”
<add> - text: <code>orderMyLogic(6)</code>应该返回 "Less than 10"。
<ide> testString: assert(orderMyLogic(6) === "Less than 10");
<del> - text: <code>orderMyLogic(11)</code>应该返回“大于或等于10”
<add> - text: <code>orderMyLogic(11)</code>应该返回 "Greater than or equal to 10"。
<ide> testString: assert(orderMyLogic(11) === "Greater than or equal to 10");
<ide>
<ide> ```
<ide> function orderMyLogic(val) {
<ide>
<ide> // Change this value to test
<ide> orderMyLogic(7);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> orderMyLogic(7);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function orderMyLogic(val) {
<add> if(val < 5) {
<add> return "Less than 5";
<add> } else if (val < 10) {
<add> return "Less than 10";
<add> } else {
<add> return "Greater than or equal to 10";
<add> }
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.chinese.md
<ide> id: 56bbb991ad1ed5201cd392cc
<ide> title: Manipulate Arrays With pop()
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用pop()操作数组
<add>videoUrl: 'https://scrimba.com/c/cRbVZAB'
<add>forumTopicId: 18236
<add>localeTitle: 使用 pop() 操作数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">更改数组中数据的另一种方法是使用<code>.pop()</code>函数。 <code>.pop()</code>用于“弹出”数组末尾的值。我们可以通过将其赋值给变量来存储这个“弹出”值。换句话说, <code>.pop()</code>从数组中删除最后一个元素并返回该元素。任何类型的条目都可以从数组“弹出” - 数字,字符串,甚至嵌套数组。 <blockquote> <code>var threeArr = [1, 4, 6]; <br> var oneDown = threeArr.pop(); <br> console.log(oneDown); // Returns 6 <br> console.log(threeArr); // Returns [1, 4]</code> </blockquote> </section>
<add><section id='description'>
<add>改变数组中数据的另一种方法是用<code>.pop()</code>函数。
<add><code>.pop()</code>函数用来“抛出”一个数组末尾的值。我们可以把这个“抛出”的值赋给一个变量存储起来。换句话说就是<code>.pop()</code>函数移除数组末尾的元素并返回这个元素。
<add>数组中任何类型的元素(数值,字符串,甚至是数组)可以被“抛出来” 。
<add>
<add>```js
<add>var threeArr = [1, 4, 6];
<add>var oneDown = threeArr.pop();
<add>console.log(oneDown); // Returns 6
<add>console.log(threeArr); // Returns [1, 4]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>.pop()</code>函数从<code>myArray</code>删除最后一项,将“弹出”值分配给<code>removedFromMyArray</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>.pop()</code>函数移除<code>myArray</code>中的最后一个元素,并且把“抛出”的值赋给<code>removedFromMyArray</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>myArray</code>应该只包含<code>[["John", 23]]</code> 。'
<add> - text: <code>myArray</code>应该只包含<code>[["John", 23]]</code>。
<ide> testString: assert((function(d){if(d[0][0] == 'John' && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray));
<del> - text: 在<code>myArray</code>上使用<code>pop()</code>
<add> - text: 对<code>myArray</code>使用<code>pop()</code>函数。
<ide> testString: assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
<del> - text: '<code>removedFromMyArray</code>应该只包含<code>["cat", 2]</code> 。'
<add> - text: <code>removedFromMyArray</code>应该只包含<code>["cat", 2]</code>。
<ide> testString: assert((function(d){if(d[0] == 'cat' && d[1] === 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray));
<ide>
<ide> ```
<ide> var myArray = [["John", 23], ["cat", 2]];
<ide> // Only change code below this line.
<ide> var removedFromMyArray;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var removedFromMyArray;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [["John", 23], ["cat", 2]];
<add>var removedFromMyArray = myArray.pop();
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.chinese.md
<ide> id: 56bbb991ad1ed5201cd392cb
<ide> title: Manipulate Arrays With push()
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 用push()操纵数组
<add>videoUrl: 'https://scrimba.com/c/cnqmVtJ'
<add>forumTopicId: 18237
<add>localeTitle: 使用 push() 操作数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">将数据附加到数组末尾的简单方法是通过<code>push()</code>函数。 <code>.push()</code>接受一个或多个<dfn>参数</dfn>并将它们“推”到数组的末尾。 <blockquote> var arr = [1,2,3]; <br> arr.push(4); <br> // arr现在是[1,2,3,4] </blockquote></section>
<add><section id='description'>
<add>一个简单的方法将数据添加到一个数组的末尾是通过<code>push()</code>函数。
<add><code>.push()</code>接受一个或多个参数,并把它“推”入到数组的末尾。
<add>
<add>```js
<add>var arr = [1,2,3];
<add>arr.push(4);
<add>// arr is now [1,2,3,4]
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>["dog", 3]</code>推到<code>myArray</code>变量的末尾。 </section>
<add><section id='instructions'>
<add>把<code>["dog", 3]</code>“推”入到<code>myArray</code>变量的末尾。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>myArray</code>现在应该等于<code>[["John", 23], ["cat", 2], ["dog", 3]]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[["John", 23], ["cat", 2], ["dog", 3]]</code>。
<ide> testString: assert((function(d){if(d[2] != undefined && d[0][0] == 'John' && d[0][1] === 23 && d[2][0] == 'dog' && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray));
<ide>
<ide> ```
<ide> var myArray = [["John", 23], ["cat", 2]];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [["John", 23], ["cat", 2]];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [["John", 23], ["cat", 2]];
<add>myArray.push(["dog",3]);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.chinese.md
<ide> id: 56bbb991ad1ed5201cd392cd
<ide> title: Manipulate Arrays With shift()
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用shift()操纵数组
<add>videoUrl: 'https://scrimba.com/c/cRbVETW'
<add>forumTopicId: 18238
<add>localeTitle: 使用 shift() 操作数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>pop()</code>总是删除数组的最后一个元素。如果你想删除第一个怎么办?这就是<code>.shift()</code>用武之地。它就像<code>.pop()</code>一样工作,除了它删除了第一个元素而不是最后一个元素。 </section>
<add><section id='description'>
<add><code>pop()</code>函数用来移出数组中最后一个元素。如果想要移出第一个元素要怎么办呢?
<add>这就是<code>.shift()</code>的用武之地。它的工作原理就像<code>.pop()</code>,但它移除的是第一个元素,而不是最后一个。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>.shift()</code>函数从<code>myArray</code>删除第一项,将“shift off”值分配给<code>removedFromMyArray</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>.shift()</code>函数移出<code>myArray</code>中的第一项,并把“移出”的值赋给<code>removedFromMyArray</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>myArray</code>现在应该等于<code>[["dog", 3]]</code> 。'
<add> - text: <code>myArray</code>应该等于<code>[["dog", 3]]</code>。
<ide> testString: assert((function(d){if(d[0][0] == 'dog' && d[0][1] === 3 && d[1] == undefined){return true;}else{return false;}})(myArray));
<del> - text: '<code>removedFromMyArray</code>应该包含<code>["John", 23]</code> 。'
<add> - text: <code>removedFromMyArray</code>应该包含<code>["John", 23]</code>。
<ide> testString: assert((function(d){if(d[0] == 'John' && d[1] === 23 && typeof removedFromMyArray === 'object'){return true;}else{return false;}})(removedFromMyArray));
<ide>
<ide> ```
<ide> var myArray = [["John", 23], ["dog", 3]];
<ide> // Only change code below this line.
<ide> var removedFromMyArray;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var removedFromMyArray;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [["John", 23], ["dog", 3]];
<add>
<add>// Only change code below this line.
<add>var removedFromMyArray = myArray.shift();
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.chinese.md
<ide> id: 56bbb991ad1ed5201cd392ce
<ide> title: Manipulate Arrays With unshift()
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用unshift操作数组()
<add>videoUrl: 'https://scrimba.com/c/ckNDESv'
<add>forumTopicId: 18239
<add>localeTitle: 使用 unshift() 操作数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">不仅可以<code>shift</code>元件关闭的阵列的开头的,也可以<code>unshift</code>元素添加到数组的开始,即在阵列的前添加元素。 <code>.unshift()</code>工作方式与<code>.push()</code>完全相同,但是不是在数组的末尾添加元素, <code>unshift()</code>会在数组的开头添加元素。 </section>
<add><section id='description'>
<add>你不仅可以<code>shift</code>(移出)数组中的第一个元素,你也可以<code>unshift</code>(移入)一个元素到数组的头部。
<add><code>.unshift()</code>函数用起来就像<code>.push()</code>函数一样, 但不是在数组的末尾添加元素,而是在数组的头部添加元素。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>unshift()</code>将<code>["Paul",35]</code>添加到<code>myArray</code>变量的开头。 </section>
<add><section id='instructions'>
<add>使用<code>unshift()</code>函数把<code>["Paul",35]</code>加入到<code>myArray</code>的头部。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>myArray</code>现在应该有[[“Paul”,35],[“dog”,3]]。'
<add> - text: <code>myArray</code>应该包含[["Paul", 35], ["dog", 3]]。
<ide> testString: assert((function(d){if(typeof d[0] === "object" && d[0][0] == 'Paul' && d[0][1] === 35 && d[1][0] != undefined && d[1][0] == 'dog' && d[1][1] != undefined && d[1][1] == 3){return true;}else{return false;}})(myArray));
<ide>
<ide> ```
<ide> myArray.shift();
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> myArray.shift();
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y, z){return 'myArray = ' + JSON.stringify(y);})(myArray);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [["John", 23], ["dog", 3]];
<add>myArray.shift();
<add>myArray.unshift(["Paul", 35]);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.chinese.md
<ide> id: 56533eb9ac21ba0edf2244cb
<ide> title: Manipulating Complex Objects
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 操纵复杂对象
<add>videoUrl: 'https://scrimba.com/c/c9yNMfR'
<add>forumTopicId: 18208
<add>localeTitle: 操作复杂对象
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时您可能希望将数据存储在灵活的<dfn>数据结构中</dfn> 。 JavaScript对象是处理灵活数据的一种方法。它们允许<dfn>字符串</dfn> , <dfn>数字</dfn> , <dfn>布尔值</dfn> , <dfn>数组</dfn> , <dfn>函数</dfn>和<dfn>对象的</dfn>任意组合。这是一个复杂数据结构的示例: <blockquote> var ourMusic = [ <br> { <br> “艺术家”:“Daft Punk”, <br> “标题”:“家庭作业”, <br> “release_year”:1997年, <br> “格式”:[ <br> “光盘”, <br> “盒式” <br> “LP” <br> ] <br> “黄金”:是的<br> } <br> ]。 </blockquote>这是一个包含一个对象的数组。该对象具有关于专辑的各种<dfn>元数据</dfn> 。它还有一个嵌套的<code>"formats"</code>数组。如果要添加更多专辑记录,可以通过向顶级数组添加记录来完成此操作。对象将数据保存在属性中,该属性具有键值格式。在上面的示例中, <code>"artist": "Daft Punk"</code>是具有<code>"artist"</code>键和<code>"Daft Punk"</code>值的属性。 <a href="http://www.json.org/" target="_blank">JavaScript Object Notation</a>或<code>JSON</code>是用于存储数据的相关数据交换格式。 <blockquote> { <br> “艺术家”:“Daft Punk”, <br> “标题”:“家庭作业”, <br> “release_year”:1997年, <br> “格式”:[ <br> “光盘”, <br> “盒式” <br> “LP” <br> ] <br> “黄金”:是的<br> } </blockquote> <strong>注意</strong> <br>除非它是数组中的最后一个对象,否则您需要在数组中的每个对象后面放置一个逗号。 </section>
<add><section id='description'>
<add>有时你可能希望将数据存储在灵活的<dfn>数据结构</dfn>中。JavaScript 对象是处理灵活数据的一种方法。它可以储存<dfn>字符串</dfn>,<dfn>数字</dfn>,<dfn>布尔值</dfn>,<dfn>函数</dfn>,和<dfn>对象</dfn>以及这些值的任意组合。
<add>这是一个复杂数据结构的示例:
<add>
<add>```js
<add>var ourMusic = [
<add> {
<add> "artist": "Daft Punk",
<add> "title": "Homework",
<add> "release_year": 1997,
<add> "formats": [
<add> "CD",
<add> "Cassette",
<add> "LP"
<add> ],
<add> "gold": true
<add> }
<add>];
<add>```
<add>
<add>这是一个对象数组,并且对象有各种关于专辑的 <dfn>详细信息</dfn>。它也有一个嵌套的<code>formats</code>的数组。附加专辑记录可以被添加到数组的最上层。
<add>对象将数据以一种键-值对的形式保存。在上面的示例中,<code>"artist": "Daft Punk"</code>是一个具有<code>"artist"</code>键和<code>"Daft Punk"</code>值的属性。
<add><a href='http://www.json.org/' target=_blank>JavaScript Object Notation</a> 简称<code>JSON</code>是用于存储数据的相关数据交换格式。
<add>
<add>```json
<add>{
<add> "artist": "Daft Punk",
<add> "title": "Homework",
<add> "release_year": 1997,
<add> "formats": [
<add> "CD",
<add> "Cassette",
<add> "LP"
<add> ],
<add> "gold": true
<add>}
<add>```
<add>
<add><strong>提示</strong><br>数组中有多个 JSON 对象的时候,对象与对象之间要用逗号隔开。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将新相册添加到<code>myMusic</code>阵列。添加<code>artist</code>和<code>title</code>字符串, <code>release_year</code>数字和<code>formats</code>字符串数组。 </section>
<add><section id='instructions'>
<add>添加一个新专辑到<code>myMusic</code>的JSON对象。添加<code>artist</code>和<code>title</code>字符串,<code>release_year</code>数字和<code>formats</code>字符串数组。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myMusic</code>应该是一个数组
<add> - text: <code>myMusic</code>应该是一个数组。
<ide> testString: assert(Array.isArray(myMusic));
<del> - text: <code>myMusic</code>应该至少有两个元素
<add> - text: <code>myMusic</code>应该至少包含两个元素。
<ide> testString: assert(myMusic.length > 1);
<del> - text: '<code>myMusic[1]</code>应该是一个对象'
<add> - text: <code>myMusic[1]</code>应该是一个对象。
<ide> testString: assert(typeof myMusic[1] === 'object');
<del> - text: '<code>myMusic[1]</code>应该至少有4个属性'
<add> - text: <code>myMusic[1]</code>至少要包含四个属性。
<ide> testString: assert(Object.keys(myMusic[1]).length > 3);
<del> - text: '<code>myMusic[1]</code>应该包含一个<code>artist</code>属性,它是一个字符串'
<add> - text: <code>myMusic[1]</code>应该包含一个类型为字符串的<code>artist</code>的属性。
<ide> testString: assert(myMusic[1].hasOwnProperty('artist') && typeof myMusic[1].artist === 'string');
<del> - text: '<code>myMusic[1]</code>应该包含一个<code>title</code>属性,它是一个字符串'
<add> - text: <code>myMusic[1]</code>应该包含一个类型为字符串的<code>title</code>的属性。
<ide> testString: assert(myMusic[1].hasOwnProperty('title') && typeof myMusic[1].title === 'string');
<del> - text: '<code>myMusic[1]</code>应该包含一个<code>release_year</code>属性,它是一个数字'
<add> - text: <code>myMusic[1]</code>应该包含一个类型为数字的<code>release_year</code> 应该包含一个类型为数字的属性。
<ide> testString: assert(myMusic[1].hasOwnProperty('release_year') && typeof myMusic[1].release_year === 'number');
<del> - text: '<code>myMusic[1]</code>应该包含一个<code>formats</code>属性,它是一个数组'
<add> - text: <code>myMusic[1]</code>应该包含一个类型为数组的<code>formats</code>属性。
<ide> testString: assert(myMusic[1].hasOwnProperty('formats') && Array.isArray(myMusic[1].formats));
<del> - text: <code>formats</code>应该是一个至少包含两个元素的字符串数组
<add> - text: <code>formats</code>应该是一个至少包含两个字符串元素的数组。
<ide> testString: assert(myMusic[1].formats.every(function(item) { return (typeof item === "string")}) && myMusic[1].formats.length > 1);
<ide>
<ide> ```
<ide> var myMusic = [
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(x){ if (Array.isArray(x)) { return JSON.stringify(x); } return "myMusic is not an array"})(myMusic);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myMusic = [
<add> {
<add> "artist": "Billy Joel",
<add> "title": "Piano Man",
<add> "release_year": 1973,
<add> "formats": [
<add> "CS",
<add> "8T",
<add> "LP" ],
<add> "gold": true
<add> },
<add> {
<add> "artist": "ABBA",
<add> "title": "Ring Ring",
<add> "release_year": 1973,
<add> "formats": [
<add> "CS",
<add> "8T",
<add> "LP",
<add> "CD",
<add> ]
<add> }
<add>];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.chinese.md
<ide> id: cf1111c1c11feddfaeb8bdef
<ide> title: Modify Array Data With Indexes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用索引修改数组数据
<add>videoUrl: 'https://scrimba.com/c/czQM4A8'
<add>forumTopicId: 18241
<add>localeTitle: 通过索引修改数组中的数据
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">与字符串不同,数组的条目是<dfn>可变的</dfn> ,可以自由更改。 <strong>例</strong> <blockquote> var ourArray = [50,40,30]; <br> ourArray [0] = 15; //等于[15,40,30] </blockquote> <strong>注意</strong> <br>数组名称和方括号之间不应有任何空格,如<code>array [0]</code> 。尽管JavaScript能够正确处理,但这可能会让其他程序员在阅读代码时感到困惑。 </section>
<add><section id='description'>
<add>与字符串的数据不可变不同,数组的数据是可变的,并且可以自由地改变。
<add><strong>示例</strong>
<add>
<add>```js
<add>var ourArray = [50,40,30];
<add>ourArray[0] = 15; // equals [15,40,30]
<add>```
<add>
<add><strong>提示</strong><br>数组名称和方括号之间不应有任何空格,如<code>array [0]</code>尽管 JavaScript 能够正确处理,但可能会让看你代码的其他程序员感到困惑。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将存储在<code>myArray</code>索引<code>0</code>处的数据修改为值<code>45</code> 。 </section>
<add><section id='instructions'>
<add>修改数组<code>myArray</code>中索引0上的值为<code>45</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>myArray</code>现在应该是[45,64,99]。'
<add> - text: <code>myArray</code>的值应该 [45,64,99]。
<ide> testString: assert((function(){if(typeof myArray != 'undefined' && myArray[0] == 45 && myArray[1] == 64 && myArray[2] == 99){return true;}else{return false;}})());
<del> - text: 您应该使用正确的索引来修改<code>myArray</code>的值。
<add> - text: 你应该使用正确的索引修改<code>myArray</code>的值。
<ide> testString: assert((function(){if(code.match(/myArray\[0\]\s*=\s*/g)){return true;}else{return false;}})());
<ide>
<ide> ```
<ide> var myArray = [18,64,99];
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myArray = [18,64,99];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [18,64,99];
<add>myArray[0] = 45;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244df
<ide> title: Multiple Identical Options in Switch Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 交换机语句中的多个相同选项
<add>videoUrl: 'https://scrimba.com/c/cdBKWCV'
<add>forumTopicId: 18242
<add>localeTitle: 在 Switch 语句添加多个相同选项
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果从<code>switch</code>语句的<code>case</code>省略了<code>break</code>语句,则会执行以下<code>case</code>语句,直到遇到<code>break</code> 。如果您有多个具有相同输出的输入,则可以在<code>switch</code>语句中表示它们,如下所示: <blockquote> switch(val){ <br>情况1: <br>案例2: <br>案例3: <br> result =“1,2或3”; <br>打破; <br>案例4: <br> result =“4 alone”; <br> } </blockquote> 1,2和3的情况都会产生相同的结果。 </section>
<add><section id='description'>
<add>如果你忘了给<code>switch</code>的每一条<code>case</code>添加<code>break</code>,那么直到遇见<code>break</code>为止,后续的<code>case</code>会一直执行。如果你想为多个不同的输入设置相同的结果,可以这样写:
<add>
<add>```js
<add>switch(val) {
<add> case 1:
<add> case 2:
<add> case 3:
<add> result = "1, 2, or 3";
<add> break;
<add> case 4:
<add> result = "4 alone";
<add>}
<add>```
<add>
<add>这样,1、2、3 都会有相同的结果。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">写一个switch语句来设置以下范围的<code>answer</code> : <br> <code>1-3</code> - “低” <br> <code>4-6</code> - “中” <br> <code>7-9</code> - “高” <strong>注</strong> <br>您需要为范围中的每个数字都有一个<code>case</code>语句。 </section>
<add><section id='instructions'>
<add>请写一个<code>switch</code>语句,根据输入的<code>val</code>的范围得出对应的<code>answer</code>:<br><code>1-3</code> - "Low"<br><code>4-6</code> - "Mid"<br><code>7-9</code> - "High"
<add><strong>提示:</strong><br>你的<code>case</code>应基于范围中的每一个数字编写。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>sequentialSizes(1)</code>应返回“Low”
<add> - text: <code>sequentialSizes(1)</code>应该返回 "Low"。
<ide> testString: assert(sequentialSizes(1) === "Low");
<del> - text: <code>sequentialSizes(2)</code>应该返回“Low”
<add> - text: <code>sequentialSizes(2)</code>应该返回 "Low"。
<ide> testString: assert(sequentialSizes(2) === "Low");
<del> - text: <code>sequentialSizes(3)</code>应返回“Low”
<add> - text: <code>sequentialSizes(3)</code>应该返回 "Low"。
<ide> testString: assert(sequentialSizes(3) === "Low");
<del> - text: <code>sequentialSizes(4)</code>应返回“Mid”
<add> - text: <code>sequentialSizes(4)</code>应该返回 "Mid"。
<ide> testString: assert(sequentialSizes(4) === "Mid");
<del> - text: <code>sequentialSizes(5)</code>应返回“Mid”
<add> - text: <code>sequentialSizes(5)</code>应该返回 "Mid"。
<ide> testString: assert(sequentialSizes(5) === "Mid");
<del> - text: <code>sequentialSizes(6)</code>应返回“Mid”
<add> - text: <code>sequentialSizes(6)</code>应该返回 "Mid"。
<ide> testString: assert(sequentialSizes(6) === "Mid");
<del> - text: <code>sequentialSizes(7)</code>应该返回“High”
<add> - text: <code>sequentialSizes(7)</code>应该返回 "High"。
<ide> testString: assert(sequentialSizes(7) === "High");
<del> - text: <code>sequentialSizes(8)</code>应该返回“High”
<add> - text: <code>sequentialSizes(8)</code>应该返回 "High"。
<ide> testString: assert(sequentialSizes(8) === "High");
<del> - text: <code>sequentialSizes(9)</code>应该返回“High”
<add> - text: <code>sequentialSizes(9)</code>应该返回 "High"。
<ide> testString: assert(sequentialSizes(9) === "High");
<del> - text: 您不应该使用任何<code>if</code>或<code>else</code>语句
<add> - text: 你不应使用<code>if</code>或<code>else</code>语句。
<ide> testString: assert(!/else/g.test(code) || !/if/g.test(code));
<del> - text: 你应该有九个<code>case</code>陈述
<add> - text: 你应该编写 9 个<code>case</code>语句。
<ide> testString: assert(code.match(/case/g).length === 9);
<ide>
<ide> ```
<ide> sequentialSizes(1);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function sequentialSizes(val) {
<add> var answer = "";
<add>
<add> switch(val) {
<add> case 1:
<add> case 2:
<add> case 3:
<add> answer = "Low";
<add> break;
<add> case 4:
<add> case 5:
<add> case 6:
<add> answer = "Mid";
<add> break;
<add> case 7:
<add> case 8:
<add> case 9:
<add> answer = "High";
<add> }
<add>
<add> return answer;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript.chinese.md
<ide> id: bd7993c9c69feddfaeb7bdef
<ide> title: Multiply Two Decimals with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript乘以两个小数
<add>videoUrl: 'https://scrimba.com/c/ce2GeHq'
<add>forumTopicId: 301173
<add>localeTitle: 两个小数相乘
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中,您也可以使用十进制数执行计算,就像整数一样。让我们将两位小数相乘得到它们的乘积。 </section>
<add><section id='description'>
<add>在 JavaScript 中,你也可以用小数进行计算,就像整数一样。
<add>把两个小数相乘,并得到它们乘积。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0.0</code>使产品等于<code>5.0</code> 。 </section>
<add><section id='instructions'>
<add>改变<code>0.0</code>的数值让变量<code>product</code>的值等于<code>5.0</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 变量<code>product</code>应该等于<code>5.0</code> 。
<add> - text: 变量<code>product</code>应该等于<code>5.0</code>。
<ide> testString: assert(product === 5.0);
<del> - text: 你应该使用<code>*</code>运算符
<add> - text: 要使用<code>*</code>运算符。
<ide> testString: assert(/\*/.test(code));
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> var product = 2.0 * 0.0;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var product = 2.0 * 0.0;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(y){return 'product = '+y;})(product);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var product = 2.0 * 2.5;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.chinese.md
<ide> id: cf1231c1c11feddfaeb5bdef
<ide> title: Multiply Two Numbers with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript将两个数字相乘
<add>videoUrl: 'https://scrimba.com/c/cP3y3Aq'
<add>forumTopicId: 18243
<add>localeTitle: 乘法运算
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们也可以将一个数字乘以另一个数字。 JavaScript使用<code>*</code>符号来乘以两个数字。 <p> <strong>例</strong> </p><blockquote> myVar = 13 * 13; //指定169 </blockquote></section>
<add><section id='description'>
<add>我们也可在 JavaScript 中使用乘法运算。
<add>JavaScript 使用<code>*</code>符号表示两数相乘。
<add>
<add><strong>示例</strong>
<add>
<add>```js
<add>myVar = 13 * 13; // assigned 169
<add>```
<add>
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0</code>使产品等于<code>80</code> 。 </section>
<add><section id='instructions'>
<add>改变数值<code>0</code>来让变量 product 的值等于<code>80</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 使变量<code>product</code>等于80
<add> - text: 要使<code>product</code>的值等于 80。
<ide> testString: assert(product === 80);
<del> - text: 使用<code>*</code>运算符
<add> - text: 使用<code>*</code>运算符。
<ide> testString: assert(/\*/.test(code));
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> var product = 8 * 0;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var product = 8 * 0;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'product = '+z;})(product);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var product = 8 * 10;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.chinese.md
<ide> id: cf1111c1c11feddfaeb7bdef
<ide> title: Nest one Array within Another Array
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 将一个Array嵌套在另一个Array中
<add>videoUrl: 'https://scrimba.com/c/crZQZf8'
<add>forumTopicId: 18247
<add>localeTitle: 将一个数组嵌套在另一个数组中
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您还可以在其他数组中嵌套数组,如: <code>[["Bulls", 23], ["White Sox", 45]]</code> 。这也称为<dfn>多维数组<dfn>。</dfn></dfn> </section>
<add><section id='description'>
<add>你也可以在数组中包含其他数组,例如:<code>[["Bulls", 23], ["White Sox", 45]]</code>。这被称为一个<dfn>多维数组<dfn>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>myArray</code>的嵌套数组。 </section>
<add><section id='instructions'>
<add>创建一个名为<code>myArray</code>的多维数组。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myArray</code>应至少有一个嵌套在另一个数组中的数组。
<add> - text: 应该包含至少一个嵌入的数组。
<ide> testString: assert(Array.isArray(myArray) && myArray.some(Array.isArray));
<ide>
<ide> ```
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>if(typeof myArray !== "undefined"){(function(){return myArray;})();}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = [[1,2,3]];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.chinese.md
<ide> id: 56533eb9ac21ba0edf2244e1
<ide> title: Nesting For Loops
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 嵌套循环
<add>videoUrl: 'https://scrimba.com/c/cRn6GHM'
<add>forumTopicId: 18248
<add>localeTitle: 循环嵌套
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果您有一个多维数组,则可以使用与先前路点相同的逻辑来遍历数组和任何子数组。这是一个例子: <blockquote> var arr = [ <br> [1,2],[3,4],[5,6] <br> ]。 <br> for(var i = 0; i <arr.length; i ++){ <br> for(var j = 0; j <arr [i] .length; j ++){ <br>的console.log(ARR [i] [j]); <br> } <br> } </blockquote>这个输出在每个子元件<code>arr</code>一次一个。注意,对于内部循环,我们检查<code>arr[i]</code>的<code>.length</code> ,因为<code>arr[i]</code>本身就是一个数组。 </section>
<add><section id='description'>
<add>如果你有一个二维数组,可以使用相同的逻辑,先遍历外面的数组,再遍历里面的子数组。下面是一个例子:
<add>
<add>```js
<add>var arr = [
<add> [1,2], [3,4], [5,6]
<add>];
<add>for (var i=0; i < arr.length; i++) {
<add> for (var j=0; j < arr[i].length; j++) {
<add> console.log(arr[i][j]);
<add> }
<add>}
<add>```
<add>
<add>一次输出<code>arr</code>中的每个子元素。提示,对于内部循环,我们可以通过<code>arr[i]</code>的<code>.length</code>来获得子数组的长度,因为<code>arr[i]</code>的本身就是一个数组。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改函数<code>multiplyAll</code> ,使其乘以<code>product</code>变量乘以<code>arr</code>的子数组中的每个数字</section>
<add><section id='instructions'>
<add>修改函数<code>multiplyAll</code>,获得<code>arr</code>内部数组的每个数字相乘的结果<code>product</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>multiplyAll([[1],[2],[3]])</code>应该返回<code>6</code>'
<add> - text: <code>multiplyAll([[1],[2],[3]])</code>应该返回 <code>6</code>。
<ide> testString: assert(multiplyAll([[1],[2],[3]]) === 6);
<del> - text: '<code>multiplyAll([[1,2],[3,4],[5,6,7]])</code>应返回<code>5040</code>'
<add> - text: <code>multiplyAll([[1,2],[3,4],[5,6,7]])</code>应该返回 <code>5040</code>。
<ide> testString: assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040);
<del> - text: '<code>multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])</code>应该返回<code>54</code>'
<add> - text: <code>multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])</code>应该返回 <code>54</code>。
<ide> testString: assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54);
<ide>
<ide> ```
<ide> multiplyAll([[1,2],[3,4],[5,6,7]]);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function multiplyAll(arr) {
<add> var product = 1;
<add> for (var i = 0; i < arr.length; i++) {
<add> for (var j = 0; j < arr[i].length; j++) {
<add> product *= arr[i][j];
<add> }
<add> }
<add> return product;
<add>}
<add>
<add>multiplyAll([[1,2],[3,4],[5,6,7]]);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.chinese.md
<ide> id: 56533eb9ac21ba0edf2244bd
<ide> title: Passing Values to Functions with Arguments
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 将值传递给带参数的函数
<add>videoUrl: 'https://scrimba.com/c/cy8rahW'
<add>forumTopicId: 18254
<add>localeTitle: 将值传递给带有参数的函数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>参数</dfn>是变量,它们作为调用函数时要输入到函数的值的占位符。定义函数时,通常将其与一个或多个参数一起定义。调用函数时输入(或<dfn>“传递”</dfn> )的实际值称为<dfn>参数</dfn> 。这是一个带有两个参数的函数, <code>param1</code>和<code>param2</code> : <blockquote> function testFun(param1,param2){ <br> console.log(param1,param2); <br> } </blockquote>然后我们可以调用<code>testFun</code> : <code>testFun("Hello", "World");</code>我们通过了两个论点, <code>"Hello"</code>和<code>"World"</code> 。在函数内部, <code>param1</code>将等于“Hello”, <code>param2</code>将等于“World”。请注意,您可以使用不同的参数再次调用<code>testFun</code> ,并且参数将采用新参数的值。 </section>
<add><section id='description'>
<add>函数的参数<code>parameters</code>在函数中充当占位符(也叫形参)的作用,参数可以为一个或多个。调用一个函数时所传入的参数为实参,实参决定着形参真正的值。简单理解:形参即形式、实参即内容。
<add>这是带有两个参数的函数,<code>param1</code>和<code>param2</code>:
<add>
<add>```js
<add>function testFun(param1, param2) {
<add> console.log(param1, param2);
<add>}
<add>```
<add>
<add>接着我们调用<code>testFun</code>:
<add><code>testFun("Hello", "World");</code>
<add>我们传递了两个参数,<code>"Hello"</code>和<code>"World"</code>。在函数内部,<code>param1</code>等于“Hello”,<code>param2</code>等于“World”。请注意,<code>testFun</code>函数可以多次调用,每次调用时传递的参数会决定形参的实际值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"><ol><li>创建一个名为<code>functionWithArgs</code> ,该函数接受两个参数并将其总和输出到开发控制台。 </li><li>使用两个数字作为参数调用该函数。 </li></ol></section>
<add><section id='instructions'>
<add><ol><li>创建一个名为<code>functionWithArgs</code>的函数,它可以接收两个参数,计算参数的和,将结果输出到控制台。</li><li>调用这个函数。</li></ol>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>functionWithArgs</code>应该是一个函数
<add> - text: <code>functionWithArgs</code>应该是一个函数。
<ide> testString: assert(typeof functionWithArgs === 'function');
<del> - text: '<code>functionWithArgs(1,2)</code>应该输出<code>3</code>'
<add> - text: <code>functionWithArgs(1,2)</code>应该输出<code>3</code>。
<ide> testString: if(typeof functionWithArgs === "function") { capture(); functionWithArgs(1,2); uncapture(); } assert(logOutput == 3);
<del> - text: '<code>functionWithArgs(7,9)</code>应该输出<code>16</code>'
<add> - text: <code>functionWithArgs(7,9)</code>应该输出<code>16</code>。
<ide> testString: if(typeof functionWithArgs === "function") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16);
<del> - text: 定义后,使用两个数字调用<code>functionWithArgs</code> 。
<del> testString: assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*/m.test(code));
<add> - text: 在你定义<code>functionWithArgs</code>之后记得调用它。
<add> testString: assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*;?/m.test(code));
<ide>
<ide> ```
<ide>
<ide> ourFunctionWithArgs(10, 5); // Outputs 5
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> function uncapture() {
<ide> }
<ide>
<ide> capture();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> capture();
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>uncapture();
<add>
<add>if (typeof functionWithArgs !== "function") {
<add> (function() { return "functionWithArgs is not defined"; })();
<add>} else {
<add> (function() { return logOutput || "console.log never called"; })();
<add>}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function functionWithArgs(a, b) {
<add> console.log(a + b);
<add>}
<add>functionWithArgs(10, 5);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.chinese.md
<ide> id: 599a789b454f2bbd91a3ff4d
<ide> title: Practice comparing different values
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 练习比较不同的值
<add>videoUrl: 'https://scrimba.com/c/cm8PqCa'
<add>forumTopicId: 301174
<add>localeTitle: 比较不同值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在最后两个挑战中,我们学习了等于运算符( <code>==</code> )和严格相等运算符( <code>===</code> )。让我们快速回顾一下这些运算符的实践。如果要比较的值不是同一类型,则相等运算符将执行类型转换,然后计算值。但是,严格相等运算符将按原样比较数据类型和值,而不将一种类型转换为另一种类型。 <strong>例子</strong> <blockquote> 3 =='3'//返回true,因为JavaScript执行从字符串到数字的类型转换<br> 3 ==='3'//返回false,因为类型不同并且未执行类型转换</blockquote> <strong>注意</strong> <br>在JavaScript中,您可以使用<code>typeof</code>运算符确定变量的类型或值,如下所示: <blockquote> typeof 3 //返回'number' <br> typeof'3'//返回'string' </blockquote></section>
<add><section id='description'>
<add>在上两个挑战中,我们学习了相等运算符 (<code>==</code>) 和严格相等运算符 (<code>===</code>)。现在让我们快速回顾并实践一下。
<add>如果要比较的值不是同一类型,相等运算符会先执行数据类型转换,然后比较值。而严格相等运算符只比较值,不会进行数据类型转换。
<add>由此可见,相等运算符和严格相等运算符的区别是:前者会执行隐式类型转换,后者不会。
<add><strong>示例</strong>
<add>
<add>```js
<add>3 == '3' // returns true because JavaScript performs type conversion from string to number
<add>3 === '3' // returns false because the types are different and type conversion is not performed
<add>```
<add>
<add><strong>提示</strong><br>在JavaScript中,你可以使用<code>typeof</code>运算符确定变量的类型或值,如下所示:
<add>
<add>```js
<add>typeof 3 // returns 'number'
<add>typeof '3' // returns 'string'
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">编辑器中的<code>compareEquality</code>函数使用<code>equality operator</code>比较两个值。修改函数,使其仅在值严格相等时返回“Equal”。 </section>
<add><section id='instructions'>
<add>编辑器中的<code>compareEquality</code>函数使用相等运算符比较两个值。修改函数,使其仅在值严格相等时返回 "Equal" 。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>compareEquality(10, "10")</code>应返回“Not Equal”'
<add> - text: <code>compareEquality(10, "10")</code>应该返回 "Not Equal"。
<ide> testString: assert(compareEquality(10, "10") === "Not Equal");
<del> - text: '<code>compareEquality("20", 20)</code>应该返回“Not Equal”'
<add> - text: <code>compareEquality("20", 20)</code>应该返回 "Not Equal"。
<ide> testString: assert(compareEquality("20", 20) === "Not Equal");
<del> - text: 您应该使用<code>===</code>运算符
<add> - text: 你应该使用<code>===</code>运算符。
<ide> testString: assert(code.match(/===/g));
<ide>
<ide> ```
<ide> function compareEquality(a, b) {
<ide>
<ide> // Change this value to test
<ide> compareEquality(10, "10");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> compareEquality(10, "10");
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function compareEquality(a,b) {
<add> if (a === b) {
<add> return "Equal";
<add> }
<add> return "Not Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.chinese.md
<ide> id: 5688e62ea601b2482ff8422b
<ide> title: Profile Lookup
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 个人资料查询
<add>videoUrl: 'https://scrimba.com/c/cDqW2Cg'
<add>forumTopicId: 18259
<add>localeTitle: 资料查找
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们的联系人列表中有一组代表不同人的对象。已经为您预先编写了一个以<code>name</code>和属性( <code>prop</code> )作为参数的<code>lookUpProfile</code>函数。该函数应检查<code>name</code>是否是实际联系人的<code>firstName</code> ,并且给定属性( <code>prop</code> )是该联系人的属性。如果两者都为真,则返回该属性的“值”。如果<code>name</code>与任何联系人不对应,则返回<code>"No such contact"</code>如果<code>prop</code>不符合找到匹配<code>name</code>的联系人的任何有效属性,则返回<code>"No such property"</code> </section>
<add><section id='description'>
<add>我们有一个对象数组,里面存储着通讯录。
<add>函数<code>lookUp</code>有两个预定义参数:<code>firstName</code>值和<code>prop</code>属性 。
<add>函数将会检查通讯录中是否存在一个与传入的<code>firstName</code>相同的联系人。如果存在,那么还需要检查对应的联系人中是否存在<code>prop</code>属性。
<add>如果它们都存在,函数返回<code>prop</code>属性对应的值。
<add>如果<code>firstName</code>值不存在,返回<code>"No such contact"</code>。
<add>如果<code>prop</code>属性不存在,返回<code>"No such property"</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>"Kristian", "lastName"</code>应该返回<code>"Vos"</code>'
<add> - text: <code>"Kristian", "lastName"</code>应该返回 <code>"Vos"</code>。
<ide> testString: assert(lookUpProfile('Kristian','lastName') === "Vos");
<del> - text: '<code>"Sherlock", "likes"</code>应该回归<code>["Intriguing Cases", "Violin"]</code>'
<add> - text: <code>"Sherlock", "likes"</code>应该返回 <code>["Intriguing Cases", "Violin"]</code>。
<ide> testString: assert.deepEqual(lookUpProfile("Sherlock", "likes"), ["Intriguing Cases", "Violin"]);
<del> - text: '<code>"Harry","likes"</code>应该返回一个阵列'
<add> - text: <code>"Harry","likes"</code>应该返回 an array。
<ide> testString: assert(typeof lookUpProfile("Harry", "likes") === "object");
<del> - text: '<code>"Bob", "number"</code>应该返回“没有这样的联系”'
<add> - text: <code>"Bob", "number"</code>应该返回 "No such contact"。
<ide> testString: assert(lookUpProfile("Bob", "number") === "No such contact");
<del> - text: '<code>"Bob", "potato"</code>应该返回“没有这样的联系”'
<add> - text: <code>"Bob", "potato"</code>应该返回 "No such contact"。
<ide> testString: assert(lookUpProfile("Bob", "potato") === "No such contact");
<del> - text: '<code>"Akira", "address"</code>应该返回“没有这样的财产”'
<add> - text: <code>"Akira", "address"</code>应该返回 "No such property"。
<ide> testString: assert(lookUpProfile("Akira", "address") === "No such property");
<ide>
<ide> ```
<ide> function lookUpProfile(name, prop){
<ide>
<ide> // Change these values to test your function
<ide> lookUpProfile("Akira", "likes");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> lookUpProfile("Akira", "likes");
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var contacts = [
<add> {
<add> "firstName": "Akira",
<add> "lastName": "Laine",
<add> "number": "0543236543",
<add> "likes": ["Pizza", "Coding", "Brownie Points"]
<add> },
<add> {
<add> "firstName": "Harry",
<add> "lastName": "Potter",
<add> "number": "0994372684",
<add> "likes": ["Hogwarts", "Magic", "Hagrid"]
<add> },
<add> {
<add> "firstName": "Sherlock",
<add> "lastName": "Holmes",
<add> "number": "0487345643",
<add> "likes": ["Intriguing Cases", "Violin"]
<add> },
<add> {
<add> "firstName": "Kristian",
<add> "lastName": "Vos",
<add> "number": "unknown",
<add> "likes": ["JavaScript", "Gaming", "Foxes"]
<add> },
<add>];
<add>
<add>
<add>//Write your function in between these comments
<add>function lookUpProfile(name, prop){
<add> for(var i in contacts){
<add> if(contacts[i].firstName === name) {
<add> return contacts[i][prop] || "No such property";
<add> }
<add> }
<add> return "No such contact";
<add>}
<add>//Write your function in between these comments
<add>
<add>lookUpProfile("Akira", "likes");
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/quoting-strings-with-single-quotes.chinese.md
<ide> id: 56533eb9ac21ba0edf2244b4
<ide> title: Quoting Strings with Single Quotes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 单引号引用字符串
<add>videoUrl: 'https://scrimba.com/c/cbQmnhM'
<add>forumTopicId: 18260
<add>localeTitle: 用单引号引用字符串
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> JavaScript中的<dfn>字符串</dfn>值可以使用单引号或双引号编写,只要您以相同类型的引号开头和结尾即可。与其他一些编程语言不同,单引号和双引号在JavaScript中的工作方式相同。 <blockquote> doubleQuoteStr =“这是一个字符串”; <br> singleQuoteStr ='这也是一个字符串'; </blockquote>你可能想要使用一种报价而不是另一种报价的原因是你想在字符串中使用这两种报价。如果要将对话保存在字符串中并将对话用引号括起,则可能会发生这种情况。它的另一个用途是在一个字符串中保存带引号中各种属性的<code><a></code>标签。 <blockquote>谈话='芬恩向杰克惊呼,“代数!”'; </blockquote>但是,如果您需要使用其中的最外层引号,这将成为一个问题。请记住,字符串在开头和结尾都有相同的引用。但是如果你在中间的某个地方有相同的引用,字符串将提前停止并抛出错误。 <blockquote> goodStr ='杰克问芬恩,“嘿,我们去冒险吧?” <br> badStr ='芬恩回答,“我们走了!”'; //引发错误</blockquote>在上面的<dfn>goodStr中</dfn> ,您可以使用反斜杠<code>\</code>作为转义字符安全地使用两个引号。 <strong>注意</strong> <br>反斜杠<code>\</code>不应与正斜杠<code>/</code>混淆。他们不做同样的事情。 </section>
<add><section id='description'>
<add>JavaScript 中的<dfn>字符串</dfn>可以使用开始和结束都是同类型的单引号或双引号表示,与其他一些编程语言不同的是,单引号和双引号的功能在 JavaScript 中是相同的。
<add>
<add>```js
<add>doubleQuoteStr = "This is a string";
<add>singleQuoteStr = 'This is also a string';
<add>```
<add>
<add>当你需要在一个字符串中使用多个引号的时候,你可以使用单引号包裹双引号或者相反。常见的场景比如在字符串中包含对话的句子需要用引号包裹。另外比如在一个包含有<code><a></code>标签的字符串中,<code><a></code>标签的属性值需要用引号包裹。
<add>
<add>```js
<add>conversation = 'Finn exclaims to Jake, "Algebraic!"';
<add>```
<add>
<add>但是,如果你想在字符串中使用与最外层相同的引号,会有一些问题。要知道,字符串在开头和结尾都有相同的引号,如果在中间使用了相同的引号,字符串会提前中止并抛出错误。
<add>
<add>```js
<add>goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
<add>badStr = 'Finn responds, "Let's go!"'; // Throws an error
<add>```
<add>
<add>在上面的<code>goodStr</code>中,通过使用反斜杠<code>\</code>转义字符可以安全地使用两种引号
<add><strong>提示</strong><br/>不要把反斜杠<code>\</code>和斜杠<code>/</code>搞混,它们不是一回事。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将提供的字符串更改为在开头和结尾使用单引号的字符串,并且不包含转义字符。现在,字符串中的<code><a></code>标签在任何地方都使用双引号。您需要将外引号更改为单引号,以便删除转义字符。 </section>
<add><section id='instructions'>
<add>把字符串更改为开头和结尾使用单引号的字符串,并且不包含转义字符。
<add>这样字符串中的<code><a></code>标签里面任何地方都可以使用双引号。你需要将最外层引号更改为单引号,以便删除转义字符。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 删除所有<code>backslashes</code> ( <code>\</code> )
<add> - text: 删除所有<code>反斜杠</code> (<code>\</code>)。
<ide> testString: assert(!/\\/g.test(code) && myStr.match('\\s*<a href\\s*=\\s*"http://www.example.com"\\s*target\\s*=\\s*"_blank">\\s*Link\\s*</a>\\s*'));
<del> - text: '你应该有两个单引号<code>'</code>和四个双引号<code>"</code>'
<add> - text: 应该要有两个单引号<code>'</code>和四个双引号<code>"</code>。
<ide> testString: assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> var myStr = "<a href=\"http://www.example.com\" target=\"_blank\">Link</a>";
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myStr = "<a href=\"http://www.example.com\" target=\"_blank\">Link</a>";
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function() { return "myStr = " + myStr; })();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myStr = '<a href="http://www.example.com" target="_blank">Link</a>';
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.chinese.md
<ide> id: 56533eb9ac21ba0edf2244cf
<ide> title: Record Collection
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 记录收集
<add>videoUrl: 'https://scrimba.com/c/c4mpysg'
<add>forumTopicId: 18261
<add>localeTitle: 记录集合
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您将获得一个JSON对象,表示您的音乐专辑集合的一部分。每张专辑都有几个属性和一个唯一的ID号作为其关键。并非所有相册都有完整的信息。写一个功能,它取一个专辑的<code>id</code> (如<code>2548</code> ),一个属性<code>prop</code> (如<code>"artist"</code>或<code>"tracks"</code> ),以及一个<code>value</code> (如<code>"Addicted to Love"</code> )来修改此集合中的数据。如果<code>prop</code>不是<code>"tracks"</code>且<code>value</code>不为空( <code>""</code> ),则更新或设置该记录专辑属性的<code>value</code> 。您的函数必须始终返回整个集合对象。处理不完整数据有几个规则:如果<code>prop</code>是<code>"tracks"</code>但是相册没有<code>"tracks"</code>属性,则在将新值添加到相册的相应属性之前创建一个空数组。如果<code>prop</code>是<code>"tracks"</code>且<code>value</code>不为空( <code>""</code> ),则将<code>value</code>推到专辑现有<code>tracks</code>数组的末尾。如果<code>value</code>为空( <code>""</code> ),则从相册中删除给定的<code>prop</code>属性。 <strong>提示</strong> <br>使用<a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">变量访问对象属性</a>时使用<code>bracket notation</code> 。 Push是一种可以在<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a>上阅读的数组方法。您可以参考<a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">操作复杂对象</a>介绍JavaScript对象表示法(JSON)进行复习。 </section>
<add><section id='description'>
<add>给定一个 JSON 对象,用来表示部分音乐专辑收藏。每张专辑都有几个属性和一个唯一的 id 号作为键值。并非所有专辑都有完整的信息。
<add>写一个函数,根据传入的<code>id</code>(如<code>2548</code>)、<code>prop</code>(属性,如<code>"artist"</code>或<code>"tracks"</code>)以及<code>value</code>(值,如<code>"Addicted to Love"</code>)来修改音乐专辑收藏的数据。
<add>如果属性<code>prop</code>不是<code>"tracks"</code>且值<code>value</code>不为空(<code>""</code>),则更新或设置该专辑属性的值<code>value</code>。
<add>你的函数必须始终返回整个音乐专辑集合对象。
<add>处理不完整数据有几条规则:
<add>如果属性<code>prop</code>是<code>"tracks"</code>,但是专辑没有<code>"tracks"</code>属性,则在添加值之前先给<code>"tracks"</code>创建一个空数组。
<add>如果<code>prop</code>是<code>"tracks"</code>,并且值<code>value</code>不为空(<code>""</code>), 把值<code>value</code>添加到<code>tracks</code>数组中。
<add>如果值<code>value</code>为空(<code>""</code>),则删除专辑的这一属性<code>prop</code>
<add><strong>提示:</strong><br><a href="javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">通过变量访问对象的属性</a>时,应使用<code>中括号</code>。
<add>Push 是一个数组方法,详情请查看<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a>.
<add>你可以参考<a href="/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">操作复杂对象</a>这一节的内容复习相关知识。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '在<code>updateRecords(5439, "artist", "ABBA")</code> , <code>artist</code>应该是<code>"ABBA"</code>'
<del> testString: collection = collectionCopy; assert(updateRecords(5439, "artist", "ABBA")[5439]["artist"] === "ABBA");
<del> - text: '在<code>updateRecords(5439, "tracks", "Take a Chance on Me")</code> , <code>tracks</code>应该以<code>"Take a Chance on Me"</code>作为最后一个元素。'
<add> - text: 执行<code>updateRecords(5439, "artist", "ABBA")</code>后,<code>artist</code>属性值应该是<code>"ABBA"</code>。
<add> testString: 'assert(code.match(/var collection = {\s*2548: {\s*album: "Slippery When Wet",\s*artist: "Bon Jovi",\s*tracks: \[\s*"Let It Rock",\s*"You Give Love a Bad Name"\s*\]\s*},\s*2468: {\s*album: "1999",\s*artist: "Prince",\s*tracks: \[\s*"1999",\s*"Little Red Corvette"\s*\]\s*},\s*1245: {\s*artist: "Robert Palmer",\s*tracks: \[ \]\s*},\s*5439: {\s*album: "ABBA Gold"\s*}\s*};/g));'
<add> - text: 执行<code>updateRecords(5439, "artist", "ABBA")</code>后,<code>artist</code> 最后的元素应该是 <code>"ABBA"</code>。
<add> testString: assert(updateRecords(5439, "artist", "ABBA")[5439]["artist"] === "ABBA");
<add> - text: 执行 <code>updateRecords(5439, "tracks", "Take a Chance on Me")</code> 后,<code>tracks</code> 最后的元素应该是 <code>"Take a Chance on Me"</code>。
<ide> testString: assert(updateRecords(5439, "tracks", "Take a Chance on Me")[5439]["tracks"].pop() === "Take a Chance on Me");
<del> - text: '在<code>updateRecords(2548, "artist", "")</code> ,不应该设置<code>artist</code>'
<add> - text: 执行<code>updateRecords(2548, "artist", "")</code>后,<code>artist</code>不应被创建。
<ide> testString: updateRecords(2548, "artist", ""); assert(!collection[2548].hasOwnProperty("artist"));
<del> - text: '在<code>updateRecords(1245, "tracks", "Addicted to Love")</code> , <code>tracks</code>应该将<code>"Addicted to Love"</code>作为最后一个元素。'
<add> - text: 执行<code>updateRecords(1245, "tracks", "Addicted to Love")</code>后,<code>tracks</code>最后的元素应该是<code>"Addicted to Love"</code>。
<ide> testString: assert(updateRecords(1245, "tracks", "Addicted to Love")[1245]["tracks"].pop() === "Addicted to Love");
<del> - text: '在<code>updateRecords(2468, "tracks", "Free")</code> , <code>tracks</code>应该以<code>"1999"</code>作为第一个元素。'
<add> - text: 执行<code>updateRecords(2468, "tracks", "Free")</code>后,<code>tracks</code>第一个元素应该是<code>"1999"</code>。
<ide> testString: assert(updateRecords(2468, "tracks", "Free")[2468]["tracks"][0] === "1999");
<del> - text: '在<code>updateRecords(2548, "tracks", "")</code> ,不应设置<code>tracks</code>'
<add> - text: 执行<code>updateRecords(2548, "tracks", "")</code>后,<code>tracks</code>不应被创建。
<ide> testString: updateRecords(2548, "tracks", ""); assert(!collection[2548].hasOwnProperty("tracks"));
<del> - text: '在<code>updateRecords(1245, "album", "Riptide")</code> , <code>album</code>应该是<code>"Riptide"</code>'
<add> - text: 执行<code>updateRecords(1245, "album", "Riptide")</code>后,<code>album</code>应该是<code>"Riptide"</code>。
<ide> testString: assert(updateRecords(1245, "album", "Riptide")[1245]["album"] === "Riptide");
<ide>
<ide> ```
<ide> tests:
<ide>
<ide> ## Challenge Seed
<ide> <section id='challengeSeed'>
<del>
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<ide> // Setup
<ide> var collection = {
<del> "2548": {
<del> "album": "Slippery When Wet",
<del> "artist": "Bon Jovi",
<del> "tracks": [
<del> "Let It Rock",
<del> "You Give Love a Bad Name"
<del> ]
<del> },
<del> "2468": {
<del> "album": "1999",
<del> "artist": "Prince",
<del> "tracks": [
<del> "1999",
<del> "Little Red Corvette"
<del> ]
<del> },
<del> "1245": {
<del> "artist": "Robert Palmer",
<del> "tracks": [ ]
<del> },
<del> "5439": {
<del> "album": "ABBA Gold"
<del> }
<add> 2548: {
<add> album: "Slippery When Wet",
<add> artist: "Bon Jovi",
<add> tracks: [
<add> "Let It Rock",
<add> "You Give Love a Bad Name"
<add> ]
<add> },
<add> 2468: {
<add> album: "1999",
<add> artist: "Prince",
<add> tracks: [
<add> "1999",
<add> "Little Red Corvette"
<add> ]
<add> },
<add> 1245: {
<add> artist: "Robert Palmer",
<add> tracks: [ ]
<add> },
<add> 5439: {
<add> album: "ABBA Gold"
<add> }
<ide> };
<del>// Keep a copy of the collection for tests
<del>var collectionCopy = JSON.parse(JSON.stringify(collection));
<ide>
<ide> // Only change code below this line
<ide> function updateRecords(id, prop, value) {
<ide> updateRecords(5439, "artist", "ABBA");
<ide> ```
<ide>
<ide> </div>
<del>
<del>
<del>### After Test
<del><div id='js-teardown'>
<del>
<del>```js
<del>console.info('after the test');
<del>```
<del>
<del></div>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>var collection = {
<add> 2548: {
<add> album: "Slippery When Wet",
<add> artist: "Bon Jovi",
<add> tracks: [
<add> "Let It Rock",
<add> "You Give Love a Bad Name"
<add> ]
<add> },
<add> 2468: {
<add> album: "1999",
<add> artist: "Prince",
<add> tracks: [
<add> "1999",
<add> "Little Red Corvette"
<add> ]
<add> },
<add> 1245: {
<add> artist: "Robert Palmer",
<add> tracks: [ ]
<add> },
<add> 5439: {
<add> album: "ABBA Gold"
<add> }
<add>};
<add>
<add>// Only change code below this line
<add>function updateRecords(id, prop, value) {
<add> if(value === "") delete collection[id][prop];
<add> else if(prop === "tracks") {
<add> collection[id][prop] = collection[id][prop] || [];
<add> collection[id][prop].push(value);
<add> } else {
<add> collection[id][prop] = value;
<add> }
<add>
<add> return collection;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion.chinese.md
<add>---
<add>id: 5cfa3679138e7d9595b9d9d4
<add>title: Replace Loops using Recursion
<add>challengeType: 1
<add>videoUrl: 'https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/'
<add>forumTopicId: 301175
<add>localeTitle: 使用递归代替循环
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>函数调用自身的编程技巧称为递归。为了便于理解,有如下任务:计算数组内元素第 <code>0</code> 到第 <code>n</code> 的元素乘积,使用 <code>for</code> 循环, 可以这样做:
<add>
<add>```js
<add> function multiply(arr, n) {
<add> var product = arr[0];
<add> for (var i = 1; i <= n; i++) {
<add> product *= arr[i];
<add> }
<add> return product;
<add> }
<add>```
<add>
<add>下面是递归写法,注意代码里的 <code>multiply(arr, n) == multiply(arr, n - 1) * arr[n]</code>。这意味着可以重写 <code>multiply</code> 以调用自身而无需依赖循环。
<add>
<add>```js
<add> function multiply(arr, n) {
<add> if (n <= 0) {
<add> return arr[0];
<add> } else {
<add> return multiply(arr, n - 1) * arr[n];
<add> }
<add> }
<add>```
<add>
<add>递归版本的 <code>multiply</code> 详述如下。在 <dfn>base case</dfn> 里,也就是 <code>n <= 0</code> 时,返回结果,也就是 <code>arr[0]</code>。在 <code>n</code> 比 0 大的情况里,函数会调用自身,参数 n 的值为 <code>n - 1</code>。函数以相同的方式持续调用 <code>multiply</code>,直到 <code>n = 0</code> 为止。所以,所有函数都可以返回,原始的 <code>multiply</code> 返回结果。
<add>
<add><strong>注意:</strong> 递归函数在没有函数调用时(在这个例子是,是当 <code>n <= 0</code> 时)必需有一个跳出结构,否则永远不会执行完毕。
<add>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add>写一个递归函数,<code>sum(arr, n)</code>,返回递归调用数组 <code>arr</code> 从第 <code>0</code> 个到第 <code>n</code> 个元素和。
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>``` yml
<add>tests:
<add> - text: <code>sum([1], 0)</code> 应该返回 1 。
<add> testString: assert.equal(sum([1], 0), 1);
<add> - text: <code>sum([2, 3, 4], 1)</code> 应该返回 5 。
<add> testString: assert.equal(sum([2, 3, 4], 1), 5);
<add> - text: 代码不应该包含任何形式的循环(<code>for</code> 或者 <code>while</code> 或者高阶函数比如 <code>forEach</code>,<code>map</code>,<code>filter</code>,或者 <code>reduce</code>)。
<add> testString: assert(!removeJSComments(code).match(/for|while|forEach|map|filter|reduce/g));
<add> - text: 应该使用递归来解决这个问题。
<add> testString: assert(removeJSComments(sum.toString()).match(/sum\(.*\)/g).length > 1);
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add><div id='js-seed'>
<add>
<add>```js
<add>function sum(arr, n) {
<add> // Only change code below this line
<add>
<add> // Only change code above this line
<add>}
<add>
<add>```
<add>
<add></div>
<add>
<add>### After Test
<add><div id='js-teardown'>
<add>
<add>```js
<add>const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
<add>
<add>```
<add>
<add></div>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>function sum(arr, n) {
<add> // Only change code below this line
<add> if(n <= 0) {
<add> return arr[0];
<add> } else {
<add> return sum(arr, n - 1) + arr[n];
<add> }
<add> // Only change code above this line
<add>}
<add>
<add>```
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.chinese.md
<ide> id: 56533eb9ac21ba0edf2244e0
<ide> title: Replacing If Else Chains with Switch
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 如果用交换机替换其他链条
<add>videoUrl: 'https://scrimba.com/c/c3JE8fy'
<add>forumTopicId: 18266
<add>localeTitle: 用一个 Switch 语句来替代多个 if else 语句
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">如果您有许多选项可供选择,那么<code>switch</code>语句比许多链接的<code>if</code> / <code>else if</code>语句更容易编写。下列: <blockquote> if(val === 1){ <br> answer =“a”; <br> } else if(val === 2){ <br> answer =“b”; <br> } else { <br> answer =“c”; <br> } </blockquote>可以替换为: <blockquote> switch(val){ <br>情况1: <br> answer =“a”; <br>打破; <br>案例2: <br> answer =“b”; <br>打破; <br>默认: <br> answer =“c”; <br> } </blockquote></section>
<add><section id='description'>
<add>如果你有多个选项需要选择,<code>switch</code>语句写起来会比多个串联的<code>if</code>/<code>if else</code>语句容易些,譬如:
<add>
<add>```js
<add>if (val === 1) {
<add> answer = "a";
<add>} else if (val === 2) {
<add> answer = "b";
<add>} else {
<add> answer = "c";
<add>}
<add>```
<add>
<add>可以被下面替代:
<add>
<add>```js
<add>switch(val) {
<add> case 1:
<add> answer = "a";
<add> break;
<add> case 2:
<add> answer = "b";
<add> break;
<add> default:
<add> answer = "c";
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将链接的<code>if</code> / <code>else if</code>语句更改为<code>switch</code>语句。 </section>
<add><section id='instructions'>
<add>把串联的<code>if</code>/<code>if else</code>语句改成<code>switch</code>语句。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您不应该在编辑器中的任何位置使用任何<code>else</code>语句
<add> - text: 不要使用<code>else</code>表达式。
<ide> testString: assert(!/else/g.test(code));
<del> - text: 您不应在编辑器中的任何位置使用任何<code>if</code>语句
<add> - text: 不要使用<code>if</code>表达式。
<ide> testString: assert(!/if/g.test(code));
<del> - text: 你应该至少有四个<code>break</code>语句
<add> - text: 你应该有至少 4 个<code>break</code>表达式。
<ide> testString: assert(code.match(/break/g).length >= 4);
<del> - text: <code>chainToSwitch("bob")</code>应该是“Marley”
<add> - text: <code>chainToSwitch("bob")</code>应该为 "Marley"。
<ide> testString: assert(chainToSwitch("bob") === "Marley");
<del> - text: <code>chainToSwitch(42)</code>应该是“答案”
<add> - text: <code>chainToSwitch(42)</code>应该为 "The Answer"。
<ide> testString: assert(chainToSwitch(42) === "The Answer");
<del> - text: <code>chainToSwitch(1)</code>应该是“没有#1”
<add> - text: <code>chainToSwitch(1)</code>应该为 "There is no #1"。
<ide> testString: "assert(chainToSwitch(1) === \"There is no #1\");"
<del> - text: <code>chainToSwitch(99)</code>应该是“错过了我这么多!”
<add> - text: <code>chainToSwitch(99)</code>应该为 "Missed me by this much!"。
<ide> testString: assert(chainToSwitch(99) === "Missed me by this much!");
<del> - text: <code>chainToSwitch(7)</code>应该是“Ate Nine”
<add> - text: <code>chainToSwitch(7)</code>应该为 "Ate Nine"。
<ide> testString: assert(chainToSwitch(7) === "Ate Nine");
<del> - text: <code>chainToSwitch("John")</code>应为“”(空字符串)
<add> - text: <code>chainToSwitch("John")</code>应该为 "" (empty string)。
<ide> testString: assert(chainToSwitch("John") === "");
<del> - text: <code>chainToSwitch(156)</code>应为“”(空字符串)
<add> - text: <code>chainToSwitch(156)</code>应该为 "" (empty string)。
<ide> testString: assert(chainToSwitch(156) === "");
<ide>
<ide> ```
<ide> chainToSwitch(7);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function chainToSwitch(val) {
<add> var answer = "";
<add>
<add> switch(val) {
<add> case "bob":
<add> answer = "Marley";
<add> break;
<add> case 42:
<add> answer = "The Answer";
<add> break;
<add> case 1:
<add> answer = "There is no #1";
<add> break;
<add> case 99:
<add> answer = "Missed me by this much!";
<add> break;
<add> case 7:
<add> answer = "Ate Nine";
<add> }
<add> return answer;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c2
<ide> title: Return a Value from a Function with Return
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 从带返回的函数返回值
<add>videoUrl: 'https://scrimba.com/c/cy87wue'
<add>forumTopicId: 18271
<add>localeTitle: 函数可以返回某个值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们可以将值传递给带<dfn>参数</dfn>的函数。您可以使用<code>return</code>语句从函数中发回一个值。 <strong>例</strong> <blockquote> function plusThree(num){ <br>返回num + 3; <br> } <br> var answer = plusThree(5); // 8 </blockquote> <code>plusThree</code>接受<code>num</code>的<dfn>参数</dfn>并返回一个等于<code>num + 3</code>的值。 </section>
<add><section id='description'>
<add>我们可以通过函数的<dfn>参数</dfn>把值传入函数,也可以使用<code>return</code>语句把数据从一个函数中传出来。
<add><strong>示例</strong>
<add>
<add>```js
<add>function plusThree(num) {
<add> return num + 3;
<add>}
<add>var answer = plusThree(5); // 8
<add>```
<add>
<add><code>plusThree</code>带有一个<code>num</code>的<dfn>参数</dfn>并且返回(returns)一个等于<code>num + 3</code>的值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个接受一个参数的函数<code>timesFive</code> ,将其乘以<code>5</code> ,然后返回新值。有关如何测试<code>timesFive</code>函数的示例,请参阅编辑器中的最后一行。 </section>
<add><section id='instructions'>
<add>创建一个函数<code>timesFive</code>接收一个参数, 把它乘以<code>5</code>之后返回,关于如何测试timesFive 函数,可以参考编辑器中最后一行的示例。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>timesFive</code>应该是一个功能
<add> - text: <code>timesFive</code>应是一个函数。
<ide> testString: assert(typeof timesFive === 'function');
<del> - text: <code>timesFive(5)</code>应该返回<code>25</code>
<add> - text: <code>timesFive(5)</code>应该返回<code>25</code>。
<ide> testString: assert(timesFive(5) === 25);
<del> - text: <code>timesFive(2)</code>应该返回<code>10</code>
<add> - text: <code>timesFive(2)</code>应该返回<code>10</code>。
<ide> testString: assert(timesFive(2) === 10);
<del> - text: <code>timesFive(0)</code>应该返回<code>0</code>
<add> - text: <code>timesFive(0)</code>应该返回<code>0</code>。
<ide> testString: assert(timesFive(0) === 0);
<ide>
<ide> ```
<ide> function minusSeven(num) {
<ide>
<ide>
<ide> console.log(minusSeven(10));
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(minusSeven(10));
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function timesFive(num) {
<add> return num * 5;
<add>}
<add>timesFive(10);
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c4
<ide> title: Return Early Pattern for Functions
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 返回函数的早期模式
<add>videoUrl: 'https://scrimba.com/c/cQe39Sq'
<add>forumTopicId: 18272
<add>localeTitle: 函数执行到 return 语句就结束
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">当达到<code>return</code>语句时,当前函数的执行停止,控制返回到调用位置。 <strong>例</strong> <blockquote> function myFun(){ <br>的console.log( “你好”); <br>回归“世界”; <br>的console.log( “BYEBYE”) <br> } <br> myFun(); </blockquote>上面输出“Hello”到控制台,返回“World”,但是<code>"byebye"</code>永远不输出,因为函数退出<code>return</code>语句。 </section>
<add><section id='description'>
<add>当代码执行到 return 语句时,函数返回一个结果就结束运行了,return 后面的语句不会执行。
<add><strong>示例</strong>
<add>
<add>```js
<add>function myFun() {
<add> console.log("Hello");
<add> return "World";
<add> console.log("byebye")
<add>}
<add>myFun();
<add>```
<add>
<add>上面的代码输出"Hello"到控制台、返回 "World",但没有输出<code>"byebye"</code>,因为函数遇到 return 语句就退出了。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改函数<code>abTest</code>以便如果<code>a</code>或<code>b</code>小于<code>0</code> ,函数将立即以<code>undefined</code>值退出。 <strong>暗示</strong> <br>请记住, <a href="http://www.freecodecamp.org/challenges/understanding-uninitialized-variables" target="_blank"><code>undefined</code>是一个关键字</a> ,而不是一个字符串。 </section>
<add><section id='instructions'>
<add>修改函数<code>abTest</code>当<code>a</code>或<code>b</code>小于0时,函数立即返回一个<code>undefined</code>并退出。
<add><strong>提示</strong><br>记住<a href='/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables' target='_blank'><code>undefined</code> 是一个关键字</a>,而不是一个字符串。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>abTest(2,2)</code>应返回一个数字'
<add> - text: <code>abTest(2,2)</code> 应该返回一个数字。
<ide> testString: assert(typeof abTest(2,2) === 'number' );
<del> - text: '<code>abTest(2,2)</code>应该返回<code>8</code>'
<add> - text: <code>abTest(2,2)</code> 应该返回 <code>8</code>。
<ide> testString: assert(abTest(2,2) === 8 );
<del> - text: '<code>abTest(-2,2)</code>应返回<code>undefined</code>'
<add> - text: <code>abTest(-2,2)</code> 应该返回 <code>undefined</code>。
<ide> testString: assert(abTest(-2,2) === undefined );
<del> - text: '<code>abTest(2,-2)</code>应返回<code>undefined</code>'
<add> - text: <code>abTest(2,-2)</code> 应该返回 <code>undefined</code>。
<ide> testString: assert(abTest(2,-2) === undefined );
<del> - text: '<code>abTest(2,8)</code>应该返回<code>18</code>'
<add> - text: <code>abTest(2,8)</code> 应该返回 <code>18</code>。
<ide> testString: assert(abTest(2,8) === 18 );
<del> - text: '<code>abTest(3,3)</code>应该返回<code>12</code>'
<add> - text: <code>abTest(3,3)</code> 应该返回 <code>12</code>。
<ide> testString: assert(abTest(3,3) === 12 );
<ide>
<ide> ```
<ide> function abTest(a, b) {
<ide>
<ide> // Change values below to test your code
<ide> abTest(2,2);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> abTest(2,2);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function abTest(a, b) {
<add> if(a < 0 || b < 0) {
<add> return undefined;
<add> }
<add> return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2));
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.chinese.md
<ide> id: 5679ceb97cbaa8c51670a16b
<ide> title: Returning Boolean Values from Functions
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cp62qAQ'
<add>forumTopicId: 18273
<ide> localeTitle: 从函数返回布尔值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以从<a href="/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">与Equality运算符的比较中</a>回忆一下,所有比较运算符都返回布尔值<code>true</code>或<code>false</code>值。有时人们使用if / else语句进行比较,如下所示: <blockquote> function isEqual(a,b){ <br> if(a === b){ <br>返回true; <br> } else { <br>返回虚假; <br> } <br> } </blockquote>但是有一种更好的方法可以做到这一点。由于<code>===</code>返回<code>true</code>或<code>false</code> ,我们可以返回比较结果: <blockquote> function isEqual(a,b){ <br>返回a === b; <br> } </blockquote></section>
<add><section id='description'>
<add>你应该还记得<a href="javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator" target="_blank">相等运算符</a>这道挑战题。在那里我们提到,所有比较操作符都会返回 boolean:要么是<code>true</code>要么是<code>false</code>。
<add>有时人们通过 if/else 语句来做比较然后返回<code>true</code>或<code>false</code>。
<add>
<add>```js
<add>function isEqual(a,b) {
<add> if (a === b) {
<add> return true;
<add> } else {
<add> return false;
<add> }
<add>}
<add>```
<add>
<add>有一个更好的方法,因为<code>===</code>总是返回<code>true</code>或<code>false</code>,所以我们可以直接返回比较的结果:
<add>
<add>```js
<add>function isEqual(a,b) {
<add> return a === b;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复函数<code>isLess</code>以删除<code>if/else</code>语句。 </section>
<add><section id='instructions'>
<add>移除<code>isLess</code>函数的<code>if/else</code>语句但不影响函数的功能。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>isLess(10,15)</code>应该返回<code>true</code>'
<add> - text: <code>isLess(10,15)</code>应该返回 <code>true</code>。
<ide> testString: assert(isLess(10,15) === true);
<del> - text: '<code>isLess(15,10)</code>应该返回<code>false</code>'
<add> - text: <code>isLess(15,10)</code>应该返回 <code>false</code>。
<ide> testString: assert(isLess(15, 10) === false);
<del> - text: 您不应该使用任何<code>if</code>或<code>else</code>语句
<add> - text: 不应该使用 <code>if</code> 或者 <code>else</code> 语句。
<ide> testString: assert(!/if|else/g.test(code));
<ide>
<ide> ```
<ide> function isLess(a, b) {
<ide>
<ide> // Change these values to test
<ide> isLess(10, 15);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> isLess(10, 15);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function isLess(a, b) {
<add> return a < b;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.chinese.md
<ide> id: 56533eb9ac21ba0edf2244dd
<ide> title: Selecting from Many Options with Switch Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 从带有开关语句的多个选项中进行选择
<add>videoUrl: 'https://scrimba.com/c/c4mv4fm'
<add>forumTopicId: 18277
<add>localeTitle: 使用 Switch 语句从许多选项中进行选择
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">
<del>
<del>如果您有很多选择,请使用<dfn> switch </dfn>语句。 <code> switch </code>语句测试一个值,并且可以包含许多定义各种可能值的<dfn> case </dfn>语句。 从第一个匹配的<code> case </code>值开始执行语句,直到遇到<code> break </code>。
<del>这是<code> switch </code>语句的示例:
<add><section id='description'>
<add>如果你有非常多的选项需要选择,可以使用 switch 语句。根据不同的参数值会匹配上不同的 case 分支,语句会从第一个匹配的 case 分支开始执行,直到碰到 break 就结束。
<add>这是一个伪代码案例:
<ide>
<ide> ```js
<ide> switch(lowercaseLetter) {
<ide> switch(lowercaseLetter) {
<ide> }
<ide> ```
<ide>
<del><code> case </code>值以严格相等性(<code> === </code>)进行测试。 <code> break </code>告诉JavaScript停止执行语句。 如果省略<code> break </code>,将执行下一条语句。
<del>
<add>测试<code>case</code>值使用严格相等运算符进行比较,break 关键字告诉 JavaScript 停止执行语句。如果没有 break 关键字,下一个语句会继续执行。
<ide> </section>
<ide>
<ide> ## Instructions
<del><section id="instructions">编写一个switch语句,测试<code>val</code>并设置以下条件的<code>answer</code> : <br> <code>1</code> - “alpha” <br> <code>2</code> - “beta” <br> <code>3</code> - “伽玛” <br> <code>4</code> - “三角洲” </section>
<add><section id='instructions'>
<add>写一个测试<code>val</code>的 switch 语句,并且根据下面的条件来设置不同的<code>answer</code>:<br><code>1</code>- "alpha"<br><code>2</code> - "beta"<br><code>3</code>- "gamma"<br><code>4</code> - "delta"
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>caseInSwitch(1)</code>的值应为“alpha”
<add> - text: <code>caseInSwitch(1)</code> 应该有一个值为 "alpha"。
<ide> testString: assert(caseInSwitch(1) === "alpha");
<del> - text: <code>caseInSwitch(2)</code>的值应为“beta”
<add> - text: <code>caseInSwitch(2)</code> 应该有一个值为 "beta"。
<ide> testString: assert(caseInSwitch(2) === "beta");
<del> - text: <code>caseInSwitch(3)</code>的值应为“gamma”
<add> - text: <code>caseInSwitch(3)</code> 应该有一个值为 "gamma"。
<ide> testString: assert(caseInSwitch(3) === "gamma");
<del> - text: <code>caseInSwitch(4)</code>的值应为“delta”
<add> - text: <code>caseInSwitch(4)</code> 应该有一个值为 "delta"。
<ide> testString: assert(caseInSwitch(4) === "delta");
<del> - text: 您不应该使用任何<code>if</code>或<code>else</code>语句
<add> - text: 不能使用任何<code>if</code>或<code>else</code>表达式。
<ide> testString: assert(!/else/g.test(code) || !/if/g.test(code));
<del> - text: 你应该至少有3个<code>break</code>语句
<add> - text: 你应该有至少 3 个<code>break</code>表达式。
<ide> testString: assert(code.match(/break/g).length > 2);
<ide>
<ide> ```
<ide> caseInSwitch(1);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function caseInSwitch(val) {
<add> var answer = "";
<add>
<add> switch(val) {
<add> case 1:
<add> answer = "alpha";
<add> break;
<add> case 2:
<add> answer = "beta";
<add> break;
<add> case 3:
<add> answer = "gamma";
<add> break;
<add> case 4:
<add> answer = "delta";
<add> }
<add> return answer;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.chinese.md
<ide> id: 56533eb9ac21ba0edf2244bc
<ide> title: Shopping List
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/c9MEKHZ'
<add>forumTopicId: 18280
<ide> localeTitle: 购物清单
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在变量<code>myList</code>创建购物清单。该列表应该是包含多个子阵列的多维数组。每个子数组中的第一个元素应包含一个带有项目名称的字符串。第二个元素应该是一个代表数量的数字,即<code>["Chocolate Bar", 15]</code>列表中应该至少有5个子数组。 </section>
<add><section id='description'>
<add>创建一个名叫<code>myList</code>的购物清单,清单的数据格式就是多维数组。
<add>每个子数组中的第一个元素应该是购买的物品名称,第二个元素应该是物品的数量,类似于:
<add><code>["Chocolate Bar", 15]</code>
<add>任务:你的购物清单至少应该有 5 个子数组。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myList</code>应该是一个数组
<add> - text: <code>myList</code>应该一个数组。
<ide> testString: assert(isArray);
<del> - text: 每个子数组中的第一个元素都必须是字符串
<add> - text: 你的每个子数组的第一个元素的类型都应该是字符串。
<ide> testString: assert(hasString);
<del> - text: 每个子数组中的第二个元素都必须是数字
<add> - text: 你的每个子数组的第二个元素的类型都应该是数字。
<ide> testString: assert(hasNumber);
<del> - text: 您的列表中必须至少有5个项目
<add> - text: 你的列表中至少要包含 5 个元素。
<ide> testString: assert(count > 4);
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> var myList = [];
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myList = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>var count = 0;
<add>var isArray = false;
<add>var hasString = false;
<add>var hasNumber = false;
<add>(function(list){
<add> if(Array.isArray(myList)) {
<add> isArray = true;
<add> if(myList.length > 0) {
<add> hasString = true;
<add> hasNumber = true;
<add> for (var elem of myList) {
<add> if(!elem || !elem[0] || typeof elem[0] !== 'string') {
<add> hasString = false;
<add> }
<add> if(!elem || typeof elem[1] !== 'number') {
<add> hasNumber = false;
<add> }
<add> }
<add> }
<add> count = myList.length;
<add> return JSON.stringify(myList);
<add> } else {
<add> return "myList is not an array";
<add> }
<add>
<add>})(myList);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myList = [
<add> ["Candy", 10],
<add> ["Potatoes", 12],
<add> ["Eggs", 12],
<add> ["Catfood", 1],
<add> ["Toads", 9]
<add>];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.chinese.md
<ide> id: 56533eb9ac21ba0edf2244c6
<ide> title: Stand in Line
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 站在队中
<add>videoUrl: 'https://scrimba.com/c/ca8Q8tP'
<add>forumTopicId: 18307
<add>localeTitle: 排队
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在计算机科学中, <dfn>队列</dfn>是一个抽象的<dfn>数据结构</dfn> ,其中项目按顺序保存。可以在<code>queue</code>的后面添加新项目,并从<code>queue</code>的前面取出旧项目。编写一个函数<code>nextInLine</code> ,它接受一个数组( <code>arr</code> )和一个数字( <code>item</code> )作为参数。将数字添加到数组的末尾,然后删除数组的第一个元素。然后, <code>nextInLine</code>函数应返回已删除的元素。 </section>
<add><section id='description'>
<add>在计算机科学中<dfn>队列</dfn>(queue)是一个抽象的数据结构,队列中的条目都是有秩序的。新的条目会被加到<code>队列</code>的末尾,旧的条目会从<code>队列</code>的头部被移出。
<add>写一个函数<code>nextInLine</code>,用一个数组(<code>arr</code>)和一个数字(<code>item</code>)作为参数。
<add>把数字添加到数组的结尾,然后移出数组的第一个元素。
<add>最后<code>nextInLine</code>函数应该返回被删除的元素。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>nextInLine([], 5)</code>应返回一个数字。'
<add> - text: <code>nextInLine([], 5)</code>应该返回一个数字。
<ide> testString: assert.isNumber(nextInLine([],5));
<del> - text: '<code>nextInLine([], 1)</code>应该返回<code>1</code>'
<add> - text: <code>nextInLine([], 1)</code>应该返回<code>1</code>。
<ide> testString: assert(nextInLine([],1) === 1);
<del> - text: '<code>nextInLine([2], 1)</code>应返回<code>2</code>'
<add> - text: <code>nextInLine([2], 1)</code>应该返回<code>2</code>。
<ide> testString: assert(nextInLine([2],1) === 2);
<del> - text: '<code>nextInLine([5,6,7,8,9], 1)</code>应该返回<code>5</code>'
<add> - text: <code>nextInLine([5,6,7,8,9], 1)</code>应该返回<code>5</code>。
<ide> testString: assert(nextInLine([5,6,7,8,9],1) === 5);
<del> - text: '在<code>nextInLine(testArr, 10)</code> , <code>testArr[4]</code>应为<code>10</code>'
<add> - text: 在<code>nextInLine(testArr, 10)</code>执行后<code>testArr[4]</code>应该是<code>10</code>。
<ide> testString: nextInLine(testArr, 10); assert(testArr[4] === 10);
<ide>
<ide> ```
<ide> var testArr = [1,2,3,4,5];
<ide> console.log("Before: " + JSON.stringify(testArr));
<ide> console.log(nextInLine(testArr, 6)); // Modify this line to test
<ide> console.log("After: " + JSON.stringify(testArr));
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function uncapture() {
<ide> }
<ide>
<ide> capture();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> capture();
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>uncapture();
<add>testArr = [1,2,3,4,5];
<add>(function() { return logOutput.join("\n");})();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var testArr = [ 1,2,3,4,5];
<add>
<add>function nextInLine(arr, item) {
<add> arr.push(item);
<add> return arr.shift();
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.chinese.md
<ide> id: bd7993c9c69feddfaeb8bdef
<ide> title: Store Multiple Values in one Variable using JavaScript Arrays
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript数组在一个变量中存储多个值
<add>videoUrl: 'https://scrimba.com/c/crZQWAm'
<add>forumTopicId: 18309
<add>localeTitle: 使用 JavaScript 数组将多个值存储在一个变量中
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用JavaScript <code>array</code>变量,我们可以在一个地方存储多个数据。你开始一个带有开口方括号的数组声明,用一个结束的方括号结束,并在每个条目之间加一个逗号,如下所示: <code>var sandwich = ["peanut butter", "jelly", "bread"]</code> 。 </section>
<add><section id='description'>
<add>使用<code>数组</code>,我们可以在一个地方存储多个数据。
<add>以左方括号<code>[</code>开始定义一个数组,以右方括号<code>]</code>结束,里面每个元素之间用逗号隔开,例如:
<add><code>var sandwich = ["peanut butter", "jelly", "bread"]</code>.
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改新数组<code>myArray</code> ,使其包含<code>string</code>和<code>number</code> ( <code>myArray</code>顺序)。 <strong>暗示</strong> <br>如果卡住,请参阅文本编辑器中的示例代码。 </section>
<add><section id='instructions'>
<add>创建一个包含<code>字符串</code>和<code>数字</code>的数组<code>myArray</code>。
<add><strong>提示</strong><br>如果你遇到困难,请参考文本编辑器中的示例代码。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myArray</code>应该是一个<code>array</code> 。
<add> - text: <code>myArray</code>应该是一个<code>数组</code>。
<ide> testString: assert(typeof myArray == 'object');
<del> - text: <code>myArray</code>的第一项应该是一个<code>string</code> 。
<add> - text: <code>myArray</code>数组的第一个元素应该是一个<code>字符串</code>。
<ide> testString: assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
<del> - text: <code>myArray</code>的第二项应该是一个<code>number</code> 。
<add> - text: <code>myArray</code>数组的第二个元素应该是一个<code>数字</code>。
<ide> testString: assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');
<ide>
<ide> ```
<ide> var myArray = [];
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return z;})(myArray);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myArray = ["The Answer", 42];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.chinese.md
<ide> id: 56533eb9ac21ba0edf2244a8
<ide> title: Storing Values with the Assignment Operator
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cEanysE'
<add>forumTopicId: 18310
<ide> localeTitle: 使用赋值运算符存储值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中,您可以使用<dfn>赋值</dfn>运算符将值存储在变量中。 <code>myVariable = 5;</code>这将<code>Number</code>值<code>5</code>分配给<code>myVariable</code> 。作业总是从右到左。在将值分配给运算符左侧的变量之前,将解析<code>=</code>运算符右侧的所有内容。 <blockquote> myVar = 5; <br> myNum = myVar; </blockquote>这将为<code>myVar</code>分配<code>5</code> ,然后再次将<code>myVar</code>解析为<code>5</code>并将其分配给<code>myNum</code> 。 </section>
<add><section id='description'>
<add>在 JavaScript 中,你可以使用赋值运算符将值存储在变量中。
<add><code>myVariable = 5;</code>
<add>这条语句把<code>Number</code>类型的值<code>5</code>赋给变量<code>myVariable</code>。
<add>赋值过程是从右到左进行的。在将值分配给运算符左侧的变量之前,将解析<code>=</code>运算符右侧的所有内容。
<add>
<add>```js
<add>myVar = 5;
<add>myNum = myVar;
<add>```
<add>
<add>数值<code>5</code>被赋给变量<code>myVar</code>中,然后再次将变量<code>myVar</code>解析为<code>5</code>并将其赋给<code>myNum</code>变量。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将值<code>7</code>分配给变量<code>a</code> 。分配的内容<code>a</code>变量<code>b</code> 。 </section>
<add><section id='instructions'>
<add>把数值<code>7</code>赋给变量 <code>a</code>。
<add>把变量<code>a</code>中的内容赋给变量<code>b</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 不要更改行上方的代码
<add> - text: 不要修改注释上方的代码。
<ide> testString: assert(/var a;/.test(code) && /var b = 2;/.test(code));
<del> - text: <code>a</code>的值应为7
<add> - text: <code>a</code>的值应该是 7。
<ide> testString: assert(typeof a === 'number' && a === 7);
<del> - text: <code>b</code>的值应为7
<add> - text: <code>b</code>的值应该是 7。
<ide> testString: assert(typeof b === 'number' && b === 7);
<del> - text: <code>a</code>应分配给<code>b</code> <code>=</code>
<add> - text: 你需要用<code>=</code>把<code>a</code>的值赋给<code>b</code>。
<ide> testString: assert(/b\s*=\s*a\s*;/g.test(code));
<ide>
<ide> ```
<ide> if (typeof a != 'undefined') {
<ide> if (typeof b != 'undefined') {
<ide> b = undefined;
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> if (typeof b != 'undefined') {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b){return "a = " + a + ", b = " + b;})(a,b);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a;
<add>var b = 2;
<add>a = 7;
<add>b = a;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.chinese.md
<ide> id: cf1111c1c11feddfaeb4bdef
<ide> title: Subtract One Number from Another with JavaScript
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript从另一个数字中减去一个数字
<add>videoUrl: 'https://scrimba.com/c/cP3yQtk'
<add>forumTopicId: 18314
<add>localeTitle: 减法运算
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们也可以从另一个数字中减去一个数字。 JavaScript使用<code>-</code>符号进行减法。 <p> <strong>例</strong> </p><blockquote> myVar = 12 - 6; //分配6 </blockquote></section>
<add><section id='description'>
<add>我们也可以在 JavaScript 中进行减法运算。
<add>JavaScript 中使用<code>-</code>来做减法运算。
<add>
<add><strong>示例</strong>
<add>
<add>```js
<add>myVar = 12 - 6; // assigned 6
<add>```
<add>
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>0</code>因此差异为<code>12</code> 。 </section>
<add><section id='instructions'>
<add>改变数字<code>0</code>让变量 difference 的值为<code>12</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 使变量<code>difference</code>等于12。
<add> - text: 要使<code>difference</code>的值等于 12。
<ide> testString: assert(difference === 12);
<del> - text: 只从45中减去一个数字。
<del> testString: assert(/difference=45-33;?/.test(code.replace(/\s/g, '')));
<add> - text: 只用 45 减去一个数。
<add> testString: assert(/var\s*difference\s*=\s*45\s*-\s*[0-9]*;(?!\s*[a-zA-Z0-9]+)/.test(code));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```js
<ide> var difference = 45 - 0;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var difference = 45 - 0;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return 'difference = '+z;})(difference);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var difference = 45 - 33;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.chinese.md
<ide> id: 567af2437cbaa8c51670a16c
<ide> title: Testing Objects for Properties
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 测试属性的对象
<add>videoUrl: 'https://scrimba.com/c/cm8Q7Ua'
<add>forumTopicId: 18324
<add>localeTitle: 测试对象的属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时检查给定对象的属性是否存在是有用的。我们可以使用对象的<code>.hasOwnProperty(propname)</code>方法来确定该对象是否具有给定的属性名称。 <code>.hasOwnProperty()</code>如果找到属性则返回<code>true</code>或<code>false</code> 。 <strong>例</strong> <blockquote> var myObj = { <br>顶部:“帽子”, <br>底部:“裤子” <br> }; <br> myObj.hasOwnProperty( “顶部”); //真的<br> myObj.hasOwnProperty( “中间”); //假</blockquote></section>
<add><section id='description'>
<add>有时检查一个对象属性是否存在是非常有用的,我们可以用<code>.hasOwnProperty(propname)</code>方法来检查对象是否有该属性。如果有返回<code>true</code>,反之返回<code>false</code>。
<add><strong>示例</strong>
<add>
<add>```js
<add>var myObj = {
<add> top: "hat",
<add> bottom: "pants"
<add>};
<add>myObj.hasOwnProperty("top"); // true
<add>myObj.hasOwnProperty("middle"); // false
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改函数<code>checkObj</code>以测试<code>myObj</code>的<code>checkProp</code> 。如果找到该属性,则返回该属性的值。如果没有,请返回<code>"Not Found"</code> 。 </section>
<add><section id='instructions'>
<add>修改函数<code>checkObj</code>检查<code>myObj</code>是否有<code>checkProp</code>属性,如果属性存在,返回属性对应的值,如果不存在,返回<code>"Not Found"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>checkObj("gift")</code>应该返回<code>"pony"</code> 。
<add> - text: <code>checkObj("gift")</code>应该返回<code>"pony"</code>。
<ide> testString: assert(checkObj("gift") === "pony");
<del> - text: <code>checkObj("pet")</code>应该返回<code>"kitten"</code> 。
<add> - text: <code>checkObj("pet")</code>应该返回<code>"kitten"</code>。
<ide> testString: assert(checkObj("pet") === "kitten");
<del> - text: <code>checkObj("house")</code>应该返回<code>"Not Found"</code> 。
<add> - text: <code>checkObj("house")</code>应该返回<code>"Not Found"</code>。
<ide> testString: assert(checkObj("house") === "Not Found");
<ide>
<ide> ```
<ide> function checkObj(checkProp) {
<ide>
<ide> // Test your code by modifying these values
<ide> checkObj("gift");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> checkObj("gift");
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myObj = {
<add> gift: "pony",
<add> pet: "kitten",
<add> bed: "sleigh"
<add>};
<add>function checkObj(checkProp) {
<add> if(myObj.hasOwnProperty(checkProp)) {
<add> return myObj[checkProp];
<add> } else {
<add> return "Not Found";
<add> }
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ba
<ide> title: Understand String Immutability
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 理解字符串不变性
<add>videoUrl: 'https://scrimba.com/c/cWPVaUR'
<add>forumTopicId: 18331
<add>localeTitle: 了解字符串的不变性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中, <code>String</code>值是<dfn>不可变的</dfn> ,这意味着一旦创建它们就不能被更改。例如,以下代码: <blockquote> var myStr =“Bob”; <br> myStr [0] =“J”; </blockquote>无法将<code>myStr</code>的值更改为“Job”,因为<code>myStr</code>的内容无法更改。请注意,这<em>并不</em>意味着<code>myStr</code>不能改变的,只是一个<dfn>字符串</dfn>的单个字符不能改变。更改<code>myStr</code>的唯一方法是为其分配一个新字符串,如下所示: <blockquote> var myStr =“Bob”; <br> myStr =“工作”; </blockquote></section>
<add><section id='description'>
<add>在 JavaScript 中,<code>字符串</code>的值是 <dfn>不可变的</dfn>,这意味着一旦字符串被创建就不能被改变。
<add>例如,下面的代码:
<add>
<add>```js
<add>var myStr = "Bob";
<add>myStr[0] = "J";
<add>```
<add>
<add>是不会把变量<code>myStr</code>的值改变成 "Job" 的,因为变量<code>myStr</code>是不可变的。注意,这<em>并不</em>意味着<code>myStr</code>永远不能被改变,只是字符串字面量 <dfn>string literal</dfn> 的各个字符不能被改变。改变<code>myStr</code>中的唯一方法是重新给它赋一个值,例如:
<add>
<add>```js
<add>var myStr = "Bob";
<add>myStr = "Job";
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更正<code>myStr</code>的赋值,使其包含<code>Hello World</code>的字符串值,使用上面示例中显示的方法。 </section>
<add><section id='instructions'>
<add>把<code>myStr</code>的值改为<code>Hello World</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>myStr</code>应该具有<code>Hello World</code>的值
<add> - text: message:<code>myStr</code>的值应该是<code>Hello World</code>。
<ide> testString: assert(myStr === "Hello World");
<del> - text: 不要更改行上方的代码
<add> - text: 不要修改注释上面的代码。
<ide> testString: assert(/myStr = "Jello World"/.test(code));
<ide>
<ide> ```
<ide> var myStr = "Jello World";
<ide>
<ide> myStr[0] = "H"; // Fix Me
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> myStr[0] = "H"; // Fix Me
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(v){return "myStr = " + v;})(myStr);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myStr = "Jello World";
<add>myStr = "Hello World";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.chinese.md
<ide> id: bd7123c9c441eddfaeb5bdef
<ide> title: Understanding Boolean Values
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 了解布尔值
<add>videoUrl: 'https://scrimba.com/c/c9Me8t4'
<add>forumTopicId: 301176
<add>localeTitle: 理解布尔值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">另一种数据类型是<dfn>布尔值</dfn> 。 <code>Booleans</code>可能只是两个值中的一个: <code>true</code>或<code>false</code> 。它们基本上是很少的开关,其中<code>true</code>为“on”而<code>false</code>为“off”。这两个国家是相互排斥的。 <strong>注意</strong> <br> <code>Boolean</code>值永远不会用引号写。 <code>strings</code> <code>"true"</code>和<code>"false"</code>不是<code>Boolean</code> ,在JavaScript中没有特殊含义。 </section>
<add><section id='description'>
<add>另一种数据类型是<dfn>布尔</dfn>(Boolean)。<code>布尔</code>值要么是<code>true</code>要么是<code>false</code>。它非常像电路开关,<code>true</code>是 “开”,<code>false</code>是 “关”。这两种状态是互斥的。
<add><strong>注意</strong><br><code>布尔值</code>是不带引号的,<code>"true"</code>和<code>"false"</code>是<code>字符串</code>而不是<code>布尔值</code>,在 JavaScript 中也没有特殊含义。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改<code>welcomeToBooleans</code>函数,以便在单击运行按钮时返回<code>true</code>而不是<code>false</code> 。 </section>
<add><section id='instructions'>
<add>修改<code>welcomeToBooleans</code>函数,让它返回<code>true</code>而不是<code>false</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>welcomeToBooleans()</code>函数应该返回一个布尔值(true / false)。
<add> - text: <code>welcomeToBooleans()</code>函数应该返回一个布尔值 (true/false)。
<ide> testString: assert(typeof welcomeToBooleans() === 'boolean');
<del> - text: <code>welcomeToBooleans()</code>应该返回true。
<add> - text: <code>welcomeToBooleans()</code>应该返回 true。
<ide> testString: assert(welcomeToBooleans() === true);
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> function welcomeToBooleans() {
<ide>
<del>// Only change code below this line.
<add> // Only change code below this line.
<ide>
<del>return false; // Change this line
<add> return false; // Change this line
<ide>
<del>// Only change code above this line.
<add> // Only change code above this line.
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> return false; // Change this line
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>welcomeToBooleans();
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function welcomeToBooleans() {
<add> return true; // Change this line
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ab
<ide> title: Understanding Case Sensitivity in Variables
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 了解变量中的大小写敏感度
<add>videoUrl: 'https://scrimba.com/c/cd6GDcD'
<add>forumTopicId: 18334
<add>localeTitle: 了解变量名区分大小写
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中,所有变量和函数名称都区分大小写。这意味着资本化很重要。 <code>MYVAR</code>与<code>MyVar</code>和<code>myvar</code> 。可以有多个具有相同名称但不同外壳的不同变量。强烈建议您为清晰起见, <em>不要</em>使用此语言功能。 <h4>最佳实践</h4>在<dfn>camelCase中用</dfn> JavaScript编写变量名。在<dfn>camelCase中</dfn> ,多字变量名称的第一个单词为小写,每个后续单词的首字母大写。 <strong>例子:</strong> <blockquote> var someVariable; <br> var anotherVariableName; <br> var thisVariableNameIsSoLong; </blockquote></section>
<add><section id='description'>
<add>在 JavaScript 中所有的变量和函数名都是大小写敏感的。要区别对待大写字母和小写字母。
<add><code>MYVAR</code>与<code>MyVar</code>和<code>myvar</code>是截然不同的变量。这有可能导致出现多个相似名字的的变量。所以强烈地建议你,为了保持代码清晰不要使用这一特性。
<add><h4>最佳实践</h4>
<add>使用<dfn>驼峰命名法</dfn>来书写一个 Javascript 变量,在<dfn>驼峰命名法</dfn>中,变量名的第一个单词的首写字母小写,后面的单词的第一个字母大写。
<add><strong>示例:</strong>
<add>
<add>```js
<add>var someVariable;
<add>var anotherVariableName;
<add>var thisVariableNameIsSoLong;
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修改现有的声明和赋值,使其名称使用<dfn>camelCase</dfn> 。 <br>不要创建任何新变量。 </section>
<add><section id='instructions'>
<add>修改已声明的变量,让它们的命名符合<dfn>驼峰命名法</dfn>的规范。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>studlyCapVar</code>已定义且值为<code>10</code>
<add> - text: <code>studlyCapVar</code>应该被定义并且值为<code>10</code>。
<ide> testString: assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
<del> - text: <code>properCamelCase</code>已定义且值为<code>"A String"</code>
<add> - text: <code>properCamelCase</code>应该被定义并且值为<code>"A String"</code>。
<ide> testString: assert(typeof properCamelCase !== 'undefined' && properCamelCase === "A String");
<del> - text: <code>titleCaseOver</code>已定义,其值为<code>9000</code>
<add> - text: <code>titleCaseOver</code>应该被定义并且值为<code>9000</code>。
<ide> testString: assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
<del> - text: <code>studlyCapVar</code>应该在声明和赋值部分使用camelCase。
<add> - text: <code>studlyCapVar</code>在声明和赋值时都应该使用驼峰命名法。
<ide> testString: assert(code.match(/studlyCapVar/g).length === 2);
<del> - text: <code>properCamelCase</code>应该在声明和赋值部分使用camelCase。
<add> - text: <code>properCamelCase</code> 在声明和赋值时都应该使用驼峰命名法。
<ide> testString: assert(code.match(/properCamelCase/g).length === 2);
<del> - text: <code>titleCaseOver</code>应该在声明和赋值部分使用camelCase。
<add> - text: <code>titleCaseOver</code> 在声明和赋值时都应该使用驼峰命名法。
<ide> testString: assert(code.match(/titleCaseOver/g).length === 2);
<ide>
<ide> ```
<ide> var TitleCaseOver;
<ide> STUDLYCAPVAR = 10;
<ide> PRoperCAmelCAse = "A String";
<ide> tITLEcASEoVER = 9000;
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tITLEcASEoVER = 9000;
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var studlyCapVar;
<add>var properCamelCase;
<add>var titleCaseOver;
<add>
<add>studlyCapVar = 10;
<add>properCamelCase = "A String";
<add>titleCaseOver = 9000;
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.chinese.md
<ide> id: 598e8944f009e646fc236146
<ide> title: Understanding Undefined Value returned from a Function
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 了解从函数返回的未定义值
<add>videoUrl: 'https://scrimba.com/c/ce2p7cL'
<add>forumTopicId: 301177
<add>localeTitle: 函数也可以返回 undefined
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">函数可以包含<code>return</code>语句但不必包含。在函数没有<code>return</code>语句的情况下,当您调用它时,该函数处理内部代码但返回的值是<code>undefined</code> 。 <strong>例</strong> <blockquote> var sum = 0; <br> function addSum(num){ <br> sum = sum + num; <br> } <br> var returnedValue = addSum(3); //将修改sum,但返回值未定义</blockquote> <code>addSum</code>是一个没有<code>return</code>语句的函数。该函数将更改全局<code>sum</code>变量,但函数的返回值<code>undefined</code> </section>
<add><section id='description'>
<add>函数一般用<code>return</code>语句来返回值,但这不是必须的。在函数没有<code>return</code>语句的情况下,当你调用它时,该函数会执行内部代码,返回的值是<code>undefined</code>。
<add><strong>示例</strong>
<add>
<add>```js
<add>var sum = 0;
<add>function addSum(num) {
<add> sum = sum + num;
<add>}
<add>addSum(3); // sum will be modified but returned value is undefined
<add>```
<add>
<add><code>addSum</code>是一个没有<code>return</code>语句的函数。该函数将更改全局变量<code>sum</code>,函数的返回值为<code>undefined</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个没有任何参数的函数<code>addFive</code> 。此函数向<code>sum</code>变量添加5,但其返回值<code>undefined</code> 。 </section>
<add><section id='instructions'>
<add>创建一个没有任何参数的函数<code>addFive</code>。此函数使<code>sum</code>变量加 5,但其返回值是<code>undefined</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>addFive</code>应该是一个函数
<add> - text: <code>addFive</code>应该是一个函数。
<ide> testString: assert(typeof addFive === 'function');
<del> - text: <code>sum</code>应该等于8
<add> - text: <code>sum</code>应该等于 8。
<ide> testString: assert(sum === 8);
<del> - text: <code>addFive</code>返回值应该是<code>undefined</code>
<add> - text: <code>addFive</code>的返回值应该是<code>undefined</code>。
<ide> testString: assert(addFive() === undefined);
<del> - text: 在函数内部,向<code>sum</code>变量添加5
<add> - text: 函数给变量 <code>sum</code> 加 5。
<ide> testString: assert(addFive.toString().replace(/\s/g, '').match(/sum=sum\+5|sum\+=5/));
<ide>
<ide> ```
<ide> function addThree() {
<ide>
<ide> // Only change code below this line
<ide>
<del>
<del>
<ide> // Only change code above this line
<del>var returnedValue = addFive();
<del>
<add>addThree();
<add>addFive();
<ide> ```
<ide>
<ide> </div>
<ide>
<ide>
<del>### After Test
<del><div id='js-teardown'>
<add>## Solution
<add><section id='solution'>
<ide>
<del>```js
<del>console.info('after the test');
<del>```
<ide>
<del></div>
<add>```js
<add>// Example
<add>var sum = 0;
<add>function addThree() {
<add> sum = sum + 3;
<add>}
<ide>
<del></section>
<add>// Only change code below this line
<ide>
<del>## Solution
<del><section id='solution'>
<add>function addFive() {
<add> sum = sum + 5;
<add>}
<ide>
<del>```js
<del>// solution required
<add>// Only change code above this line
<add>addThree();
<add>addFive();
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.chinese.md
<ide> id: 56533eb9ac21ba0edf2244aa
<ide> title: Understanding Uninitialized Variables
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 了解未初始化的变量
<add>videoUrl: 'https://scrimba.com/c/cBa2JAL'
<add>forumTopicId: 18335
<add>localeTitle: 理解未初始化的变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">声明JavaScript变量时,它们的初始值为<code>undefined</code> 。如果对<code>undefined</code>变量进行数学运算,则结果将为<code>NaN</code> ,表示<dfn>“非数字”</dfn> 。如果将字符串与<code>undefined</code>变量连接起来,您将得到一个<code>"undefined"</code>的文字<dfn>字符串</dfn> 。 </section>
<add><section id='description'>
<add>当 JavaScript 中的变量被声明的时候,程序内部会给它一个初始值<code>undefined</code>。当你对一个值为<code>undefined</code>的变量进行运算操作的时候,算出来的结果将会是<code>NaN</code>,<code>NaN</code>的意思是<dfn>"Not a Number"</dfn>。当你用一个值是<code>undefined</code>的变量来做字符串拼接操作的时候,它会输出字符串<code>"undefined"</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">初始化三个变量<code>a</code> , <code>b</code>和<code>c</code>与<code>5</code> , <code>10</code> ,和<code>"I am a"</code>分别让他们不会<code>undefined</code> 。 </section>
<add><section id='instructions'>
<add>定义 3 个变量<code>a</code>、<code>b</code>、<code>c</code>,并且分别给他们赋值:<code>5</code>、<code>10</code>、<code>"I am a"</code>,这样它们值就不会是<code>undefined</code>了。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>a</code>应定义并评估其值为<code>6</code>
<add> - text: <code>a</code>应该被定义,并且值为<code>6</code>。
<ide> testString: assert(typeof a === 'number' && a === 6);
<del> - text: 应定义和评估<code>b</code>的值为<code>15</code>
<add> - text: <code>b</code>应该被定义,并且值为<code>15</code>。
<ide> testString: assert(typeof b === 'number' && b === 15);
<del> - text: <code>c</code>不应该包含<code>undefined</code>并且值应为“我是一个字符串!”
<add> - text: <code>c</code>的值不能包含<code>undefined</code>,应该为 "I am a String!"。
<ide> testString: assert(!/undefined/.test(c) && c === "I am a String!");
<del> - text: 不要更改行下方的代码
<add> - text: 不要修改第二条注释下的代码。
<ide> testString: assert(/a = a \+ 1;/.test(code) && /b = b \+ 5;/.test(code) && /c = c \+ " String!";/.test(code));
<ide>
<ide> ```
<ide> c = c + " String!";
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(a,b,c){ return "a = " + a + ", b = " + b + ", c = '" + c + "'"; })(a,b,c);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 5;
<add>var b = 10;
<add>var c = "I am a";
<add>a = a + 1;
<add>b = b + 5;
<add>c = c + " String!";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.chinese.md
<ide> id: 56bbb991ad1ed5201cd392d1
<ide> title: Updating Object Properties
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/c9yEJT4'
<add>forumTopicId: 18336
<ide> localeTitle: 更新对象属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在创建JavaScript对象之后,您可以随时更新其属性,就像更新任何其他变量一样。您可以使用点或括号表示法进行更新。例如,让我们看看我们的<code>ourDog</code> : <blockquote> var ourDog = { <br> “名字”:“露营者”, <br> “腿”:4, <br> “尾巴”:1, <br> “朋友们”:[“一切!”] <br> }; </blockquote>由于他是一只特别开心的狗,让我们改名为“快乐露营者”。以下是我们更新对象名称属性的方法: <code>ourDog.name = "Happy Camper";</code>或者我们的<code>ourDog["name"] = "Happy Camper";</code>现在,当我们评估我们的<code>ourDog.name</code> ,而不是获得“Camper”时,我们将获得他的新名字“Happy Camper”。 </section>
<add><section id='description'>
<add>当你创建了一个对象后,你可以用点操作符或中括号操作符来更新对象的属性。
<add>举个例子,让我们看看<code>ourDog</code>:
<add>
<add>```js
<add>var ourDog = {
<add> "name": "Camper",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["everything!"]
<add>};
<add>```
<add>
<add>让我们更改它的名称为 "Happy Camper",这有两种方式来更新对象的<code>name</code>属性:
<add><code>ourDog.name = "Happy Camper";</code> 或
<add><code>ourDog["name"] = "Happy Camper";</code>
<add>现在,<code>ourDog.name</code>的值就不再是 "Camper",而是 "Happy Camper"。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更新<code>myDog</code>对象的name属性。让我们将她的名字从“Coder”改为“Happy Coder”。您可以使用点或括号表示法。 </section>
<add><section id='instructions'>
<add>更新<code>myDog</code>对象的<code>name</code>属性,让它的名字从 "Coder" 变成 "Happy Coder"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 将<code>myDog</code>的<code>"name"</code>属性更新为“Happy Coder”。
<add> - text: 更新<code>myDog</code>的<code>"name"</code>属性, 使其等于 "Happy Coder"。
<ide> testString: assert(/happy coder/gi.test(myDog.name));
<del> - text: 不要编辑<code>myDog</code>定义
<add> - text: 不要修改<code>myDog</code>的定义。
<ide> testString: 'assert(/"name": "Coder"/.test(code));'
<ide>
<ide> ```
<ide> var myDog = {
<ide>
<ide> // Only change code below this line.
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var myDog = {
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(z){return z;})(myDog);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myDog = {
<add> "name": "Coder",
<add> "legs": 4,
<add> "tails": 1,
<add> "friends": ["freeCodeCamp Campers"]
<add>};
<add>myDog.name = "Happy Coder";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.chinese.md
<ide> id: bd7123c9c549eddfaeb5bdef
<ide> title: Use Bracket Notation to Find the First Character in a String
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用括号表示法查找字符串中的第一个字符
<add>videoUrl: 'https://scrimba.com/c/ca8JwhW'
<add>forumTopicId: 18341
<add>localeTitle: 使用方括号查找字符串中的第一个字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>Bracket notation</code>是一种在字符串中的特定<code>index</code>处获取字符的方法。大多数现代编程语言,如JavaScript,都不像人类那样开始计算。它们从0开始。这称为<dfn>基于零的</dfn>索引。例如,单词“Charles”中索引0处的字符是“C”。因此,如果<code>var firstName = "Charles"</code> ,则可以使用<code>firstName[0]</code>获取字符串第一个字母的值。 </section>
<add><section id='description'>
<add>方括号表示法是一种在字符串中的特定<code>index</code>(索引)处获取字符的方法。
<add>大多数现代编程语言,如JavaScript,不同于人类从 1 开始计数。它们是从 0 开始计数,这被称为 <dfn>基于零</dfn> 的索引。
<add>例如, 在单词 "Charles" 中索引 0 上的字符为 "C",所以在<code>var firstName = "Charles"</code>中,你可以使用<code>firstName[0]</code>来获得第一个位置上的字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<dfn>括号表示法</dfn>查找<code>lastName</code>变量中的第一个字符并将其分配给<code>firstLetterOfLastName</code> 。 <strong>暗示</strong> <br>如果卡住,请尝试查看<code>firstLetterOfFirstName</code>变量声明。 </section>
<add><section id='instructions'>
<add>使用方括号获取变量<code>lastName</code>中的第一个字符,并赋给变量<code>firstLetterOfLastName</code>。
<add><strong>提示</strong><br>如果你遇到困难了,不妨看看变量<code>firstLetterOfFirstName</code>是如何赋值的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>firstLetterOfLastName</code>变量的值应为<code>L</code>
<add> - text: <code>firstLetterOfLastName</code>的值应该是<code>L</code>。
<ide> testString: assert(firstLetterOfLastName === 'L');
<del> - text: 您应该使用括号表示法。
<add> - text: 你应该使用中括号。
<ide> testString: assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
<ide>
<ide> ```
<ide> var lastName = "Lovelace";
<ide> // Only change code below this line
<ide> firstLetterOfLastName = lastName;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> firstLetterOfLastName = lastName;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(v){return v;})(firstLetterOfLastName);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var firstLetterOfLastName = "";
<add>var lastName = "Lovelace";
<add>
<add>// Only change code below this line
<add>firstLetterOfLastName = lastName[0];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.chinese.md
<ide> id: bd7123c9c451eddfaeb5bdef
<ide> title: Use Bracket Notation to Find the Last Character in a String
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用括号表示法查找字符串中的最后一个字符
<add>videoUrl: 'https://scrimba.com/c/cBZQGcv'
<add>forumTopicId: 18342
<add>localeTitle: 使用方括号查找字符串中的最后一个字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">为了获得字符串的最后一个字母,您可以从字符串的长度中减去一个字母。例如,如果<code>var firstName = "Charles"</code> ,则可以使用<code>firstName[firstName.length - 1]</code>获取字符串最后一个字母的值。 </section>
<add><section id='description'>
<add>要获取字符串的最后一个字符,可以用字符串的长度减 1 的索引值。
<add>例如,在<code>var firstName = "Charles"</code>中,你可以这样操作<code>firstName[firstName.length - 1]</code>来得到字符串的最后的一个字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<dfn>括号表示法</dfn>查找<code>lastName</code>变量中的最后一个字符。 <strong>暗示</strong> <br>如果卡住了,请尝试查看<code>lastLetterOfFirstName</code>变量声明。 </section>
<add><section id='instructions'>
<add>使用<dfn>方括号<dfn来取得<code>lastName</code>变量中的最后一个字符。
<add><strong>提示</strong><br>如果你遇到困难了,不妨看看在<code>lastLetterOfFirstName</code>变量上是怎么做的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>lastLetterOfLastName</code>应为“e”。
<add> - text: <code>lastLetterOfLastName</code>应该是"e"。
<ide> testString: assert(lastLetterOfLastName === "e");
<del> - text: 你必须使用<code>.length</code>来获取最后一个字母。
<add> - text: 你需要使用<code>.length</code>获取最后一个字符。
<ide> testString: assert(code.match(/\.length/g).length === 2);
<ide>
<ide> ```
<ide> var lastName = "Lovelace";
<ide> // Only change code below this line.
<ide> var lastLetterOfLastName = lastName;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var lastLetterOfLastName = lastName;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(v){return v;})(lastLetterOfLastName);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var firstName = "Ada";
<add>var lastLetterOfFirstName = firstName[firstName.length - 1];
<add>
<add>var lastName = "Lovelace";
<add>var lastLetterOfLastName = lastName[lastName.length - 1];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.chinese.md
<ide> id: bd7123c9c450eddfaeb5bdef
<ide> title: Use Bracket Notation to Find the Nth Character in a String
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用括号表示法查找字符串中的第N个字符
<add>videoUrl: 'https://scrimba.com/c/cWPVJua'
<add>forumTopicId: 18343
<add>localeTitle: 使用方括号查找字符串中的第N个字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您还可以使用<dfn>括号表示法</dfn>来获取字符串中其他位置的字符。请记住,计算机从<code>0</code>开始计数,因此第一个字符实际上是第0个字符。 </section>
<add><section id='description'>
<add>你也可以使用方括号来获得一个字符串中的其他位置的字符。
<add>请记住,程序是从<code>0</code>开始计数,所以获取第一个字符实际上是[0]。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">让我们尝试使用括号表示法将<code>thirdLetterOfLastName</code>设置为等于<code>lastName</code>变量的第三个字母。 <strong>暗示</strong> <br>如果卡住,请尝试查看<code>secondLetterOfFirstName</code>变量声明。 </section>
<add><section id='instructions'>
<add>让我们使用方括号,把<code>lastName</code>变量的第三个字符赋值给<code>thirdLetterOfLastName</code>。
<add><strong>提示</strong><br>如果你遇到困难了,看看<code>secondLetterOfFirstName</code>变量是如何做的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>thirdLetterOfLastName</code>变量的值应为<code>v</code> 。
<add> - text: <code>thirdLetterOfLastName</code>的值应该是<code>v</code>。
<ide> testString: assert(thirdLetterOfLastName === 'v');
<del> - text: 您应该使用括号表示法。
<add> - text: 你应该使用方括号。
<ide> testString: assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
<ide>
<ide> ```
<ide> var lastName = "Lovelace";
<ide> // Only change code below this line.
<ide> var thirdLetterOfLastName = lastName;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var thirdLetterOfLastName = lastName;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(v){return v;})(thirdLetterOfLastName);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var lastName = "Lovelace";
<add>var thirdLetterOfLastName = lastName[2];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.chinese.md
<ide> id: bd7123c9c452eddfaeb5bdef
<ide> title: Use Bracket Notation to Find the Nth-to-Last Character in a String
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用括号表示法查找字符串中的第N个到最后一个字符
<add>videoUrl: 'https://scrimba.com/c/cw4vkh9'
<add>forumTopicId: 18344
<add>localeTitle: 使用方括号查找字符串中的第N个字符到最后一个字符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用我们刚刚用于检索字符串中最后一个字符的相同原理来检索N到最后一个字符。例如,您可以使用<code>firstName[firstName.length - 3]</code>获取<code>var firstName = "Charles"</code>字符串的倒数第三个字母的值</section>
<add><section id='description'>
<add>我们既可以获取字符串的最后一个字符,也可以用获取字符串的倒数第N个字符。
<add>例如,你可以这样<code>firstName[firstName.length - 3]</code>操作来获得<code>var firstName = "Charles"</code>字符串中的倒数第三个字符。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<dfn>括号表示法</dfn>查找<code>lastName</code>字符串中倒数第二个字符。 <strong>暗示</strong> <br>如果卡住,请尝试查看<code>thirdToLastLetterOfFirstName</code>变量声明。 </section>
<add><section id='instructions'>
<add>使用<dfn>方括号</dfn>来获得<code>lastName</code>字符串中的倒数第二个字符。
<add><strong>提示</strong><br>如果你遇到困难了,不妨看看<code>thirdToLastLetterOfFirstName</code>变量是如何做到的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>secondToLastLetterOfLastName</code>应为“c”。
<add> - text: <code>secondToLastLetterOfLastName</code>应该是"c"。
<ide> testString: assert(secondToLastLetterOfLastName === 'c');
<del> - text: 你必须使用<code>.length</code>来获得倒数第二个字母。
<add> - text: 你需要使用<code>.length</code>获取倒数第二个字符。
<ide> testString: assert(code.match(/\.length/g).length === 2);
<ide>
<ide> ```
<ide> var lastName = "Lovelace";
<ide> // Only change code below this line
<ide> var secondToLastLetterOfLastName = lastName;
<ide>
<add>
<ide> ```
<ide>
<ide> </div>
<ide> var secondToLastLetterOfLastName = lastName;
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>(function(v){return v;})(secondToLastLetterOfLastName);
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var firstName = "Ada";
<add>var thirdToLastLetterOfFirstName = firstName[firstName.length - 3];
<add>
<add>var lastName = "Lovelace";
<add>var secondToLastLetterOfLastName = lastName[lastName.length - 2];
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.chinese.md
<ide> id: cf1111c1c12feddfaeb3bdef
<ide> title: Use Conditional Logic with If Statements
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用条件逻辑和If语句
<add>videoUrl: 'https://scrimba.com/c/cy87mf3'
<add>forumTopicId: 18348
<add>localeTitle: 用 if 语句来表达条件逻辑
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>If</code>语句用于在代码中做出决定。关键字<code>if</code>告诉JavaScript在括号中定义的特定条件下执行花括号中的代码。这些条件称为<code>Boolean</code>条件,它们可能只是<code>true</code>或<code>false</code> 。当条件计算结果为<code>true</code> ,程序将执行花括号内的语句。当布尔条件的计算结果为<code>false</code> ,大括号内的语句将不会执行。 <strong>伪代码</strong> <blockquote> if( <i>condition为true</i> ){ <br> <i>声明被执行</i> <br> } </blockquote> <strong>例</strong> <blockquote>功能测试(myCondition){ <br> if(myCondition){ <br>回归“这是真的”; <br> } <br>返回“这是假的”; <br> } <br>测试(真); //返回“这是真的” <br>测试(假); //返回“这是假的” </blockquote>当使用值<code>true</code>调用<code>test</code> , <code>if</code>语句将评估<code>myCondition</code>以查看它是否为<code>true</code> 。因为它是<code>true</code> ,函数返回<code>"It was true"</code> 。当我们使用<code>false</code>值调用<code>test</code>时, <code>myCondition</code> <em>不为</em> <code>true</code>并且不执行花括号中的语句,函数返回<code>"It was false"</code> 。 </section>
<add><section id='description'>
<add><code>If</code>语句用于在代码中做条件判断。关键字<code>if</code>告诉 JavaScript 在小括号中的条件为真的情况下去执行定义在大括号里面的代码。这种条件被称为<code>Boolean</code>条件,因为他们只可能是<code>true</code>(真)或<code>false</code>(假)。
<add>当条件的计算结果为<code>true</code>,程序执行大括号内的语句。当布尔条件的计算结果为<code>false</code>,大括号内的代码将不会执行。
<add><strong>伪代码</strong>
<add><blockquote>if(<i>条件为真</i>){<br> <i>语句被执行</i><br>}</blockquote>
<add><strong>示例</strong>
<add>
<add>```js
<add>function test (myCondition) {
<add> if (myCondition) {
<add> return "It was true";
<add> }
<add> return "It was false";
<add>}
<add>test(true); // returns "It was true"
<add>test(false); // returns "It was false"
<add>```
<add>
<add>当<code>test</code>被调用,并且传递进来的参数值为<code>true</code>,<code>if</code>语句会计算<code>myCondition</code>的结果,看它是真还是假。如果条件为<code>true</code>,函数会返回<code>"It was true"</code>。当<code>test</code>被调用,并且传递进来的参数值为<code>false</code>,<code>myCondition</code><em>不</em> 为<code>true</code>,并且不执行大括号后面的语句,函数返回<code>"It was false"</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在函数内部创建一个<code>if</code>语句<code>"Yes, that was true"</code>如果参数<code>wasThatTrue</code>为<code>true</code>则返回<code>"Yes, that was true"</code> <code>"No, that was false"</code>否则返回<code>"No, that was false"</code> 。 </section>
<add><section id='instructions'>
<add>在函数内部创建一个<code>if</code>语句,如果该参数<code>wasThatTrue</code>值为<code>true</code>,返回<code>"Yes, that was true"</code>,否则,并返回<code>"No, that was false"</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>trueOrFalse</code>应该是一个函数
<add> - text: <code>trueOrFalse</code>应该是一个函数。
<ide> testString: assert(typeof trueOrFalse === "function");
<del> - text: <code>trueOrFalse(true)</code>应该返回一个字符串
<add> - text: <code>trueOrFalse(true)</code>应该返回一个字符串。
<ide> testString: assert(typeof trueOrFalse(true) === "string");
<del> - text: <code>trueOrFalse(false)</code>应该返回一个字符串
<add> - text: <code>trueOrFalse(false)</code>应该返回一个字符串。
<ide> testString: assert(typeof trueOrFalse(false) === "string");
<del> - text: <code>trueOrFalse(true)</code>应该返回“是的,那是真的”
<add> - text: <code>trueOrFalse(true)</code>应该返回 "Yes, that was true"。
<ide> testString: assert(trueOrFalse(true) === "Yes, that was true");
<del> - text: <code>trueOrFalse(false)</code>应该返回“No,that was false”
<add> - text: <code>trueOrFalse(false)</code>应该返回 "No, that was false"。
<ide> testString: assert(trueOrFalse(false) === "No, that was false");
<ide>
<ide> ```
<ide> function trueOrFalse(wasThatTrue) {
<ide>
<ide> // Change this value to test
<ide> trueOrFalse(true);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> trueOrFalse(true);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function trueOrFalse(wasThatTrue) {
<add> if (wasThatTrue) {
<add> return "Yes, that was true";
<add> }
<add> return "No, that was false";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.chinese.md
<ide> id: 587d7b7e367417b2b2512b21
<ide> title: Use Multiple Conditional (Ternary) Operators
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用多个条件(三元)运算符
<add>videoUrl: 'https://scrimba.com/c/cyWJBT4'
<add>forumTopicId: 301179
<add>localeTitle: 使用多个三元运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在之前的挑战中,您使用了单个<code>conditional operator</code> 。您也可以将它们链接在一起以检查多种条件。以下函数使用if,else if和else语句来检查多个条件: <blockquote> function findGreaterOrEqual(a,b){ <br> if(a === b){ <br>返回“a和b相等”; <br> } <br>否则如果(a> b){ <br>返回“a更大”; <br> } <br>其他{ <br>返回“b更大”; <br> } <br> } </blockquote>可以使用多个<code>conditional operators</code>重写上述函数: <blockquote> function findGreaterOrEqual(a,b){ <br>返回(a === b)? “a和b相等”:(a> b)? “a更大”:“b更大”; <br> } </blockquote></section>
<add><section id='description'>
<add>在之前的挑战中,你使用了一个条件运算符。你也可以将多个运算符串联在一起以检查多种条件。
<add>下面的函数使用 if,else if 和 else 语句来检查多个条件:
<add>
<add>```js
<add>function findGreaterOrEqual(a, b) {
<add> if (a === b) {
<add> return "a and b are equal";
<add> }
<add> else if (a > b) {
<add> return "a is greater";
<add> }
<add> else {
<add> return "b is greater";
<add> }
<add>}
<add>```
<add>
<add>上面的函数使用条件运算符写法如下:
<add>
<add>```js
<add>function findGreaterOrEqual(a, b) {
<add> return (a === b) ? "a and b are equal"
<add> : (a > b) ? "a is greater"
<add> : "b is greater";
<add>}
<add>```
<add>
<add>即便如此,应谨慎使用多个三元运算符,因为在没有适当缩进的情况下使用多个三元运算符可能会使您的代码难以阅读。 例如:
<add>
<add>```js
<add>function findGreaterOrEqual(a, b) {
<add> return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>checkSign</code>函数中使用多个<code>conditional operators</code>来检查数字是正数,负数还是零。 </section>
<add><section id='instructions'>
<add>在 checkSign 函数中使用多个条件运算符来检查数字是正数 ("positive")、负数 ("negative") 或零 ("zero")。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>checkSign</code>应该使用多个<code>conditional operators</code>
<del> testString: assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code));
<del> - text: <code>checkSign(10)</code>应该返回“positive”。请注意,资本化很重要
<add> - text: <code>checkSign</code>应该使用多个条件运算符。
<add> testString: 'assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code));'
<add> - text: <code>checkSign(10)</code>应该返回 "positive" 注意,结果对大小写敏感。
<ide> testString: assert(checkSign(10) === 'positive');
<del> - text: <code>checkSign(-12)</code>应返回“否定”。请注意,资本化很重要
<add> - text: <code>checkSign(-12)</code>应该返回 "negative" 注意,结果对大小写敏感。
<ide> testString: assert(checkSign(-12) === 'negative');
<del> - text: <code>checkSign(0)</code>应返回“零”。请注意,资本化很重要
<add> - text: <code>checkSign(0)</code>应该返回 "zero" 注意,结果对大小写敏感。
<ide> testString: assert(checkSign(0) === 'zero');
<ide>
<ide> ```
<ide> function checkSign(num) {
<ide> }
<ide>
<ide> checkSign(10);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> checkSign(10);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function checkSign(num) {
<add> return (num > 0) ? 'positive' : (num < 0) ? 'negative' : 'zero';
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown.md
<add>---
<add>id: 5cd9a70215d3c4e65518328f
<add>title: Use Recursion to Create a Countdown
<add>challengeType: 1
<add>forumTopicId: 305925
<add>localeTitle: 使用递归创建一个倒计时
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>
<add>在上一个[挑战](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion),学习了怎样用递归来代替循环。现在来学习一个更复杂的函数,函数返回一个从 <code>1</code> 到传递给函数的指定数字的连续数字数组。
<add>
<add>正如上一个挑战提到的,会有一个 <dfn>base case</dfn>。base case 告诉递归函数什么时候不在需要调用其自身。这是简单 情况,返回得到的值。还有 <dfn>recursive call</dfn>,继续用不同的参数调用自身。如果函数无误,一直执行直到 base case 为止。
<add>
<add>比如,如果想写一个递归函数,返回一个数字 <code>1</code> 到 <code>n</code> 的连续数组。这个函数需要接收一个参数<code>n</code> 代表起始数字。然后会持续的调用自身,传入一个比 <code>n</code> 更小的值一直到传入的值是 <code>1</code> 为止。函数如下:
<add>
<add>```javascript
<add>function countup(n) {
<add> if (n < 1) {
<add> return [];
<add> } else {
<add> const countArray = countup(n - 1);
<add> countArray.push(n);
<add> return countArray;
<add> }
<add>}
<add>console.log(countup(5)); // [ 1, 2, 3, 4, 5 ]
<add>```
<add>
<add>起初,这似乎是违反直觉的,因为 n 的值<em>递减</em>,但是最终数组中的值却<em>递增</em>。 之所以发生这种情况,是因为在递归调用返回之后,才调用 push。 在将 `n` pushed 进数组时,`count(n - 1)` 已经调用赋值成功并返回了 `[1, 2, ..., n - 1]`。
<add>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add>已经定义了一个函数 <code>countdown</code>,函数有一个参数(<code>n</code>)。函数应该基于参数 <code>n</code> 递归调用返回 <code>n</code> 到 <code>1</code> 的连续数字的数组。如果函数以小于 1 的参数调用,函数应该返回空数组。
<add>比如,用 <code>n = 5</code> 调用函数应该返回数组 <code>[5, 4, 3, 2, 1]</code>。
<add>函数必需使用递归函数调用自身,不能使用任何形式的循环。
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>``` yml
<add>tests:
<add> - text: <code>countdown(-1)</code> 应该返回一个空数组。
<add> testString: assert.isEmpty(countdown(-1));
<add> - text: <code>countdown(10)</code> 应该返回 <code>[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]</code>。
<add> testString: assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
<add> - text: <code>countdown(5)</code> 应该返回 <code>[5, 4, 3, 2, 1]</code>。
<add> testString: assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]);
<add> - text: 代码不能包含任意形式的循环(<code>for</code>、<code>while</code> 或者高阶函数如:<code>forEach</code>、<code>map</code>、<code>filter</code> 以及 <code>reduce</code>)。
<add> testString: assert(!removeJSComments(code).match(/for|while|forEach|map|filter|reduce/g));
<add> - text: 应该用递归解决这个问题。
<add> testString: assert(removeJSComments(countdown.toString()).match(/countdown\s*\(.+\)\;/));
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add><div id='js-seed'>
<add>
<add>```js
<add>
<add>
<add>//Only change code below this line
<add>function countdown(n){
<add> return;
<add>}
<add>console.log(countdown(5)); // [5, 4, 3, 2, 1]
<add>```
<add>
<add></div>
<add>
<add>### After Test
<add><div id='js-teardown'>
<add>
<add>```js
<add>const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
<add>```
<add>
<add></div>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>//Only change code below this line
<add>function countdown(n){
<add> return n < 1 ? [] : [n].concat(countdown(n - 1));
<add>}
<add>```
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers.chinese.md
<add>---
<add>id: 5cc0bd7a49b71cb96132e54c
<add>title: Use Recursion to Create a Range of Numbers
<add>challengeType: 1
<add>forumTopicId: 301180
<add>localeTitle: 使用递归来创建一个数字序列
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>
<add>接着上一个挑战,有另外一个机会来创建递归函数解决问题。
<add>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>定义好了 <code>rangeOfNumbers</code> 函数,包含两个参数。函数应该返回一个连续数字数组,<code>startNum</code> 参数开始 <code>endNum</code> 参数截止。开始的数字小于或等于截止数字。函数必需递归调用自身,不能使用任意形式的循环。要考虑到 <code>startNum</code> 和 <code>endNum</code> 相同的情况。
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>``` yml
<add>tests:
<add> - text: 函数应该返回一个数组。
<add> testString: assert(Array.isArray(rangeOfNumbers(5, 10)));
<add> - text: 不能包含循环语句(<code>for</code> 或者 <code>while</code> 或者高阶函数比如 <code>forEach</code>、<code>map</code>、<code>filter</code> 或者 <code>reduce</code>)。
<add> testString: assert(!removeJSComments(code).match(/for|while|forEach|map|filter|reduce/g));
<add> - text: <code>rangeOfNumbers</code> 应该使用递归函数(调用自身)来完成这个挑战。
<add> testString: assert(removeJSComments(rangeOfNumbers.toString()).match(/rangeOfNumbers\s*\(.+\)/));
<add> - text: <code>rangeOfNumbers(1, 5)</code> 应该返回 <code>[1, 2, 3, 4, 5]</code>。
<add> testString: assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]);
<add> - text: <code>rangeOfNumbers(6, 9)</code> 应该返回 <code>[6, 7, 8, 9]</code>。
<add> testString: assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]);
<add> - text: <code>rangeOfNumbers(4, 4)</code> 应该返回 <code>[4]</code>。
<add> testString: assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]);
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add><div id='js-seed'>
<add>
<add>```js
<add>function rangeOfNumbers(startNum, endNum) {
<add> return [];
<add>};
<add>```
<add>
<add></div>
<add>
<add>### After Test
<add><div id='js-teardown'>
<add>
<add>```js
<add>const removeJSComments = str => str.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '');
<add>```
<add>
<add></div>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>function rangeOfNumbers(startNum, endNum) {
<add> if (endNum - startNum === 0) {
<add> return [startNum];
<add> } else {
<add> var numbers = rangeOfNumbers(startNum, endNum - 1);
<add> numbers.push(endNum);
<add> return numbers;
<add> }
<add>}
<add>```
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.chinese.md
<ide> id: 587d7b7e367417b2b2512b24
<ide> title: Use the Conditional (Ternary) Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用条件(三元)运算符
<add>videoUrl: 'https://scrimba.com/c/c3JRmSg'
<add>forumTopicId: 301181
<add>localeTitle: 使用三元运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>条件运算符</dfn> (也称为<dfn>三元运算符</dfn> )可以用作一行if-else表达式。语法是: <code>condition ? statement-if-true : statement-if-false;</code>以下函数使用if-else语句来检查条件: <blockquote> function findGreater(a,b){ <br> if(a> b){ <br>返回“a更大”; <br> } <br>其他{ <br>返回“b更大”; <br> } <br> } </blockquote>这可以使用<code>conditional operator</code>重写: <blockquote> function findGreater(a,b){ <br>返回a> b? “a更大”:“b更大”; <br> } </blockquote></section>
<add><section id='description'>
<add>条件运算符(也称为三元运算符)的用处就像写成一行的 if-else 表达式
<add>语法如下所示:
<add><code>condition ? statement-if-true : statement-if-false;</code>
<add>以下函数使用 if-else 语句来检查条件:
<add>
<add>```js
<add>function findGreater(a, b) {
<add> if(a > b) {
<add> return "a is greater";
<add> }
<add> else {
<add> return "b is greater";
<add> }
<add>}
<add>```
<add>
<add>上面的函数使用条件运算符写法如下:
<add>
<add>```js
<add>function findGreater(a, b) {
<add> return a > b ? "a is greater" : "b is greater";
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>checkEqual</code>函数中使用<code>conditional operator</code>来检查两个数字是否相等。该函数应返回true或false。 </section>
<add><section id='instructions'>
<add>在<code>checkEqual</code>函数中使用条件运算符检查两个数字是否相等,函数应该返回 "Equal" 或 "Not Equal"
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>checkEqual</code>应该使用<code>conditional operator</code>
<add> - text: <code>checkEqual</code>应该使用条件运算符。
<ide> testString: assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
<del> - text: '<code>checkEqual(1, 2)</code>应该返回false'
<add> - text: <code>checkEqual(1, 2)</code>应该返回 "Not Equal"。
<ide> testString: assert(checkEqual(1, 2) === "Not Equal");
<del> - text: '<code>checkEqual(1, 1)</code>应该返回true'
<add> - text: <code>checkEqual(1, 1)</code>应该返回 "Equal"。
<ide> testString: assert(checkEqual(1, 1) === "Equal");
<del> - text: '<code>checkEqual(1, -1)</code>应该返回false'
<add> - text: <code>checkEqual(1, -1)</code>应该返回 "Not Equal"。
<ide> testString: assert(checkEqual(1, -1) === "Not Equal");
<del>
<ide> ```
<ide>
<ide> </section>
<ide> function checkEqual(a, b) {
<ide> }
<ide>
<ide> checkEqual(1, 2);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> checkEqual(1, 2);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function checkEqual(a, b) {
<add> return a === b ? "Equal" : "Not Equal";
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.chinese.md
<ide> id: 587d7b7e367417b2b2512b22
<ide> title: Use the parseInt Function with a Radix
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 将parseInt函数与Radix一起使用
<add>videoUrl: 'https://scrimba.com/c/c6K4Kh3'
<add>forumTopicId: 301182
<add>localeTitle: 使用 parseInt 函数并传入一个基数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>parseInt()</code>函数解析字符串并返回一个整数。它需要一个基数的第二个参数,它指定字符串中数字的基数。基数可以是2到36之间的整数。函数调用如下: <code>parseInt(string, radix);</code>这是一个例子: <code>var a = parseInt("11", 2);</code>基数变量表示“11”在二进制系统或基数2中。此示例将字符串“11”转换为整数3。 </section>
<add><section id='description'>
<add><code>parseInt()</code>函数解析一个字符串并返回一个整数。它同时可接受第二个参数,一个介于2和36之间的整数,表示字符串的基数。
<add>函数调用如下所示:
<add><code>parseInt(string, radix);</code>
<add>示例:
<add><code>var a = parseInt("11", 2);</code>
<add>参数 2 表示 "11" 使用二进制数值系统。此示例将字符串 "11" 转换为整数 3。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>convertToInteger</code>函数中使用<code>parseInt()</code> ,以便将二进制数转换为整数并返回它。 </section>
<add><section id='instructions'>
<add>在<code>convertToInteger</code中使用<code>parseInt()</code>函数把二进制数转换成十进制并返回。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>convertToInteger</code>应该使用<code>parseInt()</code>函数
<add> - text: <code>convertToInteger</code>中应该使用<code>parseInt()</code>函数。
<ide> testString: assert(/parseInt/g.test(code));
<del> - text: <code>convertToInteger("10011")</code>应该返回一个数字
<add> - text: <code>convertToInteger("10011")</code>应该返回一个数字。
<ide> testString: assert(typeof(convertToInteger("10011")) === "number");
<del> - text: <code>convertToInteger("10011")</code>应该返回19
<add> - text: <code>convertToInteger("10011")</code>应该返回 19。
<ide> testString: assert(convertToInteger("10011") === 19);
<del> - text: <code>convertToInteger("111001")</code>应该返回57
<add> - text: <code>convertToInteger("111001")</code>应该返回 57。
<ide> testString: assert(convertToInteger("111001") === 57);
<del> - text: <code>convertToInteger("JamesBond")</code>应该返回NaN
<add> - text: <code>convertToInteger("JamesBond")</code>应该返回 NaN。
<ide> testString: assert.isNaN(convertToInteger("JamesBond"));
<ide>
<ide> ```
<ide> function convertToInteger(str) {
<ide> }
<ide>
<ide> convertToInteger("10011");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> convertToInteger("10011");
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function convertToInteger(str) {
<add> return parseInt(str, 2);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.chinese.md
<ide> id: 587d7b7e367417b2b2512b23
<ide> title: Use the parseInt Function
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用parseInt函数
<add>videoUrl: 'https://scrimba.com/c/cm83LSW'
<add>forumTopicId: 301183
<add>localeTitle: 使用 parseInt 函数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>parseInt()</code>函数解析字符串并返回一个整数。这是一个例子: <code>var a = parseInt("007");</code>上面的函数将字符串“007”转换为整数7.如果字符串中的第一个字符无法转换为数字,则返回<code>NaN</code> 。 </section>
<add><section id='description'>
<add><code>parseInt()</code>函数解析一个字符串返回一个整数下面是一个示例:
<add><code>var a = parseInt("007");</code>
<add>上面的函数把字符串 "007" 转换成数字 7。 如果字符串参数的第一个字符是字符串类型的,结果将不会转换成数字,而是返回<code>NaN</code>.
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>convertToInteger</code>函数中使用<code>parseInt()</code> ,以便将输入字符串<code>str</code>转换为整数,然后返回它。 </section>
<add><section id='instructions'>
<add>在<code>convertToInteger</code>函数中使用<code>parseInt()</code>将字符串<code>str</code>转换为正数并返回。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>convertToInteger</code>应该使用<code>parseInt()</code>函数
<add> - text: <code>convertToInteger</code>应该使用<code>parseInt()</code>函数。
<ide> testString: assert(/parseInt/g.test(code));
<del> - text: <code>convertToInteger("56")</code>应该返回一个数字
<add> - text: <code>convertToInteger("56")</code>应该返回一个数字。
<ide> testString: assert(typeof(convertToInteger("56")) === "number");
<del> - text: <code>convertToInteger("56")</code>应该返回56
<add> - text: <code>convertToInteger("56")</code>应该返回 56。
<ide> testString: assert(convertToInteger("56") === 56);
<del> - text: <code>convertToInteger("77")</code>应该返回77
<add> - text: <code>convertToInteger("77")</code>应该返回 77。
<ide> testString: assert(convertToInteger("77") === 77);
<del> - text: <code>convertToInteger("JamesBond")</code>应该返回NaN
<add> - text: <code>convertToInteger("JamesBond")</code>应该返回 NaN。
<ide> testString: assert.isNaN(convertToInteger("JamesBond"));
<ide>
<ide> ```
<ide> function convertToInteger(str) {
<ide> }
<ide>
<ide> convertToInteger("56");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> convertToInteger("56");
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function convertToInteger(str) {
<add> return parseInt(str);
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.chinese.md
<ide> id: 56533eb9ac21ba0edf2244ca
<ide> title: Using Objects for Lookups
<ide> challengeType: 1
<del>videoUrl: ''
<add>videoUrl: 'https://scrimba.com/c/cdBk8sM'
<add>forumTopicId: 18373
<ide> localeTitle: 使用对象进行查找
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">对象可以被认为是键/值存储,就像字典一样。如果您有表格数据,则可以使用对象“查找”值而不是<code>switch</code>语句或<code>if/else</code>链。当您知道输入数据限制在特定范围内时,这非常有用。以下是简单反向字母查找的示例: <blockquote> var alpha = { <br> 1: “Z”, <br> 2: “Y”, <br> 3: “X”, <br> 4: “W”, <br> ... <br> 24: “C”, <br> 25: “B”, <br> 26: “A” <br> }; <br>阿尔法[2]; //“Y” <br>阿尔法[24]; // “C” <br><br> var value = 2; <br>阿尔法[值]。 //“Y” </blockquote></section>
<add><section id='description'>
<add>对象和字典一样,可以用来存储键/值对。如果你的数据跟对象一样,你可以用对象来查找你想要的值,而不是使用switch或if/else语句。当你知道你的输入数据在某个范围时,这种查找方式极为有效。
<add>这是简单的反向字母表:
<add>
<add>```js
<add>var alpha = {
<add> 1:"Z",
<add> 2:"Y",
<add> 3:"X",
<add> 4:"W",
<add> ...
<add> 24:"C",
<add> 25:"B",
<add> 26:"A"
<add>};
<add>alpha[2]; // "Y"
<add>alpha[24]; // "C"
<add>
<add>var value = 2;
<add>alpha[value]; // "Y"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将switch语句转换为名为<code>lookup</code>的对象。使用它来查找<code>val</code>并将关联的字符串分配给<code>result</code>变量。 </section>
<add><section id='instructions'>
<add>把 switch 语句转化为<code>lookup</code>对象。使用它来查找<code>val</code>属性的值,并赋值给<code>result</code>变量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>phoneticLookup("alpha")</code>应该等于<code>"Adams"</code>
<add> - text: <code>phoneticLookup("alpha")</code>应该等于<code>"Adams"</code>。
<ide> testString: assert(phoneticLookup("alpha") === 'Adams');
<del> - text: <code>phoneticLookup("bravo")</code>应该等于<code>"Boston"</code>
<add> - text: <code>phoneticLookup("bravo")</code>应该等于<code>"Boston"</code>。
<ide> testString: assert(phoneticLookup("bravo") === 'Boston');
<del> - text: <code>phoneticLookup("charlie")</code>应该等于<code>"Chicago"</code>
<add> - text: <code>phoneticLookup("charlie")</code>应该等于<code>"Chicago"</code>。
<ide> testString: assert(phoneticLookup("charlie") === 'Chicago');
<del> - text: <code>phoneticLookup("delta")</code>应该等于<code>"Denver"</code>
<add> - text: <code>phoneticLookup("delta")</code>应该等于<code>"Denver"</code>。
<ide> testString: assert(phoneticLookup("delta") === 'Denver');
<del> - text: <code>phoneticLookup("echo")</code>应该等于<code>"Easy"</code>
<add> - text: <code>phoneticLookup("echo")</code>应该等于<code>"Easy"</code>。
<ide> testString: assert(phoneticLookup("echo") === 'Easy');
<del> - text: <code>phoneticLookup("foxtrot")</code>应该等于<code>"Frank"</code>
<add> - text: <code>phoneticLookup("foxtrot")</code>应该等于<code>"Frank"</code>。
<ide> testString: assert(phoneticLookup("foxtrot") === 'Frank');
<del> - text: <code>phoneticLookup("")</code>应该等于<code>undefined</code>
<add> - text: <code>phoneticLookup("")</code>应该等于<code>undefined</code>。
<ide> testString: assert(typeof phoneticLookup("") === 'undefined');
<del> - text: 您不应该修改<code>return</code>语句
<add> - text: 请不要修改<code>return</code>语句。
<ide> testString: assert(code.match(/return\sresult;/));
<del> - text: 您不应该使用<code>case</code> , <code>switch</code>或<code>if</code>语句
<add> - text: 请不要使用<code>case</code>,<code>switch</code>,或<code>if</code>语句。
<ide> testString: assert(!/case|switch|if/g.test(code.replace(/([/]{2}.*)|([/][*][^/*]*[*][/])/g,'')));
<ide>
<ide> ```
<ide> function phoneticLookup(val) {
<ide>
<ide> // Change this value to test
<ide> phoneticLookup("charlie");
<del>
<ide> ```
<ide>
<ide> </div>
<ide> phoneticLookup("charlie");
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function phoneticLookup(val) {
<add> var result = "";
<add>
<add> var lookup = {
<add> alpha: "Adams",
<add> bravo: "Boston",
<add> charlie: "Chicago",
<add> delta: "Denver",
<add> echo: "Easy",
<add> foxtrot: "Frank"
<add> };
<add>
<add> result = lookup[val];
<add>
<add> return result;
<add>}
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.chinese.md
<ide> id: 56533eb9ac21ba0edf2244bb
<ide> title: Word Blanks
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 字空白
<add>videoUrl: 'https://scrimba.com/c/caqn8zuP'
<add>forumTopicId: 18377
<add>localeTitle: 填词造句
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们现在将使用我们的弦乐知识来构建一个“ <a href="https://en.wikipedia.org/wiki/Mad_Libs" target="_blank">疯狂的自由</a> ”风格的文字游戏,我们称之为“Word Blanks”。您将创建一个(可选幽默的)“填空”样式句子。在“疯狂的自由人”游戏中,您将获得包含名词,动词,形容词和副词等缺失单词的句子。然后,您可以用完成的句子有意义的方式用您选择的单词填写缺失的部分。想想这句话- “这是真的<strong>____,</strong>我们<strong>____</strong> <strong>____</strong>自己”。这句话有三个缺失的部分 - 形容词,动词和副词,我们可以添加我们选择的单词来完成它。然后我们可以将完成的句子分配给变量,如下所示: <blockquote> var sentence =“它真的是”+“热”+“,我们”+“笑”+“自己”+“傻。”; </blockquote></section>
<add><section id='description'>
<add>现在,我们来用字符串的相关知识实现一个 "<a href='https://en.wikipedia.org/wiki/Mad_Libs' target='_blank'>Mad Libs</a>" 类的文字游戏,称为 "Word Blanks"。 你将创建一个(可选幽默的)“填空”样式句子。
<add>在 "Mad Libs" 游戏中,提供一个缺少一些单词的句子,缺少的单词包括名词,动词,形容词和副词等。然后,你选择一些单词填写句子缺失的地方,使句子完整并且有意义。
<add>思考一下这句话 - "It was really <strong>____</strong>, and we <strong>____</strong> ourselves <strong>____</strong>"。这句话有三个缺失的部分 - 形容词,动词和副词,选择合适单词填入完成它。然后将完成的句子赋值给变量,如下所示:
<add>
<add>```js
<add>var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在这个挑战中,我们为您提供名词,动词,形容词和副词。您需要使用您选择的单词以及我们提供的单词来形成完整的句子。您将需要使用字符串连接运算符<code>+</code>来使用提供的变量构建新字符串: <code>myNoun</code> , <code>myAdjective</code> , <code>myVerb</code>和<code>myAdverb</code> 。然后,您将形成的字符串分配给<code>result</code>变量。您还需要考虑字符串中的空格,以便最后一句话在所有单词之间有空格。结果应该是一个完整的句子。 </section>
<add><section id='instructions'>
<add>在这个挑战中,我们为你提供名词,动词,形容词和副词。你需要使用合适单词以及我们提供的单词来形成完整的句子。
<add>你需要使用字符串连接运算符<code>+</code>来拼接字符串变量:<code>myNoun</code>,<code>myAdjective</code>,<code>myVerb</code>,和<code>myAdverb</code>来构建一个新字符串。然后,将新字符串赋给<code>result</code>变量。
<add>你还需要考虑字符串中的空格,确保句子的所有单词之间有空格。结果应该是一个完整的句子。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>wordBlanks("","","","")</code>应该返回一个字符串。'
<del> testString: assert(typeof wordBlanks("","","","") === "string");
<del> - text: '<code>wordBlanks("dog", "big", "ran", "quickly")</code>应包含由非单词字符(以及madlib中的任何其他单词)分隔的所有传入单词。'
<del> testString: assert(/\bdog\b/.test(test1) && /\bbig\b/.test(test1) && /\bran\b/.test(test1) && /\bquickly\b/.test(test1));
<del> - text: '<code>wordBlanks("cat", "little", "hit", "slowly")</code>应包含由非单词字符(以及madlib中的任何其他单词)分隔的所有传入单词。'
<del> testString: assert(/\bcat\b/.test(test2) && /\blittle\b/.test(test2) && /\bhit\b/.test(test2) && /\bslowly\b/.test(test2));
<add> - text: <code>wordBlanks("","","","")</code>应该返回一个字符串。
<add> testString: assert(typeof wordBlanks === 'string');
<add> - text: 不能改变 <code>myNoun</code>、<code>myVerb</code>、<code>myAdjective</code> 或者 <code>myAdverb</code> 的值。
<add> testString: assert(myNoun === "dog" && myVerb === "ran" && myAdjective === "big" && myAdverb === "quickly");
<add> - text: 不能直接使用 "dog"、"ran"、"big" 或者 "quickly" 来创建 <code>wordBlanks</code>。
<add> testString: const newCode = removeAssignments(code); assert(!/dog/.test(newCode) && !/ran/.test(newCode) && !/big/.test(newCode) && !/quickly/.test(newCode));
<add> - text: <code>wordBlanks</code> 应包含分配给变量 <code>myNoun</code>、<code>myVerb</code>、<code>myAdjective</code> 和 <code>myAdverb</code> 的所有单词,并用非单词字符(以及 madlib 中的其它单词)分隔。
<add> testString: assert(/\bdog\b/.test(wordBlanks) && /\bbig\b/.test(wordBlanks) && /\bran\b/.test(wordBlanks) && /\bquickly\b/.test(wordBlanks));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) {
<del> // Your code below this line
<del> var result = "";
<add>var myNoun = "dog";
<add>var myAdjective = "big";
<add>var myVerb = "ran";
<add>var myAdverb = "quickly";
<ide>
<del> // Your code above this line
<del> return result;
<del>}
<del>
<del>// Change the words here to test your function
<del>wordBlanks("dog", "big", "ran", "quickly");
<add>var wordBlanks = ""; // Only change this line;
<ide>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<del>### After Test
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>const removeAssignments = str => str
<add> .replace(/myNoun\s*=\s*["']dog["']/g, '')
<add> .replace(/myAdjective\s*=\s*["']big["']/g, '')
<add> .replace(/myVerb\s*=\s*["']ran["']/g, '')
<add> .replace(/myAdverb\s*=\s*["']quickly["']/g, '');
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var myNoun = "dog";
<add>var myAdjective = "big";
<add>var myVerb = "ran";
<add>var myAdverb = "quickly";
<add>
<add>var wordBlanks = "Once there was a " + myNoun + " which was very " + myAdjective + ". ";
<add>wordBlanks += "It " + myVerb + " " + myAdverb + " around the yard.";
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.chinese.md
<ide> id: 56bbb991ad1ed5201cd392cf
<ide> title: Write Reusable JavaScript with Functions
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 用函数编写可重用的JavaScript
<add>videoUrl: 'https://scrimba.com/c/cL6dqfy'
<add>forumTopicId: 18378
<add>localeTitle: 用函数编写可重用代码
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在JavaScript中,我们可以将代码划分为称为<dfn>函数的</dfn>可重用部分。这是一个函数的例子: <blockquote> function functionName(){ <br> console.log(“Hello World”); <br> } </blockquote>您可以使用其名称后跟括号来调用或<dfn>调用</dfn>此函数,如下所示: <code>functionName();</code>每次调用该函数时,它都会在开发控制台上打印出<code>"Hello World"</code>消息。每次调用函数时,都会执行大括号之间的所有代码。 </section>
<add><section id='description'>
<add>在 JavaScript 中,我们可以把代码的重复部分抽取出来,放到一个<dfn>函数</dfn>中。
<add>举个例子:
<add>
<add>```js
<add>function functionName() {
<add> console.log("Hello World");
<add>}
<add>```
<add>
<add>你可以通过函数名<code>functionName</code>加上后面的小括号来调用这个函数,就像这样:
<add><code>functionName();</code>
<add>每次调用函数时,它都会在控制台上打印消息<code>"Hello World"</code>。每次调用函数时,大括号之间的所有代码都将被执行。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"><ol><li>创建一个名为<code>reusableFunction</code>的函数,它将<code>"Hi World"</code>打印到开发控制台。 </li><li>调用该功能。 </li></ol></section>
<add><section id='instructions'>
<add><ol><li>先创建一个名为<code>reusableFunction</code>的函数,这个函数可以打印<code>"Hi World"</code>到控制台上。</li><li>然后调用这个函数。</li></ol>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>reusableFunction</code>应该是一个函数
<add> - text: <code>reusableFunction</code>应该是一个函数。
<ide> testString: assert(typeof reusableFunction === 'function');
<del> - text: <code>reusableFunction</code>应该将“Hi World”输出到开发控制台
<add> - text: <code>reusableFunction</code>应该在控制台中输出 "Hi World"。
<ide> testString: assert(hiWorldWasLogged);
<del> - text: 定义后调用<code>reusableFunction</code>
<add> - text: 在你定义<code>reusableFunction</code>之后记得调用它。
<ide> testString: assert(/^\s*reusableFunction\(\)\s*/m.test(code));
<ide>
<ide> ```
<ide> ourReusableFunction();
<ide>
<ide> ```js
<ide> var logOutput = "";
<del>var originalConsole = console
<add>var originalConsole = console;
<add>var nativeLog = console.log;
<add>var hiWorldWasLogged = false;
<ide> function capture() {
<del> var nativeLog = console.log;
<ide> console.log = function (message) {
<add> if(message === 'Hi World') hiWorldWasLogged = true;
<ide> if(message && message.trim) logOutput = message.trim();
<ide> if(nativeLog.apply) {
<ide> nativeLog.apply(originalConsole, arguments);
<ide> function capture() {
<ide> }
<ide>
<ide> function uncapture() {
<del> console.log = originalConsole.log;
<add> console.log = nativeLog;
<ide> }
<ide>
<ide> capture();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> capture();
<ide> <div id='js-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>uncapture();
<add>
<add>if (typeof reusableFunction !== "function") {
<add> (function() { return "reusableFunction is not defined"; })();
<add>} else {
<add> (function() { return logOutput || "console.log never called"; })();
<add>}
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>function reusableFunction() {
<add> console.log("Hi World");
<add>}
<add>reusableFunction();
<ide> ```
<add>
<ide> </section> | 110 |
PHP | PHP | change config param get method | 0073655789b4297ed3667897ccf705c83f210462 | <ide><path>src/Illuminate/Database/Connectors/SqlServerConnector.php
<ide> protected function getDsn(array $config)
<ide> if (in_array('dblib', $this->getAvailableDrivers())) {
<ide> return $this->getDblibDsn($config);
<ide> } elseif (in_array('odbc', $this->getAvailableDrivers())) {
<del> return 'odbc:'.(isset($config('ODBC_DATA_SOURCE_NAME')) ? $config('ODBC_DATA_SOURCE_NAME') : '');
<add> return $this->getOdbcDsn($config);
<ide> } else {
<ide> return $this->getSqlSrvDsn($config);
<ide> }
<ide> }
<ide>
<add> /**
<add> * Get the DSN string for a ODBC connection.
<add> *
<add> * @param array $config
<add> * @return string
<add> */
<add> protected function getOdbcDsn(array $config)
<add> {
<add> if (isset($config['ODBC_DATA_SOURCE_NAME'])) {
<add> return 'odbc:'.$config['ODBC_DATA_SOURCE_NAME'];
<add> } else {
<add> return '';
<add> }
<add> }
<add>
<ide> /**
<ide> * Get the DSN string for a DbLib connection.
<ide> * | 1 |
Text | Text | add badges for airflow docker | 42543c58dcaf488fc233969cb7cad5f49a9fec9f | <ide><path>README.md
<ide> [](https://airflow.readthedocs.io/en/latest/?badge=latest)
<ide> [](http://www.apache.org/licenses/LICENSE-2.0.txt)
<ide> [](https://pypi.org/project/apache-airflow/)
<add>[](https://hub.docker.com/r/apache/airflow)
<add>[](https://hub.docker.com/r/apache/airflow)
<ide>
<ide> [](https://twitter.com/ApacheAirflow)
<ide> [](https://apache-airflow-slack.herokuapp.com/) | 1 |
Text | Text | fix actionview changelog documentation [ci skip] | fc0bbe110eb7c5bbcc4dfcd782348182d89ad692 | <ide><path>actionview/CHANGELOG.md
<ide>
<ide> *Nikolay Shebanov*
<ide>
<del>* Add a `hidden_field` on the `file_field` to avoid raise a error when the only
<add>* Add a `hidden_field` on the `file_field` to avoid raising an error when the only
<ide> input on the form is the `file_field`.
<ide>
<ide> *Mauro George* | 1 |
PHP | PHP | improve some comments | 5cfe7313ccb65485dc5cf2eb6f3bf0512aebf5e1 | <ide><path>src/Illuminate/Queue/Worker.php
<ide> public function runNextJob($connectionName, $queue = null, $delay = 0, $sleep =
<ide>
<ide> $job = $this->getNextJob($connection, $queue);
<ide>
<del> // If we're able to pull a job off of the stack, we will process it and
<del> // then immediately return back out. If there is no job on the queue
<del> // we will "sleep" the worker for the specified number of seconds.
<add> // If we're able to pull a job off of the stack, we will process it and then return
<add> // from this method. If there is no job on the queue, we will "sleep" the worker
<add> // for the specified number of seconds, then keep processing jobs after sleep.
<ide> if (! is_null($job)) {
<ide> return $this->process(
<ide> $this->manager->getName($connectionName), $job, $maxTries, $delay
<ide> public function process($connection, Job $job, $maxTries = 0, $delay = 0)
<ide> try {
<ide> $this->raiseBeforeJobEvent($connection, $job);
<ide>
<del> // First we will fire off the job. Once it is done we will see if it will be
<del> // automatically deleted after processing and if so we'll fire the delete
<del> // method on the job. Otherwise, we will just keep on running our jobs.
<add> // Here we will fire off the job and let it process. We will catch any exceptions so
<add> // they can be reported to the developers logs, etc. Once the job is finished the
<add> // proper events will be fired to let any listeners know this job has finished.
<ide> $job->fire();
<ide>
<ide> $this->raiseAfterJobEvent($connection, $job);
<ide> public function process($connection, Job $job, $maxTries = 0, $delay = 0)
<ide> */
<ide> protected function handleJobException($connection, Job $job, $delay, $e)
<ide> {
<del> // If we catch an exception, we will attempt to release the job back onto
<del> // the queue so it is not lost. This will let is be retried at a later
<del> // time by another listener (or the same one). We will do that here.
<add> // If we catch an exception, we will attempt to release the job back onto the queue
<add> // so it is not lost entirely. This'll let the job be retried at a later time by
<add> // another listener (or this same one). We will re-throw this exception after.
<ide> try {
<ide> $this->raiseExceptionOccurredJobEvent(
<ide> $connection, $job, $e | 1 |
Python | Python | compute seq_len from inputs_embeds | 14e9d2954c3a7256a49a3e581ae25364c76f521e | <ide><path>src/transformers/models/electra/modeling_electra.py
<ide> def forward(
<ide> raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
<ide> elif input_ids is not None:
<ide> input_shape = input_ids.size()
<del> batch_size, seq_length = input_shape
<ide> elif inputs_embeds is not None:
<ide> input_shape = inputs_embeds.size()[:-1]
<ide> else:
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<add> batch_size, seq_length = input_shape
<ide> device = input_ids.device if input_ids is not None else inputs_embeds.device
<ide>
<ide> if attention_mask is None: | 1 |
Text | Text | add version metadata for packages features | 332521e3109451de3de6b208002806e0aef2741b | <ide><path>doc/api/packages.md
<ide> changes:
<ide> - v12.20.0
<ide> pr-url: https://github.com/nodejs/node/pull/34718
<ide> description: Add support for `"exports"` patterns.
<del> - version: v14.6.0
<add> - version:
<add> - v14.6.0
<add> - v12.19.0
<ide> pr-url: https://github.com/nodejs/node/pull/34117
<ide> description: Add package `"imports"` field.
<ide> - version:
<ide> package:
<ide> `"commonjs"` package).
<ide>
<ide> ### `--input-type` flag
<add><!-- YAML
<add>added: v12.0.0
<add>-->
<ide>
<ide> Strings passed in as an argument to `--eval` (or `-e`), or piped to `node` via
<ide> `STDIN`, are treated as [ES modules][] when the `--input-type=module` flag
<ide> absolute subpath of the package such as
<ide> `require('/path/to/node_modules/pkg/subpath.js')` will still load `subpath.js`.
<ide>
<ide> ### Subpath exports
<add><!-- YAML
<add>added: v12.7.0
<add>-->
<ide>
<ide> When using the [`"exports"`][] field, custom subpaths can be defined along
<ide> with the main entry point by treating the main entry point as the
<ide> import submodule from 'es-module-package/private-module.js';
<ide> ```
<ide>
<ide> ### Subpath imports
<add><!--YAML
<add>added:
<add> - v14.6.0
<add> - v12.19.0
<add>-->
<ide>
<ide> In addition to the [`"exports"`][] field, it is possible to define internal
<ide> package import maps that only apply to import specifiers from within the package
<ide> The resolution rules for the imports field are otherwise
<ide> analogous to the exports field.
<ide>
<ide> ### Subpath patterns
<add><!--YAML
<add>added:
<add> - v14.13.0
<add> - v12.19.0
<add>-->
<ide>
<ide> For packages with a small number of exports or imports, we recommend
<ide> explicitly listing each exports subpath entry. But for packages that have
<ide> The benefit of patterns over folder exports is that packages can always be
<ide> imported by consumers without subpath file extensions being necessary.
<ide>
<ide> ### Exports sugar
<add><!--YAML
<add>added: v12.11.0
<add>-->
<ide>
<ide> If the `"."` export is the only export, the [`"exports"`][] field provides sugar
<ide> for this case being the direct [`"exports"`][] field value.
<ide> can be written:
<ide> ```
<ide>
<ide> ### Conditional exports
<add><!--YAML
<add>added:
<add> - v13.2.0
<add> - v12.16.0
<add>changes:
<add> - version:
<add> - v13.7.0
<add> - v12.16.0
<add> pr-url: https://github.com/nodejs/node/pull/31001
<add> description: Unflag conditional exports.
<add>-->
<ide>
<ide> Conditional exports provide a way to map to different paths depending on
<ide> certain conditions. They are supported for both CommonJS and ES module imports.
<ide> the remaining conditions of the parent condition. In this way nested
<ide> conditions behave analogously to nested JavaScript `if` statements.
<ide>
<ide> ### Resolving user conditions
<add><!-- YAML
<add>added:
<add> - v14.9.0
<add> - v12.19.0
<add>-->
<ide>
<ide> When running Node.js, custom user conditions can be added with the
<ide> `--conditions` flag:
<ide> The above definitions may be moved to a dedicated conditions registry in due
<ide> course.
<ide>
<ide> ### Self-referencing a package using its name
<add><!--YAML
<add>added:
<add> - v13.1.0
<add> - v12.16.0
<add>changes:
<add> - version:
<add> - v13.6.0
<add> - v12.16.0
<add> pr-url: https://github.com/nodejs/node/pull/31002
<add> description: Unflag self-referencing a package using its name.
<add>-->
<ide>
<ide> Within a package, the values defined in the package’s
<ide> `package.json` [`"exports"`][] field can be referenced via the package’s name. | 1 |
Text | Text | correct broken links in docs | 14eebab94ad64860d2f1b4ff53f0f5d796ac4ad3 | <ide><path>laravel/documentation/contrib/github.md
<ide> In order to keep the codebase clean, stable and at high quality, even with so ma
<ide>
<ide> *Further Reading*
<ide>
<del> - [Contributing to Laravel via Command-Line](docs/contrib/command-line)
<del> - [Contributing to Laravel using TortoiseGit](docs/contrib/tortoisegit)
<add> - [Contributing to Laravel via Command-Line](#contrib/command-line)
<add> - [Contributing to Laravel using TortoiseGit](#contrib/tortoisegit) | 1 |
Python | Python | set version to v3.0.0a32 | 70b9de8e589776ba90c000addfa24dffe5915b33 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy-nightly"
<del>__version__ = "3.0.0a31"
<add>__version__ = "3.0.0a32"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Go | Go | fix racy events test | 202709d178a24bcbfac223f0bcd9c4eda669e928 | <ide><path>integration-cli/docker_cli_events_test.go
<ide> func TestEventsFilters(t *testing.T) {
<ide>
<ide> // make sure we at least got 2 start events
<ide> count := strings.Count(out, "start")
<del> if count != 2 {
<add> if count < 2 {
<ide> t.Fatalf("should have had 2 start events but had %d, out: %s", count, out)
<ide> }
<ide> | 1 |
Text | Text | add fezto as a premium sponsor | e5fb9af0eaffde683fa0af3987085f86cf0d2640 | <ide><path>docs/index.md
<ide> continued development by **[signing up for a paid plan][funding]**.
<ide> <ul class="premium-promo promo">
<ide> <li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
<ide> <li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
<del> <li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
<del> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<ide> <li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
<ide> <li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
<ide> <li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
<ide> <li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
<add> <li><a href="https://www.fezto.xyz/?utm_source=DjangoRESTFramework" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/fezto.png)">FEZTO</a></li>
<ide> </ul>
<ide> <div style="clear: both; padding-bottom: 20px;"></div>
<ide>
<del>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), and [CryptAPI](https://cryptapi.io).*
<add>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).*
<ide>
<ide> ---
<ide> | 1 |
Javascript | Javascript | fix typo in enumerable docs | b03a2da383f375ee6766df46900dd440a83165ce | <ide><path>packages/sproutcore-runtime/lib/mixins/enumerable.js
<ide> SC.Enumerable = SC.Mixin.create( /** @lends SC.Enumerable */ {
<ide> to nextObject for the current iteration. This is a useful way to
<ide> manage iteration if you are tracing a linked list, for example.
<ide>
<del> Finally the context paramter will always contain a hash you can use as
<add> Finally the context parameter will always contain a hash you can use as
<ide> a "scratchpad" to maintain any other state you need in order to iterate
<ide> properly. The context object is reused and is not reset between
<ide> iterations so make sure you setup the context with a fresh state whenever | 1 |
PHP | PHP | handle ajax requests in requirepassword middleware | 93eb836c4d0b5d03cc789de98acc6e03aa4aca25 | <ide><path>src/Illuminate/Auth/Middleware/RequirePassword.php
<ide> public function __construct(ResponseFactory $responseFactory, UrlGenerator $urlG
<ide> public function handle($request, Closure $next, $redirectToRoute = null)
<ide> {
<ide> if ($this->shouldConfirmPassword($request)) {
<add> if ($request->expectsJson()) {
<add> abort(423, 'Password confirmation required.');
<add> }
<add>
<ide> return $this->responseFactory->redirectGuest(
<ide> $this->urlGenerator->route($redirectToRoute ?? 'password.confirm')
<ide> ); | 1 |
PHP | PHP | fix failing tests for utility classes in windows | 33a8bac40bf991e03b14c3a2ac26570897580c3f | <ide><path>tests/TestCase/Utility/DebuggerTest.php
<ide> public function testDebugInfo() {
<ide> 'inner' => object(Cake\Test\TestCase\Utility\DebuggableThing) {
<ide>
<ide> [maximum depth reached]
<del>
<add>
<ide> }
<ide>
<ide> }
<ide><path>tests/TestCase/Utility/FolderTest.php
<ide> public function testFolderTree() {
<ide> CAKE . 'Config',
<ide> ),
<ide> array(
<del> CAKE . 'Config/config.php',
<add> CAKE . 'Config' . DS . 'config.php',
<ide> )
<ide> );
<ide>
<ide> public function testFindRecursive() {
<ide> $Folder = new Folder(CAKE);
<ide> $result = $Folder->findRecursive('(config|paths)\.php');
<ide> $expected = array(
<del> CAKE . 'Config/config.php'
<add> CAKE . 'Config'. DS . 'config.php'
<ide> );
<ide> $this->assertSame(array(), array_diff($expected, $result));
<ide> $this->assertSame(array(), array_diff($expected, $result));
<ide>
<ide> $result = $Folder->findRecursive('(config|woot)\.php', true);
<ide> $expected = array(
<del> CAKE . 'Config/config.php'
<add> CAKE . 'Config'. DS . 'config.php'
<ide> );
<ide> $this->assertSame($expected, $result);
<ide>
<del> $path = TMP . 'tests/';
<add> $path = TMP . 'tests' . DS;
<ide> $Folder = new Folder($path, true);
<ide> $Folder->create($path . 'sessions');
<ide> $Folder->create($path . 'testme');
<ide> public function testFindRecursive() {
<ide>
<ide> $result = $Folder->findRecursive('(paths|my)\.php');
<ide> $expected = array(
<del> $path . 'testme/my.php',
<del> $path . 'testme/paths.php'
<add> $path . 'testme'. DS . 'my.php',
<add> $path . 'testme'. DS . 'paths.php'
<ide> );
<ide> $this->assertSame(sort($expected), sort($result));
<ide>
<ide> $result = $Folder->findRecursive('(paths|my)\.php', true);
<ide> $expected = array(
<del> $path . 'testme/my.php',
<del> $path . 'testme/paths.php'
<add> $path . 'testme'. DS . 'my.php',
<add> $path . 'testme'. DS . 'paths.php'
<ide> );
<ide> $this->assertSame($expected, $result);
<ide> }
<ide> public function testDirSize() {
<ide> * @return void
<ide> */
<ide> public function testReset() {
<del> $path = TMP . 'tests/folder_delete_test';
<add> $path = TMP . 'tests' . DS . 'folder_delete_test';
<ide> mkdir($path, 0777, true);
<ide> $folder = $path . DS . 'sub';
<ide> mkdir($folder);
<ide> public function testReset() {
<ide> * @return void
<ide> */
<ide> public function testDelete() {
<del> $path = TMP . 'tests/folder_delete_test';
<add> $path = TMP . 'tests'. DS . 'folder_delete_test';
<ide> mkdir($path, 0777, true);
<ide> touch($path . DS . 'file_1');
<ide> mkdir($path . DS . 'level_1_1'); | 2 |
Python | Python | simplify logic from | e8591afa2aa4cf16c40989ffad757b6afcdefb36 | <ide><path>numpy/distutils/fcompiler/gnu.py
<ide> def get_library_dirs(self):
<ide> opt.append(d2)
<ide> opt.append(d)
<ide> # For Macports / Linux, libgfortran and libgcc are not co-located
<del> if sys.platform[:5] == 'linux' or sys.platform == 'darwin':
<del> lib_gfortran_dir = self.get_libgfortran_dir()
<del> if lib_gfortran_dir:
<del> opt.append(lib_gfortran_dir)
<add> lib_gfortran_dir = self.get_libgfortran_dir()
<add> if lib_gfortran_dir:
<add> opt.append(lib_gfortran_dir)
<ide> return opt
<ide>
<ide> def get_libraries(self):
<ide> def get_library_dirs(self):
<ide> if os.path.exists(os.path.join(mingwdir, "libmingwex.a")):
<ide> opt.append(mingwdir)
<ide> # For Macports / Linux, libgfortran and libgcc are not co-located
<del> if sys.platform[:5] == 'linux' or sys.platform == 'darwin':
<del> lib_gfortran_dir = self.get_libgfortran_dir()
<del> if lib_gfortran_dir:
<del> opt.append(lib_gfortran_dir)
<add> lib_gfortran_dir = self.get_libgfortran_dir()
<add> if lib_gfortran_dir:
<add> opt.append(lib_gfortran_dir)
<ide> return opt
<ide>
<ide> def get_libraries(self): | 1 |
Javascript | Javascript | add reactube to showcase | 8ca3a0c91c7ad6e0d0dd87c83c0550fe60e8d337 | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/us/app/reactto36/id989009293?mt=8',
<ide> author: 'Jonathan Solichin',
<ide> },
<add> {
<add> name: 'ReacTube',
<add> icon: 'https://raw.githubusercontent.com/alexkendall/ReacTube/master/images/RTIconAlternative.png?token=AH3CygkR6xhSOsgO7YZ3kDNcMZ-y-3Qgks5XYuPwwA%3D%3D',
<add> link: 'https://play.google.com/store/apps/details?id=com.reactube',
<add> author: 'Icon Interactive',
<add> },
<ide> {
<ide> name: 'Reading',
<ide> icon: 'http://7xr0xq.com1.z0.glb.clouddn.com/about_logo.png', | 1 |
Go | Go | clarify a message | aab2450e25b397d38cdcb5e173ef1121283196c2 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) closeTransaction() error {
<ide> }
<ide>
<ide> func determineDriverCapabilities(version string) error {
<del> /*
<del> * Driver version 4.27.0 and greater support deferred activation
<del> * feature.
<del> */
<add> // Kernel driver version >= 4.27.0 support deferred removal
<ide>
<del> logrus.Debugf("devicemapper: driver version is %s", version)
<add> logrus.Debugf("devicemapper: kernel dm driver version is %s", version)
<ide>
<ide> versionSplit := strings.Split(version, ".")
<ide> major, err := strconv.Atoi(versionSplit[0]) | 1 |
Ruby | Ruby | remove stray quotation mark | 16b69317fe926acaa742f520b13340fb4f117e7d | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_non_executables bin
<ide> ["Non-executables were installed to \"#{bin}\".",
<ide> <<-EOS.undent
<ide> The offending files are:
<del> #{non_exes}"
<add> #{non_exes}
<ide> EOS
<ide> ]
<ide> end | 1 |
PHP | PHP | fix seejsonstructure for empty response | 6ea6e22e77bb66446de18b0ed5b22141a75ba204 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php
<ide> public function seeJsonStructure(array $structure = null, $responseData = null)
<ide> return $this->seeJson();
<ide> }
<ide>
<del> if (! $responseData) {
<add> if (is_null($responseData)) {
<ide> $responseData = $this->decodeResponseJson();
<ide> }
<ide> | 1 |
PHP | PHP | apply suggestions from code review | b1bcaca8cd827279d7964d57accd6f4972f5923a | <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> protected function getErrorHandler(): ErrorHandler
<ide> {
<ide> if ($this->errorHandler === null) {
<ide> deprecationWarning(
<del> 'Using an `errorHandler` is deprecated. You should migate to the `ExceptionTrap` sub-system instead.'
<add> 'Using an `ErrorHandler` is deprecated. You should migate to the `ExceptionTrap` sub-system instead.'
<ide> );
<ide> /** @var class-string<\Cake\Error\ErrorHandler> $className */
<ide> $className = App::className('ErrorHandler', 'Error'); | 1 |
Text | Text | add contributor agreement for @ursachec | cdd4b3d05c511372d888b04c70d0a985bb307b17 | <ide><path>.github/contributors/ursachec.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | ------------------------- |
<add>| Name | Claudiu-Vlad Ursache |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2018-02-04 |
<add>| GitHub username | ursachec |
<add>| Website (optional) | https://www.cvursache.com | | 1 |
Go | Go | fix flaky testsaveloadparents | 0c0198a5e671928b67db6a3be35f1a419f633af4 | <ide><path>integration-cli/docker_cli_save_load_test.go
<ide> func (s *DockerSuite) TestSaveLoadParents(c *check.C) {
<ide> out, _ = dockerCmd(c, "commit", cleanedContainerID)
<ide> imageID := strings.TrimSpace(out)
<ide>
<del> dockerCmd(c, "rm", cleanedContainerID)
<add> dockerCmd(c, "rm", "-f", cleanedContainerID)
<ide> return imageID
<ide> }
<ide> | 1 |
Ruby | Ruby | add tests for `caskunreadableerror | 785ec4ef57677f1b2cf6dc171a5b524faaaaafb4 | <ide><path>Library/Homebrew/test/cask/cask_loader/from__path_loader_spec.rb
<add>describe Hbc::CaskLoader::FromPathLoader do
<add> describe "#load" do
<add> context "when the file does not contain a cask" do
<add> let(:path) {
<add> (mktmpdir/"cask.rb").tap do |path|
<add> path.write <<~RUBY
<add> true
<add> RUBY
<add> end
<add> }
<add>
<add> it "raises an error" do
<add> expect {
<add> described_class.new(path).load
<add> }.to raise_error(Hbc::CaskUnreadableError, /does not contain a cask/)
<add> end
<add> end
<add>
<add> context "when the file calls a non-existent method" do
<add> let(:path) {
<add> (mktmpdir/"cask.rb").tap do |path|
<add> path.write <<~RUBY
<add> this_method_does_not_exist
<add> RUBY
<add> end
<add> }
<add>
<add> it "raises an error" do
<add> expect {
<add> described_class.new(path).load
<add> }.to raise_error(Hbc::CaskUnreadableError, /undefined local variable or method/)
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/cask/dsl_spec.rb
<ide> let(:token) { "invalid/invalid-header-format" }
<ide>
<ide> it "raises an error" do
<del> expect { cask }.to raise_error(SyntaxError)
<add> expect { cask }.to raise_error(Hbc::CaskUnreadableError)
<ide> end
<ide> end
<ide> | 2 |
Javascript | Javascript | add some decent (non-trivial) hull tests | 317740be1b9170b6cd2bed970e6f37753bca81ff | <ide><path>test/geom/hull-test.js
<ide> suite.addBatch({
<ide> },
<ide> "handles overlapping upper and lower hulls": function(h) {
<ide> assert.deepEqual(h([[0, -10], [0, 10], [0, 0], [10, 0], [-10, 0]]), [[10, 0], [0, -10], [-10, 0], [0, 10]]);
<add> },
<add>
<add> // Cases below taken from http://uva.onlinejudge.org/external/6/681.html
<add>
<add> "for a complex 15-point polygon": function(h) {
<add> var poly = [[30,30], [50,60], [60,20], [70,45], [86,39], [112,60], [200,113], [250,50], [300,200], [130,240], [76,150], [47,76], [36,40], [33,35], [30,30]];
<add> var expectedHull = [[300,200], [250,50], [60,20], [30,30], [47,76], [76,150], [130,240]];
<add> assert.deepEqual(h(poly), expectedHull);
<add> },
<add> "for a complex 12-point polygon": function(h) {
<add> var poly = [[50,60], [60,20], [70,45], [100,70], [125,90], [200,113], [250,140], [180,170], [105,140], [79,140], [60,85], [50,60]];
<add> var expectedHull = [[250,140], [60,20], [50,60], [79,140], [180,170]];
<add> assert.deepEqual(h(poly), expectedHull);
<add> },
<add> "for a complex 6-point polygon": function(h) {
<add> var poly = [[60,20], [250,140], [180,170], [79,140], [50,60], [60,20]];
<add> var expectedHull = [[250,140], [60,20], [50,60], [79,140], [180,170]];
<add> assert.deepEqual(h(poly), expectedHull);
<ide> }
<ide> },
<ide> "the hull layout with custom accessors": { | 1 |
Javascript | Javascript | fix buggy test around dst | 3891698e424f38f2bd82b56ac9f479f553f7250f | <ide><path>src/locale/bg-x.js
<add>import moment from '../moment';
<add>
<add>export default moment.defineLocale('bg-x', {
<add> parentLocale: 'bg'
<add>});
<ide><path>src/test/moment/zone_switching.js
<ide> test('utc to local, keepLocalTime = false', function (assert) {
<ide> });
<ide>
<ide> test('zone to local, keepLocalTime = true', function (assert) {
<del> test.expectedDeprecations('moment().zone');
<ide> // Don't test near the spring DST transition
<ide> if (isNearSpringDST()) {
<ide> expect(0);
<ide> return;
<ide> }
<ide>
<add> test.expectedDeprecations('moment().zone');
<add>
<ide> var m = moment(),
<ide> fmt = 'YYYY-DD-MM HH:mm:ss',
<ide> z; | 2 |
Text | Text | add links for zlib convenience methods | 55c42bc6e5602e5a47fb774009cfe9289cb88e71 | <ide><path>doc/api/zlib.md
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Compress a Buffer or string with Deflate.
<add>Compress a [Buffer][] or string with [Deflate][].
<ide>
<ide> ### zlib.deflateRaw(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Compress a Buffer or string with DeflateRaw.
<add>Compress a [Buffer][] or string with [DeflateRaw][].
<ide>
<ide> ### zlib.gunzip(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Decompress a Buffer or string with Gunzip.
<add>Decompress a [Buffer][] or string with [Gunzip][].
<ide>
<ide> ### zlib.gzip(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Compress a Buffer or string with Gzip.
<add>Compress a [Buffer][] or string with [Gzip][].
<ide>
<ide> ### zlib.inflate(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Decompress a Buffer or string with Inflate.
<add>Decompress a [Buffer][] or string with [Inflate][].
<ide>
<ide> ### zlib.inflateRaw(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Decompress a Buffer or string with InflateRaw.
<add>Decompress a [Buffer][] or string with [InflateRaw][].
<ide>
<ide> ### zlib.unzip(buf[, options], callback)
<ide> <!-- YAML
<ide> added: v0.6.0
<ide> added: v0.11.12
<ide> -->
<ide>
<del>Decompress a Buffer or string with Unzip.
<add>Decompress a [Buffer][] or string with [Unzip][].
<ide>
<ide> [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
<ide> [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 | 1 |
Ruby | Ruby | remove redundant uniq | 78a18392e15c3de1c70b44e285d1742687624dd1 | <ide><path>activerecord/lib/active_record/association_preload.rb
<ide> def preload_belongs_to_association(records, reflection, preload_options={})
<ide> table_name = klass.quoted_table_name
<ide> primary_key = klass.primary_key
<ide> column_type = klass.columns.detect{|c| c.name == primary_key}.type
<del> ids = id_map.keys.uniq.map do |id|
<add> ids = id_map.keys.map do |id|
<ide> if column_type == :integer
<ide> id.to_i
<ide> elsif column_type == :float | 1 |
PHP | PHP | move stub helper into a separate file | 589ff7b1c0be905ba02c77f47b263eaf7db732c5 | <ide><path>src/TestSuite/Stub/ConsoleOutput.php
<add><?php
<add>/**
<add> * CakePHP : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP Project
<add> * @since 3.1.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\TestSuite\Stub;
<add>
<add>use Cake\Console\ConsoleOutput as ConsoleOutputBase;
<add>
<add>/**
<add> * StubOutput makes testing shell commands/shell helpers easier.
<add> */
<add>class ConsoleOutput extends ConsoleOutputBase
<add>{
<add> protected $_out = [];
<add>
<add> public function write($message, $newlines = 1)
<add> {
<add> $this->_out[] = $message;
<add> }
<add>
<add> public function messages()
<add> {
<add> return $this->_out;
<add> }
<add>}
<ide><path>tests/TestCase/Shell/Helper/TableHelperTest.php
<ide> namespace Cake\Test\TestCase\Shell\Helper;
<ide>
<ide> use Cake\Console\ConsoleIo;
<del>use Cake\Console\ConsoleOutput;
<ide> use Cake\Shell\Helper\TableHelper;
<add>use Cake\TestSuite\Stub\ConsoleOutput;
<ide> use Cake\TestSuite\TestCase;
<ide>
<del>/**
<del> * StubOutput makes testing easier.
<del> */
<del>class StubOutput extends ConsoleOutput
<del>{
<del> protected $_out = [];
<del>
<del> public function write($message, $newlines = 1)
<del> {
<del> $this->_out[] = $message;
<del> }
<del>
<del> public function messages()
<del> {
<del> return $this->_out;
<del> }
<del>}
<del>
<ide> /**
<ide> * TableHelper test.
<ide> */
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<ide>
<del> $this->stub = new StubOutput();
<add> $this->stub = new ConsoleOutput();
<ide> $this->io = new ConsoleIo($this->stub);
<ide> $this->helper = new TableHelper($this->io);
<ide> }
<ide> public function testOutputUtf8()
<ide> '| Longer thing | longerish | Longest Value |',
<ide> '+--------------+-----------+---------------+',
<ide> ];
<del> debug($this->stub->messages());
<ide> $this->assertEquals($expected, $this->stub->messages());
<ide> }
<ide> } | 2 |
Text | Text | update changelog for v15.5.1-15.5.4 | 0549c4506f32d19a9ebd1d1d5db5aac83d3e5a29 | <ide><path>CHANGELOG.md
<del>## 15.5.0 (April 7, 2017)
<add>## 15.5.4 (April 11, 2017)
<add>
<add>### React Addons
<add>* **Critical Bugfix:** Update the version of `prop-types` to fix critical bug. ([@gaearon](https://github.com/gaearon) in [#545c87f](https://github.com/facebook/react/commit/545c87fdc348f82eb0c3830bef715ed180785390))
<add>
<add>### React Test Renderer
<add>* Fix compatibility with Enzyme by exposing `batchedUpdates` on shallow renderer. ([@gaearon](https://github.com/gaearon) in [#9382](https://github.com/facebook/react/commit/69933e25c37cf5453a9ef132177241203ee8d2fd).
<add>
<add>
<add>## 15.5.3 (April 7, 2017)
<add>
<add>**Note: this release has a critical issue and was deprecated. Please update to 15.5.4 or higher.**
<add>
<add>### React Addons
<add>* Fix `react-addons-create-fragment` package to export correct thing. ([@gaearon](https://github.com/gaearon) in [#9385](https://github.com/facebook/react/pull/9383))
<add>
<add>## 15.5.2 (April 7, 2017)
<add>
<add>### React Addons
<add>* Fix the production single-file builds to not include the development code. ([@gaearon](https://github.com/gaearon) in [#9385](https://github.com/facebook/react/pull/9383))
<add>* Apply better minification to production single-file builds. ([@gaearon](https://github.com/gaearon) in [#9385](https://github.com/facebook/react/pull/9383))
<add>* Add missing and remove unnecessary dependencies to packages. ([@gaearon](https://github.com/gaearon) in [#9385](https://github.com/facebook/react/pull/9383))
<add>
<add>## 15.5.1 (April 7, 2017)
<add>
<add>**Note: this release has a critical issue and was deprecated. Please update to 15.5.4 or higher.**
<ide>
<ide> ### React
<add>* Fix erroneous PropTypes access warning. ([@acdlite](https://github.com/acdlite) in ([ec97ebb](https://github.com/facebook/react/commit/ec97ebbe7f15b58ae2f1323df39d06f119873344))
<add>
<add>## 15.5.0 (April 7, 2017)
<add>
<add>**Note: this release has a critical issue and was deprecated. Please update to 15.5.4 or higher.**
<ide>
<add>### React
<ide> * Added a deprecation warning for `React.createClass`. Points users to create-react-class instead. ([@acdlite](https://github.com/acdlite) in [d9a4fa4](https://github.com/facebook/react/commit/d9a4fa4f51c6da895e1655f32255cf72c0fe620e))
<ide> * Added a deprecation warning for `React.PropTypes`. Points users to prop-types instead. ([@acdlite](https://github.com/acdlite) in [043845c](https://github.com/facebook/react/commit/043845ce75ea0812286bbbd9d34994bb7e01eb28))
<ide> * Fixed an issue when using `ReactDOM` together with `ReactDOMServer`. ([@wacii](https://github.com/wacii) in [#9005](https://github.com/facebook/react/pull/9005))
<ide> * Added component stack info to invalid element type warning. ([@n3tr](https://github.com/n3tr) in [#8495](https://github.com/facebook/react/pull/8495))
<ide>
<ide> ### React DOM
<del>
<ide> * Fixed Chrome bug when backspacing in number inputs. ([@nhunzaker](https://github.com/nhunzaker) in [#7359](https://github.com/facebook/react/pull/7359))
<ide> * Added `react-dom/test-utils`, which exports the React Test Utils. ([@bvaughn](https://github.com/bvaughn))
<ide>
<ide> ### React Test Renderer
<del>
<ide> * Fixed bug where `componentWillUnmount` was not called for children. ([@gre](https://github.com/gre) in [#8512](https://github.com/facebook/react/pull/8512))
<ide> * Added `react-test-renderer/shallow`, which exports the shallow renderer. ([@bvaughn](https://github.com/bvaughn))
<ide>
<ide> ### React Addons
<del>
<ide> * Last release for addons; they will no longer be actively maintained.
<ide> * Removed `peerDependencies` so that addons continue to work indefinitely. ([@acdlite](https://github.com/acdlite) and [@bvaughn](https://github.com/bvaughn) in [8a06cd7](https://github.com/facebook/react/commit/8a06cd7a786822fce229197cac8125a551e8abfa) and [67a8db3](https://github.com/facebook/react/commit/67a8db3650d724a51e70be130e9008806402678a))
<ide> * Updated to remove references to `React.createClass` and `React.PropTypes` ([@acdlite](https://github.com/acdlite) in [12a96b9](https://github.com/facebook/react/commit/12a96b94823d6b6de6b1ac13bd576864abd50175))
<ide> ## 15.4.2 (January 6, 2017)
<ide>
<ide> ### React
<del>
<ide> * Fixed build issues with the Brunch bundler. ([@gaearon](https://github.com/gaearon) in [#8686](https://github.com/facebook/react/pull/8686))
<ide> * Improved error messages for invalid element types. ([@spicyj](https://github.com/spicyj) in [#8612](https://github.com/facebook/react/pull/8612))
<ide> * Removed a warning about `getInitialState` when `this.state` is set. ([@bvaughn](https://github.com/bvaughn) in [#8594](https://github.com/facebook/react/pull/8594))
<ide> * Removed some dead code. ([@diegomura](https://github.com/diegomura) in [#8050](https://github.com/facebook/react/pull/8050), [@dfrownfelter](https://github.com/dfrownfelter) in [#8597](https://github.com/facebook/react/pull/8597))
<ide>
<ide> ### React DOM
<del>
<ide> * Fixed a decimal point issue on uncontrolled number inputs. ([@nhunzaker](https://github.com/nhunzaker) in [#7750](https://github.com/facebook/react/pull/7750))
<ide> * Fixed rendering of textarea placeholder in IE11. ([@aweary](https://github.com/aweary) in [#8020](https://github.com/facebook/react/pull/8020))
<ide> * Worked around a script engine bug in IE9. ([@eoin](https://github.com/eoin) in [#8018](https://github.com/facebook/react/pull/8018))
<ide>
<ide> ### React Addons
<del>
<ide> * Fixed build issues in RequireJS and SystemJS environments. ([@gaearon](https://github.com/gaearon) in [#8686](https://github.com/facebook/react/pull/8686))
<ide> * Added missing package dependencies. ([@kweiberth](https://github.com/kweiberth) in [#8467](https://github.com/facebook/react/pull/8467))
<ide> | 1 |
Javascript | Javascript | add a semi-colon at the end of the umd template | 3c4284f01176a3d8bb88c133fd9ef693c5117a7f | <ide><path>lib/UmdMainTemplatePlugin.js
<ide> UmdMainTemplatePlugin.prototype.apply = function(mainTemplate) {
<ide> " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
<ide> " }\n"
<ide> ) +
<del> "})(this, function(" + externalsArguments + ") {\nreturn ", "webpack/universalModuleDefinition"), source, "\n})\n");
<add> "})(this, function(" + externalsArguments + ") {\nreturn ", "webpack/universalModuleDefinition"), source, "\n});\n");
<ide> }.bind(this));
<ide> mainTemplate.plugin("global-hash", function(chunk) {
<ide> if(Template.REGEXP_HASH.test([].concat(this.name || "").join("|")))
<ide> UmdMainTemplatePlugin.prototype.apply = function(mainTemplate) {
<ide> hash.update("umd");
<ide> hash.update(this.name + "");
<ide> }.bind(this));
<del>};
<ide>\ No newline at end of file
<add>}; | 1 |
PHP | PHP | raise an error for pages < 1. | 825b454b65b1277d9c05742bb3e2f4eb4a7da368 | <ide><path>src/Database/Query.php
<ide> public function orHaving($conditions, $types = [])
<ide> * @param int|null $limit The number of rows you want in the page. If null
<ide> * the current limit clause will be used.
<ide> * @return $this
<add> * @throws \InvalidArgumentException If page number < 1.
<ide> */
<ide> public function page($num, $limit = null)
<ide> {
<add> if ($num < 1) {
<add> $msg = 'Pages should start at 1.';
<add> throw new InvalidArgumentException($msg);
<add> }
<ide> if ($limit !== null) {
<ide> $this->limit($limit);
<ide> }
<ide><path>src/Datasource/QueryInterface.php
<ide> public function order($fields, $overwrite = false);
<ide> * @param int|null $limit The number of rows you want in the page. If null
<ide> * the current limit clause will be used.
<ide> * @return $this
<add> * @throws \InvalidArgumentException If page number < 1.
<ide> */
<ide> public function page($num, $limit = null);
<ide>
<ide><path>tests/TestCase/Database/QueryTest.php
<ide> public function testSelectOffset()
<ide> $this->assertTrue($dirty);
<ide> }
<ide>
<add> /**
<add> * Test Pages number.
<add> *
<add> * @expectedException \InvalidArgumentException
<add> * @expectedExceptionMessage Pages should start at 1.
<add> * @return void
<add> */
<add> public function testPageShouldStartAtOne()
<add> {
<add> $this->loadFixtures('Comments');
<add> $query = new Query($this->connection);
<add> $result = $query->from('comments')
<add> ->page(0);
<add> }
<add>
<ide> /**
<ide> * Test selecting rows using the page() method.
<ide> * | 3 |
Javascript | Javascript | add size prop | 63d15af18d1f09db16aa4dbd5ed949b4307f37dd | <ide><path>Examples/UIExplorer/js/ActivityIndicatorExample.js
<ide> exports.examples = [
<ide> return (
<ide> <ActivityIndicator
<ide> style={[styles.centering, styles.gray]}
<del> color="white"
<ide> size="large"
<add> color="white"
<ide> />
<ide> );
<ide> }
<ide> exports.examples = [
<ide> );
<ide> }
<ide> },
<add> {
<add> platform: 'android',
<add> title: 'Custom size (size: 75)',
<add> render() {
<add> return (
<add> <ActivityIndicator
<add> style={styles.centering}
<add> size={75}
<add> />
<add> );
<add> }
<add> },
<ide> ];
<ide>
<add>
<ide> const styles = StyleSheet.create({
<ide> centering: {
<ide> alignItems: 'center',
<ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<ide> const GRAY = '#999999';
<ide>
<add>type IndicatorSize = number | 'small' | 'large';
<add>
<add>type DefaultProps = {
<add> animating: boolean;
<add> color: any;
<add> hidesWhenStopped: boolean;
<add> size: IndicatorSize;
<add>}
<add>
<ide> /**
<ide> * Displays a circular loading indicator.
<ide> */
<ide> const ActivityIndicator = React.createClass({
<ide> */
<ide> color: ColorPropType,
<ide> /**
<del> * Size of the indicator. Small has a height of 20, large has a height of 36.
<del> * Other sizes can be obtained using a scale transform.
<add> * Size of the indicator (default is 'small').
<add> * Passing a number to the size prop is only supported on Android.
<ide> */
<del> size: PropTypes.oneOf([
<del> 'small',
<del> 'large',
<add> size: PropTypes.oneOfType([
<add> PropTypes.oneOf([ 'small', 'large' ]),
<add> PropTypes.number,
<ide> ]),
<ide> /**
<ide> * Whether the indicator should hide when not animating (true by default).
<ide> const ActivityIndicator = React.createClass({
<ide> hidesWhenStopped: PropTypes.bool,
<ide> },
<ide>
<del> getDefaultProps() {
<add> getDefaultProps(): DefaultProps {
<ide> return {
<ide> animating: true,
<ide> color: Platform.OS === 'ios' ? GRAY : undefined,
<ide> const ActivityIndicator = React.createClass({
<ide> render() {
<ide> const {onLayout, style, ...props} = this.props;
<ide> let sizeStyle;
<add>
<ide> switch (props.size) {
<ide> case 'small':
<ide> sizeStyle = styles.sizeSmall;
<ide> break;
<ide> case 'large':
<ide> sizeStyle = styles.sizeLarge;
<ide> break;
<add> default:
<add> sizeStyle = {height: props.size, width: props.size};
<add> break;
<ide> }
<add>
<ide> return (
<ide> <View
<ide> onLayout={onLayout} | 2 |
Python | Python | remove useless pass | ad42d88fb2cda12a21c4fb6f002f425f233d1fe3 | <ide><path>flask/cli.py
<ide> def list_commands(self, ctx):
<ide> # However, we will not do so silently because that would confuse
<ide> # users.
<ide> traceback.print_exc()
<del> pass
<ide> return sorted(rv)
<ide>
<ide> def main(self, *args, **kwargs): | 1 |
Ruby | Ruby | expose role/shard on pool/connection | 061b527d79020fd8bc9cb163a88a88dbedfe3d4c | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_handler.rb
<ide> def connection_pool_list(role = ActiveRecord::Base.current_role)
<ide> def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard)
<ide> owner_name = StringConnectionOwner.new(config.to_s) if config.is_a?(Symbol)
<ide>
<del> pool_config = resolve_pool_config(config, owner_name)
<add> pool_config = resolve_pool_config(config, owner_name, role, shard)
<ide> db_config = pool_config.db_config
<ide>
<ide> # Protects the connection named `ActiveRecord::Base` from being removed
<ide> def get_pool_manager(owner)
<ide> # pool_config.db_config.configuration_hash
<ide> # # => { host: "localhost", database: "foo", adapter: "sqlite3" }
<ide> #
<del> def resolve_pool_config(config, owner_name)
<add> def resolve_pool_config(config, owner_name, role, shard)
<ide> db_config = Base.configurations.resolve(config)
<ide>
<ide> raise(AdapterNotSpecified, "database configuration does not specify adapter") unless db_config.adapter
<ide> def resolve_pool_config(config, owner_name)
<ide> raise AdapterNotFound, "database configuration specifies nonexistent #{db_config.adapter} adapter"
<ide> end
<ide>
<del> ConnectionAdapters::PoolConfig.new(owner_name, db_config)
<add> ConnectionAdapters::PoolConfig.new(owner_name, db_config, role, shard)
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> class ConnectionPool
<ide> include ConnectionAdapters::AbstractPool
<ide>
<ide> attr_accessor :automatic_reconnect, :checkout_timeout
<del> attr_reader :db_config, :size, :reaper, :pool_config, :connection_klass, :async_executor
<add> attr_reader :db_config, :size, :reaper, :pool_config, :connection_klass, :async_executor, :role, :shard
<ide>
<ide> delegate :schema_cache, :schema_cache=, to: :pool_config
<ide>
<ide> def initialize(pool_config)
<ide> @pool_config = pool_config
<ide> @db_config = pool_config.db_config
<ide> @connection_klass = pool_config.connection_klass
<add> @role = pool_config.role
<add> @shard = pool_config.shard
<ide>
<ide> @checkout_timeout = db_config.checkout_timeout
<ide> @idle_timeout = db_config.idle_timeout
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def connection_klass # :nodoc:
<ide> @pool.connection_klass
<ide> end
<ide>
<add> # The role (ie :writing) for the current connection. In a
<add> # non-multi role application, `:writing` is returned.
<add> def role
<add> @pool.role
<add> end
<add>
<add> # The shard (ie :default) for the current connection. In
<add> # a non-sharded application, `:default` is returned.
<add> def shard
<add> @pool.shard
<add> end
<add>
<ide> def schema_cache
<ide> @pool.get_schema_cache(self)
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/pool_config.rb
<ide> module ConnectionAdapters
<ide> class PoolConfig # :nodoc:
<ide> include Mutex_m
<ide>
<del> attr_reader :db_config, :connection_klass
<add> attr_reader :db_config, :connection_klass, :role, :shard
<ide> attr_accessor :schema_cache
<ide>
<ide> INSTANCES = ObjectSpace::WeakMap.new
<ide> def discard_pools!
<ide> end
<ide> end
<ide>
<del> def initialize(connection_klass, db_config)
<add> def initialize(connection_klass, db_config, role, shard)
<ide> super()
<ide> @connection_klass = connection_klass
<ide> @db_config = db_config
<add> @role = role
<add> @shard = shard
<ide> @pool = nil
<ide> INSTANCES[self] = self
<ide> end
<ide><path>activerecord/test/cases/connection_adapters/adapter_leasing_test.rb
<ide> def test_expire_mutates_in_use
<ide>
<ide> def test_close
<ide> db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("test", "primary", {})
<del> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config)
<add> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :writing, :default)
<ide> pool = Pool.new(pool_config)
<ide> pool.insert_connection_for_test! @adapter
<ide> @adapter.pool = pool
<ide><path>activerecord/test/cases/connection_pool_test.rb
<ide> def setup
<ide>
<ide> # Keep a duplicate pool so we do not bother others
<ide> @db_config = ActiveRecord::Base.connection_pool.db_config
<del> @pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, @db_config)
<add> @pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, @db_config, :writing, :default)
<ide> @pool = ConnectionPool.new(@pool_config)
<ide>
<ide> if in_memory_db?
<ide> def test_idle_timeout_configuration
<ide> config = @db_config.configuration_hash.merge(idle_timeout: "0.02")
<ide> db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.name, config)
<ide>
<del> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config)
<add> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :writing, :default)
<ide> @pool = ConnectionPool.new(pool_config)
<ide> idle_conn = @pool.checkout
<ide> @pool.checkin(idle_conn)
<ide> def test_disable_flush
<ide>
<ide> config = @db_config.configuration_hash.merge(idle_timeout: -5)
<ide> db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(@db_config.env_name, @db_config.name, config)
<del> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config)
<add> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :writing, :default)
<ide> @pool = ConnectionPool.new(pool_config)
<ide> idle_conn = @pool.checkout
<ide> @pool.checkin(idle_conn)
<ide> def test_public_connections_access_threadsafe
<ide> assert_not_nil found_conn
<ide> end
<ide>
<add> def test_role_and_shard_is_returned
<add> assert_equal :writing, @pool_config.role
<add> assert_equal :writing, @pool.role
<add> assert_equal :writing, @pool.connection.role
<add>
<add> assert_equal :default, @pool_config.shard
<add> assert_equal :default, @pool.shard
<add> assert_equal :default, @pool.connection.shard
<add>
<add> db_config = ActiveRecord::Base.connection_pool.db_config
<add> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :reading, :shard_one)
<add> pool = ConnectionPool.new(pool_config)
<add>
<add> assert_equal :reading, pool_config.role
<add> assert_equal :reading, pool.role
<add> assert_equal :reading, pool.connection.role
<add>
<add> assert_equal :shard_one, pool_config.shard
<add> assert_equal :shard_one, pool.shard
<add> assert_equal :shard_one, pool.connection.shard
<add> end
<add>
<ide> private
<ide> def with_single_connection_pool
<ide> config = @db_config.configuration_hash.merge(pool: 1)
<ide> db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("arunit", "primary", config)
<del> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config)
<add> pool_config = ActiveRecord::ConnectionAdapters::PoolConfig.new(ActiveRecord::Base, db_config, :writing, :default)
<ide>
<ide> yield(pool = ConnectionPool.new(pool_config))
<ide> ensure
<ide><path>activerecord/test/cases/reaper_test.rb
<ide> def test_some_time
<ide>
<ide> def test_pool_has_reaper
<ide> config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary")
<del> pool_config = PoolConfig.new(ActiveRecord::Base, config)
<add> pool_config = PoolConfig.new(ActiveRecord::Base, config, :writing, :default)
<ide> pool = ConnectionPool.new(pool_config)
<ide>
<ide> assert pool.reaper
<ide> def test_reaper_does_not_reap_discarded_connection_pools
<ide> def duplicated_pool_config(merge_config_options = {})
<ide> old_config = ActiveRecord::Base.connection_pool.db_config.configuration_hash.merge(merge_config_options)
<ide> db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new("arunit", "primary", old_config.dup)
<del> PoolConfig.new(ActiveRecord::Base, db_config)
<add> PoolConfig.new(ActiveRecord::Base, db_config, :writing, :default)
<ide> end
<ide>
<ide> def new_conn_in_thread(pool) | 7 |
Go | Go | remove the json alterations when decoding | dc2d930520cd528129330098e868c7fffe8349b9 | <ide><path>registry.go
<ide> func NewImgJson(src []byte) (*Image, error) {
<ide>
<ide> Debugf("Json string: {%s}\n", src)
<ide> // FIXME: Is there a cleaner way to "puryfy" the input json?
<del> src = []byte(strings.Replace(string(src), "null", "\"\"", -1))
<del>
<ide> if err := json.Unmarshal(src, ret); err != nil {
<ide> return nil, err
<ide> } | 1 |
Java | Java | improve javadoc of contentcachingrequestwrapper | f9167c3df59edbca2f8a99541750d87957d34a49 | <ide><path>spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 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> * the {@linkplain #getInputStream() input stream} and {@linkplain #getReader() reader},
<ide> * and allows this content to be retrieved via a {@link #getContentAsByteArray() byte array}.
<ide> *
<add> * <p>This class acts as an interceptor that only caches content as it is being
<add> * read but otherwise does not cause content to be read. That means if the request
<add> * content is not consumed, then the content is not cached, and cannot be
<add> * retrieved via {@link #getContentAsByteArray()}.
<add> *
<ide> * <p>Used e.g. by {@link org.springframework.web.filter.AbstractRequestLoggingFilter}.
<ide> * Note: As of Spring Framework 5.0, this wrapper is built on the Servlet 3.1 API.
<ide> *
<add> *
<ide> * @author Juergen Hoeller
<ide> * @author Brian Clozel
<ide> * @since 4.1.3
<ide> private void writeRequestParametersToCachedContent() {
<ide> /**
<ide> * Return the cached request content as a byte array.
<ide> * <p>The returned array will never be larger than the content cache limit.
<add> * <p><strong>Note:</strong> The byte array returned from this method
<add> * reflects the amount of content that has has been read at the time when it
<add> * is called. If the application does not read the content, this method
<add> * returns an empty array.
<ide> * @see #ContentCachingRequestWrapper(HttpServletRequest, int)
<ide> */
<ide> public byte[] getContentAsByteArray() { | 1 |
Text | Text | extend example code for autoloading serializers | 2d9a64ded514ccd9dff470b79726eac374e5ffe8 | <ide><path>guides/source/active_job_basics.md
<ide> by default has been mixed into Active Record classes.
<ide> You can extend the list of supported argument types. You just need to define your own serializer:
<ide>
<ide> ```ruby
<add># app/serializers/money_serializer.rb
<ide> class MoneySerializer < ActiveJob::Serializers::ObjectSerializer
<ide> # Checks if an argument should be serialized by this serializer.
<ide> def serialize?(argument)
<ide> end
<ide> and add this serializer to the list:
<ide>
<ide> ```ruby
<add># config/initializer/custom_serializers.rb
<ide> Rails.application.config.active_job.custom_serializers << MoneySerializer
<ide> ```
<ide>
<add>Note that auto-loading reloadable code during initialization is not supported. Thus it is recommended
<add>to set-up serializers to be loaded only once, e.g. by amending `config/application.rb` like this:
<add>
<add>```ruby
<add># config/application.rb
<add>module YourApp
<add> class Application < Rails::Application
<add> config.autoload_once_paths << Rails.root.join('app', 'serializers')
<add> end
<add>end
<add>```
<add>
<ide> Exceptions
<ide> ----------
<ide> | 1 |
Text | Text | fix minor typos | 294579cafdfe7445dd1035bbdd8840570b8873ad | <ide><path>official/nlp/bert/README.md
<ide> Install `tf-nightly` to get latest updates:
<ide> pip install tf-nightly-gpu
<ide> ```
<ide>
<del>With TPU, GPU support is not necessary. First, you need to create a `tf-nigthly`
<del>TPU with [cptu tool](https://github.com/tensorflow/tpu/tree/master/tools/ctpu):
<add>With TPU, GPU support is not necessary. First, you need to create a `tf-nightly`
<add>TPU with [ctpu tool](https://github.com/tensorflow/tpu/tree/master/tools/ctpu):
<ide>
<ide> ```shell
<ide> ctpu up -name <instance name> --tf-version=”nightly”
<ide> ```
<ide>
<del>Second, you need to install TF 2 `tf-night` on your VM:
<add>Second, you need to install TF 2 `tf-nightly` on your VM:
<ide>
<ide> ```shell
<ide> pip install tf-nightly | 1 |
Python | Python | fix polynomial division | 5c9620bdebb6eb98e3d58b9756419b68461f8b04 | <ide><path>scipy/base/polynomial.py
<ide> def polyadd(a1, a2):
<ide> """Adds two polynomials represented as sequences
<ide> """
<ide> truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
<del> a1, a2 = map(atleast_1d, (a1, a2))
<add> a1 = atleast_1d(a1)
<add> a2 = atleast_1d(a2)
<ide> diff = len(a2) - len(a1)
<ide> if diff == 0:
<ide> return a1 + a2
<ide> def polysub(a1, a2):
<ide> """Subtracts two polynomials represented as sequences
<ide> """
<ide> truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
<del> a1, a2 = map(atleast_1d, (a1, a2))
<add> a1 = atleast_1d(a1)
<add> a2 = atleast_1d(a2)
<ide> diff = len(a2) - len(a1)
<ide> if diff == 0:
<ide> return a1 - a2
<ide> def deconvolve(signal, divisor):
<ide> rem = num - NX.convolve(den, quot, mode='full')
<ide> return quot, rem
<ide>
<del>def polydiv(a1, a2):
<del> """Computes q and r polynomials so that a1(s) = q(s)*a2(s) + r(s)
<add>def polydiv(u, v):
<add> """Computes q and r polynomials so that u(s) = q(s)*v(s) + r(s)
<add> and deg r < deg v.
<ide> """
<del> truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d))
<del> monDivisor = NX.asarray(a2) / a2[0]
<del> dividend = NX.asarray(a1) / a2[0]
<del> q = []
<del> r = dividend
<del> while len(r) >= len(monDivisor):
<del> q.append(r[0])
<del> r = polysub(r, polymul(q, monDivisor))[1:]
<del> q = NX.asarray(q)
<add> truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d))
<add> u = atleast_1d(u)
<add> v = atleast_1d(v)
<add> m = len(u) - 1
<add> n = len(v) - 1
<add> scale = 1. / v[0]
<add> q = NX.zeros((m-n+1,), float)
<add> r = u.copy()
<add> for k in range(0, m-n+1):
<add> d = scale * r[k]
<add> q[k] = d
<add> r[k:k+n+1] -= d*v
<ide> while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1):
<ide> r = r[1:]
<del> r *= a2[0]
<ide> if truepoly:
<del> q, r = map(poly1d, (q, r))
<add> q = poly1d(q)
<add> r = poly1d(r)
<ide> return q, r
<ide>
<del>
<ide> _poly_mat = re.compile(r"[*][*]([0-9]*)")
<ide> def _raise_power(astr, wrap=70):
<ide> n = 0
<ide> def __div__(self, other):
<ide> return poly1d(self.coeffs/other)
<ide> else:
<ide> other = poly1d(other)
<del> return map(poly1d, polydiv(self.coeffs, other.coeffs))
<add> return polydiv(self, other)
<ide>
<ide> def __rdiv__(self, other):
<ide> if isscalar(other):
<ide> return poly1d(other/self.coeffs)
<ide> else:
<ide> other = poly1d(other)
<del> return map(poly1d, polydiv(other.coeffs, self.coeffs))
<add> return polydiv(other, self)
<ide>
<ide> def __setattr__(self, key, val):
<ide> raise ValueError, "Attributes cannot be changed this way."
<ide><path>scipy/base/tests/test_polynomial.py
<ide> """
<ide> >>> import scipy.base as nx
<del>>>> from scipy.base.polynomial import poly1d
<add>>>> from scipy.base.polynomial import poly1d, polydiv
<ide>
<ide> >>> p = poly1d([1.,2,3])
<ide> >>> p
<ide> >>> p * q
<ide> poly1d([ 3., 8., 14., 8., 3.])
<ide> >>> p / q
<del>[poly1d([ 0.33333333]), poly1d([ 1.33333333, 2.66666667])]
<add>(poly1d([ 0.33333333]), poly1d([ 1.33333333, 2.66666667]))
<ide> >>> p + q
<ide> poly1d([ 4., 4., 4.])
<ide> >>> p - q
<ide> 2
<ide> 1 lambda + 2 lambda + 3
<ide>
<add>>>> polydiv(poly1d([1,0,-1]), poly1d([1,1]))
<add>(poly1d([ 1., -1.]), poly1d([ 0.]))
<ide> """
<ide>
<ide> from scipy.test.testing import * | 2 |
Javascript | Javascript | remove redundant scripts | aadee894dac5275de01d90387f0cc157bf620183 | <ide><path>scripts/validate-commit-msg.js
<del>#!/usr/bin/env node
<del>
<del>/**
<del> * Git COMMIT-MSG hook for validating commit message
<del> * See https://docs.google.com/document/d/1rk04jEuGfk9kYzfqCuOlPTSJw3hEDZJTBN5E5f1SALo/edit
<del> *
<del> * Installation:
<del> * >> cd <angular-repo>
<del> * >> ln -s ../../validate-commit-msg.js .git/hooks/commit-msg
<del> */
<del>
<del>'use strict';
<del>
<del>var fs = require('fs');
<del>var util = require('util');
<del>
<del>
<del>var MAX_LENGTH = 100;
<del>var PATTERN = /^(?:fixup!\s*)?(\w*)(\(([\w$.*/-]*)\))?: (.*)$/;
<del>var IGNORED = /^WIP:/;
<del>var TYPES = {
<del> feat: true,
<del> fix: true,
<del> docs: true,
<del> style: true,
<del> refactor: true,
<del> perf: true,
<del> test: true,
<del> chore: true,
<del> revert: true
<del>};
<del>
<del>
<del>var error = function() {
<del> // gitx does not display it
<del> // http://gitx.lighthouseapp.com/projects/17830/tickets/294-feature-display-hook-error-message-when-hook-fails
<del> // https://groups.google.com/group/gitx/browse_thread/thread/a03bcab60844b812
<del> console.error('INVALID COMMIT MSG: ' + util.format.apply(null, arguments));
<del>};
<del>
<del>
<del>var validateMessage = function(message) {
<del> var isValid = true;
<del>
<del> if (IGNORED.test(message)) {
<del> console.log('Commit message validation ignored.');
<del> return true;
<del> }
<del>
<del> if (message.length > MAX_LENGTH) {
<del> error('is longer than %d characters !', MAX_LENGTH);
<del> isValid = false;
<del> }
<del>
<del> var match = PATTERN.exec(message);
<del>
<del> if (!match) {
<del> error('does not match "<type>(<scope>): <subject>" ! was: ' + message);
<del> return false;
<del> }
<del>
<del> var type = match[1];
<del>
<del> if (!TYPES.hasOwnProperty(type)) {
<del> error('"%s" is not allowed type !', type);
<del> return false;
<del> }
<del>
<del> // Some more ideas, do want anything like this ?
<del> // - allow only specific scopes (eg. fix(docs) should not be allowed ?
<del> // - auto correct the type to lower case ?
<del> // - auto correct first letter of the subject to lower case ?
<del> // - auto add empty line after subject ?
<del> // - auto remove empty () ?
<del> // - auto correct typos in type ?
<del> // - store incorrect messages, so that we can learn
<del>
<del> return isValid;
<del>};
<del>
<del>
<del>var firstLineFromBuffer = function(buffer) {
<del> return buffer.toString().split('\n').shift();
<del>};
<del>
<del>
<del>
<del>// publish for testing
<del>exports.validateMessage = validateMessage;
<del>
<del>// hacky start if not run by jasmine :-D
<del>if (process.argv.join('').indexOf('jasmine-node') === -1) {
<del> var commitMsgFile = process.argv[2];
<del> var incorrectLogFile = commitMsgFile.replace('COMMIT_EDITMSG', 'logs/incorrect-commit-msgs');
<del>
<del> fs.readFile(commitMsgFile, function(err, buffer) {
<del> if (err) {
<del> console.error(err);
<del> process.exit(1);
<del> }
<del> var msg = firstLineFromBuffer(buffer);
<del>
<del> if (!validateMessage(msg)) {
<del> fs.appendFile(incorrectLogFile, msg + '\n', function() {
<del> process.exit(1);
<del> });
<del> } else {
<del> process.exit(0);
<del> }
<del> });
<del>}
<ide><path>scripts/validate-commit-msg.spec.js
<del>/* global describe: false, beforeEach: false, it: false, expect: false, spyOn: false */
<del>'use strict';
<del>
<del>describe('validate-commit-msg.js', function() {
<del> var m = require('./validate-commit-msg');
<del> var errors = [];
<del> var logs = [];
<del>
<del> var VALID = true;
<del> var INVALID = false;
<del>
<del> beforeEach(function() {
<del> errors.length = 0;
<del> logs.length = 0;
<del>
<del> spyOn(console, 'error').andCallFake(function(msg) {
<del> // eslint-disable-next-line no-control-regex
<del> errors.push(msg.replace(/\x1B\[\d+m/g, '')); // uncolor
<del> });
<del>
<del> spyOn(console, 'log').andCallFake(function(msg) {
<del> // eslint-disable-next-line no-control-regex
<del> logs.push(msg.replace(/\x1B\[\d+m/g, '')); // uncolor
<del> });
<del> });
<del>
<del> describe('validateMessage', function() {
<del>
<del> it('should be valid', function() {
<del> expect(m.validateMessage('fixup! fix($compile): something')).toBe(VALID);
<del> expect(m.validateMessage('fix($compile): something')).toBe(VALID);
<del> expect(m.validateMessage('feat($location): something')).toBe(VALID);
<del> expect(m.validateMessage('docs($filter): something')).toBe(VALID);
<del> expect(m.validateMessage('style($http): something')).toBe(VALID);
<del> expect(m.validateMessage('refactor($httpBackend): something')).toBe(VALID);
<del> expect(m.validateMessage('test($resource): something')).toBe(VALID);
<del> expect(m.validateMessage('chore($controller): something')).toBe(VALID);
<del> expect(m.validateMessage('chore(foo-bar): something')).toBe(VALID);
<del> expect(m.validateMessage('chore(*): something')).toBe(VALID);
<del> expect(m.validateMessage('chore(guide/location): something')).toBe(VALID);
<del> expect(m.validateMessage('revert(foo): something')).toBe(VALID);
<del> expect(errors).toEqual([]);
<del> });
<del>
<del>
<del> it('should validate 100 characters length', function() {
<del> var msg = 'fix($compile): something super mega extra giga tera long, maybe even longer and longer and longer... ';
<del>
<del> expect(m.validateMessage(msg)).toBe(INVALID);
<del> expect(errors).toEqual(['INVALID COMMIT MSG: is longer than 100 characters !']);
<del> });
<del>
<del>
<del> it('should validate "<type>(<scope>): <subject>" format', function() {
<del> var msg = 'not correct format';
<del>
<del> expect(m.validateMessage(msg)).toBe(INVALID);
<del> expect(errors).toEqual(['INVALID COMMIT MSG: does not match "<type>(<scope>): <subject>" ! was: not correct format']);
<del> });
<del>
<del>
<del> it('should validate type', function() {
<del> expect(m.validateMessage('weird($filter): something')).toBe(INVALID);
<del> expect(errors).toEqual(['INVALID COMMIT MSG: "weird" is not allowed type !']);
<del> });
<del>
<del>
<del> it('should allow empty scope', function() {
<del> expect(m.validateMessage('fix: blablabla')).toBe(VALID);
<del> });
<del>
<del>
<del> it('should allow dot in scope', function() {
<del> expect(m.validateMessage('chore(mocks.$httpBackend): something')).toBe(VALID);
<del> });
<del>
<del>
<del> it('should ignore msg prefixed with "WIP: "', function() {
<del> expect(m.validateMessage('WIP: bullshit')).toBe(VALID);
<del> });
<del> });
<del>}); | 2 |
PHP | PHP | fix password column for future hashing | 531629e442b147fcbb172ebbf0d57deb4f5a60ee | <ide><path>database/migrations/2014_10_12_000000_create_users_table.php
<ide> public function up()
<ide> $table->increments('id');
<ide> $table->string('name');
<ide> $table->string('email')->unique();
<del> $table->string('password', 60);
<add> $table->string('password');
<ide> $table->rememberToken();
<ide> $table->timestamps();
<ide> }); | 1 |
Javascript | Javascript | remove obsolete code from shortcut handler | 64a4a2745591cf21e8cd38e653334dfd05de83fd | <ide><path>web/viewer.js
<ide> window.addEventListener('keydown', function keydown(evt) {
<ide> return;
<ide> }
<ide> }
<del> var controlsElement = document.getElementById('toolbar');
<del> while (curElement) {
<del> if (curElement === controlsElement && !PresentationMode.active)
<del> return; // ignoring if the 'toolbar' element is focused
<del> curElement = curElement.parentNode;
<del> }
<ide> //#if (FIREFOX || MOZCENTRAL)
<ide> //// Workaround for issue in Firefox, that prevents scroll keys from working
<ide> //// when elements with 'tabindex' are focused. | 1 |
Text | Text | add backticks [ci-skip] | ff2ee259073d6963b1e13b901188dd0bad48c6e4 | <ide><path>guides/source/caching_with_rails.md
<ide> NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside o
<ide>
<ide> You can access the cache by calling `Rails.cache`.
<ide>
<del>### ActiveSupport::Cache::Store
<add>### `ActiveSupport::Cache::Store`
<ide>
<ide> This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
<ide>
<ide> custom class.
<ide> config.cache_store = MyCacheStore.new
<ide> ```
<ide>
<del>### ActiveSupport::Cache::MemoryStore
<add>### `ActiveSupport::Cache::MemoryStore`
<ide>
<ide> This cache store keeps entries in memory in the same Ruby process. The cache
<ide> store has a bounded size specified by sending the `:size` option to the
<ide> New Rails projects are configured to use this implementation in the development
<ide> NOTE: Since processes will not share cache data when using `:memory_store`,
<ide> it will not be possible to manually read, write, or expire the cache via the Rails console.
<ide>
<del>### ActiveSupport::Cache::FileStore
<add>### `ActiveSupport::Cache::FileStore`
<ide>
<ide> This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
<ide>
<ide> periodically clear out old entries.
<ide> This is the default cache store implementation (at `"#{root}/tmp/cache/"`) if
<ide> no explicit `config.cache_store` is supplied.
<ide>
<del>### ActiveSupport::Cache::MemCacheStore
<add>### `ActiveSupport::Cache::MemCacheStore`
<ide>
<ide> This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.
<ide>
<ide> See the [`Dalli::Client` documentation](https://www.rubydoc.info/gems/dalli/Dall
<ide>
<ide> The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operations like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
<ide>
<del>### ActiveSupport::Cache::RedisCacheStore
<add>### `ActiveSupport::Cache::RedisCacheStore`
<ide>
<ide> The Redis cache store takes advantage of Redis support for automatic eviction
<ide> when it reaches max memory, allowing it to behave much like a Memcached cache server.
<ide> config.cache_store = :redis_cache_store, { url: cache_servers,
<ide> }
<ide> ```
<ide>
<del>### ActiveSupport::Cache::NullStore
<add>### `ActiveSupport::Cache::NullStore`
<ide>
<ide> This cache store is scoped to each web request, and clears stored values at the end of a request. It is meant for use in development and test environments. It can be very useful when you have code that interacts directly with `Rails.cache` but caching interferes with seeing the results of code changes.
<ide>
<ide><path>guides/source/security.md
<ide> be explicitly configured.
<ide> By default Rails is configured to return the following response headers. Your
<ide> application returns these headers for every HTTP response.
<ide>
<del>#### X-Frame-Options
<add>#### `X-Frame-Options`
<ide>
<ide> This header indicates if a browser can render the page in a `<frame>`,
<ide> `<iframe>`, `<embed>` or `<object>` tag. This header is set to `SAMEORIGIN` by
<ide> default to allow framing on the same domain only. Set it to `DENY` to deny
<ide> framing at all, or remove this header completely if you want to allow framing on
<ide> all domains.
<ide>
<del>#### X-XSS-Protection
<add>#### `X-XSS-Protection`
<ide>
<ide> A [deprecated legacy
<ide> header](https://owasp.org/www-project-secure-headers/#x-xss-protection), set to
<ide> `0` in Rails by default to disable problematic legacy XSS auditors.
<ide>
<del>#### X-Content-Type-Options
<add>#### `X-Content-Type-Options`
<ide>
<ide> This header is set to `nosniff` in Rails by default. It stops the browser from
<ide> guessing the MIME type of a file.
<ide>
<del>#### X-Permitted-Cross-Domain-Policies
<add>#### `X-Permitted-Cross-Domain-Policies`
<ide>
<ide> This header is set to `none` in Rails by default. It disallows Adobe Flash and
<ide> PDF clients from embedding your page on other domains.
<ide>
<del>#### Referrer-Policy
<add>#### `Referrer-Policy`
<ide>
<ide> This header is set to `strict-origin-when-cross-origin` in Rails by default.
<ide> For cross-origin requests, this only sends the origin in the Referer header. This
<ide> Or you can remove them:
<ide> config.action_dispatch.default_headers.clear
<ide> ```
<ide>
<del>### Strict-Transport-Security Header
<add>### `Strict-Transport-Security` Header
<ide>
<ide> The HTTP
<del>[Strict-Transport-Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
<add>[`Strict-Transport-Security`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
<ide> (HTST) response header makes sure the browser automatically upgrades to HTTPS
<ide> for current and future connections.
<ide>
<ide> The header is added to the response when enabling the `force_ssl` option:
<ide> config.force_ssl = true
<ide> ```
<ide>
<del>### Content-Security-Policy Header
<add>### `Content-Security-Policy` Header
<ide>
<ide> To help protect against XSS and injection attacks, it is recommended to define a
<del>[Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
<add>[`Content-Security-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)
<ide> response header for your application. Rails provides a DSL that allows you to
<ide> configure the header.
<ide>
<ide> end
<ide> #### Reporting Violations
<ide>
<ide> Enable the
<del>[report-uri](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri)
<add>[`report-uri`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/report-uri)
<ide> directive to report violations to the specified URI:
<ide>
<ide> ```ruby
<ide> end
<ide>
<ide> When migrating legacy content, you might want to report violations without
<ide> enforcing the policy. Set the
<del>[Content-Security-Policy-Report-Only](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only)
<add>[`Content-Security-Policy-Report-Only`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only)
<ide> response header to only report violations:
<ide>
<ide> ```ruby
<ide> end
<ide>
<ide> #### Adding a Nonce
<ide>
<del>If you are considering 'unsafe-inline', consider using nonces instead. [Nonces
<add>If you are considering `'unsafe-inline'`, consider using nonces instead. [Nonces
<ide> provide a substantial improvement](https://www.w3.org/TR/CSP3/#security-nonces)
<del>over 'unsafe-inline' when implementing a Content Security Policy on top
<add>over `'unsafe-inline'` when implementing a Content Security Policy on top
<ide> of existing code.
<ide>
<ide> ```ruby
<ide> for allowing inline `<script>` tags.
<ide> This is used by the Rails UJS helper to create dynamically
<ide> loaded inline `<script>` elements.
<ide>
<del>### Feature-Policy Header
<add>### `Feature-Policy` Header
<ide>
<del>NOTE: The Feature-Policy header has been renamed to Permissions-Policy.
<del>The Permissions-Policy requires a different implementation and isn't
<add>NOTE: The `Feature-Policy` header has been renamed to `Permissions-Policy`.
<add>The `Permissions-Policy` requires a different implementation and isn't
<ide> yet supported by all browsers. To avoid having to rename this
<ide> middleware in the future, we use the new name for the middleware but
<ide> keep the old header name and implementation for now.
<ide>
<ide> To allow or block the use of browser features, you can define a
<del>[Feature-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy)
<add>[`Feature-Policy`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy)
<ide> response header for your application. Rails provides a DSL that allows you to
<ide> configure the header.
<ide> | 2 |
Javascript | Javascript | add some helpful comments to the rollup config | f7230ef9f9e54db8cb0fc91f6cfd429fbf1a5305 | <ide><path>rollup.config.js
<ide> import { terser } from 'rollup-plugin-terser'
<ide> import pkg from './package.json'
<ide>
<ide> export default [
<add> // CommonJS
<ide> {
<ide> input: 'src/index.js',
<ide> output: { file: 'lib/redux.js', format: 'cjs', indent: false },
<ide> external: [
<ide> ...Object.keys(pkg.dependencies || {}),
<del> ...Object.keys(pkg.peerDependencies || {}),
<add> ...Object.keys(pkg.peerDependencies || {})
<ide> ],
<del> plugins: [
<del> babel()
<del> ]
<add> plugins: [babel()]
<ide> },
<add>
<add> // ES
<ide> {
<ide> input: 'src/index.js',
<ide> output: { file: 'es/redux.js', format: 'es', indent: false },
<ide> external: [
<ide> ...Object.keys(pkg.dependencies || {}),
<del> ...Object.keys(pkg.peerDependencies || {}),
<add> ...Object.keys(pkg.peerDependencies || {})
<ide> ],
<del> plugins: [
<del> babel()
<del> ]
<add> plugins: [babel()]
<ide> },
<add>
<add> // ES for Browsers
<ide> {
<ide> input: 'src/index.js',
<ide> output: { file: 'es/redux.mjs', format: 'es', indent: false },
<ide> export default [
<ide> })
<ide> ]
<ide> },
<add>
<add> // UMD Development
<ide> {
<ide> input: 'src/index.js',
<ide> output: {
<ide> export default [
<ide> jsnext: true
<ide> }),
<ide> babel({
<del> exclude: 'node_modules/**',
<add> exclude: 'node_modules/**'
<ide> }),
<ide> replace({
<ide> 'process.env.NODE_ENV': JSON.stringify('development')
<ide> })
<ide> ]
<ide> },
<add>
<add> // UMD Production
<ide> {
<ide> input: 'src/index.js',
<ide> output: {
<ide> export default [
<ide> jsnext: true
<ide> }),
<ide> babel({
<del> exclude: 'node_modules/**',
<add> exclude: 'node_modules/**'
<ide> }),
<ide> replace({
<ide> 'process.env.NODE_ENV': JSON.stringify('production') | 1 |
Javascript | Javascript | add skipci flag to release script | f4488bee514aba9a17b2498aa8e3b300e5149954 | <ide><path>scripts/release/build-commands/check-circle-ci-status.js
<ide>
<ide> const chalk = require('chalk');
<ide> const http = require('request-promise-json');
<add>const logUpdate = require('log-update');
<add>const prompt = require('prompt-promise');
<ide> const {execRead, logPromise} = require('../utils');
<ide>
<ide> // https://circleci.com/docs/api/v1-reference/#projects
<ide> module.exports = async params => {
<ide> if (params.local) {
<ide> return;
<ide> }
<add>
<add> if (params.skipCI) {
<add> logUpdate(chalk.red`Are you sure you want to skip CI? (y for yes, n for no)`);
<add> const confirm = await prompt('');
<add> logUpdate.done();
<add> if (confirm === 'y') {
<add> return;
<add> } else {
<add> throw Error(
<add> chalk`
<add> Cancelling release.
<add> `
<add> );
<add> }
<add> }
<add>
<ide> return logPromise(check(params), 'Checking CircleCI status');
<ide> };
<ide><path>scripts/release/build-commands/update-git.js
<ide> module.exports = async params => {
<ide> update(params),
<ide> `Updating checkout ${chalk.yellow.bold(
<ide> params.cwd
<del> )} on branch ${chalk.yellow.bold(params.branch)}}`
<add> )} on branch ${chalk.yellow.bold(params.branch)}`
<ide> );
<ide> };
<ide><path>scripts/release/config.js
<ide> const paramDefinitions = [
<ide> 'The npm dist tag; defaults to [bold]{latest} for a stable' +
<ide> 'release, [bold]{next} for unstable',
<ide> },
<add> {
<add> name: 'skipCI',
<add> type: Boolean,
<add> description:
<add> 'Skip Circle CI status check (requires confirmation)',
<add> },
<ide> ];
<ide>
<ide> module.exports = { | 3 |
Python | Python | add ma.median tests for valid axis | ad5b13a585cb2b43b7f6ef7a30124bec82dfa359 | <ide><path>numpy/ma/tests/test_extras.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import warnings
<add>import itertools
<ide>
<ide> import numpy as np
<ide> from numpy.testing import (
<ide> def test_docstring_examples(self):
<ide> assert_equal(ma_x.shape, (2,), "shape mismatch")
<ide> assert_(type(ma_x) is MaskedArray)
<ide>
<add> def test_axis_argument_errors(self):
<add> msg = "mask = %s, ndim = %s, axis = %s, overwrite_input = %s"
<add> for ndmin in range(5):
<add> for mask in [False, True]:
<add> x = array(1, ndmin=ndmin, mask=mask)
<add>
<add> # Valid axis values should not raise exception
<add> args = itertools.product(range(-ndmin, ndmin), [False, True])
<add> for axis, over in args:
<add> try:
<add> np.ma.median(x, axis=axis, overwrite_input=over)
<add> except:
<add> raise AssertionError(msg % (mask, ndmin, axis, over))
<add>
<add> # Invalid axis values should raise exception
<add> args = itertools.product([-(ndmin + 1), ndmin], [False, True])
<add> for axis, over in args:
<add> try:
<add> np.ma.median(x, axis=axis, overwrite_input=over)
<add> except IndexError:
<add> pass
<add> else:
<add> raise AssertionError(msg % (mask, ndmin, axis, over))
<add>
<add> def test_masked_0d(self):
<add> # Check values
<add> x = array(1, mask=False)
<add> assert_equal(np.ma.median(x), 1)
<add> x = array(1, mask=True)
<add> assert_equal(np.ma.median(x), np.ma.masked)
<add>
<ide> def test_masked_1d(self):
<ide> x = array(np.arange(5), mask=True)
<ide> assert_equal(np.ma.median(x), np.ma.masked) | 1 |
Javascript | Javascript | convert objectproxy and arrayproxy | 72733afb5e9cb11308f8e21115ccc7d6d9335f6a | <ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> @property {Number} length
<ide> @public
<ide> */
<del> length: null,
<ide>
<ide> /**
<ide> Returns the object at the given `index`. If the given `index` is negative
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> @return {*} item at index or undefined
<ide> @public
<ide> */
<del> objectAt(idx) {
<del> if (idx < 0 || idx >= this.length) {
<del> return undefined;
<del> }
<del>
<del> return get(this, idx);
<del> },
<ide>
<ide> /**
<ide> This returns the objects at the specified indexes, using `objectAt`.
<ide> const MutableArray = Mixin.create(ArrayMixin, MutableEnumerable, {
<ide> inserted into the array at *idx*
<ide> @public
<ide> */
<del> replace: null,
<ide>
<ide> /**
<ide> Remove all elements from the array. This is useful if you
<ide><path>packages/ember-runtime/lib/system/array_proxy.js
<ide> import {
<ide> get,
<ide> objectAt,
<del> computed,
<ide> alias,
<ide> PROPERTY_DID_CHANGE,
<ide> addArrayObserver,
<ide> const ARRAY_OBSERVER_MAPPING = {
<ide> @uses MutableArray
<ide> @public
<ide> */
<del>export default EmberObject.extend(MutableArray, {
<add>export default class ArrayProxy extends EmberObject {
<ide> init() {
<del> this._super(...arguments);
<add> super.init(...arguments);
<ide>
<ide> /*
<ide> `this._objectsDirtyIndex` determines which indexes in the `this._objects`
<ide> export default EmberObject.extend(MutableArray, {
<ide>
<ide> this._arrangedContent = null;
<ide> this._addArrangedContentArrayObsever();
<del> },
<add> }
<ide>
<ide> willDestroy() {
<ide> this._removeArrangedContentArrayObsever();
<del> },
<add> }
<ide>
<ide> /**
<ide> The content array. Must be an object that implements `Array` and/or
<ide> export default EmberObject.extend(MutableArray, {
<ide> @type EmberArray
<ide> @public
<ide> */
<del> content: null,
<del>
<del> /**
<del> The array that the proxy pretends to be. In the default `ArrayProxy`
<del> implementation, this and `content` are the same. Subclasses of `ArrayProxy`
<del> can override this property to provide things like sorting and filtering.
<del>
<del> @property arrangedContent
<del> @public
<del> */
<del> arrangedContent: alias('content'),
<ide>
<ide> /**
<ide> Should actually retrieve the object at the specified index from the
<ide> export default EmberObject.extend(MutableArray, {
<ide> */
<ide> objectAtContent(idx) {
<ide> return objectAt(get(this, 'arrangedContent'), idx);
<del> },
<add> }
<ide>
<ide> replace(idx, amt, objects) {
<ide> assert(
<ide> 'Mutating an arranged ArrayProxy is not allowed',
<ide> get(this, 'arrangedContent') === get(this, 'content')
<ide> );
<ide> this.replaceContent(idx, amt, objects);
<del> },
<add> }
<ide>
<ide> /**
<ide> Should actually replace the specified objects on the content array.
<ide> export default EmberObject.extend(MutableArray, {
<ide> */
<ide> replaceContent(idx, amt, objects) {
<ide> get(this, 'content').replace(idx, amt, objects);
<del> },
<add> }
<ide>
<ide> // Overriding objectAt is not supported.
<ide> objectAt(idx) {
<ide> export default EmberObject.extend(MutableArray, {
<ide> }
<ide>
<ide> return this._objects[idx];
<del> },
<add> }
<ide>
<ide> // Overriding length is not supported.
<del> length: computed(function() {
<add> get length() {
<ide> if (this._lengthDirty) {
<ide> let arrangedContent = get(this, 'arrangedContent');
<ide> this._length = arrangedContent ? get(arrangedContent, 'length') : 0;
<ide> this._lengthDirty = false;
<ide> }
<ide>
<ide> return this._length;
<del> }).volatile(),
<add> }
<ide>
<ide> [PROPERTY_DID_CHANGE](key) {
<ide> if (key === 'arrangedContent') {
<ide> export default EmberObject.extend(MutableArray, {
<ide> this.arrayContentDidChange(0, oldLength, newLength);
<ide> this._addArrangedContentArrayObsever();
<ide> }
<del> },
<add> }
<ide>
<ide> _addArrangedContentArrayObsever() {
<ide> let arrangedContent = get(this, 'arrangedContent');
<ide> export default EmberObject.extend(MutableArray, {
<ide>
<ide> this._arrangedContent = arrangedContent;
<ide> }
<del> },
<add> }
<ide>
<ide> _removeArrangedContentArrayObsever() {
<ide> if (this._arrangedContent) {
<ide> removeArrayObserver(this._arrangedContent, this, ARRAY_OBSERVER_MAPPING);
<ide> }
<del> },
<add> }
<ide>
<del> _arrangedContentArrayWillChange() {},
<add> _arrangedContentArrayWillChange() {}
<ide>
<ide> _arrangedContentArrayDidChange(proxy, idx, removedCnt, addedCnt) {
<ide> this.arrayContentWillChange(idx, removedCnt, addedCnt);
<ide> export default EmberObject.extend(MutableArray, {
<ide> this._lengthDirty = true;
<ide>
<ide> this.arrayContentDidChange(idx, removedCnt, addedCnt);
<del> },
<add> }
<add>}
<add>
<add>ArrayProxy.reopen(MutableArray, {
<add> /**
<add> The array that the proxy pretends to be. In the default `ArrayProxy`
<add> implementation, this and `content` are the same. Subclasses of `ArrayProxy`
<add> can override this property to provide things like sorting and filtering.
<add>
<add> @property arrangedContent
<add> @public
<add> */
<add> arrangedContent: alias('content'),
<ide> });
<ide><path>packages/ember-runtime/lib/system/object_proxy.js
<ide> import _ProxyMixin from '../mixins/-proxy';
<ide> @uses Ember.ProxyMixin
<ide> @public
<ide> */
<del>
<del>export default FrameworkObject.extend(_ProxyMixin);
<add>export default class ObjectProxy extends FrameworkObject {}
<add>ObjectProxy.PrototypeMixin.reopen(_ProxyMixin); | 3 |
PHP | PHP | change method order | bbc1ba6c6d1f5f9f925e67071427b2aae21731db | <ide><path>src/Illuminate/Database/Eloquent/SoftDeletingScope.php
<ide> class SoftDeletingScope implements Scope
<ide> *
<ide> * @var array
<ide> */
<del> protected $extensions = ['ForceDelete', 'Restore', 'WithTrashed', 'OnlyTrashed', 'WithoutTrashed'];
<add> protected $extensions = ['ForceDelete', 'Restore', 'WithTrashed', 'WithoutTrashed', 'OnlyTrashed'];
<ide>
<ide> /**
<ide> * Apply the scope to a given Eloquent query builder.
<ide> protected function addWithTrashed(Builder $builder)
<ide> }
<ide>
<ide> /**
<del> * Add the only-trashed extension to the builder.
<add> * Add the without-trashed extension to the builder.
<ide> *
<ide> * @param \Illuminate\Database\Eloquent\Builder $builder
<ide> * @return void
<ide> */
<del> protected function addOnlyTrashed(Builder $builder)
<add> protected function addWithoutTrashed(Builder $builder)
<ide> {
<del> $builder->macro('onlyTrashed', function (Builder $builder) {
<add> $builder->macro('withoutTrashed', function (Builder $builder) {
<ide> $model = $builder->getModel();
<ide>
<del> $builder->withoutGlobalScope($this)->whereNotNull(
<add> $builder->withoutGlobalScope($this)->whereNull(
<ide> $model->getQualifiedDeletedAtColumn()
<ide> );
<ide>
<ide> protected function addOnlyTrashed(Builder $builder)
<ide> }
<ide>
<ide> /**
<del> * Add the without-trashed extension to the builder.
<add> * Add the only-trashed extension to the builder.
<ide> *
<ide> * @param \Illuminate\Database\Eloquent\Builder $builder
<ide> * @return void
<ide> */
<del> protected function addWithoutTrashed(Builder $builder)
<add> protected function addOnlyTrashed(Builder $builder)
<ide> {
<del> $builder->macro('withoutTrashed', function (Builder $builder) {
<add> $builder->macro('onlyTrashed', function (Builder $builder) {
<ide> $model = $builder->getModel();
<ide>
<del> $builder->withoutGlobalScope($this)->whereNull(
<add> $builder->withoutGlobalScope($this)->whereNotNull(
<ide> $model->getQualifiedDeletedAtColumn()
<ide> );
<ide> | 1 |
Ruby | Ruby | add test using identity map and select | 1c88d59891d11bd60a07f35a15c0043e0f8cf28a | <ide><path>activerecord/test/cases/identity_map_test.rb
<ide> def test_find_using_identity_map_respects_readonly
<ide> assert comment.save
<ide> end
<ide>
<add> def test_find_using_select_and_identity_map
<add> author_id, author = Author.select('id').first, Author.first
<add>
<add> assert_equal author_id, author
<add> assert_same author_id, author
<add> assert_not_nil author.name
<add>
<add> post, post_id = Post.first, Post.select('id').first
<add>
<add> assert_equal post_id, post
<add> assert_same post_id, post
<add> assert_not_nil post.title
<add> end
<add>
<ide> # Currently AR is not allowing changing primary key (see Persistence#update)
<ide> # So we ignore it. If this changes, this test needs to be uncommented.
<ide> # def test_updating_of_pkey | 1 |
Java | Java | add support for `double` type in reactpropgroup | c0c8e7cfdf83b3a215f15257892f892604eff431 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactPropGroup.java
<ide> * group of the property being updated. Last, third argument represent the value that should be set.
<ide> *
<ide> *
<del> * Currently only {@code int}, {@code float} and {@link String} value types are supported.
<add> * Currently only {@code int}, {@code float}, {@code double} and {@link String} value types are
<add> * supported.
<ide> *
<ide> * In case when property has been removed from the corresponding react component annotated setter
<ide> * will be called and default value will be provided as a value parameter. Default value can be
<ide> */
<ide> float defaultFloat() default 0.0f;
<ide>
<add> /**
<add> * Default value for property of type {@code double}. This value will be provided to property
<add> * setter method annotated with {@link ReactPropGroup} if property with a given name gets removed
<add> * from the component description in JS
<add> */
<add> double defaultDouble() default 0.0;
<add>
<ide> /**
<ide> * Default value for property of type {@code int}. This value will be provided to property
<ide> * setter method annotated with {@link ReactPropGroup} if property with a given name gets removed
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java
<ide> public DoublePropSetter(ReactProp prop, Method setter, double defaultValue) {
<ide> mDefaultValue = defaultValue;
<ide> }
<ide>
<add> public DoublePropSetter(ReactPropGroup prop, Method setter, int index, double defaultValue) {
<add> super(prop, "number", setter, index);
<add> mDefaultValue = defaultValue;
<add> }
<add>
<ide> @Override
<ide> protected Object extractProperty(CatalystStylesDiffMap props) {
<ide> return props.getDouble(mPropName, mDefaultValue);
<ide> private static void createPropSetters(
<ide> names[i],
<ide> new FloatPropSetter(annotation, method, i, annotation.defaultFloat()));
<ide> }
<add> } else if (propTypeClass == double.class) {
<add> for (int i = 0; i < names.length; i++) {
<add> props.put(
<add> names[i],
<add> new DoublePropSetter(annotation, method, i, annotation.defaultDouble()));
<add> }
<ide> } else if (propTypeClass == Integer.class) {
<ide> for (int i = 0; i < names.length; i++) {
<ide> props.put( | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.