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
PHP
PHP
fix missing things
7c7c3bc4be3052afe0889fe323230dfd92f81000
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php <ide> public function morphMany($related, $name, $type = null, $id = null, $localKey = <ide> * @param string $table <ide> * @param string $foreignKey <ide> * @param string $relatedKey <add> * @param string $localKey <ide> * @param string $relation <ide> * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany <ide> */ <ide> public function belongsToMany($related, $table = null, $foreignKey = null, $rela <ide> <ide> $relatedKey = $relatedKey ?: $instance->getForeignKey(); <ide> <del> $localKey = $localKey ?: $this->getKeyName(); <del> <ide> // If no table name was provided, we can guess it by concatenating the two <ide> // models using underscores in alphabetical order. The two model names <ide> // are transformed to snake case from their default CamelCase also. <ide> public function belongsToMany($related, $table = null, $foreignKey = null, $rela <ide> } <ide> <ide> return new BelongsToMany( <del> $instance->newQuery(), $this, $table, $foreignKey, $relatedKey, $localKey, $relation <add> $instance->newQuery(), $this, $table, $foreignKey, <add> $relatedKey, $localKey ?: $this->getKeyName(), $relation <ide> ); <ide> } <ide> <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> class BelongsToMany extends Relation <ide> * @param string $table <ide> * @param string $foreignKey <ide> * @param string $relatedKey <add> * @param string $localKey <ide> * @param string $relationName <ide> * @return void <ide> */ <ide> public function __construct(Builder $query, Model $parent, $table, $foreignKey, $relatedKey, $localKey, $relationName = null) <ide> { <ide> $this->table = $table; <add> $this->localKey = $localKey; <ide> $this->relatedKey = $relatedKey; <ide> $this->foreignKey = $foreignKey; <ide> $this->relationName = $relationName; <del> $this->localKey = $localKey; <ide> <ide> parent::__construct($query, $parent); <ide> } <ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php <ide> class MorphToMany extends BelongsToMany <ide> * @param string $table <ide> * @param string $foreignKey <ide> * @param string $relatedKey <add> * @param string $localKey <ide> * @param string $relationName <ide> * @param bool $inverse <ide> * @return void
3
PHP
PHP
make()
bd1d2e76ad20d43d7eaaa47394260ba1a7b66571
<ide><path>src/Illuminate/View/Environment.php <ide> public function make($view, $data = array(), $mergeData = array()) <ide> { <ide> $path = $this->finder->find($view); <ide> <del> $data = array_merge($this->parseData($data), $mergeData); <add> $data = array_merge($mergeData, $this->parseData($data)); <ide> <ide> return new View($this, $this->getEngineFromPath($path), $view, $path, $data); <ide> }
1
Python
Python
add task to __all__ in celery.__init__.py
5af2a6598b908d80530258ebefc67d92dea1bd9e
<ide><path>celery/__init__.py <ide> # -eof meta- <ide> <ide> __all__ = ( <del> 'Celery', 'bugreport', 'shared_task', 'task', <add> 'Celery', 'bugreport', 'shared_task', 'task', 'Task', <ide> 'current_app', 'current_task', 'maybe_signature', <ide> 'chain', 'chord', 'chunks', 'group', 'signature', <ide> 'xmap', 'xstarmap', 'uuid',
1
Text
Text
improve documentation in "project" directory
fcdb1fbfa1e691bbdfb73a289ff84fbf6b26fad6
<ide><path>docs/sources/project/advanced-contributing.md <ide> The following provides greater detail on the process: <ide> This is a Markdown file that describes your idea. Your proposal <ide> should include information like: <ide> <del> * Why is this changed needed or what are the use cases? <add> * Why is this change needed or what are the use cases? <ide> * What are the requirements this change should meet? <ide> * What are some ways to design/implement this feature? <ide> * Which design/implementation do you think is best and why? <ide><path>docs/sources/project/coding-style.md <ide> page_keywords: change, commit, squash, request, pull request, test, unit test, i <ide> <ide> This checklist summarizes the material you experienced working through [make a <ide> code contribution](/project/make-a-contribution) and [advanced <del>contributing](/project/advanced-contributing). The checklist applies to code <del>that is program code or code that is documentation code. <add>contributing](/project/advanced-contributing). The checklist applies to both <add>program code and documentation code. <ide> <ide> ## Change and commit code <ide> <ide><path>docs/sources/project/create-pr.md <ide> Before you create a pull request, check your work. <ide> 2. Checkout your feature branch. <ide> <ide> $ git checkout 11038-fix-rhel-link <del> Already on '11038-fix-rhel-link' <add> Switched to branch '11038-fix-rhel-link' <ide> <ide> 3. Run the full test suite on your branch. <ide> <ide> Before you create a pull request, check your work. <ide> <ide> Always rebase and squash your commits before making a pull request. <ide> <del>1. Fetch any of the last minute changes from `docker/docker`. <add>1. Checkout your feature branch in your local `docker-fork` repository. <add> <add> This is the branch associated with your request. <add> <add>2. Fetch any last minute changes from `docker/docker`. <ide> <ide> $ git fetch upstream master <ide> From github.com:docker/docker <ide> Always rebase and squash your commits before making a pull request. <ide> pick 1a79f55 Tweak some of the other text for grammar <ide> pick 53e4983 Fix a link <ide> pick 3ce07bb Add a new line about RHEL <del> <del> If you run into trouble, `git --rebase abort` removes any changes and gets <del> you back to where you started. <ide> <del>4. Squash the `pick` keyword with `squash` on all but the first commit. <add>5. Replace the `pick` keyword with `squash` on all but the first commit. <ide> <ide> pick 1a79f55 Tweak some of the other text for grammar <ide> squash 53e4983 Fix a link <ide> squash 3ce07bb Add a new line about RHEL <ide> <del> After closing the file, `git` opens your editor again to edit the commit <del> message. <add> After you save the changes and quit from the editor, git starts <add> the rebase, reporting the progress along the way. Sometimes <add> your changes can conflict with the work of others. If git <add> encounters a conflict, it stops the rebase, and prints guidance <add> for how to correct the conflict. <ide> <del>5. Edit and save your commit message. <add>6. Edit and save your commit message. <ide> <ide> `git commit -s` <ide> <ide> Make sure your message includes <a href="./set-up-git" target="_blank>your signature</a>. <ide> <del>8. Push any changes to your fork on GitHub. <add>7. Force push any changes to your fork on GitHub. <ide> <del> $ git push origin 11038-fix-rhel-link <add> $ git push -f origin 11038-fix-rhel-link <ide> <ide> ## Create a PR on GitHub <ide> <ide> You create and manage PRs on GitHub: <ide> 4. Scroll down and verify the PR contains the commits and changes you expect. <ide> <ide> For example, is the file count correct? Are the changes in the files what <del> you expect. <add> you expect? <ide> <ide> ![Commits](/project/images/commits_expected.png) <ide> <ide> You create and manage PRs on GitHub: <ide> <ide> Congratulations, you've created your first pull request to Docker. The next <ide> step is for you learn how to [participate in your PR's <del>review](/project/review-pr/). <ide>\ No newline at end of file <add>review](/project/review-pr/). <ide><path>docs/sources/project/find-an-issue.md <ide> To sync your repository: <ide> remote: Total 141 (delta 52), reused 46 (delta 46), pack-reused 66 <ide> Receiving objects: 100% (141/141), 112.43 KiB | 0 bytes/s, done. <ide> Resolving deltas: 100% (79/79), done. <del> From github.com:docker/docker <del> * branch master -> FETCH_HEAD <add> From github.com:docker/docker <add> * branch master -> FETCH_HEAD <ide> <ide> This command says get all the changes from the `master` branch belonging to <ide> the `upstream` remote. <ide> To sync your repository: <ide> First, rewinding head to replay your work on top of it... <ide> Fast-forwarded master to upstream/master. <ide> <del> This command writes all the commits from the upstream branch into your local <del> branch. <add> This command applies all the commits from the upstream master to your local <add> master. <ide> <ide> 8. Check the status of your local branch. <ide> <ide> To sync your repository: <ide> (use "git push" to publish your local commits) <ide> nothing to commit, working directory clean <ide> <del> Your local repository now has any changes from the `upstream` remote. You <add> Your local repository now has all the changes from the `upstream` remote. You <ide> need to push the changes to your own remote fork which is `origin master`. <ide> <ide> 9. Push the rebased master to `origin master`. <ide> <del> $ git push origin <add> $ git push origin master <ide> Username for 'https://github.com': moxiegirl <ide> Password for 'https://moxiegirl@github.com': <ide> Counting objects: 223, done. <ide> To sync your repository: <ide> Current branch 11038-fix-rhel-link is up to date. <ide> <ide> At this point, your local branch, your remote repository, and the Docker <del> repository all have identical code. You are ready to make changesfor your <del> issues. <add> repository all have identical code. You are ready to make changes for your <add> issue. <ide> <ide> <ide> ## Where to go next <ide><path>docs/sources/project/set-up-git.md <ide> contributions through pseudonyms. <ide> As you change code in your fork, you'll want to keep it in sync with the changes <ide> others make in the `docker/docker` repository. To make syncing easier, you'll <ide> also add a _remote_ called `upstream` that points to `docker/docker`. A remote <del>is just another a project version hosted on the internet or network. <add>is just another project version hosted on the internet or network. <ide> <ide> To configure your username, email, and add a remote: <ide> <ide> the branch to your fork on GitHub: <ide> <ide> You can use any text editor you are comfortable with. <ide> <del>6. Close and save the file. <add>6. Save and close the file. <ide> <ide> 7. Check the status of your branch. <ide> <ide><path>docs/sources/project/software-required.md <ide> your user to the `docker` group as follows: <ide> <ide> $ sudo usermod -aG docker ubuntu <ide> <del>You must log out and back in for this modification to take effect. <add>You must log out and log back in for this modification to take effect. <ide> <ide> <ide> ## Where to go next <ide><path>docs/sources/project/work-issue.md <ide> Follow this workflow as you work: <ide> <ide> 9. Push your change to your repository. <ide> <del> $ git push origin <add> $ git push origin 11038-fix-rhel-link <ide> Username for 'https://github.com': moxiegirl <ide> Password for 'https://moxiegirl@github.com': <ide> Counting objects: 60, done. <ide> After you push a new branch, you should verify it on GitHub: <ide> <ide> You should pull and rebase frequently as you work. <ide> <del>1. Return to the terminal on your local machine. <add>1. Return to the terminal on your local machine and checkout your <add> feature branch in your local `docker-fork` repository. <ide> <del>2. Make sure you are in your branch. <add>2. Fetch any last minute changes from `docker/docker`. <ide> <del> $ git checkout 11038-fix-rhel-link <add> $ git fetch upstream master <add> From github.com:docker/docker <add> * branch master -> FETCH_HEAD <ide> <del>3. Fetch all the changes from the `upstream master` branch. <add>3. Start an interactive rebase. <ide> <del> $ git fetch upstream master <add> $ git rebase -i upstream/master <ide> <del> This command says get all the changes from the `master` branch belonging to <del> the `upstream` remote. <add>4. Rebase opens an editor with a list of commits. <ide> <del>4. Rebase your master with the local copy of Docker's `master` branch. <add> pick 1a79f55 Tweak some of the other text for grammar <add> pick 53e4983 Fix a link <add> pick 3ce07bb Add a new line about RHEL <ide> <del> $ git rebase -i upstream/master <del> <del> This command starts an interactive rebase to rewrite all the commits from <del> Docker's `upstream/master` onto your local branch, and then re-apply each of <del> your commits on top of the upstream changes. If you aren't familiar or <del> comfortable with rebase, you can <a <del> href="http://nathanleclaire.com/blog/2014/09/14/dont-be-scared-of-git- <del> rebase" target="_blank">learn more about rebasing</a> on the web. <del> <del>5. Rebase opens an editor with a list of commits. <add>5. Replace the `pick` keyword with `squash` on all but the first commit. <ide> <del> pick 1a79f55 Tweak some of the other text for grammar <del> pick 53e4983 Fix a link <del> pick 3ce07bb Add a new line about RHEL <del> <del> If you run into trouble, `git --rebase abort` removes any changes and gets <del> you back to where you started. <add> pick 1a79f55 Tweak some of the other text for grammar <add> squash 53e4983 Fix a link <add> squash 3ce07bb Add a new line about RHEL <ide> <del>6. Squash the `pick` keyword with `squash` on all but the first commit. <add> After you save the changes and quit from the editor, git starts <add> the rebase, reporting the progress along the way. Sometimes <add> your changes can conflict with the work of others. If git <add> encounters a conflict, it stops the rebase, and prints guidance <add> for how to correct the conflict. <ide> <del> pick 1a79f55 Tweak some of the other text for grammar <del> squash 53e4983 Fix a link <del> squash 3ce07bb Add a new line about RHEL <add>6. Edit and save your commit message. <ide> <del> After closing the file, `git` opens your editor again to edit the commit <del> message. <add> `git commit -s` <ide> <del>7. Edit the commit message to reflect the entire change. <add> Make sure your message includes <a href="./set-up-git" target="_blank>your signature</a>. <ide> <del> Make sure you include your signature. <add>7. Force push any changes to your fork on GitHub. <ide> <del>8. Push any changes to your fork on GitHub. <del> <del> The rebase rewrote history, so you'll need to use the `-f` or `--force` flag <del> to push your change. <del> <del> $ git push -f origin 11038-fix-rhel-link <add> $ git push -f origin 11038-fix-rhel-link <ide> <ide> <ide> ## Where to go next
7
Text
Text
add note about sproutcore guides to the readme
8a9c1a68188af818a3874a7ecba7a7683c5d0389
<ide><path>README.md <ide> For new users, we recommend downloading the [SproutCore Starter Kit](https://git <ide> <ide> We also recommend that you check out the [annotated Todos example](http://annotated-todos.strobeapp.com/), which shows you the best practices for architecting an MVC-based web application. <ide> <add>The [SproutCore Guides are available](http://guides.sproutcore20.com/) for SproutCore 2.0. If you find an error, please [fork the guides on GitHub](https://github.com/sproutcore/sproutguides/tree/v2.0) and submit a pull request. (Note that 2.0 guides are on the `v2.0` branch.) <add> <ide> To learn more about what we're up to, follow [@sproutcore on Twitter](http://twitter.com/sproutcore), [subscribe to the blog](http://blog.sproutcore.com), or [read the original SproutCore 2.0 announcement](http://blog.sproutcore.com/announcing-sproutcore-2-0/). <ide> <ide> # Building SproutCore 2.0
1
Ruby
Ruby
add arrandale to list of core2 cpus
3299ffe5904bb5d0664c7fd77119556570dd7704
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def setup_build_environment <ide> # http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/i386-and-x86_002d64-Options.html <ide> if MACOS_VERSION >= 10.6 <ide> case Hardware.intel_family <del> when :nehalem, :penryn, :core2 <add> when :nehalem, :penryn, :core2, :arrandale <ide> # the 64 bit compiler adds -mfpmath=sse for us <ide> cflags << "-march=core2" <ide> when :core
1
Text
Text
remove extra changelog added by
a72bc8f0043d1dd43da2654e4b0d4c1585f9b420
<ide><path>activesupport/CHANGELOG.md <ide> <ide> *Tomas Valent* <ide> <del>* Return all mappings for a timezone identifier in `country_zones` <del> <del> Some timezones like `Europe/London` have multiple mappings in <del> `ActiveSupport::TimeZone::MAPPING` so return all of them instead <del> of the first one found by using `Hash#value`. e.g: <del> <del> # Before <del> ActiveSupport::TimeZone.country_zones("GB") # => ["Edinburgh"] <del> <del> # After <del> ActiveSupport::TimeZone.country_zones("GB") # => ["Edinburgh", "London"] <del> <del> Fixes #31668. <del> <del> *Andrew White* <del> <ide> * `String#truncate_bytes` to truncate a string to a maximum bytesize without <ide> breaking multibyte characters or grapheme clusters like 👩‍👩‍👦‍👦. <ide>
1
Ruby
Ruby
move extra stdenv setup to extended callback
d09e23c8b1df7404d95b963e53bef3d1936a921a
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def activate_extensions! <ide> extend(Superenv) <ide> else <ide> extend(HomebrewEnvExtension) <del> prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin' <ide> end <ide> end <ide> end <ide> module HomebrewEnvExtension <ide> FC_FLAG_VARS = %w{FCFLAGS FFLAGS} <ide> DEFAULT_FLAGS = '-march=core2 -msse4' <ide> <add> def self.extended(base) <add> unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin' <add> base.prepend_path 'PATH', "#{HOMEBREW_PREFIX}/bin" <add> end <add> end <add> <ide> def setup_build_environment <ide> # Clear CDPATH to avoid make issues that depend on changing directories <ide> delete('CDPATH')
1
PHP
PHP
shorten variable name
f35fd194e2789c7873783587d4c6bd9b92ded067
<ide><path>src/View/Form/ContextFactory.php <ide> class ContextFactory <ide> * <ide> * @var array <ide> */ <del> protected $contextProviders = []; <add> protected $providers = []; <ide> <ide> /** <ide> * Constructor. <ide> public static function createWithDefaults(array $providers = []) <ide> */ <ide> public function addProvider($type, callable $check) <ide> { <del> $this->contextProviders = [$type => ['type' => $type, 'callable' => $check]] <del> + $this->contextProviders; <add> $this->providers = [$type => ['type' => $type, 'callable' => $check]] <add> + $this->providers; <ide> } <ide> <ide> /** <ide> public function get(ServerRequest $request, array $data = []) <ide> { <ide> $data += ['entity' => null]; <ide> <del> foreach ($this->contextProviders as $provider) { <add> foreach ($this->providers as $provider) { <ide> $check = $provider['callable']; <ide> $context = $check($request, $data); <ide> if ($context) {
1
Javascript
Javascript
lowerize the params to allow case sensitive
4623f202215597a21d87d027526182d002618f13
<ide><path>web/viewer.js <ide> var PDFView = { <ide> var params = {}; <ide> for (var i = 0, ii = parts.length; i < ii; ++i) { <ide> var param = parts[i].split('='); <del> var key = param[0]; <add> var key = param[0].toLowerCase(); <ide> var value = param.length > 1 ? param[1] : null; <ide> params[decodeURIComponent(key)] = decodeURIComponent(value); <ide> }
1
Java
Java
simplify conversion of databuffer to string
f17b0125ff8a93a996882915fdda4df85cba15f8
<ide><path>spring-core/src/main/java/org/springframework/core/io/buffer/DefaultDataBuffer.java <ide> public DefaultDataBuffer capacity(int newCapacity) { <ide> if (newCapacity > oldCapacity) { <ide> ByteBuffer oldBuffer = this.byteBuffer; <ide> ByteBuffer newBuffer = allocate(newCapacity, oldBuffer.isDirect()); <del> ((Buffer) oldBuffer).position(0).limit(oldBuffer.capacity()); <del> ((Buffer) newBuffer).position(0).limit(oldBuffer.capacity()); <add> oldBuffer.position(0).limit(oldBuffer.capacity()); <add> newBuffer.position(0).limit(oldBuffer.capacity()); <ide> newBuffer.put(oldBuffer); <ide> newBuffer.clear(); <ide> setNativeBuffer(newBuffer); <ide> else if (newCapacity < oldCapacity) { <ide> writePosition = newCapacity; <ide> writePosition(writePosition); <ide> } <del> ((Buffer) oldBuffer).position(readPosition).limit(writePosition); <del> ((Buffer) newBuffer).position(readPosition).limit(writePosition); <add> oldBuffer.position(readPosition).limit(writePosition); <add> newBuffer.position(readPosition).limit(writePosition); <ide> newBuffer.put(oldBuffer); <ide> newBuffer.clear(); <ide> } <ide> public DefaultDataBuffer read(byte[] destination, int offset, int length) { <ide> <ide> ByteBuffer tmp = this.byteBuffer.duplicate(); <ide> int limit = this.readPosition + length; <del> ((Buffer) tmp).clear().position(this.readPosition).limit(limit); <add> tmp.clear().position(this.readPosition).limit(limit); <ide> tmp.get(destination, offset, length); <ide> <ide> this.readPosition += length; <ide> public DefaultDataBuffer write(byte[] source, int offset, int length) { <ide> <ide> ByteBuffer tmp = this.byteBuffer.duplicate(); <ide> int limit = this.writePosition + length; <del> ((Buffer) tmp).clear().position(this.writePosition).limit(limit); <add> tmp.clear().position(this.writePosition).limit(limit); <ide> tmp.put(source, offset, length); <ide> <ide> this.writePosition += length; <ide> private void write(ByteBuffer source) { <ide> int length = source.remaining(); <ide> ByteBuffer tmp = this.byteBuffer.duplicate(); <ide> int limit = this.writePosition + source.remaining(); <del> ((Buffer) tmp).clear().position(this.writePosition).limit(limit); <add> tmp.clear().position(this.writePosition).limit(limit); <ide> tmp.put(source); <ide> this.writePosition += length; <ide> } <ide> public DefaultDataBuffer slice(int index, int length) { <ide> buffer.position(index); <ide> ByteBuffer slice = this.byteBuffer.slice(); <ide> // Explicit cast for compatibility with covariant return type on JDK 9's ByteBuffer <del> ((Buffer) slice).limit(length); <add> slice.limit(length); <ide> return new SlicedDefaultDataBuffer(slice, this.dataBufferFactory, length); <ide> } <ide> finally { <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/codec/AbstractEncoderTests.java <ide> protected final Consumer<DataBuffer> expectBytes(byte[] expected) { <ide> */ <ide> protected Consumer<DataBuffer> expectString(String expected) { <ide> return dataBuffer -> { <del> byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; <del> dataBuffer.read(resultBytes); <add> String actual = dataBuffer.toString(UTF_8); <ide> release(dataBuffer); <del> String actual = new String(resultBytes, UTF_8); <ide> assertThat(actual).isEqualTo(expected); <ide> }; <ide> <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/DataBufferTestUtils.java <ide> public static byte[] dumpBytes(DataBuffer buffer) { <ide> * @return the string representation of the given data buffer <ide> */ <ide> public static String dumpString(DataBuffer buffer, Charset charset) { <add> Assert.notNull(buffer, "'buffer' must not be null"); <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = dumpBytes(buffer); <del> return new String(bytes, charset); <add> return buffer.toString(charset); <ide> } <ide> <ide> } <ide><path>spring-test/src/main/java/org/springframework/mock/http/client/reactive/MockClientHttpRequest.java <ide> */ <ide> public class MockClientHttpRequest extends AbstractClientHttpRequest { <ide> <del> private HttpMethod httpMethod; <add> private final HttpMethod httpMethod; <ide> <del> private URI url; <add> private final URI url; <ide> <ide> private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); <ide> <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String bufferToString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <del> return new String(bytes, charset); <add> return buffer.toString(charset); <ide> } <ide> <ide> } <ide><path>spring-test/src/main/java/org/springframework/mock/http/client/reactive/MockClientHttpResponse.java <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String dumpString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <del> return new String(bytes, charset); <add> return buffer.toString(charset); <ide> } <ide> <ide> private Charset getCharset() { <ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String bufferToString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <add> String str = buffer.toString(charset); <ide> DataBufferUtils.release(buffer); <del> return new String(bytes, charset); <add> return str; <ide> } <ide> <ide> } <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/http/client/reactive/MockClientHttpRequest.java <ide> */ <ide> public class MockClientHttpRequest extends AbstractClientHttpRequest { <ide> <del> private HttpMethod httpMethod; <add> private final HttpMethod httpMethod; <ide> <del> private URI url; <add> private final URI url; <ide> <ide> private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); <ide> <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String bufferToString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <del> return new String(bytes, charset); <add> return buffer.toString(charset); <ide> } <ide> <ide> } <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/http/client/reactive/MockClientHttpResponse.java <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String dumpString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <del> return new String(bytes, charset); <add> return buffer.toString(charset); <ide> } <ide> <ide> private Charset getCharset() { <ide><path>spring-web/src/testFixtures/java/org/springframework/web/testfixture/http/server/reactive/MockServerHttpResponse.java <ide> public Mono<String> getBodyAsString() { <ide> <ide> private static String bufferToString(DataBuffer buffer, Charset charset) { <ide> Assert.notNull(charset, "'charset' must not be null"); <del> byte[] bytes = new byte[buffer.readableByteCount()]; <del> buffer.read(bytes); <add> String s = buffer.toString(charset); <ide> DataBufferUtils.release(buffer); <del> return new String(bytes, charset); <add> return s; <ide> } <ide> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/WebSocketMessage.java <ide> public String getPayloadAsText() { <ide> * @since 5.0.5 <ide> */ <ide> public String getPayloadAsText(Charset charset) { <del> byte[] bytes = new byte[this.payload.readableByteCount()]; <del> this.payload.read(bytes); <del> return new String(bytes, charset); <add> return this.payload.toString(charset); <ide> } <ide> <ide> /**
10
Python
Python
remove unnecessary multiplication
dc6b8df8d1025c522a2877bb06547d143f481cc6
<ide><path>numpy/lib/function_base.py <ide> def angle(z, deg=0): <ide> 45.0 <ide> <ide> """ <del> if deg: <del> fact = 180/pi <del> else: <del> fact = 1.0 <ide> z = asarray(z) <ide> if (issubclass(z.dtype.type, _nx.complexfloating)): <ide> zimag = z.imag <ide> zreal = z.real <ide> else: <ide> zimag = 0 <ide> zreal = z <del> return arctan2(zimag, zreal) * fact <add> <add> a = arctan2(zimag, zreal) <add> if deg: <add> a *= 180/pi <add> return a <ide> <ide> <ide> def unwrap(p, discont=pi, axis=-1):
1
Python
Python
add missing driver argument to libclouderror class
c690a0efb333062e6ec3e79cfc86f4e131648868
<ide><path>libcloud/compute/drivers/vsphere.py <ide> def __init__(self, host, username, password, port=443, ca_cert=None): <ide> if 'connection refused' in error_message or 'is not a vim server' \ <ide> in error_message: <ide> raise LibcloudError('Check that the host provided is a ' <del> 'vSphere installation') <add> 'vSphere installation', <add> driver=self) <ide> if 'name or service not known' in error_message: <ide> raise LibcloudError( <del> 'Check that the vSphere host is accessible') <add> 'Check that the vSphere host is accessible', <add> driver=self) <ide> if 'certificate verify failed' in error_message: <ide> # bypass self signed certificates <ide> try: <ide> def __init__(self, host, username, password, port=443, ca_cert=None): <ide> ) <ide> atexit.register(connect.Disconnect, self.connection) <ide> else: <del> raise LibcloudError('Cannot connect to vSphere') <add> raise LibcloudError('Cannot connect to vSphere', <add> driver=self) <ide> <ide> def list_locations(self, ex_show_hosts_in_drs=True): <ide> """ <ide> def ex_remove_snapshot(self, node, snapshot_name=None, <ide> vm = self.find_by_uuid(node.id) <ide> if not vm.snapshot: <ide> raise LibcloudError( <del> "Remove snapshot failed. No snapshots for node %s" % node.name) <add> "Remove snapshot failed. No snapshots for node %s" % node.name, <add> driver=self) <ide> snapshots = recurse_snapshots(vm.snapshot.rootSnapshotList) <ide> if not snapshot_name: <ide> snapshot = snapshots[-1].snapshot <ide> def ex_remove_snapshot(self, node, snapshot_name=None, <ide> snapshot = s.snapshot <ide> break <ide> else: <del> raise LibcloudError("Snapshot `%s` not found" % snapshot_name) <add> raise LibcloudError("Snapshot `%s` not found" % snapshot_name, <add> driver=self) <ide> return self.wait_for_task(snapshot.RemoveSnapshot_Task( <ide> removeChildren=remove_children)) <ide> <ide> def ex_revert_to_snapshot(self, node, snapshot_name=None): <ide> vm = self.find_by_uuid(node.id) <ide> if not vm.snapshot: <ide> raise LibcloudError("Revert failed. No snapshots " <del> "for node %s" % node.name) <add> "for node %s" % node.name, <add> driver=self) <ide> snapshots = recurse_snapshots(vm.snapshot.rootSnapshotList) <ide> if not snapshot_name: <ide> snapshot = snapshots[-1].snapshot <ide> def ex_revert_to_snapshot(self, node, snapshot_name=None): <ide> snapshot = s.snapshot <ide> break <ide> else: <del> raise LibcloudError("Snapshot `%s` not found" % snapshot_name) <add> raise LibcloudError("Snapshot `%s` not found" % snapshot_name, <add> driver=self) <ide> return self.wait_for_task(snapshot.RevertToSnapshot_Task()) <ide> <ide> def _find_template_by_uuid(self, template_uuid): <ide> def _find_template_by_uuid(self, template_uuid): <ide> if vm.config.instanceUuid == template_uuid: <ide> template = vm <ide> except Exception as exc: <del> raise LibcloudError("Error while searching for template, ", exc) <add> raise LibcloudError("Error while searching for template: %s" % exc, <add> driver=self) <ide> if not template: <del> raise LibcloudError("Unable to locate VirtualMachine.") <add> raise LibcloudError("Unable to locate VirtualMachine.", <add> driver=self) <ide> <ide> return template <ide> <ide> def find_by_uuid(self, node_uuid): <ide> # perhaps it is a moid <ide> vm = self._get_item_by_moid('VirtualMachine', node_uuid) <ide> if not vm: <del> raise LibcloudError("Unable to locate VirtualMachine.") <add> raise LibcloudError("Unable to locate VirtualMachine.", <add> driver=self) <ide> return vm <ide> <ide> def find_custom_field_key(self, key_id): <ide> def wait_for_task(self, task, timeout=1800, interval=10): <ide> if (time.time() - start_time >= timeout): <ide> raise LibcloudError('Timeout while waiting ' <ide> 'for import task Id %s' <del> % task.info.id) <add> % task.info.id, <add> driver=self) <ide> if task.info.state == 'success': <ide> if task.info.result and str(task.info.result) != 'success': <ide> return task.info.result <ide> return True <ide> <ide> if task.info.state == 'error': <del> raise LibcloudError(task.info.error.msg) <add> raise LibcloudError(task.info.error.msg, driver=self) <ide> time.sleep(interval) <ide> <ide> def create_node(self, name, image, size, location=None, ex_cluster=None,
1
Ruby
Ruby
use relations to build uniqueness conditions
4a7a14b0e15e07dbc4e49cfdd0694c17f81cfad0
<ide><path>activerecord/lib/active_record/validations/uniqueness.rb <ide> def initialize(options) <ide> <ide> def validate_each(record, attribute, value) <ide> finder_class = find_finder_class_for(record) <add> table = finder_class.active_relation <add> <ide> table_name = record.class.quoted_table_name <ide> sql, params = mount_sql_and_params(finder_class, table_name, attribute, value) <ide> <add> relation = table.where(sql, *params) <add> <ide> Array(options[:scope]).each do |scope_item| <ide> scope_value = record.send(scope_item) <del> sql << " AND " << record.class.send(:attribute_condition, "#{table_name}.#{scope_item}", scope_value) <del> params << scope_value <add> relation = relation.where(scope_item => scope_value) <ide> end <ide> <ide> unless record.new_record? <del> sql << " AND #{record.class.quoted_table_name}.#{record.class.primary_key} <> ?" <del> params << record.send(:id) <add> # TODO : This should be in Arel <add> relation = relation.where("#{record.class.quoted_table_name}.#{record.class.primary_key} <> ?", record.send(:id)) <ide> end <ide> <del> finder_class.send(:with_exclusive_scope) do <del> if finder_class.exists?([sql, *params]) <del> record.errors.add(attribute, :taken, :default => options[:message], :value => value) <del> end <add> if relation.exists? <add> record.errors.add(attribute, :taken, :default => options[:message], :value => value) <ide> end <ide> end <ide>
1
Text
Text
update readme about where to put new chart types
f81d6f45e19da797def2709551ef2fde2d1c1a1d
<ide><path>README.md <ide> Chart.js is available under the [MIT license](http://opensource.org/licenses/MIT <ide> <ide> When reporting bugs or issues, if you could include a link to a simple [jsbin](http://jsbin.com) or similar demonstrating the issue, that'd be really helpful. <ide> <del>This project is modular and supports separately-maintained new chart types. This project's scope includes only the chart types included. New chart types will be considered for inclusion in the project if they incude passing build tests and have complete documentation. Please discuss new or "missing" chart types in the [Chart.js User Discussion](https://groups.google.com/forum/#!forum/chartjs-user-discussion) Google Group and not in Issues. For more information, please also see the CONTRIBUTING file. <add>This project is modular and supports separately-maintained new chart types. This project's scope includes only the chart types included. New chart types should be created and maintained in separate repositories. We may consider linking to them from this project if they incude passing build tests and have complete documentation. Please discuss new or "missing" chart types in the [Chart.js User Discussion](https://groups.google.com/forum/#!forum/chartjs-user-discussion) Google Group and not in Issues. For more information, please also see the CONTRIBUTING file.
1
Ruby
Ruby
simplify client connection closing
662c064334638cfb783e2588c64342fe753f8c63
<ide><path>lib/action_cable/connection/base.rb <ide> def process <ide> @websocket.on(:close) do |event| <ide> logger.info "[ActionCable] #{finished_request_message}" <ide> <del> worker_pool.async.invoke(self, :cleanup_subscriptions) <del> worker_pool.async.invoke(self, :cleanup_internal_redis_subscriptions) <del> worker_pool.async.invoke(self, :disconnect) if respond_to?(:disconnect) <del> <add> worker_pool.async.invoke(self, :close_client_connection) <ide> EventMachine.cancel_timer(@ping_timer) if @ping_timer <ide> end <ide> <ide> def initialize_client <ide> worker_pool.async.invoke(self, :received_data, @pending_messages.shift) until @pending_messages.empty? <ide> end <ide> <add> def close_client_connection <add> cleanup_subscriptions <add> cleanup_internal_redis_subscriptions <add> disconnect if respond_to?(:disconnect) <add> end <add> <ide> def broadcast_ping_timestamp <ide> broadcast({ identifier: '_ping', message: Time.now.to_i }.to_json) <ide> end
1
PHP
PHP
fix deprecation issue with translator
f6e9f54385f167a17b25445f8d855e754a4f50d6
<ide><path>src/Illuminate/Translation/Translator.php <ide> protected function makeReplacements($line, array $replace) <ide> $shouldReplace = []; <ide> <ide> foreach ($replace as $key => $value) { <del> $shouldReplace[':'.Str::ucfirst($key)] = Str::ucfirst($value); <del> $shouldReplace[':'.Str::upper($key)] = Str::upper($value); <add> $shouldReplace[':'.Str::ucfirst($key ?? '')] = Str::ucfirst($value ?? ''); <add> $shouldReplace[':'.Str::upper($key ?? '')] = Str::upper($value ?? ''); <ide> $shouldReplace[':'.$key] = $value; <ide> } <ide> <ide><path>tests/Translation/TranslationTranslatorTest.php <ide> public function testGetJsonForNonExistingReturnsSameKeyAndReplaces() <ide> $this->assertSame('foo baz', $t->get('foo :message', ['message' => 'baz'])); <ide> } <ide> <add> public function testEmptyFallbacks() <add> { <add> $t = new Translator($this->getLoader(), 'en'); <add> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]); <add> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo :message', '*')->andReturn([]); <add> $this->assertSame('foo ', $t->get('foo :message', ['message' => null])); <add> } <add> <ide> protected function getLoader() <ide> { <ide> return m::mock(Loader::class);
2
Python
Python
update example scripts
3fd71c4431f2b31eaad737d364e4a4d9bf35fd5b
<ide><path>examples/distillation/distiller.py <ide> def __init__(self, <ide> self.last_log = 0 <ide> <ide> self.ce_loss_fct = nn.KLDivLoss(reduction='batchmean') <del> self.lm_loss_fct = nn.CrossEntropyLoss(ignore_index=-1) <add> self.lm_loss_fct = nn.CrossEntropyLoss(ignore_index=-100) <ide> if self.alpha_mse > 0.: <ide> self.mse_loss_fct = nn.MSELoss(reduction='sum') <ide> if self.alpha_cos > 0.: <ide> def prepare_batch_mlm(self, <ide> _token_ids = _token_ids_mask * (probs == 0).long() + _token_ids_real * (probs == 1).long() + _token_ids_rand * (probs == 2).long() <ide> token_ids = token_ids.masked_scatter(pred_mask, _token_ids) <ide> <del> mlm_labels[~pred_mask] = -1 # previously `mlm_labels[1-pred_mask] = -1`, cf pytorch 1.2.0 compatibility <add> mlm_labels[~pred_mask] = -100 # previously `mlm_labels[1-pred_mask] = -1`, cf pytorch 1.2.0 compatibility <ide> <ide> # sanity checks <ide> assert 0 <= token_ids.min() <= token_ids.max() < self.vocab_size <ide> def prepare_batch_clm(self, <ide> <ide> attn_mask = (torch.arange(token_ids.size(1), dtype=torch.long, device=lengths.device) < lengths[:, None]) <ide> clm_labels = token_ids.new(token_ids.size()).copy_(token_ids) <del> clm_labels[~attn_mask] = -1 # previously `clm_labels[1-attn_mask] = -1`, cf pytorch 1.2.0 compatibility <add> clm_labels[~attn_mask] = -100 # previously `clm_labels[1-attn_mask] = -1`, cf pytorch 1.2.0 compatibility <ide> <ide> # sanity checks <ide> assert 0 <= token_ids.min() <= token_ids.max() < self.vocab_size <ide><path>examples/utils_ner.py <ide> def convert_examples_to_features(examples, <ide> pad_on_left=False, <ide> pad_token=0, <ide> pad_token_segment_id=0, <del> pad_token_label_id=-1, <add> pad_token_label_id=-100, <ide> sequence_a_segment_id=0, <ide> mask_padding_with_zero=True): <ide> """ Loads a data file into a list of `InputBatch`s
2
Ruby
Ruby
fix actionmailer test issues
1e4be20672252ac15a355589dd44bdd4623640c4
<ide><path>actionmailer/test/old_base/mail_service_test.rb <ide> def setup <ide> <ide> @original_logger = TestMailer.logger <ide> @recipient = 'test@localhost' <add> <add> TestMailer.delivery_method = :test <ide> end <ide> <ide> def teardown <ide> def test_should_still_raise_exception_with_expected_message_when_calling_an_unde <ide> RespondToMailer.not_a_method <ide> end <ide> <del> assert_match(/undefined method.*not_a_method/, error.message) <add> assert_match(/method.*not_a_method/, error.message) <ide> end <del>end <ide>\ No newline at end of file <add>end
1
Ruby
Ruby
change numericaly validator to use round
6657e3428b1dff30df78b42c1304dde35fc4de4a
<ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> def parse_as_number(raw_value, precision, scale, option = nil) <ide> raw_value if raw_value.is_a?(Range) <ide> elsif raw_value.is_a?(Float) <ide> parse_float(raw_value, precision, scale) <add> elsif raw_value.is_a?(BigDecimal) <add> round(raw_value, scale) <ide> elsif raw_value.is_a?(Numeric) <ide> raw_value <ide> elsif is_integer?(raw_value) <ide> def parse_as_number(raw_value, precision, scale, option = nil) <ide> end <ide> <ide> def parse_float(raw_value, precision, scale) <del> (scale ? raw_value.truncate(scale) : raw_value).to_d(precision) <add> round(raw_value, scale).to_d(precision) <add> end <add> <add> def round(raw_value, scale) <add> scale ? raw_value.round(scale) : raw_value <ide> end <ide> <ide> def is_number?(raw_value, precision, scale) <ide><path>activerecord/test/cases/validations/numericality_validation_test.rb <ide> def test_virtual_attribute_with_scale <ide> assert_not_predicate subject, :valid? <ide> end <ide> <add> def test_virtual_attribute_with_precision_and_scale <add> model_class.attribute(:virtual_decimal_number, :decimal, precision: 4, scale: 2) <add> model_class.validates_numericality_of( <add> :virtual_decimal_number, less_than_or_equal_to: 99.99 <add> ) <add> <add> subject = model_class.new(virtual_decimal_number: 99.994) <add> assert_equal 99.99.to_d(4), subject.virtual_decimal_number <add> assert_predicate subject, :valid? <add> <add> subject = model_class.new(virtual_decimal_number: 99.999) <add> assert_equal 100.00.to_d(4), subject.virtual_decimal_number <add> assert_not_predicate subject, :valid? <add> end <add> <ide> def test_aliased_attribute <ide> model_class.validates_numericality_of(:new_bank_balance, greater_or_equal_than: 0) <ide> <ide><path>activerecord/test/cases/validations_test.rb <ide> def self.model_name <ide> validates_numericality_of :wibble, greater_than_or_equal_to: BigDecimal("97.18") <ide> end <ide> <del> assert_not_predicate klass.new(wibble: "97.179"), :valid? <del> assert_not_predicate klass.new(wibble: 97.179), :valid? <del> assert_not_predicate klass.new(wibble: BigDecimal("97.179")), :valid? <add> ["97.179", 97.179, BigDecimal("97.179")].each do |raw_value| <add> subject = klass.new(wibble: raw_value) <add> assert_equal 97.18.to_d(4), subject.wibble <add> assert_predicate subject, :valid? <add> end <add> <add> ["97.174", 97.174, BigDecimal("97.174")].each do |raw_value| <add> subject = klass.new(wibble: raw_value) <add> assert_equal 97.17.to_d(4), subject.wibble <add> assert_not_predicate subject, :valid? <add> end <ide> end <ide> <ide> def test_numericality_validator_wont_be_affected_by_custom_getter
3
Text
Text
add zerodha to airflow users list
fc5390dcd27734a8b3ec28109db273e4ca25fa31
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [Zego](https://www.zego.com/) [[@ruimffl](https://github.com/ruimffl), [@james-welly](https://github.com/james-welly), [@ken-payne](https://github.com/ken-payne)] <ide> 1. [Zendesk](https://www.github.com/zendesk) <ide> 1. [Zenly](https://zen.ly) [[@cerisier](https://github.com/cerisier) & [@jbdalido](https://github.com/jbdalido)] <add>1. [Zerodha](https://zerodha.com/) [[@johnnybravo-xyz](https://github.com/johnnybravo-xyz)] <ide> 1. [Zymergen](https://www.zymergen.com/) <ide> 1. [Zynga](https://www.zynga.com) <ide>
1
Text
Text
fix typo in upgrading_ruby_on_rails.md
9e18326de8d532718d46dc9437188af0d06ace1c
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> FFmpeg v3.4+. <ide> <ide> For new apps, image transformation will use libvips instead of ImageMagick. This will reduce <ide> the time taken to generate variants as well as CPU and memory usage, improving response <del>times in apps that rely on active storage to serve their images. <add>times in apps that rely on Active Storage to serve their images. <ide> <ide> The `:mini_magick` option is not being deprecated, so it is fine to keep using it. <ide>
1
Text
Text
add license information to model cards
55adefe42813d68338d0f6b8b777eb2e2097d747
<ide><path>model_cards/albert-base-v1-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=albert-base-v1"> <ide><path>model_cards/albert-xxlarge-v2-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=albert-xxlarge-v2"> <ide><path>model_cards/bert-base-cased-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=bert-base-cased"> <ide><path>model_cards/bert-base-chinese-README.md <add>--- <add>language: chinese <add>--- <ide><path>model_cards/bert-base-german-dbmdz-cased-README.md <add>--- <add>language: german <add>license: mit <add>--- <ide><path>model_cards/bert-base-german-dbmdz-uncased-README.md <add>--- <add>language: german <add>license: mit <add>--- <ide><path>model_cards/bert-base-multilingual-cased-README.md <add>--- <add>language: multilingual <add> <add>license: apache-2.0 <add>--- <ide><path>model_cards/bert-base-multilingual-uncased-README.md <add>--- <add>language: multilingual <add> <add>license: apache-2.0 <add>--- <ide><path>model_cards/bert-base-uncased-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=bert-base-uncased"> <ide><path>model_cards/bert-large-cased-README.md <add>--- <add>license: apache-2.0 <add>--- <ide><path>model_cards/camembert-base-README.md <ide> --- <ide> language: french <add> <add>license: mit <ide> --- <ide> <ide> # CamemBERT: a Tasty French Language Model <ide><path>model_cards/distilbert-base-multilingual-cased-README.md <add>--- <add>language: multilingual <add>license: apache-2.0 <add>--- <ide><path>model_cards/distilbert-base-uncased-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=distilbert-base-uncased"> <ide><path>model_cards/distilgpt2-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=distilgpt2"> <ide><path>model_cards/distilroberta-base-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: apache-2.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=distilroberta-base"> <ide><path>model_cards/google/electra-base-discriminator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/google/electra-base-generator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/google/electra-large-discriminator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/google/electra-large-generator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/google/electra-small-discriminator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/google/electra-small-generator/README.md <ide> --- <ide> language: english <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> ## ELECTRA: Pre-training Text Encoders as Discriminators Rather Than Generators <ide><path>model_cards/gpt2-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: mit <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=gpt2"> <ide><path>model_cards/iuliaturc/bert_uncased_L-2_H-128_A-2/README.md <ide> --- <ide> thumbnail: https://huggingface.co/front/thumbnails/google.png <add> <add>license: apache-2.0 <ide> --- <ide> <ide> BERT Miniatures <ide><path>model_cards/microsoft/DialoGPT-large/README.md <ide> thumbnail: https://huggingface.co/front/thumbnails/dialogpt.png <ide> tags: <ide> - conversational <add>license: mit <ide> --- <ide> <ide> ## A State-of-the-Art Large-scale Pretrained Response generation model (DialoGPT) <ide><path>model_cards/microsoft/DialoGPT-medium/README.md <ide> thumbnail: https://huggingface.co/front/thumbnails/dialogpt.png <ide> tags: <ide> - conversational <add>license: mit <ide> --- <ide> <ide> ## A State-of-the-Art Large-scale Pretrained Response generation model (DialoGPT) <ide><path>model_cards/microsoft/DialoGPT-small/README.md <ide> thumbnail: https://huggingface.co/front/thumbnails/dialogpt.png <ide> tags: <ide> - conversational <add>license: mit <ide> --- <ide> <ide> ## A State-of-the-Art Large-scale Pretrained Response generation model (DialoGPT) <ide><path>model_cards/roberta-base-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: mit <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=roberta-base"> <ide><path>model_cards/t5-11b-README.md <ide> tags: <ide> - summarization <ide> - translation <add> <add>license: apache-2.0 <ide> --- <ide> <ide><path>model_cards/t5-3b-README.md <ide> tags: <ide> - summarization <ide> - translation <add> <add>license: apache-2.0 <ide> --- <ide> <ide><path>model_cards/t5-base-README.md <ide> tags: <ide> - summarization <ide> - translation <add> <add>license: apache-2.0 <ide> --- <ide> <ide><path>model_cards/t5-large-README.md <ide> tags: <ide> - summarization <ide> - translation <add> <add>license: apache-2.0 <ide> --- <ide> <ide><path>model_cards/t5-small-README.md <ide> tags: <ide> - summarization <ide> - translation <add> <add>license: apache-2.0 <ide> --- <ide> <ide><path>model_cards/xlm-mlm-en-2048-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: cc-by-nc-4.0 <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=xlm-mlm-en-2048"> <ide><path>model_cards/xlm-roberta-base-README.md <ide> --- <ide> tags: <ide> - exbert <add> <add>license: mit <ide> --- <ide> <ide> <a href="https://huggingface.co/exbert/?model=xlm-roberta-base">
34
Mixed
Javascript
add deep linking support to intentandroid
eb188c8d98fa08686c6b9335e3dcbefe3f524b7e
<ide><path>Libraries/Components/Intent/IntentAndroid.android.js <ide> var invariant = require('invariant'); <ide> /** <ide> * `IntentAndroid` gives you a general interface to handle external links. <ide> * <add> * ### Basic Usage <add> * <add> * #### Handling deep links <add> * <add> * If your app was launched from an external url registered to your app you can <add> * access and handle it from any component you want with <add> * <add> * ``` <add> * componentDidMount() { <add> * var url = IntentAndroid.getInitialURL(url => { <add> * if (url) { <add> * console.log('Initial url is: ' + url); <add> * } <add> * }); <add> * } <add> * ``` <add> * <add> * NOTE: For instructions on how to add support for deep linking, <add> * refer [Enabling Deep Links for App Content - Add Intent Filters for Your Deep Links](http://developer.android.com/training/app-indexing/deep-linking.html#adding-filters). <add> * <ide> * #### Opening external links <ide> * <ide> * To start the corresponding activity for a link (web URL, email, contact etc.), call <ide> class IntentAndroid { <ide> IntentAndroidModule.canOpenURL(url, callback); <ide> } <ide> <add> /** <add> * If the app launch was triggered by an app link with {@code Intent.ACTION_VIEW}, <add> * it will give the link url, otherwise it will give `null` <add> * <add> * Refer http://developer.android.com/training/app-indexing/deep-linking.html#handling-intents <add> */ <add> static getInitialURL(callback: Function) { <add> invariant( <add> typeof callback === 'function', <add> 'A valid callback function is required' <add> ); <add> IntentAndroidModule.getInitialURL(callback); <add> } <add> <ide> static _validateURL(url: string) { <ide> invariant( <ide> typeof url === 'string', <ide><path>ReactAndroid/src/main/java/com/facebook/react/modules/intent/IntentModule.java <ide> <ide> package com.facebook.react.modules.intent; <ide> <add>import android.app.Activity; <ide> import android.content.Intent; <ide> import android.net.Uri; <ide> <ide> import com.facebook.react.bridge.Callback; <add>import com.facebook.react.bridge.JSApplicationIllegalArgumentException; <ide> import com.facebook.react.bridge.ReactApplicationContext; <del>import com.facebook.react.bridge.ReactContext; <ide> import com.facebook.react.bridge.ReactContextBaseJavaModule; <ide> import com.facebook.react.bridge.ReactMethod; <del>import com.facebook.react.bridge.JSApplicationIllegalArgumentException; <ide> <ide> /** <ide> * Intent module. Launch other activities or open URLs. <ide> public String getName() { <ide> return "IntentAndroid"; <ide> } <ide> <add> /** <add> * Return the URL the activity was started with <add> * <add> * @param callback a callback which is called with the initial URL <add> */ <add> @ReactMethod <add> public void getInitialURL(Callback callback) { <add> try { <add> Activity currentActivity = getCurrentActivity(); <add> String initialURL = null; <add> <add> if (currentActivity != null) { <add> Intent intent = currentActivity.getIntent(); <add> String action = intent.getAction(); <add> Uri uri = intent.getData(); <add> <add> if (Intent.ACTION_VIEW.equals(action) && uri != null) { <add> initialURL = uri.toString(); <add> } <add> } <add> <add> callback.invoke(initialURL); <add> } catch (Exception e) { <add> throw new JSApplicationIllegalArgumentException( <add> "Could not get the initial URL : " + e.getMessage()); <add> } <add> } <add> <ide> /** <ide> * Starts a corresponding external activity for the given URL. <ide> * <ide> * For example, if the URL is "https://www.facebook.com", the system browser will be opened, <ide> * or the "choose application" dialog will be shown. <ide> * <del> * @param URL the URL to open <add> * @param url the URL to open <ide> */ <ide> @ReactMethod <ide> public void openURL(String url) { <ide> if (url == null || url.isEmpty()) { <ide> throw new JSApplicationIllegalArgumentException("Invalid URL: " + url); <ide> } <add> <ide> try { <add> Activity currentActivity = getCurrentActivity(); <ide> Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); <del> // We need Intent.FLAG_ACTIVITY_NEW_TASK since getReactApplicationContext() returns <del> // the ApplicationContext instead of the Activity context. <del> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); <del> getReactApplicationContext().startActivity(intent); <add> <add> if (currentActivity != null) { <add> currentActivity.startActivity(intent); <add> } else { <add> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); <add> getReactApplicationContext().startActivity(intent); <add> } <ide> } catch (Exception e) { <ide> throw new JSApplicationIllegalArgumentException( <ide> "Could not open URL '" + url + "': " + e.getMessage()); <ide> public void openURL(String url) { <ide> /** <ide> * Determine whether or not an installed app can handle a given URL. <ide> * <del> * @param URL the URL to open <del> * @param promise a promise that is always resolved with a boolean argument <add> * @param url the URL to open <add> * @param callback a callback that is always called with a boolean argument <ide> */ <ide> @ReactMethod <ide> public void canOpenURL(String url, Callback callback) { <ide> if (url == null || url.isEmpty()) { <ide> throw new JSApplicationIllegalArgumentException("Invalid URL: " + url); <ide> } <add> <ide> try { <ide> Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); <ide> // We need Intent.FLAG_ACTIVITY_NEW_TASK since getReactApplicationContext() returns <ide> // the ApplicationContext instead of the Activity context. <ide> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); <ide> boolean canOpen = <del> intent.resolveActivity(this.getReactApplicationContext().getPackageManager()) != null; <add> intent.resolveActivity(getReactApplicationContext().getPackageManager()) != null; <ide> callback.invoke(canOpen); <ide> } catch (Exception e) { <ide> throw new JSApplicationIllegalArgumentException(
2
Ruby
Ruby
fix args for --installed with no formula
4cfd80451a28977a8621fcedfd2ffdcc9f82f734
<ide><path>Library/Homebrew/cmd/deps.rb <ide> def deps <ide> if args.no_named? <ide> raise FormulaUnspecifiedError unless args.installed? <ide> <del> puts_deps sorted_dependents(Formula.installed + Cask::Caskroom.casks), recursive <add> puts_deps sorted_dependents(Formula.installed + Cask::Caskroom.casks), recursive, args: args <ide> return <ide> end <ide>
1
Go
Go
add new df subcomand to the system command
b650a7bd27dcdbb4cddbfdc2cf62f41b5a8e8652
<ide><path>cli/command/formatter/container.go <ide> const ( <ide> statusHeader = "STATUS" <ide> portsHeader = "PORTS" <ide> mountsHeader = "MOUNTS" <add> localVolumes = "LOCAL VOLUMES" <ide> ) <ide> <ide> // NewContainerFormat returns a Format for rendering using a Context <ide> func (c *containerContext) Mounts() string { <ide> } <ide> return strings.Join(mounts, ",") <ide> } <add> <add>func (c *containerContext) LocalVolumes() string { <add> c.AddHeader(localVolumes) <add> <add> count := 0 <add> for _, m := range c.c.Mounts { <add> if m.Driver == "local" { <add> count++ <add> } <add> } <add> <add> return fmt.Sprintf("%d", count) <add>} <ide><path>cli/command/formatter/disk_usage.go <add>package formatter <add> <add>import ( <add> "bytes" <add> "fmt" <add> "strings" <add> "text/template" <add> <add> "github.com/docker/distribution/reference" <add> "github.com/docker/docker/api/types" <add> units "github.com/docker/go-units" <add>) <add> <add>const ( <add> defaultDiskUsageImageTableFormat = "table {{.Repository}}\t{{.Tag}}\t{{.ID}}\t{{.CreatedSince}} ago\t{{.VirtualSize}}\t{{.SharedSize}}\t{{.UniqueSize}}\t{{.Containers}}" <add> defaultDiskUsageContainerTableFormat = "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.LocalVolumes}}\t{{.Size}}\t{{.RunningFor}} ago\t{{.Status}}\t{{.Names}}" <add> defaultDiskUsageVolumeTableFormat = "table {{.Name}}\t{{.Links}}\t{{.Size}}" <add> defaultDiskUsageTableFormat = "table {{.Type}}\t{{.TotalCount}}\t{{.Active}}\t{{.Size}}\t{{.Reclaimable}}" <add> <add> typeHeader = "TYPE" <add> totalHeader = "TOTAL" <add> activeHeader = "ACTIVE" <add> reclaimableHeader = "RECLAIMABLE" <add> containersHeader = "CONTAINERS" <add> sharedSizeHeader = "SHARED SIZE" <add> uniqueSizeHeader = "UNIQUE SiZE" <add>) <add> <add>// DiskUsageContext contains disk usage specific information required by the formater, encapsulate a Context struct. <add>type DiskUsageContext struct { <add> Context <add> Verbose bool <add> LayersSize int64 <add> Images []*types.Image <add> Containers []*types.Container <add> Volumes []*types.Volume <add>} <add> <add>func (ctx *DiskUsageContext) startSubsection(format string) (*template.Template, error) { <add> ctx.buffer = bytes.NewBufferString("") <add> ctx.header = "" <add> ctx.Format = Format(format) <add> ctx.preFormat() <add> <add> return ctx.parseFormat() <add>} <add> <add>func (ctx *DiskUsageContext) Write() { <add> if ctx.Verbose == false { <add> ctx.buffer = bytes.NewBufferString("") <add> ctx.Format = defaultDiskUsageTableFormat <add> ctx.preFormat() <add> <add> tmpl, err := ctx.parseFormat() <add> if err != nil { <add> return <add> } <add> <add> err = ctx.contextFormat(tmpl, &diskUsageImagesContext{ <add> totalSize: ctx.LayersSize, <add> images: ctx.Images, <add> }) <add> if err != nil { <add> return <add> } <add> err = ctx.contextFormat(tmpl, &diskUsageContainersContext{ <add> containers: ctx.Containers, <add> }) <add> if err != nil { <add> return <add> } <add> <add> err = ctx.contextFormat(tmpl, &diskUsageVolumesContext{ <add> volumes: ctx.Volumes, <add> }) <add> if err != nil { <add> return <add> } <add> <add> ctx.postFormat(tmpl, &diskUsageContainersContext{containers: []*types.Container{}}) <add> <add> return <add> } <add> <add> // First images <add> tmpl, err := ctx.startSubsection(defaultDiskUsageImageTableFormat) <add> if err != nil { <add> return <add> } <add> <add> ctx.Output.Write([]byte("Images space usage:\n\n")) <add> for _, i := range ctx.Images { <add> repo := "<none>" <add> tag := "<none>" <add> if len(i.RepoTags) > 0 && !isDangling(*i) { <add> // Only show the first tag <add> ref, err := reference.ParseNamed(i.RepoTags[0]) <add> if err != nil { <add> continue <add> } <add> if nt, ok := ref.(reference.NamedTagged); ok { <add> repo = ref.Name() <add> tag = nt.Tag() <add> } <add> } <add> <add> err = ctx.contextFormat(tmpl, &imageContext{ <add> repo: repo, <add> tag: tag, <add> trunc: true, <add> i: *i, <add> }) <add> if err != nil { <add> return <add> } <add> } <add> ctx.postFormat(tmpl, &imageContext{}) <add> <add> // Now containers <add> ctx.Output.Write([]byte("\nContainers space usage:\n\n")) <add> tmpl, err = ctx.startSubsection(defaultDiskUsageContainerTableFormat) <add> if err != nil { <add> return <add> } <add> for _, c := range ctx.Containers { <add> // Don't display the virtual size <add> c.SizeRootFs = 0 <add> err = ctx.contextFormat(tmpl, &containerContext{ <add> trunc: true, <add> c: *c, <add> }) <add> if err != nil { <add> return <add> } <add> } <add> ctx.postFormat(tmpl, &containerContext{}) <add> <add> // And volumes <add> ctx.Output.Write([]byte("\nLocal Volumes space usage:\n\n")) <add> tmpl, err = ctx.startSubsection(defaultDiskUsageVolumeTableFormat) <add> if err != nil { <add> return <add> } <add> for _, v := range ctx.Volumes { <add> err = ctx.contextFormat(tmpl, &volumeContext{ <add> v: *v, <add> }) <add> if err != nil { <add> return <add> } <add> } <add> ctx.postFormat(tmpl, &volumeContext{v: types.Volume{}}) <add>} <add> <add>type diskUsageImagesContext struct { <add> HeaderContext <add> totalSize int64 <add> images []*types.Image <add>} <add> <add>func (c *diskUsageImagesContext) Type() string { <add> c.AddHeader(typeHeader) <add> return "Images" <add>} <add> <add>func (c *diskUsageImagesContext) TotalCount() string { <add> c.AddHeader(totalHeader) <add> return fmt.Sprintf("%d", len(c.images)) <add>} <add> <add>func (c *diskUsageImagesContext) Active() string { <add> c.AddHeader(activeHeader) <add> used := 0 <add> for _, i := range c.images { <add> if i.Containers > 0 { <add> used++ <add> } <add> } <add> <add> return fmt.Sprintf("%d", used) <add>} <add> <add>func (c *diskUsageImagesContext) Size() string { <add> c.AddHeader(sizeHeader) <add> return units.HumanSize(float64(c.totalSize)) <add> <add>} <add> <add>func (c *diskUsageImagesContext) Reclaimable() string { <add> var used int64 <add> <add> c.AddHeader(reclaimableHeader) <add> for _, i := range c.images { <add> if i.Containers != 0 { <add> used += i.Size <add> } <add> } <add> <add> reclaimable := c.totalSize - used <add> if c.totalSize > 0 { <add> return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/c.totalSize) <add> } <add> return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable))) <add>} <add> <add>type diskUsageContainersContext struct { <add> HeaderContext <add> verbose bool <add> containers []*types.Container <add>} <add> <add>func (c *diskUsageContainersContext) Type() string { <add> c.AddHeader(typeHeader) <add> return "Containers" <add>} <add> <add>func (c *diskUsageContainersContext) TotalCount() string { <add> c.AddHeader(totalHeader) <add> return fmt.Sprintf("%d", len(c.containers)) <add>} <add> <add>func (c *diskUsageContainersContext) isActive(container types.Container) bool { <add> return strings.Contains(container.State, "running") || <add> strings.Contains(container.State, "paused") || <add> strings.Contains(container.State, "restarting") <add>} <add> <add>func (c *diskUsageContainersContext) Active() string { <add> c.AddHeader(activeHeader) <add> used := 0 <add> for _, container := range c.containers { <add> if c.isActive(*container) { <add> used++ <add> } <add> } <add> <add> return fmt.Sprintf("%d", used) <add>} <add> <add>func (c *diskUsageContainersContext) Size() string { <add> var size int64 <add> <add> c.AddHeader(sizeHeader) <add> for _, container := range c.containers { <add> size += container.SizeRw <add> } <add> <add> return units.HumanSize(float64(size)) <add>} <add> <add>func (c *diskUsageContainersContext) Reclaimable() string { <add> var reclaimable int64 <add> var totalSize int64 <add> <add> c.AddHeader(reclaimableHeader) <add> for _, container := range c.containers { <add> if !c.isActive(*container) { <add> reclaimable += container.SizeRw <add> } <add> totalSize += container.SizeRw <add> } <add> <add> if totalSize > 0 { <add> return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize) <add> } <add> <add> return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable))) <add>} <add> <add>type diskUsageVolumesContext struct { <add> HeaderContext <add> verbose bool <add> volumes []*types.Volume <add>} <add> <add>func (c *diskUsageVolumesContext) Type() string { <add> c.AddHeader(typeHeader) <add> return "Local Volumes" <add>} <add> <add>func (c *diskUsageVolumesContext) TotalCount() string { <add> c.AddHeader(totalHeader) <add> return fmt.Sprintf("%d", len(c.volumes)) <add>} <add> <add>func (c *diskUsageVolumesContext) Active() string { <add> c.AddHeader(activeHeader) <add> <add> used := 0 <add> for _, v := range c.volumes { <add> if v.RefCount > 0 { <add> used++ <add> } <add> } <add> <add> return fmt.Sprintf("%d", used) <add>} <add> <add>func (c *diskUsageVolumesContext) Size() string { <add> var size int64 <add> <add> c.AddHeader(sizeHeader) <add> for _, v := range c.volumes { <add> if v.Size != -1 { <add> size += v.Size <add> } <add> } <add> <add> return units.HumanSize(float64(size)) <add>} <add> <add>func (c *diskUsageVolumesContext) Reclaimable() string { <add> var reclaimable int64 <add> var totalSize int64 <add> <add> c.AddHeader(reclaimableHeader) <add> for _, v := range c.volumes { <add> if v.Size != -1 { <add> if v.RefCount == 0 { <add> reclaimable += v.Size <add> } <add> totalSize += v.Size <add> } <add> } <add> <add> if totalSize > 0 { <add> return fmt.Sprintf("%s (%v%%)", units.HumanSize(float64(reclaimable)), (reclaimable*100)/totalSize) <add> } <add> <add> return fmt.Sprintf("%s", units.HumanSize(float64(reclaimable))) <add>} <ide><path>cli/command/formatter/image.go <ide> package formatter <ide> <ide> import ( <add> "fmt" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types" <ide> func (c *imageContext) Size() string { <ide> //NOTE: For backward compatibility we need to return VirtualSize <ide> return units.HumanSizeWithPrecision(float64(c.i.VirtualSize), 3) <ide> } <add> <add>func (c *imageContext) Containers() string { <add> c.AddHeader(containersHeader) <add> if c.i.Containers == -1 { <add> return "N/A" <add> } <add> return fmt.Sprintf("%d", c.i.Containers) <add>} <add> <add>func (c *imageContext) VirtualSize() string { <add> c.AddHeader(sizeHeader) <add> return units.HumanSize(float64(c.i.VirtualSize)) <add>} <add> <add>func (c *imageContext) SharedSize() string { <add> c.AddHeader(sharedSizeHeader) <add> if c.i.SharedSize == -1 { <add> return "N/A" <add> } <add> return units.HumanSize(float64(c.i.SharedSize)) <add>} <add> <add>func (c *imageContext) UniqueSize() string { <add> c.AddHeader(uniqueSizeHeader) <add> if c.i.Size == -1 { <add> return "N/A" <add> } <add> return units.HumanSize(float64(c.i.Size)) <add>} <ide><path>cli/command/formatter/image_test.go <ide> func TestImageContext(t *testing.T) { <ide> trunc: false, <ide> }, imageID, imageIDHeader, ctx.ID}, <ide> {imageContext{ <del> i: types.Image{Size: 10}, <add> i: types.Image{Size: 10, VirtualSize: 10}, <ide> trunc: true, <ide> }, "10 B", sizeHeader, ctx.Size}, <ide> {imageContext{ <ide><path>cli/command/formatter/volume.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> units "github.com/docker/go-units" <ide> ) <ide> <ide> const ( <ide> defaultVolumeQuietFormat = "{{.Name}}" <ide> defaultVolumeTableFormat = "table {{.Driver}}\t{{.Name}}" <ide> <ide> mountpointHeader = "MOUNTPOINT" <add> linksHeader = "LINKS" <ide> // Status header ? <ide> ) <ide> <ide> func (c *volumeContext) Label(name string) string { <ide> } <ide> return c.v.Labels[name] <ide> } <add> <add>func (c *volumeContext) Links() string { <add> c.AddHeader(linksHeader) <add> if c.v.Size == -1 { <add> return "N/A" <add> } <add> return fmt.Sprintf("%d", c.v.RefCount) <add>} <add> <add>func (c *volumeContext) Size() string { <add> c.AddHeader(sizeHeader) <add> if c.v.Size == -1 { <add> return "N/A" <add> } <add> return units.HumanSize(float64(c.v.Size)) <add>} <ide><path>cli/command/system/cmd.go <ide> func NewSystemCommand(dockerCli *command.DockerCli) *cobra.Command { <ide> cmd.AddCommand( <ide> NewEventsCommand(dockerCli), <ide> NewInfoCommand(dockerCli), <add> NewDiskUsageCommand(dockerCli), <ide> NewPruneCommand(dockerCli), <ide> ) <ide> return cmd <ide><path>cli/command/system/df.go <add>package system <add> <add>import ( <add> "github.com/docker/docker/cli" <add> "github.com/docker/docker/cli/command" <add> "github.com/docker/docker/cli/command/formatter" <add> "github.com/spf13/cobra" <add> "golang.org/x/net/context" <add>) <add> <add>type diskUsageOptions struct { <add> verbose bool <add>} <add> <add>// NewDiskUsageCommand creates a new cobra.Command for `docker df` <add>func NewDiskUsageCommand(dockerCli *command.DockerCli) *cobra.Command { <add> var opts diskUsageOptions <add> <add> cmd := &cobra.Command{ <add> Use: "df [OPTIONS]", <add> Short: "Show docker disk usage", <add> Args: cli.RequiresMaxArgs(1), <add> RunE: func(cmd *cobra.Command, args []string) error { <add> return runDiskUsage(dockerCli, opts) <add> }, <add> } <add> <add> flags := cmd.Flags() <add> <add> flags.BoolVarP(&opts.verbose, "verbose", "v", false, "Show detailed information on space usage") <add> <add> return cmd <add>} <add> <add>func runDiskUsage(dockerCli *command.DockerCli, opts diskUsageOptions) error { <add> du, err := dockerCli.Client().DiskUsage(context.Background()) <add> if err != nil { <add> return err <add> } <add> <add> duCtx := formatter.DiskUsageContext{ <add> Context: formatter.Context{ <add> Output: dockerCli.Out(), <add> }, <add> LayersSize: du.LayersSize, <add> Images: du.Images, <add> Containers: du.Containers, <add> Volumes: du.Volumes, <add> Verbose: opts.verbose, <add> } <add> <add> duCtx.Write() <add> <add> return nil <add>} <ide><path>daemon/images.go <ide> func (daemon *Daemon) Images(filterArgs, filter string, all bool, withExtraAttrs <ide> <ide> if withExtraAttrs { <ide> // lazyly init variables <del> if len(allContainers) == 0 { <add> if imagesMap == nil { <ide> allContainers = daemon.List() <ide> allLayers = daemon.layerStore.Map() <ide> imagesMap = make(map[*image.Image]*types.Image)
8
PHP
PHP
remove use of file in loadtask
470274f8673cd2475caa8a3d835baa2d1ab4089d
<ide><path>src/Shell/Task/LoadTask.php <ide> <ide> use Cake\Console\ConsoleOptionParser; <ide> use Cake\Console\Shell; <del>use Cake\Filesystem\File; <ide> <ide> /** <ide> * Task for loading plugins. <ide> protected function makeOptions(): string <ide> */ <ide> protected function modifyApplication(string $app, string $plugin, string $options): void <ide> { <del> $file = new File($app, false); <del> $contents = $file->read(); <add> $contents = file_get_contents($app); <ide> <ide> $append = "\n \$this->addPlugin('%s', [%s]);\n"; <ide> $insert = str_replace(', []', '', sprintf($append, $plugin, $options)); <ide> protected function modifyApplication(string $app, string $plugin, string $option <ide> } else { <ide> $contents = preg_replace('/(function bootstrap\(\)(?:\s*)\:(?:\s*)void(?:\s+)\{)/m', '$1' . $insert, $contents); <ide> } <del> $file->write($contents); <add> file_put_contents($app, $contents); <ide> <ide> $this->out(''); <ide> $this->out(sprintf('%s modified', $app)); <ide> protected function modifyApplication(string $app, string $plugin, string $option <ide> */ <ide> protected function _modifyBootstrap(string $plugin, string $options): bool <ide> { <del> $bootstrap = new File($this->bootstrap, false); <del> $contents = $bootstrap->read(); <add> $contents = file_get_contents($this->bootstrap); <ide> if (!preg_match("@\n\s*Plugin::loadAll@", $contents)) { <ide> $append = "\nPlugin::load('%s', [%s]);\n"; <ide> <del> $bootstrap->append(str_replace(', []', '', sprintf($append, $plugin, $options))); <add> file_put_contents( <add> $this->bootstrap, <add> str_replace(', []', '', sprintf($append, $plugin, $options)) <add> ); <ide> $this->out(''); <ide> $this->out(sprintf('%s modified', $this->bootstrap)); <ide>
1
PHP
PHP
add ormdelete option to treebehavior
f7525df84fb966770b0c58c010723c9b85cd90c3
<ide><path>src/ORM/Behavior/TreeBehavior.php <ide> class TreeBehavior extends Behavior <ide> 'scope' => null, <ide> 'level' => null, <ide> 'recoverOrder' => null, <add> 'enableOrmDelete' => false, <ide> ]; <ide> <ide> /** <ide> public function beforeDelete(EventInterface $event, EntityInterface $entity) <ide> <ide> if ($diff > 2) { <ide> $query = $this->_scope($this->_table->query()) <del> ->delete() <ide> ->where(function ($exp) use ($config, $left, $right) { <ide> /** @var \Cake\Database\Expression\QueryExpression $exp */ <ide> return $exp <ide> ->gte($config['leftField'], $left + 1) <ide> ->lte($config['leftField'], $right - 1); <ide> }); <del> $statement = $query->execute(); <del> $statement->closeCursor(); <add> if($this->getConfig('enableOrmDelete')){ <add> $result = $query->toArray(); <add> foreach($result as $entity) { <add> $this->_table->delete($entity, ['atomic' => false]); <add> } <add> } else { <add> $query->delete(); <add> $statement = $query->execute(); <add> $statement->closeCursor(); <add> } <ide> } <ide> <ide> $this->_sync($diff, '-', "> {$right}"); <ide><path>tests/Fixture/NumberTreesArticlesFixture.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 1.2.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Test\Fixture; <add> <add>use Cake\TestSuite\Fixture\TestFixture; <add> <add>/** <add> * Short description for class. <add> */ <add>class NumberTreesArticlesFixture extends TestFixture <add>{ <add> /** <add> * fields property <add> * <add> * @var array <add> */ <add> public $fields = [ <add> 'id' => ['type' => 'integer'], <add> 'number_tree_id' => ['type' => 'integer', 'null' => true], <add> 'title' => ['type' => 'string', 'null' => true], <add> 'body' => 'text', <add> 'published' => ['type' => 'string', 'length' => 1, 'default' => 'N'], <add> '_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]], <add> ]; <add> <add> /** <add> * records property <add> * <add> * @var array <add> */ <add> public $records = [ <add> ['number_tree_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y'], <add> ['number_tree_id' => 1, 'title' => 'Second Article', 'body' => 'Second Article Body', 'published' => 'Y'], <add> ['number_tree_id' => 11, 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y'], <add> ]; <add>} <ide><path>tests/TestCase/ORM/Behavior/TreeBehaviorTest.php <ide> class TreeBehaviorTest extends TestCase <ide> protected $fixtures = [ <ide> 'core.MenuLinkTrees', <ide> 'core.NumberTrees', <add> 'core.NumberTreesArticles', <ide> ]; <ide> <ide> /** <ide> public function testDeleteSubTreeScopedTree(): void <ide> $this->assertMpttValues($expected, $table); <ide> } <ide> <add> /** <add> * Tests deleting a subtree with ORM delete operations <add> */ <add> public function testDeleteSubTreeWithOrm(): void <add> { <add> $NumberTreesArticles = $this->getTableLocator()->get('NumberTreesArticles'); <add> $table = $this->table; <add> $table->addAssociations([ <add> 'hasMany' => [ <add> 'NumberTreesArticles' => [ <add> 'cascadeCallbacks' => true, <add> 'dependent' => true <add> ] <add> ] <add> ]); <add> $table->getBehavior('Tree')->setConfig(['enableOrmDelete' => true]); <add> $entity = $table->get(1); <add> $this->assertTrue($table->delete($entity)); <add> <add> $expected = [ <add> ' 5: 6 - 11:alien hardware', <add> ]; <add> $this->assertMpttValues($expected, $this->table); <add> $this->assertSame(1, $NumberTreesArticles->find()->count()); <add> } <add> <ide> /** <ide> * Test deleting a root node <ide> */ <ide><path>tests/schema.php <ide> ], <ide> ], <ide> ], <add> [ <add> 'table' => 'number_trees_articles', <add> 'columns' => [ <add> 'id' => [ <add> 'type' => 'integer', <add> ], <add> 'number_tree_id' => [ <add> 'type' => 'integer', <add> 'null' => true, <add> ], <add> 'title' => [ <add> 'type' => 'string', <add> 'null' => true, <add> ], <add> 'body' => 'text', <add> 'published' => [ <add> 'type' => 'string', <add> 'length' => 1, <add> 'default' => 'N', <add> ], <add> ], <add> 'constraints' => [ <add> 'primary' => [ <add> 'type' => 'primary', <add> 'columns' => [ <add> 'id', <add> ], <add> ], <add> ], <add> ], <ide> [ <ide> 'table' => 'composite_increments', <ide> 'columns' => [
4
Javascript
Javascript
convert jsonpmaintemplateplugin to use .tap
ad10141c381d7ad2af25b47d9b328f4f1d0c8e61
<ide><path>lib/web/JsonpMainTemplatePlugin.js <ide> class JsonpMainTemplatePlugin { <ide> return otherChunksInEntry || onDemandChunks; <ide> }; <ide> // TODO refactor this <del> if(!mainTemplate.hooks.jsonpScript) <add> if(!mainTemplate.hooks.jsonpScript) { <ide> mainTemplate.hooks.jsonpScript = new SyncWaterfallHook(["source", "chunk", "hash"]); <del> mainTemplate.plugin("local-vars", (source, chunk) => { <add> } <add> <add> mainTemplate.hooks.localVar.tap("JsonpMainTemplatePlugin", (source, chunk) => { <ide> if(needChunkLoadingCode(chunk)) { <ide> return Template.asString([ <ide> source, <ide> class JsonpMainTemplatePlugin { <ide> } <ide> return source; <ide> }); <del> mainTemplate.plugin("jsonp-script", (_, chunk, hash) => { <add> mainTemplate.hooks.jsonpScript.tap("JsonpMainTemplatePlugin", (_, chunk, hash) => { <ide> const chunkFilename = mainTemplate.outputOptions.chunkFilename; <ide> const chunkMaps = chunk.getChunkMaps(); <ide> const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; <ide> class JsonpMainTemplatePlugin { <ide> "};", <ide> ]); <ide> }); <del> mainTemplate.plugin("require-ensure", (source, chunk, hash) => { <add> mainTemplate.hooks.requireEnsure.tap("JsonpMainTemplatePlugin", (source, chunk, hash) => { <ide> return Template.asString([ <ide> source, <ide> "", <ide> class JsonpMainTemplatePlugin { <ide> "}", <ide> ]); <ide> }); <del> mainTemplate.plugin("require-extensions", (source, chunk) => { <add> mainTemplate.hooks.requireExtensions.tap("JsonpMainTemplatePlugin", (source, chunk) => { <ide> if(chunk.getNumberOfChunks() === 0) return source; <ide> <ide> return Template.asString([ <ide> class JsonpMainTemplatePlugin { <ide> `${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };` <ide> ]); <ide> }); <del> mainTemplate.plugin("bootstrap", (source, chunk, hash) => { <add> mainTemplate.hooks.bootstrap.tap("JsonpMainTemplatePlugin", (source, chunk, hash) => { <ide> if(needChunkLoadingCode(chunk)) { <ide> return Template.asString([ <ide> source, <ide> class JsonpMainTemplatePlugin { <ide> } <ide> return source; <ide> }); <del> mainTemplate.plugin("startup", (source, chunk, hash) => { <add> mainTemplate.hooks.startup.tap("JsonpMainTemplatePlugin", (source, chunk, hash) => { <ide> if(needChunkLoadingCode(chunk)) { <ide> var jsonpFunction = mainTemplate.outputOptions.jsonpFunction; <ide> return Template.asString([ <ide> class JsonpMainTemplatePlugin { <ide> } <ide> return source; <ide> }); <del> mainTemplate.plugin("hot-bootstrap", (source, chunk, hash) => { <add> mainTemplate.hooks.hotBootstrap.tap("JsonpMainTemplatePlugin", (source, chunk, hash) => { <ide> const hotUpdateChunkFilename = mainTemplate.outputOptions.hotUpdateChunkFilename; <ide> const hotUpdateMainFilename = mainTemplate.outputOptions.hotUpdateMainFilename; <ide> const crossOriginLoading = mainTemplate.outputOptions.crossOriginLoading; <ide> function hotDisposeChunk(chunkId) { <ide> var parentHotUpdateCallback = window[${JSON.stringify(hotUpdateFunction)}]; <ide> window[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`; <ide> }); <del> mainTemplate.plugin("hash", hash => { <add> mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => { <ide> hash.update("jsonp"); <ide> hash.update("5"); <ide> hash.update(`${mainTemplate.outputOptions.filename}`);
1
Java
Java
fix arraystoreexception reading subclassed enums
8abe949734414e91e204d14e381be7f922f2dfc3
<ide><path>spring-core/src/main/java/org/springframework/core/type/classreading/AnnotationAttributesReadingVisitor.java <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <del> <ide> import org.springframework.asm.AnnotationVisitor; <ide> import org.springframework.asm.SpringAsmInfo; <ide> import org.springframework.asm.Type; <ide> public void visit(String attributeName, Object attributeValue) { <ide> newValue = ObjectUtils.addObjectToArray((Object[]) existingValue, newValue); <ide> } <ide> else { <del> Object[] newArray = (Object[]) Array.newInstance(newValue.getClass(), 1); <add> Class<?> arrayClass = newValue.getClass(); <add> if(Enum.class.isAssignableFrom(arrayClass)) { <add> while(arrayClass.getSuperclass() != null && !arrayClass.isEnum()) { <add> arrayClass = arrayClass.getSuperclass(); <add> } <add> } <add> Object[] newArray = (Object[]) Array.newInstance(arrayClass, 1); <ide> newArray[0] = newValue; <ide> newValue = newArray; <ide> } <ide><path>spring-core/src/test/java/org/springframework/core/type/AnnotationMetadataTests.java <ide> private void doTestAnnotationInfo(AnnotationMetadata metadata) { <ide> assertThat(metadata.hasAnnotation(Component.class.getName()), is(true)); <ide> assertThat(metadata.hasAnnotation(Scope.class.getName()), is(true)); <ide> assertThat(metadata.hasAnnotation(SpecialAttr.class.getName()), is(true)); <del> assertThat(metadata.getAnnotationTypes().size(), is(5)); <add> assertThat(metadata.getAnnotationTypes().size(), is(6)); <ide> assertThat(metadata.getAnnotationTypes().contains(Component.class.getName()), is(true)); <ide> assertThat(metadata.getAnnotationTypes().contains(Scope.class.getName()), is(true)); <ide> assertThat(metadata.getAnnotationTypes().contains(SpecialAttr.class.getName()), is(true)); <ide> public static enum SomeEnum { <ide> public @interface MetaMetaAnnotation { <ide> } <ide> <add> @Target(ElementType.TYPE) <add> @Retention(RetentionPolicy.RUNTIME) <add> public @interface EnumSubclasses { <add> SubclassEnum[] value(); <add> } <add> <add> // SPR-10914 <add> public static enum SubclassEnum { <add> FOO { <add> }, <add> BAR { <add> }; <add> } <add> <ide> @Component("myName") <ide> @Scope("myScope") <ide> @SpecialAttr(clazz = String.class, state = Thread.State.NEW, <ide> public static enum SomeEnum { <ide> @SuppressWarnings({"serial", "unused"}) <ide> @DirectAnnotation("direct") <ide> @MetaMetaAnnotation <add> @EnumSubclasses({ SubclassEnum.FOO, SubclassEnum.BAR }) <ide> private static class AnnotatedComponent implements Serializable { <ide> <ide> @TestAutowired
2
Javascript
Javascript
avoid use of arguments
1e21d05632fe75322f158df984df80c44132bcdb
<ide><path>lib/buffer.js <ide> Buffer.prototype.copy = function(target, targetStart, sourceStart, sourceEnd) { <ide> return binding.copy(this, target, targetStart, sourceStart, sourceEnd); <ide> }; <ide> <del>Buffer.prototype.toString = function() { <add>Buffer.prototype.toString = function(encoding, start, end) { <ide> let result; <ide> if (arguments.length === 0) { <ide> result = this.utf8Slice(0, this.length); <ide> } else { <del> result = slowToString.apply(this, arguments); <add> result = slowToString.call(this, encoding, start, end); <ide> } <ide> if (result === undefined) <ide> throw new Error('"toString()" failed');
1
Ruby
Ruby
add schema cache tests
c1a215a06b7b8202dbb4f090bf7eefb661bf438a
<ide><path>railties/test/application/rake/dbs_test.rb <ide> def db_schema_dump <ide> db_schema_dump <ide> end <ide> <add> def db_schema_cache_dump(filename = "db/schema_cache.yml") <add> Dir.chdir(app_path) do <add> rails "db:schema:cache:dump" <add> <add> cache_size = lambda { rails("runner", "p ActiveRecord::Base.connection.schema_cache.size").strip } <add> cache_tables = lambda { rails("runner", "p ActiveRecord::Base.connection.schema_cache.columns('books')").strip } <add> <add> assert_equal "12", cache_size[] <add> assert_includes cache_tables[], "id", "expected cache_tables to include an id entry" <add> assert_includes cache_tables[], "title", "expected cache_tables to include a title entry" <add> end <add> end <add> <add> test "db:schema:cache:dump" do <add> db_schema_dump <add> db_schema_cache_dump <add> end <add> <add> test "db:schema:cache:dump with custom filename" do <add> Dir.chdir(app_path) do <add> File.open("#{app_path}/config/database.yml", "w") do |f| <add> f.puts <<-YAML <add> default: &default <add> adapter: sqlite3 <add> pool: 5 <add> timeout: 5000 <add> variables: <add> statement_timeout: 1000 <add> development: <add> <<: *default <add> database: db/development.sqlite3 <add> schema_cache_path: db/special_schema_cache.yml <add> YAML <add> end <add> end <add> <add> db_schema_dump <add> db_schema_cache_dump("db/special_schema_cache.yml") <add> end <add> <add> test "db:schema:cache:dump custom env" do <add> @old_schema_cache_env = ENV["SCHEMA_CACHE"] <add> filename = "db/special_schema_cache.yml" <add> ENV["SCHEMA_CACHE"] = filename <add> <add> db_schema_dump <add> db_schema_cache_dump(filename) <add> ensure <add> ENV["SCHEMA_CACHE"] = @old_schema_cache_env <add> end <add> <add> test "db:schema:cache:dump primary wins" do <add> Dir.chdir(app_path) do <add> File.open("#{app_path}/config/database.yml", "w") do |f| <add> f.puts <<-YAML <add> default: &default <add> adapter: sqlite3 <add> pool: 5 <add> timeout: 5000 <add> variables: <add> statement_timeout: 1000 <add> development: <add> some_entry: <add> <<: *default <add> database: db/development_other.sqlite3 <add> primary: <add> <<: *default <add> database: db/development.sqlite3 <add> YAML <add> end <add> end <add> <add> db_schema_dump <add> db_schema_cache_dump <add> end <add> <ide> def db_fixtures_load(expected_database) <ide> Dir.chdir(app_path) do <ide> rails "generate", "model", "book", "title:string" <ide><path>railties/test/application/rake/multi_dbs_test.rb <ide> class TwoMigration < ActiveRecord::Migration::Current <ide> db_migrate_and_schema_cache_dump <ide> end <ide> <add> # Note that schema cache loader depends on the connection and <add> # does not work for all connections. <add> test "schema_cache is loaded on primary db in multi-db app" do <add> require "#{app_path}/config/environment" <add> db_migrate_and_schema_cache_dump <add> <add> cache_size_a = lambda { rails("runner", "p ActiveRecord::Base.connection.schema_cache.size").strip } <add> cache_tables_a = lambda { rails("runner", "p ActiveRecord::Base.connection.schema_cache.columns('books')").strip } <add> cache_size_b = lambda { rails("runner", "p AnimalsBase.connection.schema_cache.size").strip } <add> cache_tables_b = lambda { rails("runner", "p AnimalsBase.connection.schema_cache.columns('dogs')").strip } <add> <add> assert_equal "12", cache_size_a[] <add> assert_includes cache_tables_a[], "title", "expected cache_tables_a to include a title entry" <add> <add> # Will be 0 because it's not loaded by the railtie <add> assert_equal "0", cache_size_b[] <add> assert_includes cache_tables_b[], "name", "expected cache_tables_b to include a name entry" <add> end <add> <ide> test "db:schema:cache:clear works on all databases" do <ide> require "#{app_path}/config/environment" <ide> db_migrate_and_schema_cache_dump_and_schema_cache_clear
2
Javascript
Javascript
allow alternate clicks for href handling - fixes
e668276a3aab382e145c3bc7afd059a9a6438534
<ide><path>packages/ember-application/tests/system/action_url_test.js <ide> test("it sets an URL with a context", function() { <ide> <ide> ok(view.$().html().match(/href=['"].*\/dashboard\/1['"]/), "The html (" + view.$().html() + ") has the href /dashboard/1 in it"); <ide> }); <add> <add>test("it does not trigger action with special clicks", function() { <add> var dispatcher = Ember.EventDispatcher.create(); <add> dispatcher.setup(); <add> <add> var showCalled = false; <add> <add> var view = Ember.View.create({ <add> template: compile("<a {{action show href=true}}>Hi</a>") <add> }); <add> <add> var controller = Ember.Object.create(Ember.ControllerMixin, { <add> target: { <add> urlForEvent: function(event, context) { <add> return "/foo/bar"; <add> }, <add> <add> show: function() { <add> showCalled = true; <add> } <add> } <add> }); <add> <add> Ember.run(function() { <add> view.set('controller', controller); <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> function checkClick(prop, value, expected) { <add> var event = Ember.$.Event("click"); <add> event[prop] = value; <add> view.$('a').trigger(event); <add> if (expected) { <add> ok(showCalled, "should call action with "+prop+":"+value); <add> ok(event.isDefaultPrevented(), "should prevent default"); <add> } else { <add> ok(!showCalled, "should not call action with "+prop+":"+value); <add> ok(!event.isDefaultPrevented(), "should not prevent default"); <add> } <add> } <add> <add> checkClick('ctrlKey', true, false); <add> checkClick('altKey', true, false); <add> checkClick('metaKey', true, false); <add> checkClick('shiftKey', true, false); <add> checkClick('button', 1, false); <add> <add> checkClick('button', 0, true); <add> <add> Ember.run(function() { <add> dispatcher.destroy(); <add> }); <add>}); <ide><path>packages/ember-handlebars/lib/helpers/action.js <ide> var ActionHelper = EmberHandlebars.ActionHelper = { <ide> registeredActions: {} <ide> }; <ide> <del>ActionHelper.registerAction = function(actionName, eventName, target, view, context) { <add>ActionHelper.registerAction = function(actionName, eventName, target, view, context, link) { <ide> var actionId = (++Ember.$.uuid).toString(); <ide> <ide> ActionHelper.registeredActions[actionId] = { <ide> eventName: eventName, <ide> handler: function(event) { <add> if (link && (event.button !== 0 || event.shiftKey || event.metaKey || event.altKey || event.ctrlKey)) { <add> // Allow the browser to handle special link clicks normally <add> return; <add> } <add> <add> event.preventDefault(); <add> <ide> event.view = view; <ide> event.context = context; <ide> <ide> EmberHandlebars.registerHelper('action', function(actionName, options) { <ide> var hash = options.hash, <ide> eventName = hash.on || "click", <ide> view = options.data.view, <del> target, context, controller; <add> target, context, controller, link; <ide> <ide> view = get(view, 'concreteView'); <ide> <ide> EmberHandlebars.registerHelper('action', function(actionName, options) { <ide> if (hash.href && target.urlForEvent) { <ide> url = target.urlForEvent(actionName, context); <ide> output.push('href="' + url + '"'); <add> link = true; <ide> } <ide> <del> var actionId = ActionHelper.registerAction(actionName, eventName, target, view, context); <add> var actionId = ActionHelper.registerAction(actionName, eventName, target, view, context, link); <ide> output.push('data-ember-action="' + actionId + '"'); <ide> <ide> return new EmberHandlebars.SafeString(output.join(" ")); <ide><path>packages/ember-views/lib/system/event_dispatcher.js <ide> Ember.EventDispatcher = Ember.Object.extend( <ide> handler = action.handler; <ide> <ide> if (action.eventName === eventName) { <del> evt.preventDefault(); <ide> return handler(evt); <ide> } <ide> });
3
Text
Text
fix typo in buffer api
74562356db6964f8057ef4bd897725793e55d513
<ide><path>doc/api/buffer.md <ide> elements, and not as a byte array of the target type. That is, <ide> `[0x1020304]` or `[0x4030201]`. <ide> <ide> It is possible to create a new `Buffer` that shares the same allocated memory as <del>a [`TypedArray`] instance by using the `TypeArray` object's `.buffer` property. <add>a [`TypedArray`] instance by using the `TypedArray` object's `.buffer` property. <ide> <ide> ```js <ide> const arr = new Uint16Array(2);
1
PHP
PHP
fix typo in oauth
304d6f8e24491ad46ddaeb2ff2a643aeac4d45e9
<ide><path>lib/Cake/Network/Http/Auth/Oauth.php <ide> protected function _normalizedParams($request, $oauthValues) { <ide> * @return string <ide> */ <ide> protected function _buildAuth($data) { <del> $out = 'Oauth '; <add> $out = 'OAuth '; <ide> $params = []; <ide> foreach ($data as $key => $value) { <ide> $params[] = $key . '="' . $this->_encode($value) . '"'; <ide><path>lib/Cake/Test/TestCase/Network/Http/Auth/OauthTest.php <ide> public function testPlainTextSigning() { <ide> $auth->authentication($request, $creds); <ide> <ide> $result = $request->header('Authorization'); <del> $this->assertContains('Oauth', $result); <add> $this->assertContains('OAuth', $result); <ide> $this->assertContains('oauth_version="1.0"', $result); <ide> $this->assertContains('oauth_token="a%20token%20value"', $result); <ide> $this->assertContains('oauth_consumer_key="a%20key"', $result);
2
PHP
PHP
update task.php
6bdc08511762479189a1046a3ea7f413216a412a
<ide><path>src/Illuminate/Console/View/Components/Task.php <ide> public function render($description, $task = null, $verbosity = OutputInterface: <ide> throw $e; <ide> } finally { <ide> $runTime = $task <del> ? (' '.number_format((microtime(true) - $startTime) * 1000, 2).'ms') <add> ? (' '.number_format((microtime(true) - $startTime) * 1000).'ms') <ide> : ''; <ide> <ide> $runTimeWidth = mb_strlen($runTime);
1
PHP
PHP
fix cs errors
c952214a8901a02a340a3981d51cbfc64c5a982f
<ide><path>tests/TestCase/Database/QueryTest.php <ide> public function testJoinReadMode() <ide> ->from('articles') <ide> ->join(['authors' => [ <ide> 'type' => 'INNER', <del> 'conditions' => ['articles.author_id = authors.id'] <add> 'conditions' => ['articles.author_id = authors.id'], <ide> ]]); <ide> <ide> $this->deprecated(function () use ($query) { <ide><path>tests/TestCase/Http/ServerRequestTest.php <ide> public function testClientIpWithTrustedProxies() <ide> '192.168.1.0', <ide> '192.168.1.1', <ide> '192.168.1.2', <del> '192.168.1.3' <add> '192.168.1.3', <ide> ]); <ide> <ide> $this->assertEquals('real.ip', $request->clientIp()); <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php <ide> public function testDefaultTableLocator() <ide> $table = $locator->get('Articles'); <ide> $table->addBehavior('Translate', [ <ide> 'fields' => ['title', 'body'], <del> 'validator' => 'custom' <add> 'validator' => 'custom', <ide> ]); <ide> <ide> $behaviorLocator = $table->behaviors()->get('Translate')->getTableLocator(); <ide><path>tests/TestCase/ORM/TableTest.php <ide> public function testSaveManyFailedWithException() <ide> ->get('authors'); <ide> $entities = [ <ide> new Entity(['name' => 'mark']), <del> new Entity(['name' => 'jose']) <add> new Entity(['name' => 'jose']), <ide> ]; <ide> <ide> $table->getEventManager()->on('Model.beforeSave', function (EventInterface $event, Entity $entity) {
4
Javascript
Javascript
pass env vars through to test-benchmark-http
eef94a8bf827b98cd27e8aaab6bb20791a46bace
<ide><path>test/sequential/test-benchmark-http.js <ide> const path = require('path'); <ide> <ide> const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); <ide> <add>const env = Object.assign({}, process.env, <add> { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); <add> <ide> const child = fork(runjs, ['--set', 'benchmarker=test-double', <ide> '--set', 'c=1', <ide> '--set', 'chunks=0', <ide> const child = fork(runjs, ['--set', 'benchmarker=test-double', <ide> '--set', 'len=1', <ide> '--set', 'n=1', <ide> 'http'], <del> {env: {NODEJS_BENCHMARK_ZERO_ALLOWED: 1}}); <add> {env}); <ide> child.on('exit', (code, signal) => { <ide> assert.strictEqual(code, 0); <ide> assert.strictEqual(signal, null);
1
Python
Python
get printing of nas to work a little bit better
0cc2e75cd160c44dba1dbcadfb530cfbe7d0cf98
<ide><path>numpy/core/arrayprint.py <ide> def __call__(self, x, strip_zeros=True): <ide> import numeric as _nc <ide> err = _nc.seterr(invalid='ignore') <ide> try: <del> if isnan(x): <add> if isna(x): <add> return str(x) <add> elif isnan(x): <ide> if self.sign: <ide> return self.special_fmt % ('+' + _nan_str,) <ide> else: <ide><path>numpy/core/numeric.py <ide> def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): <ide> ', ', "array(") <ide> else: # show zero-length shape unless it is (0,) <ide> lst = "[], shape=%s" % (repr(arr.shape),) <del> typeless = arr.dtype.type in _typelessdata <ide> <ide> if arr.__class__ is not ndarray: <ide> cName= arr.__class__.__name__ <ide> else: <ide> cName = "array" <del> if typeless and arr.size: <del> return cName + "(%s)" % lst <add> <add> skiptype = (arr.dtype.type in _typelessdata) and arr.size > 0 <add> <add> if arr.flags.maskna: <add> lst += ", maskna=True" <add> # If everything is NA, can't skip the type <add> if np.all(np.isna(arr)): <add> skiptype = False <add> <add> if skiptype: <add> return "%s(%s)" % (cName, lst) <ide> else: <ide> typename = arr.dtype.name <ide> # Quote typename in the output if it is "complex".
2
Text
Text
fix a typo in changelog_v15
02e60a61ea6ffc474e533b0787a1ef83f3731141
<ide><path>doc/changelogs/CHANGELOG_V15.md <ide> The V8 JavaScript engine has been updated to V8 8.6 (V8 8.4 is the latest availa <ide> * [[`7ecb285842`](https://github.com/nodejs/node/commit/7ecb285842)] - **src**: make code cache test work with snapshots (Joyee Cheung) [#32984](https://github.com/nodejs/node/pull/32984) <ide> * [[`1faf6f459f`](https://github.com/nodejs/node/commit/1faf6f459f)] - **src**: snapshot Environment upon instantiation (Joyee Cheung) [#32984](https://github.com/nodejs/node/pull/32984) <ide> * [[`ef9964f4c1`](https://github.com/nodejs/node/commit/ef9964f4c1)] - **src**: add an ExternalReferenceRegistry class (Joyee Cheung) [#32984](https://github.com/nodejs/node/pull/32984) <del>* [[`404302fff5`](https://github.com/nodejs/node/commit/404302fff5)] - **src**: split the main context initialization from Environemnt ctor (Joyee Cheung) [#32984](https://github.com/nodejs/node/pull/32984) <add>* [[`404302fff5`](https://github.com/nodejs/node/commit/404302fff5)] - **src**: split the main context initialization from Environment ctor (Joyee Cheung) [#32984](https://github.com/nodejs/node/pull/32984) <ide> * [[`874460a1d1`](https://github.com/nodejs/node/commit/874460a1d1)] - **src**: refactor TimerWrap lifetime management (Anna Henningsen) [#34252](https://github.com/nodejs/node/pull/34252) <ide> * [[`e2f9dc6e5a`](https://github.com/nodejs/node/commit/e2f9dc6e5a)] - **src**: remove user\_data from TimerWrap (Anna Henningsen) [#34252](https://github.com/nodejs/node/pull/34252) <ide> * [[`e19a251824`](https://github.com/nodejs/node/commit/e19a251824)] - **src**: replace InspectorTimer with TimerWrap utility (James M Snell) [#34186](https://github.com/nodejs/node/pull/34186)
1
Ruby
Ruby
fix keyonlyreason property access
b752efbd37d75f58e423a86a05476b248031c374
<ide><path>Library/Homebrew/cmd/link.rb <ide> def link <ide> if keg_only <ide> if Homebrew.default_prefix? <ide> f = keg.to_formula <del> if f.keg_only_reason.reason.by_macos? <add> if f.keg_only_reason.by_macos? <ide> caveats = Caveats.new(f) <ide> opoo <<~EOS <ide> Refusing to link macOS provided/shadowed software: #{keg.name}
1
Text
Text
add translation of algorithm and data structures
306e4aaacfc278d099053f116d1799b6bb7fa6aa
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who.md <ide> --- <ide> id: a77dbc43c33f39daa4429b4f <del>title: 嘘谁 <add>title: 基本类型布尔值的检查 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16000 <ide> --- <ide> <ide> # --description-- <ide> <del>检查参数是否归类为布尔基元。返回true或false。布尔基元是true和false。如果卡住,请记得使用[Read-Search-Ask](http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514) 。尝试配对程序。编写自己的代码。 <add>检查一个值是否是[基本类型](https://developer.mozilla.org/zh-CN/docs/Glossary/Primitive)中的布尔值(boolean)类型。函数应返回 true 或者 false。 <add> <add>基本类型中的布尔值为 true 或者 false。 <ide> <ide> # --hints-- <ide> <del>`booWho(true)`应该返回true。 <add>`booWho(true)` 应返回 true。 <ide> <ide> ```js <ide> assert.strictEqual(booWho(true), true); <ide> ``` <ide> <del>`booWho(false)`应该返回true。 <add>`booWho(false)` 应返回 true。 <ide> <ide> ```js <ide> assert.strictEqual(booWho(false), true); <ide> ``` <ide> <del>`booWho([1, 2, 3])`应该返回false。 <add>`booWho([1, 2, 3])` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho([1, 2, 3]), false); <ide> ``` <ide> <del>`booWho([].slice)`应该返回false。 <add>`booWho([].slice)` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho([].slice), false); <ide> ``` <ide> <del>`booWho({ "a": 1 })`应该返回false。 <add>`booWho({ "a": 1 })` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho({ a: 1 }), false); <ide> ``` <ide> <del>`booWho(1)`应该返回false。 <add>`booWho(1)` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho(1), false); <ide> ``` <ide> <del>`booWho(NaN)`应该返回false。 <add>`booWho(NaN)` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho(NaN), false); <ide> ``` <ide> <del>`booWho("a")`应该返回false。 <add>`booWho("a")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho('a'), false); <ide> ``` <ide> <del>`booWho("true")`应该返回false。 <add>`booWho("true")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho('true'), false); <ide> ``` <ide> <del>`booWho("false")`应该返回false。 <add>`booWho("false")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual(booWho('false'), false); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey.md <ide> --- <ide> id: a9bd25c716030ec90084d8a1 <del>title: 矮胖的猴子 <add>title: 分割数组 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16005 <ide> --- <ide> <ide> # --description-- <ide> <del>编写一个函数,将数组(第一个参数)拆分为`size`的长度(第二个参数),并将它们作为二维数组返回。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>请编写一个函数,该函数将一个数组(第一个参数)拆分成若干长度为 `size`(第二个参数)的子数组,并将它们作为二维数组返回。 <ide> <ide> # --hints-- <ide> <del>`chunkArrayInGroups(["a", "b", "c", "d"], 2)`应返回`[["a", "b"], ["c", "d"]]` 。 <add>`chunkArrayInGroups(["a", "b", "c", "d"], 2)` 应返回 `[["a", "b"], ["c", "d"]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [ <ide> assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)`应返回`[[0, 1, 2], [3, 4, 5]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` 应返回 `[[0, 1, 2], [3, 4, 5]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [ <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)`应返回`[[0, 1], [2, 3], [4, 5]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` 应返回 `[[0, 1], [2, 3], [4, 5]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [ <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)`应该返回`[[0, 1, 2, 3], [4, 5]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` 应返回 `[[0, 1, 2, 3], [4, 5]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [ <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)`应该返回`[[0, 1, 2], [3, 4, 5], [6]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` 应返回 `[[0, 1, 2], [3, 4, 5], [6]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [ <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)`应返回`[[0, 1, 2, 3], [4, 5, 6, 7], [8]]` `chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` 应返回 `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [ <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [ <ide> ]); <ide> ``` <ide> <del>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)`应返回`[[0, 1], [2, 3], [4, 5], [6, 7], [8]]` 。 <add>`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` 应返回 `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`。 <ide> <ide> ```js <ide> assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [ <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending.md <ide> --- <ide> id: acda2fb1324d9b0fa741e6b5 <del>title: 确认结束 <add>title: 检查字符串结尾 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16006 <ide> --- <ide> <ide> # --description-- <ide> <del>检查字符串(第一个参数`str` )是否以给定的目标字符串(第二个参数, `target` )结束。这个挑战*可以*通过`.endsWith()`中引入的`.endsWith()`方法来解决。但是出于这个挑战的目的,我们希望您使用其中一个JavaScript子字符串方法。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>检查字符串(第一个参数 `str`)是否以给定的目标字符串(第二个参数 `target`)结束。 <add> <add>这个挑战*可以*用 ES2015 引入的 `.endsWith()` 方法来解决。但在这个挑战中,请使用 JavaScript 的字符串子串方法或正则表达式来通过挑战,而不要使用 `.endsWith()` 方法。 <ide> <ide> # --hints-- <ide> <del>`confirmEnding("Bastian", "n")`应该返回true。 <add>`confirmEnding("Bastian", "n")` 应返回 true。 <ide> <ide> ```js <ide> assert(confirmEnding('Bastian', 'n') === true); <ide> ``` <ide> <del>`confirmEnding("Congratulation", "on")`应该返回true。 <add>`confirmEnding("Congratulation", "on")` 应返回 true。 <ide> <ide> ```js <ide> assert(confirmEnding('Congratulation', 'on') === true); <ide> ``` <ide> <del>`confirmEnding("Connor", "n")`应返回false。 <add>`confirmEnding("Connor", "n")` 应返回 false。 <ide> <ide> ```js <ide> assert(confirmEnding('Connor', 'n') === false); <ide> ``` <ide> <del>`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")`应该返回false。 <add>`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` 应返回 false。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`confirmEnding("He has to give me a new name", "name")`应该返回true。 <add>`confirmEnding("He has to give me a new name", "name")` 应返回 true。 <ide> <ide> ```js <ide> assert(confirmEnding('He has to give me a new name', 'name') === true); <ide> ``` <ide> <del>`confirmEnding("Open sesame", "same")`应该返回true。 <add>`confirmEnding("Open sesame", "same")` 应返回 true。 <ide> <ide> ```js <ide> assert(confirmEnding('Open sesame', 'same') === true); <ide> ``` <ide> <del>`confirmEnding("Open sesame", "pen")`应该返回false。 <add>`confirmEnding("Open sesame", "sage")` 应返回 false。 <ide> <ide> ```js <del>assert(confirmEnding('Open sesame', 'pen') === false); <add>assert(confirmEnding('Open sesame', 'sage') === false); <ide> ``` <ide> <del>`confirmEnding("Open sesame", "game")`应该返回false。 <add>`confirmEnding("Open sesame", "game")` 应返回 false。 <ide> <ide> ```js <ide> assert(confirmEnding('Open sesame', 'game') === false); <ide> ``` <ide> <del>`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")`应该返回虚假。 <add>`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` 应返回 false。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`confirmEnding("Abstraction", "action")`应该返回true。 <add>`confirmEnding("Abstraction", "action")` 应该返回 true。 <ide> <ide> ```js <ide> assert(confirmEnding('Abstraction', 'action') === true); <ide> ``` <ide> <del>不要使用内置方法`.endsWith()`来解决挑战。 <add>不应使用内置方法 `.endsWith()` 来完成挑战。 <ide> <ide> ```js <ide> assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit.md <ide> --- <ide> id: 56533eb9ac21ba0edf2244b3 <del>title: 将摄氏温度转换为华氏温度 <add>title: 将摄氏度转换为华氏度 <ide> challengeType: 1 <del>videoUrl: '' <add>forumTopicId: 16806 <ide> --- <ide> <ide> # --description-- <ide> <del>从摄氏温度转换为华氏温度的算法是以摄氏度乘以`9/5`,再加上`32` 。您将获得一个参数`celsius`代表着摄氏温度。使用已准备好代表华氏温度的变量`fahrenheit`,将`celsius`摄氏温度变量值兑换成华氏温度值,然后存储在`farenheit`变量里。使用以上提到的算法将摄氏温度转换为华氏温度。不需要过多担心函数和返回语句,因为它们将会在未来的挑战中加以解释。目前,只需使用您已经学过的运算符。 <add>将摄氏度转换为华氏度的计算方式为:摄氏度乘以 `9/5` 然后加上 `32`。 <add> <add>输入参数 `celsius` 代表一个摄氏度的温度。请根据上述转换公式,将已定义好的 `fahrenheit` 变量赋值为相应的华氏度的温度值。 <ide> <ide> # --hints-- <ide> <del>`convertToF(0)`应该返回一个数字 <add>`convertToF(0)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof convertToF(0) === 'number'); <ide> ``` <ide> <del>`convertToF(-30)`应该返回值`-22` <add>`convertToF(-30)` 应返回 `-22`。 <ide> <ide> ```js <ide> assert(convertToF(-30) === -22); <ide> ``` <ide> <del>`convertToF(-10)`应该返回值`14` <add>`convertToF(-10)` 应返回 `14`。 <ide> <ide> ```js <ide> assert(convertToF(-10) === 14); <ide> ``` <ide> <del>`convertToF(0)`应返回值`32` <add>`convertToF(0)` 应返回 `32`。 <ide> <ide> ```js <ide> assert(convertToF(0) === 32); <ide> ``` <ide> <del>`convertToF(20)`应返回值`68` <add>`convertToF(20)` 应返回 `68`。 <ide> <ide> ```js <ide> assert(convertToF(20) === 68); <ide> ``` <ide> <del>`convertToF(30)`应返回值`86` <add>`convertToF(30)` 应返回 `86`。 <ide> <ide> ```js <ide> assert(convertToF(30) === 86); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number.md <ide> --- <ide> id: a302f7aae1aa3152a5b413bc <del>title: 对一个数字进行推理 <add>title: 计算整数的阶乘 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16013 <ide> --- <ide> <ide> # --description-- <ide> <del>返回提供的整数的阶乘。如果整数用字母n表示,则阶乘是所有小于或等于n的正整数的乘积。因子通常用简写符号`n!`表示`n!`例如: `5! = 1 * 2 * 3 * 4 * 5 = 120`只有大于或等于零的整数才会被提供给该函数。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>返回一个给定整数的阶乘计算结果。 <add> <add>对于整数 n,n 的阶乘就是所有小于等于 n 的正整数的乘积。 <add> <add>`n` 的阶乘通常用符号 `n!` 来表示。 <add> <add>例如:`5! = 1 * 2 * 3 * 4 * 5 = 120` <add> <add>在这个挑战中,只有非负整数会作为参数传入函数。 <ide> <ide> # --hints-- <ide> <del>`factorialize(5)`应该返回一个数字。 <add>`factorialize(5)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof factorialize(5) === 'number'); <ide> ``` <ide> <del>`factorialize(5)`应该返回120。 <add>`factorialize(5)` 应返回 120。 <ide> <ide> ```js <ide> assert(factorialize(5) === 120); <ide> ``` <ide> <del>`factorialize(10)`应返回3628800。 <add>`factorialize(10)` 应返回 3628800。 <ide> <ide> ```js <ide> assert(factorialize(10) === 3628800); <ide> ``` <ide> <del>`factorialize(20)`应该返回2432902008176640000。 <add>`factorialize(20)` 应返回 2432902008176640000。 <ide> <ide> ```js <ide> assert(factorialize(20) === 2432902008176640000); <ide> ``` <ide> <del>`factorialize(0)`应该返回1。 <add>`factorialize(0)` 应返回 1。 <ide> <ide> ```js <ide> assert(factorialize(0) === 1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer.md <ide> --- <ide> id: adf08ec01beb4f99fc7a68f2 <del>title: Falsy Bouncer <add>title: 过滤数组中的假值 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16014 <ide> --- <ide> <ide> # --description-- <ide> <del>从数组中删除所有有价值的值。 JavaScript中的Falsy值为`false` , `null` , `0` , `""` , `undefined`和`NaN` 。提示:尝试将每个值转换为布尔值。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>从数组中移除所有假值(falsy values)。 <add> <add>JavaScript 中的假值有 `false`、`null`、`0`、`""`、`undefined`、`NaN`。 <add> <add>提示:可以考虑将每个值都转换为布尔值(boolean)。 <add> <ide> <ide> # --hints-- <ide> <del>`bouncer([7, "ate", "", false, 9])`应该返回`[7, "ate", 9]` 。 <add>`bouncer([7, "ate", "", false, 9])` 应返回 `[7, "ate", 9]`。 <ide> <ide> ```js <ide> assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]); <ide> ``` <ide> <del>`bouncer(["a", "b", "c"])`应返回`["a", "b", "c"]` 。 <add>`bouncer(["a", "b", "c"])` 应返回 `["a", "b", "c"]`。 <ide> <ide> ```js <ide> assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']); <ide> ``` <ide> <del>`bouncer([false, null, 0, NaN, undefined, ""])`应返回`[]` 。 <add>`bouncer([false, null, 0, NaN, undefined, ""])` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []); <ide> ``` <ide> <del>`bouncer([1, null, NaN, 2, undefined])`应该返回`[1, 2]` 。 <add>`bouncer([1, null, NaN, 2, undefined])`应返回 `[1, 2]`。 <ide> <ide> ```js <ide> assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string.md <ide> --- <ide> id: a26cbbe9ad8655a977e1ceb5 <del>title: 找到字符串中最长的单词 <add>title: 找出字符串中的最长单词 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16015 <ide> --- <ide> <ide> # --description-- <ide> <del>返回所提供句子中最长单词的长度。您的回答应该是一个数字。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>返回给出的句子中,最长单词的长度。 <add> <add>函数的返回值应是一个数字。 <ide> <ide> # --hints-- <ide> <del>`findLongestWordLength("The quick brown fox jumped over the lazy dog")`应该返回一个数字。 <add>`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 应返回一个数字。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`findLongestWordLength("The quick brown fox jumped over the lazy dog")`应该返回6。 <add>`findLongestWordLength("The quick brown fox jumped over the lazy dog")` 应返回 6。 <ide> <ide> ```js <ide> assert( <ide> findLongestWordLength('The quick brown fox jumped over the lazy dog') === 6 <ide> ); <ide> ``` <ide> <del>`findLongestWordLength("May the force be with you")`应该返回5。 <add>`findLongestWordLength("May the force be with you")` 应返回 5。 <ide> <ide> ```js <ide> assert(findLongestWordLength('May the force be with you') === 5); <ide> ``` <ide> <del>`findLongestWordLength("Google do a barrel roll")`应返回6。 <add>`findLongestWordLength("Google do a barrel roll")` 应返回 6。 <ide> <ide> ```js <ide> assert(findLongestWordLength('Google do a barrel roll') === 6); <ide> ``` <ide> <del>`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")`应该返回8。 <add>`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` 应返回 8。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")`应该返回19。 <add>`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` 应返回 19。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers.md <ide> --- <ide> id: a6e40f1041b06c996f7b2406 <del>title: Finders Keepers <add>title: 按参数过滤数组 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16016 <ide> --- <ide> <ide> # --description-- <ide> <del>创建一个查看数组(第一个参数)的函数,并返回数组中传递真值测试的第一个元素(第二个参数)。如果没有元素通过测试,则返回undefined。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。尝试配对程序。编写自己的代码。 <add>请写一个函数来检查数组(第一个参数 `arr`)中的元素,并返回数组中第一个通过校验测试的元素。其中,“通过校验测试”指的是对于数组中的一个元素 `x`,若 `func(x)` 返回的结果为 `true`,则校验测试通过。如果没有元素通过测试,请返回 `undefined`。 <ide> <ide> # --hints-- <ide> <del>`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })`应该返回8。 <add>`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` 应返回 8。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })`应返回undefined。 <add>`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` 应返回 undefined。 <ide> <ide> ```js <ide> assert.strictEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations.md <ide> --- <ide> id: af2170cad53daa0770fabdea <del>title: 突变 <add>title: 比较字符串 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16025 <ide> --- <ide> <ide> # --description-- <ide> <del>如果数组的第一个元素中的字符串包含数组第二个元素中字符串的所有字母,则返回true。例如, `["hello", "Hello"]`应该返回true,因为第二个字符串中的所有字母都出现在第一个字母中,忽略大小写。参数`["hello", "hey"]`应返回false,因为字符串“hello”不包含“y”。最后, `["Alien", "line"]`应该返回true,因为“line”中的所有字母都出现在“Alien”中。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>输入参数是一个数组,其中包含两个字符串元素。如果数组里的第一个字符串包含了第二个字符串中的所有字母,则返回 true。 <add> <add>例如,`["hello", "Hello"]` 应该返回 true。因为在忽略大小写的情况下,第一个字符串中包含了第二个字符串里出现的所有字母。 <add> <add>而 `["hello", "hey"]` 应该返回 false。因为第一个字符串 "hello" 没有包含字母 "y"。 <add> <add>最后,`["Alien", "line"]` 应该返回 true。因为 "line" 中的所有字母都出现在了 "Alien" 中。 <ide> <ide> # --hints-- <ide> <del>`mutation(["hello", "hey"])`应该返回false。 <add>`mutation(["hello", "hey"])` 应返回 false。 <ide> <ide> ```js <ide> assert(mutation(['hello', 'hey']) === false); <ide> ``` <ide> <del>`mutation(["hello", "Hello"])`应该返回true。 <add>`mutation(["hello", "Hello"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['hello', 'Hello']) === true); <ide> ``` <ide> <del>`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])`应该返回true。 <add>`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true); <ide> ``` <ide> <del>`mutation(["Mary", "Army"])`应该返回true。 <add>`mutation(["Mary", "Army"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['Mary', 'Army']) === true); <ide> ``` <ide> <del>`mutation(["Mary", "Aarmy"])`应该返回true。 <add>`mutation(["Mary", "Aarmy"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['Mary', 'Aarmy']) === true); <ide> ``` <ide> <del>`mutation(["Alien", "line"])`应该返回true。 <add>`mutation(["Alien", "line"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['Alien', 'line']) === true); <ide> ``` <ide> <del>`mutation(["floor", "for"])`应该返回true。 <add>`mutation(["floor", "for"])` 应返回 true。 <ide> <ide> ```js <ide> assert(mutation(['floor', 'for']) === true); <ide> ``` <ide> <del>`mutation(["hello", "neo"])`应该返回false。 <add>`mutation(["hello", "neo"])` 应返回 false。 <ide> <ide> ```js <ide> assert(mutation(['hello', 'neo']) === false); <ide> ``` <ide> <del>`mutation(["voodoo", "no"])`应该返回false。 <add>`mutation(["voodoo", "no"])` 应返回 false。 <add> <add>```js <add>assert(mutation(['voodoo', 'no']) === false); <add>``` <add> <add>`mutation(["voodoo", "no"])` 应返回 false。 <ide> <ide> ```js <ide> assert(mutation(['voodoo', 'no']) === false); <ide> ``` <ide> <add>`mutation(["ate", "date"]` 应返回 false。 <add> <add>```js <add>assert(mutation(['ate', 'date']) === false); <add>``` <add> <add>`mutation(["Tiger", "Zebra"])` 应返回 false。 <add> <add>```js <add>assert(mutation(['Tiger', 'Zebra']) === false); <add>``` <add> <add>`mutation(["Noel", "Ole"])` 应返回 true。 <add> <add>```js <add>assert(mutation(['Noel', 'Ole']) === true); <add>``` <add> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string.md <ide> --- <ide> id: afcc8d540bea9ea2669306b6 <del>title: 重复一个字符串重复字符串 <add>title: 重复输出字符串 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16041 <ide> --- <ide> <ide> # --description-- <ide> <ide> 为`num` times(第二个参数)重复给定的字符串`str` (第一个参数)。如果`num`不是正数,则返回空字符串。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <ide> <add>将一个给定的字符串 `str`(第一个参数)重复输出 `num`(第二个参数)次。如果 `num` 不是正数,返回空字符串。在这个挑战中,请不要使用 JavaScript 内置的 `.repeat()` 方法。 <add> <add> <ide> # --hints-- <ide> <del>`repeatStringNumTimes("*", 3)`应该返回`"***"` 。 <add>`repeatStringNumTimes("*", 3)` 应返回 `"***"`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('*', 3) === '***'); <ide> ``` <ide> <del>`repeatStringNumTimes("abc", 3)`应该返回`"abcabcabc"` 。 <add>`repeatStringNumTimes("abc", 3)` 应返回 `"abcabcabc"`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('abc', 3) === 'abcabcabc'); <ide> ``` <ide> <del>`repeatStringNumTimes("abc", 4)`应返回`"abcabcabcabc"` 。 <add>`repeatStringNumTimes("abc", 4)` 应返回 `"abcabcabcabc"`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc'); <ide> ``` <ide> <del>`repeatStringNumTimes("abc", 1)`应该返回`"abc"` 。 <add>`repeatStringNumTimes("abc", 1)` 应返回 `"abc"`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('abc', 1) === 'abc'); <ide> ``` <ide> <del>`repeatStringNumTimes("*", 8)`应该返回`"********"` 。 <add>`repeatStringNumTimes("*", 8)` 应返回 `"********"`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('*', 8) === '********'); <ide> ``` <ide> <del>`repeatStringNumTimes("abc", -2)`应返回`""` 。 <add>`repeatStringNumTimes("abc", -2)` 应返回 `""`。 <ide> <ide> ```js <ide> assert(repeatStringNumTimes('abc', -2) === ''); <ide> ``` <ide> <del>不应使用内置的`repeat()`方法 <add>不应使用内置的 `repeat()` 方法。 <ide> <ide> ```js <ide> assert(!/\.repeat/g.test(code)); <ide> ``` <ide> <add>`repeatStringNumTimes("abc", 0)` 应返回 `""`。 <add> <add>```js <add>assert(repeatStringNumTimes('abc', 0) === ''); <add>``` <add> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays.md <ide> --- <ide> id: a789b3483989747d63b0e427 <del>title: 返回数组中的最大数字 <add>title: 找出多个数组中的最大数字 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16042 <ide> --- <ide> <ide> # --description-- <ide> <del>返回一个数组,该数组由每个提供的子数组中的最大数字组成。为简单起见,提供的数组将包含4个子数组。请记住,您可以使用简单的for循环遍历数组,并使用数组语法`arr[i]`访问每个成员。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>请返回一个数组,该数组由参数中每个子数组中的最大数字组成。为简单起见,给出的数组总会包含 4 个子数组。 <add> <add>别忘了,你可以通过 for 循环遍历一个数组,并用 `arr[i]` 的写法来访问数组中的元素。 <ide> <ide> # --hints-- <ide> <del>`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])`应该返回一个数组。 <add>`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 应返回一个数组。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])`应该返回`[27, 5, 39, 1001]` `largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` `[27, 5, 39, 1001]` 。 <add>`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` 应返回 `[27, 5, 39, 1001]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])`应该返回`[9, 35, 97, 1000000]` `largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` `[9, 35, 97, 1000000]` 。 <add>`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` 应返回 `[9, 35, 97, 1000000]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])`应该返回`[25, 48, 21, -3]` 。 <add>`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` 应返回 `[25, 48, 21, -3]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string.md <ide> id: a202eed8fc186c8434cb6d61 <ide> title: 反转字符串 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16043 <ide> --- <ide> <ide> # --description-- <ide> <del>反转提供的字符串。您可能需要先将字符串转换为数组,然后才能将其反转。您的结果必须是字符串。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>请反转传入函数的字符串。 <add> <add>在反转字符串之前,你可能需要将其切分成包含字符的数组。 <add> <add>函数的返回结果应为字符串。 <ide> <ide> # --hints-- <ide> <del>`reverseString("hello")`应该返回一个字符串。 <add>`reverseString("hello")` 应返回一个字符串。 <ide> <ide> ```js <ide> assert(typeof reverseString('hello') === 'string'); <ide> ``` <ide> <del>`reverseString("hello")`应该变成`"olleh"` 。 <add>`reverseString("hello")` 应返回 `"olleh"`。 <ide> <ide> ```js <ide> assert(reverseString('hello') === 'olleh'); <ide> ``` <ide> <del>`reverseString("Howdy")`应该变成`"ydwoH"` 。 <add>`reverseString("Howdy")` 应返回 `"ydwoH"`。 <ide> <ide> ```js <ide> assert(reverseString('Howdy') === 'ydwoH'); <ide> ``` <ide> <del>`reverseString("Greetings from Earth")`应返回`"htraE morf sgniteerG"` 。 <add>`reverseString("Greetings from Earth")` 应返回 `"htraE morf sgniteerG"`。 <ide> <ide> ```js <ide> assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice.md <ide> --- <ide> id: 579e2a2c335b9d72dd32e05c <del>title: 切片和拼接 <add>title: Slice 与 Splice <ide> challengeType: 5 <ide> forumTopicId: 301148 <ide> --- <ide> <ide> # --description-- <ide> <del>您将获得两个数组和一个索引。使用数组方法`slice`和`splice`按顺序将第一个数组的每个元素复制到第二个数组中。开始在第二个数组的索引`n`处插入元素。返回结果数组。函数运行后,输入数组应保持不变。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>本挑战的输入参数为两个数组和一个索引值。 <add> <add>请使用数组的 `slice` 和 `splice` 方法,将第一个数组中的所有元素依次复制到第二个数组中。 <add> <add>请注意,你需要从第二个数组索引值为 `n`(函数的第三个参数)的地方开始插入。 <add> <add>最后,请返回插入元素后的数组。作为输入参数的两个数组在函数执行前后应保持不变。 <ide> <ide> # --hints-- <ide> <del>`frankenSplice([1, 2, 3], [4, 5], 1)`应该返回`[4, 1, 2, 3, 5]`。 <add>`frankenSplice([1, 2, 3], [4, 5], 1)` 应返回 `[4, 1, 2, 3, 5]`。 <ide> <ide> ```js <ide> assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]); <ide> ``` <ide> <del>`frankenSplice([1, 2], ["a", "b"], 1)` 应返回 `["a", 1, 2, "b"]` <add>`frankenSplice([1, 2], ["a", "b"], 1)` 应返回 `["a", 1, 2, "b"]`。 <ide> <ide> ```js <ide> assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']); <ide> ``` <ide> <del>`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` 应该返回 `["head", "shoulders", "claw", "tentacle", "knees", "toes"]` <add>`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` 应返回 `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence.md <ide> --- <ide> id: ab6137d4e35944e21037b769 <del>title: 标题案例句子 <add>title: 句中单词首字母大写 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16088 <ide> --- <ide> <ide> # --description-- <ide> <del>返回提供的字符串,每个单词的首字母大写。确保单词的其余部分为小写。出于本练习的目的,您还应该将诸如“the”和“of”之类的连接词大写。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>请将传入的字符串中,每个单词的第一个字母变成大写并返回。注意除首字母外,其余的字符都应是小写的。 <add> <add>另外请注意,像是 “the”、“of” 之类的连接词的首字母也要大写。 <ide> <ide> # --hints-- <ide> <del>`titleCase("I'm a little tea pot")`应该返回一个字符串。 <add>`titleCase("I'm a little tea pot")` 应返回一个字符串。 <ide> <ide> ```js <ide> assert(typeof titleCase("I'm a little tea pot") === 'string'); <ide> ``` <ide> <del>`titleCase("I'm a little tea pot")`应该归还`I'm A Little Tea Pot` 。 <add>`titleCase("I'm a little tea pot")` 应返回 `I'm A Little Tea Pot`。 <ide> <ide> ```js <ide> assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot"); <ide> ``` <ide> <del>`titleCase("sHoRt AnD sToUt")`应返回`Short And Stout` 。 <add>`titleCase("sHoRt AnD sToUt")` 应返回 `Short And Stout`。 <ide> <ide> ```js <ide> assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout'); <ide> ``` <ide> <del>`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` `Here Is My Handle Here Is My Spout` `titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")`应该回到`Here Is My Handle Here Is My Spout` 。 <add>`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` 应返回 `Here Is My Handle Here Is My Spout`。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string.md <ide> id: ac6993d51946422351508a41 <ide> title: 截断字符串 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16089 <ide> --- <ide> <ide> # --description-- <ide> <del>如果字符串(第一个参数)长于给定的最大字符串长度(第二个参数),则截断该字符串。返回带有`...`结尾的截断字符串。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>如果传入的字符串(第一个参数)的长度大于传入的值(第二个参数),请在这个位置截断它并在后面加上 `...`,然后返回结果。 <ide> <ide> # --hints-- <ide> <del>`truncateString("A-tisket a-tasket A green and yellow basket", 8)`应该返回“A-tisket ......”。 <add>`truncateString("A-tisket a-tasket A green and yellow basket", 8)` 应返回 "A-tisket..."。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`truncateString("Peter Piper picked a peck of pickled peppers", 11)`应该回归“Peter Piper ......”。 <add>`truncateString("Peter Piper picked a peck of pickled peppers", 11)` 应返回 "Peter Piper..."。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)`应该返回“A-tisket a-tasket A green and yellow basket”。 <add>`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` 应返回 "A-tisket a-tasket A green and yellow basket"。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)`应返回“A-tisket a-tasket A green and yellow basket”。 <add>`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` 应返回 "A-tisket a-tasket A green and yellow basket"。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`truncateString("A-", 1)`应返回“A ...”。 <add>`truncateString("A-", 1)` 应返回 "A..."。 <ide> <ide> ```js <ide> assert(truncateString('A-', 1) === 'A...'); <ide> ``` <ide> <del>`truncateString("Absolutely Longer", 2)`应返回“Ab ...”。 <add>`truncateString("Absolutely Longer", 2)` 应返回 "Ab..."。 <ide> <ide> ```js <ide> assert(truncateString('Absolutely Longer', 2) === 'Ab...'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong.md <ide> --- <ide> id: a24c1a4622e3c05097f71d67 <del>title: 我属于哪里? <add>title: 找出元素在排序后数组中的索引 <ide> challengeType: 5 <del>videoUrl: '' <add>forumTopicId: 16094 <ide> --- <ide> <ide> # --description-- <ide> <del>返回一个值(第二个参数)应该在排序后插入数组(第一个参数)的最低索引。返回的值应该是一个数字。例如, `getIndexToIns([1,2,3,4], 1.5)`应返回`1`因为它大于`1` (索引0),但小于`2` (索引1)。同样, `getIndexToIns([20,3,5], 19)`应返回`2`因为一旦数组已经排序,它将看起来像`[3,5,20]` , `19`小于`20` (索引2)并且大于`5` (指数1)。如果卡住,请记得使用[Read-Search-Ask](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck-coding/19514) 。编写自己的代码。 <add>第一个参数的数组在排序后,将一个值(第二个参数)插入该数组,并使数组保持有序。返回这个新插入元素的**最小**索引值(应为一个数字)。 <add> <add>例如,`getIndexToIns([1,2,3,4], 1.5)` 应该返回 `1` 因为 `1.5` 大于 `1`(索引为 0)且小于 `2`(索引为 1)。 <add> <add>同样地,`getIndexToIns([20,3,5], 19)` 应该返回 `2`。因为数组排序后会变成 `[3,5,20]`,而 `19` 小于 `20`(索引为 2)且大于 `5`(索引为 1)。 <ide> <ide> # --hints-- <ide> <del>`getIndexToIns([10, 20, 30, 40, 50], 35)`应返回`3` 。 <add>`getIndexToIns([10, 20, 30, 40, 50], 35)` 应返回 `3`。 <ide> <ide> ```js <ide> assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3); <ide> ``` <ide> <del>`getIndexToIns([10, 20, 30, 40, 50], 35)`应返回一个数字。 <add>`getIndexToIns([10, 20, 30, 40, 50], 35)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([10, 20, 30, 40, 50], 30)`应该返回`2` 。 <add>`getIndexToIns([10, 20, 30, 40, 50], 30)` 应返回 `2`。 <ide> <ide> ```js <ide> assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2); <ide> ``` <ide> <del>`getIndexToIns([10, 20, 30, 40, 50], 30)`应该返回一个数字。 <add>`getIndexToIns([10, 20, 30, 40, 50], 30)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([40, 60], 50)`应返回`1` 。 <add>`getIndexToIns([40, 60], 50)` 应返回 `1`。 <ide> <ide> ```js <ide> assert(getIndexToIns([40, 60], 50) === 1); <ide> ``` <ide> <del>`getIndexToIns([40, 60], 50)`应返回一个数字。 <add>`getIndexToIns([40, 60], 50)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([40, 60], 50) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([3, 10, 5], 3)`应该返回`0` 。 <add>`getIndexToIns([3, 10, 5], 3)` 应返回 `0`。 <ide> <ide> ```js <ide> assert(getIndexToIns([3, 10, 5], 3) === 0); <ide> ``` <ide> <del>`getIndexToIns([3, 10, 5], 3)`应返回一个数字。 <add>`getIndexToIns([3, 10, 5], 3)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([3, 10, 5], 3) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([5, 3, 20, 3], 5)`应返回`2` 。 <add>`getIndexToIns([5, 3, 20, 3], 5)` 应返回 `2`。 <ide> <ide> ```js <ide> assert(getIndexToIns([5, 3, 20, 3], 5) === 2); <ide> ``` <ide> <del>`getIndexToIns([5, 3, 20, 3], 5)`应返回一个数字。 <add>`getIndexToIns([5, 3, 20, 3], 5)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([2, 20, 10], 19)`应该返回`2` 。 <add>`getIndexToIns([2, 20, 10], 19)` 应返回 `2`。 <ide> <ide> ```js <ide> assert(getIndexToIns([2, 20, 10], 19) === 2); <ide> ``` <ide> <del>`getIndexToIns([2, 20, 10], 19)`应返回一个数字。 <add>`getIndexToIns([2, 20, 10], 19)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([2, 20, 10], 19) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([2, 5, 10], 15)`应该返回`3` 。 <add>`getIndexToIns([2, 5, 10], 15)` 应返回 `3`。 <ide> <ide> ```js <ide> assert(getIndexToIns([2, 5, 10], 15) === 3); <ide> ``` <ide> <del>`getIndexToIns([2, 5, 10], 15)`应返回一个数字。 <add>`getIndexToIns([2, 5, 10], 15)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([2, 5, 10], 15) === 'number'); <ide> ``` <ide> <del>`getIndexToIns([], 1)`应该返回`0` 。 <add>`getIndexToIns([], 1)`应该返回 `0`。 <ide> <ide> ```js <ide> assert(getIndexToIns([], 1) === 0); <ide> ``` <ide> <del>`getIndexToIns([], 1)`应该返回一个数字。 <add>`getIndexToIns([], 1)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof getIndexToIns([], 1) === 'number'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation.md <ide> --- <ide> id: 5a661e0f1068aca922b3ef17 <del>title: 使用方括号访问数组的内容 <add>title: 使用方括号访问数组的元素 <ide> challengeType: 1 <ide> forumTopicId: 301149 <ide> --- <ide> <ide> # --description-- <ide> <del>所有数据结构的基本特性是,它们不仅能够存储数据,我们还能够按照需求来访问存放在其中的数据。我们已经学习了如何创建一个数组结构,现在让我们开始学习如何访问这个数组结构中的数据。 <add>所有数据结构的基本特性是,它们不仅可以存储数据,还可以让我们按需访问存放在其中的数据。我们已经学习了如何创建数组,现在让我们来学习如何访问数组中的数据。 <ide> <ide> 我们先定义一个包含 3 个元素的数组: <ide> <ide> ```js <ide> let ourArray = ["a", "b", "c"]; <ide> ``` <ide> <del>在一个数组结构中,其内部的每个元素都有一个与之对应的<dfn>索引</dfn>(<dfn>index</dfn>)。索引是该元素在数组中的位置,可被用于引用该元素。但需要注意的是,JavaScript 数组的索引是从0开始的(<dfn>zero-indexed</dfn>),即一个数组的第一个元素是在数组中的***第 0 个***位置,而不是第 1 个位置。 要从一个数组中获取一个元素,我们可以在一个数组变量名的后面加一个使用“方括号”括起来的索引。这叫做<dfn>方括号符号</dfn>(<dfn>bracket notation</dfn>)。 例如我们要从`ourArray`数组变量中获取数据元素`"a"`并将其赋值给一个变量,我们可以编写如下所示的代码: <add>在数组中,内部的每个元素都有一个与之对应的<dfn>索引</dfn>(<dfn>index</dfn>)。索引既是该元素在数组中的位置,也是我们访问该元素的参考。需要注意的是,JavaScript 数组的索引是从 0 开始的(这种从 0 开始的规则叫做 <dfn>zero-indexed</dfn>),即数组的第一个元素是在数组中的***第 0 个***位置,而不是第 1 个位置。要从数组中获取一个元素,我们可以在数组字面量后面加一个用方括号(`[]`)括起来的索引。不过习惯上,我们会通过表示数组的变量名来访问,而不是直接通过字面量。这种从数组中读取元素的方式叫做<dfn>方括号表示法</dfn>(<dfn>bracket notation</dfn>)。如果我们要从数组 `ourArray` 中获取数据元素 `"a"` 并将其赋值给另一个变量,可以这样写: <ide> <ide> ```js <ide> let ourVariable = ourArray[0]; <ide> // ourVariable 的值为 "a" <ide> ``` <ide> <del>除了使用 “索引” 来获取某个元素值以外,你还可以通过类似的方法来*设置*一个索引位置所对应的元素值: <add>除了使用索引来获取某个元素值以外,你还可以通过类似的写法来*设置*一个索引位置的元素值: <ide> <ide> ```js <ide> ourArray[1] = "not b anymore"; <ide> // ourArray 现在的值为 ["a", "not b anymore", "c"]; <ide> ``` <ide> <del>我们现在已经利用方括号将索引为 1 的元素从`"b"`设置为了`"not b anymore"`。 <add>在上面的代码中,我们用方括号表示法把索引为 1 的元素从 `"b"` 改成了 `"not b anymore"`。 <ide> <ide> # --instructions-- <ide> <del>在本挑战中,请你将`myArray`中第二个元素(索引`1`)设置为除了`"b"`以外的任意值。 <add>在本挑战中,请将 `myArray` 中的第二个元素(索引为 `1`)设置为除了 `"b"` 以外的任意值。 <ide> <ide> # --hints-- <ide> <del>`myArray[0]`等于`"a"` <add>`myArray[0]` 应为 `"a"`。 <ide> <ide> ```js <ide> assert.strictEqual(myArray[0], 'a'); <ide> ``` <ide> <del>`myArray[1]`不再设置为`"b"` <add>`myArray[1]` 不应为 `"b"`。 <ide> <ide> ```js <ide> assert.notStrictEqual(myArray[1], 'b'); <ide> ``` <ide> <del>`myArray[2]`等于`"c"` <add>`myArray[2]` 应为 `"c"`。 <ide> <ide> ```js <ide> assert.strictEqual(myArray[2], 'c'); <ide> ``` <ide> <del>`myArray[3]`等于`"d"` <add>`myArray[3]` 应为 `"d"`。 <ide> <ide> ```js <ide> assert.strictEqual(myArray[3], 'd'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation.md <ide> forumTopicId: 301150 <ide> <ide> # --description-- <ide> <del>在关于对象的第一个挑战中,我们提到可以在方括号符号中用一个变量作为属性名来访问属性值。假设一个超市的收银台的程序中使用了一个`foods`对象,并且有一些程序逻辑会设置`selectedFood`,我们需要查询`foods`对象来检查某种食物是否存在,我们可以这样写检查逻辑: <add>在关于对象的第一个挑战中,我们提到可以在一对方括号中用一个变量作为属性名来访问属性的值。假设一个超市收银台程序中有一个 `foods` 对象,并且有一个函数会设置 `selectedFood`;如果我们需要查询 `foods` 对象中,某种食物是否存在,可以这样实现: <ide> <ide> ```js <ide> let selectedFood = getCurrentFood(scannedItem); <ide> let inventory = foods[selectedFood]; <ide> ``` <ide> <del>上述代码会先计算`selectedFood`变量的值,并返回`foods`对象中以该值命名的属性对应的值,若没有以该值命名的属性则会返回`undefined`。有时候对象的属性名在运行之前是不确定的,或者我们需要动态地访问对象的属性,这时方括号符号就会很有用。 <add>上述代码会先读取 `selectedFood` 变量的值,并返回 `foods` 对象中以该值命名的属性所对应的属性值。若没有以该值命名的属性,则会返回 `undefined`。有时候对象的属性名在运行之前是不确定的,或者我们需要动态地访问对象的属性值。在这些场景下,方括号表示法就变得十分有用。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`checkInventory`函数,它接受一个被扫描到的商品名作为输入参数。它要返回`foods`对象中以`scannedItem`的值命名的属性的值。只有有效的属性名会作为参数传入`checkInventory`,你在完成挑战时不需处理参数无效的情况。 <add>我们已经定义了 `checkInventory` 函数,它接受一个被扫描到的商品名作为输入参数。请让这个函数返回 `foods` 对象中,以 `scannedItem` 的值所命名的属性对应的属性值。在本挑战中,只有合理有效的属性名会作为参数传入 `checkInventory`,因此你不需要处理参数无效的情况。 <ide> <ide> # --hints-- <ide> <del>`checkInventory`是一个函数 <add>`checkInventory` 应是一个函数。 <ide> <ide> ```js <ide> assert.strictEqual(typeof checkInventory, 'function'); <ide> ``` <ide> <del>`foods`对象应该只有以下键值对: `apples: 25` , `oranges: 32` , `plums: 28` , `bananas: 13` , `grapes: 35` , `strawberries: 27` <add>`foods` 对象应只包含以下键值对:`apples: 25`、`oranges: 32`、`plums: 28`、`bananas: 13`、`grapes: 35`、`strawberries: 27`。 <ide> <ide> ```js <ide> assert.deepEqual(foods, { <ide> assert.deepEqual(foods, { <ide> }); <ide> ``` <ide> <del>`checkInventory("apples")`应该返回`25` <add>`checkInventory("apples")` 应返回 `25`。 <ide> <ide> ```js <ide> assert.strictEqual(checkInventory('apples'), 25); <ide> ``` <ide> <del>`checkInventory("bananas")`应该返回`13` <add>`checkInventory("bananas")` 应返回 `13`。 <ide> <ide> ```js <ide> assert.strictEqual(checkInventory('bananas'), 13); <ide> ``` <ide> <del>`checkInventory("strawberries")`应该返回`27` <add>`checkInventory("strawberries")` 应返回 `27`。 <ide> <ide> ```js <ide> assert.strictEqual(checkInventory('strawberries'), 27); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift.md <ide> --- <ide> id: 587d78b2367417b2b2512b0e <del>title: 使用 push() 和 unshift() 添加项目到数组中 <add>title: 使用 push() 和 unshift() 为数组添加元素 <ide> challengeType: 1 <ide> forumTopicId: 301151 <ide> --- <ide> <ide> # --description-- <ide> <del>一个数组的长度与其包含的数据类型一样,是不固定的。数组可以包含任意数量的元素,可以不限次数地往数组中添加元素或者从中移除元素,或者说数组是<dfn>可变的</dfn>(<dfn>mutable</dfn>)。在本挑战中,我们要学习两个以编程方式修改数组的方法:`Array.push()`和`Array.unshift()`。 <add>数组的长度与数组能包含的数据类型一样,都是不固定的。数组可以包含任意数量的元素,可以不限次数地往数组中添加元素或者从中移除元素。总之,数组是<dfn>可变的</dfn>(<dfn>mutable</dfn>)。在本挑战中,我们要学习两种修改数组的方法:`Array.push()` 和 `Array.unshift()`。 <ide> <del>这两个方法都接收一个或多个元素作为参数;对一个数组调用这两个方法都可以将输入的元素插入到该数组中;`push()`方法将元素插入到一个数组的末尾,而`unshift()`方法将元素插入到一个数组的开头。请看以下例子: <add>这两个方法都接收一个或多个元素作为参数,并会将参数中的元素添加到该数组中。`push()` 方法会将元素插入到数组的末尾,而 `unshift()` 方法会将元素插入到数组的开头。请看以下例子: <ide> <ide> ```js <ide> let twentyThree = 'XXIII'; <ide> romanNumerals.push(twentyThree); <ide> // 数组现在为 ['XIX', 'XX', 'XXI', 'XXII', 'XXIII'] <ide> ``` <ide> <del>注意,我们还可以输入变量,这允许我们很灵活地动态改变我们数组中的数据。 <add>**注意:**我们甚至可以传入变量,这在动态改变数组数据的场景下十分有用。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`mixedNumbers`函数,它会接受一个数组作为参数。请你修改这个函数,使用`push()`和`unshift()`来将`'I', 2, 'three'`插入到数组的开头,将`7, 'VIII', 9`插入到数组的末尾,使得这个函数返回一个依次包含 1-9 的数组。 <add>我们已经定义了一个 `mixedNumbers` 函数,它接收一个数组作为参数。请你修改这个函数,使用 `push()` 和 `unshift()` 来将 `'I', 2, 'three'` 插入到数组开头,将 `7, 'VIII', 9` 插入到数组的末尾,使得这个函数返回一个依次包含 1 至 9。 <ide> <ide> # --hints-- <ide> <del>`mixedNumbers(["IV", 5, "six"])`现在应该返回`["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]` <add>`mixedNumbers(["IV", 5, "six"])` 应返回 `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`。 <ide> <ide> ```js <ide> assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [ <ide> assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [ <ide> ]); <ide> ``` <ide> <del>`mixedNumbers`函数应该使用`push()`方法 <add>`mixedNumbers` 函数中应调用 `push()` 方法。 <ide> <ide> ```js <ide> assert(mixedNumbers.toString().match(/\.push/)); <ide> ``` <ide> <del>`mixedNumbers`函数应该使用`unshift()`方法 <add>`mixedNumbers` 函数中应调用 `unshift()` 方法。 <ide> <ide> ```js <ide> assert(mixedNumbers.toString().match(/\.unshift/)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.md <ide> --- <ide> id: 587d78b3367417b2b2512b11 <del>title: 使用 splice() 增加项目 <add>title: 使用 splice() 添加元素 <ide> challengeType: 1 <ide> forumTopicId: 301152 <ide> --- <ide> <ide> # --description-- <ide> <del>你还记得在上个挑战中我们提到`splice()`方法可以接受最多 3 个参数吗?我们现在可以进一步了解`splice()`。除了移除元素,我们还可以利用它的第三个参数来向数组中*添加*元素。第三个参数可以是一个或多个元素,这些元素会被添加到数组中。这使我们能够便捷地将数组中的一个或一系列元素换成其他的元素。例如: <add>还记得在上个挑战中我们提到 `splice()` 方法最多可以接收 3 个参数吗?除了移除元素,我们还可以利用它的第三个参数来向数组中*添加*元素。第三个参数可以是一个或多个元素,这些元素会被添加到数组中。这样,我们能够便捷地将数组中的一个或多个连续元素换成其他的元素。例如: <ide> <ide> ```js <ide> const numbers = [10, 11, 12, 12, 15]; <ide> console.log(numbers); <ide> // 返回 [ 10, 11, 12, 13, 14, 15 ] <ide> ``` <ide> <del>以一个数字数组开始。接着调用 `splice()` 方法,在 (3) 的索引位置开始删除元素,删除的元素数量是 (1),(13, 14) 是在删除位置插入的元素,可以在 `amountToDelete` 后面插入任意数量的元素(以逗号分隔),每个都会被插入。 <add>在上面的代码中,数组一开始包含了若干数字。接着,我们调用 `splice()` 方法,索引为 (3) 的地方开始删除元素,删除的元素数量是 (1)。然后,(13, 14) 是在删除位置插入的元素,可以在 `amountToDelete` 后面传入任意数量的元素(以逗号分隔),每个都会被插入到数组中。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`htmlColorNames`函数,它以一个 HTML 颜色的数组作为输入参数。请修改这个函数,利用`splice()`来移除数组中的前两个元素,并在对应的位置上添加`'DarkSalmon'`和`'BlanchedAlmond'`。 <add>我们已经定义了一个 `htmlColorNames` 函数,它以一个 HTML 颜色的数组作为输入参数。请修改这个函数,使用 `splice()` 来移除数组中的前两个元素,并在对应的位置上添加 `'DarkSalmon'` 和 `'BlanchedAlmond'`。 <ide> <ide> # --hints-- <ide> <del>`htmlColorNames`应该返回`["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]` <add>`htmlColorNames` 应返回 `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`htmlColorNames`函数应该使用`splice()`方法 <add>`htmlColorNames` 函数中应调用 `splice()` 方法。 <ide> <ide> ```js <ide> assert(/.splice/.test(code)); <ide> ``` <ide> <del>你不应该使用`shift()`或`unshift()` 。 <add>不应使用 `shift()` 或 `unshift()`。 <ide> <ide> ```js <ide> assert(!/shift|unshift/.test(code)); <ide> ``` <ide> <del>您不应该使用数组括号表示法。 <add>不应使用数组的方括号表示法。 <ide> <ide> ```js <ide> assert(!/\[\d\]\s*=/.test(code)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.md <ide> forumTopicId: 301153 <ide> <ide> # --description-- <ide> <del>对象(object)本质上是<dfn>键值对(key-value pair)</dfn>的集合,或者说,一系列被映射到唯一标识符(叫做<dfn>属性(property)</dfn>或者<dfn>键(key)</dfn>)的数据。让我们来看一个很简单的例子: <add>对象(object)本质上是<dfn>键值对(key-value pair)</dfn>的集合。或者说,一系列被映射到唯一标识符的数据就是对象;习惯上,唯一标识符叫做<dfn>属性(property)</dfn>或者<dfn>键(key)</dfn>);数据叫做<dfn>值(value)</dfn>。让我们来看一个简单的例子: <ide> <ide> ```js <del>let FCC_User = { <del> username: 'awesome_coder', <del> followers: 572, <del> points: 1741, <del> completedProjects: 15 <add>const tekkenCharacter = { <add> player: 'Hwoarang', <add> fightingStyle: 'Tae Kwon Doe', <add> human: true <ide> }; <ide> ``` <ide> <del>上面的代码定义了一个叫做`FCC_User`的对象,它有 4 个<dfn>属性</dfn>,每个属性映射一个特定的值。如果我们想知道`FCC_User`有多少`followers`,我们可以这样访问其`followers`属性: <add>上面的代码定义了一个叫做 `tekkenCharacter` 的“铁拳”游戏人物对象。它有三个属性,每个属性都对应一个特定的值。如果我们想为它再添加一个叫做 `origin` 的属性,可以这样写: <ide> <ide> ```js <del>let userData = FCC_User.followers; <del>// userData 等于 572 <add>tekkenCharacter.origin = 'South Korea'; <ide> ``` <ide> <del>这叫做<dfn>点符号(dot notation)</dfn>。我们还可以用方括号符号来访问对象中的属性: <add>上面的代码中,我们使用了<dfn>点号表示法(dot notation)</dfn>。如果我们现在输出这个对象,便可以看到它具有 `origin` 属性。接下来,因为这个人物在游戏中有着与众不同的橘色头发,我们可以通过方括号表示法来为它添加这个属性,像这样: <ide> <ide> ```js <del>let userData = FCC_User['followers']; <del>// userData 等于 572 <add>tekkenCharacter['hair color'] = 'dyed orange'; <ide> ``` <ide> <del>注意,在用<dfn>方括号符号</dfn>时,我们在括号里写的是字符串`followers`(用引号括起)。方括号符号让我们能用一个变量作为属性名来访问对象的属性(请记住)。若我们在方括号中不写引号而直接写`followers`,JavaScript 引擎会将其看作一个变量,并抛出一个`ReferenceError: followers is not defined`的错误。 <add>如果要设置的属性中存在空格,或者要设置的属性是一个变量,那我们必须使用<dfn>方括号表示法(bracket notation)</dfn>来为对象添加属性。在上面的代码中,我们把属性 `hair color` 放到引号里,以此来表示整个字符串都是需要设置的属性。如果我们不加上引号,那么中括号里的内容会被当作一个变量来解析,这个变量对应的值就会作为要设置的属性,请看这段代码: <add> <add>```js <add>const eyes = 'eye color'; <add> <add>tekkenCharacter[eyes] = 'brown'; <add>``` <add> <add>执行以上所有示例代码后,对象会变成这样: <add> <add>```js <add>{ <add> player: 'Hwoarang', <add> fightingStyle: 'Tae Kwon Doe', <add> human: true, <add> origin: 'South Korea', <add> 'hair color': 'dyed orange', <add> 'eye color': 'brown' <add>}; <add>``` <ide> <ide> # --instructions-- <ide> <del>用这样的语法,我们还可以向对象中***新增***键值对。我们已经创建了一个有 3 个属性的`foods`对象,请为其新增 3 项:值为`13`的`bananas`属性、值为`35`的`grapes`属性和值为`27`的`strawberries`属性。 <add>我们已经为你创建了 `foods` 对象。请使用上述任意语法,来为 `foods` 对象添加如下三个键值对:`bananas` 属性,值为 `13`;`grapes` 属性,值为 `35`;`strawberries` 属性,值为 `27`。 <ide> <ide> # --hints-- <ide> <del>`foods`应该是一个对象。 <add>`foods` 应为一个对象。 <ide> <ide> ```js <ide> assert(typeof foods === 'object'); <ide> ``` <ide> <del>`foods`应该有一个值为`13`的`"bananas"`属性。 <add>`foods` 应有一个值为 `13` 的 `"bananas"` 属性。 <ide> <ide> ```js <ide> assert(foods.bananas === 13); <ide> ``` <ide> <del>`foods`应该有一个值为`35`的`"grapes"`属性。 <add>`foods` 应有一个值为 `35` 的 `"grapes"` 属性。 <ide> <ide> ```js <ide> assert(foods.grapes === 35); <ide> ``` <ide> <del>`foods`应该有一个值为`27`的`"strawberries"`属性。 <add>`foods` 应有一个值为 `27` 的 `"strawberries"` 属性。 <ide> <ide> ```js <ide> assert(foods.strawberries === 27); <ide> ``` <ide> <del>你应该用点符号或者方括号符号来设置对象的属性。 <add>应使用点号表示法或方括号表示法来设置对象的属性。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.md <ide> forumTopicId: 301154 <ide> <ide> # --description-- <ide> <del>由于数组可以在任意时间被修改或者说*被改变(mutated)*,我们不能保证某个数据在一个给定数组中的位置,甚至不能保证该元素还存在于该数组中。幸运的是,JavaScript 给我们提供了另一个内置方法`indexOf()`。这个方法让我们可以便捷地检查某个元素是否存在于一个数组中。`indexOf()`方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回`-1`。 <add>由于数组随时都可以修改或发生“突变”(*mutated*),我们很难保证某个数据始终处于数组中的特定位置,甚至不能保证该元素是否还存在于该数组中。好消息是,JavaScript 为我们提供了内置方法 `indexOf()`。这个方法让我们可以方便地检查某个元素是否存在于数组中。`indexOf()` 方法接受一个元素作为输入参数,并返回该元素在数组中的位置(索引);若该元素不存在于数组中则返回 `-1`。 <ide> <ide> 例如: <ide> <ide> let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears']; <ide> <ide> fruits.indexOf('dates'); // 返回 -1 <ide> fruits.indexOf('oranges'); // 返回 2 <del>fruits.indexOf('pears'); // 返回 1,即第一个出现的 'pears' 元素在数组中的索引为 1 <add>fruits.indexOf('pears'); // 返回 1,因为第一个出现在数组中的 'pears' 元素索引为 1 <ide> ``` <ide> <ide> # --instructions-- <ide> <del>`indexOf()`在快速检查一个数组中是否存在某个元素时非常有用。我们已经定义了一个`quickCheck`函数,它接受一个数组和一个元素作为输入参数。请修改这个函数,利用`indexOf()`方法,使得当输入的数组中含有输入的元素时,函数返回`true`;不含有输入的元素时,函数返回`false`。 <add>`indexOf()` 在快速检查一个数组中是否存在某个元素时非常有用。我们已经定义了一个 `quickCheck` 函数,它接受一个数组和一个元素作为输入参数。请修改这个函数,通过 `indexOf()` 方法,使得当参数数组中包含第二个参数的元素时返回 `true`,不包含时返回 `false`。 <ide> <ide> # --hints-- <ide> <del>`quickCheck(["squash", "onions", "shallots"], "mushrooms")`应该返回`false` <add>`quickCheck(["squash", "onions", "shallots"], "mushrooms")` 应返回 `false`。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`quickCheck(["squash", "onions", "shallots"], "onions")`应该返回`true` <add>`quickCheck(["squash", "onions", "shallots"], "onions")` 应返回 `true`。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`quickCheck([3, 5, 9, 125, 45, 2], 125)`应该返回`true` <add>`quickCheck([3, 5, 9, 125, 45, 2], 125)` 应返回 `true`。 <ide> <ide> ```js <ide> assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true); <ide> ``` <ide> <del>`quickCheck([true, false, false], undefined)`应返回`false` <add>`quickCheck([true, false, false], undefined)` 应返回 `false`。 <ide> <ide> ```js <ide> assert.strictEqual(quickCheck([true, false, false], undefined), false); <ide> ``` <ide> <del>`quickCheck`函数应该使用`indexOf()`方法 <add>`quickCheck` 函数中应使用 `indexOf()` 方法。 <ide> <ide> ```js <ide> assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.md <ide> forumTopicId: 301155 <ide> <ide> # --description-- <ide> <del>现在我们可以新增、修改和移除对象中的属性。但如果我们想知道一个对象中是否含有某个属性呢?JavaScript 为我们提供了两种不同的方式来实现这个功能,一个是`hasOwnProperty()`方法,另一个是`in`关键字。如果我们有一个`users`对象,它有一个`Alan`属性,我们可以用以下两种方式之一来检查该属性在对象中是否存在: <add>我们已经学习了如果添加、修改和移除对象中的属性。但如果我们想知道一个对象中是否包含某个属性呢?JavaScript 为我们提供了两种不同的方式来实现这个功能:一个是通过 `hasOwnProperty()` 方法,另一个是使用 `in` 关键字。假如我们有一个 `users` 对象,为检查它是否含有 `Alan` 属性,可以这样写: <ide> <ide> ```js <ide> users.hasOwnProperty('Alan'); <ide> users.hasOwnProperty('Alan'); <ide> <ide> # --instructions-- <ide> <del>我们已经创建了一个含有一些用户的`users`对象和一个`isEveryoneHere`函数,该函数接受`users`对象作为参数。请完成该函数使其在`users`对象中包含以下 4 个键`Alan`、`Jeff`、`Sarah`和`Ryan`时才返回`true`,否则返回`false`。 <add>我们已经定义了一个包含若干用户信息的 `users` 对象和一个 `isEveryoneHere` 函数,该函数接收 `users` 对象作为参数。请完成该函数使其在 `users` 对象中同时包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 四个属性时才返回 `true`,否则返回 `false`。 <ide> <ide> # --hints-- <ide> <del>`users`对象应该只含有`Alan`、`Jeff`、`Sarah`和`Ryan`4 个键。 <add>`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`isEveryoneHere`函数在`users`对象包含`Alan`、`Jeff`、`Sarah`和`Ryan`4 个键时应该返回`true`。 <add>`isEveryoneHere` 函数在 `users` 对象包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `true`。 <ide> <ide> ```js <ide> assert(isEveryoneHere(users) === true); <ide> ``` <ide> <del>`isEveryoneHere`函数在`users`对象不包含`Alan`、`Jeff`、`Sarah`或`Ryan`4 个键时应该返回`false`。 <add>`isEveryoneHere` 函数在 `users` 对象不包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 4 个属性时应返回 `false`。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>如果 `Jeff` 不是 `users` 对象的属性,函数 `isEveryoneHere` 应该返回 `false`。 <add>如果 `users` 对象中不包含属性 `Jeff`,则函数 `isEveryoneHere` 应返回 `false`。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>如果 `Sarah` 不是 `users` 对象的属性,函数 `isEveryoneHere` 应该返回 `false`。 <add>如果 `users` 对象中不包含属性 `Sarah`,则函数 `isEveryoneHere` 应返回 `false`。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>如果 `Ryan` 不是 `users` 对象的属性,函数 `isEveryoneHere` 应该返回 `false`。 <add>如果 `users` 对象中不包含属性 `Ryan`,则函数 `isEveryoneHere` 应返回 `false`。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.md <ide> --- <ide> id: 587d7b7b367417b2b2512b17 <del>title: 组合使用数组和扩展运算符 <add>title: 使用展开运算符合并数组 <ide> challengeType: 1 <ide> forumTopicId: 301156 <ide> --- <ide> <ide> # --description-- <ide> <del><dfn>展开运算符</dfn>的另一个大用处是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。用传统的语法我们也可以连接两个数组,但只能两个数组首尾相接。而展开语法能使下面的操作变得极其简单: <add><dfn>展开语法</dfn>的另一个重要用途是合并数组,或者将某个数组的所有元素插入到另一个数组的任意位置。我们也可以使用 ES5 的语法连接两个数组,但只能让它们首尾相接。而展开语法可以让这样的操作变得极其简单: <ide> <ide> ```js <ide> let thisArray = ['sage', 'rosemary', 'parsley', 'thyme']; <ide> let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander']; <ide> // thatArray 现在是 ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander'] <ide> ``` <ide> <del>使用展开语法,我们这样就实现了一个用传统方法要写得很复杂冗长的操作。 <add>使用展开语法,我们像这样就可以实现一个用传统方法会写得很复杂且冗长的操作。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个返回`sentence`变量的`spreadOut`函数,请修改该函数,利用<dfn>展开运算符</dfn>使该函数返回数组`['learning', 'to', 'code', 'is', 'fun']`。 <add>我们已经定义了一个返回 `sentence` 变量的 `spreadOut` 函数。请修改这个函数,利用<dfn>展开语法</dfn>使该函数返回数组 `['learning', 'to', 'code', 'is', 'fun']`。 <ide> <ide> # --hints-- <ide> <del>`spreadOut`应该返回`["learning", "to", "code", "is", "fun"]` <add>`spreadOut` 应返回 `["learning", "to", "code", "is", "fun"]`。 <ide> <ide> ```js <ide> assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']); <ide> ``` <ide> <del>`spreadOut`函数里应该用到展开语法 <add>`spreadOut` 函数里应用到展开语法。 <ide> <ide> ```js <ide> assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.md <ide> --- <ide> id: 587d7b7b367417b2b2512b13 <del>title: 使用扩展运算符复制数组 <add>title: 使用展开运算符复制数组 <ide> challengeType: 1 <ide> forumTopicId: 301157 <ide> --- <ide> <ide> # --description-- <ide> <del>`slice()`已经能让我们从一个数组中选择一些元素来复制到新数组中了,而 ES6 中又新引入了一个简洁且可读性强的语法<dfn>展开运算符(spread operator)</dfn>,它能让我们方便地复制数组中的*所有*元素。展开语法是这样的:`...` <add>`slice()` 可以让我们从一个数组中选择一些元素来复制到新数组中,而 ES6 中又引入了一个简洁且可读性强的语法:<dfn>展开运算符(spread operator)</dfn>,它能让我们方便地复制数组中的*所有*元素。展开语法写出来是这样:`...` <ide> <del>在实践中,我们可以这样用展开运算符来复制一个数组: <add>我们可以用展开运算符来复制数组: <ide> <ide> ```js <ide> let thisArray = [true, true, undefined, false, null]; <ide> let thatArray = [...thisArray]; <del>// thatArray 等于 [true, true, undefined, false, null] <del>// thisArray 保持不变,等于 thatArray <add>// thatArray 的值现在也是 [true, true, undefined, false, null] <add>// thisArray 保持不变。现在 thatArray 所包含的值与 thisArray 完全相同 <ide> ``` <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`copyMachine`函数,它接受`arr`(一个数组)和`num`(一个数字)作为输入参数。该函数应该返回一个由`num`个`arr`组成的新数组。我们已经为你写好了大部分的代码,但它还不能正确地工作。请修改这个函数,使用展开语法,使该函数正确工作(提示:我们已经学到过的一个方法很适合用在这里!) <add>我们已经定义了一个 `copyMachine` 函数,它接受 `arr`(一个数组)和 `num`(一个数字)作为输入参数。该函数需要返回一个由 `num` 个 `arr` 组成的新的二维数组。同时,我们写好了大致的流程,只是细节实现还没有写完。请修改这个函数,使用展开语法,使该函数能正常工作(提示:我们已经学到过的一个方法很适合用在这里)! <ide> <ide> # --hints-- <ide> <del>`copyMachine([true, false, true], 2)`应该返回`[[true, false, true], [true, false, true]]` <add>`copyMachine([true, false, true], 2)` 应返回 `[[true, false, true], [true, false, true]]`。 <ide> <ide> ```js <ide> assert.deepEqual(copyMachine([true, false, true], 2), [ <ide> assert.deepEqual(copyMachine([true, false, true], 2), [ <ide> ]); <ide> ``` <ide> <del>`copyMachine([1, 2, 3], 5)`应该返回`[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]` <add>`copyMachine([1, 2, 3], 5)` 应返回 `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`。 <ide> <ide> ```js <ide> assert.deepEqual(copyMachine([1, 2, 3], 5), [ <ide> assert.deepEqual(copyMachine([1, 2, 3], 5), [ <ide> ]); <ide> ``` <ide> <del>`copyMachine([true, true, null], 1)`应该返回`[[true, true, null]]` <add>`copyMachine([true, true, null], 1)` 应返回 `[[true, true, null]]`。 <ide> <ide> ```js <ide> assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]); <ide> ``` <ide> <del>`copyMachine(["it works"], 3)`应该返回`[["it works"], ["it works"], ["it works"]]` <add>`copyMachine(["it works"], 3)` 应返回 `[["it works"], ["it works"], ["it works"]]`。 <ide> <ide> ```js <ide> assert.deepEqual(copyMachine(['it works'], 3), [ <ide> assert.deepEqual(copyMachine(['it works'], 3), [ <ide> ]); <ide> ``` <ide> <del>`copyMachine`函数中应该对数组`arr`使用`spread operator`。 <add>`copyMachine` 函数中应对 `arr` 使用`展开运算符`。 <ide> <ide> ```js <ide> assert(removeJSComments(code).match(/\.\.\.arr/)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.md <ide> --- <ide> id: 587d7b7a367417b2b2512b12 <del>title: 使用 slice() 拷贝数组项目 <add>title: 使用 slice() 复制数组元素 <ide> challengeType: 1 <ide> forumTopicId: 301158 <ide> --- <ide> <ide> # --description-- <ide> <del>接下来我们要介绍`slice()`方法。`slice()`并不修改数组,而是复制或者说*提取(extract)*给定数量的元素到一个新数组里,而调用方法的数组则保持不变。`slice()`只接受 2 个输入参数—第一个是开始提取元素的位置(索引),第二个是结束提取元素的位置(索引)。slice 方法会提取直到截止索引的元素,但被提取的元素不包括截止索引对应的元素。请看以下例子: <add>接下来我们要介绍 `slice()` 方法。`slice()` 不会修改数组,而是会复制,或者说*提取(extract)*给定数量的元素到一个新数组。同时,调用方法的数组保持不变。`slice()` 只接收 2 个输入参数:第一个是开始提取元素的位置(索引),第二个是提取元素的结束位置(索引)。`slice()` 提取的元素中不包括第二个参数所对应的元素。请看以下例子: <ide> <ide> ```js <ide> let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear']; <ide> let todaysWeather = weatherConditions.slice(1, 3); <ide> // weatherConditions 仍然等于 ['rain', 'snow', 'sleet', 'hail', 'clear'] <ide> ``` <ide> <del>现在我们从一个已有的数组中提取了一些元素,并用这些元素创建了一个新数组。 <add>在上面的代码中,我们从一个数组中提取了一些元素,并用这些元素创建了一个新数组。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`forecast`函数,它接受一个数组作为参数。请修改这个函数,利用`slice()`来从输入的数组中提取信息,并返回一个包含元素`'warm'`和`'sunny'` 的新数组。 <add>我们已经定义了一个 `forecast` 函数,它接受一个数组作为参数。请修改这个函数,利用 `slice()` 从输入的数组中提取信息,最终返回一个包含元素 `'warm'` 和 `'sunny'` 的新数组。 <ide> <ide> # --hints-- <ide> <del>`forecast`应该返回`["warm", "sunny"]` <add>`forecast` 应返回 `["warm", "sunny"]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`forecast`函数应该使用`slice()`方法 <add>`forecast` 函数中应使用 `slice()` 方法。 <ide> <ide> ```js <ide> assert(/\.slice\(/.test(code)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.md <ide> forumTopicId: 301159 <ide> <ide> # --description-- <ide> <del>很好!你已经学到很多关于数组的知识了!但这些只是一个开始,你将在接下来的小节中学习到与数组相关的更多知识。但在继续去学习<dfn>对象</dfn>(<dfn>Objects</dfn>)之前,让我们再花一点时间看一看,数组怎样能够变得比之前的挑战中更复杂一点。 <add>很好!你现在已经学到很多关于数组的知识了,但这些只是个开始。我们将在接下来的中挑战中学到更多与数组相关的知识。在继续学习<dfn>对象</dfn>(<dfn>Objects</dfn>)之前,让我们再花一点时间了解下更复杂的数组嵌套。 <ide> <del>数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。我们已经在上一个挑战中看到了包含数组的数组,但它还算是比较简单的。数组中的数组还可以在包含其他数组,数组中是可以嵌套任意层的数组的。数组从而可以被用来实现非常复杂的叫做<dfn>多维(multi-dimensional)</dfn>或嵌套(nested)数组的数据结构。请看如下例子: <add>数组的一个强大的特性是,它可以包含其他数组,甚至完全由其他数组组成。在上一个挑战中,我们已经接触到了包含数组的数组,但它还算是比较简单的。数组中的数组还可以再包含其他数组,即可以嵌套任意多层数组。习惯上,我们称这种数据结构为<dfn>多维(multi-dimensional)数组</dfn>或嵌套(nested)数组。请看如下的示例: <ide> <ide> ```js <del>let nestedArray = [ // 顶层,或第 1 层——最外层的数组 <add>let nestedArray = [ // 顶层,或第 1 层,即最外层数组 <ide> ['deep'], // 数组中的数组,第 2 层 <ide> [ <del> ['deeper'], ['deeper'] // 第 3 层嵌套的两个数组 <add> ['deeper'], ['deeper'] // 第 3 层,元素为嵌套的两个数组 <ide> ], <ide> [ <ide> [ <del> ['deepest'], ['deepest'] // 第 4 层嵌套的两个数组 <add> ['deepest'], ['deepest'] // 第 4 层,元素为嵌套的两个数组 <ide> ], <ide> [ <ide> [ <del> ['deepest-est?'] // 第 5 层嵌套的一个数组 <add> ['deepest-est?'] // 第 5 层,元素为嵌套的一个数组 <ide> ] <ide> ] <ide> ] <ide> ]; <ide> ``` <ide> <del>虽然这个例子看起来错综复杂,但这样复杂的数组并不算罕见,尤其是在处理大量数据的时候。 但我们仍能简单地用方括号符号来访问到嵌套得最深的数组: <add>虽然这个例子看起来错综复杂,不过,尤其是在处理大量数据的时候,这种数据结构还是经常会用到的。尽管结构复杂,不过我们仍可以通过方括号表示法来访问嵌套得最深的数组: <ide> <ide> ```js <ide> console.log(nestedArray[2][1][0][0][0]); <ide> // logs: deepest-est? <ide> ``` <ide> <del>既然我们知道数据在哪里,我们就能修改它: <add>既然我们知道数据的位置,当然,我们也可以修改它: <ide> <ide> ```js <ide> nestedArray[2][1][0][0][0] = 'deeper still'; <ide> console.log(nestedArray[2][1][0][0][0]); <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`myNestedArray`数组变量。请修改`myNestedArray`,用<dfn>字符串(string)</dfn>、<dfn>数字(number)</dfn>或者<dfn>布尔值(boolean)</dfn>作为数组的数据元素,使得`myNestedArray`刚好有 5 层数组嵌套(记住,最外层的数组是第 1 层)。请在第 3 层的数组中包含字符串`'deep'`,在第 4 层的数组中包含字符串`'deeper'`,在第 5 层的数组中包含字符串`'deepest'`。 <add>我们已经定义了一个叫做 `myNestedArray` 的数组变量。请修改 `myNestedArray`,使用<dfn>字符串(string)</dfn>、<dfn>数字(number)</dfn>或<dfn>布尔值(boolean)</dfn>作为数组的元素,并让 `myNestedArray` 刚好有 5 层(注意,最外层的数组是第 1 层)。同时,请在第 3 层的数组中包含字符串 `'deep'`;在第 4 层的数组中包含字符串 `'deeper'`,在第 5 层的数组中包含字符串 `'deepest'`。 <ide> <ide> # --hints-- <ide> <del>`myNestedArray`中的数据元素应当只能是字符串、数字或者布尔值。 <add>`myNestedArray` 中的数据元素应只包含字符串、数字或者布尔值。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`myNestedArray`应该刚好有 5 层数组嵌套。 <add>`myNestedArray` 应刚好包含 5 层嵌套数组。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`myNestedArray`里应该有且只有一个字符串`"deep"`,并且应该出现在第 3 层数组中。 <add>`myNestedArray` 中应只有一个字符串 `"deep"`,并且应出现在第 3 层数组中。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`myNestedArray`里应该有且只有一个字符串`"deeper"`,并且应该出现在第 4 层数组中。 <add>`myNestedArray` 中应只有一个字符串 `"deeper"`,并且应出现在第 4 层数组中。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`myNestedArray`里应该有且只有一个字符串`"deepest"`,并且应该出现在第 5 层数组中。 <add>`myNestedArray` 中应只有一个字符串 `"deepest"`,并且应出现在第 5 层数组中。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object.keys.md <ide> --- <ide> id: 587d7b7d367417b2b2512b1e <del>title: 使用 Object.Keys() 生成对象所有键组成的数组 <add>title: 使用 Object.keys() 生成由对象的所有属性组成的数组 <ide> challengeType: 1 <ide> forumTopicId: 301160 <ide> --- <ide> <ide> # --description-- <ide> <del>我们还可以输入一个对象作为参数来调用`Object.keys()`方法,使其生成一个包含对象中所有键的数组。这会返回一个由对象中所有键的名称(字符串)组成的数组。再次说明,这个数组中的项的顺序是不确定的。 <add>我们可以给 `Object.keys()` 方法传入一个对象作为参数,这会返回一个由对象中所有属性(字符串)组成的数组。需要注意的是,数组中元素的顺序是不确定的。 <ide> <ide> # --instructions-- <ide> <del>请你完成`getArrayOfUsers`函数,使其返回一个包含输入的对象的所有属性的数组。 <add>请完成 `getArrayOfUsers` 函数的实现,使其返回一个由输入对象中的所有属性所组成的数组。 <ide> <ide> # --hints-- <ide> <del>`users`对象应该只包含`Alan`、`Jeff`、`Sarah`和`Ryan`这 4 个键 <add>`users` 对象应该只包含 `Alan`、`Jeff`、`Sarah`、`Ryan` 这 4 个属性。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`getArrayOfUsers`函数应该返回一个包含`users`对象中所有键的数组 <add>`getArrayOfUsers` 函数应返回一个包含 `users` 对象中所有属性的数组。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.md <ide> --- <ide> id: 587d7b7b367417b2b2512b15 <del>title: 使用 For 循环迭代数组的所有项 <add>title: 使用 for 循环遍历数组中的全部元素 <ide> challengeType: 1 <ide> forumTopicId: 301161 <ide> --- <ide> <ide> # --description-- <ide> <del>在进行与数组有关的编程时,我们有时需要遍历数组的所有元素来找出我们需要的元素,或者对数组执行特定的操作。JavaScript 提供了几个内置的方法,它们以不同的方式遍历数组来获得不同的结果(如`every()`、`forEach()`、`map()`等等)。而简单的`for`循环不仅能实现这些功能,而且相比之下也更灵活。 <add>使用数组时,我们经常需要遍历数组的所有元素来找出我们需要的一个或多个元素,抑或是对数组执行一些特定的操作。JavaScript 为我们提供了几个内置的方法,它们以不同的方式遍历数组,以便我们可以用于不同的场景(如 `every()`、`forEach()`、`map()` 等等)。然而,最简单的 `for` 循环不仅能实现上述这些方法的功能,而且相比之下也会更加灵活。 <ide> <del>请看以下例子: <add>请看以下的例子: <ide> <ide> ```js <ide> function greaterThanTen(arr) { <ide> greaterThanTen([2, 12, 8, 14, 80, 0, 1]); <ide> // 返回 [12, 14, 80] <ide> ``` <ide> <del>这个函数使用一个`for`循环来遍历一个数组,逐一对其中的元素进行测试。我们用这个方法简单地以编程的方式找出了数组中大于`10`的元素,并返回了一个包含这些元素的数组。 <add>在这个函数中,我们用一个 `for` 循环来遍历数组,逐一对其中的元素进行判断。通过上面的代码,我们可以找出数组中大于 `10` 的所有元素,并返回一个包含这些元素的新数组。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`filteredArray`函数,它接受一个嵌套的数组参数`arr`以及一个`elem`参数,并要返回一个新数组。`arr`数组中的数组可能包含`elem`元素,也可能不包含。请修改该函数,用一个`for`循环来做筛选,使函数返回一个由`arr`中不包含`elem`的数组组成的新数组。 <add>我们已经定义了 `filteredArray` 函数,它接受一个嵌套的数组 `arr` 和一个 `elem` 作为参数,并要返回一个新数组。`arr` 数组中嵌套的数组里可能包含 `elem` 元素,也可能不包含。请修改该函数,用一个 `for` 循环来做筛选,使函数返回一个由 `arr` 中不包含 `elem` 的数组所组成的新数组。 <ide> <ide> # --hints-- <ide> <del>`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)`应该返回`[ [10, 8, 3], [14, 6, 23] ]` <add>`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` 应返回 `[ [10, 8, 3], [14, 6, 23] ]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)`应返回`[ ["flutes", 4] ]` <add>`filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)` 应返回 `[ ["flutes", 4] ]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")`应该返回`[ ["amy", "beth", "sam"] ]` <add>`filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")` 应返回 `[ ["amy", "beth", "sam"] ]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)`应该返回`[ ]` <add>`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`filteredArray`函数应该使用`for`循环 <add>`filteredArray` 函数中应使用 `for` 循环。 <ide> <ide> ```js <ide> assert.notStrictEqual(filteredArray.toString().search(/for/), -1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-the-keys-of-an-object-with-a-for...in-statement.md <ide> --- <ide> id: 587d7b7d367417b2b2512b1d <del>title: 使用 for...in 语句迭代对象 <add>title: 使用 for...in 语句遍历对象 <ide> challengeType: 1 <ide> forumTopicId: 301162 <ide> --- <ide> <ide> # --description-- <ide> <del>有时候你需要遍历一个对象中的所有键。这需要 JavaScript 中的一个特殊语法:<dfn>for...in</dfn> 语句。以遍历 `users` 对象的键为例: <add>如果我们想要遍历对象中的所有属性,只需要使用 JavaScript 中的 <dfn>for...in</dfn> 语句即可。以遍历 `users` 对象的属性为例: <ide> <ide> ```js <ide> for (let user in users) { <ide> console.log(user); <ide> } <ide> <del>// logs: <add>// 输出: <ide> Alan <ide> Jeff <ide> Sarah <ide> Ryan <ide> ``` <ide> <del>在这个语句中,我们定义了一个`user`变量,你可以看到,这个变量在 for...in 语句对对象的每一个键的遍历中都会被重置。 **注意:** <del>跟数组不同,对象中的键是无序的,因此一个对象中某个键的位置,或者说它出现的相对顺序,在引用或访问该键时是不确定的。 <add>在上面的代码中,我们定义了一个 `user` 变量。可以观察到,这个变量在遍历对象的 `for...in` 语句执行过程中会一直被重置并赋予新值,结果就是不同的用户名打印到了 console 中。**注意:**对象中的键是无序的,这与数组不同。因此,一个对象中某个属性的位置,或者说它出现的相对顺序,在引用或访问该属性时是不确定的。 <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`countOnline`函数,请在其中使用一个 <dfn>for...in</dfn> 语句来遍历`users`对象中的用户,并返回`online`属性为`true`的用户的数量。 <add>我们已经定义了一个 `countOnline` 函数,请在其中使用 <dfn>for...in</dfn> 语句来遍历 `users` 对象中的用户,并返回 `online` 属性为 `true` 的用户数量。以下是一个传入 `countOnline` 函数的对象示例,注意每个用户都有 `online` 属性,其属性值为 `true` 或 `false`: <ide> <ide> ```js <ide> { <ide> Ryan <ide> <ide> # --hints-- <ide> <del>函数 `countOnline` 应该使用 `for in` 语句遍历传入对象的key。 <add>函数 `countOnline` 中应使用 `for in` 语句遍历传入的对象。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>当传入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `1`。 <add>当传入 `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `1`。 <ide> <ide> ```js <ide> assert(countOnline(usersObj1) === 1); <ide> ``` <ide> <del>当传入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 时,函数 `countOnline` 应该返回 `2`。 <add>当传入 `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` 时,函数 `countOnline` 应该返回 `2`。 <ide> <ide> ```js <ide> assert(countOnline(usersObj2) === 2); <ide> ``` <ide> <del>当传入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `0`。 <add>当传入 `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` 时,函数 `countOnline` 应该返回 `0`。 <ide> <ide> ```js <ide> assert(countOnline(usersObj3) === 0); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object.md <ide> forumTopicId: 301163 <ide> <ide> # --description-- <ide> <del>现在你已经接触到 JavaScript 对象的所有运算。你可以增加、修改和移除键值对,检查某个键是否存在,并且遍历一个对象中的所有键。在你继续学习 JavaScript 的过程中,你会看到对象的更多用法。另外,后续的《高级数据结构》课程还会介绍 ES6 的 <dfn>Map</dfn> 和 <dfn>Set</dfn> 对象。这两种对象都跟一般的对象相似,但它们提供了一些额外的特性。现在你已经学到了数组和对象的基础知识,你已经可以继续用 JavaScript 来解决更加复杂的问题了! <add>我们已经学习了 JavaScript 对象的这些基本操作:添加、修改、移除键值对、检查某个属性是否存在、遍历对象的所有属性。在继续学习 JavaScript 的过程中,我们会了解对象的更多用法。另外,在之后的数据结构课程中,我们还会学习 ES6 的 <dfn>Map</dfn> 和 <dfn>Set</dfn>。这两种数据结构与我们现在学到的对象十分类似,但它们在对象的基础上提供了一些额外的功能。目前,我们已经学习了数组和对象的基础知识,让我们试着来用所学的知识解决一些更复杂的问题。 <ide> <ide> # --instructions-- <ide> <del>请你看一下代码编辑器中我们提供的对象。`user`对象包含 3 个键。`data`对象包含 5 个键,其中一个包含一个`friends`数组。从这个例子你可以看到对象作为数据结构是多么的灵活。我们已经写了`addFriend`函数的一部分,请你完成这个函数,使其接受一个`user`对象,将`friend`参数中的名字添加到`user.data.friends`数组中并返回该数组。 <add>请看一下代码编辑器中我们为你写好的对象。`user` 对象包含 3 个属性;`data` 对象包含 5 个属性,其中包含一个叫做 `friends` 的数组。这就是对象作为数据结构所展现出的灵活性。我们已经写好了 `addFriend` 函数的一部分,请你完成这个函数,使其接受一个 `user` 对象,将 `friend` 参数中的名字添加到 `user.data.friends` 数组中并返回该数组。 <ide> <ide> # --hints-- <ide> <del>`user`对象应该包含`name`、`age`和`data`三个键。 <add>`user` 对象应该包含 `name`、`age` 和 `data` 三个属性。 <ide> <ide> ```js <ide> assert('name' in user && 'age' in user && 'data' in user); <ide> ``` <ide> <del>`addFriend`函数应该接受一个`user`对象和一个`friend`字符串作为输入参数,并将 friend 插入到`user`对象的`friends`数组中。 <add>`addFriend` 函数应该接受一个 `user` 对象和一个 `friend` 字符串作为输入参数,并将这个字符串插入到 `user` 对象的 `friends` 数组中。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`addFriend(user, "Pete")`应该返回`["Sam", "Kira", "Tomo", "Pete"]`。 <add>`addFriend(user, "Pete")` 应该返回 `["Sam", "Kira", "Tomo", "Pete"]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object.md <ide> forumTopicId: 301164 <ide> <ide> # --description-- <ide> <del>现在我们来看一个稍微复杂一点的对象。对象中也可以嵌套任意层的对象。对象的属性值可以是 JavaScript 支持的任意类型,包括数组和其他对象。请看以下例子: <add>现在我们来看一个稍复杂的对象。在对象中,我们也可以嵌套任意层数的对象,对象的属性值可以是 JavaScript 支持的任意类型,包括数组和其他对象。请看以下例子: <ide> <ide> ```js <ide> let nestedObject = { <ide> let nestedObject = { <ide> }; <ide> ``` <ide> <del>`nestedObject`有 3 个唯一的键:值为一个数字的`id`、值为一个字符串的`date`和值为一个嵌套了其他对象的对象的`data`。虽然对象中的数据可能很复杂,我们仍能使用上一个挑战中讲的符号来访问我们需要的信息。 <add>`nestedObject` 有 3 个属性:`id`(属性值为数字)、`date`(属性值为字符串)、`data`(属性值为嵌套的对象)。虽然对象中的数据可能很复杂,我们仍能使用上一个挑战中讲到的写法来访问我们需要的信息。如果我们想把嵌套在 `onlineStatus` 中 `busy` 的属性值改为 `10`,可以用点号表示法来这样实现: <add> <add>```js <add>nestedObject.data.onlineStatus.busy = 10; <add>``` <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`userActivity`对象,它包含了另一个对象。你可以用上一个挑战中那样的方式来修改被嵌套的对象的属性。请将`online`属性设为`45`。 <add>我们已经定义了一个 `userActivity` 对象,它包含了另一个对象。请将 `online` 的属性值改为 `45`。 <ide> <ide> # --hints-- <ide> <del>`userActivity`应该含有`id`、`date`和`data`属性。 <add>`userActivity` 应包含 `id`、`date` 和 `data` 属性。 <ide> <ide> ```js <ide> assert( <ide> 'id' in userActivity && 'date' in userActivity && 'data' in userActivity <ide> ); <ide> ``` <ide> <del>`userActivity`应该有一个`data`属性,该属性要是一个含有`totalUsers`和`online`属性的对象。 <add>`userActivity` 应包含 `data` 属性,其属性值应为包含 `totalUsers` 和 `online` 属性的对象。 <ide> <ide> ```js <ide> assert('totalUsers' in userActivity.data && 'online' in userActivity.data); <ide> ``` <ide> <del>`userActivity`的`data`属性值中的`online`属性应该被设为`45`。 <add>`userActivity` 的 `data` 属性值中的 `online` 属性值应被改为 `45`。 <ide> <ide> ```js <ide> assert(userActivity.data.online === 45); <ide> ``` <ide> <del>你应该用点符号或者方括号符号来设置`online`属性。 <add>应使用点号表示法或方括号表示法来修改 `online` 属性值。 <ide> <ide> ```js <ide> assert.strictEqual(code.search(/online: 45/), -1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.md <ide> --- <ide> id: 587d78b2367417b2b2512b0f <del>title: 使用 pop() 和 shift() 从数组中删除项目 <add>title: 使用 pop() 和 shift() 从数组中删除元素 <ide> challengeType: 1 <ide> forumTopicId: 301165 <ide> --- <ide> <ide> # --description-- <ide> <del>`push()`和`unshift()`都分别有一个作用基本与之相反的函数:`pop()`和`shift()`。你现在或许已经猜到,与插入元素相反,`pop()`从数组的末尾*移除*一个元素,而`shift()`从数组的开头移除一个元素。`pop()`和`shift()`与对应的`push()`和`unshift()`的关键区别在于,前者不能接受输入参数,而且每次只能修改数组中的一个元素。 <add>`push()` 和 `unshift()` 都有一个与它们作用相反的函数:`pop()` 和 `shift()`。与插入元素相反,`pop()` 会从数组的末尾*移除*一个元素,而 `shift()` 会从数组的开头移除一个元素。`pop()` 和 `shift()` 与 `push()` 和 `unshift()` 的关键区别在于,用于删除元素的方法不接收参数,而且每次只能删除数组中的一个元素。 <ide> <ide> 让我们来看以下的例子: <ide> <ide> ```js <ide> let greetings = ['whats up?', 'hello', 'see ya!']; <ide> <ide> greetings.pop(); <del>// now equals ['whats up?', 'hello'] <add>// 数组现在是 ['whats up?', 'hello'] <ide> <ide> greetings.shift(); <del>// now equals ['hello'] <add>// 数组现在是 ['hello'] <ide> ``` <ide> <del>还可以用这些方法返回移除的元素,像这样: <add>这些用于删除数组元素的方法会返回被删除的元素: <ide> <ide> ```js <ide> let popped = greetings.pop(); <del>// returns 'hello' <del>// greetings now equals [] <add>// 返回 'hello',即 popped 的值为 'hello' <add>// greetings 数组现在为 [] <ide> ``` <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个`popShift`函数,它会接收一个数组作为输入参数并返回一个新的数组。请你修改这个函数,使用`pop()`和`shift()`来移除输入的数组的第一个元素和最后一个元素,并将这两个被移除的元素赋值给对应的变量,使得返回的数组包含它们的值。 <add>我们已经定义了一个 `popShift` 函数,它接收一个数组作为输入参数并返回一个新的数组。请修改这个函数,使用 `pop()` 和 `shift()` 来移除输入的数组中的第一个元素和最后一个元素,并将这两个被移除的元素分别赋值给对应的变量,使得最终返回的数组里包含这两个值。 <ide> <ide> # --hints-- <ide> <del>`popShift(["challenge", "is", "not", "complete"])`应返回`["challenge", "complete"]` <add>`popShift(["challenge", "is", "not", "complete"])` 应返回 `["challenge", "complete"]`。 <ide> <ide> ```js <ide> assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [ <ide> assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [ <ide> ]); <ide> ``` <ide> <del>`popShift`函数应该使用`pop()`方法 <add>`popShift` 函数中应使用 `pop()` 方法。 <ide> <ide> ```js <ide> assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1); <ide> ``` <ide> <del>`popShift`函数应该使用`shift()`方法 <add>`popShift` 函数中应使用 `shift()` 方法。 <ide> <ide> ```js <ide> assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.md <ide> --- <ide> id: 587d78b2367417b2b2512b10 <del>title: 使用 splice() 删除项目 <add>title: 使用 splice() 删除元素 <ide> challengeType: 1 <ide> forumTopicId: 301166 <ide> --- <ide> <ide> # --description-- <ide> <del>在上面的挑战中,我们已经学到了如何利用`shift()`和`pop()`从数组的开头或者末尾移除元素,但如果我们想移除数组中间的一个元素呢?或者想一次移除多个元素呢?这时候我们就需要`splice()`了。`splice()`让我们可以从数组中的任意位置**移除任意数量的连续的元素**。 <add>在之前的挑战中,我们已经学习了如何用 `shift()` 和 `pop()` 从数组的开头或末尾移除元素。但如果我们想删除数组中间的一个元素,或者想一次删除多个元素,该如何操作呢?这时候我们就需要使用 `splice()` 方法了,`splice()` 可以让我们从数组中的任意位置**连续删除任意数量的元素**。 <ide> <del>`splice()`最多可以接受 3 个参数,但现在我们先关注前两个。`splice()`接收的前两个参数基于调用`splice()`数组中元素的索引。记住,数组的索引是*从 0 开始的*(*zero-indexed*),所以我们要用`0`来指示数组中的第一个元素。`splice()`的第一个参数代表从数组中的哪个索引开始移除元素,而第二个参数指示要从数组中删除多少个元素。例如: <add>`splice()` 最多可以接受 3 个参数,但现在我们先关注前两个。`splice()` 接收的前两个参数以调用 `splice()` 数组中的元素索引作为参考。别忘了,数组的索引是*从 0 开始的*,所以我们要用 `0` 来表示数组中的第一个元素。`splice()` 的第一个参数代表从数组中的哪个索引开始移除元素,而第二个参数表示要从数组中的这位位置删除多少个元素。例如: <ide> <ide> ```js <ide> let array = ['today', 'was', 'not', 'so', 'great']; <ide> <ide> array.splice(2, 2); <del>// 从第三个索引位置开始移除 2 个元素 <del>// array 现在是 ['today', 'was', 'great'] <add>// 从索引为 2 的位置(即第三个元素)开始移除 2 个元素 <add>// array 的值现在是 ['today', 'was', 'great'] <ide> ``` <ide> <del>`splice()`不仅从被调用的数组中移除元素,还会返回一个包含被移除元素的数组: <add>`splice()` 不仅会修改调用该方法的数组,还会返回一个包含被移除元素的数组: <ide> <ide> ```js <ide> let array = ['I', 'am', 'feeling', 'really', 'happy']; <ide> <ide> let newArray = array.splice(3, 2); <del>// newArray 是 ['really', 'happy'] <add>// newArray 的值是 ['really', 'happy'] <ide> ``` <ide> <ide> # --instructions-- <ide> <del>给定初始化的数组 `arr`。使用 `splice()` 从 `arr` 里移除元素,使剩余的元素的和为 `10`。 <add>我们已经定义了数组 `arr`。请使用 `splice()` 从 `arr` 里移除元素,使剩余的元素之和为 `10`。 <ide> <ide> # --hints-- <ide> <del>不应该修改这一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`。 <add>不应修改这一行 `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`。 <ide> <ide> ```js <ide> assert(code.replace(/\s/g, '').match(/constarr=\[2,4,5,1,7,5,2,1\];?/)); <ide> ``` <ide> <del>`arr` 的剩余元素和应该为 `10`。 <add>`ahr` 的剩余元素之和应为 `10`。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>应该利用 `arr` 的 `splice()`。 <add>应对 `arr` 调用 `splice()` 方法。 <ide> <ide> ```js <ide> assert(code.replace(/\s/g, '').match(/arr\.splice\(/)); <ide> ``` <ide> <del>splice 应该只删除 `arr` 里面的元素,不能给 `arr` 添加元素。 <add>splice 应只删除 `arr` 里面的元素,不能给 `arr` 添加元素。 <ide> <ide> ```js <ide> assert(!code.replace(/\s/g, '').match(/arr\.splice\(\d+,\d+,\d+.*\)/g)); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.md <ide> --- <ide> id: 587d7b7e367417b2b2512b20 <del>title: 使用数组存储数据集合 <add>title: 使用数组存储不同类型的数据 <ide> challengeType: 1 <ide> forumTopicId: 301167 <ide> --- <ide> <ide> # --description-- <ide> <del>以下是<dfn>数组(Array)</dfn>数据结构的最简单的实现例子。这是一个<dfn>一维数组(one-dimensional array)</dfn>,它只有一层,或者说在它里面没有包含其它的数组结构。可以看到它里面包含了<dfn>布尔值(booleans)</dfn>、<dfn>字符串(strings)</dfn>、<dfn>数字(numbers)</dfn>以及一些其他的 JavaScript 语言中合法的数据类型: <add>以下是最简单的<dfn>数组(Array)</dfn>示例:这是一个<dfn>一维数组(one-dimensional array)</dfn>,它只有一层,或者说它里面没有包含其它数组。可以观察到,这个数组中只包含了<dfn>布尔值(booleans)</dfn>、<dfn>字符串(strings)</dfn>、<dfn>数字(numbers)</dfn>以及 JavaScript 中的其他数据类型: <ide> <ide> ```js <ide> let simpleArray = ['one', 2, 'three', true, false, undefined, null]; <ide> console.log(simpleArray.length); <del>// logs 7 <add>// 输出 7 <ide> ``` <ide> <del>可以在上述例子中看到,所有数组都有一个<dfn>长度(length)</dfn>属性。可以简单地使用`Array.length`方法来访问它。 下面是一个关于数组的更复杂的例子。这是一个<dfn>多维数组(multi-dimensional Array</dfn>),或者说是一个包含了其他数组的数组。可以注意到,在它的内部还包含了 JavaScript 中的<dfn>对象(objects)</dfn>结构。我们会在后面的小节中讨论该数据结构,但现在你只需要知道数组能够存储复杂的对象类型数据。 <add>所有数组都有一个表示长度的属性,我们可以通过 `Array.length` 来访问它。接下来是一个稍复杂的数组示例:这是一个<dfn>多维数组(multi-dimensional Array)</dfn>,或者说是一个包含了其他数组的数组。可以观察到,在这个数组内部还包含了 JavaScript 的<dfn>对象(objects)</dfn>,我们会在后面的挑战中详细讨论该数据结构。现在,你只需要知道数组能够存储复杂的对象数据。 <ide> <ide> ```js <ide> let complexArray = [ <ide> let complexArray = [ <ide> <ide> # --instructions-- <ide> <del>我们已经定义了一个名为`yourArray`的变量。请修改题目中的语句,将一个含有至少 5 个元素的数组赋值给`yourArray`变量。你的数组应该包含至少一个 <dfn>string</dfn> 类型的数据、一个 <dfn>number</dfn> 类型的数据和一个 <dfn>boolean</dfn> 类型的数据。 <add>我们已经定义了一个名为 `yourArray` 的变量。请修改代码,将一个含有至少 5 个元素的数组赋值给 `yourArray` 变量。你的数组中应包含至少一个 <dfn>string</dfn> 类型的数据、一个 <dfn>number</dfn> 类型的数据和一个 <dfn>boolean</dfn> 类型的数据。 <ide> <ide> # --hints-- <ide> <del>yourArray 应该是一个数组。 <add>yourArray 应为数组。 <ide> <ide> ```js <ide> assert.strictEqual(Array.isArray(yourArray), true); <ide> ``` <ide> <del>`yourArray`至少要包含 5 个元素。 <add>`yourArray` 应包含至少 5 个元素。 <ide> <ide> ```js <ide> assert.isAtLeast(yourArray.length, 5); <ide> ``` <ide> <del>`yourArray`应该包含至少一个`boolean`。 <add>`yourArray` 应包含至少一个 `boolean`。 <ide> <ide> ```js <ide> assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1); <ide> ``` <ide> <del>`yourArray`应该包含至少一个`number`。 <add>`yourArray` 应包含至少一个 `number`。 <ide> <ide> ```js <ide> assert(yourArray.filter((el) => typeof el === 'number').length >= 1); <ide> ``` <ide> <del>`yourArray`应该包含至少一个`string`。 <add>`yourArray` 应包含至少一个 `string`。 <ide> <ide> ```js <ide> assert(yourArray.filter((el) => typeof el === 'string').length >= 1); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties.md <ide> forumTopicId: 301168 <ide> <ide> # --description-- <ide> <del>现在你已经知道什么是对象以及对象的基本特性和用途。总之,对象是以键值对的形式,灵活、直观地存储结构化数据的一种方式,***并且***查找对象属性的速度是很快的。在本章剩下的挑战中,我们会讲对象的几种常用操作,这样你能更好地在你的程序中使用这种有用的数据结构。 <add>现在我们已经学习了什么是对象以及对象的基本特性和用途。总之,对象是以键值对的形式,灵活、直观地存储结构化数据的一种方式,***而且***,通过对象的属性查找属性值是速度很快的操作。在本章余下的挑战中,我们来了解一下对象的几种常用操作,这样你能更好地在代码中使用这个十分有用的数据结构:对象。 <ide> <del>在之前的挑战中,我们已经试过新增和修改对象中的键值对。现在我们来看如何从一个对象中*移除*一个键值对。 <add>在之前的挑战中,我们已经试过添加和修改对象中的键值对。现在我们来看看如何从一个对象中*移除*一个键值对。 <ide> <del>我们再来看上一个挑战中的`foods`对象。如果我们想移除`apples`属性,我们可以使用`delete`关键字: <add>我们再来回顾一下上一个挑战中的 `foods` 对象。如果我们想移除 `apples` 属性,可以像这样使用 `delete` 关键字: <ide> <ide> ```js <ide> delete foods.apples; <ide> ``` <ide> <ide> # --instructions-- <ide> <del>请你用 delete 关键字来移除`foods`中的`oranges`、`plums`和`strawberries`属性。 <add>请使用 `delete` 关键字来移除 `foods` 中的 `oranges`、`plums` 和 `strawberries` 属性。 <ide> <ide> # --hints-- <ide> <del>`foods`对象应该只含有 3 个键:`apples`、`grapes`和`bananas`。 <add>`foods` 对象应只包含 3 个属性:`apples`、`grapes` 和 `bananas`。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>你应该用`delete`关键字来移除`oranges`、`plums`和`strawberries`属性。 <add>应使用 `delete` 关键字来移除 `oranges`、`plums` 和 `strawberries` 属性。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.md <ide> forumTopicId: 14271 <ide> <ide> # --description-- <ide> <del>创建一个将两个参数相加的函数。如果只传入了一个参数,则返回一个函数,需要传入一个参数并返回总和。 <add>创建一个将两个参数相加的函数。如果调用时只传入了一个参数,则应返回一个接收新的参数的函数。待传入下一个参数后,再返回与之前传入的参数之和。 <ide> <del>比如,`addTogether(2, 3)`应该返回`5`。而`addTogether(2)`应该返回一个函数。 <add>比如,`addTogether(2, 3)` 应该返回 `5`。而 `addTogether(2)` 应该返回一个函数。 <ide> <del>调用这个返回的函数,传入一个值,返回总和: <add>调用这个返回的函数,为它传入一个值,然后再返回总和: <ide> <ide> `var sumTwoAnd = addTogether(2);` <ide> <del>`sumTwoAnd(3)`此时应返回`5`。 <add>`sumTwoAnd(3)` 此时应返回 `5`。 <ide> <del>只要其中任何一个参数不是数字,那就应返回`undefined`。 <add>任何时候,只要任一传入的参数不是数字,就应返回 `undefined`。 <ide> <ide> # --hints-- <ide> <del>`addTogether(2, 3)`应该返回5。 <add>`addTogether(2, 3)` 应返回 5。 <ide> <ide> ```js <ide> assert.deepEqual(addTogether(2, 3), 5); <ide> ``` <ide> <del>`addTogether(2)(3)`应该返回5。 <add>`addTogether(23, 30)` 应返回 53。 <ide> <ide> ```js <del>assert.deepEqual(addTogether(2)(3), 5); <add>assert.deepEqual(addTogether(23, 30), 53); <ide> ``` <ide> <del>`addTogether("http://bit.ly/IqT6zt")`应返回undefined。 <add>`addTogether(5)(7)` 应返回 12。 <add> <add>```js <add>assert.deepEqual(addTogether(5)(7), 12); <add>``` <add> <add>`addTogether("http://bit.ly/IqT6zt")` 应返回 undefined。 <ide> <ide> ```js <ide> assert.isUndefined(addTogether('http://bit.ly/IqT6zt')); <ide> ``` <ide> <del>`addTogether(2, "3")`应返回undefined。 <add>`addTogether(2, "3")` 应返回 undefined。 <ide> <ide> ```js <ide> assert.isUndefined(addTogether(2, '3')); <ide> ``` <ide> <del>`addTogether(2)([3])`应返回undefined。 <add>`addTogether(2)([3])` 应返回 undefined。 <ide> <ide> ```js <ide> assert.isUndefined(addTogether(2)([3])); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.md <ide> --- <ide> id: a8d97bd4c764e91f9d2bda01 <del>title: 二进制转化 <add>title: 翻译二进制字符串 <ide> challengeType: 5 <ide> forumTopicId: 14273 <ide> --- <ide> <ide> # --description-- <ide> <del>写一个函数,把输入的二进制字符串转换成英文句子。 <add>请实现一个函数,把传入的二进制字符串转换成英文句子。 <ide> <del>二进制字符串将以空格分隔。 <add>二进制字符串会以空格分隔。 <ide> <ide> # --hints-- <ide> <del>`binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111')`应该返回 'Aren't bonfires fun!?'。 <add>`binaryAgent('01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111')` 应返回 "Aren't bonfires fun!?"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`binaryAgent('01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001')`应该返回 'I love FreeCodeCamp!'。 <add>`binaryAgent('01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001')` 应返回 "I love FreeCodeCamp!"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.md <ide> --- <ide> id: a6b0bb188d873cb2c8729495 <del>title: 转换HTML实体 <add>title: 转换 HTML 实体字符 <ide> challengeType: 5 <add>forumTopicId: 16007 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个转换 HTML entity 的函数。需要转换的 HTML entity 有`&`、`<`、`>`、`"`(双引号)和`'`(单引号)。 <add>请将字符串中的 `&`、`<`、`>`、`"`(双引号)和 `'`(单引号)转换为 [HTML 实体字符](https://developer.mozilla.org/zh-CN/docs/Glossary/Entity),并返回转换之后的字符串。 <ide> <ide> # --hints-- <ide> <del>`convertHTML('Dolce & Gabbana')`应该返回`Dolce &​amp; Gabbana`。 <add>`convertHTML("Dolce & Gabbana")` 应返回 `"Dolce &amp; Gabbana"`。 <ide> <ide> ```js <ide> assert.match(convertHTML('Dolce & Gabbana'), /Dolce &amp; Gabbana/); <ide> ``` <ide> <del>`convertHTML('Hamburgers < Pizza < Tacos')`应该返回`Hamburgers &​lt; Pizza &​lt; Tacos`。 <add>`convertHTML("Hamburgers < Pizza < Tacos")` 应返回 `"Hamburgers &lt; Pizza &lt; Tacos"`。 <ide> <ide> ```js <ide> assert.match( <ide> assert.match( <ide> ); <ide> ``` <ide> <del>`convertHTML('Sixty > twelve')`应该返回`Sixty &​gt; twelve`。 <add>`convertHTML("Sixty > twelve")` 应返回 `"Sixty &gt; twelve"`。 <ide> <ide> ```js <ide> assert.match(convertHTML('Sixty > twelve'), /Sixty &gt; twelve/); <ide> ``` <ide> <del>`convertHTML('Stuff in "quotation marks"')`应该返回`Stuff in &​quot;quotation marks&​quot;`。 <add>`convertHTML('Stuff in "quotation marks"')` 应返回 `"Stuff in &quot;quotation marks&quot;"`。 <ide> <ide> ```js <ide> assert.match( <ide> assert.match( <ide> ); <ide> ``` <ide> <del>`convertHTML('Schindler's List')`应该返回`Schindler&​apos;s List`。 <add>`convertHTML("Schindler's List")` 应返回 `"Schindler&apos;s List"`。 <ide> <ide> ```js <ide> assert.match(convertHTML("Schindler's List"), /Schindler&apos;s List/); <ide> ``` <ide> <del>`convertHTML('<>')`应该返回`&​lt;&​gt;`。 <add>`convertHTML("<>")` 应返回 `"&lt;&gt;"`。 <ide> <ide> ```js <ide> assert.match(convertHTML('<>'), /&lt;&gt;/); <ide> ``` <ide> <del>`convertHTML('abc')`应该返回`abc`。 <add>`convertHTML("abc")` 应返回 `"abc"`。 <ide> <ide> ```js <ide> assert.strictEqual(convertHTML('abc'), 'abc'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.md <ide> --- <ide> id: a5de63ebea8dbee56860f4f2 <del>title: 区分两个数组 <add>title: 数组的对称差 <ide> challengeType: 5 <ide> forumTopicId: 16008 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,比较两个数组,返回一个新的数组。这个新数组需要包含传入的两个数组所有元素中,仅在其中一个数组里出现的元素。如果某个元素同时出现在两个数组中,则不应包含在返回的数组里。换言之,我们需要返回这两个数组的对称差。 <add>在这道题目中,我们需要实现一个函数,它可以比较两个输入数组并返回一个新数组;返回的新数组需包含传入的两个数组中,仅在一个数组里出现的元素。如果某个元素同时出现在两个数组中,则不应包含在返回的数组里。换言之,我们需要返回两个数组的对称差。 <ide> <ide> **注意:** <del>返回数组中的元素可任意排序。 <add>返回数组中的元素顺序不会影响挑战是否通过。 <ide> <ide> # --hints-- <ide> <del>`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])`应该返回一个数组。 <add>`diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5])` 应返回一个数组。 <ide> <ide> ```js <ide> assert(typeof diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) === 'object'); <ide> ``` <ide> <del>`['diorite', 'andesite', 'grass', 'dirt', 'pink wool', 'dead shrub'], ['diorite', 'andesite', 'grass', 'dirt', 'dead shrub']`应该返回`['pink wool']`。 <add>`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回 `["pink wool"]`。 <ide> <ide> ```js <ide> assert.sameMembers( <ide> assert.sameMembers( <ide> ); <ide> ``` <ide> <del>`['diorite', 'andesite', 'grass', 'dirt', 'pink wool', 'dead shrub'], ['diorite', 'andesite', 'grass', 'dirt', 'dead shrub']`应该返回一个长度为 1 的数组。 <add>`["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回一个长度为 1 的数组。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`['andesite', 'grass', 'dirt', 'pink wool', 'dead shrub'], ['diorite', 'andesite', 'grass', 'dirt', 'dead shrub']`应该返回`['diorite', 'pink wool']`。 <add>`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回 `["diorite", "pink wool"]`。 <ide> <ide> ```js <ide> assert.sameMembers( <ide> assert.sameMembers( <ide> ); <ide> ``` <ide> <del>`['andesite', 'grass', 'dirt', 'pink wool', 'dead shrub'], ['diorite', 'andesite', 'grass', 'dirt', 'dead shrub']`应该返回一个长度为 2 的数组。 <add>`["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]` 应返回一个长度为 2 的数组。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`['andesite', 'grass', 'dirt', 'dead shrub'], ['andesite', 'grass', 'dirt', 'dead shrub']`应该返回`[]`。 <add>`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.sameMembers( <ide> assert.sameMembers( <ide> ); <ide> ``` <ide> <del>`['andesite', 'grass', 'dirt', 'dead shrub'], ['andesite', 'grass', 'dirt', 'dead shrub']`应该返回一个空数组。 <add>`["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]` 应返回一个空数组。 <ide> <ide> ```js <ide> assert( <ide> assert( <ide> ); <ide> ``` <ide> <del>`[1, 2, 3, 5], [1, 2, 3, 4, 5]`应该返回`[4]`。 <add>`[1, 2, 3, 5], [1, 2, 3, 4, 5]` 应返回 `[4]`。 <ide> <ide> ```js <ide> assert.sameMembers(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), [4]); <ide> ``` <ide> <del>`[1, 2, 3, 5], [1, 2, 3, 4, 5]`应该返回一个长度为 1 的数组。 <add>`[1, 2, 3, 5], [1, 2, 3, 4, 5]` 应返回一个长度为 1 的数组。 <ide> <ide> ```js <ide> assert(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]).length === 1); <ide> ``` <ide> <del>`[1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]`应该返回`['piglet', 4]`。 <add>`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` 应返回 `["piglet", 4]`。 <ide> <ide> ```js <ide> assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [ <ide> assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]), [ <ide> ]); <ide> ``` <ide> <del>`[1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]`应该返回一个长度为 2 的数组。 <add>`[1, "calf", 3, "piglet"], [1, "calf", 3, 4]` 应返回一个长度为 2 的数组。 <ide> <ide> ```js <ide> assert(diffArray([1, 'calf', 3, 'piglet'], [1, 'calf', 3, 4]).length === 2); <ide> ``` <ide> <del>`[], ['snuffleupagus', 'cookie monster', 'elmo']`应该返回`['snuffleupagus', 'cookie monster', 'elmo']`。 <add>`[], ["snuffleupagus", "cookie monster", "elmo"]` 应返回 `["snuffleupagus", "cookie monster", "elmo"]`。 <ide> <ide> ```js <ide> assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [ <ide> assert.sameMembers(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']), [ <ide> ]); <ide> ``` <ide> <del>`[], ['snuffleupagus', 'cookie monster', 'elmo']`应该返回一个长度为 3 的数组。 <add>`[], ["snuffleupagus", "cookie monster", "elmo"]` 应返回一个长度为 3 的数组。 <ide> <ide> ```js <ide> assert(diffArray([], ['snuffleupagus', 'cookie monster', 'elmo']).length === 3); <ide> ``` <ide> <del>`[1, 'calf', 3, 'piglet'], [7, 'filly']`应该返回`[1, 'calf', 3, 'piglet', 7, 'filly']`。 <add>`[1, "calf", 3, "piglet"], [7, "filly"]` 应返回 `[1, "calf", 3, "piglet", 7, "filly"]`。 <ide> <ide> ```js <ide> assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [ <ide> assert.sameMembers(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']), [ <ide> ]); <ide> ``` <ide> <del>`[1, 'calf', 3, 'piglet'], [7, 'filly']`应该返回一个长度为 6 的数组。 <add>`[1, "calf", 3, "piglet"], [7, "filly"]` 应返回一个长度为 6 的数组。 <ide> <ide> ```js <ide> assert(diffArray([1, 'calf', 3, 'piglet'], [7, 'filly']).length === 6); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.md <ide> forumTopicId: 16009 <ide> <ide> # --description-- <ide> <del>DNA 链缺少配对元素。对于每个字符,获取与其配对的元素,并将结果作为二维数组返回。 <add>给出的 DNA 链上缺少配对元素。请基于每个字符,获取与其配对的元素,并将结果作为二维数组返回。 <ide> <del>[碱基对](http://en.wikipedia.org/wiki/Base_pair) 是一对 AT 和 CG。将缺少的元素与提供的字符匹配。 <add>DNA 的[碱基对](http://en.wikipedia.org/wiki/Base_pair) 有两种形式:一种是 A 与 T,一种是 C 与 G。请为参数中给出的每个字符配对相应的碱基。 <ide> <del>将提供的字符作为每个数组中的第一个元素返回。 <add>注意,参数中给出的字符应作为每个子数组中的第一个元素返回。 <ide> <del>例如,对于输入 GCG,返回\[\[“G”, “C”],\[“C”, “G”],\[“G”, “C”]]。 <add>例如,传入 GCG 时,应返回 \[\["G", "C"], \["C", "G"], \["G", "C"]]。 <ide> <del>字符及与其配对的元素在一个数组中。再将所有数组放到一个封装数组中。 <add>参数中的字符及与其配对的碱基应存在于一个数组中,代表碱基对。再将每个配对完成的碱基对数组按顺序放到一个数组中,作为最终的返回结果。 <ide> <ide> # --hints-- <ide> <del>`pairElement('ATCGA')`应该返回`[['A','T'],['T','A'],['C','G'],['G','C'],['A','T']]`。 <add>`pairElement("ATCGA")` 应返回 `[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]`。 <ide> <ide> ```js <ide> assert.deepEqual(pairElement('ATCGA'), [ <ide> assert.deepEqual(pairElement('ATCGA'), [ <ide> ]); <ide> ``` <ide> <del>`pairElement('TTGAG')`应该返回`[['T','A'],['T','A'],['G','C'],['A','T'],['G','C']]`。 <add>`pairElement("TTGAG")` 应返回 `[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]]`。 <ide> <ide> ```js <ide> assert.deepEqual(pairElement('TTGAG'), [ <ide> assert.deepEqual(pairElement('TTGAG'), [ <ide> ]); <ide> ``` <ide> <del>`pairElement('CTCTA')`应该返回`[['C','G'],['T','A'],['C','G'],['T','A'],['A','T']]`。 <add>`pairElement("CTCTA")` 应返回 `[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]]`。 <ide> <ide> ```js <ide> assert.deepEqual(pairElement('CTCTA'), [ <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.md <ide> --- <ide> id: a5deed1811a43193f9f1c841 <del>title: 筛选出数组中满足条件的元素 <add>title: 根据参数删除数组元素 <ide> challengeType: 5 <ide> forumTopicId: 16010 <ide> --- <ide> <ide> # --description-- <ide> <del>给定数组`arr`,从数组的第一个元素开始,用函数`func`来检查数组的每个元素并删除,直到某个元素传入函数`func`时返回`true`。函数最终的返回值也是一个数组,它由原数组中第一个使得`func`为`true`的元素及其之后的所有元素组成。 <add>给定数组 `arr`,从数组的第一个元素开始,用函数 `func` 来检查数组的每个元素是否返回 `true`。如果返回 `false`,就把这个元素删除。持续执行删除操作,直到某个元素传入 `func` 时返回 `true` 为止。换言之,函数的最终返回值也应是一个数组,它由原数组中第一个使得 `func` 为 `true` 的元素及其之后的所有元素组成。 <ide> <del>如果数组中的所有元素都不能让`func`为`true`,则返回空数组`[]`。 <add>如果数组中的所有元素都不能让 `func` 为 `true`,则返回空数组 `[]`。 <ide> <ide> # --hints-- <ide> <del>`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})`应该返回`[3, 4]`。 <add>`dropElements([1, 2, 3, 4], function(n) {return n >= 3;})` 应返回 `[3, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`dropElements([0, 1, 0, 1], function(n) {return n === 1;})`应该返回`[1, 0, 1]`。 <add>`dropElements([0, 1, 0, 1], function(n) {return n === 1;})` 应返回 `[1, 0, 1]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`dropElements([1, 2, 3], function(n) {return n > 0;})`应该返回`[1, 2, 3]`。 <add>`dropElements([1, 2, 3], function(n) {return n > 0;})` 应返回 `[1, 2, 3]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`dropElements([1, 2, 3, 4], function(n) {return n > 5;})`应该返回`[]`。 <add>`dropElements([1, 2, 3, 4], function(n) {return n > 5;})` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})`应该返回`[7, 4]`。 <add>`dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})` 应返回 `[7, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})`应该返回`[3, 9, 2]`。 <add>`dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})` 应返回 `[3, 9, 2]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.md <ide> --- <ide> id: a10d2431ad0c6a099a4b8b52 <del>title: 真假值判断 <add>title: 检查对象属性 <ide> challengeType: 5 <ide> forumTopicId: 16011 <ide> --- <ide> <ide> # --description-- <ide> <del>检查谓词(第二个参数)是否对集合的所有元素(第一个参数)都是`truthy`(真实的)。 <add>对于第一个参数(对象数组)中的每个元素,检查第二个参数(字符串)所对应的属性值是否都为 <dfn>truthy</dfn>。 <ide> <del>换句话说,你将获得一个对象的数组集合。谓词`pre`是一个对象的属性,如果它的值是`truthy`(真实的) ,则返回`true`,否则,返回`false` 。 <add>换句话说,函数的第一个参数是一个对象数组,第二个参数是一个字符串 `pre`,表示对象的属性。如果数组中的每个对象里,`pre` 对应属性值均为 `truthy`,则返回 `true`;否则返回 `false`。 <ide> <del>JavaScript 中,如果一个值在 Boolean 的上下文中(比如`if`语句)可以被执行为`true`,那么这个值就被认为是`truthy`的。 <add>JavaScript 中,如果一个值在 Boolean 的上下文中(比如 `if` 语句)的执行结果为 `true`,那么我们称这个值是 `truthy` 的。 <ide> <del>注意,你可以选择使用`.`或`[]`来访问对象属性对应的值。 <add>别忘了,你可以使用点号表示法(`.`)或方括号表示法(`[]`)来访问对象的属性。 <ide> <ide> # --hints-- <ide> <del>`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")`应该返回`true`。 <add>`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` 应返回 true。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")`应该返回`false`。 <add>`truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")`应该返回`false`。 <add>`truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat")`应该返回`false`。 <add>`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastForward", "onBoat": null}], "onBoat")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> truthCheck( <ide> [ <ide> { name: 'Pete', onBoat: true }, <ide> { name: 'Repeat', onBoat: true }, <del> { name: 'FastFoward', onBoat: null } <add> { name: 'FastForward', onBoat: null } <ide> ], <ide> 'onBoat' <ide> ), <ide> false <ide> ); <ide> ``` <ide> <del>`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat")`应该返回`true`。 <add>`truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastForward", "onBoat": true}], "onBoat")` 应返回 true。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> truthCheck( <ide> [ <ide> { name: 'Pete', onBoat: true }, <ide> { name: 'Repeat', onBoat: true, alias: 'Repete' }, <del> { name: 'FastFoward', onBoat: true } <add> { name: 'FastForward', onBoat: true } <ide> ], <ide> 'onBoat' <ide> ), <ide> true <ide> ); <ide> ``` <ide> <del>`truthCheck([{"single": "yes"}], "single")`应该返回`true`。 <add>`truthCheck([{"single": "yes"}], "single")` 应返回 true。 <ide> <ide> ```js <ide> assert.strictEqual(truthCheck([{ single: 'yes' }], 'single'), true); <ide> ``` <ide> <del>`truthCheck([{"single": ""}, {"single": "double"}], "single")`应该返回`false`。 <add>`truthCheck([{"single": ""}, {"single": "double"}], "single")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`truthCheck([{"single": "double"}, {"single": undefined}], "single")`应该返回`false`。 <add>`truthCheck([{"single": "double"}, {"single": undefined}], "single")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`truthCheck([{"single": "double"}, {"single": NaN}], "single")`应该返回`false`。 <add>`truthCheck([{"single": "double"}, {"single": NaN}], "single")` 应返回 false。 <ide> <ide> ```js <ide> assert.strictEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.md <ide> --- <ide> id: a2f1d72d9b908d0bd72bb9f6 <del>title: 构造一个 Person 类 <add>title: 构建 Person 类 <ide> challengeType: 5 <ide> forumTopicId: 16020 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个构造器(constructor)函数。它只接收一个字符串参数`firstAndLast`,这个参数代表一个英文名的全名(姓和名)。这个构造函数创建出的实例需要具有以下方法: <add>在这道题目中,我们需要写一个构造器(constructor)函数。它只接收一个字符串参数 `firstAndLast`,这个参数代表一个英文名的全名(包含姓和名)。通过这个构造函数创建出的实例需要具有以下方法: <ide> <ide> ```js <ide> getFirstName() <ide> setLastName(last) <ide> setFullName(firstAndLast) <ide> ``` <ide> <del>你可以点击 “运行测试”,然后就可以在底下的控制台中看到每个测试用例执行的情况。 方法接收一个字符串格式的参数。 这些方法必须是与对象进行交互的唯一可用方法。 如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>你可以点击“运行测试”,然后就可以在底下的控制台中看到每个测试用例执行的情况。以上方法中,接收一个参数的方法只会接收一个字符串作为参数。同时,我们只会通过以上定义的这些方法与实例进行交互。 <ide> <ide> # --hints-- <ide> <del>`Object.keys(bob).length`应该返回 6。 <add>`Object.keys(bob).length` 应返回 6。 <ide> <ide> ```js <ide> assert.deepEqual(Object.keys(bob).length, 6); <ide> ``` <ide> <del>`bob instanceof Person`应该返回`true`。 <add>`bob instanceof Person` 应返回 true。 <ide> <ide> ```js <ide> assert.deepEqual(bob instanceof Person, true); <ide> ``` <ide> <del>`bob.firstName`应该返回`undefined`。 <add>`bob.firstName` 应返回 undefined。 <ide> <ide> ```js <ide> assert.deepEqual(bob.firstName, undefined); <ide> ``` <ide> <del>`bob.lastName`应该返回`undefined`。 <add>`bob.lastName` 应返回 undefined。 <ide> <ide> ```js <ide> assert.deepEqual(bob.lastName, undefined); <ide> ``` <ide> <del>`bob.getFirstName()`应该返回 'Bob'。 <add>`bob.getFirstName()` 应返回 "Bob"。 <ide> <ide> ```js <ide> assert.deepEqual(bob.getFirstName(), 'Bob'); <ide> ``` <ide> <del>`bob.getLastName()`应该返回 'Ross'。 <add>`bob.getLastName()` 应返回 "Ross"。 <ide> <ide> ```js <ide> assert.deepEqual(bob.getLastName(), 'Ross'); <ide> ``` <ide> <del>`bob.getFullName()`应该返回 'Bob Ross'。 <add>`bob.getFullName()` 应返回 "Bob Ross"。 <ide> <ide> ```js <ide> assert.deepEqual(bob.getFullName(), 'Bob Ross'); <ide> ``` <ide> <del>调用`bob.setFirstName('Haskell')`之后,`bob.getFullName()`应该返回 'Haskell Ross'。 <add>在执行 `bob.setFirstName("Haskell")` 后,`bob.getFullName()` 应返回 "Haskell Ross"。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>调用`bob.setLastName('Curry')`之后,`bob.getFullName()`应该返回 'Haskell Curry'。 <add>在执行 `bob.setLastName("Curry")` 后,`bob.getFullName()` 应返回 "Haskell Curry"。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>调用`bob.setFullName('Haskell Curry')`之后,`bob.getFullName()`应该返回 'Haskell Curry'。 <add>在执行 `bob.setFullName("Haskell Curry")` 后,`bob.getFullName()` 应返回 "Haskell Curry"。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>调用`bob.setFullName('Haskell Curry')`之后,`bob.getFirstName()`应该返回 'Haskell'。 <add>在执行 `bob.setFullName("Haskell Curry")` 后,`bob.getFirstName()` 应返回 "Haskell"。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>调用`bob.setFullName('Haskell Curry')`之后,`bob.getLastName()`应该返回 'Curry'。 <add>在执行 `bob.setFullName("Haskell Curry")` 后,`bob.getLastName()` 应返回 "Curry"。 <ide> <ide> ```js <ide> assert.strictEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.md <ide> --- <ide> id: af4afb223120f7348cdfc9fd <del>title: 绘制碎片图 <add>title: 计算轨道周期 <ide> challengeType: 5 <ide> forumTopicId: 16021 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个计算天体轨道周期的函数,它接收一个对象数组参数`arr`,对象中包含表示天体名称的`name`属性,及表示天体表面平均海拔的`avgAlt`属性。就像这样:`{name: 'name', avgAlt: avgAlt}`。 <add>在这道题目中,我们需要写一个计算天体轨道周期(单位是秒)的函数。 <ide> <del>这个函数的返回值也是一个对象数组,应保留原对象中的`name`属性和值,然后根据`avgAlt`属性的值求出轨道周期(单位是秒),并赋值给`orbitalPeriod`属性。返回值中不应保留原数据中的`avgAlt`属性及其对应的值。 <add>它接收一个对象数组参数 `arr`,对象中包含表示天体名称的 `name` 属性,及表示天体表面平均海拔的 `avgAlt` 属性。就像这样:`{name: 'name', avgAlt: avgAlt}`。 <ide> <del>你可以在这条[维基百科](http://en.wikipedia.org/wiki/Orbital_period)的链接中找到轨道周期的计算公式。 <add>这个函数的返回值也是一个对象数组,应保留原对象中的 `name` 属性及其属性值,然后根据 `avgAlt` 的属性值求出轨道周期(单位是秒),并赋值给 `orbitalPeriod` 属性。返回值中不应保留原数据中的 `avgAlt` 属性。 <ide> <del>轨道周期的计算以地球为基准(即环绕地球的轨道周期),计算结果应取整到最接近的整数。 <add>你可以在这条[维基百科](http://en.wikipedia.org/wiki/Orbital_period)的链接中找到轨道周期的计算公式: <ide> <del>地球的半径是 6367.4447 千米,地球的 GM 值为 398600.4418 km<sup>3</sup>s<sup>-2</sup>。 <add>``` <add>T = 2π*(a^3/GM)^(1/2) <add>``` <ide> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>轨道周期的计算以地球为基准(即环绕地球的轨道周期),因此公式中的 `a` 为数组对象中的 `avgAlt` 加上地球半径。最终的计算结果应取整到最接近的整数。 <add> <add>地球的半径是 6367.4447 千米,地球的 GM 值为 398600.4418 km<sup>3</sup>s<sup>-2</sup>。 <ide> <ide> # --hints-- <ide> <del>`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])`应该返回`[{name: "sputnik", orbitalPeriod: 86400}]`。 <add>`orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])` 应返回 `[{name: "sputnik", orbitalPeriod: 86400}]`。 <ide> <ide> ```js <ide> assert.deepEqual(orbitalPeriod([{ name: 'sputnik', avgAlt: 35873.5553 }]), [ <ide> { name: 'sputnik', orbitalPeriod: 86400 } <ide> ]); <ide> ``` <ide> <del>`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])`应该返回`[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`。 <add>`orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])` 应返回 `[{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.md <ide> --- <ide> id: af7588ade1100bde429baf20 <del>title: 丢失的字母 <add>title: 寻找缺失的字母 <ide> challengeType: 5 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,找到传入的字符串里缺失的字母并返回它。 <add>在这道题目中,我们需要写一个函数,找出传入的字符串里缺失的字母并返回它。 <ide> <del>判断缺失的依据是字母顺序,比如 abcdfg 中缺失了 e。而 abcdef 中就没有字母缺失,此时我们需要返回`undefined`。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>判断缺失的依据是字母顺序。对于没有缺失的情况,请返回 `undefined`。 <ide> <ide> # --hints-- <ide> <del>`fearNotLetter('abce')`应该返回 'd'。 <add>`fearNotLetter("abce")` 应返回 "d"。 <ide> <ide> ```js <ide> assert.deepEqual(fearNotLetter('abce'), 'd'); <ide> ``` <ide> <del>`fearNotLetter('abcdefghjklmno')`应该返回 'i'。 <add>`fearNotLetter("abcdefghjklmno")` 应返回 "i"。 <ide> <ide> ```js <ide> assert.deepEqual(fearNotLetter('abcdefghjklmno'), 'i'); <ide> ``` <ide> <del>`fearNotLetter('stvwx')`应该返回 'u'。 <add>`fearNotLetter("stvwx")` 应返回 "u"。 <ide> <ide> ```js <ide> assert.deepEqual(fearNotLetter('stvwx'), 'u'); <ide> ``` <ide> <del>`fearNotLetter('bcdf')`应该返回 'e'。 <add>`fearNotLetter("bcdf")` 应返回 "e"。 <ide> <ide> ```js <ide> assert.deepEqual(fearNotLetter('bcdf'), 'e'); <ide> ``` <ide> <del>`fearNotLetter('abcdefghijklmnopqrstuvwxyz')`应该返回`undefined`。 <add>`fearNotLetter("abcdefghijklmnopqrstuvwxyz")` 应返回 undefined。 <ide> <ide> ```js <ide> assert.isUndefined(fearNotLetter('abcdefghijklmnopqrstuvwxyz')); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.md <ide> forumTopicId: 16039 <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,把传入的字符串翻译成“儿童黑话”。 <add>[儿童黑话](http://en.wikipedia.org/wiki/Pig_Latin),也叫 Pig Latin,是一种英语语言游戏。规则如下: <ide> <del>[儿童黑话](http://en.wikipedia.org/wiki/Pig_Latin)的基本转换规则很简单,只需要把一个英文单词的第一个辅音字母或第一组辅音簇移到单词的结尾,并在后面加上`ay`即可。在英语中,字母 a、e、i、o、u 为元音,其余的字母均为辅音。辅音簇的意思是连续的多个辅音字母。 <add>\- 如果单词以辅音开头,就把第一个辅音字母或第一组辅音簇移到单词的结尾,并在后面加上 "ay"。 <ide> <del>额外地,如果单词本身是以元音开头的,那只需要在结尾加上`way`。 <add>\- 如果单词以元音开头,只需要在结尾加上 "way"。 <ide> <del>额外地,如果单词不包含元音,那只需要在结尾加上`ay`。 <add>在英语中,字母 a、e、i、o、u 为元音,其余的字母均为辅音。辅音簇的意思是连续的多个辅音字母。 <ide> <del>在本题中,传入的单词一定会是英文单词,且所有字母均为小写。 <add># --instructions-- <ide> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>请把传入的字符串根据上述规则翻译成儿童黑话并返回结果。输入的字符串一定是一个小写的英文单词。 <ide> <ide> # --hints-- <ide> <del>`translatePigLatin('california')`应该返回 'aliforniacay'。 <add>`translatePigLatin("california")` 应返回 "aliforniacay"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('california'), 'aliforniacay'); <ide> ``` <ide> <del>`translatePigLatin('paragraphs')`应该返回 'aragraphspay'。 <add>`translatePigLatin("paragraphs")` 应返回 "aragraphspay"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('paragraphs'), 'aragraphspay'); <ide> ``` <ide> <del>`translatePigLatin('glove')`应该返回 'oveglay'。 <add>`translatePigLatin("glove")` 应返回 "oveglay"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('glove'), 'oveglay'); <ide> ``` <ide> <del>`translatePigLatin('algorithm')`应该返回 'algorithmway'。 <add>`translatePigLatin("algorithm")` 应返回 "algorithmway"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('algorithm'), 'algorithmway'); <ide> ``` <ide> <del>`translatePigLatin('eight')`应该返回 'eightway'。 <add>`translatePigLatin("eight")` 应返回 "eightway"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('eight'), 'eightway'); <ide> ``` <ide> <del>你的代码应该能处理第一个 vowel 在单词中间的情况。比如`translatePigLatin('schwartz')` 应该返回 'artzschway' <add>Should handle words where the first vowel comes in the middle of the word. `translatePigLatin("schwartz")` 应返回 "artzschway"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('schwartz'), 'artzschway'); <ide> ``` <ide> <del>你的代码应当能够处理单词中不含元音字母的情况。比如`translatePigLatin('rhythm')`应该返回 'rhythmay'。 <add>应可以处理不含元音的单词,`translatePigLatin("rhythm")` 应返回 "rhythmay"。 <ide> <ide> ```js <ide> assert.deepEqual(translatePigLatin('rhythm'), 'rhythmay'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.md <ide> --- <ide> id: a0b5010f579e69b815e7c5d6 <del>title: 搜索和替换 <add>title: 搜索与替换 <ide> challengeType: 5 <ide> forumTopicId: 16045 <ide> --- <ide> forumTopicId: 16045 <ide> **注意:** <ide> 你需要保留被替换单词首字母的大小写格式。即如果传入的第二个参数为 "Book",第三个参数为 "dog",那么替换后的结果应为 "Dog" <ide> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <del> <ide> # --hints-- <ide> <del>`myReplace('Let us go to the store', 'store', 'mall')`应该返回 'Let us go to the mall'。 <add>`myReplace("Let us go to the store", "store", "mall")` 应返回 "Let us go to the mall"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`myReplace('He is Sleeping on the couch', 'Sleeping', 'sitting')`应该返回 'He is Sitting on the couch'。 <add>`myReplace("He is Sleeping on the couch", "Sleeping", "sitting")` 应返回 "He is Sitting on the couch"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`myReplace('This has a spellngi error', 'spellngi', 'spelling')`应该返回 'This has a spelling error'。 <add>`myReplace("I think we should look up there", "up", "Down")` 应返回 "I think we should look down there"。 <add> <add>```js <add>assert.deepEqual( <add> myReplace('I think we should look up there', 'up', 'Down'), <add> 'I think we should look down there' <add>); <add>``` <add> <add>`myReplace("This has a spellngi error", "spellngi", "spelling")` 应返回 "This has a spelling error"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`myReplace('His name is Tom', 'Tom', 'john')`应该返回 'His name is John'。 <add>`myReplace("His name is Tom", "Tom", "john")` 应返回 "His name is John"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`myReplace('Let us get back to more Coding', 'Coding', 'algorithms')`应该返回 'Let us get back to more Algorithms'。 <add>`myReplace("Let us get back to more Coding", "Coding", "algorithms")` 应返回 "Let us get back to more Algorithms"。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.md <ide> --- <ide> id: a39963a4c10bc8b4d4f06d7e <del>title: 瞄准和消灭 <add>title: 过滤数组元素 <ide> challengeType: 5 <ide> forumTopicId: 16046 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们要写一个叫`destroyer`的函数。传给它的第一个参数是数组,我们称他为初始数组。后续的参数数量是不确定的,可能有一个或多个。你需要做的是,从初始数组中移除所有与后续参数相等的元素,并返回移除元素后的数组。 <add>在这道题目中,我们要写一个叫 `destroyer` 的函数。传入的第一个参数是一个数组,我们称他为初始数组。后续的参数数量是不确定的,可能有一个或多个。你需要做的是,从初始数组中移除所有与后续参数相等的元素,并返回移除元素后的数组。 <ide> <ide> **注意:** <del>你可以使用`arguments`对象,也可以使用`...`,即“剩余参数”(Rest Parameters)语法。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>你可以使用 `arguments` 对象,也可以使用 `...`,即“剩余参数”(Rest Parameters)语法。 <ide> <ide> # --hints-- <ide> <del>`destroyer([1, 2, 3, 1, 2, 3], 2, 3)`应该返回`[1, 1]`。 <add>`destroyer([1, 2, 3, 1, 2, 3], 2, 3)` 应返回 `[1, 1]`。 <ide> <ide> ```js <ide> assert.deepEqual(destroyer([1, 2, 3, 1, 2, 3], 2, 3), [1, 1]); <ide> ``` <ide> <del>`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)`应该返回`[1, 5, 1]`。 <add>`destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3)` 应返回 `[1, 5, 1]`。 <ide> <ide> ```js <ide> assert.deepEqual(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3), [1, 5, 1]); <ide> ``` <ide> <del>`destroyer([3, 5, 1, 2, 2], 2, 3, 5)`应该返回`[1]`。 <add>`destroyer([3, 5, 1, 2, 2], 2, 3, 5)` 应返回 `[1]`。 <ide> <ide> ```js <ide> assert.deepEqual(destroyer([3, 5, 1, 2, 2], 2, 3, 5), [1]); <ide> ``` <ide> <del>`destroyer([2, 3, 2, 3], 2, 3)`应该返回`[]`。 <add>`destroyer([2, 3, 2, 3], 2, 3)` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.deepEqual(destroyer([2, 3, 2, 3], 2, 3), []); <ide> ``` <ide> <del>`destroyer(['tree', 'hamburger', 53], 'tree', 53)`应该返回`['hamburger']`。 <add>`destroyer(["tree", "hamburger", 53], "tree", 53)` 应返回 `["hamburger"]`。 <ide> <ide> ```js <ide> assert.deepEqual(destroyer(['tree', 'hamburger', 53], 'tree', 53), [ <ide> 'hamburger' <ide> ]); <ide> ``` <ide> <del>`destroyer(['possum', 'trollo', 12, 'safari', 'hotdog', 92, 65, 'grandma', 'bugati', 'trojan', 'yacht'], 'yacht', 'possum', 'trollo', 'safari', 'hotdog', 'grandma', 'bugati', 'trojan')`应该返回`[12,92,65]`。 <add>`destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan")` 应返回 `[12,92,65]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.md <ide> --- <ide> id: ae9defd7acaf69703ab432ea <del>title: 最小公倍数 <add>title: 找出数字范围内的最小公倍数 <ide> challengeType: 5 <ide> forumTopicId: 16075 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,它接收一个包含两个数字的数组参数`arr`,它的返回值为这两个数字范围内所有数字(包含这两个数字)的最小公倍数。 <add>在这道题目中,我们需要写一个函数,它接收一个包含两个数字的数组参数 `arr`;它的返回值为这两个数字范围内所有数字(包含这两个数字)的最小公倍数。 <ide> <ide> 注意,较小数不一定总是出现在数组的第一个元素。 <ide> <del>比如,传入`[1, 3]`,那么函数的返回结果应为 1、2、3 的最小公倍数,即为 6。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>比如,传入 `[1, 3]`,那么函数的返回结果应为 1、2、3 的最小公倍数,即为 6。 <ide> <ide> # --hints-- <ide> <del>`smallestCommons([1, 5])`应该返回一个数字。 <add>`smallestCommons([1, 5])` 应返回 a number。 <ide> <ide> ```js <ide> assert.deepEqual(typeof smallestCommons([1, 5]), 'number'); <ide> ``` <ide> <del>`smallestCommons([1, 5])`应该返回 60。 <add>`smallestCommons([1, 5])` 应返回 60。 <ide> <ide> ```js <ide> assert.deepEqual(smallestCommons([1, 5]), 60); <ide> ``` <ide> <del>`smallestCommons([5, 1])`应该返回 60。 <add>`smallestCommons([5, 1])` 应返回 60。 <ide> <ide> ```js <ide> assert.deepEqual(smallestCommons([5, 1]), 60); <ide> ``` <ide> <del>`smallestCommons([2, 10])`应该返回 2520。. <add>`smallestCommons([2, 10])` 应返回 2520。 <ide> <ide> ```js <ide> assert.deepEqual(smallestCommons([2, 10]), 2520); <ide> ``` <ide> <del>`smallestCommons([1, 13])`应该返回 360360。 <add>`smallestCommons([1, 13])` 应返回 360360。 <ide> <ide> ```js <ide> assert.deepEqual(smallestCommons([1, 13]), 360360); <ide> ``` <ide> <del>`smallestCommons([23, 18])`应该返回 6056820。 <add>`smallestCommons([23, 18])` 应返回 6056820。 <ide> <ide> ```js <ide> assert.deepEqual(smallestCommons([23, 18]), 6056820); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.md <ide> forumTopicId: 16077 <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,它接收两个或多个数组为参数。我们需要对这些数组中所有元素进行去除重复元素的处理,并以数组的形式返回去重结果。 <add>在这道题目中,我们需要写一个函数,它接收两个或多个数组为参数。我们需要首先求出所有数组的并集,然后进行去除重复元素的处理,并以数组的形式返回去重结果。 <ide> <ide> 换句话说,所有数组中出现的所有值都应按其原始顺序包括在内,但最终数组中不得重复。 <ide> <del>唯一数字应按其原始顺序排序,但最终数组不应按数字顺序排序。 <add>去重后的数字应按其出现在参数中的原始顺序排序,最终数组不应按数字大小进行排序。 <ide> <ide> 如有疑问,请先浏览下方的测试用例。 <ide> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <del> <ide> # --hints-- <ide> <del>`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])`应该返回`[1, 3, 2, 5, 4]`。 <add>`uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])` 应返回 `[1, 3, 2, 5, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), [1, 3, 2, 5, 4]); <ide> ``` <ide> <del>`uniteUnique([1, 2, 3], [5, 2, 1])`应该返回`[1, 2, 3, 5]`。 <add>`uniteUnique([1, 2, 3], [5, 2, 1])` 应返回 `[1, 2, 3, 5]`。 <ide> <ide> ```js <ide> assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1]), [1, 2, 3, 5]); <ide> ``` <ide> <del>`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])`应该返回`[1, 2, 3, 5, 4, 6, 7, 8]`。 <add>`uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8])` 应返回 `[1, 2, 3, 5, 4, 6, 7, 8]`。 <ide> <ide> ```js <ide> assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), [ <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.md <ide> forumTopicId: 16078 <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,把一个字符串转换为“短线连接格式”。短线连接格式的意思是,所有字母都是小写,且用`-`连接。比如,对于`Hello World`,应该转换为`hello-world`;对于`I love_Javascript-VeryMuch`,应该转换为`i-love-javascript-very-much`。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>在这道题目中,我们需要写一个函数,把一个字符串转换为“短线连接格式”。短线连接格式的意思是,所有字母都是小写,且用 `-` 连接。比如,`Hello World` 的短线连接格式为 `hello-world`;`I love_Javascript-VeryMuch` 的短线连接格式为 `i-love-javascript-very-much`。 <ide> <ide> # --hints-- <ide> <del>`spinalCase('This Is Spinal Tap')`应该返回`'this-is-spinal-tap'`。 <add>`spinalCase("This Is Spinal Tap")` 应返回 `"this-is-spinal-tap"`。 <ide> <ide> ```js <ide> assert.deepEqual(spinalCase('This Is Spinal Tap'), 'this-is-spinal-tap'); <ide> ``` <ide> <del>`spinalCase('thisIsSpinalTap')`应该返回`'this-is-spinal-tap'`。 <add>`spinalCase("thisIsSpinalTap")` 应返回 `"this-is-spinal-tap"`。 <ide> <ide> ```js <ide> assert.strictEqual(spinalCase('thisIsSpinalTap'), 'this-is-spinal-tap'); <ide> ``` <ide> <del>`spinalCase('The_Andy_Griffith_Show')`应该返回`'the-andy-griffith-show'`。 <add>`spinalCase("The_Andy_Griffith_Show")` 应返回 `"the-andy-griffith-show"`。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`spinalCase('Teletubbies say Eh-oh')`应该返回`'teletubbies-say-eh-oh'`。 <add>`spinalCase("Teletubbies say Eh-oh")` 应返回 `"teletubbies-say-eh-oh"`。 <ide> <ide> ```js <ide> assert.strictEqual( <ide> assert.strictEqual( <ide> ); <ide> ``` <ide> <del>`spinalCase('AllThe-small Things')`应该返回`'all-the-small-things'`。 <add>`spinalCase("AllThe-small Things")` 应返回 `"all-the-small-things"`。 <ide> <ide> ```js <ide> assert.strictEqual(spinalCase('AllThe-small Things'), 'all-the-small-things'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.md <ide> --- <ide> id: ab306dbdcc907c7ddfc30830 <del>title: 扁平化 <add>title: 数组扁平化 <ide> challengeType: 5 <ide> forumTopicId: 16079 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个数组扁平化的函数。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>在这道题目中,我们需要写一个数组扁平化的函数。请注意考虑多层数组嵌套的情景。 <ide> <ide> # --hints-- <ide> <del>`steamrollArray([[['a']], [['b']]])`应该返回`['a', 'b']`。 <add>`steamrollArray([[["a"]], [["b"]]])` 应返回 `["a", "b"]`。 <ide> <ide> ```js <ide> assert.deepEqual(steamrollArray([[['a']], [['b']]]), ['a', 'b']); <ide> ``` <ide> <del>`steamrollArray([1, [2], [3, [[4]]]])`应该返回`[1, 2, 3, 4]`。 <add>`steamrollArray([1, [2], [3, [[4]]]])` 应返回 `[1, 2, 3, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]); <ide> ``` <ide> <del>`steamrollArray([1, [], [3, [[4]]]])`应该返回`[1, 3, 4]`。 <add>`steamrollArray([1, [], [3, [[4]]]])` 应返回 `[1, 3, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]); <ide> ``` <ide> <del>`steamrollArray([1, {}, [3, [[4]]]])`应该返回`[1, {}, 3, 4]`。 <add>`steamrollArray([1, {}, [3, [[4]]]])` 应返回 `[1, {}, 3, 4]`。 <ide> <ide> ```js <ide> assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]); <ide> ``` <ide> <add>代码中不应使用 `Array.prototype.flat()` 或 `Array.prototype.flatMap()` 方法。 <add> <add>```js <add>assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/)); <add>``` <add> <ide> # --solutions-- <ide> <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.md <ide> forumTopicId: 16083 <ide> <ide> # --description-- <ide> <del>给出一个含有两个数字的数组,我们需要写一个函数,让它返回这两个数字间所有数字(包含这两个数字)的总和。 <add>给出一个含有两个数字的数组,我们需要写一个函数,让它返回这两个数字间所有数字(包含这两个数字)的总和。注意,较小数不一定总是出现在数组的第一个元素。 <ide> <del>例如,`sumAll([4,1])` 应该返回 `10`,因为从 1 到 4 (包含 1、4)的所有数字的和是 `10`。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>例如,`sumAll([4,1])` 应返回 `10`,因为从 1 到 4(包含 1、4)的所有数字的和是 `10`。 <ide> <ide> # --hints-- <ide> <del>`sumAll([1, 4])`应该返回一个数字。 <add>`sumAll([1, 4])` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof sumAll([1, 4]) === 'number'); <ide> ``` <ide> <del>`sumAll([1, 4])`应该返回 10。 <add>`sumAll([1, 4])` 应返回 10。 <ide> <ide> ```js <ide> assert.deepEqual(sumAll([1, 4]), 10); <ide> ``` <ide> <del>`sumAll([4, 1])`应该返回 10。 <add>`sumAll([4, 1])` 应返回 10。 <ide> <ide> ```js <ide> assert.deepEqual(sumAll([4, 1]), 10); <ide> ``` <ide> <del>`sumAll([5, 10])`应该返回 45。 <add>`sumAll([5, 10])` 应返回 45。 <ide> <ide> ```js <ide> assert.deepEqual(sumAll([5, 10]), 45); <ide> ``` <ide> <del>`sumAll([10, 5])`应该返回 45。 <add>`sumAll([10, 5])` 应返回 45。 <ide> <ide> ```js <ide> assert.deepEqual(sumAll([10, 5]), 45); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.md <ide> --- <ide> id: a5229172f011153519423690 <del>title: 求斐波那契数组中的奇数之和 <add>title: 求斐波那契数列中的奇数之和 <ide> challengeType: 5 <ide> forumTopicId: 16084 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们需要写一个函数,参数为一个正整数`num`。它的作用是计算斐波那契数列中,小于或等于`num`的奇数之和。 <add>在这道题目中,我们需要写一个函数,参数为一个正整数 `num`,返回值为斐波那契数列中,小于或等于 `num` 的奇数之和。 <ide> <ide> 斐波那契数列中,第一和第二个数字都是 1,后面的每个数字由之前两数相加得出。斐波那契数列的前六个数字分别为:1、1、2、3、5、8。 <ide> <del>比如,`sumFibs(10)`应该返回`10`。因为斐波那契数列中,比`10`小的数字只有 1、1、3、5。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>比如,`sumFibs(10)` 应该返回 `10`。因为斐波那契数列中,比 `10` 小的数字只有 1、1、3、5。 <ide> <ide> # --hints-- <ide> <del>`sumFibs(1)`应该返回一个数字。 <add>`sumFibs(1)` 应返回一个数字。 <ide> <ide> ```js <ide> assert(typeof sumFibs(1) === 'number'); <ide> ``` <ide> <del>`sumFibs(1000)`应该返回 1785。 <add>`sumFibs(1000)` 应返回 1785。 <ide> <ide> ```js <ide> assert(sumFibs(1000) === 1785); <ide> ``` <ide> <del>`sumFibs(4000000)`应该返回 4613732。 <add>`sumFibs(4000000)` 应返回 4613732。 <ide> <ide> ```js <ide> assert(sumFibs(4000000) === 4613732); <ide> ``` <ide> <del>`sumFibs(4)`应该返回 5。 <add>`sumFibs(4)` 应返回 5。 <ide> <ide> ```js <ide> assert(sumFibs(4) === 5); <ide> ``` <ide> <del>`sumFibs(75024)`应该返回 60696。 <add>`sumFibs(75024)` 应返回 60696。 <ide> <ide> ```js <ide> assert(sumFibs(75024) === 60696); <ide> ``` <ide> <del>`sumFibs(75025)`应该返回 135721。 <add>`sumFibs(75025)` 应返回 135721。 <ide> <ide> ```js <ide> assert(sumFibs(75025) === 135721); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.md <ide> --- <ide> id: a3bfc1673c0526e06d3ac698 <del>title: 对所有素数求和 <add>title: 质数求和 <ide> challengeType: 5 <ide> forumTopicId: 16085 <ide> --- <ide> <ide> # --description-- <ide> <del>质数是大于 1 且仅可以被 1 和自己整除的数。 比如,2 就是一个质数,因为它只可以被 1 和 2(它本身)整除。 相反,4 不是质数,因为它可以被 1, 2 和 4 整除。 <add><dfn>质数</dfn>是大于 1 且仅可以被 1 和自己整除的数。比如,2 就是一个质数,因为它只可以被 1 和 2(它本身)整除。相反,4 不是质数,因为它可以被 1, 2 和 4 整除。 <ide> <del>重写 `sumPrimes` 使其返回所有小于或等于该数字的质数 的和。 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>请完成 `sumPrimes` 方法,使其返回小于等于传入参数数字的所有质数之和。 <ide> <ide> # --hints-- <ide> <del>`sumPrimes(10)`应该返回一个数字。 <add>`sumPrimes(10)` 应返回一个数字。 <ide> <ide> ```js <ide> assert.deepEqual(typeof sumPrimes(10), 'number'); <ide> ``` <ide> <del>`sumPrimes(10)`应该返回 17。 <add>`sumPrimes(10)` 应返回 17。 <ide> <ide> ```js <ide> assert.deepEqual(sumPrimes(10), 17); <ide> ``` <ide> <del>`sumPrimes(977)`应该返回 73156。 <add>`sumPrimes(977)` 应返回 73156。 <ide> <ide> ```js <ide> assert.deepEqual(sumPrimes(977), 73156); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.md <ide> --- <ide> id: a8e512fbe388ac2f9198f0fa <del>title: 罗密欧与朱丽叶 <add>title: 找出包含特定键值对的对象 <ide> challengeType: 5 <ide> forumTopicId: 16092 <ide> --- <ide> <ide> # --description-- <ide> <del>在这道题目中,我们要写一个函数,它接收两个参数:第一个参数是对象数组,第二个参数是一个对象。我们需要从对象数组中找出与第二个参数相等或包含第二个参数的所有对象,并以对象数组的形式返回。其中,相等的意思是原数组中的对象与第二个参数中对象的所有键值对完全相等;包含的意思是只要第二个参数中对象的所有键存在于原数组对象中,且它们对应的值相同即可。 <add>在这道题目中,我们要写一个函数,它接收两个参数:第一个参数是对象数组,第二个参数是一个对象。我们需要从对象数组中找出与第二个参数的属性和属性值均相等或包含第二个参数的所有对象,并以对象数组的形式返回。其中,相等的意思是原数组中的对象与第二个参数中对象的所有键值对完全相等;包含的意思是只要第二个参数中对象的所有键存在于原数组对象中,且它们对应的值相同即可。 <ide> <del>比如,如果第一个参数是`[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`,第二个参数是`{ last: "Capulet" }`。那么你需要以对象数组的形式返回第一个参数中的第三个元素,因为它包含第二个参数中定义的键`last`,且对应的值`"Capulet"`相同 <del> <del>如果你遇到了问题,请点击[帮助](https://forum.freecodecamp.one/t/topic/157)。 <add>比如,如果第一个参数是 `[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]`,第二个参数是 `{ last: "Capulet" }`。那么你需要以对象数组的形式返回第一个参数中的第三个元素,因为它包含第二个参数中定义的键 `last`,且对应的值 `"Capulet"` 相同 <ide> <ide> # --hints-- <ide> <del>`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })`应该返回`[{ first: "Tybalt", last: "Capulet" }]`。 <add>`whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })` 应返回 `[{ first: "Tybalt", last: "Capulet" }]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })`应该返回`[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`。 <add>`whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 })` 应返回 `[{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })`应该返回`[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`。 <add>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 })` 应返回 `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })`应该返回`[{ "apple": 1, "bat": 2, "cookie": 2 }]`。 <add>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 })` 应返回 `[{ "apple": 1, "bat": 2, "cookie": 2 }]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })`应该返回`[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`。 <add>`whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 })` 应返回 `[{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})`应该返回`[]`。 <add>`whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3})` 应返回 `[]`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.md <ide> forumTopicId: 16003 <ide> <ide> # --description-- <ide> <del>`凯撒密码`是最简单和最广为人知的<dfn>密码之一</dfn>,也被称为`移位密码`。在`移位密码`中,明文中的字母通过按照一个固定数目进行偏移后被替换成新的字母。 <add><dfn>凯撒密码</dfn>是最简单且最广为人知的<dfn>密码</dfn>,也被称为<dfn>移位密码</dfn>。在移位密码中,明文中的字母通过按照一个固定数目进行偏移后被替换成新的字母。 <ide> <del>[ROT13](https://en.wikipedia.org/wiki/ROT13) 是一个被广泛使用的编码技术,明文中的所有字母都被移动 13 位。因此,'A' ↔ 'N', 'B' ↔ 'O' 等等。 <add>[ROT13](https://en.wikipedia.org/wiki/ROT13) 是一个被广泛使用的加密技术,明文中的所有字母都被移动 13 位。因此有:'A' ↔ 'N'、'B' ↔ 'O' 等等。 <ide> <ide> 请编写一个函数,用于解码一个被 [ROT13](https://en.wikipedia.org/wiki/ROT13) 编码的字符串,然后返回解码后的结果。 <ide> <ide> 所有解码后的字母都必须为字母大写。请不要解码非字母的字符(例如,空格、标点符号),但你需要在结果中保留它们。 <ide> <ide> # --hints-- <ide> <del>`rot13('SERR PBQR PNZC')`应解码为`FREE CODE CAMP`。 <add>`rot13("SERR PBQR PNZC")` 应解码为 `FREE CODE CAMP`。 <ide> <ide> ```js <ide> assert(rot13('SERR PBQR PNZC') === 'FREE CODE CAMP'); <ide> ``` <ide> <del>`rot13('SERR CVMMN!')`应解码为`FREE PIZZA!`。 <add>`rot13("SERR CVMMN!")` 应解码为 `FREE PIZZA!`。 <ide> <ide> ```js <ide> assert(rot13('SERR CVMMN!') === 'FREE PIZZA!'); <ide> ``` <ide> <del>`rot13('SERR YBIR?')`应解码为`FREE LOVE?`。 <add>`rot13("SERR YBIR?")` 应解码为 `FREE LOVE?`。 <ide> <ide> ```js <ide> assert(rot13('SERR YBIR?') === 'FREE LOVE?'); <ide> ``` <ide> <del>`rot13('GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.')`应解码为`THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.`。 <add>`rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")` 应解码为 `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.`。 <ide> <ide> ```js <ide> assert( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.md <ide> --- <ide> id: aa2e6f85cab2ab736c9a9b24 <del>title: 收银机 <add>title: 计算找零 <ide> challengeType: 5 <ide> forumTopicId: 16012 <ide> --- <ide> <ide> # --description-- <ide> <del>编写一个用于收银机的函数`checkCashRegister()`,传入售价为第一个参数(`price`)、支付金额为第二个参数(`cash`)、收银机內的金额为第三个参数(`cid`)。 <add>请编写一个用于收银机的函数 `checkCashRegister()`:它的第一个参数为售价 `price`、第二个参数为支付金额 `cash`、第三个参数为收银机內的金额 `cid`。 <ide> <del>`cid`是包含货币面值的二维数组。 <add>`cid` 是包含货币面值的二维数组。 <ide> <del>函数`checkCashRegister()`必须返回含有`status`键值和`change`键值的对象。 <add>函数 `checkCashRegister()` 应返回含有 `status` 属性和 `change` 属性的对象。 <ide> <del>如果收银机內的金额少于应找回的零钱数,或者你无法返回确切的数目时,返回`{status: "INSUFFICIENT_FUNDS", change: []}`。 <add>如果收银机內的金额少于应找回的零钱数,或者你无法返回确切的数目时,返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 <ide> <del>如果收银机內的金额等于应找回的零钱数,返回`{status: "CLOSED", change: [...]}`,其中`change`键值是收银机內的金额。 <add>如果收银机內的金额恰好等于应找回的零钱数,返回 `{status: "CLOSED", change: [...]}`,其中 `change` 的属性值就是收银机內的金额。 <ide> <del>否则,返回`{status: "OPEN", change: [...]}`,其中`change`键值是应找回的零钱数,并且它的面值由高到低排序。 <add>否则,返回 `{status: "OPEN", change: [...]}`,其中 `change` 键值是应找回的零钱数,并将找零的面值由高到低排序。 <ide> <del><table class='table table-striped'><tbody><tr><th>货币单位</th><th>面值</th></tr><tr><td>Penny</td><td>$0.01 (PENNY)</td></tr><tr><td>Nickel</td><td>$0.05 (NICKEL)</td></tr><tr><td>Dime</td><td>$0.1 (DIME)</td></tr><tr><td>Quarter</td><td>$0.25 (QUARTER)</td></tr><tr><td>Dollar</td><td>$1 (DOLLAR)</td></tr><tr><td>Five Dollars</td><td>$5 (FIVE)</td></tr><tr><td>Ten Dollars</td><td>$10 (TEN)</td></tr><tr><td>Twenty Dollars</td><td>$20 (TWENTY)</td></tr><tr><td>One-hundred Dollars</td><td>$100 (ONE HUNDRED)</td></tr></tbody></table> <add><table class='table table-striped'><tbody><tr><th>货币单位 Unit</th><th>面值</th></tr><tr><td>Penny</td><td>$0.01 (PENNY)</td></tr><tr><td>Nickel</td><td>$0.05 (NICKEL)</td></tr><tr><td>Dime</td><td>$0.1 (DIME)</td></tr><tr><td>Quarter</td><td>$0.25 (QUARTER)</td></tr><tr><td>Dollar</td><td>$1 (ONE)</td></tr><tr><td>Five Dollars</td><td>$5 (FIVE)</td></tr><tr><td>Ten Dollars</td><td>$10 (TEN)</td></tr><tr><td>Twenty Dollars</td><td>$20 (TWENTY)</td></tr><tr><td>One-hundred Dollars</td><td>$100 (ONE HUNDRED)</td></tr></tbody></table> <add> <add>以下为 `cid` 参数的示例: <add> <add>```js <add>[ <add> ["PENNY", 1.01], <add> ["NICKEL", 2.05], <add> ["DIME", 3.1], <add> ["QUARTER", 4.25], <add> ["ONE", 90], <add> ["FIVE", 55], <add> ["TEN", 20], <add> ["TWENTY", 60], <add> ["ONE HUNDRED", 100] <add>] <add>``` <ide> <ide> # --hints-- <ide> <del>`checkCashRegister(19.5, 20, [['PENNY', 1.01], ['NICKEL', 2.05], ['DIME', 3.1], ['QUARTER', 4.25], ['ONE', 90], ['FIVE', 55], ['TEN', 20], ['TWENTY', 60], ['ONE HUNDRED', 100]])`应该返回一个对象。 <add>`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回一个对象。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])`应该返回`{status: "OPEN", change: [["QUARTER", 0.5]]}`。 <add>`checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回 `{status: "OPEN", change: [["QUARTER", 0.5]]}`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])`应该返回`{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`。 <add>`checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])` 应返回 `{status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])`应该返回`{status: "INSUFFICIENT_FUNDS", change: []}`。 <add>`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])`应该返回`{status: "INSUFFICIENT_FUNDS", change: []}`。 <add>`checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "INSUFFICIENT_FUNDS", change: []}`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])`应该返回`{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`。 <add>`checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])` 应返回 `{status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}`。 <ide> <ide> ```js <ide> assert.deepEqual( <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.md <ide> forumTopicId: 16004 <ide> <ide> # --description-- <ide> <del>如果给定的一个字符串是回文,那么返回`true`,否则返回`false`。 <add>如果传入的字符串是回文字符串,则返回 `true`,否则返回 `false`。 <ide> <del><dfn>palindrome(回文)</dfn>,指在忽略标点符号、大小写和空格的前提下,正着读和反着读一模一样。 <add><dfn>Palindrome(回文)</dfn>,指在忽略标点符号、大小写和空格的前提下,正着读和反着读一模一样。 <ide> <del>**注意:** <del>检查回文时,你需要先除去**所有非字母数字的字符**(标点、空格和符号)并且将所有字符转换成字母大写或字母小写。 <add>**注意:**检查回文时,你需要先去除**所有非字母数字的字符**(标点、空格和符号),并将所有字母都转换成大写或都转换成小写。 <ide> <del>我们将会传入不同格式的字符串,例如:`"racecar"`、`"RaceCar"`、`"race CAR"`等等。 <add>我们会传入不同格式的字符串,例如:`"racecar"`、`"RaceCar"`、`"race CAR"` 等等。 <ide> <del>我们也会传入一些包含特殊符号的字符串,例如`"2A3*3a2"`,`"2A3 3a2"`和`"2_A3*3#A2"`。 <add>我们也会传入一些包含特殊符号的字符串,例如 `"2A3*3a2"`、`"2A3 3a2"`、`"2_A3*3#A2"`。 <ide> <ide> # --hints-- <ide> <del>`palindrome('eye')`应该返回一个布尔值。 <add>`palindrome("eye")` 应返回一个布尔值。 <ide> <ide> ```js <ide> assert(typeof palindrome('eye') === 'boolean'); <ide> ``` <ide> <del>`palindrome('eye')`应该返回 true。 <add>`palindrome("eye")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('eye') === true); <ide> ``` <ide> <del>`palindrome('_eye')`应该返回 true。 <add>`palindrome("_eye")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('_eye') === true); <ide> ``` <ide> <del>`palindrome('race car')`应该返回 true。 <add>`palindrome("race car")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('race car') === true); <ide> ``` <ide> <del>`palindrome('not a palindrome')`应该返回 false。 <add>`palindrome("not a palindrome")` 应返回 false。 <ide> <ide> ```js <ide> assert(palindrome('not a palindrome') === false); <ide> ``` <ide> <del>`palindrome('A man, a plan, a canal. Panama')`应该返回 true。 <add>`palindrome("A man, a plan, a canal. Panama")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('A man, a plan, a canal. Panama') === true); <ide> ``` <ide> <del>`palindrome('never odd or even')`应该返回 true。 <add>`palindrome("never odd or even")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('never odd or even') === true); <ide> ``` <ide> <del>`palindrome('nope')`应该返回 false。 <add>`palindrome("nope")` 应返回 false。 <ide> <ide> ```js <ide> assert(palindrome('nope') === false); <ide> ``` <ide> <del>`palindrome('almostomla')`应该返回 false。 <add>`palindrome("almostomla")` 应返回 false。 <ide> <ide> ```js <ide> assert(palindrome('almostomla') === false); <ide> ``` <ide> <del>`palindrome('My age is 0, 0 si ega ym.')`应该返回 true。 <add>`palindrome("My age is 0, 0 si ega ym.")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('My age is 0, 0 si ega ym.') === true); <ide> ``` <ide> <del>`palindrome('1 eye for of 1 eye.')`应该返回 false。 <add>`palindrome("1 eye for of 1 eye.")` 应返回 false。 <ide> <ide> ```js <ide> assert(palindrome('1 eye for of 1 eye.') === false); <ide> ``` <ide> <del>`palindrome("0_0 (: /-\ :) 0-0")`应该返回 true。 <add>`palindrome("0_0 (: /-\ :) 0-0")` 应返回 true。 <ide> <ide> ```js <ide> assert(palindrome('0_0 (: /- :) 0-0') === true); <ide> ``` <ide> <del>`palindrome('five| /|four')`应该返回 false。 <add>`palindrome("five|\_/|four")` 应返回 false。 <ide> <ide> ```js <ide> assert(palindrome('five|_/|four') === false); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.md <ide> forumTopicId: 16044 <ide> <ide> # --description-- <ide> <del>把传入的数字转变为罗马数字。 <add>把传入的数字转为罗马数字。 <ide> <ide> 转换后的[罗马数字](http://www.mathsisfun.com/roman-numerals.html)字母必须都是大写。 <ide> <ide> # --hints-- <ide> <del>`convertToRoman(2)`应该返回 'II'。 <add>`convertToRoman(2)` 应返回 "II"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(2), 'II'); <ide> ``` <ide> <del>`convertToRoman(3)`应该返回 'III'。 <add>`convertToRoman(3)` 应返回 "III"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(3), 'III'); <ide> ``` <ide> <del>`convertToRoman(4)`应该返回 'IV'。 <add>`convertToRoman(4)` 应返回 "IV"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(4), 'IV'); <ide> ``` <ide> <del>`convertToRoman(5)`应该返回 'V'。 <add>`convertToRoman(5)` 应返回 "V"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(5), 'V'); <ide> ``` <ide> <del>`convertToRoman(9)`应该返回 'IX'。 <add>`convertToRoman(9)` 应返回 "IX"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(9), 'IX'); <ide> ``` <ide> <del>`convertToRoman(12)`应该返回 'XII'。 <add>`convertToRoman(12)` 应返回 "XII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(12), 'XII'); <ide> ``` <ide> <del>`convertToRoman(16)`应该返回 'XVI'。 <add>`convertToRoman(16)` 应返回 "XVI"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(16), 'XVI'); <ide> ``` <ide> <del>`convertToRoman(29)`应该返回 'XXIX'。 <add>`convertToRoman(29)` 应返回 "XXIX"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(29), 'XXIX'); <ide> ``` <ide> <del>`convertToRoman(44)`应该返回 'XLIV'。 <add>`convertToRoman(44)` 应返回 "XLIV"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(44), 'XLIV'); <ide> ``` <ide> <del>`convertToRoman(45)`应该返回 'XLV'。 <add>`convertToRoman(45)` 应返回 "XLV"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(45), 'XLV'); <ide> ``` <ide> <del>`convertToRoman(68)`应该返回 'LXVIII'。 <add>`convertToRoman(68)` 应返回 "LXVIII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(68), 'LXVIII'); <ide> ``` <ide> <del>`convertToRoman(83)`应该返回 'LXXXIII'。 <add>`convertToRoman(83)` 应返回 "LXXXIII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(83), 'LXXXIII'); <ide> ``` <ide> <del>`convertToRoman(97)`应该返回 'XCVII'。 <add>`convertToRoman(97)` 应返回 "XCVII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(97), 'XCVII'); <ide> ``` <ide> <del>`convertToRoman(99)`应该返回 'XCIX'。 <add>`convertToRoman(99)` 应返回 "XCIX"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(99), 'XCIX'); <ide> ``` <ide> <del>`convertToRoman(400)`应该返回 'CD'。 <add>`convertToRoman(400)` 应返回 "CD"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(400), 'CD'); <ide> ``` <ide> <del>`convertToRoman(500)`应该返回 'D'。 <add>`convertToRoman(500)` 应返回 "D"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(500), 'D'); <ide> ``` <ide> <del>`convertToRoman(501)`应该返回 'DI'。 <add>`convertToRoman(501)` 应返回 "DI"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(501), 'DI'); <ide> ``` <ide> <del>`convertToRoman(649)`应该返回 'DCXLIX'。 <add>`convertToRoman(649)` 应返回 "DCXLIX"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(649), 'DCXLIX'); <ide> ``` <ide> <del>`convertToRoman(798)`应该返回 'DCCXCVIII'。 <add>`convertToRoman(798)` 应返回 "DCCXCVIII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(798), 'DCCXCVIII'); <ide> ``` <ide> <del>`convertToRoman(891)`应该返回 'DCCCXCI'。 <add>`convertToRoman(891)` 应返回 "DCCCXCI"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(891), 'DCCCXCI'); <ide> ``` <ide> <del>`convertToRoman(1000)`应该返回 'M'。 <add>`convertToRoman(1000)` 应返回 "M"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(1000), 'M'); <ide> ``` <ide> <del>`convertToRoman(1004)`应该返回 'MIV'。 <add>`convertToRoman(1004)` 应返回 "MIV"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(1004), 'MIV'); <ide> ``` <ide> <del>`convertToRoman(1006)`应该返回 'MVI'。 <add>`convertToRoman(1006)` 应返回 "MVI"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(1006), 'MVI'); <ide> ``` <ide> <del>`convertToRoman(1023)`应该返回 'MXXIII'。 <add>`convertToRoman(1023)` 应返回 "MXXIII"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(1023), 'MXXIII'); <ide> ``` <ide> <del>`convertToRoman(2014)`应该返回 'MMXIV'。 <add>`convertToRoman(2014)` 应返回 "MMXIV"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(2014), 'MMXIV'); <ide> ``` <ide> <del>`convertToRoman(3999)`应该返回 'MMMCMXCIX'。 <add>`convertToRoman(3999)` 应返回 "MMMCMXCIX"。 <ide> <ide> ```js <ide> assert.deepEqual(convertToRoman(3999), 'MMMCMXCIX'); <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.md <ide> --- <ide> id: aff0395860f5d3034dc0bfc9 <del>title: 电话号码验证器 <add>title: 电话号码检查器 <ide> challengeType: 5 <ide> forumTopicId: 16090 <ide> --- <ide> forumTopicId: 16090 <ide> <ide> <blockquote>555-555-5555<br>(555)555-5555<br>(555) 555-5555<br>555 555 5555<br>5555555555<br>1 555 555 5555</blockquote> <ide> <del>在这个挑战中,你将会看到例如`800-692-7753`或者`8oo-six427676;laskdjf`的号码。你的任务是根据上面不同的格式组合,判断它是否美国号码。区号是必须的。如果提供国家代码,则必须确认国家代码为`1`。如果这是有效的美国电话就返回`true`,否则返回`false`。 <add>在这个挑战中,参数可能是 `800-692-7753` 或者 `8oo-six427676;laskdjf` 的号码。你的任务是根据上面不同的格式组合,判断它是否为有效的电话号码。其中,地区码(电话号码中的前三位)是必须的。如果提供国家代码,则国家代码只能为 `1`。如果传入的参数是有效的美国电话号码就返回 `true`,否则返回 `false`。 <ide> <ide> # --hints-- <ide> <del>`telephoneCheck('555-555-5555')`应该返回布尔值。 <add>`telephoneCheck("555-555-5555")` 应返回一个布尔值。 <ide> <ide> ```js <ide> assert(typeof telephoneCheck('555-555-5555') === 'boolean'); <ide> ``` <ide> <del>`telephoneCheck('1 555-555-5555')`应该返回 true。 <add>`telephoneCheck("1 555-555-5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('1 555-555-5555') === true); <ide> ``` <ide> <del>`telephoneCheck('1 (555) 555-5555')`应该返回 true。 <add>`telephoneCheck("1 (555) 555-5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('1 (555) 555-5555') === true); <ide> ``` <ide> <del>`telephoneCheck('5555555555')`应该返回 true。 <add>`telephoneCheck("5555555555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('5555555555') === true); <ide> ``` <ide> <del>`telephoneCheck('555-555-5555')`应该返回 true。 <add>`telephoneCheck("555-555-5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('555-555-5555') === true); <ide> ``` <ide> <del>`telephoneCheck('(555)555-5555')`应该返回 true。 <add>`telephoneCheck("(555)555-5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('(555)555-5555') === true); <ide> ``` <ide> <del>`telephoneCheck('1(555)555-5555')`应该返回 true。 <add>`telephoneCheck("1(555)555-5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('1(555)555-5555') === true); <ide> ``` <ide> <del>`telephoneCheck('555-5555')`应该返回 false。 <add>`telephoneCheck("555-5555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('555-5555') === false); <ide> ``` <ide> <del>`telephoneCheck('5555555')`应该返回 false。 <add>`telephoneCheck("5555555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('5555555') === false); <ide> ``` <ide> <del>`telephoneCheck('1 555)555-5555')`应该返回 false。 <add>`telephoneCheck("1 555)555-5555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('1 555)555-5555') === false); <ide> ``` <ide> <del>`telephoneCheck('1 555 555 5555')`应该返回 true。 <add>`telephoneCheck("1 555 555 5555")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('1 555 555 5555') === true); <ide> ``` <ide> <del>`telephoneCheck('1 456 789 4444')`应该返回 true。 <add>`telephoneCheck("1 456 789 4444")` 应返回 true。 <ide> <ide> ```js <ide> assert(telephoneCheck('1 456 789 4444') === true); <ide> ``` <ide> <del>`telephoneCheck('123**&!!asdf#')`应该返回 false。 <add>`telephoneCheck("123**&!!asdf#")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('123**&!!asdf#') === false); <ide> ``` <ide> <del>`telephoneCheck('55555555')`应该返回 false。 <add>`telephoneCheck("55555555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('55555555') === false); <ide> ``` <ide> <del>`telephoneCheck('(6054756961)')`应该返回 false。 <add>`telephoneCheck("(6054756961)")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('(6054756961)') === false); <ide> ``` <ide> <del>`telephoneCheck('2 (757) 622-7382')`应该返回 false。 <add>`telephoneCheck("2 (757) 622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('2 (757) 622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('0 (757) 622-7382')`应该返回 false。 <add>`telephoneCheck("0 (757) 622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('0 (757) 622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('-1 (757) 622-7382')`应该返回 false。 <add>`telephoneCheck("-1 (757) 622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('-1 (757) 622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('2 757 622-7382')`应该返回 false。 <add>`telephoneCheck("2 757 622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('2 757 622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('10 (757) 622-7382')`应该返回 false。 <add>`telephoneCheck("10 (757) 622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('10 (757) 622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('27576227382')`应该返回 false。 <add>`telephoneCheck("27576227382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('27576227382') === false); <ide> ``` <ide> <del>`telephoneCheck('(275)76227382')`应该返回 false。 <add>`telephoneCheck("(275)76227382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('(275)76227382') === false); <ide> ``` <ide> <del>`telephoneCheck('2(757)6227382')`应该返回 false。 <add>`telephoneCheck("2(757)6227382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('2(757)6227382') === false); <ide> ``` <ide> <del>`telephoneCheck('2(757)622-7382')`应该返回 false。 <add>`telephoneCheck("2(757)622-7382")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('2(757)622-7382') === false); <ide> ``` <ide> <del>`telephoneCheck('555)-555-5555')`应该返回 false。 <add>`telephoneCheck("555)-555-5555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('555)-555-5555') === false); <ide> ``` <ide> <del>`telephoneCheck('(555-555-5555')`应该返回 false。 <add>`telephoneCheck("(555-555-5555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('(555-555-5555') === false); <ide> ``` <ide> <del>`telephoneCheck('(555)5(55?)-5555')`应该返回 false。 <add>`telephoneCheck("(555)5(55?)-5555")` 应返回 false。 <ide> <ide> ```js <ide> assert(telephoneCheck('(555)5(55?)-5555') === false);
62
Ruby
Ruby
replace find_all + each with grep
177eee419a455c3fc759d6a75c392f30be50a4dc
<ide><path>Library/Homebrew/extend/set.rb <ide> def add new <ide> # smileys only <ide> return super new unless new.respond_to? :> <ide> <del> objs = find_all { |o| o.class == new.class } <del> objs.each do |o| <add> grep(new.class) do |o| <ide> return self if o > new <ide> delete o <ide> end
1
Text
Text
add arcelement to getting-started.md
3c79d104d97aa7ed25ba4e9fc134809078a2f324
<ide><path>docs/docs/getting-started/integration.md <ide> var myChart = new Chart(ctx, {...}); <ide> <ide> Chart.js 3 is tree-shakeable, so it is necessary to import and register the controllers, elements, scales and plugins you are going to use. <ide> <add>For all available imports see the example below. <ide> ```javascript <del>import { Chart, LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend } from 'chart.js'; <add>import { <add> Chart, <add> ArcElement, <add> LineElement, <add> BarElement, <add> PointElement, <add> BarController, <add> BubbleController, <add> DoughnutController, <add> LineController, <add> PieController, <add> PolarAreaController, <add> RadarController, <add> ScatterController, <add> CategoryScale, <add> LinearScale, <add> LogarithmicScale, <add> RadialLinearScale, <add> TimeScale, <add> TimeSeriesScale, <add> Filler, <add> Legend, <add> Title, <add> Tooltip <add>} from 'chart.js'; <ide> <del>Chart.register(LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend); <add>Chart.register( <add> ArcElement, <add> LineElement, <add> BarElement, <add> PointElement, <add> BarController, <add> BubbleController, <add> DoughnutController, <add> LineController, <add> PieController, <add> PolarAreaController, <add> RadarController, <add> ScatterController, <add> CategoryScale, <add> LinearScale, <add> LogarithmicScale, <add> RadialLinearScale, <add> TimeScale, <add> TimeSeriesScale, <add> Filler, <add> Legend, <add> Title, <add> Tooltip <add>); <ide> <ide> var myChart = new Chart(ctx, {...}); <ide> ```
1
Javascript
Javascript
remove log and verify lint
98bb0d40def09927fec538c8e282c564cf361954
<ide><path>script/lib/verify-machine-requirements.js <ide> const path = require('path'); <ide> const CONFIG = require('../config'); <ide> <ide> module.exports = function(ci) { <del> console.log('------') <del> console.log(ci) <del> console.log('------') <ide> verifyNode(); <ide> verifyNpm(ci); <ide> if (process.platform === 'win32') {
1
Text
Text
add changelogs for dgram
fb9572bf61f341f405d785800f6e3a3f520db264
<ide><path>doc/api/dgram.md <ide> chained. <ide> ### socket.send(msg, [offset, length,] port [, address] [, callback]) <ide> <!-- YAML <ide> added: v0.1.99 <add>changes: <add> - version: v6.0.0 <add> pr-url: https://github.com/nodejs/node/pull/5929 <add> description: On success, `callback` will now be called with an `error` <add> argument of `null` rather than `0`. <add> - version: v5.7.0 <add> pr-url: https://github.com/nodejs/node/pull/4374 <add> description: The `msg` parameter can be an array now. Also, the `offset` <add> and `length` parameters are optional now. <ide> --> <ide> <ide> * `msg` {Buffer|String|Array} Message to be sent
1
Python
Python
fix indentation of _utils
cbecc96b62477890174ae91433c4c9c28cc7765b
<ide><path>numpy/_utils/__init__.py <ide> <ide> <ide> def set_module(module): <del> """Private decorator for overriding __module__ on a function or class. <add> """Private decorator for overriding __module__ on a function or class. <ide> <del> Example usage:: <add> Example usage:: <ide> <del> @set_module('numpy') <del> def example(): <del> pass <add> @set_module('numpy') <add> def example(): <add> pass <ide> <del> assert example.__module__ == 'numpy' <del> """ <del> def decorator(func): <del> if module is not None: <del> func.__module__ = module <del> return func <del> return decorator <add> assert example.__module__ == 'numpy' <add> """ <add> def decorator(func): <add> if module is not None: <add> func.__module__ = module <add> return func <add> return decorator
1
Javascript
Javascript
add global to eslint plugin bundle config
9fb91994557ab9b47e23307aa8914d0504905f56
<ide><path>scripts/rollup/bundles.js <ide> const bundles = [ <ide> bundleTypes: [NODE_DEV, NODE_PROD, FB_WWW_DEV], <ide> moduleType: ISOMORPHIC, <ide> entry: 'eslint-plugin-react-hooks', <add> global: 'ESlintPluginReactHooks', <ide> externals: [], <ide> }, <ide>
1
Python
Python
do cheaper check for column having a type
1a6d07783d980664312ce729e1fc8867ad1a3b5c
<ide><path>django/db/backends/schema.py <ide> def delete_field(self, model, field): <ide> # Special-case implicit M2M tables <ide> if isinstance(field, ManyToManyField) and field.rel.through._meta.auto_created: <ide> return self.delete_model(field.rel.through) <del> # Get the column's definition <del> definition, params = self.column_sql(model, field) <ide> # It might not actually have a column behind it <del> if definition is None: <add> if field.db_parameters(connection=self.connection)['type'] is None: <ide> return <add> # Get the column's definition <add> definition, params = self.column_sql(model, field) <ide> # Delete the column <ide> sql = self.sql_delete_column % { <ide> "table": self.quote_name(model._meta.db_table),
1
Javascript
Javascript
fix decodeattribute reference
66225408ce42a9fa7dcf735ecbc69e66481d5a62
<ide><path>examples/js/loaders/DRACOLoader2.js <ide> THREE.DRACOLoader.DRACOWorker = function () { <ide> var attributeId = attributeIDs[ attributeName ]; <ide> var attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeId ); <ide> <del> geometry.attributes.push( this.decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) ); <add> geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) ); <ide> <ide> } <ide>
1
Python
Python
fix reformer fp16
7f65daa2e155ecdd8594e19862dac8b322ed3b73
<ide><path>tests/test_modeling_reformer.py <ide> def create_and_check_reformer_model_fp16_forward(self, config, input_ids, input_ <ide> model.to(torch_device) <ide> model.half() <ide> model.eval() <del> output = model(input_ids, attention_mask=input_mask)["last_input_state"] <add> output = model(input_ids, attention_mask=input_mask)["last_hidden_state"] <ide> self.parent.assertFalse(torch.isnan(output).any().item()) <ide> <ide> def create_and_check_reformer_model_generate(self, config, input_ids, input_mask, choice_labels):
1
Text
Text
fix typo in readme
ff5cd292e339cb997a2c8fa6958b915a9eaecb28
<ide><path>README.md <ide> These are the available config options for making requests. Only the `url` is re <ide> // `headers` are custom headers to be sent <ide> headers: {'X-Requested-With': 'XMLHttpRequest'}, <ide> <del> // `param` are the URL parameters to be sent with the request <add> // `params` are the URL parameters to be sent with the request <ide> params: { <ide> ID: 12345 <ide> },
1
Text
Text
add translations to titles and fix typo
6e7aeeda2ff0761de3fe404cd09b086e0de72d1b
<ide><path>curriculum/challenges/portuguese/01-responsive-web-design/basic-css/add-a-negative-margin-to-an-element.portuguese.md <ide> videoUrl: '' <ide> localeTitle: Adicione uma margem negativa a um elemento <ide> --- <ide> <del>## Description <del><section id="description"> A <code>margin</code> é um elemento CSS que controla a quantidade de espaço entre a <code>border</code> de um elemento com os elementos adjacentes. Se você definir a <code>margin</code> de um elemento como um valor negativo, o elemento ficará maior. </section> <ide> <del>## Instructions <del><section id="instructions"> Tente definir a <code>margin</code> para um valor negativo como o da caixa vermelha. Altere a <code>margin</code> da caixa azul para <code>-15px</code> , para preencher toda a largura horizontal da caixa amarela em torno dela. </section> <add>## Descrição <add><section id="description"> O elemento <code>margin</code> controla a quantidade de espaço entre o elemento <code>border</code> e os elementos adjacentes. Se você definir o elemento <code>margin</code> com um valor negativo, o elemento ficará maior. </section> <ide> <del>## Tests <add>## Intruções <add><section id="instructions"> Tente definir a <code>margin</code> para um valor negativo como o da caixa vermelha. Altere a <code>margin</code> da caixa azul para <code>-15px</code>, para preencher toda a largura horizontal da caixa amarela em torno dela.</section> <add> <add>## Testes <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: Sua classe de <code>blue-box</code> deve fornecer elementos de <code>-15px</code> de <code>margin</code> . <add> - text: Sua classe <code>blue-box</code> deve fornecer elementos de <code>-15px</code> de <code>margin</code> . <ide> testString: 'assert($(".blue-box").css("margin-top") === "-15px", "Your <code>blue-box</code> class should give elements <code>-15px</code> of <code>margin</code>.");' <ide> <ide> ``` <ide> <ide> </section> <ide> <del>## Challenge Seed <add>## Desafio <ide> <section id='challengeSeed'> <ide> <ide> <div id='html-seed'> <ide> tests: <ide> <ide> </section> <ide> <del>## Solution <add>## Solução <ide> <section id='solution'> <ide> <ide> ```js
1
Javascript
Javascript
use async/await in rollup scripts
a65a8abc65cd31c862f5e83eb24a8dc68458b521
<ide><path>scripts/rollup/build.js <ide> function getBabelConfig(updateBabelOptions, bundleType, filename) { <ide> plugins: options.plugins.concat([ <ide> // Use object-assign polyfill in open source <ide> resolve('./scripts/babel/transform-object-assign-require'), <del> <ide> // Minify invariant messages <ide> require('../error-codes/replace-invariant-error-codes'), <del> <ide> // Wrap warning() calls in a __DEV__ check so they are stripped from production. <ide> require('./plugins/wrap-warning-with-env-check'), <ide> ]), <ide> function getPlugins( <ide> ].filter(Boolean); <ide> } <ide> <del>function createBundle(bundle, bundleType) { <add>async function createBundle(bundle, bundleType) { <ide> const shouldSkipBundleType = bundle.bundleTypes.indexOf(bundleType) === -1; <ide> if (shouldSkipBundleType) { <del> return Promise.resolve(); <add> return; <ide> } <ide> if (requestedBundleTypes.length > 0) { <ide> const isAskingForDifferentType = requestedBundleTypes.every( <ide> requestedType => bundleType.indexOf(requestedType) === -1 <ide> ); <ide> if (isAskingForDifferentType) { <del> return Promise.resolve(); <add> return; <ide> } <ide> } <ide> if (requestedBundleNames.length > 0) { <ide> const isAskingForDifferentNames = requestedBundleNames.every( <ide> requestedName => bundle.label.indexOf(requestedName) === -1 <ide> ); <ide> if (isAskingForDifferentNames) { <del> return Promise.resolve(); <add> return; <ide> } <ide> } <ide> <ide> function createBundle(bundle, bundleType) { <ide> ); <ide> <ide> console.log(`${chalk.bgYellow.black(' BUILDING ')} ${logKey}`); <del> return rollup({ <del> input: resolvedEntry, <del> pureExternalModules, <del> external(id) { <del> const containsThisModule = pkg => id === pkg || id.startsWith(pkg + '/'); <del> const isProvidedByDependency = externals.some(containsThisModule); <del> if (!shouldBundleDependencies && isProvidedByDependency) { <del> return true; <del> } <del> return !!peerGlobals[id]; <del> }, <del> onwarn: handleRollupWarnings, <del> plugins: getPlugins( <del> bundle.entry, <del> externals, <del> bundle.babel, <del> filename, <del> bundleType, <del> bundle.global, <del> bundle.moduleType, <del> bundle.modulesToStub, <del> bundle.featureFlags <del> ), <del> // We can't use getters in www. <del> legacy: bundleType === FB_DEV || bundleType === FB_PROD, <del> }) <del> .then(result => <del> result.write( <del> getRollupOutputOptions( <del> filename, <del> format, <del> bundleType, <del> peerGlobals, <del> bundle.global, <del> bundle.moduleType <del> ) <del> ) <del> ) <del> .then(() => Packaging.createNodePackage(bundleType, packageName, filename)) <del> .then(() => { <del> console.log(`${chalk.bgGreen.black(' COMPLETE ')} ${logKey}\n`); <del> }) <del> .catch(error => { <del> if (error.code) { <del> console.error( <del> `\x1b[31m-- ${error.code}${ <del> error.plugin ? ` (${error.plugin})` : '' <del> } --` <del> ); <del> console.error(error.message); <del> <del> const {file, line, column} = error.loc; <del> if (file) { <del> // This looks like an error from Rollup, e.g. missing export. <del> // We'll use the accurate line numbers provided by Rollup but <del> // use Babel code frame because it looks nicer. <del> const rawLines = fs.readFileSync(file, 'utf-8'); <del> // column + 1 is required due to rollup counting column start position from 0 <del> // whereas babel-code-frame counts from 1 <del> const frame = codeFrame(rawLines, line, column + 1, { <del> highlightCode: true, <del> }); <del> console.error(frame); <del> } else { <del> // This looks like an error from a plugin (e.g. Babel). <del> // In this case we'll resort to displaying the provided code frame <del> // because we can't be sure the reported location is accurate. <del> console.error(error.codeFrame); <add> try { <add> const result = await rollup({ <add> input: resolvedEntry, <add> pureExternalModules, <add> external(id) { <add> const containsThisModule = pkg => <add> id === pkg || id.startsWith(pkg + '/'); <add> const isProvidedByDependency = externals.some(containsThisModule); <add> if (!shouldBundleDependencies && isProvidedByDependency) { <add> return true; <ide> } <add> return !!peerGlobals[id]; <add> }, <add> onwarn: handleRollupWarnings, <add> plugins: getPlugins( <add> bundle.entry, <add> externals, <add> bundle.babel, <add> filename, <add> bundleType, <add> bundle.global, <add> bundle.moduleType, <add> bundle.modulesToStub, <add> bundle.featureFlags <add> ), <add> // We can't use getters in www. <add> legacy: bundleType === FB_DEV || bundleType === FB_PROD, <add> }); <add> await result.write( <add> getRollupOutputOptions( <add> filename, <add> format, <add> bundleType, <add> peerGlobals, <add> bundle.global, <add> bundle.moduleType <add> ) <add> ); <add> await Packaging.createNodePackage(bundleType, packageName, filename); <add> console.log(`${chalk.bgGreen.black(' COMPLETE ')} ${logKey}\n`); <add> } catch (error) { <add> if (error.code) { <add> console.error( <add> `\x1b[31m-- ${error.code}${error.plugin ? ` (${error.plugin})` : ''} --` <add> ); <add> console.error(error.message); <add> const {file, line, column} = error.loc; <add> if (file) { <add> // This looks like an error from Rollup, e.g. missing export. <add> // We'll use the accurate line numbers provided by Rollup but <add> // use Babel code frame because it looks nicer. <add> const rawLines = fs.readFileSync(file, 'utf-8'); <add> // column + 1 is required due to rollup counting column start position from 0 <add> // whereas babel-code-frame counts from 1 <add> const frame = codeFrame(rawLines, line, column + 1, { <add> highlightCode: true, <add> }); <add> console.error(frame); <ide> } else { <del> console.error(error); <add> // This looks like an error from a plugin (e.g. Babel). <add> // In this case we'll resort to displaying the provided code frame <add> // because we can't be sure the reported location is accurate. <add> console.error(error.codeFrame); <ide> } <del> process.exit(1); <del> }); <add> } else { <add> console.error(error); <add> } <add> process.exit(1); <add> } <ide> } <ide> <ide> // clear the build directory <del>rimraf('build', () => { <del> // create a new build directory <del> fs.mkdirSync('build'); <del> // create the packages folder for NODE+UMD bundles <del> fs.mkdirSync(join('build', 'packages')); <del> // create the dist folder for UMD bundles <del> fs.mkdirSync(join('build', 'dist')); <add>rimraf('build', async () => { <add> try { <add> // create a new build directory <add> fs.mkdirSync('build'); <add> // create the packages folder for NODE+UMD bundles <add> fs.mkdirSync(join('build', 'packages')); <add> // create the dist folder for UMD bundles <add> fs.mkdirSync(join('build', 'dist')); <ide> <del> const tasks = [ <del> Packaging.createFacebookWWWBuild, <del> Packaging.createReactNativeBuild, <del> Packaging.createReactNativeRTBuild, <del> Packaging.createReactNativeCSBuild, <del> ]; <del> for (const bundle of Bundles.bundles) { <del> tasks.push( <del> () => createBundle(bundle, UMD_DEV), <del> () => createBundle(bundle, UMD_PROD), <del> () => createBundle(bundle, NODE_DEV), <del> () => createBundle(bundle, NODE_PROD), <del> () => createBundle(bundle, FB_DEV), <del> () => createBundle(bundle, FB_PROD), <del> () => createBundle(bundle, RN_DEV), <del> () => createBundle(bundle, RN_PROD) <del> ); <del> } <del> if (syncFbsource) { <del> tasks.push(() => <del> syncReactNative(join('build', 'react-native'), syncFbsource) <del> ); <del> tasks.push(() => <del> syncReactNativeRT(join('build', 'react-rt'), syncFbsource) <del> ); <del> tasks.push(() => <del> syncReactNativeCS(join('build', 'react-cs'), syncFbsource) <del> ); <del> } else if (syncWww) { <del> tasks.push(() => syncReactDom(join('build', 'facebook-www'), syncWww)); <del> } <del> // rather than run concurrently, opt to run them serially <del> // this helps improve console/warning/error output <del> // and fixes a bunch of IO failures that sometimes occurred <del> return runWaterfall(tasks) <del> .then(() => { <del> // output the results <del> console.log(Stats.printResults()); <del> // save the results for next run <del> Stats.saveResults(); <del> if (shouldExtractErrors) { <del> console.warn( <del> '\nWarning: this build was created with --extract-errors enabled.\n' + <del> 'this will result in extremely slow builds and should only be\n' + <del> 'used when the error map needs to be rebuilt.\n' <del> ); <del> } <del> }) <del> .catch(err => { <del> console.error(err); <del> process.exit(1); <del> }); <del>}); <add> await Packaging.createFacebookWWWBuild(); <add> await Packaging.createReactNativeBuild(); <add> await Packaging.createReactNativeRTBuild(); <add> await Packaging.createReactNativeCSBuild(); <ide> <del>function runWaterfall(promiseFactories) { <del> if (promiseFactories.length === 0) { <del> return Promise.resolve(); <del> } <add> // Run them serially for better console output <add> // and to avoid any potential race conditions. <add> for (const bundle of Bundles.bundles) { <add> await createBundle(bundle, UMD_DEV); <add> await createBundle(bundle, UMD_PROD); <add> await createBundle(bundle, NODE_DEV); <add> await createBundle(bundle, NODE_PROD); <add> await createBundle(bundle, FB_DEV); <add> await createBundle(bundle, FB_PROD); <add> await createBundle(bundle, RN_DEV); <add> await createBundle(bundle, RN_PROD); <add> } <ide> <del> const head = promiseFactories[0]; <del> const tail = promiseFactories.slice(1); <add> if (syncFbsource) { <add> await syncReactNative(join('build', 'react-native'), syncFbsource); <add> await syncReactNativeRT(join('build', 'react-rt'), syncFbsource); <add> await syncReactNativeCS(join('build', 'react-cs'), syncFbsource); <add> } else if (syncWww) { <add> await syncReactDom(join('build', 'facebook-www'), syncWww); <add> } <ide> <del> const nextPromiseFactory = head; <del> const nextPromise = nextPromiseFactory(); <del> if (!nextPromise || typeof nextPromise.then !== 'function') { <del> throw new Error('runWaterfall() received something that is not a Promise.'); <add> console.log(Stats.printResults()); <add> // save the results for next run <add> Stats.saveResults(); <add> if (shouldExtractErrors) { <add> console.warn( <add> '\nWarning: this build was created with --extract-errors enabled.\n' + <add> 'this will result in extremely slow builds and should only be\n' + <add> 'used when the error map needs to be rebuilt.\n' <add> ); <add> } <add> } catch (err) { <add> console.error(err); <add> process.exit(1); <ide> } <del> <del> return nextPromise.then(() => { <del> return runWaterfall(tail); <del> }); <del>} <add>}); <ide><path>scripts/rollup/packaging.js <ide> function getPackageName(name) { <ide> return name; <ide> } <ide> <del>function createReactNativeBuild() { <del> // create the react-native folder for FB bundles <add>async function createReactNativeBuild() { <ide> fs.mkdirSync(join('build', 'react-native')); <del> // create the react-native shims folder for FB shims <ide> fs.mkdirSync(join('build', 'react-native', 'shims')); <del> // copy in all the shims from build/rollup/shims/react-native <ide> const from = join('scripts', 'rollup', 'shims', 'react-native'); <ide> const to = join('build', 'react-native', 'shims'); <del> <del> return asyncCopyTo(from, to).then(() => { <del> let promises = []; <del> // we also need to copy over some specific files from src <del> // defined in reactNativeSrcDependencies <del> for (const srcDependency of reactNativeSrcDependencies) { <del> promises.push( <del> asyncCopyTo(resolve(srcDependency), join(to, basename(srcDependency))) <del> ); <del> } <del> return Promise.all(promises); <del> }); <add> await asyncCopyTo(from, to); <add> await Promise.all( <add> reactNativeSrcDependencies.map(srcDependency => <add> asyncCopyTo(resolve(srcDependency), join(to, basename(srcDependency))) <add> ) <add> ); <ide> } <ide> <del>function createReactNativeRTBuild() { <del> // create the react-rt folder for FB bundles <add>async function createReactNativeRTBuild() { <ide> fs.mkdirSync(join('build', 'react-rt')); <del> // create the react-rt shims folder for FB shims <ide> fs.mkdirSync(join('build', 'react-rt', 'shims')); <del> <ide> const to = join('build', 'react-rt', 'shims'); <del> <del> let promises = []; <del> // we also need to copy over some specific files from src <del> // defined in reactNativeRTSrcDependencies <del> for (const srcDependency of reactNativeRTSrcDependencies) { <del> promises.push( <add> await Promise.all( <add> reactNativeRTSrcDependencies.map(srcDependency => <ide> asyncCopyTo(resolve(srcDependency), join(to, basename(srcDependency))) <del> ); <del> } <del> return Promise.all(promises); <add> ) <add> ); <ide> } <ide> <del>function createReactNativeCSBuild() { <del> // create the react-cs folder for FB bundles <add>async function createReactNativeCSBuild() { <ide> fs.mkdirSync(join('build', 'react-cs')); <del> // create the react-cs shims folder for FB shims <ide> fs.mkdirSync(join('build', 'react-cs', 'shims')); <del> <ide> const to = join('build', 'react-cs', 'shims'); <del> <del> let promises = []; <del> // we also need to copy over some specific files from src <del> // defined in reactNativeCSSrcDependencies <del> for (const srcDependency of reactNativeCSSrcDependencies) { <del> promises.push( <add> await Promise.all( <add> reactNativeCSSrcDependencies.map(srcDependency => <ide> asyncCopyTo(resolve(srcDependency), join(to, basename(srcDependency))) <del> ); <del> } <del> return Promise.all(promises); <add> ) <add> ); <ide> } <ide> <del>function createFacebookWWWBuild() { <del> // create the facebookWWW folder for FB bundles <add>async function createFacebookWWWBuild() { <ide> fs.mkdirSync(join('build', facebookWWW)); <del> // create the facebookWWW shims folder for FB shims <ide> fs.mkdirSync(join('build', facebookWWW, 'shims')); <del> // copy in all the shims from build/rollup/shims/facebook-www <ide> const from = join('scripts', 'rollup', 'shims', facebookWWW); <ide> const to = join('build', facebookWWW, 'shims'); <del> <del> return asyncCopyTo(from, to); <add> await asyncCopyTo(from, to); <ide> } <ide> <del>function copyBundleIntoNodePackage(packageName, filename, bundleType) { <add>async function copyBundleIntoNodePackage(packageName, filename, bundleType) { <ide> const packageDirectory = resolve(`./build/packages/${packageName}`); <del> <del> if (fs.existsSync(packageDirectory)) { <del> let from = resolve(`./build/${filename}`); <del> let to = `${packageDirectory}/${filename}`; <del> // for UMD bundles we have to move the files into a umd directory <del> // within the package directory. we also need to set the from <del> // to be the root build from directory <del> if (bundleType === UMD_DEV || bundleType === UMD_PROD) { <del> const distDirectory = `${packageDirectory}/umd`; <del> // create a dist directory if not created <del> if (!fs.existsSync(distDirectory)) { <del> fs.mkdirSync(distDirectory); <del> } <del> from = resolve(`./build/dist/${filename}`); <del> to = `${packageDirectory}/umd/${filename}`; <add> if (!fs.existsSync(packageDirectory)) { <add> return; <add> } <add> let from = resolve(`./build/${filename}`); <add> let to = `${packageDirectory}/${filename}`; <add> // for UMD bundles we have to move the files into a umd directory <add> // within the package directory. we also need to set the from <add> // to be the root build from directory <add> if (bundleType === UMD_DEV || bundleType === UMD_PROD) { <add> const distDirectory = `${packageDirectory}/umd`; <add> // create a dist directory if not created <add> if (!fs.existsSync(distDirectory)) { <add> fs.mkdirSync(distDirectory); <ide> } <del> // for NODE bundles we have to move the files into a cjs directory <del> // within the package directory. we also need to set the from <del> // to be the root build from directory <del> if (bundleType === NODE_DEV || bundleType === NODE_PROD) { <del> const distDirectory = `${packageDirectory}/cjs`; <del> // create a dist directory if not created <del> if (!fs.existsSync(distDirectory)) { <del> fs.mkdirSync(distDirectory); <del> } <del> to = `${packageDirectory}/cjs/${filename}`; <add> from = resolve(`./build/dist/${filename}`); <add> to = `${packageDirectory}/umd/${filename}`; <add> } <add> // for NODE bundles we have to move the files into a cjs directory <add> // within the package directory. we also need to set the from <add> // to be the root build from directory <add> if (bundleType === NODE_DEV || bundleType === NODE_PROD) { <add> const distDirectory = `${packageDirectory}/cjs`; <add> // create a dist directory if not created <add> if (!fs.existsSync(distDirectory)) { <add> fs.mkdirSync(distDirectory); <ide> } <del> return asyncCopyTo(from, to).then(() => { <del> // delete the old file if this is a not a UMD bundle <del> if (bundleType !== UMD_DEV && bundleType !== UMD_PROD) { <del> fs.unlinkSync(from); <del> } <del> }); <del> } else { <del> return Promise.resolve(); <add> to = `${packageDirectory}/cjs/${filename}`; <add> } <add> await asyncCopyTo(from, to); <add> // delete the old file if this is a not a UMD bundle <add> if (bundleType !== UMD_DEV && bundleType !== UMD_PROD) { <add> fs.unlinkSync(from); <ide> } <ide> } <ide> <del>function copyNodePackageTemplate(packageName) { <add>async function copyNodePackageTemplate(packageName) { <ide> const from = resolve(`./packages/${packageName}`); <ide> const to = resolve(`./build/packages/${packageName}`); <ide> const npmFrom = resolve(`${from}/npm`); <ide> if (!fs.existsSync(npmFrom)) { <ide> // The package is not meant for npm consumption. <del> return Promise.resolve(); <add> return; <ide> } <ide> if (fs.existsSync(to)) { <ide> // We already created this package (e.g. due to another entry point). <del> return Promise.resolve(); <add> return; <ide> } <ide> // TODO: verify that all copied files are either in the "files" <ide> // whitelist or implicitly published by npm. <del> return asyncCopyTo(npmFrom, to).then(() => <del> Promise.all([ <del> asyncCopyTo(resolve(`${from}/package.json`), `${to}/package.json`), <del> asyncCopyTo(resolve(`${from}/README.md`), `${to}/README.md`), <del> asyncCopyTo(resolve('./LICENSE'), `${to}/LICENSE`), <del> ]) <del> ); <add> await asyncCopyTo(npmFrom, to); <add> await asyncCopyTo(resolve(`${from}/package.json`), `${to}/package.json`); <add> await asyncCopyTo(resolve(`${from}/README.md`), `${to}/README.md`); <add> await asyncCopyTo(resolve('./LICENSE'), `${to}/LICENSE`); <ide> } <ide> <del>function createNodePackage(bundleType, packageName, filename) { <add>async function createNodePackage(bundleType, packageName, filename) { <ide> // the only case where we don't want to copy the package is for FB bundles <del> if (bundleType !== FB_DEV && bundleType !== FB_PROD) { <del> return copyNodePackageTemplate(packageName).then(() => <del> copyBundleIntoNodePackage(packageName, filename, bundleType) <del> ); <add> if (bundleType === FB_DEV || bundleType === FB_PROD) { <add> return; <ide> } <del> return Promise.resolve(); <add> await copyNodePackageTemplate(packageName); <add> await copyBundleIntoNodePackage(packageName, filename, bundleType); <ide> } <ide> <ide> function getOutputPathRelativeToBuildFolder(bundleType, filename, hasteName) { <ide><path>scripts/rollup/sync.js <ide> const RELATIVE_RN_CS_PATH = 'xplat/js/RKJSModules/Libraries/CS/downstream/'; <ide> const RELATIVE_RN_RT_PATH = 'xplat/js/RKJSModules/Libraries/RT/downstream/'; <ide> const RELATIVE_WWW_PATH = 'html/shared/react/'; <ide> <del>function doSync(buildPath, destPath) { <add>async function doSync(buildPath, destPath) { <ide> console.log(`${chalk.bgYellow.black(' SYNCING ')} React to ${destPath}`); <ide> <del> const promise = asyncCopyTo(buildPath, destPath); <del> promise.then(() => { <del> console.log(`${chalk.bgGreen.black(' SYNCED ')} React to ${destPath}`); <del> }); <del> <del> return promise; <add> await asyncCopyTo(buildPath, destPath); <add> console.log(`${chalk.bgGreen.black(' SYNCED ')} React to ${destPath}`); <ide> } <ide> <del>function syncReactDom(buildPath, wwwPath) { <add>async function syncReactDom(buildPath, wwwPath) { <ide> wwwPath = typeof wwwPath === 'string' ? wwwPath : DEFAULT_WWW_PATH; <ide> <ide> if (wwwPath.charAt(wwwPath.length - 1) !== '/') { <ide> wwwPath += '/'; <ide> } <ide> <ide> const destPath = resolvePath(wwwPath + RELATIVE_WWW_PATH); <del> <del> return doSync(buildPath, destPath); <add> await doSync(buildPath, destPath); <ide> } <ide> <del>function syncReactNativeHelper(buildPath, fbSourcePath, relativeDestPath) { <add>async function syncReactNativeHelper( <add> buildPath, <add> fbSourcePath, <add> relativeDestPath <add>) { <ide> fbSourcePath = <ide> typeof fbSourcePath === 'string' ? fbSourcePath : DEFAULT_FB_SOURCE_PATH; <ide> <ide> function syncReactNativeHelper(buildPath, fbSourcePath, relativeDestPath) { <ide> } <ide> <ide> const destPath = resolvePath(fbSourcePath + relativeDestPath); <del> <del> return doSync(buildPath, destPath); <add> await doSync(buildPath, destPath); <ide> } <ide> <del>function syncReactNative(buildPath, fbSourcePath) { <del> return syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_PATH); <add>async function syncReactNative(buildPath, fbSourcePath) { <add> await syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_PATH); <ide> } <ide> <del>function syncReactNativeCS(buildPath, fbSourcePath) { <del> return syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_CS_PATH); <add>async function syncReactNativeCS(buildPath, fbSourcePath) { <add> await syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_CS_PATH); <ide> } <ide> <del>function syncReactNativeRT(buildPath, fbSourcePath) { <del> return syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_RT_PATH); <add>async function syncReactNativeRT(buildPath, fbSourcePath) { <add> await syncReactNativeHelper(buildPath, fbSourcePath, RELATIVE_RN_RT_PATH); <ide> } <ide> <ide> module.exports = {
3
Text
Text
add v3.7.3 to changelog
587d91c9c9bf07ed4a7b7325bf7652848074baa8
<ide><path>CHANGELOG.md <ide> - [#17357](https://github.com/emberjs/ember.js/pull/17357) Allow notifyPropertyChange to be imported from @ember/object <ide> - [#17413](https://github.com/emberjs/ember.js/pull/17413) Fix missing import in instance-initializer blueprint for ember-mocha <ide> <add>### v3.7.3 (February 6, 2019) <add> <add>- [#17563](https://github.com/emberjs/ember.js/pull/17563) [BUGFIX] Transition.send/trigger call signature <add>- [#17552](https://github.com/emberjs/ember.js/pull/17552) [BUGFIX] Support numbers in component names for Angle Brackets <add> <ide> ### v3.7.2 (January 22, 2019) <ide> <ide> * Upgrade @glimmer/* packages to 0.35.10. Fixes a few issues:
1
Javascript
Javascript
improve binarymiddleware test cases
a4d1f7cbd794c9cfdf324e3ec39cd05f67e5163f
<ide><path>test/BinaryMiddleware.unittest.js <ide> describe("BinaryMiddleware", () => { <ide> -11, <ide> -0x100, <ide> -1.25, <del> SerializerMiddleware.createLazy([5], other), <add> SerializerMiddleware.createLazy([5], other) <add> ]; <add> <add> const itemsWithLazy = [ <add> ...items, <ide> SerializerMiddleware.createLazy( <ide> [SerializerMiddleware.createLazy([5], other)], <ide> mw <ide> describe("BinaryMiddleware", () => { <ide> mw <ide> ) <ide> ]; <del> items.push(SerializerMiddleware.createLazy(items.slice(), mw)); <del> items.push(SerializerMiddleware.createLazy(items.slice(), other)); <add> itemsWithLazy.push( <add> SerializerMiddleware.createLazy(itemsWithLazy.slice(), mw) <add> ); <add> itemsWithLazy.push( <add> SerializerMiddleware.createLazy(itemsWithLazy.slice(), other) <add> ); <add> <ide> items.push(undefined); <ide> <ide> const cases = [ <del> ...items.map(item => [item]), <add> ...itemsWithLazy.map(item => [item]), <ide> [(true, true)], <ide> [false, true], <ide> [true, false], <ide> describe("BinaryMiddleware", () => { <ide> cont([false, true, false, true], 133), <ide> cont([false, true, false, true], 134), <ide> cont([false, true, false, true], 135), <add> cont([false, true, false, true], 10000), <ide> cont([true], 135), <ide> [null], <ide> [null, null], <ide> describe("BinaryMiddleware", () => { <ide> cont([5.5], 20) <ide> ]; <ide> <del> for (const caseData of cases) { <del> for (const prepend of items) { <del> for (const append of items) { <del> const data = [prepend, ...caseData, append].filter( <del> x => x !== undefined <del> ); <del> if (data.length === 0) continue; <del> const key = JSON.stringify(data.map(resolveLazy)); <del> it(`should serialize ${key} (${data.length}) correctly`, () => { <del> const serialized = mw.serialize(data, {}); <del> const newData = mw.deserialize(serialized, {}); <del> expect(newData.map(resolveLazy)).toEqual(data.map(resolveLazy)); <del> }); <add> for (const c of [1, 100]) { <add> for (const caseData of cases) { <add> for (const prepend of items) { <add> for (const append of items) { <add> if (c > 1 && append !== undefined) continue; <add> let data = [prepend, ...caseData, append].filter( <add> x => x !== undefined <add> ); <add> if (data.length * c > 200000) continue; <add> if (data.length === 0) continue; <add> let key = JSON.stringify(data.map(resolveLazy)); <add> if (key.length > 100) <add> key = key.slice(0, 50) + " ... " + key.slice(-50); <add> it(`should serialize ${c} x ${key} (${data.length}) correctly`, () => { <add> // process.stderr.write( <add> // `${c} x ${key.slice(0, 20)} (${data.length})\n` <add> // ); <add> const realData = cont(data, data.length * c); <add> const serialized = mw.serialize(realData, {}); <add> const newData = mw.deserialize(serialized, {}); <add> expect(newData.map(resolveLazy)).toEqual(realData.map(resolveLazy)); <add> }); <add> } <ide> } <ide> } <ide> }
1
PHP
PHP
add test class
5d7adf07d93e027797ad1c7848c66f42f522d6ab
<ide><path>lib/Cake/Test/TestApp/Model/PaginatorCustomPost.php <add><?php <add>namespace TestApp\Model; <add> <add>use Cake\TestSuite\Fixture\TestModel; <add> <add>/** <add> * PaginatorCustomPost class <add> * <add> * @package Cake.Test.Case.Controller.Component <add> */ <add>class PaginatorCustomPost extends TestModel { <add> <add>/** <add> * useTable property <add> * <add> * @var string <add> */ <add> public $useTable = 'posts'; <add> <add>/** <add> * belongsTo property <add> * <add> * @var string <add> */ <add> public $belongsTo = array('Author'); <add> <add>/** <add> * findMethods property <add> * <add> * @var array <add> */ <add> public $findMethods = array( <add> 'published' => true, <add> 'totals' => true, <add> 'totalsOperation' => true <add> ); <add> <add>/** <add> * _findPublished custom find <add> * <add> * @return array <add> */ <add> protected function _findPublished($state, $query, $results = array()) { <add> if ($state === 'before') { <add> $query['conditions']['published'] = 'Y'; <add> return $query; <add> } <add> return $results; <add> } <add> <add>/** <add> * _findTotals custom find <add> * <add> * @return array <add> */ <add> protected function _findTotals($state, $query, $results = array()) { <add> if ($state == 'before') { <add> $query['fields'] = array('author_id'); <add> $this->virtualFields['total_posts'] = "COUNT({$this->alias}.id)"; <add> $query['fields'][] = 'total_posts'; <add> $query['group'] = array('author_id'); <add> $query['order'] = array('author_id' => 'ASC'); <add> return $query; <add> } <add> $this->virtualFields = array(); <add> return $results; <add> } <add> <add>/** <add> * _findTotalsOperation custom find <add> * <add> * @return array <add> */ <add> protected function _findTotalsOperation($state, $query, $results = array()) { <add> if ($state == 'before') { <add> if (!empty($query['operation']) && $query['operation'] === 'count') { <add> unset($query['limit']); <add> $query['recursive'] = -1; <add> $query['fields'] = array('COUNT(DISTINCT author_id) AS count'); <add> return $query; <add> } <add> $query['recursive'] = 0; <add> $query['callbacks'] = 'before'; <add> $query['fields'] = array('author_id', 'Author.user'); <add> $this->virtualFields['total_posts'] = "COUNT({$this->alias}.id)"; <add> $query['fields'][] = 'total_posts'; <add> $query['group'] = array('author_id', 'Author.user'); <add> $query['order'] = array('author_id' => 'ASC'); <add> return $query; <add> } <add> $this->virtualFields = array(); <add> return $results; <add> } <add> <add>}
1
Text
Text
fix typos in docs (closes ) [ci skip]
0c74506c9cb79c76ca06ef04a4d44a042e1b3f7c
<ide><path>website/docs/usage/rule-based-matching.md <ide> class BadHTMLMerger(object): <ide> for match_id, start, end in matches: <ide> spans.append(doc[start:end]) <ide> with doc.retokenize() as retokenizer: <del> for span in hashtags: <add> for span in spans: <ide> retokenizer.merge(span) <ide> for token in span: <ide> token._.bad_html = True # Mark token as bad HTML <ide> for match_id, start, end in matches: <ide> if doc.vocab.strings[match_id] == "HASHTAG": <ide> hashtags.append(doc[start:end]) <ide> with doc.retokenize() as retokenizer: <del> for span in spans: <add> for span in hashtags: <ide> retokenizer.merge(span) <ide> for token in span: <ide> token._.is_hashtag = True
1
Java
Java
prevent a crash when no cursor drawable is set
1e18d907bfb8cc5f4f2e1a1ede0dd98aec40ab11
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/textinput/ReactTextInputManager.java <ide> private void setCursorColor(ReactEditText view, @Nullable Integer color) { <ide> cursorDrawableResField.setAccessible(true); <ide> int drawableResId = cursorDrawableResField.getInt(view); <ide> <add> // The view has no cursor drawable. <add> if (drawableResId == 0) { <add> return; <add> } <add> <ide> Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId); <ide> if (color != null) { <ide> drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
1
PHP
PHP
use assertsame() for array test
d4c37c3d1eaa450a6ce0649d7ac933076d1329ad
<ide><path>tests/Support/SupportCollectionTest.php <ide> public function testSortKeys() <ide> { <ide> $data = new Collection(['b' => 'dayle', 'a' => 'taylor']); <ide> <del> $this->assertEquals(['a' => 'taylor', 'b' => 'dayle'], $data->sortKeys()->all()); <add> $this->assertSame(['a' => 'taylor', 'b' => 'dayle'], $data->sortKeys()->all()); <ide> } <ide> <ide> public function testSortKeysDesc()
1
Javascript
Javascript
take the submodule into account in more instances
51831b332d3296db2c8b31bc0a1d8f01b9e0b4e7
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> // * `added` The {Number} of added lines. <ide> // * `deleted` The {Number} of deleted lines. <ide> getDiffStats (_path) { <del> return this.getRepo() <add> return this.getRepo(_path) <ide> .then(repo => Promise.all([repo, repo.getHeadCommit()])) <ide> .then(([repo, headCommit]) => Promise.all([repo, headCommit.getTree()])) <ide> .then(([repo, tree]) => { <ide> export default class GitRepositoryAsync { <ide> // * `newLines` The {Number} of lines in the new hunk <ide> getLineDiffs (_path, text) { <ide> let relativePath = null <del> return this.getRepo() <add> return this.getRepo(_path) <ide> .then(repo => { <ide> relativePath = this.relativize(_path, repo.workdir()) <ide> return repo.getHeadCommit() <ide> export default class GitRepositoryAsync { <ide> // Returns a {Promise} that resolves or rejects depending on whether the <ide> // method was successful. <ide> checkoutHead (_path) { <del> return this.getRepo() <add> return this.getRepo(_path) <ide> .then(repo => { <ide> const checkoutOptions = new Git.CheckoutOptions() <ide> checkoutOptions.paths = [this.relativize(_path, repo.workdir())]
1
Python
Python
use larger chunk size to speed up the tests
d31e3ee65768dbaa05bf85f85feb90c20f64749b
<ide><path>integration/storage/base.py <ide> def do_download(obj): <ide> <ide> def test_objects_stream_iterable(self): <ide> def do_upload(container, blob_name, content): <del> content = iter([content[i:i + 1] for i in range(len(content))]) <add> # NOTE: We originally used a chunk size of 1 which resulted in many requests and as <add> # such, very slow tests. To speed things up, we use a longer chunk size. <add> chunk_size = 1024 <add> # Ensure we still use multiple chunks and iterations <add> assert (len(content) / chunk_size) >= 500 <add> content = iter([content[i:i + chunk_size] for i in <add> range(0, len(content), chunk_size)]) <ide> return self.driver.upload_object_via_stream(content, container, blob_name) <ide> <ide> def do_download(obj):
1
PHP
PHP
add tap method to collection
c3219a630fbf9627538f37107c8427cdb60b949b
<ide><path>src/Illuminate/Support/Collection.php <ide> public function pipe(callable $callback) <ide> return $callback($this); <ide> } <ide> <add> /** <add> * Pass the collection to the given callback and return the current instance. <add> * <add> * @param callable $callback <add> * @return $this <add> */ <add> public function tap(callable $callback) <add> { <add> $callback(new static($this->items)); <add> return $this; <add> } <add> <ide> /** <ide> * Get and remove the last item from the collection. <ide> * <ide><path>tests/Support/SupportCollectionTest.php <ide> public function testHigherOrderPartition() <ide> <ide> $this->assertSame(['b' => ['free' => false]], $premium->toArray()); <ide> } <add> <add> public function testTap() <add> { <add> $collection = new Collection([1, 2, 3]); <add> <add> $fromTap = []; <add> $collection = $collection->tap(function ($collection) use (&$fromTap) { <add> $fromTap = $collection->slice(0, 1)->toArray(); <add> }); <add> <add> $this->assertSame([1], $fromTap); <add> $this->assertSame([1, 2, 3], $collection->toArray()); <add> } <ide> } <ide> <ide> class TestSupportCollectionHigherOrderItem
2
Javascript
Javascript
use spread function param in emit
d5fb78982a82285a7abe76c4bd4bb888e8f616c1
<ide><path>lib/events.js <ide> function emitMany(handler, isFn, self, args) { <ide> } <ide> } <ide> <del>EventEmitter.prototype.emit = function emit(type) { <del> var er, handler, len, args, i, events, domain; <del> var needDomainExit = false; <del> var doError = (type === 'error'); <add>EventEmitter.prototype.emit = function emit(type, ...args) { <add> let doError = (type === 'error'); <ide> <del> events = this._events; <add> const events = this._events; <ide> if (events !== undefined) <ide> doError = (doError && events.error === undefined); <ide> else if (!doError) <ide> return false; <ide> <del> domain = this.domain; <add> const domain = this.domain; <ide> <ide> // If there is no 'error' event listener then throw. <ide> if (doError) { <del> if (arguments.length > 1) <del> er = arguments[1]; <add> let er; <add> if (args.length > 0) <add> er = args[0]; <ide> if (domain !== null && domain !== undefined) { <ide> if (!er) { <ide> const errors = lazyErrors(); <ide> EventEmitter.prototype.emit = function emit(type) { <ide> return false; <ide> } <ide> <del> handler = events[type]; <add> const handler = events[type]; <ide> <ide> if (handler === undefined) <ide> return false; <ide> <add> let needDomainExit = false; <ide> if (domain !== null && domain !== undefined && this !== process) { <ide> domain.enter(); <ide> needDomainExit = true; <ide> } <ide> <del> var isFn = typeof handler === 'function'; <del> len = arguments.length; <del> switch (len) { <del> // fast cases <del> case 1: <add> const isFn = typeof handler === 'function'; <add> switch (args.length) { <add> case 0: <ide> emitNone(handler, isFn, this); <ide> break; <add> case 1: <add> emitOne(handler, isFn, this, args[0]); <add> break; <ide> case 2: <del> emitOne(handler, isFn, this, arguments[1]); <add> emitTwo(handler, isFn, this, args[0], args[1]); <ide> break; <ide> case 3: <del> emitTwo(handler, isFn, this, arguments[1], arguments[2]); <del> break; <del> case 4: <del> emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); <add> emitThree(handler, isFn, this, args[0], args[1], args[2]); <ide> break; <del> // slower <ide> default: <del> args = new Array(len - 1); <del> for (i = 1; i < len; i++) <del> args[i - 1] = arguments[i]; <ide> emitMany(handler, isFn, this, args); <ide> } <ide>
1
PHP
PHP
allow nested errors in json assertion
7161c83d4f4a28300eb5d1e739c25e3fd7ec5deb
<ide><path>src/Illuminate/Testing/TestResponse.php <ide> public function assertJsonValidationErrors($errors, $responseKey = 'errors') <ide> <ide> PHPUnit::assertNotEmpty($errors, 'No validation errors were provided.'); <ide> <del> $jsonErrors = $this->json()[$responseKey] ?? []; <add> $jsonErrors = Arr::get($this->json(), $responseKey) ?? []; <ide> <ide> $errorMessage = $jsonErrors <ide> ? 'Response has the following JSON validation errors:'. <ide><path>tests/Testing/TestResponseTest.php <ide> public function testAssertJsonValidationErrorsCustomErrorsName() <ide> $testResponse->assertJsonValidationErrors('foo', 'data'); <ide> } <ide> <add> public function testAssertJsonValidationErrorsCustomNestedErrorsName() <add> { <add> $data = [ <add> 'status' => 'ok', <add> 'data' => ['errors' => ['foo' => 'oops']], <add> ]; <add> <add> $testResponse = TestResponse::fromBaseResponse( <add> (new Response)->setContent(json_encode($data)) <add> ); <add> <add> $testResponse->assertJsonValidationErrors('foo', 'data.errors'); <add> } <add> <ide> public function testAssertJsonValidationErrorsCanFail() <ide> { <ide> $this->expectException(AssertionFailedError::class);
2
Javascript
Javascript
remove redundant $watchgroup param
7cfa79e98e54a7738722c0453432b70fbde1b6e7
<ide><path>src/ng/interpolate.js <ide> function $InterpolateProvider() { <ide> // all of these properties are undocumented for now <ide> exp: text, //just for compatibility with regular watchers created via $watch <ide> expressions: expressions, <del> $$watchDelegate: function(scope, listener, objectEquality) { <add> $$watchDelegate: function(scope, listener) { <ide> var lastValue; <ide> return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { <ide> var currValue = compute(values); <ide> if (isFunction(listener)) { <ide> listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); <ide> } <ide> lastValue = currValue; <del> }, objectEquality); <add> }); <ide> } <ide> }); <ide> }
1
Text
Text
use svg instead of png to get better image quality
b121d94369164391369cd02a559a7b64b482f59d
<ide><path>README.md <ide> Under the hood, Docker is built on the following components: <ide> Contributing to Docker <ide> ====================== <ide> <del>[![GoDoc](https://godoc.org/github.com/docker/docker?status.png)](https://godoc.org/github.com/docker/docker) <add>[![GoDoc](https://godoc.org/github.com/docker/docker?status.svg)](https://godoc.org/github.com/docker/docker) <ide> [![Jenkins Build Status](https://jenkins.dockerproject.com/job/Docker%20Master/badge/icon)](https://jenkins.dockerproject.com/job/Docker%20Master/) <ide> <ide> Want to hack on Docker? Awesome! We have [instructions to help you get
1
Python
Python
remove unreachable return statement
dde03ac855c6bb5fa3fd6db26030ab55f5f93e58
<ide><path>libcloud/compute/drivers/gandi.py <ide> def _resource_info(self, type, id): <ide> except Exception: <ide> e = sys.exc_info()[1] <ide> raise GandiException(1003, e) <del> return None <ide> <ide> def _node_info(self, id): <ide> return self._resource_info('vm', id)
1
Python
Python
parse url when adding query param
863bbe7684c44921b779a69c6b4c2ff16a223bd8
<ide><path>djangorestframework/templatetags/add_query_param.py <ide> <ide> def add_query_param(url, param): <ide> (key, sep, val) = param.partition('=') <del> return unicode(URLObject(url) & (key, val)) <add> return unicode(URLObject.parse(url) & (key, val)) <ide> <ide> <ide> register.filter('add_query_param', add_query_param)
1
Ruby
Ruby
add declared_directly field for runtime deps
a5cb621fb86cdb87761a8113ffb17d72a0f6d3ae
<ide><path>Library/Homebrew/formula_installer.rb <ide> def finish <ide> tab = Tab.for_keg(keg) <ide> Tab.clear_cache <ide> f_runtime_deps = formula.runtime_dependencies(read_from_tab: false) <del> tab.runtime_dependencies = Tab.runtime_deps_hash(f_runtime_deps) <add> tab.runtime_dependencies = Tab.runtime_deps_hash(formula, f_runtime_deps) <ide> tab.write <ide> <ide> # let's reset Utils::Git.available? if we just installed git <ide><path>Library/Homebrew/tab.rb <ide> def self.create(formula, compiler, stdlib) <ide> "compiler" => compiler, <ide> "stdlib" => stdlib, <ide> "aliases" => formula.aliases, <del> "runtime_dependencies" => Tab.runtime_deps_hash(runtime_deps), <add> "runtime_dependencies" => Tab.runtime_deps_hash(formula, runtime_deps), <ide> "arch" => Hardware::CPU.arch, <ide> "source" => { <ide> "path" => formula.specified_path.to_s, <ide> def self.empty <ide> new(attributes) <ide> end <ide> <del> def self.runtime_deps_hash(deps) <add> def self.runtime_deps_hash(formula, deps) <ide> deps.map do |dep| <ide> f = dep.to_formula <del> { "full_name" => f.full_name, "version" => f.version.to_s } <add> { <add> "full_name" => f.full_name, <add> "version" => f.version.to_s, <add> "declared_directly" => formula.deps.include?(dep), <add> } <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/tab_spec.rb <ide> <ide> specify "::runtime_deps_hash" do <ide> runtime_deps = [Dependency.new("foo")] <del> stub_formula_loader formula("foo") { url "foo-1.0" } <del> runtime_deps_hash = described_class.runtime_deps_hash(runtime_deps) <add> foo = formula("foo") { url "foo-1.0" } <add> stub_formula_loader foo <add> runtime_deps_hash = described_class.runtime_deps_hash(foo, runtime_deps) <ide> tab = described_class.new <ide> tab.homebrew_version = "1.1.6" <ide> tab.runtime_dependencies = runtime_deps_hash <ide> expect(tab.runtime_dependencies).to eql( <del> [{ "full_name" => "foo", "version" => "1.0" }], <add> [{ "full_name" => "foo", "version" => "1.0", "declared_directly" => false }], <ide> ) <ide> end <ide> <ide> tab = described_class.create(f, compiler, stdlib) <ide> <ide> runtime_dependencies = [ <del> { "full_name" => "bar", "version" => "2.0" }, <del> { "full_name" => "user/repo/from_tap", "version" => "1.0" }, <add> { "full_name" => "bar", "version" => "2.0", "declared_directly" => true }, <add> { "full_name" => "user/repo/from_tap", "version" => "1.0", "declared_directly" => true }, <ide> ] <ide> expect(tab.runtime_dependencies).to eq(runtime_dependencies) <ide>
3
Python
Python
set version to v3.0.0a10
001546c19e2616cf9740cb78367e4d9b74e1366b
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy-nightly" <del>__version__ = "3.0.0a9" <add>__version__ = "3.0.0a10" <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
Python
Python
make python2 *.npy files readable in python3
8f068b7866a2959392fae2a15c1a5a19ff79bae9
<ide><path>numpy/lib/format.py <ide> import io <ide> import warnings <ide> from numpy.lib.utils import safe_eval <del>from numpy.compat import asbytes, isfileobj, long, basestring <add>from numpy.compat import asbytes, asstr, isfileobj, long, basestring <ide> <ide> if sys.version_info[0] >= 3: <ide> import pickle <ide> def read_array_header_2_0(fp): <ide> """ <ide> _read_array_header(fp, version=(2, 0)) <ide> <add> <add>def _filter_header(s): <add> """Clean up 'L' in npz header ints. <add> <add> Cleans up the 'L' in strings representing integers. Needed to allow npz <add> headers produced in Python2 to be read in Python3. <add> <add> Parameters <add> ---------- <add> s : byte string <add> Npy file header. <add> <add> Returns <add> ------- <add> header : str <add> Cleaned up header. <add> <add> """ <add> import tokenize <add> if sys.version_info[0] >= 3: <add> from io import StringIO <add> else: <add> from StringIO import StringIO <add> <add> tokens = [] <add> last_token_was_number = False <add> for token in tokenize.generate_tokens(StringIO(asstr(s)).read): <add> token_type = token[0] <add> token_string = token[1] <add> if (last_token_was_number and <add> token_type == tokenize.NAME and <add> token_string == "L"): <add> continue <add> else: <add> tokens.append(token) <add> last_token_was_number = (token_type == tokenize.NUMBER) <add> return tokenize.untokenize(tokens) <add> <add> <ide> def _read_array_header(fp, version): <ide> """ <ide> see read_array_header_1_0 <ide> def _read_array_header(fp, version): <ide> # "shape" : tuple of int <ide> # "fortran_order" : bool <ide> # "descr" : dtype.descr <add> header = _filter_header(header) <ide> try: <ide> d = safe_eval(header) <ide> except SyntaxError as e:
1
Javascript
Javascript
fix onlayout support in <textinput>
92926f9858c0b60cf9f2e51cb8f25f2e1501c9c1
<ide><path>Libraries/Components/TextInput/TextInput.js <ide> var TextInput = React.createClass({ <ide> <ide> return ( <ide> <TouchableWithoutFeedback <add> onLayout={props.onLayout} <ide> onPress={this._onPress} <ide> rejectResponderTermination={true} <ide> accessible={props.accessible}
1
Javascript
Javascript
fix jshint issue
c9f42d7d43e6d63a522219199dbcc294416c6f1f
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js <ide> import assign from 'ember-metal/assign'; <ide> import { assert, warn } from 'ember-metal/debug'; <ide> import buildComponentTemplate from 'ember-htmlbars/system/build-component-template'; <ide> import { get } from 'ember-metal/property_get'; <del>import { set } from 'ember-metal/property_set'; <ide> import setProperties from 'ember-metal/set_properties'; <ide> import View from 'ember-views/views/view'; <ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
1
Text
Text
move ofrobots to collaborator emeritus
c6d9d8ae606dcb58b33b8363bee060ee1ef04b5e
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Brian White** &lt;mscdex@mscdex.net&gt; <ide> * [MylesBorins](https://github.com/MylesBorins) - <ide> **Myles Borins** &lt;myles.borins@gmail.com&gt; (he/him) <del>* [ofrobots](https://github.com/ofrobots) - <del>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; (he/him) <ide> * [oyyd](https://github.com/oyyd) - <ide> **Ouyang Yadong** &lt;oyydoibh@gmail.com&gt; (he/him) <ide> * [panva](https://github.com/panva) - <ide> For information about the governance of the Node.js project, see <ide> **Chen Gang** &lt;gangc.cxy@foxmail.com&gt; <ide> * [not-an-aardvark](https://github.com/not-an-aardvark) - <ide> **Teddy Katz** &lt;teddy.katz@gmail.com&gt; (he/him) <add>* [ofrobots](https://github.com/ofrobots) - <add>**Ali Ijaz Sheikh** &lt;ofrobots@google.com&gt; (he/him) <ide> * [Olegas](https://github.com/Olegas) - <ide> **Oleg Elifantiev** &lt;oleg@elifantiev.ru&gt; <ide> * [orangemocha](https://github.com/orangemocha) -
1
PHP
PHP
apply fixes from styleci
8842846e815498f982e83ba44c370143522e0d37
<ide><path>tests/Integration/Http/ThrottleRequestsTest.php <ide> public function test_lock_opens_immediately_after_decay() <ide> Carbon::now()->addSeconds(58) <ide> ); <ide> <del> try{ <add> try { <ide> $response = $this->withoutExceptionHandling()->get('/'); <del> }catch(\Throwable $e){ <add> } catch (\Throwable $e) { <ide> $this->assertEquals(429, $e->getStatusCode()); <ide> $this->assertEquals(2, $e->getHeaders()['X-RateLimit-Limit']); <ide> $this->assertEquals(0, $e->getHeaders()['X-RateLimit-Remaining']);
1
PHP
PHP
add @link to file and folder utilities
3248e34819937ba0082b675610a68a2c22087169
<ide><path>lib/Cake/Utility/File.php <ide> class File { <ide> * @param string $path Path to file <ide> * @param boolean $create Create file if it does not exist (if true) <ide> * @param integer $mode Mode to apply to the folder holding the file <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File <ide> */ <ide> public function __construct($path, $create = false, $mode = 0755) { <ide> $this->Folder = new Folder(dirname($path), $create, $mode); <ide> public function __destruct() { <ide> * Creates the File. <ide> * <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::create <ide> */ <ide> public function create() { <ide> $dir = $this->Folder->pwd(); <ide> public function create() { <ide> * @param string $mode A valid 'fopen' mode string (r|w|a ...) <ide> * @param boolean $force If true then the file will be re-opened even if its already opened, otherwise it won't <ide> * @return boolean True on success, false on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::open <ide> */ <ide> public function open($mode = 'r', $force = false) { <ide> if (!$force && is_resource($this->handle)) { <ide> public function open($mode = 'r', $force = false) { <ide> * @param string $mode A `fread` compatible mode. <ide> * @param boolean $force If true then the file will be re-opened even if its already opened, otherwise it won't <ide> * @return mixed string on success, false on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::read <ide> */ <ide> public function read($bytes = false, $mode = 'rb', $force = false) { <ide> if ($bytes === false && $this->lock === null) { <ide> public function read($bytes = false, $mode = 'rb', $force = false) { <ide> * @param mixed $offset The $offset in bytes to seek. If set to false then the current offset is returned. <ide> * @param integer $seek PHP Constant SEEK_SET | SEEK_CUR | SEEK_END determining what the $offset is relative to <ide> * @return mixed True on success, false on failure (set mode), false on failure or integer offset on success (get mode) <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::offset <ide> */ <ide> public function offset($offset = false, $seek = SEEK_SET) { <ide> if ($offset === false) { <ide> public function offset($offset = false, $seek = SEEK_SET) { <ide> * @param string $data Data to prepare for writing. <ide> * @param boolean $forceWindows <ide> * @return string The with converted line endings. <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::prepare <ide> */ <ide> public static function prepare($data, $forceWindows = false) { <ide> $lineBreak = "\n"; <ide> public static function prepare($data, $forceWindows = false) { <ide> * @param string $mode Mode of writing. {@link http://php.net/fwrite See fwrite()}. <ide> * @param string $force force the file to open <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::write <ide> */ <ide> public function write($data, $mode = 'w', $force = false) { <ide> $success = false; <ide> public function write($data, $mode = 'w', $force = false) { <ide> * @param string $data Data to write <ide> * @param string $force force the file to open <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::append <ide> */ <ide> public function append($data, $force = false) { <ide> return $this->write($data, 'a', $force); <ide> public function append($data, $force = false) { <ide> * Closes the current file if it is opened. <ide> * <ide> * @return boolean True if closing was successful or file was already closed, otherwise false <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::close <ide> */ <ide> public function close() { <ide> if (!is_resource($this->handle)) { <ide> public function close() { <ide> * Deletes the File. <ide> * <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::delete <ide> */ <ide> public function delete() { <ide> clearstatcache(); <ide> public function delete() { <ide> * Returns the File info. <ide> * <ide> * @return string The File extension <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::info <ide> */ <ide> public function info() { <ide> if ($this->info == null) { <ide> public function info() { <ide> * Returns the File extension. <ide> * <ide> * @return string The File extension <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::ext <ide> */ <ide> public function ext() { <ide> if ($this->info == null) { <ide> public function ext() { <ide> * Returns the File name without extension. <ide> * <ide> * @return string The File name without extension. <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::name <ide> */ <ide> public function name() { <ide> if ($this->info == null) { <ide> public function name() { <ide> * @param string $name The name of the file to make safe if different from $this->name <ide> * @param string $ext The name of the extension to make safe if different from $this->ext <ide> * @return string $ext the extension of the file <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::safe <ide> */ <ide> public function safe($name = null, $ext = null) { <ide> if (!$name) { <ide> public function safe($name = null, $ext = null) { <ide> * <ide> * @param mixed $maxsize in MB or true to force <ide> * @return string md5 Checksum {@link http://php.net/md5_file See md5_file()} <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::md5 <ide> */ <ide> public function md5($maxsize = 5) { <ide> if ($maxsize === true) { <ide> public function md5($maxsize = 5) { <ide> * Returns the full path of the File. <ide> * <ide> * @return string Full path to file <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::pwd <ide> */ <ide> public function pwd() { <ide> if (is_null($this->path)) { <ide> public function pwd() { <ide> * Returns true if the File exists. <ide> * <ide> * @return boolean true if it exists, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::exists <ide> */ <ide> public function exists() { <ide> return (file_exists($this->path) && is_file($this->path)); <ide> public function exists() { <ide> * Returns the "chmod" (permissions) of the File. <ide> * <ide> * @return string Permissions for the file <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::perms <ide> */ <ide> public function perms() { <ide> if ($this->exists()) { <ide> public function perms() { <ide> * Returns the Filesize <ide> * <ide> * @return integer size of the file in bytes, or false in case of an error <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::size <ide> */ <ide> public function size() { <ide> if ($this->exists()) { <ide> public function size() { <ide> * Returns true if the File is writable. <ide> * <ide> * @return boolean true if its writable, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::writable <ide> */ <ide> public function writable() { <ide> return is_writable($this->path); <ide> public function writable() { <ide> * Returns true if the File is executable. <ide> * <ide> * @return boolean true if its executable, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::executable <ide> */ <ide> public function executable() { <ide> return is_executable($this->path); <ide> public function executable() { <ide> * Returns true if the File is readable. <ide> * <ide> * @return boolean true if file is readable, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::readable <ide> */ <ide> public function readable() { <ide> return is_readable($this->path); <ide> public function readable() { <ide> * Returns the File's owner. <ide> * <ide> * @return integer the Fileowner <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::owner <ide> */ <ide> public function owner() { <ide> if ($this->exists()) { <ide> public function owner() { <ide> * Returns the File's group. <ide> * <ide> * @return integer the Filegroup <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::group <ide> */ <ide> public function group() { <ide> if ($this->exists()) { <ide> public function group() { <ide> * Returns last access time. <ide> * <ide> * @return integer timestamp Timestamp of last access time <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::lastAccess <ide> */ <ide> public function lastAccess() { <ide> if ($this->exists()) { <ide> public function lastAccess() { <ide> * Returns last modified time. <ide> * <ide> * @return integer timestamp Timestamp of last modification <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::lastChange <ide> */ <ide> public function lastChange() { <ide> if ($this->exists()) { <ide> public function lastChange() { <ide> * Returns the current folder. <ide> * <ide> * @return Folder Current folder <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::Folder <ide> */ <ide> public function &Folder() { <ide> return $this->Folder; <ide> public function &Folder() { <ide> * <ide> * @param string $dest destination for the copy <ide> * @param boolean $overwrite Overwrite $dest if exists <del> * @return boolean Succes <add> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#File::copy <ide> */ <ide> public function copy($dest, $overwrite = true) { <ide> if (!$this->exists() || is_file($dest) && !$overwrite) { <ide><path>lib/Cake/Utility/Folder.php <ide> class Folder { <ide> * @param string $path Path to folder <ide> * @param boolean $create Create folder if not found <ide> * @param mixed $mode Mode (CHMOD) to apply to created folder, false to ignore <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder <ide> */ <ide> public function __construct($path = false, $create = false, $mode = false) { <ide> if (empty($path)) { <ide> public function __construct($path = false, $create = false, $mode = false) { <ide> * Return current path. <ide> * <ide> * @return string Current path <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::pwd <ide> */ <ide> public function pwd() { <ide> return $this->path; <ide> public function pwd() { <ide> * <ide> * @param string $path Path to the directory to change to <ide> * @return string The new path. Returns false on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::cd <ide> */ <ide> public function cd($path) { <ide> $path = $this->realpath($path); <ide> public function cd($path) { <ide> * @param mixed $exceptions Either an array or boolean true will not grab dot files <ide> * @param boolean $fullPath True returns the full path <ide> * @return mixed Contents of current directory as an array, an empty array on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::read <ide> */ <ide> public function read($sort = true, $exceptions = false, $fullPath = false) { <ide> $dirs = $files = array(); <ide> public function read($sort = true, $exceptions = false, $fullPath = false) { <ide> * @param string $regexpPattern Preg_match pattern (Defaults to: .*) <ide> * @param boolean $sort Whether results should be sorted. <ide> * @return array Files that match given pattern <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::find <ide> */ <ide> public function find($regexpPattern = '.*', $sort = false) { <ide> list($dirs, $files) = $this->read($sort); <ide> public function find($regexpPattern = '.*', $sort = false) { <ide> * @param string $pattern Preg_match pattern (Defaults to: .*) <ide> * @param boolean $sort Whether results should be sorted. <ide> * @return array Files matching $pattern <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::findRecursive <ide> */ <ide> public function findRecursive($pattern = '.*', $sort = false) { <ide> if (!$this->pwd()) { <ide> protected function _findRecursive($pattern, $sort = false) { <ide> * <ide> * @param string $path Path to check <ide> * @return boolean true if windows path, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isWindowsPath <ide> */ <ide> public static function isWindowsPath($path) { <ide> return (preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\'); <ide> public static function isWindowsPath($path) { <ide> * <ide> * @param string $path Path to check <ide> * @return boolean true if path is absolute. <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isAbsolute <ide> */ <ide> public static function isAbsolute($path) { <ide> return !empty($path) && ($path[0] === '/' || preg_match('/^[A-Z]:\\\\/i', $path) || substr($path, 0, 2) == '\\\\'); <ide> public static function isAbsolute($path) { <ide> * <ide> * @param string $path Path to check <ide> * @return string Set of slashes ("\\" or "/") <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::normalizePath <ide> */ <ide> public static function normalizePath($path) { <ide> return Folder::correctSlashFor($path); <ide> public static function normalizePath($path) { <ide> * <ide> * @param string $path Path to check <ide> * @return string Set of slashes ("\\" or "/") <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::correctSlashFor <ide> */ <ide> public static function correctSlashFor($path) { <ide> return (Folder::isWindowsPath($path)) ? '\\' : '/'; <ide> public static function correctSlashFor($path) { <ide> * <ide> * @param string $path Path to check <ide> * @return string Path with ending slash <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::slashTerm <ide> */ <ide> public static function slashTerm($path) { <ide> if (Folder::isSlashTerm($path)) { <ide> public static function slashTerm($path) { <ide> * @param string $path Path <ide> * @param string $element Element to and at end of path <ide> * @return string Combined path <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::addPathElement <ide> */ <ide> public static function addPathElement($path, $element) { <ide> return rtrim($path, DS) . DS . $element; <ide> public static function addPathElement($path, $element) { <ide> * <ide> * @param string $path The path to check. <ide> * @return boolean <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::inCakePath <ide> */ <ide> public function inCakePath($path = '') { <ide> $dir = substr(Folder::slashTerm(ROOT), 0, -1); <ide> public function inCakePath($path = '') { <ide> * @param string $path The path to check that the current pwd() resides with in. <ide> * @param boolean $reverse <ide> * @return boolean <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::inPath <ide> */ <ide> public function inPath($path = '', $reverse = false) { <ide> $dir = Folder::slashTerm($path); <ide> public function inPath($path = '', $reverse = false) { <ide> * @param boolean $recursive chmod recursively, set to false to only change the current directory. <ide> * @param array $exceptions array of files, directories to skip <ide> * @return boolean Returns TRUE on success, FALSE on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::chmod <ide> */ <ide> public function chmod($path, $mode = false, $recursive = true, $exceptions = array()) { <ide> if (!$mode) { <ide> public function chmod($path, $mode = false, $recursive = true, $exceptions = arr <ide> * @param mixed $exceptions Array of files to exclude, defaults to excluding hidden files. <ide> * @param string $type either file or dir. null returns both files and directories <ide> * @return mixed array of nested directories and files in each directory <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::tree <ide> */ <ide> public function tree($path = null, $exceptions = true, $type = null) { <ide> if ($path == null) { <ide> protected function _tree($path, $exceptions) { <ide> * @param string $pathname The directory structure to create <ide> * @param integer $mode octal value 0755 <ide> * @return boolean Returns TRUE on success, FALSE on failure <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::create <ide> */ <ide> public function create($pathname, $mode = false) { <ide> if (is_dir($pathname) || empty($pathname)) { <ide> public function create($pathname, $mode = false) { <ide> * Returns the size in bytes of this Folder and its contents. <ide> * <ide> * @return integer size in bytes of current folder <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::dirsize <ide> */ <ide> public function dirsize() { <ide> $size = 0; <ide> public function dirsize() { <ide> * <ide> * @param string $path Path of directory to delete <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::delete <ide> */ <ide> public function delete($path = null) { <ide> if (!$path) { <ide> public function delete($path = null) { <ide> * <ide> * @param mixed $options Either an array of options (see above) or a string of the destination directory. <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::copy <ide> */ <ide> public function copy($options = array()) { <ide> if (!$this->pwd()) { <ide> public function copy($options = array()) { <ide> * <ide> * @param array $options (to, from, chmod, skip) <ide> * @return boolean Success <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::move <ide> */ <ide> public function move($options) { <ide> $to = null; <ide> public function move($options) { <ide> * get messages from latest method <ide> * <ide> * @return array <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::messages <ide> */ <ide> public function messages() { <ide> return $this->_messages; <ide> public function messages() { <ide> * get error from latest method <ide> * <ide> * @return array <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::errors <ide> */ <ide> public function errors() { <ide> return $this->_errors; <ide> public function errors() { <ide> * <ide> * @param string $path Path to resolve <ide> * @return string The resolved path <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::realpath <ide> */ <ide> public function realpath($path) { <ide> $path = str_replace('/', DS, trim($path)); <ide> public function realpath($path) { <ide> * <ide> * @param string $path Path to check <ide> * @return boolean true if path ends with slash, false otherwise <add> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/file-folder.html#Folder::isSlashTerm <ide> */ <ide> public static function isSlashTerm($path) { <ide> $lastChar = $path[strlen($path) - 1];
2
PHP
PHP
add dummy code in bulk() function
51329309c18d47dcc0e245c25e2173629dca04c7
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php <ide> public function pop($queue = null) <ide> */ <ide> public function bulk($jobs, $data = '', $queue = null) <ide> { <del> // <add> foreach ($this->jobs as $job) { <add> $this->jobs[get_class($job)][] = [ <add> 'job' => $job, <add> 'queue' => $queue, <add> ]; <add> } <ide> } <ide> <ide> /**
1
Ruby
Ruby
handle recursive installs
0578ba0f429708773489fdd8f9647c2712c7025c
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def install_p(src, new_basename) <ide> src = Pathname(src) <ide> dst = join(new_basename) <ide> dst = yield(src, dst) if block_given? <add> return unless dst <ide> <ide> mkpath <ide> <ide><path>Library/Homebrew/install_renamed.rb <ide> module InstallRenamed <ide> def install_p(_, new_basename) <ide> super do |src, dst| <ide> if src.directory? <del> dst <add> dst.install(src.children) <add> next <ide> else <ide> append_default_if_different(src, dst) <ide> end <ide><path>Library/Homebrew/test/test_pathname.rb <ide> def test_install_renamed_directory <ide> assert_equal "a", File.read(@dst+@src.basename+@file.basename) <ide> end <ide> <add> def test_install_renamed_directory_recursive <add> @dst.extend(InstallRenamed) <add> (@dst+@dir.basename).mkpath <add> (@dst+@dir.basename+"another_file").write "a" <add> @dir.mkpath <add> (@dir+"another_file").write "b" <add> @dst.install @dir <add> assert_equal "b", File.read(@dst+@dir.basename+"another_file.default") <add> end <add> <ide> def test_cp_path_sub_file <ide> @file.write "a" <ide> @file.cp_path_sub @src, @dst
3
Python
Python
fix merge conflict
0e62ae4eaa8807b7e0e27e73ca1ff6be05e8b715
<ide><path>examples/cifar10_cnn.py <ide> model.add(Activation('relu')) <ide> model.add(Convolution2D(nb_filters[0], nb_filters[0], nb_conv[0], nb_conv[0])) <ide> model.add(Activation('relu')) <del>model.add(MaxPooling2D(poolsize=(nb_pool[0], nb_pool[0]))) <add>model.add(MaxPooling2D(pool_size=(nb_pool[0], nb_pool[0]))) <ide> model.add(Dropout(0.25)) <ide> <ide> model.add(Convolution2D(nb_filters[1], nb_filters[0], nb_conv[0], nb_conv[0], border_mode='full')) <ide> model.add(Activation('relu')) <ide> model.add(Convolution2D(nb_filters[1], nb_filters[1], nb_conv[1], nb_conv[1])) <ide> model.add(Activation('relu')) <del>model.add(MaxPooling2D(poolsize=(nb_pool[1], nb_pool[1]))) <add>model.add(MaxPooling2D(pool_size=(nb_pool[1], nb_pool[1]))) <ide> model.add(Dropout(0.25)) <ide> <ide> model.add(Flatten()) <ide><path>examples/mnist_cnn.py <ide> model.add(Activation('relu')) <ide> model.add(Convolution2D(nb_filters, nb_filters, nb_conv, nb_conv)) <ide> model.add(Activation('relu')) <del>model.add(MaxPooling2D(poolsize=(nb_pool, nb_pool))) <add>model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool))) <ide> model.add(Dropout(0.25)) <ide> <ide> model.add(Flatten()) <ide><path>keras/layers/convolutional.py <ide> def get_config(self): <ide> <ide> <ide> class MaxPooling1D(Layer): <del> def __init__(self, pool_length=2, stride=1, ignore_border=True): <add> def __init__(self, pool_length=2, stride=None, ignore_border=True): <ide> super(MaxPooling1D, self).__init__() <del> if type(stride) is not int or not stride: <del> raise Exception('"stride" argument in MaxPooling1D should be an int > 0.') <add> if stride is None: <add> stride = pool_length <ide> self.pool_length = pool_length <ide> self.stride = stride <ide> self.st = (self.stride, 1) <ide> def get_config(self): <ide> <ide> <ide> class MaxPooling2D(Layer): <del> def __init__(self, pool_size=(2, 2), stride=(1, 1), ignore_border=True): <add> def __init__(self, pool_size=(2, 2), stride=None, ignore_border=True): <ide> super(MaxPooling2D, self).__init__() <ide> self.input = T.tensor4() <ide> self.pool_size = tuple(pool_size) <add> if stride is None: <add> stride = self.pool_size <ide> self.stride = tuple(stride) <ide> self.ignore_border = ignore_border <ide>
3
Python
Python
add node_name attribute to kubernetespod
0f56fae02edff19b8350f79b8bf61b5f21940674
<ide><path>libcloud/container/drivers/kubernetes.py <ide> <ide> <ide> class KubernetesPod(object): <del> def __init__( <del> self, id, name, containers, namespace, state, ip_addresses, created_at <del> ): <add> def __init__(self, id, name, containers, namespace, state, ip_addresses, <add> created_at, node_name): <ide> """ <ide> A Kubernetes pod <ide> """ <ide> def __init__( <ide> self.state = state <ide> self.ip_addresses = ip_addresses <ide> self.created_at = created_at <add> self.node_name = node_name <ide> <ide> <ide> class KubernetesContainerDriver(KubernetesDriverMixin, ContainerDriver): <ide> def _to_pod(self, data): <ide> ip_addresses=ip_addresses, <ide> containers=containers, <ide> created_at=created_at, <del> ) <add> node_name=data['spec'].get('nodeName')) <ide> <ide> def _to_container(self, data, container_status, pod_data): <ide> """
1
Text
Text
fix typo in requests.md
30e6f32f6fbe20eafe949017cd62aed5d15529d5
<ide><path>docs/api-guide/requests.md <ide> For clarity inside your code, we recommend using `request.query_params` instead <ide> <ide> ## .DATA and .FILES <ide> <del>The old-style version 2.x `request.data` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute. <add>The old-style version 2.x `request.DATA` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute. <ide> <ide> ## .QUERY_PARAMS <ide>
1
Text
Text
draft pretrain usage
6efb7688a65faae489de33073c1c40b11ec4f432
<ide><path>website/docs/usage/embeddings-transformers.md <ide> def MyCustomVectors( <ide> <ide> ## Pretraining {#pretraining} <ide> <del><Infobox title="This section is still under construction" emoji="🚧" variant="warning"> <del></Infobox> <add>The `spacy pretrain` command lets you initialize your models with information <add>from raw text. Without pretraining, the models for your components will usually <add>be initialized randomly. The idea behind pretraining is simple: random probably <add>isn't optimal, so if we have some text to learn from, we can probably find <add>a way to get the model off to a better start. The impact of `spacy pretrain` varies, <add>but it will usually be worth trying if you're not using a transformer model and <add>you have relatively little training data (for instance, fewer than 5,000 sentence). <add>A good rule of thumb is that pretraining will generally give you a similar accuracy <add>improvement to using word vectors in your model. If word vectors have given you <add>a 10% error reduction, the `spacy pretrain` command might give you another 10%, <add>for a 20% error reduction in total. <add> <add>The `spacy pretrain` command will take a specific subnetwork within one of your <add>components, and add additional layers to build a network for a temporary task, <add>that forces the model to learn something about sentence structure and word <add>cooccurrence statistics. Pretraining produces a binary weights file that can be <add>loaded back in at the start of training. The weights file specifies an initial <add>set of weights. Training then proceeds as normal. <add> <add>You can only pretrain one subnetwork from your pipeline at a time, and the subnetwork <add>must be typed `Model[List[Doc], List[Floats2d]]` (i.e., it has to be a "tok2vec" layer). <add>The most common workflow is to use the `Tok2Vec` component to create a shared <add>token-to-vector layer for several components of your pipeline, and apply <add>pretraining to its whole model. <add> <add>The `spacy pretrain` command is configured using the `[pretraining]` section of <add>your config file. The `pretraining.component` and `pretraining.layer` settings <add>tell spaCy how to find the subnetwork to pretrain. The `pretraining.layer` <add>setting should be either the empty string (to use the whole model), or a <add>[node reference](https://thinc.ai/docs/usage-models#model-state). Most of spaCy's <add>built-in model architectures have a reference named `"tok2vec"` that will refer <add>to the right layer. <ide> <del><!-- <del>- explain general concept and idea (short!) <del>- present it as a separate lightweight mechanism for pretraining the tok2vec <del> layer <del>- advantages (could also be pros/cons table) <del>- explain how it generates a separate file (!) and how it depends on the same <del> vectors <del>--> <add>```ini <add># Pretrain nlp.get_pipe("tok2vec").model <add>[pretraining] <add>component = "tok2vec" <add>layer = "" <add> <add>[pretraining] <add># Pretrain nlp.get_pipe("textcat").model.get_ref("tok2vec") <add>component = "textcat" <add>layer = "tok2vec" <add>``` <add> <add>two pretraining objectives are available, both of which are variants of the cloze <add>task Devlin et al (2018) introduced for BERT. <add> <add>* The *characters* objective asks the model to predict some number of leading and <add> trailing UTF-8 bytes for the words. For instance, setting `n_characters=2`, the <add> model will try to predict the first two and last two characters of the word. <add> <add>* The *vectors* objective asks the model to predict the word's vector, from <add> a static embeddings table. This requires a word vectors model to be trained <add> and loaded. The vectors objective can optimize either a cosine or an L2 loss. <add> We've generally found cosine loss to perform better. <add> <add>These pretraining objectives use a trick that we term _language modelling with <add>approximate outputs (LMAO)_. The motivation for the trick is that predicting <add>an exact word ID introduces a lot of incidental complexity. You need a large <add>output layer, and even then, the vocabulary is too large, which motivates <add>tokenization schemes that do not align to actual word boundaries. At the end of <add>training, the output layer will be thrown away regardless: we just want a task <add>that forces the network to model something about word cooccurrence statistics. <add>Predicting leading and trailing characters does that more than adequately, as <add>the exact word sequence could be recovered with high accuracy if the initial <add>and trailing characters are predicted accurately. With the vectors objective, <add>the pretraining is use the embedding space learned by an algorithm such as <add>GloVe or word2vec, allowing the model to focus on the contextual <add>modelling we actual care about. <add> <add>The `[pretraining]` section has several configuration subsections that are <add>familiar from the training block: the `[pretraining.batcher]`, <add>[pretraining.optimizer]` and `[pretraining.corpus]` all work the same way and <add>expect the same types of objects, although for pretraining your corpus does not <add>need to have any annotations, so you will often use a different reader, such as <add>`spacy.training.JsonlReader1`. <ide> <ide> > #### Raw text format <ide> >
1
Ruby
Ruby
resolve view paths correctly on cygwin
5998dd7bb84c76f4c8a272a71b588e2331989b4b
<ide><path>actionpack/lib/action_view/template/resolver.rb <ide> def build_path(name, details, prefix, partial) <ide> end <ide> <ide> def query(path, exts) <del> query = "#{@path}/#{path}" <add> query = File.join(@path, path) <ide> exts.each do |ext| <ide> query << '{' << ext.map {|e| e && ".#{e}" }.join(',') << '}' <ide> end
1
Python
Python
remove unused imports
8a896ce937058533601a4c94495f45d7cca17173
<ide><path>libcloud/compute/drivers/opsource.py <ide> Opsource Driver <ide> """ <ide> import base64 <del>import socket <ide> from xml.etree import ElementTree as ET <del>from xml.parsers.expat import ExpatError <ide> <ide> from libcloud.utils import fixxpath, findtext, findall <ide> from libcloud.common.base import ConnectionUserAndKey, Response
1
PHP
PHP
fix formatting and spacing
e47c09bc43f3bed5e02c783c165bcde0a1778468
<ide><path>src/ORM/Marshaller.php <ide> use Cake\Database\Type; <ide> use Cake\Datasource\EntityInterface; <ide> use Cake\Datasource\InvalidPropertyInterface; <del>use Cake\ORM\Exception\MissingAssociationException; <ide> use RuntimeException; <ide> <ide> /** <ide> protected function _buildPropertyMap($options) <ide> $map[$assoc->property()] = ['association' => $assoc] + $nested + ['associated' => []]; <ide> continue; <ide> } <del> if (substr($key, 0, 1) !== "_") { // if $key is not a special underscored field eg _ids or _joinData <del> throw new \InvalidArgumentException(vsprintf("%s is not associated with %s",[$this->_table->alias(), $key])); <add> // If the key is not a special field like _ids or _joinData <add> // it is a missing association that we should error on. <add> if (substr($key, 0, 1) !== "_") { <add> throw new \InvalidArgumentException(sprintf( <add> "'%s' is not associated with '%s'", <add> $this->_table->alias(), <add> $key <add> )); <ide> } <ide> } <ide> return $map; <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testManyAssociations() <ide> } <ide> <ide> /** <del> * Test if exceptin is raised when called with [associated=>NonExistingAssociation] <del> * Previously such association has been simply ignored <add> * Test if exception is raised when called with [associated => NonExistingAssociation] <add> * Previously such association were simply ignored <add> * <ide> * @expectedException \InvalidArgumentException <ide> * @return void <ide> */ <ide> public function testManyInvalidAssociation() <ide> ], <ide> ]; <ide> $marshall = new Marshaller($this->comments); <del> $marshall->many($data, ['associated' => ['Users','People']]); <add> $marshall->many($data, ['associated' => ['Users', 'People']]); <ide> } <ide> <ide> /**
2
PHP
PHP
remove previous url stuff from session. bad idea
da39766b20b915a6b554cbf6392f6a9c9c8f1a90
<ide><path>src/Illuminate/Routing/Redirector.php <ide> public function home($status = 302) <ide> */ <ide> public function back($status = 302, $headers = array()) <ide> { <del> if ($this->generator->getRequest()->headers->has('referer')) <del> { <del> $back = $this->generator->getRequest()->headers->get('referer'); <del> } <del> elseif ($this->session->hasPreviousUrl()) <del> { <del> $back = $this->session->getPreviousUrl(); <del> } <add> $back = $this->generator->getRequest()->headers->get('referer'); <ide> <ide> return $this->createRedirect($back, $status, $headers); <ide> } <ide><path>src/Illuminate/Session/Middleware.php <ide> public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQ <ide> // add the session identifier cookie to the application response headers now. <ide> if ($this->sessionConfigured()) <ide> { <del> $this->closeSession($session, $request); <add> $this->closeSession($session); <ide> <ide> $this->addCookieToResponse($response, $session); <ide> } <ide> protected function startSession(Request $request) <ide> * @param \Illuminate\Session\SessionInterface $session <ide> * @return void <ide> */ <del> protected function closeSession(SessionInterface $session, Request $request) <add> protected function closeSession(SessionInterface $session) <ide> { <del> $session->setPreviousUrl($this->getUrl($request)); <del> <ide> $session->save(); <ide> <ide> $this->collectGarbage($session); <ide><path>src/Illuminate/Session/Store.php <ide> public function flush() <ide> $this->clear(); <ide> } <ide> <del> /** <del> * Determine if the session contains the previous URL. <del> * <del> * @return bool <del> */ <del> public function hasPreviousUrl() <del> { <del> return $this->has('_previous_url'); <del> } <del> <del> /** <del> * Get the previous URL from the session. <del> * <del> * @return string|null <del> */ <del> public function getPreviousUrl() <del> { <del> return $this->get('_previous_url'); <del> } <del> <del> /** <del> * Set the previous URL in the session. <del> * <del> * @param string $url <del> * @return void <del> */ <del> public function setPreviousUrl($url) <del> { <del> $this->set('_previous_url', $url); <del> } <del> <ide> /** <ide> * {@inheritdoc} <ide> */ <ide><path>tests/Routing/RoutingRedirectorTest.php <ide> public function testRefreshRedirectToCurrentUrl() <ide> <ide> public function testBackRedirectToHttpReferer() <ide> { <del> $this->session->shouldReceive('hasPreviousUrl')->never(); <ide> $this->headers->shouldReceive('has')->with('referer')->andReturn(true); <ide> $this->headers->shouldReceive('get')->with('referer')->andReturn('http://foo.com/bar'); <ide> $response = $this->redirect->back(); <ide> $this->assertEquals('http://foo.com/bar', $response->getTargetUrl()); <ide> } <ide> <ide> <del> public function testBackRedirectToSessionsPreviousUrlIfAvailable() <del> { <del> $this->headers->shouldReceive('has')->with('referer')->andReturn(false); <del> $this->session->shouldReceive('hasPreviousUrl')->once()->andReturn(true); <del> $this->session->shouldReceive('getPreviousUrl')->once()->andReturn('http://foo.com/bar'); <del> $this->headers->shouldReceive('get')->never(); <del> $response = $this->redirect->back(); <del> $this->assertEquals('http://foo.com/bar', $response->getTargetUrl()); <del> } <del> <del> <ide> public function testAwayDoesntValidateTheUrl() <ide> { <ide> $response = $this->redirect->away('bar');
4
Text
Text
fix russian rust docs (index page)
d0560e90268ed15436d4db028b8e33967cc41126
<ide><path>guide/russian/rust/index.md <ide> --- <ide> title: Rust <del>localeTitle: Ржавчина <add>localeTitle: Rust <ide> --- <del># Ржавчина <add># Rust <ide> <ide> ## Введение <ide> <del>Rust - это язык системного программирования, ориентированный на три цели: безопасность, скорость и параллелизм. Его дизайн позволяет создавать программы, которые имеют производительность и управление языком низкого уровня, но с мощными абстракциями языка высокого уровня. Эти свойства делают Rust подходящим для программистов, которые имеют опыт работы на таких языках, как C, и ищут более безопасную альтернативу, а также такие языки, как Python, которые ищут способы написания кода, который работает лучше, не жертвуя выразительностью. Rust запускает большинство своих проверок безопасности и решений по управлению памятью во время компиляции, так что производительность выполнения вашей программы не влияет. Это делает его полезным в ряде случаев, когда другие языки не подходят: программы с предсказуемыми требованиями к пространству и времени, встраивание в другие языки и запись низкоуровневого кода, например драйверов устройств и операционных систем. Также для веб-приложений также используется сайт реестра пакета Rust, [crates.io](https://www.crates.io) . <add>Rust - это язык системного программирования, ориентированный на три цели: безопасность, скорость и параллелизм. Его дизайн позволяет создавать программы, которые имеют производительность и контроль, свойственные языкам низкого уровня, но с мощными абстракциями языка высокого уровня. Эти свойства делают Rust подходящим для программистов с опытом работы на таких языках, как C, и ищут более безопасную альтернативу, а также для программистов на языках, подобных Python, которые ищут способы написания кода, который работает производительнее, не жертвуя выразительностью. Rust выполняет большую часть своих проверок безопасности и решений по управлению памятью во время компиляции, так что производительность выполнения вашей программы не страдает. Это делает его полезным в ряде случаев, когда другие языки не подходят: программы с предсказуемыми требованиями к пространству и времени, встраивание в другие языки и написание низкоуровневого кода, например, драйверов устройств и операционных систем. Его используют и для написания веб-приложений, например, на нём написан сайт репозитория пакетов для Rust, [crates.io](https://www.crates.io). <ide> <del>Для получения дополнительной информации [перейдите на главную страницу Rust](https://www.rust-lang.org) . <add>Для получения дополнительной информации [перейдите на главную страницу Rust](https://www.rust-lang.org). <ide> <del>## Монтаж <add>## Установка <ide> <del>Разработчики ржавчины чрезвычайно упрощают установку и управление ржавчиной в вашей системе. Это достигается с помощью инструмента `rustup` который позволяет не только устанавливать `rustc` компилятор `rustc` , но также легко переключаться между стабильными, бета-версиями и ночными версиями компилятора и поддерживать их в актуальном состоянии. <add>Разработчики Rust чрезвычайно упрощают установку и управление Rust в вашей системе. Это достигается с помощью инструмента `rustup` который позволяет не только устанавливать компилятор `rustc` , но также легко переключаться между стабильными, бета-версиями и ночными версиями компилятора и поддерживать их в актуальном состоянии. <ide> <ide> Официальную документацию по установке можно найти [здесь](https://doc.rust-lang.org/book/second-edition/ch01-01-installation.html) . <ide> <ide> ### Linux или Mac <ide> <del>Если вы используете Linux или Mac, установка `rustup` лучше всего сделать через терминал: <add>Если вы используете Linux или Mac, установку `rustup` лучше всего сделать через терминал: <ide> <ide> ```bash <ide> $ curl https://sh.rustup.rs -sSf | sh <ide> $ curl https://sh.rustup.rs -sSf | sh <ide> <ide> ### Windows <ide> <del>В Windows перейдите на [сайт rustup](https://rustup.rs) и следуйте инструкциям по загрузке `rustup-init.exe` . Запустите это и следуйте остальным инструкциям, которые он вам дает. <add>В Windows перейдите на [сайт rustup](https://rustup.rs) и следуйте инструкциям по загрузке `rustup-init.exe`. Запустите его и следуйте его инструкциям. <ide> <ide> ### обновление <ide> <del>Как только вы установили `rustup` , обновление до более новых версий прост. Все, что вам нужно запустить: <add>Когда вы установили `rustup`, вы можете легко обновиться до актуальных версий. Все, что вам нужно запустить: <ide> <ide> ```bash <ide> $ rustup update <ide> ``` <ide> <del>Чтобы просмотреть текущий номер версии, зафиксировать хеш и дату фиксации вашего компилятора ржавчины, выполните следующую команду: <add>Чтобы просмотреть текущий номер версии, хеш и дату коммита вашего компилятора Rust, выполните следующую команду: <ide> <ide> ```bash <ide> $ rustc --version <ide> $ rustc --version <ide> <ide> ### Удаление <ide> <del>Удаление ржавчины из вашей системы так же просто, как и установка: <add>Удаление Rust из вашей системы так же просто, как и установка: <ide> <ide> ```bash <ide> $ rustup self uninstall <ide> <del>``` <ide>\ No newline at end of file <add>```
1
Ruby
Ruby
pass check_ip and proxies to getip constructor
6c4416183454cc75ee4dbed107fe7370c69fc37d
<ide><path>actionpack/lib/action_dispatch/middleware/remote_ip.rb <ide> def initialize(app, check_ip_spoofing = true, custom_proxies = nil) <ide> # requests. For those requests that do need to know the IP, the <ide> # GetIp#calculate_ip method will calculate the memoized client IP address. <ide> def call(env) <del> env["action_dispatch.remote_ip"] = GetIp.new(env, self) <add> env["action_dispatch.remote_ip"] = GetIp.new(env, check_ip, proxies) <ide> @app.call(env) <ide> end <ide> <ide> # The GetIp class exists as a way to defer processing of the request data <ide> # into an actual IP address. If the ActionDispatch::Request#remote_ip method <ide> # is called, this class will calculate the value and then memoize it. <ide> class GetIp <del> def initialize(env, middleware) <add> def initialize(env, check_ip, proxies) <ide> @env = env <del> @check_ip = middleware.check_ip <del> @proxies = middleware.proxies <add> @check_ip = check_ip <add> @proxies = proxies <ide> end <ide> <ide> # Sort through the various IP address headers, looking for the IP most
1
Ruby
Ruby
move layout lookup to views
ffd8d753f171a33cb0f8dadaff7fc5ba12b8f6b0
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> class Base < AbstractController::Base <ide> include AbstractController::Layouts <ide> include AbstractController::Helpers <ide> include AbstractController::Translation <del> include AbstractController::Compatibility <ide> <ide> helper ActionMailer::MailHelper <ide> <ide><path>actionpack/lib/abstract_controller/base.rb <ide> class ActionNotFound < StandardError; end <ide> class Base <ide> attr_internal :response_body <ide> attr_internal :action_name <del> attr_internal :formats <ide> <ide> class << self <ide> attr_reader :abstract <ide> def controller_path <ide> <ide> abstract! <ide> <del> # Initialize controller with nil formats. <del> def initialize #:nodoc: <del> @_formats = nil <del> end <del> <ide> def config <ide> @config ||= ActiveSupport::InheritableOptions.new(self.class.config) <ide> end <ide><path>actionpack/lib/abstract_controller/compatibility.rb <del>module AbstractController <del> module Compatibility <del> extend ActiveSupport::Concern <del> <del> def _find_layout(name, details) <del> details[:prefix] = nil if name =~ /\blayouts/ <del> super <del> end <del> <del> # Move this into a "don't run in production" module <del> def _default_layout(details, require_layout = false) <del> super <del> rescue ActionView::MissingTemplate <del> _layout_for_name(_layout({}), {}) <del> nil <del> end <del> end <del>end <ide><path>actionpack/lib/abstract_controller/layouts.rb <ide> def _layout(details) <ide> raise ArgumentError, "Layouts must be specified as a String, Symbol, false, or nil" <ide> when nil <ide> if name <add> _prefix = "layouts" unless _implied_layout_name =~ /\blayouts/ <add> <ide> self.class_eval <<-RUBY, __FILE__, __LINE__ + 1 <ide> def _layout(details) <del> if template_exists?("#{_implied_layout_name}", :_prefix => "layouts") <add> if template_exists?("#{_implied_layout_name}", :_prefix => #{_prefix.inspect}) <ide> "#{_implied_layout_name}" <ide> else <ide> super <ide> def render_to_body(options = {}) <ide> # render_template <ide> if layout <ide> layout = _layout_for_option(layout, options[:_template].details) <add> layout = find_template(layout, {}) <ide> response = layout.render(view_context, options[:locals] || {}) { response } <ide> end <ide> <ide> def _layout(details) end <ide> # the lookup to. By default, layout lookup is limited to the <ide> # formats specified for the current request. <ide> def _layout_for_name(name, details) <del> name && _find_layout(name, details) <add> name <ide> end <ide> <ide> # Determine the layout for a given name and details, taking into account <ide> def _determine_template(options) <ide> <ide> return unless (options.keys & [:text, :inline, :partial]).empty? || options.key?(:layout) <ide> layout = options.key?(:layout) ? options[:layout] : :default <del> options[:_layout] = _layout_for_option(layout, options[:_template].details) <del> end <del> <del> # Take in the name and details and find a Template. <del> # <del> # ==== Parameters <del> # name<String>:: The name of the template to retrieve <del> # details<Hash>:: A list of details to restrict the search by. This <del> # might include details like the format or locale of the template. <del> # <del> # ==== Returns <del> # Template:: A template object matching the name and details <del> def _find_layout(name, details) <del> prefix = details.key?(:prefix) ? details.delete(:prefix) : "layouts" <del> # TODO This should happen automatically <del> template_lookup.details = template_lookup.details.merge(:formats => details[:formats]) <del> find_template(name, :_prefix => prefix) <add> options[:layout] = _layout_for_option(layout, options[:_template].details) <ide> end <ide> <ide> # Returns the default layout for this controller and a given set of details. <ide><path>actionpack/lib/abstract_controller/rendering.rb <ide> module Rendering <ide> <ide> included do <ide> class_attribute :_view_paths <del> delegate :_view_paths, :to => :'self.class' <ide> self._view_paths = ActionView::PathSet.new <ide> end <ide> <add> delegate :formats, :formats=, :to => :template_lookup <add> delegate :_view_paths, :to => :'self.class' <add> <ide> # An instance of a view class. The default view class is ActionView::Base <ide> # <ide> # The view class must have the following methods: <ide> def _determine_template(options) <ide> end <ide> <ide> def details_for_render <del> { :formats => formats, :locale => [I18n.locale] } <add> { } <ide> end <ide> <ide> def _normalize_details(options) <del> details = details_for_render <add> details = template_lookup.details <ide> details[:formats] = Array(options[:format]) if options[:format] <ide> details[:locale] = Array(options[:locale]) if options[:locale] <ide> details <ide><path>actionpack/lib/action_controller/metal/implicit_render.rb <ide> def default_render <ide> <ide> def method_for_action(action_name) <ide> super || begin <del> # TODO This should use template lookup <del> if view_paths.exists?(action_name.to_s, details_for_render, controller_path) <add> if template_exists?(action_name.to_s, :_prefix => controller_path) <ide> "default_render" <ide> end <ide> end <ide><path>actionpack/lib/action_controller/metal/rendering.rb <ide> module Rendering <ide> include ActionController::RackDelegation <ide> include AbstractController::Rendering <ide> <del> def process_action(*) <add> def process(*) <ide> self.formats = request.formats.map {|x| x.to_sym } <ide> super <ide> end <ide><path>actionpack/lib/action_view/base.rb <ide> def initialize(template_lookup = nil, assigns_for_first_render = {}, controller <ide> attr_internal :controller, :template, :config <ide> <ide> attr_reader :template_lookup <del> delegate :find, :view_paths, :view_paths=, :to => :template_lookup <del> <del> def formats=(formats) <del> update_details(:formats => Array(formats)) <del> end <add> delegate :find, :formats, :formats=, :view_paths, :view_paths=, :to => :template_lookup <ide> <ide> def update_details(details) <ide> old_details = template_lookup.details <ide><path>actionpack/lib/action_view/render/partials.rb <ide> def render_partial(options) <ide> details = options[:_details] <ide> <ide> # TODO This should happen automatically as well <del> self.formats = details[:formats] if details <add> self.formats = details[:formats] if details[:formats] <ide> renderer = PartialRenderer.new(self, options, nil) <ide> text = renderer.render <ide> options[:_template] = renderer.template <ide><path>actionpack/lib/action_view/render/rendering.rb <ide> def _layout_for(name = nil, &block) <ide> # _layout:: The layout, if any, to wrap the Template in <ide> def render_template(options) <ide> _evaluate_assigns_and_ivars <del> template, layout = options.values_at(:_template, :_layout) <add> template, layout = options.values_at(:_template, :layout) <ide> _render_template(template, layout, options) <ide> end <ide> <add> def _find_layout(template, layout) <add> begin <add> prefix = "layouts" unless layout =~ /\blayouts/ <add> layout = find(layout, prefix) <add> rescue ActionView::MissingTemplate => e <add> update_details(:formats => nil) do <add> raise unless template_lookup.exists?(layout, prefix) <add> end <add> end <add> end <add> <ide> def _render_template(template, layout = nil, options = {}) <add> self.formats = template.details[:formats] <add> <ide> locals = options[:locals] || {} <add> layout = _find_layout(template, layout) if layout.is_a?(String) <ide> <ide> ActiveSupport::Notifications.instrument("action_view.render_template", <ide> :identifier => template.identifier, :layout => layout.try(:identifier)) do <ide><path>actionpack/lib/action_view/template/lookup.rb <ide> def initialize(view_paths, details = {}) <ide> self.view_paths = view_paths <ide> end <ide> <add> def formats <add> @details[:formats] <add> end <add> <add> def formats=(value) <add> self.details = @details.merge(:formats => Array(value)) <add> end <add> <ide> def view_paths=(paths) <ide> @view_paths = ActionView::Base.process_view_paths(paths) <ide> end <ide><path>actionpack/test/abstract/layouts_test.rb <ide> class Base < AbstractController::Base <ide> self.view_paths = [ActionView::FixtureResolver.new( <ide> "layouts/hello.erb" => "With String <%= yield %>", <ide> "layouts/hello_override.erb" => "With Override <%= yield %>", <del> "layouts/abstract_controller_tests/layouts/with_string_implied_child.erb" => <add> "abstract_controller_tests/layouts/with_string_implied_child.erb" => <ide> "With Implied <%= yield %>", <ide> "layouts/overwrite.erb" => "Overwrite <%= yield %>", <ide> "layouts/with_false_layout.erb" => "False Layout <%= yield %>"
12
Python
Python
fix migration message
971cae35200968ecbeea81d39846f2d8309644a0
<ide><path>airflow/migrations/versions/b3b105409875_add_root_dag_id_to_dag.py <ide> # under the License. <ide> <ide> """add root_dag_id to DAG <add> <ide> Revision ID: b3b105409875 <ide> Revises: d38e04c12aa2 <ide> Create Date: 2019-09-28 23:20:01.744775 <add> <ide> """ <ide> <ide> import sqlalchemy as sa
1
Ruby
Ruby
preserve fractional seconds in datetime#to_time
bf0395837fc735bf98daed23f475b267e48c1118
<ide><path>activesupport/lib/active_support/core_ext/date_time/conversions.rb <ide> def to_date <ide> # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class <ide> # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time <ide> def to_time <del> self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self <add> self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self <ide> end <ide> <ide> # To be able to keep Times, Dates and DateTimes interchangeable on conversions <ide><path>activesupport/test/core_ext/date_time_ext_test.rb <ide> def test_to_time <ide> assert_equal Time.utc_time(2039, 2, 21, 10, 11, 12), DateTime.new(2039, 2, 21, 10, 11, 12, 0, 0).to_time <ide> # DateTimes with offsets other than 0 are returned unaltered <ide> assert_equal DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)), DateTime.new(2005, 2, 21, 10, 11, 12, Rational(-5, 24)).to_time <add> # Fractional seconds are preserved <add> assert_equal Time.utc(2005, 2, 21, 10, 11, 12, 256), DateTime.new(2005, 2, 21, 10, 11, 12 + Rational(256, 1000000), 0).to_time <ide> end <ide> <ide> def test_civil_from_format
2
Mixed
Text
replace therubyracer with mini_racer
6cc153959ac04a39d4081a2cf23e1ff83c4efe3b
<ide><path>guides/source/asset_pipeline.md <ide> pre-existing JavaScript runtimes, you may want to add one to your Gemfile: <ide> <ide> ```ruby <ide> group :production do <del> gem 'therubyracer' <add> gem 'mini_racer' <ide> end <ide> ``` <ide> <ide><path>guides/source/getting_started.md <ide> TIP: Compiling CoffeeScript and JavaScript asset compression requires you <ide> have a JavaScript runtime available on your system, in the absence <ide> of a runtime you will see an `execjs` error during asset compilation. <ide> Usually macOS and Windows come with a JavaScript runtime installed. <del>Rails adds the `therubyracer` gem to the generated `Gemfile` in a <add>Rails adds the `mini_racer` gem to the generated `Gemfile` in a <ide> commented line for new apps and you can uncomment if you need it. <ide> `therubyrhino` is the recommended runtime for JRuby users and is added by <ide> default to the `Gemfile` in apps generated under JRuby. You can investigate <ide><path>railties/lib/rails/generators/app_base.rb <ide> def javascript_runtime_gemfile_entry <ide> if defined?(JRUBY_VERSION) <ide> GemfileEntry.version "therubyrhino", nil, comment <ide> else <del> GemfileEntry.new "therubyracer", nil, comment, { platforms: :ruby }, true <add> GemfileEntry.new "mini_racer", nil, comment, { platforms: :ruby }, true <ide> end <ide> end <ide> <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_inclusion_of_javascript_runtime <ide> if defined?(JRUBY_VERSION) <ide> assert_gem "therubyrhino" <ide> else <del> assert_file "Gemfile", /# gem 'therubyracer', platforms: :ruby/ <add> assert_file "Gemfile", /# gem 'mini_racer', platforms: :ruby/ <ide> end <ide> end <ide>
4
Go
Go
fix entrypoint without cmd
0f249c85ea9acc7fba33994aa5d20a897463db2c
<ide><path>builder.go <ide> func (builder *Builder) Create(config *Config) (*Container, error) { <ide> MergeConfig(config, img.Config) <ide> } <ide> <del> if config.Cmd == nil || len(config.Cmd) == 0 { <add> if len(config.Entrypoint) != 0 && config.Cmd == nil { <add> config.Cmd = []string{} <add> } else if config.Cmd == nil || len(config.Cmd) == 0 { <ide> return nil, fmt.Errorf("No command specified") <ide> } <ide> <ide><path>buildfile.go <ide> func (b *buildFile) CmdRun(args string) error { <ide> b.config.Cmd = nil <ide> MergeConfig(b.config, config) <ide> <add> defer func(cmd []string) { b.config.Cmd = cmd }(cmd) <add> <ide> utils.Debugf("Command to be executed: %v", b.config.Cmd) <ide> <ide> if b.utilizeCache { <ide> func (b *buildFile) CmdRun(args string) error { <ide> if err := b.commit(cid, cmd, "run"); err != nil { <ide> return err <ide> } <del> b.config.Cmd = cmd <add> <ide> return nil <ide> } <ide>
2
Javascript
Javascript
allow objects in `define` option #100
1aa80aa48b265a05a9e704f8d56ed6ba6c19216d
<ide><path>lib/DefinePlugin.js <ide> function DefinePlugin(definitions) { <ide> } <ide> module.exports = DefinePlugin; <ide> DefinePlugin.prototype.apply = function(compiler) { <del> var definitions = this.definitions; <del> Object.keys(definitions).forEach(function(key) { <del> var code = definitions[key]; <del> if(typeof code !== "string" && code.toString) code = code.toString(); <del> else if(typeof code !== "string") code = code + ""; <del> applyDefine(key, code); <del> }); <add> (function walkDefinitions(definitions, prefix) { <add> Object.keys(definitions).forEach(function(key) { <add> var code = definitions[key]; <add> if(typeof code === "object") { <add> walkDefinitions(code, key + "."); <add> applyObjectDefine(key, code); <add> return; <add> } <add> if(typeof code !== "string" && code.toString) code = code.toString(); <add> else if(typeof code !== "string") code = code + ""; <add> applyDefine(prefix + key, code); <add> }); <add> }(this.definitions, "")); <ide> function applyDefine(key, code) { <ide> var recurse = false; <ide> var recurseTypeof = false; <ide> DefinePlugin.prototype.apply = function(compiler) { <ide> return true; <ide> }); <ide> } <add> function applyObjectDefine(key, obj) { <add> var code = "{" + Object.keys(obj).map(function(key) { <add> var code = obj[key]; <add> if(typeof code !== "string" && code.toString) code = code.toString(); <add> else if(typeof code !== "string") code = code + ""; <add> return JSON.stringify(key) + ":" + code; <add> }).join(",") + "}"; <add> compiler.parser.plugin("evaluate Identifier " + key, function(expr) { <add> return new BasicEvaluatedExpression().setRange(expr.range); <add> }); <add> compiler.parser.plugin("evaluate typeof " + key, function(expr) { <add> return new BasicEvaluatedExpression().setString("object").setRange(expr.range); <add> }); <add> compiler.parser.plugin("expression " + key, function(expr) { <add> var dep = new ConstDependency("("+code+")", expr.range); <add> dep.loc = expr.loc; <add> this.state.current.addDependency(dep); <add> return true; <add> }); <add> compiler.parser.plugin("typeof " + key, function(expr) { <add> var dep = new ConstDependency("\"object\"", expr.range); <add> dep.loc = expr.loc; <add> this.state.current.addDependency(dep); <add> return true; <add> }); <add> } <ide> }; <ide>\ No newline at end of file
1
Go
Go
use init function
740a97f1a836be17ab39e8496b7372900782c20b
<ide><path>a_test.go <del>package docker <del> <del>import ( <del> "os" <del> "testing" <del>) <del> <del>func Test(t *testing.T) { <del> os.Setenv("TEST", "1") <del>} <ide><path>runtime_test.go <ide> func layerArchive(tarfile string) (io.Reader, error) { <ide> } <ide> <ide> func init() { <add> os.Setenv("TEST", "1") <add> <ide> // Hack to run sys init during unit testing <ide> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" { <ide> SysInit()
2
Javascript
Javascript
fix some messy rebasing issues
0ccb88d48da3d3b7f1cc7369d948ffd5902c553e
<ide><path>src/event.js <ide> if ( !jQuery.support.submitBubbles ) { <ide> if ( !jQuery.support.changeBubbles ) { <ide> <ide> var getVal = function( elem ) { <del> var type = elem.type, <del> val = elem.value; <del> <del> getVal = function( elem ) { <ide> var type = jQuery.nodeName( elem, "input" ) ? elem.type : "", <ide> val = elem.value; <ide> <ide> if ( !jQuery.support.changeBubbles ) { <ide> }, <ide> <ide> changeFilters = { <del> focusout: testChange, <add> focusout: testChange, <ide> <del> beforedeactivate: testChange, <add> beforedeactivate: testChange, <ide> <del> click: function( e ) { <del> var elem = e.target, <del> name = elem.nodeName.toLowerCase(), <del> type = name === "input"? elem.type : ""; <add> click: function( e ) { <add> var elem = e.target, <add> name = elem.nodeName.toLowerCase(), <add> type = name === "input"? elem.type : ""; <ide> <del> if ( type === "radio" || type === "checkbox" || name === "select" ) { <del> testChange.call( this, e ); <del> } <del> }, <add> if ( type === "radio" || type === "checkbox" || name === "select" ) { <add> testChange.call( this, e ); <add> } <add> }, <ide> <del> // Change has to be called before submit <del> // Keydown will be called before keypress, which is used in submit-event delegation <del> keydown: function( e ) { <del> var elem = e.target, <del> name = elem.nodeName.toLowerCase(), <del> type = name === "input"? elem.type : ""; <del> <del> if ( (e.keyCode === 13 && name !== "textarea") || <del> (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || <del> type === "select-multiple" ) { <del> testChange.call( this, e ); <del> } <del> }, <add> // Change has to be called before submit <add> // Keydown will be called before keypress, which is used in submit-event delegation <add> keydown: function( e ) { <add> var elem = e.target, <add> name = elem.nodeName.toLowerCase(), <add> type = name === "input"? elem.type : ""; <add> <add> if ( (e.keyCode === 13 && name !== "textarea") || <add> (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || <add> type === "select-multiple" ) { <add> testChange.call( this, e ); <add> } <add> }, <ide> <del> // Beforeactivate happens also before the previous element is blurred <add> // Beforeactivate happens also before the previous element is blurred <ide> // here, you can't trigger a change event, but you can store data <ide> beforeactivate: function( e ) { <ide> var elem = e.target;
1
Ruby
Ruby
fix typo s/precendence/precedence/
86e46956e37d440def61551b649a17fb8a2e2f16
<ide><path>activesupport/test/zeitwerk_inflector_test.rb <ide> def camelize(basename) <ide> assert_equal "SSLError", camelize("ssl_error") <ide> end <ide> <del> test "overrides take precendence" do <add> test "overrides take precedence" do <ide> # Precondition, ensure we are testing something. <ide> assert_equal "MysqlAdapter", camelize("mysql_adapter") <ide>
1
Java
Java
fix typo in comment about package
231d2f95cdca615e30e1195275c40d4ecde86903
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ModuleHolder.java <ide> public ModuleHolder(NativeModule nativeModule) { <ide> } <ide> } <ide> <del> /* pacakge */ synchronized boolean hasInstance() { <add> /* package */ synchronized boolean hasInstance() { <ide> return mModule != null; <ide> } <ide>
1
Javascript
Javascript
fix broken tests for element dsl
275f036c1f146d37c088027c79338d0d5209c03a
<ide><path>test/scenario/DSLSpec.js <ide> describe("DSL", function() { <ide> expect(future.fulfilled).toBeTruthy(); <ide> } <ide> it('should find elements on the page and provide jquery api', function() { <del> var future = element('.reports-detail').find(); <add> var future = element('.reports-detail'); <ide> expect(future.name).toEqual("Find element '.reports-detail'"); <ide> timeTravel(future); <ide> expect(future.value.text()). <ide> describe("DSL", function() { <ide> toEqual('Description : Details...'); <ide> }); <ide> it('should find elements with angular syntax', function() { <del> var future = element('{{report.description}}').find(); <add> var future = element('{{report.description}}'); <ide> expect(future.name).toEqual("Find element '{{report.description}}'"); <ide> timeTravel(future); <ide> expect(future.value.text()).toEqual('Details...');
1