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 |
|---|---|---|---|---|---|
Text | Text | add v3.28.10 to changelog | 701ee45b79b4ee3f860d2c380aa3d87212e3fad5 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>## v3.28.10 (November 2, 2022)
<add>
<add>- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
<add>
<ide> ### v3.24.7 (November 2, 2022)
<ide>
<ide> - [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` | 1 |
Javascript | Javascript | avoid exception from "new shadermaterial()" | 8b201481846a936986c3d0cc3de3d087b90e6c0e | <ide><path>src/materials/ShaderMaterial.js
<ide> THREE.ShaderMaterial = function ( parameters ) {
<ide> this.uniforms = {};
<ide> this.attributes = [];
<ide>
<del> if ( parameters.attributes !== undefined && Array.isArray( parameters.attributes ) === false ) {
<del>
<del> console.warn( 'THREE.ShaderMaterial: attributes should now be an array of attribute names.' );
<del> parameters.attributes = Object.keys( parameters.attributes );
<del>
<del> }
<del>
<ide> this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
<ide> this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
<ide>
<ide> THREE.ShaderMaterial = function ( parameters ) {
<ide>
<ide> this.index0AttributeName = undefined;
<ide>
<del> this.setValues( parameters );
<add> if ( parameters !== undefined ) {
<add>
<add> if ( parameters.attributes !== undefined && Array.isArray( parameters.attributes ) === false ) {
<add>
<add> console.warn( 'THREE.ShaderMaterial: attributes should now be an array of attribute names.' );
<add> parameters.attributes = Object.keys( parameters.attributes );
<add>
<add> }
<add>
<add> this.setValues( parameters );
<add>
<add> }
<ide>
<ide> };
<ide> | 1 |
Javascript | Javascript | use generatetransform for geometry transforms | ad44277f5554cee5928c8f013114a1ba56fcc286 | <ide><path>examples/js/loaders/FBXLoader.js
<ide>
<ide> }, null );
<ide>
<del> var preTransform = new THREE.Matrix4();
<del>
<ide> // TODO: if there is more than one model associated with the geometry, AND the models have
<ide> // different geometric transforms, then this will cause problems
<ide> // if ( modelNodes.length > 1 ) { }
<ide>
<ide> // For now just assume one model and get the preRotations from that
<ide> var modelNode = modelNodes[ 0 ];
<ide>
<del> if ( 'GeometricRotation' in modelNode ) {
<del>
<del> var eulerOrder = 'ZYX';
<del>
<del> if ( 'RotationOrder' in modelNode ) {
<del>
<del> eulerOrder = getEulerOrder( parseInt( modelNode.RotationOrder.value ) );
<del>
<del> }
<del>
<del> var array = modelNode.GeometricRotation.value.map( THREE.Math.degToRad );
<del> array.push( eulerOrder );
<del> preTransform.makeRotationFromEuler( new THREE.Euler().fromArray( array ) );
<del>
<del> }
<del>
<del> if ( 'GeometricTranslation' in modelNode ) {
<del>
<del> preTransform.setPosition( new THREE.Vector3().fromArray( modelNode.GeometricTranslation.value ) );
<del>
<del> }
<add> var transformData = {};
<ide>
<del> if ( 'GeometricScaling' in modelNode ) {
<add> if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = modelNode.RotationOrder.value;
<ide>
<del> preTransform.scale( new THREE.Vector3().fromArray( modelNode.GeometricScaling.value ) );
<add> if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
<add> if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
<add> if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
<ide>
<del> }
<add> var transform = generateTransform( transformData );
<ide>
<del> return genGeometry( FBXTree, geoNode, skeleton, morphTarget, preTransform );
<add> return genGeometry( FBXTree, geoNode, skeleton, morphTarget, transform );
<ide>
<ide> }
<ide> | 1 |
Python | Python | fix typo in comment | b00ec66ba948077b61e25cf7dc004857c432b01a | <ide><path>keras/backend/tensorflow_backend.py
<ide>
<ide> # This dictionary holds a mapping {graph: UID_DICT}.
<ide> # each UID_DICT is a dictionary mapping name prefixes to a current index,
<del># used for generic graph-specific string UIDs
<add># used for generating graph-specific string UIDs
<ide> # for various names (e.g. layer names).
<ide> _GRAPH_UID_DICTS = {}
<ide> | 1 |
Ruby | Ruby | use bytesize rather than force encoding | 3f81230a723a04a49aa28baf038566768bd392ce | <ide><path>actionpack/test/dispatch/request/multipart_params_parsing_test.rb
<ide> def teardown
<ide>
<ide> # Rack doesn't handle multipart/mixed for us.
<ide> files = params['files']
<del> files.force_encoding('ASCII-8BIT')
<del> assert_equal 19756, files.size
<add> assert_equal 19756, files.bytesize
<ide> end
<ide>
<ide> test "does not create tempfile if no file has been selected" do | 1 |
Go | Go | fix incorrect ping, and cleanup | a3b1b66bb35485a5728590a25467de1c19d0bf59 | <ide><path>integration/system/ping_test.go
<ide> func TestPingSwarmHeader(t *testing.T) {
<ide> ctx := context.TODO()
<ide>
<ide> t.Run("before swarm init", func(t *testing.T) {
<del> res, _, err := request.Get("/_ping")
<add> p, err := client.Ping(ctx)
<ide> assert.NilError(t, err)
<del> assert.Equal(t, res.StatusCode, http.StatusOK)
<del> assert.Equal(t, hdr(res, "Swarm"), "inactive")
<add> assert.Equal(t, p.SwarmStatus.NodeState, swarm.LocalNodeStateInactive)
<add> assert.Equal(t, p.SwarmStatus.ControlAvailable, false)
<ide> })
<ide>
<ide> _, err := client.SwarmInit(ctx, swarm.InitRequest{ListenAddr: "127.0.0.1", AdvertiseAddr: "127.0.0.1:2377"})
<ide> assert.NilError(t, err)
<ide>
<ide> t.Run("after swarm init", func(t *testing.T) {
<del> res, _, err := request.Get("/_ping", request.Host(d.Sock()))
<add> p, err := client.Ping(ctx)
<ide> assert.NilError(t, err)
<del> assert.Equal(t, res.StatusCode, http.StatusOK)
<del> assert.Equal(t, hdr(res, "Swarm"), "active/manager")
<add> assert.Equal(t, p.SwarmStatus.NodeState, swarm.LocalNodeStateActive)
<add> assert.Equal(t, p.SwarmStatus.ControlAvailable, true)
<ide> })
<ide>
<ide> err = client.SwarmLeave(ctx, true)
<ide> assert.NilError(t, err)
<ide>
<ide> t.Run("after swarm leave", func(t *testing.T) {
<del> res, _, err := request.Get("/_ping", request.Host(d.Sock()))
<add> p, err := client.Ping(ctx)
<ide> assert.NilError(t, err)
<del> assert.Equal(t, res.StatusCode, http.StatusOK)
<del> assert.Equal(t, hdr(res, "Swarm"), "inactive")
<add> assert.Equal(t, p.SwarmStatus.NodeState, swarm.LocalNodeStateInactive)
<add> assert.Equal(t, p.SwarmStatus.ControlAvailable, false)
<ide> })
<ide> }
<ide> | 1 |
Python | Python | rewrite tests for issue | 0e62809a4311afcddd16a4dc57700026c2fea662 | <ide><path>spacy/tests/regression/test_issue1769.py
<ide> from __future__ import unicode_literals
<ide>
<ide> from ...lang.da.lex_attrs import like_num as da_like_num
<del># from ...lang.en.lex_attrs import like_num as en_like_num
<del># from ...lang.fr.lex_attrs import like_num as fr_like_num
<del># from ...lang.id.lex_attrs import like_num as id_like_num
<del># from ...lang.nl.lex_attrs import like_num as nl_like_num
<del># from ...lang.pt.lex_attrs import like_num as pt_like_num
<del># from ...lang.ru.lex_attrs import like_num as ru_like_num
<add>from ...lang.en.lex_attrs import like_num as en_like_num
<add>from ...lang.fr.lex_attrs import like_num as fr_like_num
<add>from ...lang.id.lex_attrs import like_num as id_like_num
<add>from ...lang.nl.lex_attrs import like_num as nl_like_num
<add>from ...lang.pt.lex_attrs import like_num as pt_like_num
<add>from ...lang.ru.lex_attrs import like_num as ru_like_num
<ide>
<ide> import pytest
<ide>
<ide>
<del>@pytest.mark.parametrize('num_words', ['elleve', 'ELLEVE'])
<del>@pytest.mark.parametrize('ordinal_words', ['første', 'FØRSTE'])
<del>def test_da_lex_attrs(num_words, ordinal_words):
<del> assert da_like_num(num_words) == True
<del> assert da_like_num(ordinal_words) == True
<del>
<del>
<del># @pytest.mark.parametrize('num_words', ['eleven', 'ELEVEN'])
<del># def test_en_lex_attrs(num_words):
<del># assert en_like_num(num_words) == True
<del>#
<del>#
<del># @pytest.mark.parametrize('num_words', ['onze', 'ONZE'])
<del># @pytest.mark.parametrize('ordinal_words', ['onzième', 'ONZIÈME'])
<del># def test_fr_lex_attrs(num_words, ordinal_words):
<del># assert fr_like_num(num_words) == True
<del># assert fr_like_num(ordinal_words) == True
<del>#
<del>#
<del># @pytest.mark.parametrize('num_words', ['sebelas', 'SEBELAS'])
<del># def test_id_lex_attrs(num_words):
<del># assert id_like_num(num_words) == True
<del>#
<del>#
<del># @pytest.mark.parametrize('num_words', ['elf', 'ELF'])
<del># @pytest.mark.parametrize('ordinal_words', ['elfde', 'ELFDE'])
<del># def test_nl_lex_attrs(num_words, ordinal_words):
<del># assert nl_like_num(num_words) == True
<del># assert nl_like_num(ordinal_words) == True
<del>#
<del>#
<del># @pytest.mark.parametrize('num_words', ['onze', 'ONZE'])
<del># @pytest.mark.parametrize('ordinal_words', ['quadragésimo', 'QUADRAGÉSIMO'])
<del># def test_pt_lex_attrs(num_words, ordinal_words):
<del># assert pt_like_num(num_words) == True
<del># assert pt_like_num(ordinal_words) == True
<del>#
<del>#
<del># @pytest.mark.parametrize('num_words', ['одиннадцать', 'ОДИННАДЦАТЬ'])
<del># def test_ru_lex_attrs(num_words):
<del># assert ru_like_num(num_words) == True
<add>@pytest.fixture
<add>def words():
<add> return {
<add> "da": {
<add> "num_words": ('elleve', 'ELLEVE'),
<add> "ord_words": ('første', 'FØRSTE')
<add> },
<add> "en": {
<add> "num_words": ('eleven', 'ELEVEN')
<add> },
<add> "fr": {
<add> "num_words": ('onze', 'ONZE'),
<add> "ord_words": ('onzième', 'ONZIÈME')
<add> },
<add> "id": {
<add> "num_words": ('sebelas', 'SEBELAS')
<add> },
<add> "nl": {
<add> "num_words": ('elf', 'ELF'),
<add> "ord_words": ('elfde', 'ELFDE')
<add> },
<add> "pt": {
<add> "num_words": ('onze', 'ONZE'),
<add> "ord_words": ('quadragésimo', 'QUADRAGÉSIMO')
<add> },
<add> "ru": {
<add> "num_words": ('одиннадцать', 'ОДИННАДЦАТЬ')
<add> }
<add> }
<add>
<add>
<add>
<add>def like_num(words, fn):
<add> ok = True
<add> for word in words:
<add> if fn(word) is not True:
<add> ok = False
<add> break
<add> return ok
<add>
<add>
<add>def test_da_lex_attrs(words):
<add> assert like_num(words["da"]["num_words"], da_like_num) == True
<add> assert like_num(words["da"]["ord_words"], da_like_num) == True
<add>
<add>
<add>def test_en_lex_attrs(words):
<add> assert like_num(words["en"]["num_words"], en_like_num) == True
<add>
<add>
<add>def test_fr_lex_attrs(words):
<add> assert like_num(words["fr"]["num_words"], fr_like_num) == True
<add> assert like_num(words["fr"]["ord_words"], fr_like_num) == True
<add>
<add>
<add>def test_id_lex_attrs(words):
<add> assert like_num(words["id"]["num_words"], id_like_num) == True
<add>
<add>
<add>def test_nl_lex_attrs(words):
<add> assert like_num(words["nl"]["num_words"], nl_like_num) == True
<add> assert like_num(words["nl"]["ord_words"], nl_like_num) == True
<add>
<add>
<add>def test_pt_lex_attrs(words):
<add> assert like_num(words["pt"]["num_words"], pt_like_num) == True
<add> assert like_num(words["pt"]["ord_words"], pt_like_num) == True
<add>
<add>
<add>def test_ru_lex_attrs(words):
<add> assert like_num(words["ru"]["num_words"], ru_like_num) == True | 1 |
Text | Text | add link to github draft pr page | 941a09bad225f1294ad4295ab9362eb30fae633f | <ide><path>.github/CONTRIBUTING.md
<ide> When you’ve decided to make changes, start with the following:
<ide>
<ide> * Once done with a patch / feature do not add more commits to a feature branch
<ide> * Create separate branches per patch or feature.
<del>* If you make a PR but it is not actually ready to be pulled into the dev branch, add `[Draft]` into the PR title and/or convert it to a draft PR
<add>* If you make a PR but it is not actually ready to be pulled into the dev branch then please [convert it to a draft PR](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/changing-the-stage-of-a-pull-request#converting-a-pull-request-to-a-draft).
<ide>
<ide> This project is currently contributed to mostly via everyone's spare time. Please keep that in mind as it may take some time for the appropriate feedback to get to you. If you are unsure about adding a new feature, it might be better to ask first to see whether other people think it's a good idea. | 1 |
Ruby | Ruby | fix pathname concatenation | b681ed42006ed92565ab97c8a4dee8fa4f8c0be7 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def initialize name, package
<ide> @co = HOMEBREW_CACHE + "#{name}--svn"
<ide> end
<ide>
<del> @co << "-HEAD" if ARGV.build_head?
<add> @co + "-HEAD" if ARGV.build_head?
<ide> end
<ide>
<ide> def cached_location | 1 |
Ruby | Ruby | add branch param | ddcb0519b6740eb4147e7520de424e895c0318bc | <ide><path>Library/Homebrew/dev-cmd/pr-publish.rb
<ide> def pr_publish_args
<ide> switch "--autosquash",
<ide> description: "If supported on the target tap, automatically reformat and reword commits "\
<ide> "in the pull request to our preferred format."
<add> flag "--branch=",
<add> description: "Branch to publish (default: `master`)."
<ide> flag "--message=",
<ide> depends_on: "--autosquash",
<ide> description: "Message to include when autosquashing revision bumps, deletions, and rebuilds."
<ide> def pr_publish
<ide>
<ide> tap = Tap.fetch(args.tap || CoreTap.instance.name)
<ide> workflow = args.workflow || "publish-commit-bottles.yml"
<del> ref = "master"
<add> ref = args.branch || "master"
<ide>
<ide> extra_args = []
<ide> extra_args << "--autosquash" if args.autosquash? | 1 |
Python | Python | remove uses of scalar aliases | 4be513d47212a28c000107d7c532c0a5a4312953 | <ide><path>numpy/core/tests/test_api.py
<ide> def test_array_astype_warning(t):
<ide>
<ide> @pytest.mark.parametrize(["dtype", "out_dtype"],
<ide> [(np.bytes_, np.bool_),
<del> (np.unicode, np.bool_),
<add> (np.unicode_, np.bool_),
<ide> (np.dtype("S10,S9"), np.dtype("?,?"))])
<ide> def test_string_to_boolean_cast(dtype, out_dtype):
<ide> """
<ide> def test_string_to_boolean_cast(dtype, out_dtype):
<ide>
<ide> @pytest.mark.parametrize(["dtype", "out_dtype"],
<ide> [(np.bytes_, np.bool_),
<del> (np.unicode, np.bool_),
<add> (np.unicode_, np.bool_),
<ide> (np.dtype("S10,S9"), np.dtype("?,?"))])
<ide> def test_string_to_boolean_cast_errors(dtype, out_dtype):
<ide> """
<ide><path>numpy/core/tests/test_scalar_ctors.py
<ide> def test_datetime(self):
<ide>
<ide> def test_bool(self):
<ide> with pytest.raises(TypeError):
<del> np.bool(False, garbage=True)
<add> np.bool_(False, garbage=True)
<ide>
<ide> def test_void(self):
<ide> with pytest.raises(TypeError):
<ide><path>numpy/core/tests/test_umath_complex.py
<ide> class TestSpecialComplexAVX(object):
<ide> @pytest.mark.parametrize("stride", [-4,-2,-1,1,2,4])
<ide> @pytest.mark.parametrize("astype", [np.complex64, np.complex128])
<ide> def test_array(self, stride, astype):
<del> arr = np.array([np.complex(np.nan , np.nan),
<del> np.complex(np.nan , np.inf),
<del> np.complex(np.inf , np.nan),
<del> np.complex(np.inf , np.inf),
<del> np.complex(0. , np.inf),
<del> np.complex(np.inf , 0.),
<del> np.complex(0. , 0.),
<del> np.complex(0. , np.nan),
<del> np.complex(np.nan , 0.)], dtype=astype)
<add> arr = np.array([complex(np.nan , np.nan),
<add> complex(np.nan , np.inf),
<add> complex(np.inf , np.nan),
<add> complex(np.inf , np.inf),
<add> complex(0. , np.inf),
<add> complex(np.inf , 0.),
<add> complex(0. , 0.),
<add> complex(0. , np.nan),
<add> complex(np.nan , 0.)], dtype=astype)
<ide> abs_true = np.array([np.nan, np.inf, np.inf, np.inf, np.inf, np.inf, 0., np.nan, np.nan], dtype=arr.real.dtype)
<del> sq_true = np.array([np.complex(np.nan, np.nan),
<del> np.complex(np.nan, np.nan),
<del> np.complex(np.nan, np.nan),
<del> np.complex(np.nan, np.inf),
<del> np.complex(-np.inf, np.nan),
<del> np.complex(np.inf, np.nan),
<del> np.complex(0., 0.),
<del> np.complex(np.nan, np.nan),
<del> np.complex(np.nan, np.nan)], dtype=astype)
<add> sq_true = np.array([complex(np.nan, np.nan),
<add> complex(np.nan, np.nan),
<add> complex(np.nan, np.nan),
<add> complex(np.nan, np.inf),
<add> complex(-np.inf, np.nan),
<add> complex(np.inf, np.nan),
<add> complex(0., 0.),
<add> complex(np.nan, np.nan),
<add> complex(np.nan, np.nan)], dtype=astype)
<ide> assert_equal(np.abs(arr[::stride]), abs_true[::stride])
<ide> with np.errstate(invalid='ignore'):
<ide> assert_equal(np.square(arr[::stride]), sq_true[::stride])
<ide><path>numpy/lib/tests/test_nanfunctions.py
<ide> def test__replace_nan():
<ide> """ Test that _replace_nan returns the original array if there are no
<ide> NaNs, not a copy.
<ide> """
<del> for dtype in [np.bool, np.int32, np.int64]:
<add> for dtype in [np.bool_, np.int32, np.int64]:
<ide> arr = np.array([0, 1], dtype=dtype)
<ide> result, mask = _replace_nan(arr, 0)
<ide> assert mask is None | 4 |
Go | Go | remove unnecessary signal conditional | c8ec36d1b9bfbe1e22acd0124409ecb5a109d406 | <ide><path>commands.go
<ide> func (cli *DockerCli) monitorTtySize(id string) error {
<ide> }
<ide> cli.resizeTty(id)
<ide>
<del> c := make(chan os.Signal, 1)
<del> signal.Notify(c, syscall.SIGWINCH)
<add> sigchan := make(chan os.Signal, 1)
<add> signal.Notify(sigchan, syscall.SIGWINCH)
<ide> go func() {
<del> for sig := range c {
<del> if sig == syscall.SIGWINCH {
<del> cli.resizeTty(id)
<del> }
<del> }
<add> <-sigchan
<add> cli.resizeTty(id)
<ide> }()
<ide> return nil
<ide> } | 1 |
Python | Python | remove unneeded stuffs | 17e078e3c614588b7b6c365336f44047c237e7bd | <ide><path>libcloud/container/drivers/rancher.py
<ide>
<ide> class RancherResponse(JsonResponse):
<ide>
<del> def parse_body(self):
<del> if len(self.body) == 0 and not self.parse_zero_length_body:
<del> return self.body
<del> valid_content_types = ['application/json',
<del> 'application/json; charset=utf-8']
<del> content_type = self.headers.get('content-type')
<del> if content_type in valid_content_types:
<del> return json.loads(self.body)
<del>
<ide> def parse_error(self):
<ide> if self.status == 401:
<ide> raise InvalidCredsError('Invalid credentials')
<ide> def __init__(self, key, secret, secure=True, host='localhost', port=443):
<ide> if host.startswith(prefix):
<ide> host = host.strip(prefix)
<ide>
<del> self.connection.host = host
<del> self.connection.port = port
<del> self.connection.secure = secure
<del>
<ide> # We only support environment api keys, meaning none of this:
<ide> # self.baseuri = "/v%s/projects/%s" % (self.version, project_id)
<ide> self.baseuri = "/v%s" % self.version | 1 |
Text | Text | add design documentation | 4f7eb502bf69ba32ab10a6e0ae8b7cbf133e3e8b | <ide><path>libnetwork/ROADMAP.md
<del># libnetwork: what's next?
<add># Roadmap
<ide>
<del>This document is a high-level overview of where we want to take libnetwork next.
<del>It is a curated selection of planned improvements which are either important, difficult, or both.
<add>Libnetwork is a young project and is still being defined.
<add>This document defines the high-level goals of the project and defines the release-relationship to the Docker Platform.
<ide>
<del>For a more complete view of planned and requested improvements, see [the Github issues](https://github.com/docker/libnetwork/issues).
<add>* [Goals](#goals)
<add>* [Project Planning](#project-planning): release-relationship to the Docker Platform.
<ide>
<del>To suggest changes to the roadmap, including additions, please write the change as if it were already in effect, and make a pull request.
<add>## Goals
<ide>
<del>## Container Network Model (CNM)
<add>- Combine the networking logic in Docker Engine and libcontainer in to a single, reusable library
<add>- Replace the networking subsystem of Docker Engine, with libnetwork
<add>- Define a flexible model that allows local and remote drivers to provide networking to containers
<add>- Provide a stand-alone tool for using/testing libnetwork
<ide>
<del>#### Concepts
<add>## Project Planning
<ide>
<del>1. Sandbox: An isolated environment. This is more or less a standard docker container.
<del>2. Endpoint: An addressable endpoint used for communication over a specific network. Endpoints join exactly one network and are expected to create a method of network communication for a container. Example : veth pair
<del>3. Network: A collection of endpoints that are able to communicate to each other. Networks are intended to be isolated from each other and to not cross communicate.
<del>
<del>#### axioms
<del>The container network model assumes the following axioms about how libnetwork provides network connectivity to containers:
<del>
<del>1. All containers on a specific network can communicate with each other freely.
<del>2. Multiple networks are the way to segment traffic between containers and should be supported by all drivers.
<del>3. Multiple endpoints per container are the way to join a container to multiple networks.
<del>4. An endpoint is added to a sandbox to provide it with network connectivity.
<del>
<del>## Bridge Driver using CNM
<del>Existing native networking functionality of Docker will be implemented as a Bridge Driver using the above CNM. In order to prove the effectiveness of the Bridge Driver, we will make the necessary modifications to Docker Daemon and LibContainer to replace the existing networking functionality with libnetwork & Bridge Driver.
<del>
<del>## Plugin support
<del>The Driver model provides a modular way to allow different networking solutions to be used as the backend, but is static in nature.
<del>Plugins promise to allow dynamic pluggable networking backends for libnetwork.
<del>There are other community efforts implementing Plugin support for the Docker platform, and the libnetwork project intends to make use of such support when it becomes available.
<add>Libnetwork versions do not map 1:1 with Docker Platform releases.
<add>Milestones and Project Pages are used to define the set of features that are included in each release.
<ide>
<add>| Platform Version | Libnetwork Version | Planning |
<add>|------------------|--------------------|----------|
<add>| Docker 1.7 | [0.3](https://github.com/docker/libnetwork/milestones/0.3) | [Project Page](https://github.com/docker/libnetwork/wiki/Docker-1.7-Project-Page) |
<add>| Docker 1.8 | [1.0](https://github.com/docker/libnetwork/milestones/1.0) | [Project Page](https://github.com/docker/libnetwork/wiki/Docker-1.8-Project-Page) |
<ide><path>libnetwork/docs/bridge.md
<add>Bridge Driver
<add>=============
<add>
<add>The bridge driver is an implementation that uses Linux Bridging and iptables to provide connectvity for containers
<add>It creates a single bridge, called `docker0` by default, and attaches a `veth pair` between the bridge and every endpoint.
<add>
<add>## Configuration
<add>
<add>The bridge driver supports configuration through the Docker Daemon flags.
<add>
<add>## Usage
<add>
<add>This driver is supported for the default "bridge" network only and it cannot be used for any other networks.
<ide><path>libnetwork/docs/design.md
<add>Design
<add>======
<add>
<add>The main goals of libnetwork are highlighted in the [roadmap](../ROADMAP.md).
<add>This document describes how libnetwork has been designed in order to acheive this.
<add>Requirements for individual releases can be found on the [Project Page](https://github.com/docker/libnetwork/wiki)
<add>
<add>## Legacy Docker Networking
<add>
<add>Prior to libnetwork a container's networking was handled in both Docker Engine and libcontainer.
<add>Docker Engine was responsible for providing the configuration of the container's networking stack.
<add>Libcontainer would then use this information to create the necessary networking devices and move them in to a network namespace.
<add>This namespace would then be used when the container is started.
<add>
<add>## The Container Network Model
<add>
<add>Libnetwork implements Container Network Model (CNM) which formalizes the steps required to provide networking for containers while providing an abstraction that can be used to support multiple network drivers. The CNM is built on 3 main components.
<add>
<add>**Sandbox**
<add>
<add>A Sandbox contains the configuration of a container's network stack.
<add>This includes management of the container's interfaces, routing table and DNS settings.
<add>An implementation of a Sandbox could be a Linux Network Namespace, a FreeBSD Jail or other similar concept.
<add>A Sandbox may contain *many* endpoints from *multiple* networks
<add>
<add>**Endpoint**
<add>
<add>An Endpoint joins a Sandbox to a Network.
<add>An implementation of an Endpoint could be a `veth` pair, an Open vSwitch internal port or similar.
<add>An Endpoint can belong to *only one* network but may only belong to *one* Sandbox
<add>
<add>**Network**
<add>
<add>A Network is a group of Endpoints that are able to communicate with each-other directly.
<add>An implementation of a Network could be a Linux bridge, a VLAN etc...
<add>Networks consist of *many* endpoints
<add>
<add>## API
<add>
<add>Consumers of the CNM, like Docker for example, interact through the following APIs
<add>
<add>The `NetworkController` object is created to manage the allocation of Networks and the binding of these Networks to a specific Driver
<add>Once a Network is created, `network.CreateEndpoint` can be called to create a new Endpoint in a given network.
<add>When an Endpoint exists, it can be joined to a Sandbox using `endpoint.Join(id)`. If no Sandbox exists, one will be created, but if the Sandbox already exists, the endpoint will be added there.
<add>The result of the Join operation is a Sandbox Key which identifies the Sandbox to the Operating System (e.g a path)
<add>This Key can be passed to the container runtime so the Sandbox is used when the container is started.
<add>
<add>When the container is stopped, `endpoint.Leave` will be called on each endpoint within the Sandbox
<add>Finally once, endpoint.
<add>
<add>## Component Lifecycle
<add>
<add>### Sandbox Lifecycle
<add>
<add>The Sandbox is created during the first `endpoint.Join` and deleted when `endpoint.Leave` is called on the last endpoint.
<add><TODO @mrjana or @mavenugo to more details>
<add>
<add>### Endpoint Lifecycle
<add>
<add>The Endpoint is created on `network.CreateEndpoint` and removed on `endpoint.Delete`
<add><TODO @mrjana or @mavenugo to add details on when this is called>
<add>
<add>### Network Lifecycle
<add>
<add>Networks are created when the CNM API call is invoked and are not cleaned up until an corresponding delete API call is made.
<add>
<add>## Implementation
<add>
<add>Networks and Endpoints are mostly implemented in drivers. For more information on these details, please see [the drivers section](#Drivers)
<add>
<add>## Sandbox
<add>
<add>Libnetwork provides an implementation of a Sandbox for Linux.
<add>This creates a Network Namespace for each sandbox which is uniquely identified by a path on the host filesystem.
<add>Netlink calls are used to move interfaces from the global namespace to the Sandbox namespace.
<add>Netlink is also used to manage the routing table in the namespace.
<add>
<add># Drivers
<add>
<add>## API
<add>
<add>The Driver API allows libnetwork to defer to a driver to provide Networking services.
<add>
<add>For Networks, drivers are notified on Create and Delete events
<add>
<add>For Endpoints, drivers are also notified on Create and Delete events
<add>
<add>## Implementations
<add>
<add>Libnetwork includes the following drivers:
<add>
<add>- null
<add>- bridge
<add>- overlay
<add>- remote
<add>
<add>### Null
<add>
<add>The null driver is a `noop` implementation of the driver API, used only in cases where no networking is desired.
<add>
<add>### Bridge
<add>
<add>The `bridge` driver provides a Linux-specific bridging implementation based on the Linux Bridge.
<add>For more details, please [see the Bridge Driver documentation](bridge.md)
<add>
<add>### Overlay
<add>
<add>The `overlay` driver implements networking that can span multiple hosts using overlay network encapsulations such as VXLAN.
<add>For more details on its design, please see the [Overlay Driver Design](overlay.md)
<add>
<add>### Remote
<add>
<add>The `remote` driver, provides a means of supporting drivers over a remote transport.
<add>This allows a driver to be written in a language of your choice.
<add>For further details, please see the [Remote Driver Design](remote.md)
<add>
<ide><path>libnetwork/docs/overlay.md
<add>Overlay Driver
<add>==============
<add>
<add>## Configuration
<add>
<add>## Usage
<ide><path>libnetwork/docs/remote.md
<add>Remote Driver
<add>=============
<add>
<add>## Configuration
<add>
<add>## Usage | 5 |
Javascript | Javascript | fix reopen project when there are no open windows | 9f453e64fe4f55c243c32e7c0cfeec2cbcb3278c | <ide><path>spec/main-process/atom-application.test.js
<ide> describe('AtomApplication', function () {
<ide> )
<ide> atomApplication.promptForPathToOpen.reset()
<ide> })
<add>
<add> it('allows reopening an existing project after all windows are closed', async () => {
<add> const tempDirPath = makeTempDir('reopen')
<add>
<add> const atomApplication = buildAtomApplication()
<add> sinon.stub(atomApplication, 'promptForPathToOpen')
<add>
<add> // Open a window and then close it, leaving the app running
<add> const [window] = await atomApplication.launch(parseCommandLine([]))
<add> await focusWindow(window)
<add> window.close()
<add> await window.closedPromise
<add>
<add> // Reopen one of the recent projects
<add> atomApplication.emit('application:reopen-project', { paths: [tempDirPath] })
<add>
<add> const windows = atomApplication.getAllWindows()
<add>
<add> assert(windows.length === 1)
<add>
<add> await focusWindow(windows[0])
<add>
<add> await conditionPromise(
<add> async () => (await getTreeViewRootDirectories(windows[0])).length === 1
<add> )
<add>
<add> // Check that the project was opened correctly.
<add> assert.deepEqual(
<add> await evalInWebContents(
<add> windows[0].browserWindow.webContents,
<add> send => {
<add> send(atom.project.getPaths())
<add> }
<add> ),
<add> [tempDirPath]
<add> )
<add> })
<ide> }
<ide>
<ide> function buildAtomApplication (params = {}) {
<ide><path>spec/reopen-project-menu-manager-spec.js
<ide> describe('ReopenProjectMenuManager', () => {
<ide> const first = projectsMenu.submenu[0]
<ide> expect(first.label).toBe('/a')
<ide> expect(first.command).toBe('application:reopen-project')
<del> expect(first.commandDetail).toEqual({ index: 0 })
<add> expect(first.commandDetail).toEqual({ index: 0, paths: ['/a'] })
<ide>
<ide> const second = projectsMenu.submenu[1]
<ide> expect(second.label).toBe('b, c:\\')
<ide> expect(second.command).toBe('application:reopen-project')
<del> expect(second.commandDetail).toEqual({ index: 1 })
<add> expect(second.commandDetail).toEqual({ index: 1, paths: ['/b', 'c:\\'] })
<ide> })
<ide>
<ide> it("adds only the number of menu items specified in the 'core.reopenProjectMenuCount' config", () => {
<ide> describe('ReopenProjectMenuManager', () => {
<ide> const first = projectsMenu.submenu[0]
<ide> expect(first.label).toBe('/a')
<ide> expect(first.command).toBe('application:reopen-project')
<del> expect(first.commandDetail).toEqual({ index: 0 })
<add> expect(first.commandDetail).toEqual({ index: 0, paths: ['/a'] })
<ide>
<ide> const second = projectsMenu.submenu[1]
<ide> expect(second.label).toBe('b, c:\\')
<ide> expect(second.command).toBe('application:reopen-project')
<del> expect(second.commandDetail).toEqual({ index: 1 })
<add> expect(second.commandDetail).toEqual({ index: 1, paths: ['/b', 'c:\\'] })
<ide> })
<ide> })
<ide>
<ide> describe('ReopenProjectMenuManager', () => {
<ide> const first = recentMenu.submenu[0]
<ide> expect(first.label).toBe('/users/neila')
<ide> expect(first.command).toBe('application:reopen-project')
<del> expect(first.commandDetail).toEqual({ index: 0 })
<add> expect(first.commandDetail).toEqual({ index: 0, paths: ['/users/neila'] })
<ide>
<ide> const second = recentMenu.submenu[1]
<ide> expect(second.label).toBe('buzza, michaelc')
<ide> expect(second.command).toBe('application:reopen-project')
<del> expect(second.commandDetail).toEqual({ index: 1 })
<add> expect(second.commandDetail).toEqual({
<add> index: 1,
<add> paths: ['/users/buzza', 'users/michaelc']
<add> })
<ide> })
<ide> })
<ide>
<ide><path>src/main-process/atom-application.js
<ide> class AtomApplication extends EventEmitter {
<ide> this.on('application:check-for-update', () => this.autoUpdateManager.check())
<ide>
<ide> if (process.platform === 'darwin') {
<add> this.on('application:reopen-project', ({ paths }) => {
<add> this.openPaths({ pathsToOpen: paths })
<add> })
<add>
<ide> this.on('application:open', () => this.promptForPathToOpen('all', getLoadSettings(), getDefaultPath()))
<ide> this.on('application:open-file', () => this.promptForPathToOpen('file', getLoadSettings(), getDefaultPath()))
<ide> this.on('application:open-folder', () => this.promptForPathToOpen('folder', getLoadSettings(), getDefaultPath()))
<ide><path>src/reopen-project-menu-manager.js
<ide> class ReopenProjectMenuManager {
<ide> submenu: projects.map((project, index) => ({
<ide> label: this.createLabel(project),
<ide> command: 'application:reopen-project',
<del> commandDetail: {index: index}
<add> commandDetail: { index: index, paths: project.paths }
<ide> }))
<ide> }
<ide> ] | 4 |
Python | Python | fix nasty `bnb` bug | 81d82e4f783925d100365458ccd8eea9aa16d0ab | <ide><path>src/transformers/modeling_utils.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> load_in_8bit=load_in_8bit,
<ide> )
<ide>
<del> cls.is_loaded_in_8bit = load_in_8bit
<add> model.is_loaded_in_8bit = load_in_8bit
<ide>
<ide> # make sure token embedding weights are still tied if needed
<ide> model.tie_weights() | 1 |
Python | Python | fix mypy in providers/grpc and providers/imap | 4fa9cfd7de13cd79956fbb68f8416a5a019465a4 | <ide><path>airflow/providers/grpc/operators/grpc.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence
<add>from typing import TYPE_CHECKING, Any, Callable, List, Optional, Sequence
<ide>
<ide> from airflow.models import BaseOperator
<ide> from airflow.providers.grpc.hooks.grpc import GrpcHook
<ide> def execute(self, context: 'Context') -> None:
<ide> for response in responses:
<ide> self._handle_response(response, context)
<ide>
<del> def _handle_response(self, response: Any, context: Dict) -> None:
<add> def _handle_response(self, response: Any, context: 'Context') -> None:
<ide> if self.log_response:
<ide> self.log.info(repr(response))
<ide> if self.response_callback:
<ide><path>airflow/providers/imap/hooks/imap.py
<ide> def get_conn(self) -> 'ImapHook':
<ide> """
<ide> if not self.mail_client:
<ide> conn = self.get_connection(self.imap_conn_id)
<del> self.mail_client = imaplib.IMAP4_SSL(conn.host, conn.port or imaplib.IMAP4_SSL_PORT)
<add> if conn.port:
<add> self.mail_client = imaplib.IMAP4_SSL(conn.host, conn.port)
<add> else:
<add> self.mail_client = imaplib.IMAP4_SSL(conn.host)
<ide> self.mail_client.login(conn.login, conn.password)
<ide>
<ide> return self | 2 |
Java | Java | add support for rx.completable as return value | 143b5c89dd7c9e9d603ccb289943ae45e262c8c5 | <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageWriterResultHandler.java
<ide> protected Mono<Void> writeBody(Object body, MethodParameter bodyType, ServerWebE
<ide> ResolvableType elementType;
<ide> if (adapter != null) {
<ide> publisher = adapter.toPublisher(body);
<del> elementType = ResolvableType.forMethodParameter(bodyType).getGeneric(0);
<add> elementType = adapter.getDescriptor().isNoValue() ?
<add> ResolvableType.forClass(Void.class) :
<add> ResolvableType.forMethodParameter(bodyType).getGeneric(0);
<ide> }
<ide> else {
<ide> publisher = Mono.justOrEmpty(body);
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandler.java
<ide> package org.springframework.web.reactive.result.method.annotation;
<ide>
<ide> import java.util.List;
<add>import java.util.Optional;
<ide>
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.MethodParameter;
<add>import org.springframework.core.ReactiveAdapter;
<ide> import org.springframework.core.ReactiveAdapterRegistry;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> private boolean isHttpEntityType(HandlerResult result) {
<ide> return true;
<ide> }
<ide> else {
<del> if (getReactiveAdapterRegistry().getAdapterFrom(rawClass, result.getReturnValue()) != null) {
<add> Optional<Object> optional = result.getReturnValue();
<add> ReactiveAdapter adapter = getReactiveAdapterRegistry().getAdapterFrom(rawClass, optional);
<add> if (adapter != null && !adapter.getDescriptor().isNoValue()) {
<ide> ResolvableType genericType = result.getReturnType().getGeneric(0);
<ide> if (HttpEntity.class.isAssignableFrom(genericType.getRawClass())) {
<ide> return true;
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandler.java
<ide> public boolean supports(HandlerResult result) {
<ide> return true;
<ide> }
<ide> else {
<del> Optional<Object> returnValue = result.getReturnValue();
<del> ReactiveAdapter adapter = getReactiveAdapterRegistry().getAdapterFrom(returnType, returnValue);
<del> if (adapter != null && !adapter.getDescriptor().isMultiValue()) {
<add> Optional<Object> optional = result.getReturnValue();
<add> ReactiveAdapter adapter = getReactiveAdapterRegistry().getAdapterFrom(returnType, optional);
<add> if (adapter != null &&
<add> !adapter.getDescriptor().isMultiValue() &&
<add> !adapter.getDescriptor().isNoValue()) {
<add>
<ide> ResolvableType genericType = result.getReturnType().getGeneric(0);
<ide> return isSupportedType(genericType.getRawClass());
<ide> }
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandler.java
<ide> public boolean supports(HandlerResult result) {
<ide> if (hasModelAttributeAnnotation(result)) {
<ide> return true;
<ide> }
<del> if (isSupportedType(clazz)) {
<del> return true;
<add> Optional<Object> optional = result.getReturnValue();
<add> ReactiveAdapter adapter = getReactiveAdapterRegistry().getAdapterFrom(clazz, optional);
<add> if (adapter != null) {
<add> if (adapter.getDescriptor().isNoValue()) {
<add> return true;
<add> }
<add> else {
<add> clazz = result.getReturnType().getGeneric(0).getRawClass();
<add> return isSupportedType(clazz);
<add> }
<ide> }
<del> if (getReactiveAdapterRegistry().getAdapterFrom(clazz, result.getReturnValue()) != null) {
<del> clazz = result.getReturnType().getGeneric(0).getRawClass();
<del> return isSupportedType(clazz);
<add> else if (isSupportedType(clazz)) {
<add> return true;
<ide> }
<ide> return false;
<ide> }
<ide> public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result)
<ide> else {
<ide> valueMono = Mono.empty();
<ide> }
<del> elementType = returnType.getGeneric(0);
<add> elementType = adapter.getDescriptor().isNoValue() ?
<add> ResolvableType.forClass(Void.class) : returnType.getGeneric(0);
<ide> }
<ide> else {
<ide> valueMono = Mono.justOrEmpty(result.getReturnValue());
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/MessageWriterResultHandlerTests.java
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.TestSubscriber;
<add>import rx.Completable;
<ide> import rx.Observable;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> public void useDefaultCharset() throws Exception {
<ide> public void voidReturnType() throws Exception {
<ide> testVoidReturnType(null, ResolvableType.forType(void.class));
<ide> testVoidReturnType(Mono.empty(), ResolvableType.forClassWithGenerics(Mono.class, Void.class));
<add> testVoidReturnType(Completable.complete(), ResolvableType.forClass(Completable.class));
<ide> testVoidReturnType(Flux.empty(), ResolvableType.forClassWithGenerics(Flux.class, Void.class));
<ide> testVoidReturnType(Observable.empty(), ResolvableType.forClassWithGenerics(Observable.class, Void.class));
<ide> }
<ide> void voidReturn() { }
<ide>
<ide> Mono<Void> monoVoid() { return null; }
<ide>
<add> Completable completable() { return null; }
<add>
<ide> Flux<Void> fluxVoid() { return null; }
<ide>
<ide> Observable<Void> observableVoid() { return null; }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<add>import rx.Completable;
<ide> import rx.Observable;
<ide> import rx.Single;
<ide>
<ide> import org.springframework.web.bind.annotation.RestController;
<ide> import org.springframework.web.reactive.config.WebReactiveConfiguration;
<ide>
<del>import static java.util.Arrays.*;
<del>import static org.junit.Assert.*;
<del>import static org.springframework.http.MediaType.*;
<add>import static java.util.Arrays.asList;
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<add>import static org.springframework.http.MediaType.APPLICATION_XML;
<ide>
<ide>
<ide> /**
<ide> public void personCreateWithPublisherXml() throws Exception {
<ide> assertEquals(2, getApplicationContext().getBean(PersonCreateController.class).persons.size());
<ide> }
<ide>
<add> @Test
<add> public void personCreateWithMono() throws Exception {
<add> ResponseEntity<Void> entity = performPost(
<add> "/person-create/mono", JSON, new Person("Robert"), null, Void.class);
<add>
<add> assertEquals(HttpStatus.OK, entity.getStatusCode());
<add> assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size());
<add> }
<add>
<add> @Test
<add> public void personCreateWithSingle() throws Exception {
<add> ResponseEntity<Void> entity = performPost(
<add> "/person-create/single", JSON, new Person("Robert"), null, Void.class);
<add>
<add> assertEquals(HttpStatus.OK, entity.getStatusCode());
<add> assertEquals(1, getApplicationContext().getBean(PersonCreateController.class).persons.size());
<add> }
<add>
<ide> @Test
<ide> public void personCreateWithFluxJson() throws Exception {
<ide> ResponseEntity<Void> entity = performPost("/person-create/flux", JSON,
<ide> private static class PersonCreateController {
<ide> final List<Person> persons = new ArrayList<>();
<ide>
<ide> @PostMapping("/publisher")
<del> public Publisher<Void> createWithPublisher(@RequestBody Publisher<Person> personStream) {
<del> return Flux.from(personStream).doOnNext(persons::add).then();
<add> public Publisher<Void> createWithPublisher(@RequestBody Publisher<Person> publisher) {
<add> return Flux.from(publisher).doOnNext(persons::add).then();
<add> }
<add>
<add> @PostMapping("/mono")
<add> public Mono<Void> createWithMono(@RequestBody Mono<Person> mono) {
<add> return mono.doOnNext(persons::add).then();
<add> }
<add>
<add> @PostMapping("/single")
<add> public Completable createWithSingle(@RequestBody Single<Person> single) {
<add> return single.map(persons::add).toCompletable();
<ide> }
<ide>
<ide> @PostMapping("/flux")
<del> public Mono<Void> createWithFlux(@RequestBody Flux<Person> personStream) {
<del> return personStream.doOnNext(persons::add).then();
<add> public Mono<Void> createWithFlux(@RequestBody Flux<Person> flux) {
<add> return flux.doOnNext(persons::add).then();
<ide> }
<ide>
<ide> @PostMapping("/observable")
<del> public Observable<Void> createWithObservable(@RequestBody Observable<Person> personStream) {
<del> return personStream.toList().doOnNext(persons::addAll).flatMap(document -> Observable.empty());
<add> public Observable<Void> createWithObservable(@RequestBody Observable<Person> observable) {
<add> return observable.toList().doOnNext(persons::addAll).flatMap(document -> Observable.empty());
<ide> }
<ide> }
<ide>
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseBodyResultHandlerTests.java
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Mono;
<add>import rx.Completable;
<add>import rx.Single;
<ide>
<ide> import org.springframework.core.codec.ByteBufferEncoder;
<ide> import org.springframework.core.codec.CharSequenceEncoder;
<ide> import org.springframework.web.server.adapter.DefaultServerWebExchange;
<ide> import org.springframework.web.server.session.MockWebSessionManager;
<ide>
<del>import static org.junit.Assert.*;
<add>import static org.junit.Assert.assertEquals;
<ide>
<ide>
<ide> /**
<ide> public void supports() throws NoSuchMethodException {
<ide>
<ide> controller = new TestRestController();
<ide> testSupports(controller, "handleToString", true);
<add> testSupports(controller, "handleToMonoString", true);
<add> testSupports(controller, "handleToSingleString", true);
<add> testSupports(controller, "handleToCompletable", true);
<ide> testSupports(controller, "handleToResponseEntity", false);
<ide> testSupports(controller, "handleToMonoResponseEntity", false);
<ide> }
<ide> public String handleToString() {
<ide> return null;
<ide> }
<ide>
<add> public Mono<String> handleToMonoString() {
<add> return null;
<add> }
<add>
<add> public Single<String> handleToSingleString() {
<add> return null;
<add> }
<add>
<add> public Completable handleToCompletable() {
<add> return null;
<add> }
<add>
<ide> public ResponseEntity<String> handleToResponseEntity() {
<ide> return null;
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.TestSubscriber;
<add>import rx.Completable;
<ide> import rx.Single;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> public void supports() throws NoSuchMethodException {
<ide> type = forClassWithGenerics(CompletableFuture.class, responseEntity(String.class));
<ide> assertTrue(this.resultHandler.supports(handlerResult(value, type)));
<ide>
<add> // False
<add>
<ide> type = ResolvableType.forClass(String.class);
<ide> assertFalse(this.resultHandler.supports(handlerResult(value, type)));
<add>
<add> type = ResolvableType.forClass(Completable.class);
<add> assertFalse(this.resultHandler.supports(handlerResult(value, type)));
<ide> }
<ide>
<ide> @Test
<ide> private static class TestController {
<ide> CompletableFuture<ResponseEntity<String>> completableFuture() { return null; }
<ide>
<ide> String string() { return null; }
<add>
<add> Completable completable() { return null; }
<ide> }
<ide>
<ide> }
<ide><path>spring-web-reactive/src/test/java/org/springframework/web/reactive/result/view/ViewResolutionResultHandlerTests.java
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.test.TestSubscriber;
<add>import rx.Completable;
<ide> import rx.Single;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> public void supports() throws Exception {
<ide> testSupports(ResolvableType.forClassWithGenerics(Mono.class, View.class), true);
<ide> testSupports(ResolvableType.forClassWithGenerics(Single.class, String.class), true);
<ide> testSupports(ResolvableType.forClassWithGenerics(Single.class, View.class), true);
<add> testSupports(ResolvableType.forClassWithGenerics(Mono.class, Void.class), true);
<add> testSupports(ResolvableType.forClass(Completable.class), true);
<ide> testSupports(ResolvableType.forClass(Model.class), true);
<ide> testSupports(ResolvableType.forClass(Map.class), true);
<ide> testSupports(ResolvableType.forClass(TestBean.class), true);
<ide> public void handleWithMultipleResolvers() throws Exception {
<ide> public void defaultViewName() throws Exception {
<ide> testDefaultViewName(null, ResolvableType.forClass(String.class));
<ide> testDefaultViewName(Mono.empty(), ResolvableType.forClassWithGenerics(Mono.class, String.class));
<add> testDefaultViewName(Mono.empty(), ResolvableType.forClassWithGenerics(Mono.class, Void.class));
<add> testDefaultViewName(Completable.complete(), ResolvableType.forClass(Completable.class));
<ide> }
<ide>
<ide> private void testDefaultViewName(Object returnValue, ResolvableType type)
<ide> private static class TestController {
<ide>
<ide> Mono<View> monoView() { return null; }
<ide>
<add> Mono<Void> monoVoid() { return null; }
<add>
<ide> Single<String> singleString() { return null; }
<ide>
<ide> Single<View> singleView() { return null; }
<ide>
<add> Completable completable() { return null; }
<add>
<ide> Model model() { return null; }
<ide>
<ide> Map map() { return null; } | 9 |
Javascript | Javascript | make dot optional when parsing months | 6fec7d3f836e6aa5294036b897362e26d5349b98 | <ide><path>src/locale/fr.js
<ide>
<ide> import moment from '../moment';
<ide>
<add>var monthsStrictRegex = /^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i,
<add> monthsShortStrictRegex = /(janv\.?|févr\.?|mars|avr\.?|mai|juin|juil\.?|août|sept\.?|oct\.?|nov\.?|déc\.?)/i,
<add> monthsRegex = /(janv\.?|févr\.?|mars|avr\.?|mai|juin|juil\.?|août|sept\.?|oct\.?|nov\.?|déc\.?|janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i,
<add> monthsParse = [
<add> /^janv/i,
<add> /^févr/i,
<add> /^mars/i,
<add> /^avr/i,
<add> /^mai/i,
<add> /^juin/i,
<add> /^juil/i,
<add> /^août/i,
<add> /^sept/i,
<add> /^oct/i,
<add> /^nov/i,
<add> /^déc/i,
<add> ];
<add>
<ide> export default moment.defineLocale('fr', {
<ide> months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split(
<ide> '_'
<ide> ),
<ide> monthsShort: 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split(
<ide> '_'
<ide> ),
<del> monthsParseExact: true,
<add> monthsRegex: monthsRegex,
<add> monthsShortRegex: monthsRegex,
<add> monthsStrictRegex: monthsStrictRegex,
<add> monthsShortStrictRegex: monthsShortStrictRegex,
<add> monthsParse: monthsParse,
<add> longMonthsParse: monthsParse,
<add> shortMonthsParse: monthsParse,
<ide> weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
<ide> weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
<ide> weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),
<ide><path>src/test/locale/fr.js
<ide> test('parse', function (assert) {
<ide> var i,
<ide> tests = 'janvier janv._février févr._mars mars_avril avr._mai mai_juin juin_juillet juil._août août_septembre sept._octobre oct._novembre nov._décembre déc.'.split(
<ide> '_'
<add> ),
<add> testsNoDot = 'janvier janv_février févr_mars mars_avril avr_mai mai_juin juin_juillet juil_août août_septembre sept_octobre oct_novembre nov_décembre déc'.split(
<add> '_'
<ide> );
<ide>
<ide> function equalTest(input, mmm, i) {
<ide> test('parse', function (assert) {
<ide> equalTestStrict(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<ide> equalTestStrict(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<ide> }
<add>
<add> for (i = 0; i < 12; i++) {
<add> testsNoDot[i] = testsNoDot[i].split(' ');
<add> equalTest(testsNoDot[i][0], 'MMM', i);
<add> equalTest(testsNoDot[i][1], 'MMM', i);
<add> equalTest(testsNoDot[i][0], 'MMMM', i);
<add> equalTest(testsNoDot[i][1], 'MMMM', i);
<add> equalTest(testsNoDot[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(testsNoDot[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(testsNoDot[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(testsNoDot[i][1].toLocaleUpperCase(), 'MMMM', i);
<add>
<add> equalTestStrict(testsNoDot[i][1], 'MMM', i);
<add> equalTestStrict(testsNoDot[i][0], 'MMMM', i);
<add> equalTestStrict(testsNoDot[i][1].toLocaleLowerCase(), 'MMM', i);
<add> equalTestStrict(testsNoDot[i][1].toLocaleUpperCase(), 'MMM', i);
<add> equalTestStrict(testsNoDot[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTestStrict(testsNoDot[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> }
<ide> });
<ide>
<ide> test('format', function (assert) { | 2 |
Go | Go | prefer crypto rand seed for pkg/rand | 4742a3964fd276a825a5ff4d1cf8417ae88abcb1 | <ide><path>pkg/random/random.go
<ide> package random
<ide>
<ide> import (
<add> cryptorand "crypto/rand"
<ide> "io"
<add> "math"
<add> "math/big"
<ide> "math/rand"
<ide> "sync"
<ide> "time"
<ide> func (r *lockedSource) Seed(seed int64) {
<ide> // NewSource returns math/rand.Source safe for concurrent use and initialized
<ide> // with current unix-nano timestamp
<ide> func NewSource() rand.Source {
<add> var seed int64
<add> if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil {
<add> // This should not happen, but worst-case fallback to time-based seed.
<add> seed = time.Now().UnixNano()
<add> } else {
<add> seed = cryptoseed.Int64()
<add> }
<ide> return &lockedSource{
<del> src: rand.NewSource(time.Now().UnixNano()),
<add> src: rand.NewSource(seed),
<ide> }
<ide> }
<ide> | 1 |
Mixed | Text | fix coffeescript syntax in code examples | 502d47d7f6b5bf9533676c44b9e325dc3feca3c0 | <ide><path>README.md
<ide> class WebNotificationsChannel < ApplicationCable::Channel
<ide> ```coffeescript
<ide> # Somewhere in your app this is called, perhaps from a NewCommentJob
<ide> ActionCable.server.broadcast \
<del> "web_notifications_1", { title: 'New things!', body: 'All shit fit for print' }
<add> "web_notifications_1", { title: 'New things!', body: 'All shit fit for print' }
<ide>
<ide> # Client-side which assumes you've already requested the right to send web notifications
<ide> App.cable.subscriptions.create "WebNotificationsChannel",
<del> received: (data) ->
<del> web_notification = new Notification data['title'], body: data['body']
<add> received: (data) ->
<add> new Notification data['title'], body: data['body']
<ide> ```
<ide>
<ide> The `ActionCable.server.broadcast` call places a message in the Redis' pubsub queue under the broadcasting name of `web_notifications_1`.
<ide><path>lib/action_cable/server/broadcasting.rb
<ide> module Server
<ide> # # Client-side coffescript which assumes you've already requested the right to send web notifications
<ide> # App.cable.subscriptions.create "WebNotificationsChannel",
<ide> # received: (data) ->
<del> # web_notification = new Notification data['title'], body: data['body']
<add> # new Notification data['title'], body: data['body']
<ide> module Broadcasting
<ide> # Broadcast a hash directly to a named <tt>broadcasting</tt>. It'll automatically be JSON encoded.
<ide> def broadcast(broadcasting, message) | 2 |
Text | Text | add release notes for 1.6.5 | 1991e77e43e09b55792af5ca082482d2f0cfaf05 | <ide><path>CHANGELOG.md
<add><a name="1.6.5"></a>
<add># 1.6.5 toffee-salinization (2017-07-03)
<add>
<add>
<add>## Bug Fixes
<add>- **core:**
<add> - correctly detect Error instances from different contexts
<add> ([6daca0](https://github.com/angular/angular.js/commit/6daca023e42098f7098b9bf153c8e53a17af84f1),
<add> [#15868](https://github.com/angular/angular.js/issues/15868),
<add> [#15872](https://github.com/angular/angular.js/issues/15872))
<add> - deprecate `angular.merge`
<add> ([dc41f4](https://github.com/angular/angular.js/commit/dc41f465baae9bc91418a61f446596157c530b6e),
<add> [#12653](https://github.com/angular/angular.js/issues/12653),
<add> [#14941](https://github.com/angular/angular.js/issues/14941),
<add> [#15180](https://github.com/angular/angular.js/issues/15180),
<add> [#15992](https://github.com/angular/angular.js/issues/15992),
<add> [#16036](https://github.com/angular/angular.js/issues/16036))
<add>- **ngOptions:**
<add> - re-render after empty option has been removed
<add> ([510d0f](https://github.com/angular/angular.js/commit/510d0f946fa1a443ad43fa31bc9337676ef31332))
<add> - allow empty option to be removed and re-added
<add> ([71b4da](https://github.com/angular/angular.js/commit/71b4daa4e10b6912891927ee2a7930c604b538f8))
<add> - select unknown option if unmatched model does not match empty option
<add> ([17d34b](https://github.com/angular/angular.js/commit/17d34b7a983a0ef63f6cf404490385c696fb0da1))
<add>- **orderBy:** guarantee stable sort
<add> ([e50ed4](https://github.com/angular/angular.js/commit/e50ed4da9e8177168f67da68bdf02f07da4e7bcf),
<add> [#14881](https://github.com/angular/angular.js/issues/14881),
<add> [#15914](https://github.com/angular/angular.js/issues/15914))
<add>- **$parse:**
<add> - do not shallow-watch inputs to one-time intercepted expressions
<add> ([6e3b5a](https://github.com/angular/angular.js/commit/6e3b5a57cd921823f3eca7200a79ac5c2ef0567a))
<add> - standardize one-time literal vs non-literal and interceptors
<add> ([f003d9](https://github.com/angular/angular.js/commit/f003d93a3dd052dccddef41125d9c51034ac3605))
<add> - do not shallow-watch inputs when wrapped in an interceptor fn
<add> ([aac562](https://github.com/angular/angular.js/commit/aac5623247a86681cbe0e1c8179617b816394c1d),
<add> [#15905](https://github.com/angular/angular.js/issues/15905))
<add> - always re-evaluate filters within literals when an input is an object
<add> ([ec9768](https://github.com/angular/angular.js/commit/ec97686f2f4a5481cc806462313a664fc7a1c893),
<add> [#15964](https://github.com/angular/angular.js/issues/15964),
<add> [#15990](https://github.com/angular/angular.js/issues/15990))
<add>- **$sanitize:** use appropriate inert document strategy for Firefox and Safari
<add> ([8f31f1](https://github.com/angular/angular.js/commit/8f31f1ff43b673a24f84422d5c13d6312b2c4d94))
<add>- **$timeout/$interval:** do not trigger a digest on cancel
<add> ([a222d0](https://github.com/angular/angular.js/commit/a222d0b452622624dc498ef0b9d3c43647fd4fbc),
<add> [#16057](https://github.com/angular/angular.js/issues/16057),
<add> [#16064](https://github.com/angular/angular.js/issues/16064))<br>
<add> This change might affect the use of `$timeout.flush()` in unit tests. See the commit message for
<add> more info.
<add>- **ngMock/$interval:** add support for zero-delay intervals in tests
<add> ([a1e3f8](https://github.com/angular/angular.js/commit/a1e3f8728e0a80396f980e48f8dc68dde6721b2b),
<add> [#15952](https://github.com/angular/angular.js/issues/15952),
<add> [#15953](https://github.com/angular/angular.js/issues/15953))
<add>- **angular-loader:** do not depend on "closure" globals that may not be available
<add> ([a3226d](https://github.com/angular/angular.js/commit/a3226d01fadaf145713518dc5b8022b581c34e81),
<add> [#15880](https://github.com/angular/angular.js/issues/15880),
<add> [#15881](https://github.com/angular/angular.js/issues/15881))
<add>
<add>
<add>## New Features
<add>- **select:** expose info about selection state in controller
<add> ([0b962d](https://github.com/angular/angular.js/commit/0b962d4881e98327a91c37f7317da557aa991663),
<add> [#13172](https://github.com/angular/angular.js/issues/13172),
<add> [#10127](https://github.com/angular/angular.js/issues/10127))
<add>- **$animate:** add support for `customFilter`
<add> ([ab114a](https://github.com/angular/angular.js/commit/ab114af8508bdbdb1fa5fd1e070d08818d882e28),
<add> [#14891](https://github.com/angular/angular.js/issues/14891))
<add>- **$compile:** overload `.component()` to accept object map of components
<add> ([210112](https://github.com/angular/angular.js/commit/2101126ce72308d8fc468ca2411bb9972e614f79),
<add> [#14579](https://github.com/angular/angular.js/issues/14579),
<add> [#16062](https://github.com/angular/angular.js/issues/16062))
<add>- **$log:** log all parameters in IE 9, not just the first two.
<add> ([3671a4](https://github.com/angular/angular.js/commit/3671a43be43d05b00c90dfb3a3f746c013139581))
<add>- **ngMock:** describe unflushed http requests
<add> ([d9128e](https://github.com/angular/angular.js/commit/d9128e7b2371ab2bb5169ba854b21c78baa784d2),
<add> [#10596](https://github.com/angular/angular.js/issues/10596),
<add> [#15928](https://github.com/angular/angular.js/issues/15928))
<add>
<add>
<add>## Performance Improvements
<add>- **ngOptions:** prevent initial options repainting
<add> ([ff52b1](https://github.com/angular/angular.js/commit/ff52b188a759f2cc7ee6ee78a8c646c2354a47eb),
<add> [#15801](https://github.com/angular/angular.js/issues/15801),
<add> [#15812](https://github.com/angular/angular.js/issues/15812),
<add> [#16071](https://github.com/angular/angular.js/issues/16071))
<add>- **$animate:**
<add> - avoid unnecessary computations if animations are globally disabled
<add> ([ce5ffb](https://github.com/angular/angular.js/commit/ce5ffbf667464bd58eae4c4af0917eb2685f1f6a),
<add> [#14914](https://github.com/angular/angular.js/issues/14914))
<add> - do not retrieve `className` unless `classNameFilter` is used
<add> ([275978](https://github.com/angular/angular.js/commit/27597887379a1904cd86832602e286894b449a75))
<add>
<add>
<add>
<ide> <a name="1.6.4"></a>
<ide> # 1.6.4 phenomenal-footnote (2017-03-31)
<ide> | 1 |
Ruby | Ruby | make sure thread runs | 12e330fc566489d0a40b360e179037370d10403b | <ide><path>test/visitors/test_to_sql.rb
<ide> module Visitors
<ide> @visitor.send(:visit_Arel_Attributes_Attribute, @attr)
<ide> end
<ide>
<add> sleep 0.2
<ide> @visitor.accept(@table[:name])
<ide> assert_equal(:string, @visitor.last_column.type)
<ide> visit_integer_column.run | 1 |
Javascript | Javascript | fix guard expression in timer.unref() | ebf9f297b30d6cf2e5060da91d63cebbedc448e2 | <ide><path>lib/timers.js
<ide> var Timeout = function(after) {
<ide> };
<ide>
<ide> Timeout.prototype.unref = function() {
<del> if (!this._handle) {
<add> if (this._handle) {
<add> this._handle.unref();
<add> } else if (typeof(this._onTimeout) === 'function') {
<ide> var now = Timer.now();
<ide> if (!this._idleStart) this._idleStart = now;
<ide> var delay = this._idleStart + this._idleTimeout - now;
<ide> Timeout.prototype.unref = function() {
<ide> this._handle.start(delay, 0);
<ide> this._handle.domain = this.domain;
<ide> this._handle.unref();
<del> } else {
<del> this._handle.unref();
<ide> }
<ide> };
<ide>
<ide><path>test/parallel/test-timers-unref-call.js
<add>// Copyright (c) 2014, StrongLoop Inc.
<add>//
<add>// Permission to use, copy, modify, and/or distribute this software for any
<add>// purpose with or without fee is hereby granted, provided that the above
<add>// copyright notice and this permission notice appear in all copies.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
<add>// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
<add>// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
<add>// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
<add>// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
<add>// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
<add>// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
<add>
<add>var common = require('../common');
<add>
<add>var Timer = process.binding('timer_wrap').Timer;
<add>Timer.now = function() { return ++Timer.now.ticks; };
<add>Timer.now.ticks = 0;
<add>
<add>var t = setInterval(function() {}, 1);
<add>var o = { _idleStart: 0, _idleTimeout: 1 };
<add>t.unref.call(o);
<add>
<add>setTimeout(clearInterval.bind(null, t), 2); | 2 |
Javascript | Javascript | fix all the linting errors in boot | 7c2f171d311ff693756fbba0ea939ea50d171462 | <ide><path>server/boot/challenge.js
<ide> exports.returnCurrentChallenge = function(req, res, next) {
<ide> exports.returnIndividualChallenge = function(req, res, next) {
<ide> var dashedName = req.params.challengeName;
<ide>
<del> var challengeName = /^(bonfire|waypoint|zipline|basejump)/i.test(dashedName) ? dashedName
<del> .replace(/\-/g, ' ')
<del> .split(' ')
<del> .slice(1)
<del> .join(' ')
<del> : dashedName.replace(/\-/g, ' ');
<add> var challengeName =
<add> (/^(bonfire|waypoint|zipline|basejump)/i).test(dashedName) ?
<add> dashedName
<add> .replace(/\-/g, ' ')
<add> .split(' ')
<add> .slice(1)
<add> .join(' ') :
<add> dashedName.replace(/\-/g, ' ');
<ide>
<ide> Challenge.find({'name': new RegExp(challengeName, 'i')},
<ide> function(err, challengeFromMongo) {
<ide> exports.returnIndividualChallenge = function(req, res, next) {
<ide> .replace(/[^a-z0-9\-\.]/gi, '');
<ide> if (dashedNameFull !== dashedName) {
<ide> return res.redirect('../challenges/' + dashedNameFull);
<del> } else {
<del> if (req.user) {
<del> req.user.currentChallenge = {
<del> challengeId: challenge._id,
<del> challengeName: challenge.name,
<del> challengeBlock: R.head(R.flatten(Object.keys(challengeMapWithIds).
<del> map(function (key) {
<del> return challengeMapWithIds[key]
<del> .filter(function (elem) {
<del> return String(elem) === String(challenge._id);
<del> }).map(function () {
<del> return key;
<del> });
<del> })
<del> ))
<del> };
<del> }
<add> } else if (req.user) {
<add> req.user.currentChallenge = {
<add> challengeId: challenge._id,
<add> challengeName: challenge.name,
<add> challengeBlock: R.head(R.flatten(Object.keys(challengeMapWithIds).
<add> map(function (key) {
<add> return challengeMapWithIds[key]
<add> .filter(function (elem) {
<add> return String(elem) === String(challenge._id);
<add> }).map(function () {
<add> return key;
<add> });
<add> })
<add> ))
<add> };
<ide> }
<ide>
<ide> var challengeType = {
<ide> exports.completedBonfire = function (req, res, next) {
<ide> return next(err);
<ide> }
<ide> if (user && paired) {
<del> res.send(true);
<add> return res.send(true);
<ide> }
<ide> });
<del> } else {
<del> if (user) {
<del> res.send(true);
<del> }
<add> } else if (user) {
<add> res.send(true);
<ide> }
<ide> });
<ide> }
<ide><path>server/boot/challengeMap.js
<ide> var R = require('ramda'),
<del> debug = require('debug')('freecc:cntr:challengeMap'), //eslint-disable-line
<add> // debug = require('debug')('freecc:cntr:challengeMap'),
<ide> User = require('../../models/User'),
<ide> resources = require('./../resources/resources'),
<ide> middleware = require('../resources/middleware'),
<ide> router.get('/about', function(req, res) {
<ide> res.redirect(301, '/map');
<ide> });
<ide>
<del>
<del>
<ide> function challengeMap(req, res, next) {
<ide> var completedList = [];
<ide>
<ide><path>server/boot/fieldGuide.js
<ide> var R = require('ramda'),
<add> // debug = require('debug')('freecc:fieldguides'),
<ide> FieldGuide = require('./../../models/FieldGuide'),
<del> resources = require('./../resources/resources'),
<del> debug = require('debug')('freecc:fieldguides');
<add> resources = require('./../resources/resources');
<ide>
<ide> exports.returnIndividualFieldGuide = function(req, res, next) {
<ide> var dashedName = req.params.fieldGuideName;
<ide><path>server/boot/home.js
<ide> var router = express.Router();
<ide>
<ide> router.get('/', index);
<ide>
<del>
<del>
<ide> function index(req, res, next) {
<ide> if (req.user && !req.user.profile.picture) {
<ide> req.user.profile.picture =
<ide><path>server/boot/jobs.js
<del>var moment = require('moment'),
<del> Job = require('./../../models/Job'),
<del> resources = require('./../resources/resources');
<add>var Job = require('./../../models/Job');
<ide>
<ide> exports.jobsDirectory = function(req, res, next) {
<ide> Job.find({}, function(err, jobs) {
<ide><path>server/boot/nonprofits.js
<del>var moment = require('moment'),
<del> Nonprofit = require('./../../models/Nonprofit'),
<del> resources = require('./../resources/resources');
<add>var express = require('express'),
<add> Nonprofit = require('./../../models/Nonprofit');
<ide>
<del>exports.nonprofitsDirectory = function(req, res, next) {
<del> Nonprofit.find({estimatedHours: { $gt: 0 } }, function(err, nonprofits) {
<add>var router = express.Router();
<add>
<add>router.get('/nonprofits/directory', nonprofitsDirectory);
<add>router.get('/nonprofits/:nonprofitName', returnIndividualNonprofit);
<add>
<add>function nonprofitsDirectory(req, res, next) {
<add> Nonprofit.find({ estimatedHours: { $gt: 0 } }, function(err, nonprofits) {
<ide> if (err) { return next(err); }
<ide>
<ide> res.render('nonprofits/directory', {
<ide> title: 'Nonprofits we help',
<ide> nonprofits: nonprofits
<ide> });
<ide> });
<del>};
<add>}
<ide>
<del>exports.returnIndividualNonprofit = function(req, res, next) {
<add>function returnIndividualNonprofit(req, res, next) {
<ide> var dashedName = req.params.nonprofitName;
<ide> var nonprofitName = dashedName.replace(/\-/g, ' ');
<ide>
<ide> exports.returnIndividualNonprofit = function(req, res, next) {
<ide> });
<ide> }
<ide> );
<del>};
<add>}
<ide>
<del>exports.interestedInNonprofit = function(req, res, next) {
<add>/*
<add>function interestedInNonprofit(req, res, next) {
<ide> if (req.user) {
<ide> Nonprofit.findOne(
<ide> { name: new RegExp(req.params.nonprofitName.replace(/-/, ' '), 'i') },
<ide> exports.interestedInNonprofit = function(req, res, next) {
<ide> }
<ide> );
<ide> }
<del>};
<add>}
<add>*/
<add>
<add>module.exports = router;
<ide><path>server/boot/redirects.js
<ide> var express = require('express');
<ide> var router = express.Router();
<ide>
<del>
<ide> router.get('/nonprofit-project-instructions', function(req, res) {
<del> res.redirect(301, '/field-guide/how-do-free-code-camp\'s-nonprofit-projects-work');
<add> res.redirect(
<add> 301,
<add> '/field-guide/how-do-free-code-camp\'s-nonprofit-projects-work'
<add> );
<ide> });
<ide>
<ide> router.get('/agile', function(req, res) {
<ide><path>server/boot/story.js
<del>/* eslint-disable no-catch-shadow, no-unused-vars */
<del>var R = require('ramda'),
<del> debug = require('debug')('freecc:cntr:story'),
<del> Story = require('./../../models/Story'),
<del> Comment = require('./../../models/Comment'),
<del> User = require('./../../models/User'),
<del> moment = require('moment'),
<del> resources = require('./../resources/resources'),
<del> mongodb = require('mongodb'),
<del> MongoClient = mongodb.MongoClient,
<del> secrets = require('../../config/secrets'),
<del> nodemailer = require('nodemailer'),
<del> sanitizeHtml = require('sanitize-html'),
<del> express = require('express'),
<del> router = express.Router();
<add>var nodemailer = require('nodemailer'),
<add> sanitizeHtml = require('sanitize-html'),
<add> express = require('express'),
<add> moment = require('moment'),
<add> // debug = require('debug')('freecc:cntr:story'),
<add> Story = require('./../../models/Story'),
<add> Comment = require('./../../models/Comment'),
<add> User = require('./../../models/User'),
<add> resources = require('./../resources/resources'),
<add> mongodb = require('mongodb'),
<add> MongoClient = mongodb.MongoClient,
<add> secrets = require('../../config/secrets'),
<add> router = express.Router();
<ide>
<ide> router.get('/stories/hotStories', hotJSON);
<ide> router.get('/stories/recentStories', recentJSON);
<ide> function submitNew(req, res) {
<ide> });
<ide> }
<ide>
<add>/*
<add> * no used anywhere
<ide> function search(req, res) {
<ide> return res.render('stories/index', {
<ide> title: 'Search the archives of Camper News',
<ide> function recent(req, res) {
<ide> page: 'recent'
<ide> });
<ide> }
<add>*/
<ide>
<ide> function preSubmit(req, res) {
<ide>
<ide> function upvote(req, res, next) {
<ide> );
<ide> story.markModified('rank');
<ide> story.save();
<add> // NOTE(Berks): This logic is full of wholes and race conditions
<add> // this could be the source of many 'can't set headers after they are sent'
<add> // errors. This needs cleaning
<ide> User.findOne({'_id': story.author.userId}, function(err, user) {
<del> if (err) {
<del> return next(err);
<del> }
<add> if (err) { return next(err); }
<add>
<ide> user.progressTimestamps.push(Date.now() || 0);
<del> user.save(function (err, user) {
<del> req.user.save(function (err, user) {
<del> if (err) {
<del> return next(err);
<del> }
<add> user.save(function (err) {
<add> req.user.save(function (err) {
<add> if (err) { return next(err); }
<ide> });
<ide> req.user.progressTimestamps.push(Date.now() || 0);
<ide> if (err) {
<ide> function storySubmission(req, res, next) {
<ide> .replace(/\s+/g, ' ')
<ide> .toLowerCase()
<ide> .trim();
<add>
<ide> var link = data.link;
<add>
<ide> if (link.search(/^https?:\/\//g) === -1) {
<ide> link = 'http://' + link;
<ide> }
<del> Story.count({ storyLink: new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i')}, function (err, storyCount) {
<add>
<add> Story.count({
<add> storyLink: new RegExp('^' + storyLink + '(?: [0-9]+)?$', 'i')
<add> }, function (err, storyCount) {
<ide> if (err) {
<del> return res.status(500);
<add> return next(err);
<ide> }
<ide>
<ide> // if duplicate storyLink add unique number
<ide> function storySubmission(req, res, next) {
<ide> });
<ide> story.save(function (err) {
<ide> if (err) {
<del> return res.status(500);
<add> return next(err);
<ide> }
<ide> req.user.progressTimestamps.push(Date.now() || 0);
<del> req.user.save(function (err, user) {
<add> req.user.save(function (err) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<add> res.send(JSON.stringify({
<add> storyLink: story.storyLink.replace(/\s+/g, '-').toLowerCase()
<add> }));
<ide> });
<del> res.send(JSON.stringify({
<del> storyLink: story.storyLink.replace(/\s+/g, '-').toLowerCase()
<del> }));
<ide> });
<ide> });
<ide> }
<ide> function commentSave(comment, Context, res, next) {
<ide> try {
<ide> // Based on the context retrieve the parent
<ide> // object of the comment (Story/Comment)
<del> Context.find({'_id': data.associatedPost}, function (err, associatedContext) {
<add> Context.find({
<add> '_id': data.associatedPost
<add> }, function (err, associatedContext) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<ide> function commentSave(comment, Context, res, next) {
<ide> });
<ide> }
<ide> // Find the author of the parent object
<del> User.findOne({'profile.username': associatedContext.author.username}, function(err, recipient) {
<add> User.findOne({
<add> 'profile.username': associatedContext.author.username
<add> }, function(err, recipient) {
<ide> if (err) {
<ide> return next(err);
<ide> }
<ide><path>server/boot/user.js
<ide> router.post('/account/password', postUpdatePassword);
<ide> router.post('/account/delete', postDeleteAccount);
<ide> router.get('/account/unlink/:provider', getOauthUnlink);
<ide> router.get('/account', getAccount);
<del>router.get('/:username', returnUser); // Ensure this is the last route!
<add>// Ensure this is the last route!
<add>router.get('/:username', returnUser);
<ide>
<ide> /**
<ide> * GET /signin
<ide> function checkUniqueUsername (req, res, next) {
<ide> /**
<ide> * Existing username check
<ide> */
<add>
<ide> function checkExistingUsername (req, res, next) {
<ide> User.count(
<ide> { 'profile.username': req.params.username.toLowerCase() },
<ide> function postForgot (req, res, next) {
<ide> }
<ide>
<ide> user.resetPasswordToken = token;
<del> user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
<add> // 3600000 = 1 hour
<add> user.resetPasswordExpires = Date.now() + 3600000;
<ide>
<ide> user.save(function(err) {
<ide> if (err) { return done(err); }
<ide><path>server/boot/utility.js
<ide> function getPair(req, res) {
<ide> var userName = req.user.profile.username;
<ide> var challenge = req.body.payload.challenge;
<ide> slack.send({
<del> text: 'Anyone want to pair with *@' + userName + '* on ' + challenge +
<del> '?\nMake sure you install Screen Hero here: ' +
<del> 'http://freecodecamp.com/field-guide/how-do-i-install-screenhero\n' +
<del> 'Then start your pair program session with *@' + userName +
<del> '* by typing \"/hero @' + userName + '\" into Slack.\n And *@'+ userName +
<del> '*, be sure to launch Screen Hero, then keep coding. ' +
<del> 'Another camper may pair with you soon.',
<add> text: [
<add> 'Anyone want to pair with *@',
<add> userName,
<add> '* on ',
<add> challenge,
<add> '?\nMake sure you install Screen Hero here: ',
<add> 'http://freecodecamp.com/field-guide/how-do-i-install-screenhero\n',
<add> 'Then start your pair program session with *@',
<add> userName,
<add> '* by typing \"/hero @',
<add> userName,
<add> '\" into Slack.\n And *@',
<add> userName,
<add> '*, be sure to launch Screen Hero, then keep coding. ',
<add> 'Another camper may pair with you soon.'
<add> ].join(''),
<ide> channel: '#letspair',
<ide> username: 'Companion Cube',
<ide> 'icon_url': 'https://lh3.googleusercontent.com/-f6xDPDV2rPE/AAAAAAAAAAI/' +
<ide><path>server/server.js
<ide> process.on('uncaughtException', function (err) {
<ide> err.message
<ide> );
<ide> console.error(err.stack);
<del> /* eslint-disable no-process-exit */
<del> process.exit(1);
<del> /* eslint-enable no-process-exit */
<add> process.exit(1); // eslint-disable-line
<ide> });
<ide>
<ide> var express = require('express'),
<ide> var express = require('express'),
<ide> methodOverride = require('method-override'),
<ide> bodyParser = require('body-parser'),
<ide> helmet = require('helmet'),
<del> //frameguard = require('frameguard'),
<del> //csp = require('helmet-csp'),
<ide> MongoStore = require('connect-mongo')(session),
<ide> flash = require('express-flash'),
<ide> path = require('path'),
<ide> mongoose = require('mongoose'),
<ide> passport = require('passport'),
<ide> expressValidator = require('express-validator'),
<del> request = require('request'),
<add> // request = require('request'),
<ide> forceDomain = require('forcedomain'),
<ide> lessMiddleware = require('less-middleware'),
<ide>
<ide> /**
<del> * Controllers (route handlers).
<add> * routers.
<ide> */
<del> homeController = require('./boot/home'),
<del> resourcesController = require('./resources/resources'),
<del> userController = require('./boot/user'),
<del> nonprofitController = require('./boot/nonprofits'),
<del> fieldGuideController = require('./boot/fieldGuide'),
<del> challengeMapController = require('./boot/challengeMap'),
<del> challengeController = require('./boot/challenge'),
<del> jobsController = require('./boot/jobs'),
<del> redirects = require('./boot/redirects'),
<del> utility = require('./boot/utility'),
<del> storyController = require('./boot/story'),
<add> homeRouter = require('./boot/home'),
<add> resourcesRouter = require('./resources/resources'),
<add> userRouter = require('./boot/user'),
<add> fieldGuideRouter = require('./boot/fieldGuide'),
<add> challengeMapRouter = require('./boot/challengeMap'),
<add> challengeRouter = require('./boot/challenge'),
<add> jobsRouter = require('./boot/jobs'),
<add> redirectsRouter = require('./boot/redirects'),
<add> utilityRouter = require('./boot/utility'),
<add> storyRouter = require('./boot/story'),
<ide>
<ide> /**
<ide> * API keys and Passport configuration.
<ide> if (process.env.NODE_ENV === 'production') {
<ide> }
<ide>
<ide> app.use(compress());
<del>app.use(lessMiddleware(__dirname + '/public'));
<add>app.use(lessMiddleware(path.join(__dirname, '/public')));
<ide> app.use(logger('dev'));
<ide> app.use(bodyParser.json());
<del>app.use(bodyParser.urlencoded({extended: true}));
<add>app.use(bodyParser.urlencoded({ extended: true }));
<ide> app.use(expressValidator({
<ide> customValidators: {
<ide> matchRegex: function (param, regex) {
<ide> app.use(helmet.csp({
<ide> '*.twitter.com',
<ide> '*.ghbtns.com'
<ide> ].concat(trusted),
<del> reportOnly: false, // set to true if you only want to report errors
<del> setAllHeaders: false, // set to true if you want to set all headers
<del> safari5: false // set to true if you want to force buggy CSP in Safari 5
<add> // set to true if you only want to report errors
<add> reportOnly: false,
<add> // set to true if you want to set all headers
<add> setAllHeaders: false,
<add> // set to true if you want to force buggy CSP in Safari 5
<add> safari5: false
<ide> }));
<ide>
<ide> app.use(function (req, res, next) {
<ide> app.use(function (req, res, next) {
<ide> next();
<ide> });
<ide>
<del>app.use(express.static(__dirname + '/public', {maxAge: 86400000 }));
<add>app.use(
<add> express.static(path.join(__dirname, '/public'), { maxAge: 86400000 })
<add>);
<ide>
<ide> app.use(function (req, res, next) {
<ide> // Remember original destination before login.
<ide> app.use(function (req, res, next) {
<ide> next();
<ide> });
<ide>
<del>
<del>
<del>
<del>
<del>/**
<del> * Nonprofit Project routes.
<del> */
<del>
<del>app.get('/nonprofits/directory', nonprofitController.nonprofitsDirectory);
<del>
<del>app.get(
<del> '/nonprofits/:nonprofitName',
<del> nonprofitController.returnIndividualNonprofit
<del>);
<del>
<add>// add sub routers
<add>app.use(homeRouter);
<add>app.use(resourcesRouter);
<add>app.use(userRouter);
<add>app.use(fieldGuideRouter);
<add>app.use(challengeMapRouter);
<add>app.use(challengeRouter);
<add>app.use(jobsRouter);
<add>app.use(redirectsRouter);
<add>app.use(utilityRouter);
<add>app.use(storyRouter);
<add>
<add>/*
<ide> app.get(
<ide> '/jobs',
<ide> jobsController.jobsDirectory
<ide> );
<ide>
<del>
<del>
<del>
<del>
<del>
<del>
<del>/**
<del> * Camper News routes.
<del> */
<del>
<del>
<del>
<ide> app.all('/account', passportConf.isAuthenticated);
<del>
<del>
<del>/**
<del> * API routes
<del> */
<del>
<del>
<del>/**
<del> * Field Guide related routes
<del> */
<ide> app.get('/field-guide/all-articles', fieldGuideController.showAllFieldGuides);
<del>
<ide> app.get('/field-guide/:fieldGuideName',
<ide> fieldGuideController.returnIndividualFieldGuide
<ide> );
<del>
<ide> app.get('/field-guide/', fieldGuideController.returnNextFieldGuide);
<del>
<ide> app.post('/completed-field-guide/', fieldGuideController.completedFieldGuide);
<del>
<del>
<del>/**
<del> * Challenge related routes
<del> */
<del>
<ide> app.get('/challenges/next-challenge',
<ide> userController.userMigration,
<ide> challengeController.returnNextChallenge
<ide> );
<del>
<ide> app.get(
<ide> '/challenges/:challengeName',
<ide> userController.userMigration,
<ide> challengeController.returnIndividualChallenge
<ide> );
<del>
<ide> app.get('/challenges/',
<ide> userController.userMigration,
<ide> challengeController.returnCurrentChallenge);
<add>
<ide> // todo refactor these routes
<ide> app.post('/completed-challenge/', challengeController.completedChallenge);
<del>
<ide> app.post('/completed-zipline-or-basejump',
<ide> challengeController.completedZiplineOrBasejump);
<del>
<ide> app.post('/completed-bonfire', challengeController.completedBonfire);
<del>
<del>// Unique Check API route
<del>
<del>
<add>*/
<ide>
<ide> /**
<ide> * OAuth sign-in routes.
<ide> app.get(
<ide> if (process.env.NODE_ENV === 'development') {
<ide> app.use(errorHandler({ log: true }));
<ide> } else {
<del> // error handling in production
<del> app.use(function(err, req, res, next) {
<add> // error handling in production disabling eslint due to express parity rules
<add> // for error handlers
<add> app.use(function(err, req, res, next) { // eslint-disable-line
<ide>
<ide> // respect err.status
<ide> if (err.status) { | 11 |
Javascript | Javascript | add check for wrk to test-keep-alive | 5fdd55473047b8e4fca79dae42b9ca2d0d5b08ae | <ide><path>test/pummel/test-keep-alive.js
<ide>
<ide> // This test requires the program 'wrk'.
<ide> const common = require('../common');
<del>if (common.isWindows)
<del> common.skip('no `wrk` on windows');
<add>
<add>const child_process = require('child_process');
<add>const result = child_process.spawnSync('wrk', ['-h']);
<add>if (result.error && result.error.code === 'ENOENT')
<add> common.skip('test requires `wrk` to be installed first');
<ide>
<ide> const assert = require('assert');
<del>const spawn = require('child_process').spawn;
<ide> const http = require('http');
<ide> const url = require('url');
<ide>
<ide> const runAb = (opts, callback) => {
<ide> args.push(url.format({ hostname: '127.0.0.1',
<ide> port: opts.port, protocol: 'http' }));
<ide>
<del> const child = spawn('wrk', args);
<add> const child = child_process.spawn('wrk', args);
<ide> child.stderr.pipe(process.stderr);
<ide> child.stdout.setEncoding('utf8');
<ide> | 1 |
Javascript | Javascript | remove ie9 soft-fails check | 3be6ce4c2900ec377560056236e79f8a9c2fea7f | <ide><path>packages/ember-metal/tests/descriptor_test.js
<ide> import {
<ide> descriptor
<ide> } from '..';
<ide>
<del>// IE9 soft-fails when trying to delete a non-configurable property
<del>const hasCompliantDelete = (function() {
<del> let obj = {};
<del>
<del> Object.defineProperty(obj, 'zomg', { configurable: false, value: 'zomg' });
<del>
<del> try {
<del> delete obj.zomg;
<del> } catch (e) {
<del> return true;
<del> }
<del>
<del> return false;
<del>})();
<del>
<del>// IE9 soft-fails when trying to assign to a non-writable property
<del>const hasCompliantAssign = (function() {
<del> let obj = {};
<del>
<del> Object.defineProperty(obj, 'zomg', { writable: false, value: 'zomg' });
<del>
<del> try {
<del> obj.zomg = 'lol';
<del> } catch (e) {
<del> return true;
<del> }
<del>
<del> return false;
<del>})();
<ide>
<ide> class DescriptorTest {
<ide>
<ide> classes.forEach(TestClass => {
<ide>
<ide> let source = factory.source();
<ide>
<del> if (hasCompliantDelete) {
<del> assert.throws(() => delete source.foo, TypeError);
<del> } else {
<del> delete source.foo;
<del> }
<add> assert.throws(() => delete source.foo, TypeError);
<ide>
<ide> assert.throws(() => Object.defineProperty(source, 'foo', { configurable: true, value: 'baz' }), TypeError);
<ide>
<ide> classes.forEach(TestClass => {
<ide>
<ide> let source = factory.source();
<ide>
<del> if (hasCompliantAssign) {
<del> assert.throws(() => source.foo = 'baz', TypeError);
<del> assert.throws(() => obj.foo = 'baz', TypeError);
<del> } else {
<del> source.foo = 'baz';
<del> obj.foo = 'baz';
<del> }
<add> assert.throws(() => source.foo = 'baz', TypeError);
<add> assert.throws(() => obj.foo = 'baz', TypeError);
<ide>
<ide> assert.equal(obj.foo, 'bar');
<ide> });
<ide> classes.forEach(TestClass => {
<ide>
<ide> assert.equal(obj.fooBar, 'FOO-BAR');
<ide>
<del> if (hasCompliantAssign) {
<del> assert.throws(() => obj.fooBar = 'foobar', TypeError);
<del> } else {
<del> obj.fooBar = 'foobar';
<del> }
<add> assert.throws(() => obj.fooBar = 'foobar', TypeError);
<ide>
<ide> assert.equal(obj.fooBar, 'FOO-BAR');
<ide> }); | 1 |
Text | Text | add an example vue integration.md | 4c277fd0f6436d72160c44749f127d69e3a86610 | <ide><path>docs/guides/player-workflows.md
<ide> This document outlines many considerations for using Video.js for advanced playe
<ide> * [React](#react)
<ide> * [Ember](#ember)
<ide> * [Angular](#angular)
<add> * [Vue](#vue)
<ide>
<ide> ## Accessing a player that has already been created on a page
<ide>
<ide> See [ReactJS integration example](/docs/guides/react.md)
<ide> ### Ember
<ide>
<ide> ### Angular
<add>
<add>### Vue
<add>
<add>See [Vue integration example](/docs/guides/vue.md)
<ide><path>docs/guides/vue.md
<add># Video.js and Vue integration
<add>
<add>Here's a basic Vue player implementation.
<add>
<add>It just instantiates the Video.js player on `mounted` and destroys it on `beforeDestroy`.
<add>
<add>```vue
<add><template>
<add> <div>
<add> <video ref="videoPlayer" class="video-js"></video>
<add> </div>
<add></template>
<add>
<add><script>
<add>import videojs from 'video.js';
<add>
<add>export default {
<add> name: "VideoPlayer",
<add> props: {
<add> options: {
<add> type: Object,
<add> default() {
<add> return {};
<add> }
<add> }
<add> },
<add> data() {
<add> return {
<add> player: null
<add> }
<add> },
<add> mounted() {
<add> this.player = videojs(this.$refs.videoPlayer, this.options, function onPlayerReady() {
<add> console.log('onPlayerReady', this);
<add> })
<add> },
<add> beforeDestroy() {
<add> if (this.player) {
<add> this.player.dispose()
<add> }
<add> }
<add>}
<add></script>
<add>```
<add>
<add>You can then use it like this: (see [options guide][options] for option information)
<add>
<add>```vue
<add><template>
<add> <div>
<add> <video-player :options="videoOptions"/>
<add> </div>
<add></template>
<add>
<add><script>
<add>import VideoPlayer from "@/components/VideoPlayer.vue";
<add>
<add>export default {
<add> name: "VideoExample",
<add> components: {
<add> VideoPlayer
<add> },
<add> data() {
<add> return {
<add> videoOptions: {
<add> autoplay: true,
<add> controls: true,
<add> sources: [
<add> {
<add> src:
<add> "/path/to/video.mp4",
<add> type: "video/mp4"
<add> }
<add> ]
<add> }
<add> };
<add> }
<add>};
<add>```
<add>
<add>Don't forget to include the Video.js CSS, located at `video.js/dist/video-js.css`.
<add>
<add>[options]: /docs/guides/options.md | 2 |
Javascript | Javascript | add onbeforerender(), onafterrender() | a1b201556d6d3763112a0495ea19f0916ceb3321 | <ide><path>src/renderers/webgl/plugins/SpritePlugin.js
<ide> function SpritePlugin( renderer, sprites ) {
<ide>
<ide> if ( material.visible === false ) continue;
<ide>
<add> sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
<add>
<ide> gl.uniform1f( uniforms.alphaTest, material.alphaTest );
<ide> gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
<ide>
<ide> function SpritePlugin( renderer, sprites ) {
<ide>
<ide> gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
<ide>
<add> sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
<add>
<ide> }
<ide>
<ide> // restore gl | 1 |
PHP | PHP | remove the responsetransformer from use | ef090d02db82e567dc565185f0a3c53b004d9911 | <ide><path>src/Http/ActionDispatcher.php
<ide> public function __construct($factory = null, $eventManager = null, array $filter
<ide> $this->addFilter($filter);
<ide> }
<ide> $this->factory = $factory ?: new ControllerFactory();
<add>
<add> // Force aliases to be autoloaded.
<add> class_exists('Cake\Network\Request');
<ide> }
<ide>
<ide> /**
<ide> * Dispatches a Request & Response
<ide> *
<del> * @param \Cake\Network\Request $request The request to dispatch.
<add> * @param \Cake\Http\ServerRequest $request The request to dispatch.
<ide> * @param \Cake\Network\Response $response The response to dispatch.
<ide> * @return \Cake\Network\Response A modified/replaced response.
<ide> */
<del> public function dispatch(Request $request, Response $response)
<add> public function dispatch(ServerRequest $request, Response $response)
<ide> {
<ide> if (Router::getRequest(true) !== $request) {
<ide> Router::pushRequest($request);
<ide><path>src/Http/BaseApplication.php
<ide> public function bootstrap()
<ide> */
<ide> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
<ide> {
<del> $cakeResponse = ResponseTransformer::toCake($response);
<del>
<del> // Dispatch the request/response to CakePHP
<del> $cakeResponse = $this->getDispatcher()->dispatch($request, $cakeResponse);
<del>
<del> // Convert the response back into a PSR7 object.
<del> return ResponseTransformer::toPsr($cakeResponse);
<add> return $this->getDispatcher()->dispatch($request, $response);
<ide> }
<ide>
<ide> /**
<ide><path>src/Http/Server.php
<ide> namespace Cake\Http;
<ide>
<ide> use Cake\Event\EventDispatcherTrait;
<add>use Cake\Network\Response;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> use RuntimeException;
<ide> use UnexpectedValueException;
<del>use Zend\Diactoros\Response;
<ide> use Zend\Diactoros\Response\EmitterInterface;
<ide> use Zend\Diactoros\Response\SapiEmitter;
<ide> use Zend\Diactoros\Response\SapiStreamEmitter;
<ide><path>src/TestSuite/IntegrationTestCase.php
<ide> public function assertRedirect($url = null, $message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert location header. ' . $message);
<ide> }
<del> $result = $this->_response->header();
<add> $result = $this->_response->getHeaderLine('Location');
<ide> if ($url === null) {
<del> $this->assertTrue(!empty($result['Location']), $message);
<add> $this->assertTrue(!empty($result), $message);
<ide>
<ide> return;
<ide> }
<del> if (empty($result['Location'])) {
<add> if (empty($result)) {
<ide> $this->fail('No location header set. ' . $message);
<ide> }
<del> $this->assertEquals(Router::url($url, ['_full' => true]), $result['Location'], $message);
<add> $this->assertEquals(Router::url($url, ['_full' => true]), $result, $message);
<ide> }
<ide>
<ide> /**
<ide> public function assertRedirectContains($url, $message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert location header. ' . $message);
<ide> }
<del> $result = $this->_response->header();
<del> if (empty($result['Location'])) {
<add> $result = $this->_response->getHeaderLine('Location');
<add> if (empty($result)) {
<ide> $this->fail('No location header set. ' . $message);
<ide> }
<del> $this->assertContains($url, $result['Location'], $message);
<add> $this->assertContains($url, $result, $message);
<ide> }
<ide>
<ide> /**
<ide> public function assertNoRedirect($message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert location header. ' . $message);
<ide> }
<del> $result = $this->_response->header();
<add> $result = $this->_response->getHeaderLine('Location');
<ide> if (!$message) {
<ide> $message = 'Redirect header set';
<ide> }
<del> if (!empty($result['Location'])) {
<del> $message .= ': ' . $result['Location'];
<add> if (!empty($result)) {
<add> $message .= ': ' . $result;
<ide> }
<del> $this->assertTrue(empty($result['Location']), $message);
<add> $this->assertTrue(empty($result), $message);
<ide> }
<ide>
<ide> /**
<ide> public function assertHeader($header, $content, $message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert headers. ' . $message);
<ide> }
<del> $headers = $this->_response->header();
<del> if (!isset($headers[$header])) {
<add> if (!$this->_response->hasHeader($header)) {
<ide> $this->fail("The '$header' header is not set. " . $message);
<ide> }
<del> $this->assertEquals($headers[$header], $content, $message);
<add> $actual = $this->_response->getHeaderLine($header);
<add> $this->assertEquals($content, $actual, $message);
<ide> }
<ide>
<ide> /**
<ide> public function assertHeaderContains($header, $content, $message = '')
<ide> if (!$this->_response) {
<ide> $this->fail('No response set, cannot assert headers. ' . $message);
<ide> }
<del> $headers = $this->_response->header();
<del> if (!isset($headers[$header])) {
<add> if (!$this->_response->hasHeader($header)) {
<ide> $this->fail("The '$header' header is not set. " . $message);
<ide> }
<del> $this->assertContains($content, $headers[$header], $message);
<add> $actual = $this->_response->getHeaderLine($header);
<add> $this->assertContains($content, $actual, $message);
<ide> }
<ide>
<ide> /**
<ide><path>src/TestSuite/MiddlewareDispatcher.php
<ide> public function execute($request)
<ide>
<ide> $server = new Server($app);
<ide> $psrRequest = $this->_createRequest($request);
<del> $response = $server->run($psrRequest);
<del>
<del> return ResponseTransformer::toCake($response);
<add> return $server->run($psrRequest);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/BaseApplicationTest.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Http\BaseApplication;
<ide> use Cake\Http\ServerRequestFactory;
<add>use Cake\Network\Response;
<ide> use Cake\TestSuite\TestCase;
<del>use Zend\Diactoros\Response;
<ide>
<ide> /**
<ide> * Base application test. | 6 |
Python | Python | fix fab install command | 67cd2d42b045b0d2cbdf3a24e7b113a30b390647 | <ide><path>fabfile.py
<ide> def make():
<ide> with virtualenv(VENV_DIR) as venv_local:
<ide> venv_local('pip install cython')
<ide> venv_local('pip install murmurhash')
<add> venv_local('pip install wheel')
<ide> venv_local('pip install -r requirements.txt')
<ide> venv_local('python setup.py build_ext --inplace')
<ide> | 1 |
PHP | PHP | apply fixes from styleci | 6fc9fb08f3f1f4c272a8899621adec2af90c59a9 | <ide><path>src/Illuminate/Console/Scheduling/ScheduleRunCommand.php
<ide> namespace Illuminate\Console\Scheduling;
<ide>
<ide> use Illuminate\Console\Command;
<del>use Illuminate\Support\Facades\Date;
<del>use Illuminate\Contracts\Events\Dispatcher;
<ide> use Illuminate\Console\Events\ScheduledTaskFinished;
<ide> use Illuminate\Console\Events\ScheduledTaskStarting;
<add>use Illuminate\Contracts\Events\Dispatcher;
<add>use Illuminate\Support\Facades\Date;
<ide>
<ide> class ScheduleRunCommand extends Command
<ide> { | 1 |
Javascript | Javascript | add safeguards to reactcomponenttreedevtool | 900a588f6309ce1c8ab1670df95f7981ccf04277 | <ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide>
<ide> var invariant = require('invariant');
<ide>
<del>var isTopLevelWrapperByID = {};
<ide> var unmountedContainerIDs = [];
<ide> var allChildIDsByContainerID = {};
<ide> var tree = {};
<ide>
<ide> function updateTree(id, update) {
<del> if (isTopLevelWrapperByID[id]) {
<del> return;
<del> }
<ide> if (!tree[id]) {
<ide> tree[id] = {
<ide> parentID: null,
<add> ownerID: null,
<add> text: null,
<ide> childIDs: [],
<add> displayName: 'Unknown',
<add> isTopLevelWrapper: false,
<ide> };
<ide> }
<ide> update(tree[id]);
<ide> function purgeTree(id) {
<ide>
<ide> var ReactComponentTreeDevtool = {
<ide> onSetIsTopLevelWrapper(id, isTopLevelWrapper) {
<del> if (isTopLevelWrapper) {
<del> delete tree[id];
<del> isTopLevelWrapperByID[id] = true;
<del> }
<add> updateTree(id, item => item.isTopLevelWrapper = isTopLevelWrapper);
<ide> },
<ide>
<ide> onSetIsComposite(id, isComposite) {
<ide> var ReactComponentTreeDevtool = {
<ide> },
<ide>
<ide> onSetChildren(id, nextChildIDs) {
<add> if (ReactComponentTreeDevtool.isTopLevelWrapper(id)) {
<add> return;
<add> }
<add>
<ide> updateTree(id, item => {
<ide> var prevChildIDs = item.childIDs;
<ide> item.childIDs = nextChildIDs;
<ide> var ReactComponentTreeDevtool = {
<ide> },
<ide>
<ide> isComposite(id) {
<del> return tree[id].isComposite;
<add> var item = tree[id];
<add> return item ? item.isComposite : false;
<add> },
<add>
<add> isTopLevelWrapper(id) {
<add> var item = tree[id];
<add> return item ? item.isTopLevelWrapper : false;
<ide> },
<ide>
<ide> getChildIDs(id) {
<del> return tree[id].childIDs;
<add> var item = tree[id];
<add> return item ? item.childIDs : [];
<ide> },
<ide>
<ide> getDisplayName(id) {
<del> return tree[id].displayName;
<add> var item = tree[id];
<add> return item ? item.displayName : 'Unknown';
<ide> },
<ide>
<ide> getOwnerID(id) {
<del> return tree[id].ownerID;
<add> var item = tree[id];
<add> return item ? item.ownerID : null;
<ide> },
<ide>
<ide> getParentID(id) {
<del> return tree[id].parentID;
<add> var item = tree[id];
<add> return item ? item.parentID : null;
<ide> },
<ide>
<ide> getText(id) {
<del> return tree[id].text;
<add> var item = tree[id];
<add> return item ? item.text : null;
<ide> },
<ide>
<ide> getRegisteredIDs() {
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> function getRegisteredDisplayNames() {
<ide> return ReactComponentTreeDevtool.getRegisteredIDs()
<add> .filter(id => !ReactComponentTreeDevtool.isTopLevelWrapper(id))
<ide> .map(ReactComponentTreeDevtool.getDisplayName);
<ide> }
<ide>
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> };
<ide>
<ide> var parentID = ReactComponentTreeDevtool.getParentID(rootID);
<del> if (expectedParentID) {
<del> expect(parentID).toBe(expectedParentID);
<del> }
<add> expect(parentID).toBe(expectedParentID);
<ide>
<ide> var childIDs = ReactComponentTreeDevtool.getChildIDs(rootID);
<ide> var text = ReactComponentTreeDevtool.getText(rootID);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> currentElement = element;
<ide> ReactDOM.render(<Wrapper />, node);
<ide> expect(
<del> getTree(rootInstance._renderedComponent._debugID, includeOwner)
<add> getTree(rootInstance._debugID, includeOwner).children[0]
<ide> ).toEqual(expectedTree);
<ide> });
<ide> ReactDOM.unmountComponentAtNode(node);
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> currentElement = element;
<ide> ReactDOMServer.renderToString(<Wrapper />);
<ide> expect(
<del> getTree(rootInstance._renderedComponent._debugID, includeOwner)
<add> getTree(rootInstance._debugID, includeOwner).children[0]
<ide> ).toEqual(expectedTree);
<ide> ReactComponentTreeDevtool.purgeUnmountedContainers();
<ide> expect(getRegisteredDisplayNames()).toEqual([]); | 2 |
Javascript | Javascript | replace `mountdepth` with `istoplevel` | fc7cf2ff639099538fbfea1bbf1a74907348c9ed | <ide><path>src/browser/server/ReactServerRendering.js
<ide> function renderToString(element, context) {
<ide>
<ide> return transaction.perform(function() {
<ide> var componentInstance = instantiateReactComponent(element, null);
<del> var markup = componentInstance.mountComponent(id, transaction, 0, context);
<add> var markup = componentInstance.mountComponent(id, transaction, context);
<ide> return ReactMarkupChecksum.addChecksumToMarkup(markup);
<ide> }, null);
<ide> } finally {
<ide> function renderToStaticMarkup(element, context) {
<ide>
<ide> return transaction.perform(function() {
<ide> var componentInstance = instantiateReactComponent(element, null);
<del> return componentInstance.mountComponent(id, transaction, 0, context);
<add> return componentInstance.mountComponent(id, transaction, context);
<ide> }, null);
<ide> } finally {
<ide> ReactServerRenderingTransaction.release(transaction);
<ide><path>src/browser/ui/ReactDOMComponent.js
<ide> ReactDOMComponent.Mixin = {
<ide> * @internal
<ide> * @param {string} rootID The root DOM ID for this node.
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {number} mountDepth number of components in the owner hierarchy
<ide> * @return {string} The computed markup.
<ide> */
<del> mountComponent: function(rootID, transaction, mountDepth, context) {
<add> mountComponent: function(rootID, transaction, context) {
<ide> ReactComponent.Mixin.mountComponent.call(
<ide> this,
<ide> rootID,
<ide> transaction,
<del> mountDepth,
<ide> context
<ide> );
<ide> this._rootNodeID = rootID;
<ide><path>src/browser/ui/ReactDOMTextComponent.js
<ide> assign(ReactDOMTextComponent.prototype, {
<ide> *
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {number} mountDepth number of components in the owner hierarchy
<ide> * @return {string} Markup for this text node.
<ide> * @internal
<ide> */
<del> mountComponent: function(rootID, transaction, mountDepth, context) {
<add> mountComponent: function(rootID, transaction, context) {
<ide> this._rootNodeID = rootID;
<ide> var escapedText = escapeTextForBrowser(this._stringText);
<ide>
<ide><path>src/browser/ui/ReactMount.js
<ide> function mountComponentIntoNode(
<ide> container,
<ide> transaction,
<ide> shouldReuseMarkup) {
<del> var markup = this.mountComponent(rootID, transaction, 0, emptyObject);
<add> var markup = this.mountComponent(rootID, transaction, emptyObject);
<add> this._isTopLevel = true;
<ide> ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup);
<ide> }
<ide>
<ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js
<ide> describe('ReactDOMComponent', function() {
<ide> _owner: null,
<ide> _context: null
<ide> });
<del> return stubComponent.mountComponent('test', transaction, 0, {});
<add> return stubComponent.mountComponent('test', transaction, {});
<ide> };
<ide> });
<ide>
<ide><path>src/browser/ui/dom/__tests__/Danger-test.js
<ide> describe('Danger', function() {
<ide> it('should render markup', function() {
<ide> var markup = instantiateReactComponent(
<ide> <div />
<del> ).mountComponent('.rX', transaction, 0, {});
<add> ).mountComponent('.rX', transaction, {});
<ide> var output = Danger.dangerouslyRenderMarkup([markup])[0];
<ide>
<ide> expect(output.nodeName).toBe('DIV');
<ide> describe('Danger', function() {
<ide> ).mountComponent(
<ide> '.rX',
<ide> transaction,
<del> 0, {}
<add> {}
<ide> );
<ide> var output = Danger.dangerouslyRenderMarkup([markup])[0];
<ide>
<ide> describe('Danger', function() {
<ide> it('should render wrapped markup', function() {
<ide> var markup = instantiateReactComponent(
<ide> <th />
<del> ).mountComponent('.rX', transaction, 0, {});
<add> ).mountComponent('.rX', transaction, {});
<ide> var output = Danger.dangerouslyRenderMarkup([markup])[0];
<ide>
<ide> expect(output.nodeName).toBe('TH');
<ide><path>src/core/ReactComponent.js
<ide> var ReactComponent = {
<ide> // to track updates.
<ide> this._currentElement = element;
<ide> this._mountIndex = 0;
<del> this._mountDepth = 0;
<ide> },
<ide>
<ide> /**
<ide> var ReactComponent = {
<ide> *
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {number} mountDepth number of components in the owner hierarchy.
<ide> * @return {?string} Rendered markup to be inserted into the DOM.
<ide> * @internal
<ide> */
<del> mountComponent: function(rootID, transaction, mountDepth, context) {
<add> mountComponent: function(rootID, transaction, context) {
<ide> var ref = this._currentElement.ref;
<ide> if (ref != null) {
<ide> var owner = this._currentElement._owner;
<ide> attachRef(ref, this, owner);
<ide> }
<del> this._mountDepth = mountDepth;
<ide> // Effectively: return '';
<ide> },
<ide>
<ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = assign({},
<ide>
<ide> this._context = null;
<ide> this._mountOrder = 0;
<add> this._isTopLevel = false;
<ide>
<ide> // See ReactUpdates.
<ide> this._pendingCallbacks = null;
<ide> var ReactCompositeComponentMixin = assign({},
<ide> *
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {number} mountDepth number of components in the owner hierarchy
<ide> * @return {?string} Rendered markup to be inserted into the DOM.
<ide> * @final
<ide> * @internal
<ide> */
<del> mountComponent: function(rootID, transaction, mountDepth, context) {
<add> mountComponent: function(rootID, transaction, context) {
<ide> ReactComponent.Mixin.mountComponent.call(
<ide> this,
<ide> rootID,
<ide> transaction,
<del> mountDepth,
<ide> context
<ide> );
<ide>
<ide> var ReactCompositeComponentMixin = assign({},
<ide> var markup = this._renderedComponent.mountComponent(
<ide> rootID,
<ide> transaction,
<del> mountDepth + 1,
<ide> this._processChildContext(context)
<ide> );
<ide> if (inst.componentDidMount) {
<ide> var ReactCompositeComponentMixin = assign({},
<ide> */
<ide> replaceProps: function(props, callback) {
<ide> invariant(
<del> this._mountDepth === 0,
<add> this._isTopLevel,
<ide> 'replaceProps(...): You called `setProps` or `replaceProps` on a ' +
<ide> 'component with a parent. This is an anti-pattern since props will ' +
<ide> 'get reactively updated when rendered. Instead, change the owner\'s ' +
<ide> var ReactCompositeComponentMixin = assign({},
<ide> var nextMarkup = this._renderedComponent.mountComponent(
<ide> thisID,
<ide> transaction,
<del> this._mountDepth + 1,
<ide> context
<ide> );
<ide> ReactComponentEnvironment.replaceNodeWithMarkupByID(
<ide> var ShallowMixin = assign({},
<ide> *
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
<del> * @param {number} mountDepth number of components in the owner hierarchy
<ide> * @return {ReactElement} Shallow rendering of the component.
<ide> * @final
<ide> * @internal
<ide> */
<del> mountComponent: function(rootID, transaction, mountDepth, context) {
<add> mountComponent: function(rootID, transaction, context) {
<ide> ReactComponent.Mixin.mountComponent.call(
<ide> this,
<ide> rootID,
<ide> transaction,
<del> mountDepth,
<ide> context
<ide> );
<ide>
<ide><path>src/core/ReactMultiChild.js
<ide> var ReactMultiChild = {
<ide> var mountImage = childInstance.mountComponent(
<ide> rootID,
<ide> transaction,
<del> this._mountDepth + 1,
<ide> context
<ide> );
<ide> childInstance._mountIndex = index;
<ide> var ReactMultiChild = {
<ide> var mountImage = child.mountComponent(
<ide> rootID,
<ide> transaction,
<del> this._mountDepth + 1,
<ide> context
<ide> );
<ide> child._mountIndex = index;
<ide><path>src/core/__tests__/ReactComponent-test.js
<ide> var ReactInstanceMap;
<ide> var ReactTestUtils;
<ide>
<ide> var reactComponentExpect;
<del>var getMountDepth;
<ide>
<ide> describe('ReactComponent', function() {
<ide> beforeEach(function() {
<ide> React = require('React');
<ide> ReactInstanceMap = require('ReactInstanceMap');
<ide> ReactTestUtils = require('ReactTestUtils');
<ide> reactComponentExpect = require('reactComponentExpect');
<del>
<del> getMountDepth = function(instance) {
<del> return ReactInstanceMap.get(instance)._mountDepth;
<del> };
<ide> });
<ide>
<ide> it('should throw on invalid render targets', function() {
<ide> describe('ReactComponent', function() {
<ide> var instance = ReactTestUtils.renderIntoDocument(element);
<ide> expect(instance.isMounted()).toBeTruthy();
<ide> });
<del>
<del> it('should know its simple mount depth', function() {
<del> var Owner = React.createClass({
<del> render: function() {
<del> return <Child ref="child" />;
<del> }
<del> });
<del>
<del> var Child = React.createClass({
<del> render: function() {
<del> return <div />;
<del> }
<del> });
<del>
<del> var instance = <Owner />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<del> expect(getMountDepth(instance)).toBe(0);
<del> expect(getMountDepth(instance.refs.child)).toBe(1);
<del> });
<del>
<del> it('should know its (complicated) mount depth', function() {
<del> var Box = React.createClass({
<del> render: function() {
<del> return <div ref="boxDiv">{this.props.children}</div>;
<del> }
<del> });
<del>
<del> var Child = React.createClass({
<del> render: function() {
<del> return <span ref="span">child</span>;
<del> }
<del> });
<del>
<del> var Switcher = React.createClass({
<del> getInitialState: function() {
<del> return {tabKey: 'hello'};
<del> },
<del>
<del> render: function() {
<del> var child = this.props.children;
<del>
<del> return (
<del> <Box ref="box">
<del> <div
<del> ref="switcherDiv"
<del> style={{
<del> display: this.state.tabKey === child.key ? '' : 'none'
<del> }}>
<del> {child}
<del> </div>
<del> </Box>
<del> );
<del> }
<del> });
<del>
<del> var App = React.createClass({
<del> render: function() {
<del> return (
<del> <Switcher ref="switcher">
<del> <Child key="hello" ref="child" />
<del> </Switcher>
<del> );
<del> }
<del> });
<del>
<del> var root = <App />;
<del> root = ReactTestUtils.renderIntoDocument(root);
<del>
<del> expect(getMountDepth(root)).toBe(0);
<del> expect(getMountDepth(root.refs.switcher)).toBe(1);
<del> expect(getMountDepth(root.refs.switcher.refs.box)).toBe(2);
<del> expect(getMountDepth(root.refs.switcher.refs.switcherDiv)).toBe(5);
<del> expect(getMountDepth(root.refs.child)).toBe(7);
<del> expect(getMountDepth(root.refs.switcher.refs.box.refs.boxDiv)).toBe(3);
<del> expect(getMountDepth(root.refs.child.refs.span)).toBe(8);
<del> });
<ide> });
<ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> describe('ReactCompositeComponent', function() {
<ide> );
<ide> });
<ide>
<add> it('should only allow `setProps` on top-level components', function() {
<add> var container = document.createElement('div');
<add> document.documentElement.appendChild(container);
<add>
<add> var innerInstance;
<add>
<add> var Component = React.createClass({
<add> render: function() {
<add> return <div><div ref="inner" /></div>;
<add> },
<add> componentDidMount: function() {
<add> innerInstance = this.refs.inner;
<add> }
<add> });
<add> React.render(<Component />, container);
<add>
<add> expect(innerInstance).not.toBe(undefined);
<add> expect(function() {
<add> innerInstance.setProps({value: 1});
<add> }).toThrow(
<add> 'Invariant Violation: replaceProps(...): You called `setProps` or ' +
<add> '`replaceProps` on a component with a parent. This is an anti-pattern ' +
<add> 'since props will get reactively updated when rendered. Instead, ' +
<add> 'change the owner\'s `render` method to pass the correct value as ' +
<add> 'props to the component where it is created.'
<add> );
<add> });
<add>
<ide> it('should cleanup even if render() fatals', function() {
<ide> var BadComponent = React.createClass({
<ide> render: function() {
<ide><path>src/test/ReactTestUtils.js
<ide> ReactShallowRenderer.prototype._render = function(element, transaction, context)
<ide> var instance = new ShallowComponentWrapper(new element.type(element.props));
<ide> instance.construct(element);
<ide>
<del> instance.mountComponent(rootID, transaction, 0, context);
<add> instance.mountComponent(rootID, transaction, context);
<ide>
<ide> this._instance = instance;
<ide> } else { | 12 |
Javascript | Javascript | return this from outgoingmessage#destroy() | 94e5b5c77dade0d8f7358c66144b75c369679cab | <ide><path>lib/_http_outgoing.js
<ide> OutgoingMessage.prototype.setTimeout = function setTimeout(msecs, callback) {
<ide> // it, since something else is destroying this connection anyway.
<ide> OutgoingMessage.prototype.destroy = function destroy(error) {
<ide> if (this.destroyed) {
<del> return;
<add> return this;
<ide> }
<ide> this.destroyed = true;
<ide>
<ide> OutgoingMessage.prototype.destroy = function destroy(error) {
<ide> socket.destroy(error);
<ide> });
<ide> }
<add>
<add> return this;
<ide> };
<ide>
<ide>
<ide><path>test/parallel/test-outgoing-message-destroy.js
<add>'use strict';
<add>
<add>// Test that http.OutgoingMessage,prototype.destroy() returns `this`.
<add>require('../common');
<add>
<add>const assert = require('assert');
<add>const http = require('http');
<add>const outgoingMessage = new http.OutgoingMessage();
<add>
<add>assert.strictEqual(outgoingMessage.destroyed, false);
<add>assert.strictEqual(outgoingMessage.destroy(), outgoingMessage);
<add>assert.strictEqual(outgoingMessage.destroyed, true);
<add>assert.strictEqual(outgoingMessage.destroy(), outgoingMessage); | 2 |
Python | Python | add tests for gce region & zone related attributes | 88667ea6fe4d4bca612588e4cca064889dd3ae37 | <ide><path>libcloud/test/compute/test_gce.py
<ide> def test_ex_get_zone(self):
<ide> zone_no_mw = self.driver.ex_get_zone("us-central1-a")
<ide> self.assertIsNone(zone_no_mw.time_until_mw)
<ide>
<add> def test_driver_zone_attributes(self):
<add> zones = self.driver.ex_list_zones()
<add> self.assertEqual(len(self.driver.zone_dict), len(zones))
<add> self.assertEqual(len(self.driver.zone_list), len(zones))
<add> for zone, fetched_zone in zip(self.driver.zone_list, zones):
<add> self.assertEqual(zone.id, fetched_zone.id)
<add> self.assertEqual(zone.name, fetched_zone.name)
<add> self.assertEqual(zone.status, fetched_zone.status)
<add>
<add> def test_driver_region_attributes(self):
<add> regions = self.driver.ex_list_regions()
<add> self.assertEqual(len(self.driver.region_dict), len(regions))
<add> self.assertEqual(len(self.driver.region_list), len(regions))
<add> for region, fetched_region in zip(self.driver.region_list, regions):
<add> self.assertEqual(region.id, fetched_region.id)
<add> self.assertEqual(region.name, fetched_region.name)
<add> self.assertEqual(region.status, fetched_region.status)
<add>
<add>
<add>class GCENodeDriverTest2(GoogleTestCase):
<add> """
<add> GCE Test Class, test node driver without passing `datacenter` parameter on initialization.
<add> """
<add>
<add> def setUp(self):
<add> GCEMockHttp.test = self
<add> GCENodeDriver.connectionCls.conn_class = GCEMockHttp
<add> GoogleBaseAuthConnection.conn_class = GoogleAuthMockHttp
<add> GCEMockHttp.type = None
<add> kwargs = GCE_KEYWORD_PARAMS.copy()
<add> kwargs["auth_type"] = "IA"
<add> self.driver = GCENodeDriver(*GCE_PARAMS, **kwargs)
<add>
<add> def test_zone_attributes(self):
<add> self.assertIsNone(self.driver._zone_dict)
<add> self.assertIsNone(self.driver._zone_list)
<add>
<add> zones = self.driver.ex_list_zones()
<add>
<add> self.assertEqual(len(self.driver.zone_list), len(zones))
<add> self.assertEqual(len(self.driver.zone_dict), len(zones))
<add> for zone, fetched_zone in zip(self.driver.zone_list, zones):
<add> self.assertEqual(zone.id, fetched_zone.id)
<add> self.assertEqual(zone.name, fetched_zone.name)
<add> self.assertEqual(zone.status, fetched_zone.status)
<add>
<add> def test_region_attributes(self):
<add> self.assertIsNone(self.driver._region_dict)
<add> self.assertIsNone(self.driver._region_list)
<add>
<add> regions = self.driver.ex_list_regions()
<add>
<add> self.assertEqual(len(self.driver.region_list), len(regions))
<add> self.assertEqual(len(self.driver.region_dict), len(regions))
<add> for region, fetched_region in zip(self.driver.region_list, regions):
<add> self.assertEqual(region.id, fetched_region.id)
<add> self.assertEqual(region.name, fetched_region.name)
<add> self.assertEqual(region.status, fetched_region.status)
<add>
<ide>
<ide> class GCEMockHttp(MockHttp, unittest.TestCase):
<ide> fixtures = ComputeFileFixtures("gce") | 1 |
Ruby | Ruby | install the brew command with a relative symlink | 3c3f1a1c921b8f5fdcc7d71e59d189fec5421771 | <ide><path>Cellar/homebrew/brewkit.rb
<ide> def system cmd
<ide> if $0 == __FILE__
<ide> d=$cellar.parent+'bin'
<ide> d.mkpath unless d.exist?
<del> (d+'brew').make_symlink $cellar+'homebrew'+'brew'
<add> Dir.chdir d
<add> Pathname.new('brew').make_symlink Pathname.new('../Cellar')+'homebrew'+'brew'
<ide> end
<ide>\ No newline at end of file | 1 |
Text | Text | specify missing step | 6eaa789ec0b74fda3d51bdd6ec4600c23cfdce3e | <ide><path>docs/GettingStarted.md
<ide> next: tutorial
<ide> 2. [Xcode](https://developer.apple.com/xcode/downloads/) 6.3 or higher is recommended.
<ide> 3. [Homebrew](http://brew.sh/) is the recommended way to install io.js, watchman, and flow.
<ide> 4. Install [io.js](https://iojs.org/) 1.0 or newer. io.js is the modern version of Node.
<del> - Install **nvm** with [its setup instructions here](https://github.com/creationix/nvm#installation). Then run `nvm install iojs-v2 && nvm alias default iojs-v2`, which installs the latest compatible version of io.js and sets up your terminal so that typing `node` runs io.js. With nvm you can install multiple versions of Node and io.js and easily switch between them.
<add> - Install **nvm** with [its setup instructions here](https://github.com/creationix/nvm#installation). To benefit from the changes to your .bashrc, run `source ~/.bashrc`. Then run `nvm install iojs-v2 && nvm alias default iojs-v2`, which installs the latest compatible version of io.js and sets up your terminal so that typing `node` runs io.js. With nvm you can install multiple versions of Node and io.js and easily switch between them.
<ide> - New to [npm](https://docs.npmjs.com/)?
<ide> 5. `brew install watchman`. We recommend installing [watchman](https://facebook.github.io/watchman/docs/install.html), otherwise you might hit a node file watching bug.
<ide> 6. `brew install flow`. If you want to use [flow](http://www.flowtype.org). | 1 |
Javascript | Javascript | add example for composite navigation | 1dc33b5f23640a60682ac879b9a3e94a4aa519d9 | <ide><path>Examples/UIExplorer/NavigationExperimental/NavigationExperimentalExample.js
<ide> const View = require('View');
<ide> */
<ide> const EXAMPLES = {
<ide> 'NavigationCardStack Example': require('./NavigationCardStack-example'),
<add> 'Header + Scenes + Tabs Example': require('./NavigationHeaderScenesTabs-example'),
<ide> };
<ide>
<ide> const EXAMPLE_STORAGE_KEY = 'NavigationExperimentalExample';
<ide><path>Examples/UIExplorer/NavigationExperimental/NavigationHeaderScenesTabs-example.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * The examples provided by Facebook are for non-commercial testing and
<add> * evaluation purposes only.
<add> *
<add> * Facebook reserves all rights not expressly granted.
<add> *
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add> * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add> * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
<add> * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
<add> * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
<add> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>*/
<add>'use strict';
<add>
<add>const NavigationExampleRow = require('./NavigationExampleRow');
<add>const React = require('react');
<add>const ReactNative = require('react-native');
<add>
<add>/**
<add> * Basic example that shows how to use <NavigationCardStack /> to build
<add> * an app with composite navigation system.
<add> */
<add>
<add>const {
<add> Component,
<add> PropTypes,
<add>} = React;
<add>
<add>const {
<add> NavigationExperimental,
<add> ScrollView,
<add> StyleSheet,
<add> Text,
<add> TouchableOpacity,
<add> View,
<add>} = ReactNative;
<add>
<add>const {
<add> CardStack: NavigationCardStack,
<add> Header: NavigationHeader,
<add> PropTypes: NavigationPropTypes,
<add> StateUtils: NavigationStateUtils,
<add>} = NavigationExperimental;
<add>
<add>// First Step.
<add>// Define what app navigation state will look like.
<add>function createAppNavigationState(): Object {
<add> return {
<add> // Three tabs.
<add> tabs: {
<add> index: 0,
<add> routes: [
<add> {key: 'apple'},
<add> {key: 'banana'},
<add> {key: 'orange'},
<add> ],
<add> },
<add> // Scenes for the `apple` tab.
<add> apple: {
<add> index: 0,
<add> routes: [{key: 'Apple Home'}],
<add> },
<add> // Scenes for the `banana` tab.
<add> banana: {
<add> index: 0,
<add> routes: [{key: 'Banana Home'}],
<add> },
<add> // Scenes for the `orange` tab.
<add> orange: {
<add> index: 0,
<add> routes: [{key: 'Orange Home'}],
<add> },
<add> };
<add>}
<add>
<add>// Next step.
<add>// Define what app navigation state shall be updated.
<add>function updateAppNavigationState(
<add> state: Object,
<add> action: Object,
<add>): Object {
<add> let {type} = action;
<add> if (type === 'BackAction') {
<add> type = 'pop';
<add> }
<add>
<add> switch (type) {
<add> case 'push': {
<add> // Push a route into the scenes stack.
<add> const route: Object = action.route;
<add> const {tabs} = state;
<add> const tabKey = tabs.routes[tabs.index].key;
<add> const scenes = state[tabKey];
<add> const nextScenes = NavigationStateUtils.push(scenes, route);
<add> if (scenes !== nextScenes) {
<add> return {
<add> ...state,
<add> [tabKey]: nextScenes,
<add> };
<add> }
<add> break;
<add> }
<add>
<add> case 'pop': {
<add> // Pops a route from the scenes stack.
<add> const {tabs} = state;
<add> const tabKey = tabs.routes[tabs.index].key;
<add> const scenes = state[tabKey];
<add> const nextScenes = NavigationStateUtils.pop(scenes);
<add> if (scenes !== nextScenes) {
<add> return {
<add> ...state,
<add> [tabKey]: nextScenes,
<add> };
<add> }
<add> break;
<add> }
<add>
<add> case 'selectTab': {
<add> // Switches the tab.
<add> const tabKey: string = action.tabKey;
<add> const tabs = NavigationStateUtils.jumpTo(state.tabs, tabKey);
<add> if (tabs !== state.tabs) {
<add> return {
<add> ...state,
<add> tabs,
<add> };
<add> }
<add> }
<add> }
<add> return state;
<add>}
<add>
<add>// Next step.
<add>// Defines a helper function that creates a HOC (higher-order-component)
<add>// which provides a function `navigate` through component props. The
<add>// `navigate` function will be used to invoke navigation changes.
<add>// This serves a convenient way for a component to navigate.
<add>function createAppNavigationContainer(ComponentClass) {
<add> const key = '_yourAppNavigationContainerNavigateCall';
<add>
<add> class Container extends Component {
<add> static contextTypes = {
<add> [key]: PropTypes.func,
<add> };
<add>
<add> static childContextTypes = {
<add> [key]: PropTypes.func.isRequired,
<add> };
<add>
<add> static propTypes = {
<add> navigate: PropTypes.func,
<add> };
<add>
<add> getChildContext(): Object {
<add> return {
<add> [key]: this.context[key] || this.props.navigate,
<add> };
<add> }
<add>
<add> render(): ReactElement {
<add> const navigate = this.context[key] || this.props.navigate;
<add> return <ComponentClass {...this.props} navigate={navigate} />;
<add> }
<add> }
<add>
<add> return Container;
<add>}
<add>
<add>// Next step.
<add>// Define a component for your application that owns the navigation state.
<add>class YourApplication extends Component {
<add>
<add> static propTypes = {
<add> onExampleExit: PropTypes.func,
<add> };
<add>
<add> // This sets up the initial navigation state.
<add> constructor(props, context) {
<add> super(props, context);
<add> // This sets up the initial navigation state.
<add> this.state = createAppNavigationState();
<add> this._navigate = this._navigate.bind(this);
<add> }
<add>
<add> render(): ReactElement {
<add> // User your own navigator (see next step).
<add> return (
<add> <YourNavigator
<add> appNavigationState={this.state}
<add> navigate={this._navigate}
<add> />
<add> );
<add> }
<add>
<add> // This public method is optional. If exists, the UI explorer will call it
<add> // the "back button" is pressed. Normally this is the cases for Android only.
<add> handleBackAction(): boolean {
<add> return this._onNavigate({type: 'pop'});
<add> }
<add>
<add> // This handles the navigation state changes. You're free and responsible
<add> // to define the API that changes that navigation state. In this exmaple,
<add> // we'd simply use a `updateAppNavigationState` to update the navigation
<add> // state.
<add> _navigate(action: Object): void {
<add> if (action.type === 'exit') {
<add> // Exits the example. `this.props.onExampleExit` is provided
<add> // by the UI Explorer.
<add> this.props.onExampleExit && this.props.onExampleExit();
<add> return;
<add> }
<add>
<add> const state = updateAppNavigationState(
<add> this.state,
<add> action,
<add> );
<add>
<add> // `updateAppNavigationState` (which uses NavigationStateUtils) gives you
<add> // back the same `state` if nothing has changed. You could use
<add> // that to avoid redundant re-rendering.
<add> if (this.state !== state) {
<add> this.setState(state);
<add> }
<add> }
<add>}
<add>
<add>// Next step.
<add>// Define your own controlled navigator.
<add>const YourNavigator = createAppNavigationContainer(class extends Component {
<add> static propTypes = {
<add> appNavigationState: PropTypes.shape({
<add> apple: NavigationPropTypes.navigationState.isRequired,
<add> banana: NavigationPropTypes.navigationState.isRequired,
<add> orange: NavigationPropTypes.navigationState.isRequired,
<add> tabs: NavigationPropTypes.navigationState.isRequired,
<add> }),
<add> navigate: PropTypes.func.isRequired,
<add> };
<add>
<add> // This sets up the methods (e.g. Pop, Push) for navigation.
<add> constructor(props: any, context: any) {
<add> super(props, context);
<add> this._renderHeader = this._renderHeader.bind(this);
<add> this._renderScene = this._renderScene.bind(this);
<add> }
<add>
<add> // Now use the `NavigationCardStack` to render the scenes.
<add> render(): ReactElement {
<add> const {appNavigationState} = this.props;
<add> const {tabs} = appNavigationState;
<add> const tabKey = tabs.routes[tabs.index].key;
<add> const scenes = appNavigationState[tabKey];
<add>
<add> return (
<add> <View style={styles.navigator}>
<add> <NavigationCardStack
<add> key={'stack_' + tabKey}
<add> onNavigate={this.props.navigate}
<add> navigationState={scenes}
<add> renderOverlay={this._renderHeader}
<add> renderScene={this._renderScene}
<add> style={styles.navigatorCardStack}
<add> />
<add> <YourTabs
<add> navigationState={tabs}
<add> />
<add> </View>
<add> );
<add> }
<add>
<add> // Render the header.
<add> // The detailed spec of `sceneProps` is defined at `NavigationTypeDefinition`
<add> // as type `NavigationSceneRendererProps`.
<add> _renderHeader(sceneProps: Object): ReactElement {
<add> return (
<add> <YourHeader
<add> {...sceneProps}
<add> />
<add> );
<add> }
<add>
<add> // Render a scene for route.
<add> // The detailed spec of `sceneProps` is defined at `NavigationTypeDefinition`
<add> // as type `NavigationSceneRendererProps`.
<add> _renderScene(sceneProps: Object): ReactElement {
<add> return (
<add> <YourScene
<add> {...sceneProps}
<add> />
<add> );
<add> }
<add>});
<add>
<add>// Next step.
<add>// Define your own header.
<add>const YourHeader = createAppNavigationContainer(class extends Component {
<add> static propTypes = {
<add> ...NavigationPropTypes.SceneRendererProps,
<add> navigate: PropTypes.func.isRequired,
<add> };
<add>
<add> constructor(props: Object, context: any) {
<add> super(props, context);
<add> this._renderTitleComponent = this._renderTitleComponent.bind(this);
<add> }
<add>
<add> render(): ReactElement {
<add> return (
<add> <NavigationHeader
<add> {...this.props}
<add> renderTitleComponent={this._renderTitleComponent}
<add> onNavigate={this.props.navigate}
<add> />
<add> );
<add> }
<add>
<add> _renderTitleComponent(): ReactElement {
<add> return (
<add> <NavigationHeader.Title>
<add> {this.props.scene.route.key}
<add> </NavigationHeader.Title>
<add> );
<add> }
<add>});
<add>
<add>// Next step.
<add>// Define your own scene.
<add>const YourScene = createAppNavigationContainer(class extends Component {
<add> static propTypes = {
<add> ...NavigationPropTypes.SceneRendererProps,
<add> navigate: PropTypes.func.isRequired,
<add> };
<add>
<add> constructor(props: Object, context: any) {
<add> super(props, context);
<add> this._exit = this._exit.bind(this);
<add> this._popRoute = this._popRoute.bind(this);
<add> this._pushRoute = this._pushRoute.bind(this);
<add> }
<add>
<add> render(): ReactElement {
<add> return (
<add> <ScrollView style={styles.scrollView}>
<add> <NavigationExampleRow
<add> text="Push Route"
<add> onPress={this._pushRoute}
<add> />
<add> <NavigationExampleRow
<add> text="Pop Route"
<add> onPress={this._popRoute}
<add> />
<add> <NavigationExampleRow
<add> text="Exit Header + Scenes + Tabs Example"
<add> onPress={this._exit}
<add> />
<add> </ScrollView>
<add> );
<add> }
<add>
<add> _pushRoute(): void {
<add> // Just push a route with a new unique key.
<add> const route = {key: '[' + this.props.scenes.length + ']-' + Date.now()};
<add> this.props.navigate({type: 'push', route});
<add> }
<add>
<add> _popRoute(): void {
<add> this.props.navigate({type: 'pop'});
<add> }
<add>
<add> _exit(): void {
<add> this.props.navigate({type: 'exit'});
<add> }
<add>});
<add>
<add>// Next step.
<add>// Define your own tabs.
<add>const YourTabs = createAppNavigationContainer(class extends Component {
<add> static propTypes = {
<add> navigationState: NavigationPropTypes.navigationState.isRequired,
<add> navigate: PropTypes.func.isRequired,
<add> };
<add>
<add> constructor(props: Object, context: any) {
<add> super(props, context);
<add> }
<add>
<add> render(): ReactElement {
<add> return (
<add> <View style={styles.tabs}>
<add> {this.props.navigationState.routes.map(this._renderTab, this)}
<add> </View>
<add> );
<add> }
<add>
<add> _renderTab(route: Object, index: number): ReactElement {
<add> return (
<add> <YourTab
<add> key={route.key}
<add> route={route}
<add> selected={this.props.navigationState.index === index}
<add> />
<add> );
<add> }
<add>});
<add>
<add>// Next step.
<add>// Define your own Tab
<add>const YourTab = createAppNavigationContainer(class extends Component {
<add>
<add> static propTypes = {
<add> navigate: PropTypes.func.isRequired,
<add> route: NavigationPropTypes.navigationRoute.isRequired,
<add> selected: PropTypes.bool.isRequired,
<add> };
<add>
<add> constructor(props: Object, context: any) {
<add> super(props, context);
<add> this._onPress = this._onPress.bind(this);
<add> }
<add>
<add> render(): ReactElement {
<add> const style = [styles.tabText];
<add> if (this.props.selected) {
<add> style.push(styles.tabSelected);
<add> }
<add> return (
<add> <TouchableOpacity style={styles.tab} onPress={this._onPress}>
<add> <Text style={style}>
<add> {this.props.route.key}
<add> </Text>
<add> </TouchableOpacity>
<add> );
<add> }
<add>
<add> _onPress() {
<add> this.props.navigate({type: 'selectTab', tabKey: this.props.route.key});
<add> }
<add>});
<add>
<add>const styles = StyleSheet.create({
<add> navigator: {
<add> flex: 1,
<add> },
<add> navigatorCardStack: {
<add> flex: 20,
<add> },
<add> scrollView: {
<add> marginTop: 64
<add> },
<add> tabs: {
<add> flex: 1,
<add> flexDirection: 'row',
<add> },
<add> tab: {
<add> alignItems: 'center',
<add> backgroundColor: '#fff',
<add> flex: 1,
<add> justifyContent: 'center',
<add> },
<add> tabText: {
<add> color: '#222',
<add> fontWeight: '500',
<add> },
<add> tabSelected: {
<add> color: 'blue',
<add> },
<add>});
<add>
<add>module.exports = YourApplication; | 2 |
Text | Text | make corrections to the translation of index.md | f39f86197dd4d060d926d6ce7989cb798c78cd64 | <ide><path>guide/russian/working-in-tech/women-in-tech/index.md
<ide> ---
<ide> title: Women in Tech
<del>localeTitle: Женщины в технике
<add>localeTitle: Женщины в сфере технологий
<ide> ---
<del>## Женщины в технике
<add>## Женщины в сфере технологий
<ide>
<del>Из статьи [«Последняя статистика по женщинам в технике»](https://www.themuse.com/advice/the-latest-stats-on-women-in-tech) ,
<add>Из статьи [«Последняя статистика по женщинам в сфере технологий»](https://www.themuse.com/advice/the-latest-stats-on-women-in-tech) ,
<ide>
<del>> «Мы все знаем, что существует серьезный гендерный разрыв, когда речь идет о женщинах в области технологий.
<add>> «Мы все знаем, что существует серьезное гендерное неравенство, когда речь идет о женщинах в сфере технологий.
<ide> >
<del>> Хотя мы составляем большую часть рабочего места и сферу социальных медиа, мы представляем лишь крошечный процент мирового технологического мира.
<add>> Хотя мы составляем большую часть рабочих мест и сферу социальных медиа, мы представляем лишь крошечный процент мирового технологического мира.
<ide> >
<del>> И это отражено в некоторых статистиках, которые вы видите. Например, согласно докладу 2011 года Института уровня игрового поля, «82% мужчин в стартапах полагали, что их компании потратили« правильное количество времени »на разнообразие, в то время как почти 40% женщин считали, что недостаточно времени было посвящено»,
<add>> И это отражено в некоторых статистиках, которые вы можете увидеть ниже. Например, согласно докладу 2011 года Института равноправных условий, «82% мужчин в стартапах полагали, что их компании потратили« достаточное количество времени »на разнообразие, в то время как почти 40% женщин считали, что данной теме было посвящено недостаточно времени»,
<ide>
<ide> 
<ide>
<del>Хотя женщины все еще недопредставлены в технологическом мире, это не означает, что мы не делаем разницы в технологическом мире.
<add>Хотя женщины все еще недостаточно представлены в сфере технологий, это не означает, что мы не имеем значения.
<ide>
<del>В мероприятии «Женщины в техническом круге», представленном Google в Остине, женщины, которые выступали на этих мероприятиях, были вице-президентами (VP) и руководящими должностями высокого уровня от прибыльных компаний, работающих в сфере технологий. Не все из них начали свою карьеру в техническом мире, многие из которых начались как секретари и другие роли, которые часто ориентированы на женщин. Они работали и рисковал, чтобы получить, где они сейчас. Единственный совет, который, казалось, звучал от всех из них, заключался в том, что для достижения успеха вы должны рисковать.
<add>На мероприятии «Женщины в технологиях», проведенном компанией Google в Остине, женщины, выступавшие на этих мероприятиях, были вице-президентами (VP) и сотрудниками на руководящих должностях высокого уровня в прибыльных компаниях, работающих в сфере технологий. Не все из них начали свою карьеру в мире технологий, многие из которых начинали как секретари и исполняли другие роли, которые зачастую ориентированы на женщин. Они усердно работали и рисковали, чтобы достигнуть своей цели. Единственный совет, который, казалось, звучал от всех из них, заключался в том, что для достижения успеха нужно рисковать.
<ide>
<del>Вице-президент Google, выступавший на этом мероприятии, дал нам все советы: мы должны предоставить любую возможность для нас и рискнуть применить к тем работам, на которые у нас нет квалификации. Самое худшее, что произойдет, - вы отклонитесь или вы не получите интервью. Мужчины получают технические позиции не потому, что они более опытные или лучше, чем женщины, но потому, что они применяются к позициям, на которых они часто не имеют права, в то время как женщины только подают заявку на работу, на которую, по их мнению, они имеют право. Самое худшее, что вы можете сделать, это продать себя коротким, если вы хотите, чтобы что-то приняло этот риск и достигло невозможного.
<add>Вице-президент Google, выступавший на этом мероприятии, дал нам всем полезную мысль: мы должны использовать любую возможность и рискнуть подать заявления на те вакансии, для которых у нас нет необходимой квалификации. Самое худшее, что произойдет, - вам откажут или не пригласят на собеседование. Мужчины получают технические позиции не потому, что они более опытные или лучше, чем женщины, но потому, что они подают заявление на вакансии, на которые они зачастую не имеют права, в то время как женщины подают заявки лишь на те вакансии, на которые, по их мнению, они имеют право. Самое худшее, что вы можете сделать - это недооценивать себя, если вы хотите чего-либо, рискните и достигните невозможного.
<ide>
<ide> ### Дополнительная информация:
<ide>
<del>* [Почему в технике так мало женщин? Истина за памяткой Google](https://www.theguardian.com/lifeandstyle/2017/aug/08/why-are-there-so-few-women-in-tech-the-truth-behind-the-google-memo)
<del>* [Эллен Пао: Что-нибудь действительно изменилось для женщин в технике?](https://www.nytimes.com/2017/09/16/opinion/sunday/ellen-pao-sexism-tech.html)
<ide>\ No newline at end of file
<add>* [Почему в технологиях так мало женщин? Истина за памяткой Google](https://www.theguardian.com/lifeandstyle/2017/aug/08/why-are-there-so-few-women-in-tech-the-truth-behind-the-google-memo)
<add>* [Эллен Пао: Что-нибудь действительно изменилось для женщин в сфере технологий?](https://www.nytimes.com/2017/09/16/opinion/sunday/ellen-pao-sexism-tech.html) | 1 |
Javascript | Javascript | add inverted test case | 49f5d148a7ed74055b1cddd5eb091b4b351be83a | <ide><path>packages/rn-tester/js/examples/SectionList/SectionList-inverted.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @format
<add> * @flow
<add> */
<add>
<add>'use strict';
<add>import {SectionList_inverted} from './SectionListExamples';
<add>const React = require('react');
<add>
<add>exports.title = 'SectionList inverted';
<add>exports.testTitle = 'Test inverted prop';
<add>exports.category = 'ListView';
<add>exports.documentationURL = 'https://reactnative.dev/docs/sectionlist';
<add>exports.description = 'Toggle inverted to see list inverted.';
<add>exports.examples = [
<add> {
<add> title: 'SectionList inverted',
<add> render: function(): React.Element<typeof SectionList_inverted> {
<add> return <SectionList_inverted />;
<add> },
<add> },
<add>];
<ide><path>packages/rn-tester/js/examples/SectionList/SectionListExamples.js
<ide> const Item = ({title}) => (
<ide> </View>
<ide> );
<ide>
<add>export function SectionList_inverted(): React.Node {
<add> const [output, setOutput] = React.useState('inverted false');
<add> const [exampleProps, setExampleProps] = React.useState({
<add> inverted: false,
<add> });
<add>
<add> const onTest = () => {
<add> setExampleProps({
<add> inverted: !exampleProps.inverted,
<add> });
<add> setOutput(`Is inverted: ${(!exampleProps.inverted).toString()}`);
<add> };
<add>
<add> return (
<add> <SectionListExampleWithForwardedRef
<add> exampleProps={exampleProps}
<add> testOutput={output}
<add> onTest={onTest}
<add> testLabel={exampleProps.inverted ? 'Toggle false' : 'Toggle true'}
<add> />
<add> );
<add>}
<add>
<ide> export function SectionList_stickySectionHeadersEnabled(): React.Node {
<ide> const [output, setOutput] = React.useState(
<ide> 'stickySectionHeadersEnabled false',
<ide><path>packages/rn-tester/js/utils/RNTesterList.android.js
<ide> const ComponentExamples: Array<RNTesterExample> = [
<ide> module: require('../examples/SectionList/SectionList-onEndReached'),
<ide> category: 'ListView',
<ide> },
<add> {
<add> key: 'SectionList_inverted',
<add> module: require('../examples/SectionList/SectionList-inverted'),
<add> category: 'ListView',
<add> },
<ide> {
<ide> key: 'SectionList-onViewableItemsChanged',
<ide> module: require('../examples/SectionList/SectionList-onViewableItemsChanged'),
<ide><path>packages/rn-tester/js/utils/RNTesterList.ios.js
<ide> const ComponentExamples: Array<RNTesterExample> = [
<ide> module: require('../examples/ScrollView/ScrollViewAnimatedExample'),
<ide> supportsTVOS: true,
<ide> },
<add> {
<add> key: 'SectionList-inverted',
<add> module: require('../examples/SectionList/SectionList-inverted'),
<add> category: 'ListView',
<add> },
<ide> {
<ide> key: 'SectionList_stickyHeadersEnabled',
<ide> module: require('../examples/SectionList/SectionList-stickyHeadersEnabled'), | 4 |
PHP | PHP | fix a typo in docblock | 031965af630947c21b5e8414042fa754e1d84bad | <ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> class FixtureManager
<ide> * Modify the debug mode.
<ide> *
<ide> * @param bool $debug Whether or not fixture debug mode is enabled.
<del> * @retun void
<add> * @return void
<ide> */
<ide> public function setDebug($debug)
<ide> { | 1 |
PHP | PHP | correct doc blocks | e343d46ddeff9c5cb10165356cc66535b5fc35eb | <ide><path>src/View/Helper.php
<ide> class Helper implements EventListener {
<ide> /**
<ide> * The View instance this helper is attached to
<ide> *
<del> * @var View
<add> * @var \Cake\View\View
<ide> */
<ide> protected $_View;
<ide>
<ide> /**
<ide> * Default Constructor
<ide> *
<del> * @param View $View The View this helper is being attached to.
<add> * @param \Cake\View\View $View The View this helper is being attached to.
<ide> * @param array $config Configuration settings for the helper.
<ide> */
<ide> public function __construct(View $View, array $config = array()) {
<ide><path>src/View/Helper/HtmlHelper.php
<ide> class HtmlHelper extends Helper {
<ide> *
<ide> * Using the `templates` option you can redefine the tag HtmlHelper will use.
<ide> *
<del> * @param View $View The View this helper is being attached to.
<add> * @param \Cake\View\View $View The View this helper is being attached to.
<ide> * @param array $config Configuration settings for the helper.
<ide> */
<ide> public function __construct(View $View, array $config = array()) {
<ide><path>src/View/Helper/NumberHelper.php
<ide> class NumberHelper extends Helper {
<ide> * - `engine` Class name to use to replace Cake\I18n\Number functionality
<ide> * The class needs to be placed in the `Utility` directory.
<ide> *
<del> * @param View $View The View this helper is being attached to.
<add> * @param \Cake\View\View $View The View this helper is being attached to.
<ide> * @param array $config Configuration settings for the helper
<ide> * @throws \Cake\Core\Exception\Exception When the engine class could not be found.
<ide> */
<ide><path>src/View/Helper/TextHelper.php
<ide> class TextHelper extends Helper {
<ide> * - `engine` Class name to use to replace String functionality.
<ide> * The class needs to be placed in the `Utility` directory.
<ide> *
<del> * @param View $View the view object the helper is attached to.
<add> * @param \Cake\View\View $View the view object the helper is attached to.
<ide> * @param array $config Settings array Settings array
<ide> * @throws \Cake\Core\Exception\Exception when the engine class could not be found.
<ide> */ | 4 |
Go | Go | use ms_private instead of ms_slave"" | 557e4fef4418a251dd3a6817b97e5c1be055cbf3 | <ide><path>pkg/libcontainer/nsinit/mount.go
<ide> const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NOD
<ide> // is no longer in use, the mounts will be removed automatically
<ide> func setupNewMountNamespace(rootfs, console string, readonly bool) error {
<ide> // mount as slave so that the new mounts do not propagate to the host
<del> if err := system.Mount("", "/", "", syscall.MS_SLAVE|syscall.MS_REC, ""); err != nil {
<add> if err := system.Mount("", "/", "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
<ide> return fmt.Errorf("mounting / as slave %s", err)
<ide> }
<ide> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, ""); err != nil { | 1 |
Ruby | Ruby | add missing require | a01cf703e23a96bad044766efad58b4d56d8bf11 | <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb
<ide> require "active_support/core_ext/hash/keys"
<ide> require "active_support/core_ext/hash/reverse_merge"
<add>require "active_support/core_ext/hash/indifferent_access"
<ide>
<ide> module ActiveSupport
<ide> # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered | 1 |
Text | Text | add oncontextmenu to events doc | 1aa9580484bed39d57713ab60bb6a6b901a9b902 | <ide><path>docs/docs/ref-05-events.md
<ide> For more information about the onChange event, see [Forms](/react/docs/forms.htm
<ide> Event names:
<ide>
<ide> ```
<del>onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave
<del>onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
<add>onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
<add>onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
<ide> onMouseMove onMouseOut onMouseOver onMouseUp
<ide> ```
<ide>
<ide><path>docs/docs/ref-05-events.zh-CN.md
<ide> onChange onInput onSubmit
<ide> 事件名称:
<ide>
<ide> ```
<del>onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave
<del>onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
<add>onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
<add>onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
<ide> onMouseMove onMouseOut onMouseOver onMouseUp
<ide> ```
<ide> | 2 |
Javascript | Javascript | remove space at end of line | 4f314fff397a7036f176bda77bb3739ae97cdb99 | <ide><path>extensions/firefox/bootstrap.js
<ide> let Factory = {
<ide> },
<ide>
<ide> // nsIFactory
<del> lockFactory: function lockFactory(lock) {
<add> lockFactory: function lockFactory(lock) {
<ide> // No longer used as of gecko 1.7.
<ide> throw Cr.NS_ERROR_NOT_IMPLEMENTED;
<ide> } | 1 |
PHP | PHP | add support for testing eloquent model events | e6f806cf35e1352d849d97b62e217398ab2c7f99 | <ide><path>src/Illuminate/Foundation/Testing/Concerns/MocksApplicationServices.php
<ide>
<ide> use Mockery;
<ide> use Exception;
<add>use Illuminate\Database\Eloquent\Model;
<ide>
<ide> trait MocksApplicationServices
<ide> {
<ide> protected function withoutEvents()
<ide> $this->firedEvents[] = $called;
<ide> });
<ide>
<add> $mock->shouldReceive('until')->andReturnUsing(function ($called) {
<add> $this->firedEvents[] = $called;
<add>
<add> return true;
<add> });
<add>
<ide> $this->app->instance('events', $mock);
<add> Model::setEventDispatcher($mock);
<ide>
<ide> return $this;
<ide> } | 1 |
PHP | PHP | add withoutmiddleware docbloc | 6e14167dd25827128e38429f4fa3c7985c497d89 | <ide><path>src/Illuminate/Support/Facades/Route.php
<ide> * @method static \Illuminate\Routing\RouteRegistrar prefix(string $prefix)
<ide> * @method static \Illuminate\Routing\RouteRegistrar scopeBindings()
<ide> * @method static \Illuminate\Routing\RouteRegistrar where(array $where)
<add> * @method static \Illuminate\Routing\RouteRegistrar withoutMiddleware(array|string $middleware)
<ide> * @method static \Illuminate\Routing\Router|\Illuminate\Routing\RouteRegistrar group(\Closure|string|array $attributes, \Closure|string $routes)
<ide> * @method static \Illuminate\Routing\ResourceRegistrar resourceVerbs(array $verbs = [])
<ide> * @method static string|null currentRouteAction() | 1 |
PHP | PHP | use newemptyentity() as more clear name | 5df5f02b146af1eb0087d1f98e32615b0be1cde7 | <ide><path>src/Datasource/RepositoryInterface.php
<ide> public function delete(EntityInterface $entity, $options = []): bool;
<ide> *
<ide> * @return \Cake\Datasource\EntityInterface
<ide> */
<del> public function createEntity(): EntityInterface;
<add> public function newEmptyEntity(): EntityInterface;
<ide>
<ide> /**
<ide> * Create a new entity + associated entities from an array.
<ide><path>src/ORM/Behavior/Translate/TranslateStrategyTrait.php
<ide> public function buildMarshalMap(Marshaller $marshaller, array $map, array $optio
<ide> }
<ide> foreach ($value as $language => $fields) {
<ide> if (!isset($translations[$language])) {
<del> $translations[$language] = $this->table->createEntity();
<add> $translations[$language] = $this->table->newEmptyEntity();
<ide> }
<ide> $marshaller->merge($translations[$language], $fields, $options);
<ide> /** @var \Cake\Datasource\EntityInterface $translation */
<ide><path>src/ORM/Table.php
<ide> protected function _processFindOrCreate($search, ?callable $callback = null, $op
<ide> if ($row !== null) {
<ide> return $row;
<ide> }
<del> $entity = $this->createEntity();
<add> $entity = $this->newEmptyEntity();
<ide> if ($options['defaults'] && is_array($search)) {
<ide> $accessibleFields = array_combine(array_keys($search), array_fill(0, count($search), true));
<ide> $entity = $this->patchEntity($entity, $search, ['accessibleFields' => $accessibleFields]);
<ide> public function marshaller(): Marshaller
<ide> *
<ide> * @return \Cake\Datasource\EntityInterface
<ide> */
<del> public function createEntity(): EntityInterface
<add> public function newEmptyEntity(): EntityInterface
<ide> {
<ide> $class = $this->getEntityClass();
<ide>
<ide><path>src/View/Form/EntityContext.php
<ide> public function entity(?array $path = null)
<ide> if (!$isLast && $next === null && $prop !== '_ids') {
<ide> $table = $this->_getTable($path);
<ide>
<del> return $table->createEntity();
<add> return $table->newEmptyEntity();
<ide> }
<ide>
<ide> $isTraversable = (
<ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php
<ide> protected function getMockRepository()
<ide> $model = $this->getMockBuilder(RepositoryInterface::class)
<ide> ->setMethods([
<ide> 'getAlias', 'setAlias', 'setRegistryAlias', 'getRegistryAlias', 'hasField',
<del> 'find', 'get', 'query', 'updateAll', 'deleteAll', 'createEntity',
<add> 'find', 'get', 'query', 'updateAll', 'deleteAll', 'newEmptyEntity',
<ide> 'exists', 'save', 'delete', 'newEntity', 'newEntities', 'patchEntity', 'patchEntities',
<ide> ])
<ide> ->getMock();
<ide><path>tests/TestCase/Datasource/PaginatorTest.php
<ide> protected function getMockRepository()
<ide> $model = $this->getMockBuilder(RepositoryInterface::class)
<ide> ->setMethods([
<ide> 'getAlias', 'setAlias', 'setRegistryAlias', 'getRegistryAlias', 'hasField',
<del> 'find', 'get', 'query', 'updateAll', 'deleteAll', 'createEntity',
<add> 'find', 'get', 'query', 'updateAll', 'deleteAll', 'newEmptyEntity',
<ide> 'exists', 'save', 'delete', 'newEntity', 'newEntities', 'patchEntity', 'patchEntities',
<ide> ])
<ide> ->getMock();
<ide><path>tests/TestCase/ORM/Association/HasManyTest.php
<ide> public function testSaveAssociatedNotEmptyNotIterable()
<ide> 'saveStrategy' => HasMany::SAVE_APPEND,
<ide> ]);
<ide>
<del> $entity = $articles->createEntity();
<add> $entity = $articles->newEmptyEntity();
<ide> $entity->set('comments', 'oh noes');
<ide>
<ide> $association->saveAssociated($entity);
<ide> public function testSaveAssociatedEmptySetWithAppendStrategyDoesNotAffectAssocia
<ide> $comments = $association->find();
<ide> $this->assertNotEmpty($comments);
<ide>
<del> $entity = $articles->createEntity();
<add> $entity = $articles->newEmptyEntity();
<ide> $entity->set('comments', $value);
<ide>
<ide> $this->assertSame($entity, $association->saveAssociated($entity));
<ide> public function testSaveAssociatedEmptySetWithReplaceStrategyDoesNotAffectAssoci
<ide> $comments = $association->find();
<ide> $this->assertNotEmpty($comments);
<ide>
<del> $entity = $articles->createEntity();
<add> $entity = $articles->newEmptyEntity();
<ide> $entity->set('comments', $value);
<ide>
<ide> $this->assertSame($entity, $association->saveAssociated($entity));
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php
<ide> public function testSaveNewRecordWithTranslatesField()
<ide> ],
<ide> ];
<ide>
<del> $article = $table->patchEntity($table->createEntity(), $data);
<add> $article = $table->patchEntity($table->newEmptyEntity(), $data);
<ide> $result = $table->save($article);
<ide>
<ide> $this->assertNotFalse($result);
<ide> public function testBuildMarshalMapBuildEntities()
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<ide> $map = $translate->buildMarshalMap($table->marshaller(), [], []);
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $data = [
<ide> 'en' => [
<ide> 'title' => 'English Title',
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php
<ide> public function testSaveNewRecordWithTranslatesField()
<ide> ],
<ide> ];
<ide>
<del> $article = $table->patchEntity($table->createEntity(), $data);
<add> $article = $table->patchEntity($table->newEmptyEntity(), $data);
<ide> $result = $table->save($article);
<ide>
<ide> $this->assertNotFalse($result);
<ide> public function testBuildMarshalMapNonArrayData()
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<ide> $map = $translate->buildMarshalMap($table->marshaller(), [], []);
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $result = $map['_translations']('garbage', $entity);
<ide> $this->assertNull($result, 'Non-array should not error out.');
<ide> $this->assertEmpty($entity->getErrors());
<ide> public function testBuildMarshalMapBuildEntities()
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<ide> $map = $translate->buildMarshalMap($table->marshaller(), [], []);
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $data = [
<ide> 'en' => [
<ide> 'title' => 'English Title',
<ide> public function testBuildMarshalMapBuildEntitiesValidationErrors()
<ide> $table->setValidator('custom', $validator);
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $map = $translate->buildMarshalMap($table->marshaller(), [], []);
<ide> $data = [
<ide> 'en' => [
<ide> public function testBuildMarshalMapUpdateExistingEntities()
<ide> ]);
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $es = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
<ide> $en = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
<ide> $entity->set('_translations', [
<ide> public function testBuildMarshalMapUpdateEntitiesValidationErrors()
<ide> $table->setValidator('custom', $validator);
<ide> $translate = $table->behaviors()->get('Translate');
<ide>
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $es = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
<ide> $en = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
<ide> $entity->set('_translations', [
<ide><path>tests/TestCase/ORM/MarshallerTest.php
<ide> class MarshallerTest extends TestCase
<ide> ];
<ide>
<ide> /**
<del> * @var Table
<add> * @var \Cake\ORM\Table
<ide> */
<ide> protected $articles;
<ide>
<ide> /**
<del> * @var Table
<add> * @var \Cake\ORM\Table
<ide> */
<ide> protected $comments;
<ide>
<ide> /**
<del> * @var Table
<add> * @var \Cake\ORM\Table
<ide> */
<ide> protected $users;
<ide>
<ide> /**
<del> * @var Table
<add> * @var \Cake\ORM\Table
<ide> */
<ide> protected $tags;
<ide>
<ide> /**
<del> * @var Table
<add> * @var \Cake\ORM\Table
<ide> */
<ide> protected $articleTags;
<ide>
<ide> public function testMergeWithTranslations()
<ide> ];
<ide>
<ide> $marshall = new Marshaller($this->articles);
<del> $entity = $this->articles->createEntity();
<add> $entity = $this->articles->newEmptyEntity();
<ide> $result = $marshall->merge($entity, $data, []);
<ide>
<ide> $this->assertSame($entity, $result);
<ide> public function testMergeWithTranslations()
<ide> $this->assertCount(2, $translations);
<ide> $this->assertInstanceOf(OpenArticleEntity::class, $translations['en']);
<ide> $this->assertInstanceOf(OpenArticleEntity::class, $translations['es']);
<del> $this->assertEquals($data['_translations']['en'], $translations['en']->toArray());
<add>
<add> /** @var \Cake\Datasource\EntityInterface $translation */
<add> $translation = $translations['en'];
<add> $this->assertEquals($data['_translations']['en'], $translation->toArray());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php
<ide> public function testSaveWithCallbacks()
<ide> return $query->contain('Authors');
<ide> });
<ide>
<del> $article = $articles->createEntity();
<add> $article = $articles->newEmptyEntity();
<ide> $article->title = 'Foo';
<ide> $article->body = 'Bar';
<ide> $this->assertSame($article, $articles->save($article));
<ide> public function testSaveWithExpressionProperty()
<ide> {
<ide> $this->loadFixtures('Articles');
<ide> $articles = $this->getTableLocator()->get('Articles');
<del> $article = $articles->createEntity();
<add> $article = $articles->newEmptyEntity();
<ide> $article->title = new QueryExpression("SELECT 'jose'");
<ide> $this->assertSame($article, $articles->save($article));
<ide> }
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testEntitySourceExistingAndNew()
<ide> $table = $this->getTableLocator()->get('TestPlugin.Authors');
<ide>
<ide> $existingAuthor = $table->find()->first();
<del> $newAuthor = $table->createEntity();
<add> $newAuthor = $table->newEmptyEntity();
<ide>
<ide> $this->assertEquals('TestPlugin.Authors', $existingAuthor->getSource());
<ide> $this->assertEquals('TestPlugin.Authors', $newAuthor->getSource());
<ide> public function testCreateEntityAndValidation()
<ide> $table = $this->getTableLocator()->get('Articles');
<ide> $table->getValidator()->requirePresence('title');
<ide>
<del> $entity = $table->createEntity();
<add> $entity = $table->newEmptyEntity();
<ide> $this->assertEmpty($entity->getErrors());
<ide> }
<ide>
<ide> function (EventInterface $event, EntityInterface $entity, ArrayObject $options)
<ide> }
<ide>
<ide> /**
<del> * Tests that calling createEntity() on a table sets the right source alias.
<add> * Tests that calling newEmptyEntity() on a table sets the right source alias.
<ide> *
<ide> * @return void
<ide> */
<ide> public function testSetEntitySource()
<ide> {
<ide> $table = $this->getTableLocator()->get('Articles');
<del> $this->assertEquals('Articles', $table->createEntity()->getSource());
<add> $this->assertEquals('Articles', $table->newEmptyEntity()->getSource());
<ide>
<ide> $this->loadPlugins(['TestPlugin']);
<ide> $table = $this->getTableLocator()->get('TestPlugin.Comments');
<del> $this->assertEquals('TestPlugin.Comments', $table->createEntity()->getSource());
<add> $this->assertEquals('TestPlugin.Comments', $table->newEmptyEntity()->getSource());
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> public function testValSchemaDefault()
<ide> $table = $this->getTableLocator()->get('Articles');
<ide> $column = $table->getSchema()->getColumn('title');
<ide> $table->getSchema()->addColumn('title', ['default' => 'default title'] + $column);
<del> $row = $table->createEntity();
<add> $row = $table->newEmptyEntity();
<ide>
<ide> $context = new EntityContext($this->request, [
<ide> 'entity' => $row,
<ide> public function testValAssociatedSchemaDefault()
<ide> $associatedTable = $table->hasMany('Comments')->getTarget();
<ide> $column = $associatedTable->getSchema()->getColumn('comment');
<ide> $associatedTable->getSchema()->addColumn('comment', ['default' => 'default comment'] + $column);
<del> $row = $table->createEntity();
<add> $row = $table->newEmptyEntity();
<ide>
<ide> $context = new EntityContext($this->request, [
<ide> 'entity' => $row,
<ide> public function testValAssociatedJoinTableSchemaDefault()
<ide> 'default' => 'default join table column value',
<ide> 'type' => 'text',
<ide> ]);
<del> $row = $table->createEntity();
<add> $row = $table->newEmptyEntity();
<ide>
<ide> $context = new EntityContext($this->request, [
<ide> 'entity' => $row,
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testControlCheckbox()
<ide> {
<ide> $articles = $this->getTableLocator()->get('Articles');
<ide> $articles->getSchema()->addColumn('active', ['type' => 'boolean', 'default' => null]);
<del> $article = $articles->createEntity();
<add> $article = $articles->newEmptyEntity();
<ide>
<ide> $this->Form->create($article);
<ide>
<ide> public function testTextDefaultValue()
<ide> ['default' => 'default title'] + $title
<ide> );
<ide>
<del> $entity = $Articles->createEntity();
<add> $entity = $Articles->newEmptyEntity();
<ide> $this->Form->create($entity);
<ide>
<ide> // Get default value from schema
<ide> public function testRadioDefaultValue()
<ide> ['default' => '1'] + $title
<ide> );
<ide>
<del> $this->Form->create($Articles->createEntity());
<add> $this->Form->create($Articles->newEmptyEntity());
<ide>
<ide> $result = $this->Form->radio('title', ['option A', 'option B']);
<ide> $expected = [
<ide> public function testCheckboxDefaultValue()
<ide> ['type' => 'boolean', 'null' => false, 'default' => true]
<ide> );
<ide>
<del> $this->Form->create($Articles->createEntity());
<add> $this->Form->create($Articles->newEmptyEntity());
<ide> $result = $this->Form->checkbox('published', ['hiddenField' => false]);
<ide> $expected = ['input' => ['type' => 'checkbox', 'name' => 'published', 'value' => '1', 'checked' => 'checked']];
<ide> $this->assertHtml($expected, $result);
<ide> public function testSourcesValueDoesntExistPassThrough()
<ide> $this->View->setRequest($this->View->getRequest()->withQueryParams(['category' => 'sesame-cookies']));
<ide>
<ide> $articles = $this->getTableLocator()->get('Articles');
<del> $entity = $articles->createEntity();
<add> $entity = $articles->newEmptyEntity();
<ide> $this->Form->create($entity);
<ide>
<ide> $this->Form->setValueSources(['query', 'context']); | 14 |
Ruby | Ruby | add limit to repology api | afe9a48373cf2c1a423464b45a464d3971ee114b | <ide><path>Library/Homebrew/dev-cmd/bump.rb
<ide> def bump
<ide>
<ide> response
<ide> else
<del> Repology.parse_api_response
<add> Repology.parse_api_response(requested_limit)
<ide> end
<ide>
<ide> validated_formulae = {}
<ide><path>Library/Homebrew/utils/repology.rb
<ide> module Repology
<ide> module_function
<ide>
<del> MAX_PAGINATION = 15
<del>
<ide> def query_api(last_package_in_response = "")
<ide> last_package_in_response += "/" if last_package_in_response.present?
<ide> url = "https://repology.org/api/v1/projects/#{last_package_in_response}?inrepo=homebrew&outdated=1"
<ide> def single_package_query(name)
<ide> homebrew.empty? ? nil : { name => data }
<ide> end
<ide>
<del> def parse_api_response
<add> def parse_api_response(limit = nil)
<ide> ohai "Querying outdated packages from Repology"
<ide>
<add> page_no = 1
<ide> outdated_packages = query_api
<del> last_package_index = outdated_packages.size - 1
<ide> response_size = outdated_packages.size
<del> page_no = 1
<add> last_package_index = outdated_packages.size - 1
<add> max_pagination = limit.nil? ? 15 : (limit.to_f / 200).ceil
<ide>
<del> while response_size > 1 && page_no <= MAX_PAGINATION
<add> while response_size > 1 && page_no <= max_pagination
<ide> odebug "Paginating Repology API page: #{page_no}"
<del>
<ide> last_package_in_response = outdated_packages.keys[last_package_index]
<ide> response = query_api(last_package_in_response)
<ide>
<ide> response_size = response.size
<ide> outdated_packages.merge!(response)
<ide> last_package_index = outdated_packages.size - 1
<del> page_no += 1
<ide> end
<add>
<add> outdated_packages = outdated_packages.first(limit) if outdated_packages.size > limit
<ide>
<ide> puts "#{outdated_packages.size} outdated #{"package".pluralize(outdated_packages.size)} found"
<ide> puts | 2 |
Ruby | Ruby | use hash#each_value rather than discarding key | 46f8be1d9ed12aa54cd472f2ae70aef7c6e35e6b | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_tmpdir
<ide> def check_missing_deps
<ide> return unless HOMEBREW_CELLAR.exist?
<ide> s = Set.new
<del> Homebrew.missing_deps(Formula.installed).each do |_, deps|
<add> Homebrew.missing_deps(Formula.installed).each_value do |deps|
<ide> s.merge deps
<ide> end
<ide> | 1 |
Javascript | Javascript | update other authentication methods | 01e86c74bce313b12172256d8829358741890758 | <ide><path>config/passport.js
<ide> passport.use(new LinkedInStrategy(secrets.linkedin, function(req, accessToken, r
<ide> User.findOne({ linkedin: profile.id }, function(err, existingUser) {
<ide> if (existingUser) return done(null, existingUser);
<ide> User.findOne({ email: profile._json.emailAddress }, function(err, existingEmailUser) {
<del> if (existingEmailUser) {
<del> // req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with LinkedIn manually from Account Settings.' });
<del> // done(err);
<del> var user = existingEmailUser;
<del> user.linkedin = profile.id;
<del> user.tokens.push({ kind: 'linkedin', accessToken: accessToken });
<del> user.email = profile._json.emailAddress;
<del> user.profile.name = profile.displayName;
<del> user.profile.location = profile._json.location.name;
<del> user.profile.picture = profile._json.pictureUrl;
<del> user.profile.website = profile._json.publicProfileUrl;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> } else {
<del> var user = new User();
<del> user.linkedin = profile.id;
<del> user.tokens.push({ kind: 'linkedin', accessToken: accessToken });
<del> user.email = profile._json.emailAddress;
<del> user.profile.name = profile.displayName;
<del> user.profile.location = profile._json.location.name;
<del> user.profile.picture = profile._json.pictureUrl;
<del> user.profile.website = profile._json.publicProfileUrl;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> }
<add> var user = existingEmailUser || new User;
<add> user.linkedin = profile.id;
<add> user.tokens.push({ kind: 'linkedin', accessToken: accessToken });
<add> user.email = profile._json.emailAddress;
<add> user.profile.name = user.profile.name || profile.displayName;
<add> user.profile.location = user.profile.location || profile._json.location.name;
<add> user.profile.picture = user.profile.picture || profile._json.pictureUrl;
<add> user.profile.website = user.profile.website || profile._json.publicProfileUrl;
<add> user.challengesComplete = user.challengesCompleted || [];
<add> user.save(function(err) {
<add> done(err, user);
<add> });
<ide> });
<ide> });
<ide> }
<ide> passport.use(new FacebookStrategy(secrets.facebook, function(req, accessToken, r
<ide> passport.use(new GitHubStrategy(secrets.github, function(req, accessToken, refreshToken, profile, done) {
<ide> if (req.user) {
<ide> User.findOne({ github: profile.id }, function(err, existingUser) {
<del> //if (existingUser) {
<del> // req.flash('errors', { msg: 'There is already a GitHub account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<del> // done(err);
<del> //} else {
<add> if (existingUser) {
<add> req.flash('errors', { msg: 'There is already a GitHub account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<add> done(err);
<add> } else {
<ide> User.findById(req.user.id, function(err, user) {
<ide> user.github = profile.id;
<ide> user.tokens.push({ kind: 'github', accessToken: accessToken });
<ide> passport.use(new GitHubStrategy(secrets.github, function(req, accessToken, refre
<ide> done(err, user);
<ide> });
<ide> });
<del> //}
<add> }
<ide> });
<ide> } else {
<ide> User.findOne({ github: profile.id }, function(err, existingUser) {
<ide> if (existingUser) return done(null, existingUser);
<ide> User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
<del> if (existingEmailUser) {
<del> //req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with GitHub manually from Account Settings.' });
<del> //done(err);
<del> var user = existingEmailUser;
<del> user.email = profile._json.email;
<del> user.github = profile.id;
<del> user.tokens.push({ kind: 'github', accessToken: accessToken });
<del> user.profile.name = profile.displayName;
<del> user.profile.picture = profile._json.avatar_url;
<del> user.profile.location = profile._json.location;
<del> user.profile.website = profile._json.blog;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> } else {
<del> var user = new User();
<del> user.email = profile._json.email;
<del> user.github = profile.id;
<del> user.tokens.push({ kind: 'github', accessToken: accessToken });
<del> user.profile.name = profile.displayName;
<del> user.profile.picture = profile._json.avatar_url;
<del> user.profile.location = profile._json.location;
<del> user.profile.website = profile._json.blog;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> }
<add> var user = existingEmailUser || new User;
<add> user.email = profile._json.email;
<add> user.github = profile.id;
<add> user.tokens.push({ kind: 'github', accessToken: accessToken });
<add> user.profile.name = user.profile.name || profile.displayName;
<add> user.profile.picture = user.profile.picture || profile._json.avatar_url;
<add> user.profile.location = user.profile.location || profile._json.location;
<add> user.profile.website = user.profile.website || profile._json.blog;
<add> user.save(function(err) {
<add> done(err, user);
<add> });
<ide> });
<ide> });
<ide> }
<ide> }));
<ide>
<del>
<ide> // Sign in with Google.
<ide>
<ide> passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refreshToken, profile, done) {
<ide> if (req.user) {
<ide> User.findOne({ google: profile.id }, function(err, existingUser) {
<del> //if (existingUser) {
<del> // req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<del> // done(err);
<del> //} else {
<add> if (existingUser) {
<add> req.flash('errors', { msg: 'There is already a Google account that belongs to you. Sign in with that account or delete it, then link it with your current account.' });
<add> done(err);
<add> } else {
<ide> User.findById(req.user.id, function(err, user) {
<ide> user.google = profile.id;
<ide> user.tokens.push({ kind: 'google', accessToken: accessToken });
<ide> passport.use(new GoogleStrategy(secrets.google, function(req, accessToken, refre
<ide> done(err, user);
<ide> });
<ide> });
<del> //}
<add> }
<ide> });
<ide> } else {
<ide> User.findOne({ google: profile.id }, function(err, existingUser) {
<ide> if (existingUser) return done(null, existingUser);
<ide> User.findOne({ email: profile._json.email }, function(err, existingEmailUser) {
<del> if (existingEmailUser) {
<del> //req.flash('errors', { msg: 'There is already an account using this email address. Sign in to that account and link it with Google manually from Account Settings.' });
<del> //done(err);
<del> var user = existingEmailUser;
<del> user.email = profile._json.email;
<del> user.google = profile.id;
<del> user.tokens.push({ kind: 'google', accessToken: accessToken });
<del> user.profile.name = profile.displayName;
<del> user.profile.gender = profile._json.gender;
<del> user.profile.picture = profile._json.picture;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> } else {
<del> var user = new User();
<del> user.email = profile._json.email;
<del> user.google = profile.id;
<del> user.tokens.push({ kind: 'google', accessToken: accessToken });
<del> user.profile.name = profile.displayName;
<del> user.profile.gender = profile._json.gender;
<del> user.profile.picture = profile._json.picture;
<del> user.save(function(err) {
<del> done(err, user);
<del> });
<del> }
<add> var user = existingEmailUser || new User;
<add> user.email = profile._json.email;
<add> user.google = profile.id;
<add> user.tokens.push({ kind: 'google', accessToken: accessToken });
<add> user.profile.name = user.profile.name || profile.displayName;
<add> user.profile.gender = user.profile.gender || profile._json.gender;
<add> user.profile.picture = user.profile.picture || profile._json.picture;
<add> user.save(function(err) {
<add> done(err, user);
<add> });
<ide> });
<ide> });
<ide> }
<ide> }));
<ide>
<del>
<ide> // Login Required middleware.
<ide>
<ide> module.exports = { | 1 |
Ruby | Ruby | handle additional cask exception | 183cbe00014803eef4e9e3f4f6e87043c1d3b3a3 | <ide><path>Library/Homebrew/cli/named_args.rb
<ide> def load_formula_or_cask(name, only: nil, method: nil, prefer_loading_from_api:
<ide> end
<ide>
<ide> return cask
<del> rescue Cask::CaskUnreadableError => e
<add> rescue Cask::CaskUnreadableError, Cask::CaskInvalidError => e
<ide> # If we're trying to get a keg-like Cask, do our best to handle it
<ide> # not being readable and return something that can be used.
<ide> if want_keg_like_cask | 1 |
Text | Text | correct anchors for buffer.md | b8573d05552b7df6c496ab5e56a1fe2a7c82eda6 | <ide><path>doc/api/buffer.md
<ide> console.log(buf);
<ide>
<ide> [iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols
<ide> [`Array#indexOf()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
<add>[`Buffer#indexOf()`]: #buffer_buf_indexof_value_byteoffset_encoding
<ide> [`Array#includes()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
<ide> [`buf.entries()`]: #buffer_buf_entries
<ide> [`buf.fill(0)`]: #buffer_buf_fill_value_offset_end_encoding
<add>[`buf.fill()`]: #buffer_buf_fill_value_offset_end_encoding
<ide> [`buf.keys()`]: #buffer_buf_keys
<ide> [`buf.slice()`]: #buffer_buf_slice_start_end
<ide> [`buf.values()`]: #buffer_buf_values | 1 |
Javascript | Javascript | update lensflare.js to properly dispose textures | 05437e236ed552fc42fef12cea69bb35ce2dd818 | <ide><path>examples/js/objects/Lensflare.js
<ide> THREE.Lensflare = function () {
<ide>
<ide> //
<ide>
<del> var elements = [];
<add> this.elements = [];
<ide>
<ide> var shader = THREE.LensflareElement.Shader;
<ide>
<ide> THREE.Lensflare = function () {
<ide>
<ide> this.addElement = function ( element ) {
<ide>
<del> elements.push( element );
<add> this.elements.push( element );
<ide>
<ide> };
<ide>
<ide> THREE.Lensflare = function () {
<ide> var vecX = - positionScreen.x * 2;
<ide> var vecY = - positionScreen.y * 2;
<ide>
<del> for ( var i = 0, l = elements.length; i < l; i ++ ) {
<add> for ( var i = 0, l = this.elements.length; i < l; i ++ ) {
<ide>
<del> var element = elements[ i ];
<add> var element = this.elements[ i ];
<ide>
<ide> var uniforms = material2.uniforms;
<ide> | 1 |
Text | Text | add jsdoc types to docs snippets | 3b9786925d43bb85a959db9f414494396c709f0f | <ide><path>docs/api-reference/next.config.js/introduction.md
<ide> For custom advanced behavior of Next.js, you can create a `next.config.js` in th
<ide> Take a look at the following `next.config.js` example:
<ide>
<ide> ```js
<del>module.exports = {
<add>/**
<add> * @type {import('next').NextConfig}
<add> */
<add>const nextConfig = {
<ide> /* config options here */
<ide> }
<add>
<add>module.exports = nextConfig
<ide> ```
<ide>
<ide> You can also use a function:
<ide>
<ide> ```js
<ide> module.exports = (phase, { defaultConfig }) => {
<del> return {
<add> /**
<add> * @type {import('next').NextConfig}
<add> */
<add> const nextConfig = {
<ide> /* config options here */
<ide> }
<add> return nextConfig
<ide> }
<ide> ```
<ide> | 1 |
Python | Python | expose missing mappings (see ) | f8823bad9a23f6623e91e71719e65342de877cb9 | <ide><path>examples/run_language_modeling.py
<ide> from tqdm import tqdm, trange
<ide>
<ide> from transformers import (
<del> CONFIG_MAPPING,
<ide> MODEL_WITH_LM_HEAD_MAPPING,
<ide> WEIGHTS_NAME,
<ide> AdamW,
<ide> def main():
<ide> elif args.model_name_or_path:
<ide> config = AutoConfig.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir)
<ide> else:
<del> config = CONFIG_MAPPING[args.model_type]()
<add> # When we release a pip version exposing CONFIG_MAPPING,
<add> # we can do `config = CONFIG_MAPPING[args.model_type]()`.
<add> raise ValueError(
<add> "You are instantiating a new config instance from scratch. This is not supported, but you can do it from another script, save it,"
<add> "and load it from here, using --config_name"
<add> )
<ide>
<ide> if args.tokenizer_name:
<ide> tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, cache_dir=args.cache_dir)
<ide> elif args.model_name_or_path:
<ide> tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, cache_dir=args.cache_dir)
<ide> else:
<ide> raise ValueError(
<del> "You are instantiating a new {} tokenizer. This is not supported, but you can do it from another script, save it,"
<del> "and load it from here, using --tokenizer_name".format(AutoTokenizer.__name__)
<add> "You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another script, save it,"
<add> "and load it from here, using --tokenizer_name"
<ide> )
<ide>
<ide> if args.block_size <= 0:
<ide><path>src/transformers/__init__.py
<ide> stop_memory_tracing,
<ide> )
<ide> from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig
<del>from .configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoConfig
<add>from .configuration_auto import ALL_PRETRAINED_CONFIG_ARCHIVE_MAP, CONFIG_MAPPING, AutoConfig
<ide> from .configuration_bart import BartConfig
<ide> from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig
<ide> from .configuration_camembert import CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CamembertConfig
<ide> pipeline,
<ide> )
<ide> from .tokenization_albert import AlbertTokenizer
<del>from .tokenization_auto import AutoTokenizer
<add>from .tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
<ide> from .tokenization_bart import BartTokenizer
<ide> from .tokenization_bert import BasicTokenizer, BertTokenizer, BertTokenizerFast, WordpieceTokenizer
<ide> from .tokenization_bert_japanese import BertJapaneseTokenizer, CharacterTokenizer, MecabTokenizer | 2 |
Javascript | Javascript | add mention of antroid 2.x browser | 58f5da86645990ef984353418cd1ed83213b111e | <ide><path>src/ng/q.js
<ide> *
<ide> * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
<ide> * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
<del> * make your code IE8 compatible.
<add> * make your code IE8 and Android 2.x compatible.
<ide> *
<ide> * # Chaining promises
<ide> * | 1 |
PHP | PHP | move route registration into booted callback | 8ac6ed8c8af8e684ac7a304713091b7b55a88a80 | <ide><path>src/Illuminate/Foundation/Support/Providers/RouteServiceProvider.php
<ide> class RouteServiceProvider extends ServiceProvider
<ide> protected $namespace;
<ide>
<ide> /**
<del> * Bootstrap any application services.
<add> * Register any application services.
<ide> *
<ide> * @return void
<ide> */
<del> public function boot()
<add> public function register()
<ide> {
<del> $this->setRootControllerNamespace();
<add> $this->booted(function () {
<add> $this->setRootControllerNamespace();
<ide>
<del> if ($this->routesAreCached()) {
<del> $this->loadCachedRoutes();
<del> } else {
<del> $this->loadRoutes();
<add> if ($this->routesAreCached()) {
<add> $this->loadCachedRoutes();
<add> } else {
<add> $this->loadRoutes();
<ide>
<del> $this->app->booted(function () {
<del> $this->app['router']->getRoutes()->refreshNameLookups();
<del> $this->app['router']->getRoutes()->refreshActionLookups();
<del> });
<del> }
<add> $this->app->booted(function () {
<add> $this->app['router']->getRoutes()->refreshNameLookups();
<add> $this->app['router']->getRoutes()->refreshActionLookups();
<add> });
<add> }
<add> });
<add> }
<add>
<add> /**
<add> * Bootstrap any application services.
<add> *
<add> * @return void
<add> */
<add> public function boot()
<add> {
<add> //
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix mistakes in default configuration arrays | d70c449dff9a3d31e2adfc1243f263fd84edd446 | <ide><path>src/Error/ErrorTrap.php
<ide> class ErrorTrap
<ide> */
<ide> protected $_defaultConfig = [
<ide> 'errorLevel' => E_ALL,
<del> 'ignoredDeprecationPaths' => [],
<ide> 'log' => true,
<ide> 'logger' => ErrorLogger::class,
<ide> 'errorRenderer' => null,
<del> 'extraFatalErrorMemory' => 4 * 1024,
<ide> 'trace' => false,
<ide> ];
<ide>
<ide><path>src/Error/ExceptionTrap.php
<ide> class ExceptionTrap
<ide> 'log' => true,
<ide> 'skipLog' => [],
<ide> 'trace' => false,
<add> 'extraFatalErrorMemory' => 4,
<ide> ];
<ide>
<ide> /** | 2 |
Text | Text | fix the slow tests doc | e1638dce16dfe2854bf8277deafd1fc2b5dc7c63 | <ide><path>CONTRIBUTING.md
<ide> and for the examples:
<ide> $ pip install -r examples/requirements.txt # only needed the first time
<ide> $ python -m pytest -n auto --dist=loadfile -s -v ./examples/
<ide> ```
<del>
<del>and for the slow tests:
<del>
<del>```bash
<del>RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
<del>```
<del>or
<del>```python
<del>RUN_SLOW=yes python -m pytest -n auto --dist=loadfile -s -v ./tests/
<del>```
<del>
<del>In fact, that's how `make test` and `make test-examples` are implemented!
<add>In fact, that's how `make test` and `make test-examples` are implemented (sans the `pip install` line)!
<ide>
<ide> You can specify a smaller set of tests in order to test only the feature
<ide> you're working on. | 1 |
Go | Go | run volume-tests again remote daemons as well | 2a5405bedd7c06ffc914ad576b83238533e4a4e0 | <ide><path>integration/volume/volume_test.go
<ide> import (
<ide> )
<ide>
<ide> func TestVolumesCreateAndList(t *testing.T) {
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
<ide> defer setupTest(t)()
<ide> client := testEnv.APIClient()
<ide> ctx := context.Background()
<ide> func TestVolumesRemove(t *testing.T) {
<ide> }
<ide>
<ide> func TestVolumesInspect(t *testing.T) {
<del> skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon")
<ide> defer setupTest(t)()
<ide> client := testEnv.APIClient()
<ide> ctx := context.Background() | 1 |
Ruby | Ruby | remove unnecessary dup from formtaghelper#field_id | c9cdf7410e1cccef6ab0ba5e9023929d70bd6368 | <ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb
<ide> def field_id(object_name, method_name, *suffixes, index: nil)
<ide>
<ide> # a little duplication to construct fewer strings
<ide> if sanitized_object_name.empty?
<del> sanitized_method_name.dup
<add> sanitized_method_name
<ide> elsif suffixes.any?
<ide> [sanitized_object_name, index, sanitized_method_name, *suffixes].compact.join("_")
<ide> elsif index | 1 |
Javascript | Javascript | provide usable error on missing internal module | 4d798e1b1bbbbbf0a45fb478e153621fc37bb242 | <ide><path>lib/internal/bootstrap/loaders.js
<ide> function nativeModuleRequire(id) {
<ide> }
<ide>
<ide> const mod = NativeModule.map.get(id);
<add> // Can't load the internal errors module from here, have to use a raw error.
<add> // eslint-disable-next-line no-restricted-syntax
<add> if (!mod) throw new TypeError(`Missing internal module '${id}'`);
<ide> return mod.compile();
<ide> }
<ide> | 1 |
Text | Text | update the link of the scrum guide | 8730c8760f51ac3aeb31ff822020c057d86897e2 | <ide><path>guide/english/agile/sprint-planning/index.md
<ide> The purpose of Sprint Planning meeting is to achiev the following goals:
<ide>
<ide> #### More Information:
<ide> * https://www.mountaingoatsoftware.com/agile/scrum/meetings/sprint-planning-meeting
<del>* [Scrum Guide](http://www.scrumguides.org/scrum-guide.html)
<add>* [Scrum Guide](https://www.scrumguides.org/scrum-guide.html#events-planning) | 1 |
Mixed | Go | add volume --format flag to ls | a488ad1a090eb0b6069f79cd045badaaa8ec1bda | <ide><path>api/client/cli.go
<ide> func (cli *DockerCli) NetworksFormat() string {
<ide> return cli.configFile.NetworksFormat
<ide> }
<ide>
<add>// VolumesFormat returns the format string specified in the configuration.
<add>// String contains columns and format specification, for example {{ID}}\t{{Name}}
<add>func (cli *DockerCli) VolumesFormat() string {
<add> return cli.configFile.VolumesFormat
<add>}
<add>
<ide> func (cli *DockerCli) setRawTerminal() error {
<ide> if os.Getenv("NORAW") == "" {
<ide> if cli.isTerminalIn {
<ide><path>api/client/formatter/volume.go
<add>package formatter
<add>
<add>import (
<add> "bytes"
<add> "fmt"
<add> "strings"
<add>
<add> "github.com/docker/engine-api/types"
<add>)
<add>
<add>const (
<add> defaultVolumeQuietFormat = "{{.Name}}"
<add> defaultVolumeTableFormat = "table {{.Driver}}\t{{.Name}}"
<add>
<add> mountpointHeader = "MOUNTPOINT"
<add> // Status header ?
<add>)
<add>
<add>// VolumeContext contains volume specific information required by the formatter,
<add>// encapsulate a Context struct.
<add>type VolumeContext struct {
<add> Context
<add> // Volumes
<add> Volumes []*types.Volume
<add>}
<add>
<add>func (ctx VolumeContext) Write() {
<add> switch ctx.Format {
<add> case tableFormatKey:
<add> if ctx.Quiet {
<add> ctx.Format = defaultVolumeQuietFormat
<add> } else {
<add> ctx.Format = defaultVolumeTableFormat
<add> }
<add> case rawFormatKey:
<add> if ctx.Quiet {
<add> ctx.Format = `name: {{.Name}}`
<add> } else {
<add> ctx.Format = `name: {{.Name}}\ndriver: {{.Driver}}\n`
<add> }
<add> }
<add>
<add> ctx.buffer = bytes.NewBufferString("")
<add> ctx.preformat()
<add>
<add> tmpl, err := ctx.parseFormat()
<add> if err != nil {
<add> return
<add> }
<add>
<add> for _, volume := range ctx.Volumes {
<add> volumeCtx := &volumeContext{
<add> v: volume,
<add> }
<add> err = ctx.contextFormat(tmpl, volumeCtx)
<add> if err != nil {
<add> return
<add> }
<add> }
<add>
<add> ctx.postformat(tmpl, &networkContext{})
<add>}
<add>
<add>type volumeContext struct {
<add> baseSubContext
<add> v *types.Volume
<add>}
<add>
<add>func (c *volumeContext) Name() string {
<add> c.addHeader(nameHeader)
<add> return c.v.Name
<add>}
<add>
<add>func (c *volumeContext) Driver() string {
<add> c.addHeader(driverHeader)
<add> return c.v.Driver
<add>}
<add>
<add>func (c *volumeContext) Scope() string {
<add> c.addHeader(scopeHeader)
<add> return c.v.Scope
<add>}
<add>
<add>func (c *volumeContext) Mountpoint() string {
<add> c.addHeader(mountpointHeader)
<add> return c.v.Mountpoint
<add>}
<add>
<add>func (c *volumeContext) Labels() string {
<add> c.addHeader(labelsHeader)
<add> if c.v.Labels == nil {
<add> return ""
<add> }
<add>
<add> var joinLabels []string
<add> for k, v := range c.v.Labels {
<add> joinLabels = append(joinLabels, fmt.Sprintf("%s=%s", k, v))
<add> }
<add> return strings.Join(joinLabels, ",")
<add>}
<add>
<add>func (c *volumeContext) Label(name string) string {
<add>
<add> n := strings.Split(name, ".")
<add> r := strings.NewReplacer("-", " ", "_", " ")
<add> h := r.Replace(n[len(n)-1])
<add>
<add> c.addHeader(h)
<add>
<add> if c.v.Labels == nil {
<add> return ""
<add> }
<add> return c.v.Labels[name]
<add>}
<ide><path>api/client/formatter/volume_test.go
<add>package formatter
<add>
<add>import (
<add> "bytes"
<add> "strings"
<add> "testing"
<add>
<add> "github.com/docker/docker/pkg/stringid"
<add> "github.com/docker/engine-api/types"
<add>)
<add>
<add>func TestVolumeContext(t *testing.T) {
<add> volumeName := stringid.GenerateRandomID()
<add>
<add> var ctx volumeContext
<add> cases := []struct {
<add> volumeCtx volumeContext
<add> expValue string
<add> expHeader string
<add> call func() string
<add> }{
<add> {volumeContext{
<add> v: &types.Volume{Name: volumeName},
<add> }, volumeName, nameHeader, ctx.Name},
<add> {volumeContext{
<add> v: &types.Volume{Driver: "driver_name"},
<add> }, "driver_name", driverHeader, ctx.Driver},
<add> {volumeContext{
<add> v: &types.Volume{Scope: "local"},
<add> }, "local", scopeHeader, ctx.Scope},
<add> {volumeContext{
<add> v: &types.Volume{Mountpoint: "mountpoint"},
<add> }, "mountpoint", mountpointHeader, ctx.Mountpoint},
<add> {volumeContext{
<add> v: &types.Volume{},
<add> }, "", labelsHeader, ctx.Labels},
<add> {volumeContext{
<add> v: &types.Volume{Labels: map[string]string{"label1": "value1", "label2": "value2"}},
<add> }, "label1=value1,label2=value2", labelsHeader, ctx.Labels},
<add> }
<add>
<add> for _, c := range cases {
<add> ctx = c.volumeCtx
<add> v := c.call()
<add> if strings.Contains(v, ",") {
<add> compareMultipleValues(t, v, c.expValue)
<add> } else if v != c.expValue {
<add> t.Fatalf("Expected %s, was %s\n", c.expValue, v)
<add> }
<add>
<add> h := ctx.fullHeader()
<add> if h != c.expHeader {
<add> t.Fatalf("Expected %s, was %s\n", c.expHeader, h)
<add> }
<add> }
<add>}
<add>
<add>func TestVolumeContextWrite(t *testing.T) {
<add> contexts := []struct {
<add> context VolumeContext
<add> expected string
<add> }{
<add>
<add> // Errors
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "{{InvalidFunction}}",
<add> },
<add> },
<add> `Template parsing error: template: :1: function "InvalidFunction" not defined
<add>`,
<add> },
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "{{nil}}",
<add> },
<add> },
<add> `Template parsing error: template: :1:2: executing "" at <nil>: nil is not a command
<add>`,
<add> },
<add> // Table format
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "table",
<add> },
<add> },
<add> `DRIVER NAME
<add>foo foobar_baz
<add>bar foobar_bar
<add>`,
<add> },
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "table",
<add> Quiet: true,
<add> },
<add> },
<add> `foobar_baz
<add>foobar_bar
<add>`,
<add> },
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "table {{.Name}}",
<add> },
<add> },
<add> `NAME
<add>foobar_baz
<add>foobar_bar
<add>`,
<add> },
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "table {{.Name}}",
<add> Quiet: true,
<add> },
<add> },
<add> `NAME
<add>foobar_baz
<add>foobar_bar
<add>`,
<add> },
<add> // Raw Format
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "raw",
<add> },
<add> }, `name: foobar_baz
<add>driver: foo
<add>
<add>name: foobar_bar
<add>driver: bar
<add>
<add>`,
<add> },
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "raw",
<add> Quiet: true,
<add> },
<add> },
<add> `name: foobar_baz
<add>name: foobar_bar
<add>`,
<add> },
<add> // Custom Format
<add> {
<add> VolumeContext{
<add> Context: Context{
<add> Format: "{{.Name}}",
<add> },
<add> },
<add> `foobar_baz
<add>foobar_bar
<add>`,
<add> },
<add> }
<add>
<add> for _, context := range contexts {
<add> volumes := []*types.Volume{
<add> {Name: "foobar_baz", Driver: "foo"},
<add> {Name: "foobar_bar", Driver: "bar"},
<add> }
<add> out := bytes.NewBufferString("")
<add> context.context.Output = out
<add> context.context.Volumes = volumes
<add> context.context.Write()
<add> actual := out.String()
<add> if actual != context.expected {
<add> t.Fatalf("Expected \n%s, got \n%s", context.expected, actual)
<add> }
<add> // Clean buffer
<add> out.Reset()
<add> }
<add>}
<ide><path>api/client/volume/list.go
<ide> package volume
<ide>
<ide> import (
<del> "fmt"
<ide> "sort"
<del> "text/tabwriter"
<ide>
<ide> "golang.org/x/net/context"
<ide>
<ide> "github.com/docker/docker/api/client"
<add> "github.com/docker/docker/api/client/formatter"
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/engine-api/types"
<ide> "github.com/docker/engine-api/types/filters"
<ide> func (r byVolumeName) Less(i, j int) bool {
<ide>
<ide> type listOptions struct {
<ide> quiet bool
<add> format string
<ide> filter []string
<ide> }
<ide>
<ide> func newListCommand(dockerCli *client.DockerCli) *cobra.Command {
<ide>
<ide> flags := cmd.Flags()
<ide> flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display volume names")
<add> flags.StringVar(&opts.format, "format", "", "Pretty-print networks using a Go template")
<ide> flags.StringSliceVarP(&opts.filter, "filter", "f", []string{}, "Provide filter values (i.e. 'dangling=true')")
<ide>
<ide> return cmd
<ide> func runList(dockerCli *client.DockerCli, opts listOptions) error {
<ide> return err
<ide> }
<ide>
<del> w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
<del> if !opts.quiet {
<del> for _, warn := range volumes.Warnings {
<del> fmt.Fprintln(dockerCli.Err(), warn)
<add> f := opts.format
<add> if len(f) == 0 {
<add> if len(dockerCli.VolumesFormat()) > 0 && !opts.quiet {
<add> f = dockerCli.VolumesFormat()
<add> } else {
<add> f = "table"
<ide> }
<del> fmt.Fprintf(w, "DRIVER \tVOLUME NAME")
<del> fmt.Fprintf(w, "\n")
<ide> }
<ide>
<ide> sort.Sort(byVolumeName(volumes.Volumes))
<del> for _, vol := range volumes.Volumes {
<del> if opts.quiet {
<del> fmt.Fprintln(w, vol.Name)
<del> continue
<del> }
<del> fmt.Fprintf(w, "%s\t%s\n", vol.Driver, vol.Name)
<add>
<add> volumeCtx := formatter.VolumeContext{
<add> Context: formatter.Context{
<add> Output: dockerCli.Out(),
<add> Format: f,
<add> Quiet: opts.quiet,
<add> },
<add> Volumes: volumes.Volumes,
<ide> }
<del> w.Flush()
<add>
<add> volumeCtx.Write()
<add>
<ide> return nil
<ide> }
<ide>
<ide><path>cliconfig/configfile/file.go
<ide> type ConfigFile struct {
<ide> PsFormat string `json:"psFormat,omitempty"`
<ide> ImagesFormat string `json:"imagesFormat,omitempty"`
<ide> NetworksFormat string `json:"networksFormat,omitempty"`
<add> VolumesFormat string `json:"volumesFormat,omitempty"`
<ide> DetachKeys string `json:"detachKeys,omitempty"`
<ide> CredentialsStore string `json:"credsStore,omitempty"`
<ide> Filename string `json:"-"` // Note: for internal use only
<ide><path>docs/reference/commandline/volume_ls.md
<ide> Options:
<ide> - dangling=<boolean> a volume if referenced or not
<ide> - driver=<string> a volume's driver name
<ide> - name=<string> a volume's name
<add> --format string Pretty-print volumes using a Go template
<ide> --help Print usage
<ide> -q, --quiet Only display volume names
<ide> ```
<ide> The following filter matches all volumes with a name containing the `rose` strin
<ide> DRIVER VOLUME NAME
<ide> local rosemary
<ide>
<add>## Formatting
<add>
<add>The formatting options (`--format`) pretty-prints volumes output
<add>using a Go template.
<add>
<add>Valid placeholders for the Go template are listed below:
<add>
<add>Placeholder | Description
<add>--------------|------------------------------------------------------------------------------------------
<add>`.Name` | Network name
<add>`.Driver` | Network driver
<add>`.Scope` | Network scope (local, global)
<add>`.Mountpoint` | Whether the network is internal or not.
<add>`.Labels` | All labels assigned to the volume.
<add>`.Label` | Value of a specific label for this volume. For example `{{.Label "project.version"}}`
<add>
<add>When using the `--format` option, the `volume ls` command will either
<add>output the data exactly as the template declares or, when using the
<add>`table` directive, includes column headers as well.
<add>
<add>The following example uses a template without headers and outputs the
<add>`Name` and `Driver` entries separated by a colon for all volumes:
<add>
<add>```bash
<add>$ docker volume ls --format "{{.Name}}: {{.Driver}}"
<add>vol1: local
<add>vol2: local
<add>vol3: local
<add>```
<add>
<ide> ## Related information
<ide>
<ide> * [volume create](volume_create.md)
<ide><path>integration-cli/docker_cli_volume_test.go
<ide> package main
<ide>
<ide> import (
<add> "io/ioutil"
<add> "os"
<ide> "os/exec"
<add> "path/filepath"
<ide> "strings"
<ide>
<ide> "github.com/docker/docker/pkg/integration/checker"
<ide> func (s *DockerSuite) TestVolumeCliInspectMulti(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestVolumeCliLs(c *check.C) {
<ide> prefix, _ := getPrefixAndSlashFromDaemonPlatform()
<del> out, _ := dockerCmd(c, "volume", "create", "--name", "aaa")
<add> dockerCmd(c, "volume", "create", "--name", "aaa")
<ide>
<ide> dockerCmd(c, "volume", "create", "--name", "test")
<ide>
<ide> dockerCmd(c, "volume", "create", "--name", "soo")
<ide> dockerCmd(c, "run", "-v", "soo:"+prefix+"/foo", "busybox", "ls", "/")
<ide>
<del> out, _ = dockerCmd(c, "volume", "ls")
<add> out, _ := dockerCmd(c, "volume", "ls")
<ide> outArr := strings.Split(strings.TrimSpace(out), "\n")
<ide> c.Assert(len(outArr), check.Equals, 4, check.Commentf("\n%s", out))
<ide>
<ide> assertVolList(c, out, []string{"aaa", "soo", "test"})
<ide> }
<ide>
<add>func (s *DockerSuite) TestVolumeLsFormat(c *check.C) {
<add> dockerCmd(c, "volume", "create", "--name", "aaa")
<add> dockerCmd(c, "volume", "create", "--name", "test")
<add> dockerCmd(c, "volume", "create", "--name", "soo")
<add>
<add> out, _ := dockerCmd(c, "volume", "ls", "--format", "{{.Name}}")
<add> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add>
<add> expected := []string{"aaa", "soo", "test"}
<add> var names []string
<add> for _, l := range lines {
<add> names = append(names, l)
<add> }
<add> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
<add>}
<add>
<add>func (s *DockerSuite) TestVolumeLsFormatDefaultFormat(c *check.C) {
<add> dockerCmd(c, "volume", "create", "--name", "aaa")
<add> dockerCmd(c, "volume", "create", "--name", "test")
<add> dockerCmd(c, "volume", "create", "--name", "soo")
<add>
<add> config := `{
<add> "volumesFormat": "{{ .Name }} default"
<add>}`
<add> d, err := ioutil.TempDir("", "integration-cli-")
<add> c.Assert(err, checker.IsNil)
<add> defer os.RemoveAll(d)
<add>
<add> err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644)
<add> c.Assert(err, checker.IsNil)
<add>
<add> out, _ := dockerCmd(c, "--config", d, "volume", "ls")
<add> lines := strings.Split(strings.TrimSpace(string(out)), "\n")
<add>
<add> expected := []string{"aaa default", "soo default", "test default"}
<add> var names []string
<add> for _, l := range lines {
<add> names = append(names, l)
<add> }
<add> c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names))
<add>}
<add>
<ide> // assertVolList checks volume retrieved with ls command
<ide> // equals to expected volume list
<ide> // note: out should be `volume ls [option]` result | 7 |
Ruby | Ruby | use appropriate assertion based on expectation | 307065f959f2b34bdad16487bae906eb3bfeaf28 | <ide><path>activesupport/test/json/decoding_test.rb
<ide> def self.json_create(object)
<ide> }
<ide>
<ide> TESTS.each_with_index do |(json, expected), index|
<add> fail_message = "JSON decoding failed for #{json}"
<add>
<ide> test "json decodes #{index}" do
<ide> with_tz_default "Eastern Time (US & Canada)" do
<ide> with_parse_json_times(true) do
<ide> silence_warnings do
<del> assert_equal expected, ActiveSupport::JSON.decode(json), "JSON decoding \
<del> failed for #{json}"
<add> if expected.nil?
<add> assert_nil ActiveSupport::JSON.decode(json), fail_message
<add> else
<add> assert_equal expected, ActiveSupport::JSON.decode(json), fail_message
<add> end
<ide> end
<ide> end
<ide> end | 1 |
Text | Text | add api challenges - arabic translation | f2e5f44da63d0ce1535bd22cde2191270b5c85af | <ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/exercise-tracker.arabic.md
<add>---
<add>id: 5a8b073d06fa14fcfde687aa
<add>title: Exercise Tracker
<add>localeTitle: متتبع التمرين
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إنشاء تطبيق جافا سكريبت كامل للمكدس يشبه وظيفيًا ما يلي: <a href='https://fuschia-custard.glitch.me/' target='_blank'>https://fuschia-custard.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-exercisetracker/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني إنشاء مستخدم عن طريق نشر اسم مستخدم بيانات النموذج إلى / api / exercise / new-user وسيتم إرجاع كائن باسم المستخدم و <code>_id</code> .
<add> testString: ''
<add> - text: يمكنني الحصول على مجموعة من جميع المستخدمين عن طريق الحصول على api / exercise / users مع نفس المعلومات عند إنشاء مستخدم.
<add> testString: ''
<add> - text: "يمكنني إضافة تمرين إلى أي مستخدم عن طريق نشر بيانات userId (_id) ، والوصف ، والمدة ، والتاريخ الاختياري إلى / api / exercise / add. إذا لم يتم تقديم تاريخ ، فسيستخدم التاريخ الحالي. سيعرض التطبيق كائن المستخدم مع إضافة حقول التمرين "
<add> testString: ''
<add> - text: يمكنني استرداد سجل تمرين كامل لأي مستخدم من خلال الحصول على / api / exercise / log بمعلمة userId (_id). سيقوم التطبيق بإرجاع كائن المستخدم مع سجل صفيف المضافة وعدد (العدد الكلي للتمرين).
<add> testString: ''
<add> - text: "يمكنني استرداد جزء من سجل أي مستخدم عن طريق تمرير المعلمات الاختيارية من وإلى أو الحد. (تنسيق التاريخ yyyy-mm-dd ، limit = int) "
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/file-metadata-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bd0f
<add>title: File Metadata Microservice
<add>localeTitle: الملف الفوقية ميكروسيرفيسي
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا ما يلي: <a href='https://purple-paladin.glitch.me/' target='_blank'>https://purple-paladin.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-filemetadata/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-filemetadata/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني إرسال كائن FormData يتضمن تحميل ملف.
<add> testString: ''
<add> - text: "عند إرسال شيء ما ، سأتلقى حجم الملف بالبايت ضمن استجابة JSON"
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/request-header-parser-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bdff
<add>title: Request Header Parser Microservice
<add>localeTitle: طلب رأس محلل ميكروسيرفيسي
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا هذا: <a href='https://dandelion-roar.glitch.me/' target='_blank'>https://dandelion-roar.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-headerparser/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-headerparser/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يمكنني الحصول على عنوان IP ولغة ونظام التشغيل لمتصفحي."
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/timestamp-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bdef
<add>title: Timestamp Microservice
<add>localeTitle: Timestamp Microservice
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا ما يلي: <a href='https://curse-arrow.glitch.me/' target='_blank'>https://curse-arrow.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-timestamp/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-timestamp/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يجب أن يتعامل مع تاريخ صالح ، ويعيد الطابع الزمني الصحيح لـ unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.unix, 1482624000000, ''Should be a valid unix timestamp''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع تاريخ صالح ، وإرجاع سلسلة UTC الصحيحة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'')+ ''/api/timestamp/2016-12-25'').then(data => { assert.equal(data.utc, ''Sun, 25 Dec 2016 00:00:00 GMT'', ''Should be a valid UTC date string''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع تاريخ unix صالح ، ويعيد الطابع الزمني الصحيح لـ unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/1482624000000'').then(data => { assert.equal(data.unix, 1482624000000) ; }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن ترجع رسالة الخطأ المتوقعة لتاريخ غير صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp/this-is-not-a-date'').then(data => { assert.equal(data.error.toLowerCase(), ''invalid date'');}, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب معالجة معلمة تاريخ فارغة ، وإرجاع الوقت الحالي بتنسيق unix"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); assert.approximately(data.unix, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "يجب أن يتعامل مع معلمة تاريخ فارغة ، وإرجاع الوقت الحالي بتنسيق UTC"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/api/timestamp'').then(data => { var now = Date.now(); var serverTime = (new Date(data.utc)).getTime(); assert.approximately(serverTime, now, 20000) ;}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/apis-and-microservices-projects/url-shortener-microservice.arabic.md
<add>---
<add>id: bd7158d8c443edefaeb5bd0e
<add>title: URL Shortener Microservice
<add>localeTitle: URL Shortener Microservice
<add>challengeType: 4
<add>isRequired: true
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بإنشاء تطبيق جافا سكريبت كامل المكدس الذي يشبه وظيفيًا هذا: <a href='https://thread-paper.glitch.me/' target='_blank'>https://thread-paper.glitch.me/</a> .
<add>سيشركك العمل في هذا المشروع في كتابة شفرتك على Glitch في مشروعنا المبدئي. بعد الانتهاء من هذا المشروع ، يمكنك نسخ عنوان URL الافتراضي الخاص بك (إلى الصفحة الرئيسية لتطبيقك) في هذه الشاشة لاختباره! اختياريًا ، يمكنك اختيار كتابة مشروعك على نظام أساسي آخر ، ولكن يجب أن يكون مرئيًا بشكل عام لاختبارنا.
<add>ابدأ هذا المشروع على خلل باستخدام <a href='https://glitch.com/#!/import/github/freeCodeCamp/boilerplate-project-urlshortener/' target='_blank'>هذا الرابط</a> أو استنساخ <a href='https://github.com/freeCodeCamp/boilerplate-project-urlshortener/'>هذا المستودع</a> على GitHub! إذا كنت تستخدم خلل ، تذكر لحفظ الرابط لمشروعك في مكان آمن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يمكنني تمرير عنوان URL كمعلمة وسيتلقى عنوان URL مختصرًا في استجابة JSON.
<add> testString: ''
<add> - text: "إذا قمت بتمرير عنوان URL غير صالح لا يتبع تنسيق http://www.example.com الصالح ، فستتضمن استجابة JSON خطأً بدلاً من ذلك"
<add> testString: ''
<add> - text: "عندما أزور عنوان URL المختصر هذا ، سيعيد توجيهي إلى الرابط الأصلي."
<add> testString: ''
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf4
<add>title: Chain Middleware to Create a Time Server
<add>localeTitle: سلسلة Middleware لإنشاء خادم الوقت
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الوسيطة يمكن تركيبه في مسار محدد باستخدام <code>app.METHOD(path, middlewareFunction)</code> . الوسيطة يمكن أيضا أن تكون بالسلاسل داخل تعريف الطريق.
<add>انظر إلى المثال التالي:
<add><blockquote style=";text-align:right;direction:rtl">app.get('/user', function(req, res, next) {<br> req.user = getTheUserSync(); // Hypothetical synchronous operation<br> next();<br>}, function(req, res) {<br> res.send(req.user);<br>})</blockquote>
<add>هذه الطريقة مفيدة لتقسيم عمليات الخادم إلى وحدات أصغر. وهذا يؤدي إلى بنية أفضل للتطبيق ، وإمكانية إعادة استخدام الرمز في أماكن مختلفة. يمكن استخدام هذا الأسلوب أيضًا لإجراء بعض التحقق من صحة البيانات. في كل نقطة من مكدس البرامج الوسيطة يمكنك منع تنفيذ التحكم في السلسلة والسلسة الحالية إلى وظائف مصممة خصيصًا للتعامل مع الأخطاء. أو يمكنك تمرير التحكم إلى المسار المطابق التالي ، للتعامل مع الحالات الخاصة. سنرى كيف في قسم Express المتقدمة.
<add>في مسار <code>app.get('/now', ...)</code> سلسلة وظيفة الوسيطة والمعالج النهائي. في وظيفة الوسيطة ، يجب إضافة الوقت الحالي إلى كائن الطلب في مفتاح <code>req.time</code> . يمكنك استخدام <code>new Date().toString()</code> . في المعالج ، <code>{time: req.time}</code> باستخدام كائن JSON ، مع أخذ البنية <code>{time: req.time}</code> .
<add>تلميح: لن يمر الاختبار إذا لم تقم بربط الوسيطة. إذا قمت بتركيب الوظيفة في مكان آخر ، سيفشل الاختبار ، حتى إذا كانت نتيجة الإخراج صحيحة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يكون نقطة النهاية / الآن الوسيطة المثبتة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { assert.equal(data.stackLength, 2, ''"/now" route has no mounted middleware''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن تقوم نقطة النهاية / الآن بإرجاع وقت يكون +/- 20 ثانية من الآن
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/chain-middleware-time'').then(data => { var now = new Date(); assert.isAtMost(Math.abs(new Date(data.time) - now), 20000, ''the returned time is not between +- 20 secs from now''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-data-from-post-requsts.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf8
<add>title: Get Data from POST Requests
<add>localeTitle: الحصول على البيانات من طلبات POST
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بتحميل معالج POST على المسار <code>/name</code> . انها نفس الطريق كما كان من قبل. قمنا بإعداد نموذج في صفحة HTML الأمامية. وسوف يقدم نفس البيانات من التمرين 10 (سلسلة الاستعلام). إذا تم تكوين محلل الجسم بشكل صحيح ، يجب أن تجد المعلمات في الكائن <code>req.body</code> . إلقاء نظرة على المثال المعتاد للمكتبة:
<add><blockquote style=";text-align:right;direction:rtl">route: POST '/library'<br>urlencoded_body: userId=546&bookId=6754 <br>req.body: {userId: '546', bookId: '6754'}</blockquote>
<add>رد باستخدام نفس كائن JSON كما كان من قبل: <code>{name: 'firstname lastname'}</code> . اختبر إذا كانت نقطة النهاية تعمل باستخدام نموذج html الذي قدمناه في صفحة التطبيق الأولى.
<add>نصيحة: هناك العديد من طرق http الأخرى بخلاف GET و POST. وبموجب الاتفاقية هناك تناظر بين الفعل http ، والعملية التي ستنفذها على الخادم. التعيين التقليدي هو:
<add>POST (أحيانًا PUT) - إنشاء مورد جديد باستخدام المعلومات المرسلة مع الطلب ،
<add>GET - قراءة مورد موجود بدون تعديله ،
<add>PUT أو PATCH (أحيانًا POST) - تحديث مورد باستخدام البيانات تم الإرسال ،
<add>DELETE => حذف مورد.
<add>هناك أيضًا طريقتين أخريين تستخدمان للتفاوض على اتصال بالخادم. باستثناء GET ، يمكن أن تحتوي جميع الطرق الأخرى المذكورة أعلاه على حمولة (أي البيانات في نص الطلب). يعمل الوسيطة محلل الجسم مع هذه الأساليب كذلك.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Mick'', last: ''Jagger''}).then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/name'', {first: ''Keith'', last: ''Richards''}).then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "POST /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-query-parameter-input-from-the-client.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf6
<add>title: Get Query Parameter Input from the Client
<add>localeTitle: الحصول على إدخال معلمة طلب البحث من العميل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>طريقة شائعة أخرى للحصول على مدخلات من العميل هي بتشفير البيانات بعد مسار المسار ، باستخدام سلسلة استعلام. تكون سلسلة الاستعلام محددة بعلامة استفهام (؟) ، وتتضمن أزواج الحقل = القيمة. يتم فصل كل زوجين بواسطة علامة العطف (&). يمكن لـ Express تحليل البيانات من سلسلة الاستعلام ، <code>req.query</code> الكائن <code>req.query</code> . لا يمكن أن تكون بعض الأحرف في عناوين URL ، يجب أن يتم ترميزها <a href='https://en.wikipedia.org/wiki/Percent-encoding' target='_blank'>بتنسيق مختلف</a> قبل أن تتمكن من إرسالها. إذا كنت تستخدم واجهة برمجة التطبيقات من جافا سكريبت ، فيمكنك استخدام طرق محددة لتشفير / فك تشفير هذه الأحرف.
<add><blockquote style=";text-align:right;direction:rtl">route_path: '/library'<br>actual_request_URL: '/library?userId=546&bookId=6754' <br>req.query: {userId: '546', bookId: '6754'}</blockquote>
<add>إنشاء نقطة نهاية API ، محملة على <code>GET /name</code> . الرد باستخدام مستند JSON ، مع أخذ البنية <code>{ name: 'firstname lastname'}</code> . يجب ترميز معلمات الاسم الأول والأخير في سلسلة استعلام على سبيل المثال: <code>?first=firstname&last=lastname</code> .
<add>نصيحة: سنقوم في التمرين التالي بتلقي بيانات من طلب POST ، على نفس مسار مسار <code>/name</code> . إذا كنت تريد يمكنك استخدام الطريقة <code>app.route(path).get(handler).post(handler)</code> . تسمح لك هذه البنية بسلسلة معالجات الأفعال المختلفة على نفس مسار المسار. يمكنك حفظ جزء من الكتابة ، والحصول على رمز أنظف.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن تستجيب نقطة نهاية API الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?first=Mick&last=Jagger'').then(data => { assert.equal(data.name, ''Mick Jagger'', ''Test 1: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن تستجيب نقطة نهاية APi الخاصة بك بالاسم الصحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/name?last=Richards&first=Keith'').then(data => { assert.equal(data.name, ''Keith Richards'', ''Test 2: "GET /name" route does not behave as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/get-route-parameter-input-from-the-client.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf5
<add>title: Get Route Parameter Input from the Client
<add>localeTitle: الحصول على إدخال معلمة المسار من العميل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>عند إنشاء واجهة برمجة التطبيقات ، يتعين علينا السماح للمستخدمين بالاتصال بنا بما يريدون الحصول عليه من خدمتنا. على سبيل المثال ، إذا كان العميل يطلب معلومات حول مستخدم مخزّن في قاعدة البيانات ، فيحتاج إلى طريقة لإعلامنا بالمستخدم الذي يهتم به. تتمثل إحدى الطرق الممكنة لتحقيق هذه النتيجة في استخدام معلمات المسار. تدعى معلمات المسار أجزاء من عنوان URL ، مفصولة بشرائط مائلة (/). يلتقط كل مقطع قيمة جزء عنوان URL الذي يطابق موقعه. يمكن العثور على القيم التي تم التقاطها في كائن <code>req.params</code> .
<add><blockquote style=";text-align:right;direction:rtl">route_path: '/user/:userId/book/:bookId'<br>actual_request_URL: '/user/546/book/6754' <br>req.params: {userId: '546', bookId: '6754'}</blockquote>
<add>إنشاء ملقم صدى ، التي شنت على الطريق <code>GET /:word/echo</code> . الرد باستخدام كائن JSON ، مع أخذ بنية <code>{echo: word}</code> . يمكنك العثور على الكلمة المراد تكرارها على <code>req.params.word</code> . يمكنك اختبار مسارك من شريط العناوين بالمتصفح ، وزيارة بعض المسارات المطابقة ، على سبيل المثال your-app-rootpath / freecodecamp / echo
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "الاختبار 1: يجب أن يكرر خادم الصدى الكلمات بشكل صحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/eChOtEsT/echo'').then(data => { assert.equal(data.echo, ''eChOtEsT'', ''Test 1: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: "الاختبار 2: يجب أن يكرر خادم الصدى الكلمات بشكل صحيح"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/ech0-t3st/echo'').then(data => { assert.equal(data.echo, ''ech0-t3st'', ''Test 2: the echo server is not working as expected'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/implement-a-root-level-request-logger-middleware.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf3
<add>title: Implement a Root-Level Request Logger Middleware
<add>localeTitle: تنفيذ برنامج Logware Logger Logger على مستوى الجذر
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>قبل أن نقدم وظيفة الوسيطة <code>express.static()</code> . الآن حان الوقت لنرى ما هي الوسيطة ، بمزيد من التفصيل. دالات الوسيطية هي الدوال التي تأخذ 3 حجج: كائن الطلب ، كائن الاستجابة ، والدالة التالية في دورة طلب-استجابة التطبيق. هذه الوظائف تنفيذ بعض التعليمات البرمجية التي يمكن أن يكون لها آثار جانبية على التطبيق ، وعادة ما تضيف المعلومات إلى الكائنات استجابة أو طلب. يمكنهم أيضًا إنهاء دورة إرسال الاستجابة ، عند استيفاء بعض الشروط. إذا لم يرسلوا الاستجابة ، فعند الانتهاء من ذلك ، يبدأون تنفيذ الوظيفة التالية في المكدس. يتم تشغيل هذا استدعاء الوسيطة الثالثة <code>next()</code> . مزيد من المعلومات في <a href='http://expressjs.com/en/guide/using-middleware.html' target='_blank'>الوثائق السريعة</a> .
<add>انظر إلى المثال التالي:
<add><blockquote style=";text-align:right;direction:rtl">function(req, res, next) {<br> console.log("I'm a middleware...");<br> next();<br>}</blockquote>
<add>دعونا نفترض أننا شنت هذه الوظيفة على الطريق. عندما يطابق أحد الطلبات المسار ، فإنه يعرض السلسلة "أنا برنامج وسيط ...". ثم ينفذ الوظيفة التالية في المكدس.
<add>في هذا التمرين ، سنقوم ببناء برنامج وسيط بمستوى الجذر. كما رأينا في التحدي 4 ، لتركيب وظيفة الوسيطة على مستوى الجذر يمكننا استخدام طريقة <code>app.use(<mware-function>)</code> . في هذه الحالة ، سيتم تنفيذ الوظيفة لجميع الطلبات ، ولكن يمكنك أيضًا تعيين شروط أكثر تحديدًا. على سبيل المثال ، إذا كنت تريد تنفيذ دالة فقط لطلبات POST ، فيمكنك استخدام <code>app.post(<mware-function>)</code> . توجد أساليب مماثلة لجميع الأفعال http (GET، DELETE، PUT،…).
<add>بناء بسيط المسجل. لكل طلب ، يجب عليه تسجيل الدخول في وحدة التحكم سلسلة أخذ التنسيق التالي: <code>method path - ip</code> . قد يبدو المثال: <code>GET /json - ::ffff:127.0.0.1</code> . لاحظ أن هناك مسافة بين <code>method</code> و <code>path</code> وأن اندفاعة فصل <code>path</code> و <code>ip</code> وتحيط به مساحة على جانبي. يمكنك الحصول على طريقة الطلب (الفعل المتشعب) ، ومسار المسار النسبي ، <code>req.method</code> المتصل من كائن الطلب ، باستخدام <code>req.method</code> ، <code>req.path</code> و <code>req.ip</code> تذكر الاتصال <code>next()</code> عند الانتهاء ، أو أن الخادم الخاص بك سيكون عالقاً إلى الأبد. تأكد من فتح "السجلات" ، وشاهد ما سيحدث عند وصول بعض الطلبات ...
<add>تلميح: يقوم Express بتقييم الوظائف بالترتيب الذي تظهر به في التعليمة البرمجية. هذا صحيح على الوسيطة أيضا. إذا كنت تريد أن تعمل في جميع المسارات ، فيجب تثبيتها قبلها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تكون البرامج الوسيطة لمسجل المستوى الجذر نشطة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/root-middleware-logger'').then(data => { assert.isTrue(data.passed, ''root-level logger is not working as expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/meet-the-node-console.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bed
<add>title: Meet the Node console
<add>localeTitle: تعرف على وحدة التحكم في العقدة
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>أثناء عملية التطوير ، من المهم أن تكون قادراً على التحقق من ما يجري في التعليمات البرمجية. العقدة هي مجرد بيئة جافا سكريبت. مثل جافا سكريبت من جانب العميل ، يمكنك استخدام وحدة التحكم لعرض معلومات تصحيح الأخطاء المفيدة. على جهازك المحلي ، سترى إخراج وحدة التحكم في جهاز طرفي. على خلل ، يمكنك فتح السجلات في الجزء السفلي من الشاشة. يمكنك تبديل لوحة السجل بزر "سجلات" الزر (أعلى اليسار ، تحت اسم التطبيق).
<add>للبدء ، ما عليك سوى طباعة "Hello World" الكلاسيكية في وحدة التحكم. نوصي بإبقاء لوحة السجلات مفتوحة أثناء العمل على مواجهة هذه التحديات. قراءة السجلات يمكنك أن تكون على علم بطبيعة الأخطاء التي قد تحدث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>قم بتعديل الملف <code>myApp.js</code> لتسجيل "Hello World" إلى وحدة التحكم.
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يكون <code>"Hello World"</code> في وحدة التحكم
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/hello-console'').then(data => { assert.isTrue(data.passed, ''"Hello World" is not in the server console''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-an-html-file.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bef
<add>title: Serve an HTML File
<add>localeTitle: تخدم ملف HTML
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يمكننا الرد باستخدام ملف باستخدام الطريقة <code>res.sendFile(path)</code> .
<add>يمكنك وضعه داخل <code>app.get('/', ...)</code> توجيه <code>app.get('/', ...)</code> . وراء الكواليس ، تقوم هذه الطريقة بتعيين الرؤوس المناسبة لإرشاد المتصفح الخاص بك حول كيفية التعامل مع الملف الذي تريد إرساله ، وفقًا لنوعه. ثم سوف يقرأ ويرسل الملف. هذه الطريقة تحتاج إلى مسار ملف مطلق. نوصي باستخدام المتغير العام <code>__dirname</code> لحساب المسار.
<add>سبيل المثال <code>absolutePath = __dirname + relativePath/file.ext</code> .
<add>الملف المطلوب إرساله هو <code>/views/index.html</code> . جرِّب "إظهار تطبيقك" ، يجب أن تشاهد عنوان HTML كبيرًا (ونموذجًا سنستخدمه لاحقًا ...) ، دون تطبيق أي أسلوب.
<add>ملاحظة: يمكنك تحرير حل التحدي السابق ، أو إنشاء حل جديد. إذا قمت بإنشاء حل جديد ، فضع في اعتبارك أن Express يقيم المسارات من الأعلى إلى الأسفل. ينفذ المعالج للمباراة الأولى. يجب عليك التعليق على الحل السابق ، أو سيستمر الخادم في الاستجابة باستخدام سلسلة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك ملف المشاهدات / index.html
<add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.match(data, /<h1>.*<\/h1>/, ''Your app does not serve the expected HTML''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-json-on-a-specific-route.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf1
<add>title: Serve JSON on a Specific Route
<add>localeTitle: خدمة JSON على طريق معين
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بينما يخدم خادم HTML (الذي خمنته!) HTML ، فإن واجهة برمجة التطبيقات تخدم البيانات. تسمح واجهة برمجة التطبيقات (Rpresentational State Transfer) <dfn>REST</dfn> بتبادل البيانات بطريقة بسيطة ، دون الحاجة إلى معرفة العملاء لأي تفاصيل حول الخادم. يحتاج العميل فقط إلى معرفة مصدر المورد (عنوان URL) والإجراء الذي يريد تنفيذه عليه (الفعل). يتم استخدام الفعل GET عندما تقوم بجلب بعض المعلومات ، دون تعديل أي شيء. في هذه الأيام ، يكون تنسيق البيانات المفضل لنقل المعلومات عبر الويب هو JSON. ببساطة ، JSON هي طريقة ملائمة لتمثيل كائن JavaScript كسلسلة ، بحيث يمكن نقله بسهولة.
<add>لنقم بإنشاء واجهة برمجة تطبيقات بسيطة عن طريق إنشاء مسار يستجيب مع JSON على المسار <code>/json</code> . يمكنك القيام بذلك كالمعتاد ، مع طريقة <code>app.get()</code> . داخل معالج المسار ، استخدم الطريقة <code>res.json()</code> ، وتمريرها في كائن كوسيطة. تغلق هذه الطريقة حلقة الطلب-الاستجابة ، وتعيد البيانات. وراء الكواليس ، يقوم بتحويل كائن جافا سكريبت صالح إلى سلسلة ، ثم يقوم بتعيين الرؤوس المناسبة لإخبار المتصفح أنك تخدم JSON ، ويرسل البيانات مرة أخرى. يحتوي الكائن الصحيح على البنية المعتادة <code>{key: data}</code> . يمكن البيانات با رقم ، سلسلة ، كائن متداخل أو مصفوفة. يمكن أن تكون البيانات أيضًا متغيرًا أو نتيجة استدعاء دالة ؛ في هذه الحالة سيتم تقييمه قبل تحويله إلى سلسلة.
<add>خدمة الكائن <code>{"message": "Hello json"}</code> كاستجابة في تنسيق JSON ، إلى طلبات GET إلى المسار <code>/json</code> . ثم أشر المتصفح الخاص بك إلى التطبيق الخاص بك-رابط / json ، يجب أن تشاهد الرسالة على الشاشة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: "يجب أن تخدم نقطة النهاية <code>/json</code> كائن json <code>{'message': 'Hello json'}</code> "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/json'').then(data => { assert.equal(data.message, ''Hello json'', ''The \''/json\'' endpoint does not serve the right data''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/serve-static-assets.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bf0
<add>title: Serve Static Assets
<add>localeTitle: خدمة الأصول الثابتة
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يحتوي خادم HTML عادة على واحد أو أكثر من الدلائل التي يمكن الوصول إليها من قبل المستخدم. يمكنك وضع الأصول الثابتة التي يحتاج إليها التطبيق الخاص بك (أوراق الأنماط ، البرامج النصية ، الصور). في Express يمكنك وضع هذه الوظيفة باستخدام الوسيطة <code>express.static(path)</code> ، حيث تكون المعلمة هي المسار المطلق للمجلد الذي يحتوي على الأصول. إذا كنت لا تعرف ما هي الوسيطة ، فلا تقلق. سنناقشها فيما بعد بالتفصيل. في المقام الأول الوسيطة هي وظائف تعترض معالجات الطريق ، تضيف نوعا من المعلومات. تحتاج الوسيطة <code>app.use(path, middlewareFunction)</code> باستخدام طريقة <code>app.use(path, middlewareFunction)</code> . وسيطة المسار الأول اختيارية. إذا لم تنجح ، سيتم تنفيذ الوسيطة لجميع الطلبات.
<add><code>app.use()</code> البرامج الوسيطة <code>express.static()</code> لكافة الطلبات باستخدام <code>app.use()</code> . المسار المطلق لمجلد الأصول هو <code>__dirname + /public</code> .
<add>يجب أن يكون تطبيقك الآن قادرًا على تقديم ورقة أنماط CSS. من خارج المجلد العام سوف تظهر محملة إلى الدليل الجذر. من المفترض أن تبدو صفحتك الأولى أفضل قليلاً الآن!
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك ملفات مواد العرض من الدليل <code>/public</code>
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/style.css'').then(data => { assert.match(data, /body\s*\{[^\}]*\}/, ''Your app does not serve static assets''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/start-a-working-express-server.arabic.md
<add>---
<add>id: 587d7fb0367417b2b2512bee
<add>title: Start a Working Express Server
<add>localeTitle: بدء تشغيل ملقم Express العمل
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في أول سطرين من الملف myApp.js يمكنك أن ترى كيف أنه من السهل إنشاء كائن تطبيق Express. يحتوي هذا الكائن على عدة طرق ، وسوف نتعلم الكثير منها في هذه التحديات. إحدى الطرق الأساسية هي <code>app.listen(port)</code> . فإنه يخبر الخادم الخاص بك للاستماع على منفذ معين ، ووضعها في حالة تشغيل. يمكنك رؤيتها في أسفل الملف. من داخل التعليقات لأننا نحتاج إلى تشغيل التطبيق في الخلفية لأسباب اختبار. كل التعليمات البرمجية التي قد ترغب في إضافتها تنتقل بين هذين الجزأين الأساسيين. يقوم Glitch بتخزين رقم المنفذ في <code>process.env.PORT</code> متغير البيئة. قيمتها <code>3000</code> .
<add>دعونا نخدم أول سلسلة لدينا! في Express ، تأخذ المسارات البنية التالية: <code>app.METHOD(PATH, HANDLER)</code> . الطريقة هي طريقة http في الأحرف الصغيرة. PATH هو مسار نسبي على الخادم (يمكن أن يكون عبارة عن سلسلة أو حتى تعبير عادي). HANDLER هي وظيفة يقوم Express باستدعاءها عند مطابقة المسار.
<add>تأخذ معالجات <code>function(req, res) {...}</code> الشكل <code>function(req, res) {...}</code> ، حيث req هي كائن الطلب ، و res هو كائن الاستجابة. على سبيل المثال ، المعالج
<add><blockquote style=";text-align:right;direction:rtl">function(req, res) {<br> res.send('Response String');<br>}</blockquote>
<add>سيخدم السلسلة "سلسلة الاستجابة".
<add>استخدم طريقة <code>app.get()</code> لعرض سلسلة Hello Express ، لطلبات GET التي تطابق مسار / root. تأكد من عمل التعليمات البرمجية الخاصة بك بالنظر إلى السجلات ، ثم انظر النتائج في المستعرض الخاص بك ، والنقر فوق الزر 'إظهار Live' في واجهة المستخدم Glitch UI.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يخدم تطبيقك السلسلة "Hello Express"
<add> testString: 'getUserInput => $.get(getUserInput(''url'')).then(data => { assert.equal(data, ''Hello Express'', ''Your app does not serve the text "Hello Express"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/use-body-parser-to-parse-post-requests.arabic.md
<add>---
<add>id: 587d7fb2367417b2b2512bf7
<add>title: Use body-parser to Parse POST Requests
<add>localeTitle: استخدام محلل body to Parse POST الطلبات
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بالإضافة إلى GET هناك فعل http شائع آخر ، هو POST. POST هي الطريقة الافتراضية المستخدمة لإرسال بيانات العميل بنماذج HTML. في REST convention يستخدم POST لإرسال البيانات لإنشاء عناصر جديدة في قاعدة البيانات (مستخدم جديد ، أو مشاركة مدونة جديدة). لا توجد لدينا قاعدة بيانات في هذا المشروع ، لكننا سنتعلم كيفية التعامل مع طلبات POST على أي حال.
<add>في هذا النوع من الطلبات لا تظهر البيانات في عنوان URL ، تكون مخفية في نص الطلب. هذا جزء من طلب HTML ، ويسمى أيضًا الحمولة. نظرًا لأن HTML يعتمد على النص ، حتى إذا لم تكن ترى البيانات ، فهذا لا يعني أنها سرية. يتم عرض المحتوى الأساسي لطلب HTTP POST أدناه:
<add><blockquote style=";text-align:right;direction:rtl">POST /path/subpath HTTP/1.0<br>From: john@example.com<br>User-Agent: someBrowser/1.0<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 20<br>name=John+Doe&age=25</blockquote>
<add>كما ترى ، يتم تشفير الجسم مثل سلسلة الاستعلام. هذا هو التنسيق الافتراضي المستخدم في نماذج HTML. مع Ajax يمكننا أيضا استخدام JSON لتكون قادرة على التعامل مع البيانات التي لديها بنية أكثر تعقيدا. هناك أيضًا نوع آخر من الترميز: multipart / form-data. هذا واحد يستخدم لتحميل الملفات الثنائية.
<add>في هذا التمرين ، سنستخدم هيئة urlencoded.
<add>لتحليل البيانات الواردة من طلبات POST ، يجب عليك تثبيت حزمة: محلل الجسم. تتيح لك هذه الحزمة استخدام سلسلة من البرامج الوسيطة ، والتي يمكن أن تفك شفرة البيانات بتنسيقات مختلفة. شاهد المستندات <a href="https://github.com/expressjs/body-parser" target="_blank" >هنا</a> .
<add>قم بتثبيت وحدة تحليل الجسم في الحزمة. json. ثم تطلب ذلك في الجزء العلوي من الملف. قم بتخزينه في متغير اسمه bodyParser.
<add>يتم إرجاع الوسيطة لمعالجة البيانات المشفرة بواسطة <code>bodyParser.urlencoded({extended: false})</code> . <code>extended=false</code> هو خيار تكوين يخبر المحلل باستخدام التشفير التقليدي. عند استخدامه ، يمكن أن تكون القيم سلاسل أو صفائف فقط. النسخة الموسعة تسمح بمرونة أكبر للبيانات ، ولكن يفوقها JSON. تمرير إلى <code>app.use()</code> الدالة التي تم إرجاعها بواسطة استدعاء الأسلوب السابق. كالعادة ، يجب تركيب الوسيطة قبل كل الطرق التي تحتاجها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب تركيب الوسيطة 'body-parser'
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/add-body-parser'').then(data => { assert.isAbove(data.mountedAt, 0, ''"body-parser" is not mounted correctly'') }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.arabic.md
<add>---
<add>id: 587d7fb1367417b2b2512bf2
<add>title: Use the .env File
<add>localeTitle: استخدم ملف .env
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الملف <code>.env</code> عبارة عن ملف مخفي يستخدم لتمرير متغيرات البيئة إلى التطبيق الخاص بك. هذا الملف سري ، لا أحد ولكن يمكنك الوصول إليه ، ويمكن استخدامه لتخزين البيانات التي تريد الاحتفاظ بها خاصة أو مخفية. على سبيل المثال ، يمكنك تخزين مفاتيح API من الخدمات الخارجية أو عنوان URI الخاص بقاعدة البيانات. يمكنك أيضًا استخدامه لتخزين خيارات التهيئة. عن طريق إعداد خيارات التكوين ، يمكنك تغيير سلوك التطبيق الخاص بك ، دون الحاجة إلى إعادة كتابة بعض التعليمات البرمجية.
<add>يمكن الوصول إلى متغيرات البيئة من التطبيق مثل <code>process.env.VAR_NAME</code> . الكائن <code>process.env</code> هو كائن عقدة عمومي ، ويتم تمرير المتغيرات كسلسلة. حسب الاصطلاح ، أسماء المتغيرات كلها أحرف كبيرة ، مع الكلمات مفصولة تسطير سفلي. <code>.env</code> عبارة عن ملف shell ، لذلك لا تحتاج إلى التفاف الأسماء أو القيم بين علامتي اقتباس. من المهم أيضًا ملاحظة أنه لا يمكن توفير مسافة حول علامة equals عند تعيين قيم للمتغيرات ، مثل <code>VAR_NAME=value</code> . عادة ، ستضع كل تعريف متغير على سطر منفصل.
<add>دعونا إضافة متغير بيئة كخيار التكوين. قم بتخزين متغير <code>MESSAGE_STYLE=uppercase</code> في ملف <code>.env</code> . ثم أخبر معالج مسار GET <code>/json</code> الذي قمت بإنشائه في التحدي الأخير لتحويل رسالة كائن الاستجابة إلى أحرف كبيرة إذا كانت <code>process.env.MESSAGE_STYLE</code> تساوي <code>uppercase</code> . يجب أن يصبح كائن الاستجابة <code>{"message": "HELLO JSON"}</code> .
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتغير استجابة نقطة النهاية <code>/json</code> طبقًا لمتغير البيئة <code>MESSAGE_STYLE</code>
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/use-env-vars'').then(data => { assert.isTrue(data.passed, ''The response of "/json" does not change according to MESSAGE_STYLE''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-description-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb3367417b2b2512bfc
<add>title: Add a Description to Your package.json
<add>localeTitle: أضف وصفًا إلى الحزمة. json
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الجزء التالي من حزمة جيدة. json هو حقل الوصف ، حيث ينتمي وصف قصير ولكن غني بالمعلومات عن مشروعك.
<add>إذا كنت تخطط في يوم ما لنشر حزمة إلى npm ، تذكر أن هذه هي السلسلة التي يجب أن تبيع فكرتك للمستخدم عندما يقررون تثبيت الحزمة الخاصة بك أم لا. ومع ذلك ، هذه ليست حالة الاستخدام الوحيدة للوصف: إنها طريقة رائعة لتلخيص ما يفعله المشروع ، لا يقل أهمية عن مشاريع Node.js العادية لمساعدة مطورين آخرين ، أو مشرفين مستقبليين أو حتى مستقبلك على فهم المشروع. بسرعة.
<add>بغض النظر عن ما كنت تخطط لمشروعك، وأوصت بالتأكيد وصفا. دعونا نضيف شيئًا مشابهًا لهذا:
<add><code>"description": "A project that does something awesome",</code>
<add>إرشادات
<add>أضف وصفًا إلى الحزمة package.json في مشروع Glitch.
<add>تذكر لاستخدام علامات الاقتباس المزدوجة لأسماء المجال ( ") والفواصل (،) للفصل بين الحقول.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "وصف" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.description, ''"description" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-license-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bfe
<add>title: Add a License to Your package.json
<add>localeTitle: إضافة ترخيص إلى الحزمة الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>حقل الترخيص هو المكان الذي تبلغ المستخدمين فيه بمشروعك المسموح لهم القيام به.
<add>بعض التراخيص المشتركة لمشاريع مفتوحة المصدر تشمل MIT و BSD. يعد http://choosealicense.com موردًا رائعًا إذا كنت تريد معرفة المزيد حول الترخيص الذي يمكن أن يناسب مشروعك.
<add>معلومات الترخيص غير مطلوبة. ستمنحك قوانين حقوق الطبع والنشر في معظم البلدان ملكية ما تنشئه افتراضيًا. ومع ذلك ، فمن الأفضل دائمًا تحديد ما يمكن للمستخدمين فعله وما لا يمكنهم فعله.
<add>مثال
<add><code>"license": "MIT",</code>
<add>تعليمات
<add>قم بتعبئة حقل الترخيص في الحزمة. json من مشروع Glitch الخاص بك كما تجد مناسبة.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "ترخيص" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.license, ''"license" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-a-version-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bff
<add>title: Add a Version to Your package.json
<add>localeTitle: أضف إصدارًا إلى الحزمة الخاصة بك. json
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الإصدار مع اسم واحد من الحقول المطلوبة في package.json. يصف هذا الحقل الإصدار الحالي لمشروعك.
<add>مثال
<add><code>"version": "1.2",</code>
<add>Instruction
<add>بإضافة نسخة إلى package.json في مشروع Glitch الخاص بك.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون لديك مفتاح "إصدار" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.version, ''"version" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/add-keywords-to-your-package.json.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512bfd
<add>title: Add Keywords to Your package.json
<add>localeTitle: أضف كلمات رئيسية إلى package.json الخاص بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>حقل الكلمات الرئيسية هو المكان الذي يمكنك فيه وصف مشروعك باستخدام الكلمات الرئيسية ذات الصلة.
<add>مثال
<add><code>"keywords": [ "descriptive", "related", "words" ],</code>
<add>كما ترى ، يتم تنظيم هذا الحقل على هيئة مصفوفة من سلاسل مقتبسة مزدوجة.
<add>إرشادات
<add>أضف مصفوفة من السلاسل المناسبة إلى حقل الكلمات الرئيسية في الحزمة. json من مشروع Glitch.
<add>يجب أن تكون واحدة من الكلمات الأساسية freecodecamp.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن يحتوي package.json على مفتاح "كلمات رئيسية" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.keywords, ''"keywords" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون حقل "الكلمات الرئيسية" مصفوفة
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.isArray(packJson.keywords, ''"keywords" is not an array''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن تتضمن "الكلمات الرئيسية" "freecodecamp"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.include(packJson.keywords, ''freecodecamp'', ''"keywords" does not include "freecodecamp"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/expand-your-project-with-external-packages-from-npm.arabic.md
<add>---
<add>id: 587d7fb4367417b2b2512c00
<add>title: Expand Your Project with External Packages from npm
<add>localeTitle: توسيع المشروع الخاص بك مع الحزم الخارجية من npm
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>واحدة من أكبر الأسباب لاستخدام مدير الحزمة هي إدارة التبعية القوية. بدلاً من الاضطرار يدويًا إلى التأكد من حصولك على جميع الاعتمادات عندما تقوم بإعداد مشروع على كمبيوتر جديد ، يقوم npm تلقائيًا بتثبيت كل شيء لك. ولكن كيف يمكن لـ npm أن تعرف بالضبط ما يحتاجه مشروعك؟ تعرّف على قسم التبعيات في الحزمة. json.
<add>في قسم التبعيات ، يتم تخزين الحزم التي تحتاجها مشروعك باستخدام التنسيق التالي:
<add><code>"dependencies": {</code>
<add><code>"package-name": "version",</code>
<add><code>"express": "4.14.0"</code>
<add><code>}</code>
<add>إرشادات
<add>قم بإضافة الإصدار 2.14.0 من حزمة الحزم إلى حقل التبعيات الخاص بك من package.json
<add>Moment هي مكتبة مفيدة للعمل مع الوقت والتواريخ.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون إصدار "اللحظة" هو "2.14.0"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.14\.0/, ''Wrong version of "moment" installed. It should be 2.14.0''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/how-to-use-package.json-the-core-of-any-node.js-project-or-npm-package.arabic.md
<add>---
<add>id: 587d7fb3367417b2b2512bfb
<add>title: 'How to Use package.json, the Core of Any Node.js Project or npm Package'
<add>localeTitle: "كيفية استخدام package.json ، أو Core of Any Node.js Project أو npm Package"
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إن ملف package.json هو مركز أي مشروع Node.js أو حزمة npm. يخزن معلومات حول مشروعك تمامًا مثل <head> - يصف القسم في مستند HTML محتوى صفحة الويب. يتكون package.json من كائن JSON واحد حيث يتم تخزين المعلومات في "مفتاح": أزواج القيم. لا يوجد سوى حقلين مطلوبين في الحد الأدنى من package.json - الاسم والإصدار - إلا أنه من الممارسات الجيدة توفير معلومات إضافية حول مشروعك يمكن أن تكون مفيدة للمستخدمين أو مشرفين المستقبل.
<add>حقل المؤلف
<add>إذا ذهبت إلى مشروع Glitch الذي قمت بإعداده سابقًا وانظرت إلى الجانب الأيسر من شاشتك ، فستجد شجرة الملفات حيث يمكنك رؤية نظرة عامة على مختلف الملفات في مشروعك. ضمن القسم الخلفي لشجرة الملفات ، ستجد حزمة package.json - الملف الذي سنحسّنه في التحديين التاليين.
<add>أحد أكثر أجزاء المعلومات شيوعًا في هذا الملف هو حقل المؤلف الذي يحدد منشئ المشروع. يمكن أن يكون إما سلسلة أو كائن مع تفاصيل الاتصال. الهدف موصى به للمشاريع الأكبر ، ولكن في حالتنا ، سوف تفعل سلسلة بسيطة مثل المثال التالي.
<add><code>"author": "Jane Doe",</code>
<add>Instructions
<add>أضف اسمك إلى حقل المؤلف في الحزمة. json لمشروع Glitch.
<add>تذكر أنك تكتب JSON.
<add>يجب أن تستخدم جميع أسماء الحقول علامات اقتباس مزدوجة (") ، على سبيل المثال" المؤلف "
<add>يجب فصل جميع الحقول بفاصلة (،)
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: package.json يجب أن يكون مفتاح "المؤلف" صالح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert(packJson.author, ''"author" is missing''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/manage-npm-dependencies-by-understanding-semantic-versioning.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c01
<add>title: Manage npm Dependencies By Understanding Semantic Versioning
<add>localeTitle: إدارة التبعيات npm عن طريق فهم الإصدار الدلالي
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إصدارات من حزم npm في قسم التبعيات من package.json الخاص بك يتبع ما يسمى بإصدار Semantic (SemVer) ، وهو معيار صناعي لإصدارات البرامج التي تهدف إلى تسهيل إدارة التبعيات. يجب أن تستخدم المكتبات وأطر العمل أو غيرها من الأدوات المنشورة على npm نظام SemVer من أجل إيصال نوع التغييرات التي يمكن للمشاريع التي تعتمد على الحزمة أن تتوقع إذا تم تحديثها.
<add>SemVer لا معنى له في مشاريع دون واجهات برمجة التطبيقات العامة - وذلك ما لم مشروع مشابه لالأمثلة أعلاه، استخدم شكل إصدارات أخرى.
<add>لماذا تحتاج لفهم SemVer؟
<add>معرفة SemVer يمكن أن تكون مفيدة عند تطوير البرمجيات التي تستخدم الاعتماد على الخارج (والتي تفعل دائما تقريبا). في يوم من الأيام ، سيوفر لك فهمك لهذه الأرقام من إدخال تغييرات مفاجئة إلى مشروعك دون فهم لماذا لا تسير الأمور "التي عملت بالأمس" فجأة.
<add>هذه هي الطريقة التي يعمل بها الإصدار الدارجة وفقًا للموقع الرسمي:
<add>بالنظر إلى رقم الإصدار MAJOR.MINOR.PATCH ، قم بزيادة:
<add>إصدار رئيسي عند إجراء تغييرات غير متوافقة على واجهة برمجة التطبيقات ، إصدار
<add>MINOR عند إضافة وظائف بطريقة متوافقة إلى الخلف و
<add>الإصدار PATCH عند إجراء إصلاحات الأخطاء المتوافقة.
<add>وهذا يعني أن PATCHes هي إصلاحات للأخطاء ، وإضافة MINORs إلى ميزات جديدة ، ولكن لا أحد منهما يكسر ما نجح من قبل. وأخيرًا ، تضيف MAJORs تغييرات لن تعمل مع الإصدارات السابقة.
<add>مثال
<add>رقم إصدار لغوي: 1.3.8
<add>إرشادات
<add>في قسم التبعيات في الحزمة الخاصة بك. json ، قم بتغيير إصدار اللحظة لمطابقة الإصدار 2 من MAJOR والإصدار 10 من MINOR والإصدار PATCH 2
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون إصدار "اللحظة" هو "2.10.2"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^[\^\~]?2\.10\.2/, ''Wrong version of "moment". It should be 2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/remove-a-package-from-your-dependencies.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c04
<add>title: Remove a Package from Your Dependencies
<add>localeTitle: قم بإزالة حزمة من التبعيات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>لقد قمت الآن باختبار بعض الطرق التي يمكنك من خلالها إدارة تبعيات مشروعك باستخدام قسم تبعيات package.json. لقد قمت بتضمين الحزم الخارجية عن طريق إضافتها إلى الملف وحتى إخبار npm بأنواع الإصدارات التي تريدها باستخدام أحرف خاصة مثل tilde (~) أو علامة الإقحام (^).
<add>ولكن ماذا لو كنت ترغب في إزالة حزمة خارجية لم تعد بحاجة إليها؟ كنت قد خمنت بالفعل - فقط إزالة "مفتاح" المقابلة: الزوج قيمة لذلك من الاعتماديات الخاصة بك.
<add>تنطبق هذه الطريقة نفسها على إزالة الحقول الأخرى في الحزمة الخاصة بك. json بالإضافة إلى
<add>تعليمات
<add>إزالة لحظة الحزمة من التبعيات الخاصة بك.
<add>تأكد من حصولك على كمية مناسبة من الفواصل بعد إزالتها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب ألا تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.notProperty(packJson.dependencies, ''moment'', ''"dependencies" still includes "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/use-the-caret-character-to-use-the-latest-minor-version-of-a-dependency.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c03
<add>title: Use the Caret-Character to Use the Latest Minor Version of a Dependency
<add>localeTitle: استخدم حرف الإقحام لاستخدام أحدث إصدار ثانوي من التبعية
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>شبيه بالكيفية التي سمعت بها التلدة (~) التي تعلمناها في التحدي الأخير لـ npm لتثبيت أحدث PATCH للتبعية ، تسمح علامة الإقحام (^) لـ npm لتثبيت التحديثات المستقبلية أيضًا. الفرق هو أن حرف الإقحام سيسمح بتحديثات MINOR و PATCHes.
<add>في الوقت الحالي ، يجب أن يكون الإصدار الحالي من اللحظة ~ 2.10.2 والذي يسمح لـ npm بالتثبيت على أحدث إصدار 2.10.x. إذا استخدمنا بدلاً من ذلك علامة الإقحام (^) كبادئة للإصدار ، فسيتم السماح لـ npm بالتحديث إلى أي إصدار 2.xx.
<add>مثال
<add><code>"some-package-name": "^1.3.8" allows updates to any 1.xx version.</code>
<add>تعليمات
<add>استخدم حرف الإقحام (^) لبدء إصدار اللحظة في تبعياتك والسماح لـ npm بتحديثه إلى أي إصدار جديد صغير.
<add>لاحظ أنه لا يجب تغيير أرقام الإصدارات نفسها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يتطابق إصدار "اللحظة" مع "^ 2.x.x"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\^2\./, ''Wrong version of "moment". It should be ^2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/managing-packages-with-npm/use-the-tilde-character-to-always-use-the-latest-patch-version-of-a-dependency.arabic.md
<add>---
<add>id: 587d7fb5367417b2b2512c02
<add>title: Use the Tilde-Character to Always Use the Latest Patch Version of a Dependency
<add>localeTitle: استخدم حرف التلدة إلى استخدام أحدث إصدار تصحيح من تبعية
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في التحدي الأخير ، أخبرنا npm بتضمين إصدار محدد فقط من الحزمة. هذه طريقة مفيدة لتجميد تبعياتك إذا كنت بحاجة إلى التأكد من أن الأجزاء المختلفة من مشروعك تبقى متوافقة مع بعضها البعض. ولكن في معظم حالات الاستخدام ، لا تريد أن تفوتك أي إصلاحات للأخطاء ، نظرًا لأنها غالبًا ما تتضمن تصحيحات أمنية مهمة (ورجاءً) ألا تكسر الأشياء في القيام بذلك.
<add>للسماح بتبعية npm ليتم تحديثها إلى أحدث إصدار PATCH ، يمكنك بادئة إصدار التبعية بحرف التلدة (~). في package.json ، فإن القاعدة الحالية التي نتبعها حول كيفية قيام npm بترقية اللحظة هي استخدام إصدار محدد فقط (2.10.2) ، ولكننا نريد السماح بأحدث إصدار 2.10.x.
<add>مثال
<add><code>"some-package-name": "~1.3.8" allows updates to any 1.3.x version.</code>
<add>إرشادات
<add>استخدم حرف التلدة (~) لبدء إصدار اللحظة في تبعياتك والسماح لـ npm بتحديثه إلى أي إصدار PATCH جديد.
<add>لاحظ أنه لا يجب تغيير أرقام الإصدارات نفسها.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تتضمن "التبعيات" "لحظة"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''moment'', ''"dependencies" does not include "moment"''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يتطابق إصدار "اللحظة" "~ 2.10.2"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/package.json'').then(data => { var packJson = JSON.parse(data); assert.match(packJson.dependencies.moment, /^\~2\.10\.2/, ''Wrong version of "moment". It should be ~2.10.2''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/chain-search-query-helpers-to-narrow-search-results.arabic.md
<add>---
<add>id: 587d7fb9367417b2b2512c12
<add>title: Chain Search Query Helpers to Narrow Search Results
<add>localeTitle: سلسلة بحث مساعدة المساعدين لضيق نتائج البحث
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إذا لم تقم بتمرير معاودة الاتصال كالوسيطة الأخيرة إلى Model.find () (أو إلى طرق البحث الأخرى) ، فلن يتم تنفيذ الاستعلام. يمكنك تخزين الاستعلام في متغير للاستخدام في وقت لاحق. يمكّنك هذا النوع من الكائنات من إنشاء استعلام باستخدام بناء جملة تسلسل. يتم تنفيذ البحث الفعلي db عندما تقوم بسلسلة الأسلوب .exec () أخيراً. تمرير رد الاتصال الخاص بك لهذه الطريقة الأخيرة. هناك العديد من مساعدي الاستعلام ، هنا سنستخدم الأكثر شيوعًا.
<add>العثور على الناس الذين يحبون "بوريتو". وفرزها حسب الاسم ، وحصر النتائج في مستندين ، وإخفاء عمرهم. سلسلة .find () ، .sort () ، .limit () ، .select () ، ثم .exec (). تمرير الاستدعاء (err، data) المنفذة exec ().
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تنجح مساعدين الاستعلام تسلسل
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/query-tools'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Pablo'', age: 26, favoriteFoods: [''burrito'', ''hot-dog'']}, {name: ''Bob'', age: 23, favoriteFoods: [''pizza'', ''nachos'']}, {name: ''Ashley'', age: 32, favoriteFoods: [''steak'', ''burrito'']}, {name: ''Mario'', age: 51, favoriteFoods: [''burrito'', ''prosciutto'']} ]) }).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data.length, 2, ''the data array length is not what expected''); assert.notProperty(data[0], ''age'', ''The returned first item has too many properties''); assert.equal(data[0].name, ''Ashley'', ''The returned first item name is not what expected''); assert.notProperty(data[1], ''age'', ''The returned second item has too many properties''); assert.equal(data[1].name, ''Mario'', ''The returned second item name is not what expected'');}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-a-model.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c07
<add>title: Create a Model
<add>localeTitle: خلق نموذج
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>أولا وقبل كل ما نحتاج إليه في المخطط. كل مخطط مخططات إلى مجموعة MongoDB. يحدد شكل المستندات داخل هذه المجموعة.
<add>المخططات هي العنصر الأساسي للنماذج. يمكن أن تكون متداخلة لإنشاء نماذج معقدة ، ولكن في هذه الحالة سنبقي الأمور بسيطة.
<add>يتيح لك نموذج إنشاء مثيلات لكائنات ، تسمى مستندات.
<add>إنشاء شخص لديه هذا النموذج الأولي:
<add><code>- Person Prototype -</code>
<add><code>--------------------</code>
<add><code>name : string [required]</code>
<add><code>age : number</code>
<add><code>favoriteFoods : array of strings (*)</code>
<add>استخدم أنواع المخطط الأساسي للنمس. إذا أردت يمكنك أيضا إضافة
<add>حقول أكثر من ذلك، استخدام المصادقون بسيطة مثل المطلوبة أو فريدة من نوعها،
<add>القيم الافتراضية والمحددة. انظر <a href='http://mongoosejs.com/docs/guide.html'>مستندات النمس</a> .
<add>[C] RUD الجزء الأول - CREATE
<add>ملاحظة: خلل هو خادم حقيقي ، والخوادم الحقيقية في التفاعلات مع ديسيبل يحدث في وظائف معالج. يتم تنفيذ هذه الوظيفة عند حدوث بعض الأحداث (على سبيل المثال ، يضرب أحد الأشخاص نقطة نهاية على واجهة برمجة التطبيقات). سنتبع نفس النهج في هذه التمارين. الدالة done () هي رد اتصال يخبرنا أنه يمكننا المتابعة بعد إكمال عملية غير متزامنة مثل الإدراج أو البحث أو التحديث أو الحذف. إنه يتبع اصطلاح "عقدة" ويجب أن يتم استدعاؤه كـ "فارغ (بيانات) فارغة" أو "تم" (خطأ) على الخطأ.
<add>تحذير - عند التفاعل مع الخدمات عن بعد ، قد تحدث أخطاء!
<add><code>/* Example */</code>
<add><code>var someFunc = function(done) {</code>
<add><code>//... do something (risky) ...</code>
<add><code>if(error) return done(error);</code>
<add><code>done(null, result);</code>
<add><code>};</code>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء مثيل من مخطط النمس
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/mongoose-model'', {name: ''Mike'', age: 28, favoriteFoods: [''pizza'', ''cheese'']}).then(data => { assert.equal(data.name, ''Mike'', ''"model.name" is not what expected''); assert.equal(data.age, ''28'', ''"model.age" is not what expected''); assert.isArray(data.favoriteFoods, ''"model.favoriteFoods" is not an Array''); assert.include(data.favoriteFoods, ''pizza'', ''"model.favoriteFoods" does not include the expected items''); assert.include(data.favoriteFoods, ''cheese'', ''"model.favoriteFoods" does not include the expected items''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c09
<add>title: Create and Save a Record of a Model
<add>localeTitle: إنشاء وحفظ سجل للنموذج
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إنشاء نسخة من المستند باستخدام مُنشئ الشخص الذي قمت بإنشائه من قبل. تمرير إلى المنشئ كائن له اسم الحقول والعمر و foodFoods المفضلة. يجب أن تكون أنواعها متوافقة مع تلك الموجودة في "مخطط الشخص". ثم استدعاء الأسلوب document.save () على مثيل المستند الذي تم إرجاعه. تمرير إليه رد اتصال باستخدام عقدة العقد. هذا نمط شائع ، كل طرق CRUD التالية تأخذ وظيفة رد اتصال مثل هذا كوسيطة أخيرة.
<add><code>/* Example */</code>
<add><code>// ...</code>
<add><code>person.save(function(err, data) {</code>
<add><code>// ...do your stuff here...</code>
<add><code>});</code>
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء عنصر db وحفظه
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/create-and-save-person'').then(data => { assert.isString(data.name, ''"item.name" should be a String''); assert.isNumber(data.age, ''28'', ''"item.age" should be a Number''); assert.isArray(data.favoriteFoods, ''"item.favoriteFoods" should be an Array''); assert.equal(data.__v, 0, ''The db item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/create-many-records-with-model.create.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0a
<add>title: Create Many Records with model.create()
<add>localeTitle: إنشاء العديد من السجلات باستخدام model.create ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>بعض الأحيان تحتاج إلى إنشاء العديد من الأمثلة من النماذج الخاصة بك ، على سبيل المثال عند إنشاء قاعدة بيانات بالبيانات الأولية. تأخذ مجموعة Model.create () مصفوفة من الكائنات مثل [{name: 'John'، ...}، {...}، ...] باعتبارها أول وسيطة ، وحفظها كلها في db. قم بإنشاء العديد من الأشخاص باستخدام Model.create () ، باستخدام الدالة arrayOfPeople.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح إنشاء العديد من عناصر db في وقت واحد
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/create-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''John'', age: 24, favoriteFoods: [''pizza'', ''salad'']}, {name: ''Mary'', age: 21, favoriteFoods: [''onions'', ''chicken'']}])}).then(data => { assert.isArray(data, ''the response should be an array''); assert.equal(data.length, 2, ''the response does not contain the expected number of items''); assert.equal(data[0].name, ''John'', ''The first item is not correct''); assert.equal(data[0].__v, 0, ''The first item should be not previously edited''); assert.equal(data[1].name, ''Mary'', ''The second item is not correct''); assert.equal(data[1].__v, 0, ''The second item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/delete-many-documents-with-model.remove.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c11
<add>title: Delete Many Documents with model.remove()
<add>localeTitle: حذف العديد من المستندات باستخدام model.remove ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>Model.remove () مفيد لحذف جميع الوثائق التي تطابق معايير محددة. احذف جميع الأشخاص الذين يكون اسمهم "Mary" ، باستخدام Model.remove (). قم بنقله إلى مستند استعلام باستخدام مجموعة حقول "الاسم" ، وبالطبع رد اتصال.
<add>ملاحظة: لا يقوم Model.remove () بإرجاع المستند المحذوف ، ولكن كائن JSON يحتوي على نتيجة العملية وعدد العناصر المتأثرة. لا تنسَ تمريرها إلى معاودة الاتصال () ، لأننا نستخدمها في الاختبارات.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح حذف العديد من العناصر في وقت واحد
<add> testString: 'getUserInput => $.ajax({url: getUserInput(''url'') + ''/_api/remove-many-people'', type: ''POST'', contentType:''application/json'', data: JSON.stringify([{name: ''Mary'', age: 16, favoriteFoods: [''lollipop'']}, {name: ''Mary'', age: 21, favoriteFoods: [''steak'']}])}).then(data => { assert.isTrue(!!data.ok, ''The mongo stats are not what expected''); assert.equal(data.n, 2, ''The number of items affected is not what expected''); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/delete-one-document-using-model.findbyidandremove.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c10
<add>title: Delete One Document Using model.findByIdAndRemove
<add>localeTitle: حذف مستند واحد باستخدام model.findByIdAndRemove
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>احذف شخصًا واحدًا من _id. يجب استخدام أحد الأساليب findByIdAndRemove () أو findOneAndRemove (). هم مثل أساليب التحديث السابقة. يمرر المستند الذي تمت إزالته إلى cb. كالعادة ، استخدم الدالة argument personId كمفتاح بحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن ينجح حذف عنصر
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/remove-one-person'', {name:''Jason Bourne'', age: 36, favoriteFoods:[''apples'']}).then(data => { assert.equal(data.name, ''Jason Bourne'', ''item.name is not what expected''); assert.equal(data.age, 36, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''apples''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0); assert.equal(data.count, 0, ''the db items count is not what expected''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/install-and-set-up-mongoose.arabic.md
<add>---
<add>id: 587d7fb6367417b2b2512c06
<add>title: Install and Set Up Mongoose
<add>localeTitle: تثبيت وإعداد النمس
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>إضافة mongodb والنمس إلى package.json المشروع. ثم تتطلب النمس. قم بتخزين URI قاعدة بيانات قاعدة البيانات الخاصة بك في ملف .env الخاص كـ MONGO_URI. الاتصال بقاعدة البيانات باستخدام mongoose.connect ( <Your URI> )
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: يجب أن تكون "" mongodb "التبعية في package.json"
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongodb''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب أن يكون التبعية "النمس" في package.json "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/file/package.json'').then(data => { var packJson = JSON.parse(data); assert.property(packJson.dependencies, ''mongoose''); }, xhr => { throw new Error(xhr.responseText); })'
<add> - text: يجب ربط "النمس" بقاعدة بيانات "
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/is-mongoose-ok'').then(data => {assert.isTrue(data.isMongooseOk, ''mongoose is not connected'')}, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/perform-classic-updates-by-running-find-edit-then-save.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c0e
<add>title: 'Perform Classic Updates by Running Find, Edit, then Save'
<add>localeTitle: "قم بإجراء التحديثات الكلاسيكية عن طريق تشغيل بحث ، تحرير ، ثم حفظ"
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>في الأيام الخوالي ، كان هذا هو ما تحتاج إلى القيام به إذا كنت ترغب في تحرير مستند وتكون قادرًا على استخدامه بطريقة ما ، على سبيل المثال إرساله مرة أخرى في استجابة الخادم. لدى Mongoose طريقة تحديث مخصصة: Model.update (). يتم ربطه بالسائق المنخفض المستوى من طراز mongo. يمكنه تحرير الكثير من الوثائق التي تتطابق مع معايير معينة ، لكنه لا يرسل الوثيقة المحدثة ، فقط رسالة "الحالة". وعلاوة على ذلك ، فإنه يجعل عمليات التحقق من صحة النموذج صعبة ، لأنه فقط يدعو مباشرة سائق المونجو.
<add>البحث عن شخص بواسطة _id (استخدام أي من الأساليب المذكورة أعلاه) مع person المعلمة كمفتاح البحث. أضف "الهامبرغر" إلى قائمة منتجاتها المفضلة (يمكنك استخدام Array.push ()). ثم - داخل البحث عن معاودة الاتصال - حفظ () الشخص المحدثة.
<add>[*] تلميح: قد يكون هذا أمرًا صعبًا إذا كنت قد أعلنت في المخطط الخاص بك أن الأطعمة المفضلة هي صفيف ، دون تحديد النوع (أي [السلسلة]). في ذلك casefavorite السلع الافتراضية إلى نوع مختلط ، ويجب عليك وضع علامة عليه يدويًا كما تم تحريره باستخدام document.markModified ('edited-field'). (http://mongoosejs.com/docs/schematypes.html - # مختلط)
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: البحث عن تحرير عنصر يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-edit-save'', {name:''Poldo'', age: 40, favoriteFoods:[''spaghetti'']}).then(data => { assert.equal(data.name, ''Poldo'', ''item.name is not what expected''); assert.equal(data.age, 40, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''spaghetti'', ''hamburger''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 1, ''The item should be previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/perform-new-updates-on-a-document-using-model.findoneandupdate.arabic.md
<add>---
<add>id: 587d7fb8367417b2b2512c0f
<add>title: Perform New Updates on a Document Using model.findOneAndUpdate()
<add>localeTitle: إجراء تحديثات جديدة على مستند باستخدام model.findOneAndUpdate ()
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>الإصدارات الحديثة من النمس لها طرق لتبسيط تحديث الوثائق. تتصرف بعض الميزات الأكثر تقدمًا (أي خطافات ما قبل / النشر والتحقق من الصحة) بشكل مختلف مع هذا الأسلوب ، لذلك لا تزال الطريقة الكلاسيكية مفيدة في العديد من المواقف. يمكن استخدام findByIdAndUpdate () عند البحث باستخدام Id.
<add>البحث عن شخص حسب الاسم وتعيين سنها إلى 20. استخدم الدالة parameter nameName كمفتاح بحث.
<add>تلميح: نريد منك إرجاع المستند الذي تم تحديثه. للقيام بذلك ، تحتاج إلى تمرير مستند الخيارات {جديد: true} كوسيطة 3 للبحث عن OneOndUpdate (). بشكل افتراضي ، ترجع هذه الطرق الكائن غير المعدل.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: findOneAndUpdate يجب أن ينجح عنصر
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-update'', {name:''Dorian Gray'', age: 35, favoriteFoods:[''unknown'']}).then(data => { assert.equal(data.name, ''Dorian Gray'', ''item.name is not what expected''); assert.equal(data.age, 20, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''unknown''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''findOneAndUpdate does not increment version by design !!!''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-dataarabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0b
<add>title: Use model.find() to Search Your Database
<add>localeTitle: استخدم model.find () للبحث في قاعدة البيانات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>البحث عن جميع الأشخاص الذين لديهم اسم معين ، باستخدام Model.find () -> [شخص]
<add>في أبسط استخدام له ، يقبل Model.find () مستند استعلام (كائن JSON) كالوسيطة الأولى ، ثم رد اتصال. تقوم بإرجاع مجموعة من التطابقات. وهو يدعم مجموعة واسعة للغاية من خيارات البحث. التحقق من ذلك في المستندات. استخدم الوسيطة function personName كمفتاح البحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: البحث عن العناصر المقابلة لمعايير يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-all-by-name'', {name: ''r@nd0mN4m3'', age: 24, favoriteFoods: [''pizza'']}).then(data => { assert.isArray(data, ''the response should be an Array''); assert.equal(data[0].name, ''r@nd0mN4m3'', ''item.name is not what expected''); assert.equal(data[0].__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.findbyid-to-search-your-database-by-id.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0d
<add>title: Use model.findById() to Search Your Database By _id
<add>localeTitle: استخدم model.findById () للبحث في قاعدة البيانات الخاصة بك بواسطة _id
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>عند حفظ مستند ، يقوم mongodb تلقائيًا بإضافة حقل _id ، وتعيينه إلى مفتاح أبجدي رقمي فريد. البحث عن طريق _id هو عملية متكررة للغاية ، لذلك يوفر النمس طريقة مخصصة لذلك. ابحث عن الشخص (فقط !!) الذي لديه _id محدد ، باستخدام Model.findById () -> الشخص. استخدم الوسيطة function personId كمفتاح البحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: العثور على عنصر من خلال معرف يجب أن تنجح
<add> testString: 'getUserInput => $.get(getUserInput(''url'') + ''/_api/find-by-id'').then(data => { assert.equal(data.name, ''test'', ''item.name is not what expected''); assert.equal(data.age, 0, ''item.age is not what expected''); assert.deepEqual(data.favoriteFoods, [''none''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section>
<ide><path>curriculum/challenges/arabic/05-apis-and-microservices/mongodb-and-mongoose/use-model.findone-to-return-a-single-matching-document-from-your-database.arabic.md
<add>---
<add>id: 587d7fb7367417b2b2512c0c
<add>title: Use model.findOne() to Return a Single Matching Document from Your Database
<add>localeTitle: استخدم model.findOne () لإرجاع مستند مطابقة مفردة من قاعدة البيانات الخاصة بك
<add>challengeType: 2
<add>---
<add>
<add>## Description
<add><section id='description'>
<add>يتصرف model.findOne () مثل .find () ، ولكنه يقوم بإرجاع مستند واحد فقط (وليس صفيف) ، حتى إذا كان هناك عدة عناصر. من المفيد بشكل خاص عند البحث عن طريق الخصائص التي أعلنت أنها فريدة من نوعها. البحث عن شخص واحد فقط لديه طعام معين في المفضلة لها ، وذلك باستخدام Model.findOne () -> شخص. استخدم الوسيطة الدالة الغذائية كمفتاح بحث.
<add></section>
<add>
<add>## Instructions
<add><section id='instructions'>
<add>
<add></section>
<add>
<add>## Tests
<add><section id='tests'>
<add>
<add>```yml
<add>tests:
<add> - text: العثور على عنصر واحد يجب أن تنجح
<add> testString: 'getUserInput => $.post(getUserInput(''url'') + ''/_api/find-one-by-food'', {name: ''Gary'', age: 46, favoriteFoods: [''chicken salad'']}).then(data => { assert.equal(data.name, ''Gary'', ''item.name is not what expected''); assert.deepEqual(data.favoriteFoods, [''chicken salad''], ''item.favoriteFoods is not what expected''); assert.equal(data.__v, 0, ''The item should be not previously edited''); }, xhr => { throw new Error(xhr.responseText); })'
<add>
<add>```
<add>
<add></section>
<add>
<add>## Challenge Seed
<add><section id='challengeSeed'>
<add>
<add></section>
<add>
<add>## Solution
<add><section id='solution'>
<add>
<add>```js
<add>// solution required
<add>```
<add></section> | 39 |
Text | Text | update rename documentation | a3505b29c66a43f54554d03e8d63adb0c002ba88 | <ide><path>share/doc/homebrew/Rename-A-Formula.md
<ide> you need:
<ide>
<ide> 1. Rename formula file and its class to new formula. New name must meet all the rules of naming. Fix any test failures that may occur due to the stricter requirements for new formula than existing formula (e.g. brew audit --strict must pass for that formula).
<ide>
<del>2. Create a pull request to the main repository deleting the formula file, adding new formula file and also add it to `Library/Homebrew/formula_renames.rb` with a commit message like `rename: ack -> newack`
<add>2. Create a pull request to the main repository deleting the formula file, adding new formula file and also add it to `Library/Homebrew/formula_renames.rb` with a commit message like `newack: renamed from ack`
<ide>
<ide> To rename tap formula you need to follow the same steps, but add formula to `formula_renames.json` in the root of your tap. You don't need to change `Library/Homebrew/formula_renames.rb`, because that file is for core formulae only. Use canonical name (e.g. `ack` instead of `user/repo/ack`).
<ide> | 1 |
Javascript | Javascript | fix externalmodule and test case | f0271d93c6716af3d0d39420c89c9723416be625 | <ide><path>lib/ExternalModule.js
<ide> class ExternalModule extends Module {
<ide> .slice(1)
<ide> .map(r => `[${JSON.stringify(r)}]`)
<ide> .join("");
<del> return `module.exports = require(${moduleName})${objectLookup};`;
<add> return `module.exports = require(${JSON.stringify(
<add> moduleName
<add> )})${objectLookup};`;
<ide> }
<ide>
<ide> checkExternalVariable(variableToCheck, request) {
<ide> class ExternalModule extends Module {
<ide> }
<ide>
<ide> getSourceForDefaultCase(optional, request) {
<add> if (!Array.isArray(request)) {
<add> // make it an array as the look up works the same basically
<add> request = [request];
<add> }
<add>
<add> const variableName = request[0];
<ide> const missingModuleError = optional
<del> ? this.checkExternalVariable(request, request)
<add> ? this.checkExternalVariable(variableName, request.join("."))
<ide> : "";
<del> return `${missingModuleError}module.exports = ${request};`;
<add> const objectLookup = request
<add> .slice(1)
<add> .map(r => `[${JSON.stringify(r)}]`)
<add> .join("");
<add> return `${missingModuleError}module.exports = ${variableName}${objectLookup};`;
<ide> }
<ide>
<ide> getSourceString(runtime) {
<ide> const request =
<del> typeof this.request === "object"
<add> typeof this.request === "object" && !Array.isArray(this.request)
<ide> ? this.request[this.externalType]
<ide> : this.request;
<ide> switch (this.externalType) {
<ide><path>test/configCases/externals/externals-array/index.js
<add>it("should not fail on optional externals", function() {
<add> const external = require("external");
<add> expect(external).toBe(EXPECTED);
<add>});
<ide><path>test/configCases/externals/externals-array/webpack.config.js
<add>const webpack = require("../../../../");
<add>module.exports = [
<add> {
<add> output: {
<add> libraryTarget: "commonjs2"
<add> },
<add> externals: {
<add> external: ["webpack", "version"]
<add> },
<add> plugins: [
<add> new webpack.DefinePlugin({
<add> EXPECTED: JSON.stringify(webpack.version)
<add> })
<add> ]
<add> },
<add> {
<add> externals: {
<add> external: ["Array", "isArray"]
<add> },
<add> plugins: [
<add> new webpack.DefinePlugin({
<add> EXPECTED: "Array.isArray"
<add> })
<add> ]
<add> }
<add>];
<ide><path>test/configCases/externals/optional-externals-array/index.js
<del>it("should not fail on optional externals", function() {
<del> try {
<del> require("external");
<del> } catch(e) {
<del> expect(e).toBeInstanceOf(Error);
<del> expect(e.code).toBe("MODULE_NOT_FOUND");
<del> return;
<del> }
<del> throw new Error("It doesn't fail");
<del>});
<ide><path>test/configCases/externals/optional-externals-array/webpack.config.js
<del>module.exports = {
<del> externals: {
<del> external: ["./math", "subtract"]
<del> }
<del>}; | 5 |
Ruby | Ruby | add more api test coverage | 8c8c6964c8371988b8d7831b2c2141596b67c814 | <ide><path>Library/Homebrew/test/formulary_spec.rb
<ide> def formula_json_contents(extra_items = {})
<ide> "reason" => ":provided_by_macos",
<ide> "explanation" => "",
<ide> },
<del> "build_dependencies" => [],
<del> "dependencies" => [],
<del> "recommended_dependencies" => [],
<del> "optional_dependencies" => [],
<del> "uses_from_macos" => [],
<add> "build_dependencies" => ["build_dep"],
<add> "dependencies" => ["dep"],
<add> "recommended_dependencies" => ["recommended_dep"],
<add> "optional_dependencies" => ["optional_dep"],
<add> "uses_from_macos" => ["uses_from_macos_dep"],
<ide> "caveats" => "",
<ide> }.merge(extra_items),
<ide> }
<ide> def formula_json_contents(extra_items = {})
<ide> formula = described_class.factory(formula_name)
<ide> expect(formula).to be_kind_of(Formula)
<ide> expect(formula.keg_only_reason.reason).to eq :provided_by_macos
<add> expect(formula.deps.count).to eq 4
<add> expect(formula.uses_from_macos_elements).to eq ["uses_from_macos_dep"]
<ide> expect {
<ide> formula.install
<ide> }.to raise_error("Cannot build from source from abstract formula.") | 1 |
Java | Java | improve javadoc for databasepopulator | 87e58a6d7b7209f5f932b0d34e509452c62405d6 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/DatabasePopulator.java
<ide> import java.sql.SQLException;
<ide>
<ide> /**
<del> * Strategy used to populate a database during initialization.
<add> * Strategy used to populate, initialize, or clean up a database.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Sam Brannen
<ide> * @since 3.0
<ide> * @see ResourceDatabasePopulator
<ide> * @see DatabasePopulatorUtils
<add> * @see DataSourceInitializer
<ide> */
<ide> public interface DatabasePopulator {
<ide>
<ide> /**
<del> * Populate the database using the provided JDBC connection.
<add> * Populate, initialize, or clean up the database using the provided JDBC
<add> * connection.
<ide> * <p>Concrete implementations <em>may</em> throw an {@link SQLException} if
<ide> * an error is encountered but are <em>strongly encouraged</em> to throw a
<ide> * specific {@link ScriptException} instead. For example, Spring's | 1 |
PHP | PHP | add file headers | f17097ce890c2b4b44390ee534447aaa5f855942 | <ide><path>App/Config/app.php
<ide> <?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<ide> namespace App\Config;
<ide>
<ide> use Cake\Core\Configure;
<ide><path>App/Config/cache.php
<ide> <?php
<ide> /**
<del> * Pick the caching engine to use. If APC is enabled use it.
<del> * If running via cli - apc is disabled by default. ensure it's available and enabled in this case
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<del> * Note: 'default' and other application caches should be configured in app/Config/bootstrap.php.
<del> * Please check the comments in boostrap.php for more info on the cache engines available
<del> * and their setttings.
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> namespace App\Config;
<ide>
<ide><path>App/Config/error.php
<ide> <?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<ide> namespace App\Config;
<ide>
<ide> use Cake\Core\Configure;
<ide><path>App/Config/logging.php
<ide> <?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<ide> namespace App\Config;
<ide>
<ide> use Cake\Log\Log;
<ide><path>App/Config/paths.php
<ide> <?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>
<ide> /**
<ide> * Use the DS to separate the directories in other defines
<ide> */
<ide><path>App/Config/session.php
<ide> <?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package app.Config
<add> * @since CakePHP(tm) v3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<ide> namespace App\Config;
<ide>
<ide> use Cake\Model\Datasource\Session; | 6 |
Javascript | Javascript | teach yellowbox to count | ab87033185b3bf9b08b69c8e0e3ed2cbc651376d | <ide><path>Libraries/ReactIOS/YellowBox.js
<ide> function updateWarningMap(format, ...args): void {
<ide> ].join(' ');
<ide>
<ide> const count = _warningMap.has(warning) ? _warningMap.get(warning) : 0;
<del> _warningMap.set(warning, count + 2);
<add> _warningMap.set(warning, count + 1);
<ide> _warningEmitter.emit('warning', _warningMap);
<ide> }
<ide> | 1 |
PHP | PHP | fix getcrumbs() with no crumbs and first link | c54ac257f1f55bfa64a8545572dbf614f2404445 | <ide><path>lib/Cake/Test/Case/View/Helper/HtmlHelperTest.php
<ide> public function testBreadcrumb() {
<ide> * Test the array form of $startText
<ide> */
<ide> public function testGetCrumbFirstLink() {
<add> $result = $this->Html->getCrumbList(null, 'Home');
<add> $this->assertTags(
<add> $result,
<add> array(
<add> '<ul',
<add> array('li' => array('class' => 'first')),
<add> array('a' => array('href' => '/')), 'Home', '/a',
<add> '/li',
<add> '/ul'
<add> )
<add> );
<add>
<ide> $this->Html->addCrumb('First', '#first');
<ide> $this->Html->addCrumb('Second', '#second');
<ide>
<ide><path>lib/Cake/View/Helper/HtmlHelper.php
<ide> public function style($data, $oneline = true) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<ide> */
<ide> public function getCrumbs($separator = '»', $startText = false) {
<del> if (!empty($this->_crumbs)) {
<add> $crumbs = $this->_prepareCrumbs($startText);
<add> if (!empty($crumbs)) {
<ide> $out = array();
<del> $crumbs = $this->_prepareCrumbs($startText);
<ide> foreach ($crumbs as $crumb) {
<ide> if (!empty($crumb[1])) {
<ide> $out[] = $this->link($crumb[0], $crumb[1], $crumb[2]);
<ide> public function getCrumbs($separator = '»', $startText = false) {
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html#creating-breadcrumb-trails-with-htmlhelper
<ide> */
<ide> public function getCrumbList($options = array(), $startText = false) {
<del> if (!empty($this->_crumbs)) {
<add> $crumbs = $this->_prepareCrumbs($startText);
<add> if (!empty($crumbs)) {
<ide> $result = '';
<del> $crumbs = $this->_prepareCrumbs($startText);
<ide> $crumbCount = count($crumbs);
<ide> $ulOptions = $options;
<ide> foreach ($crumbs as $which => $crumb) { | 2 |
Go | Go | fix apparent typo | 14b2b2b7c2db83ef1413a7469608f655cd15958e | <ide><path>utils/utils.go
<ide> func (k *KernelVersionInfo) String() string {
<ide> }
<ide>
<ide> // Compare two KernelVersionInfo struct.
<del>// Returns -1 if a < b, = if a == b, 1 it a > b
<add>// Returns -1 if a < b, 0 if a == b, 1 it a > b
<ide> func CompareKernelVersion(a, b *KernelVersionInfo) int {
<ide> if a.Kernel < b.Kernel {
<ide> return -1 | 1 |
PHP | PHP | fix failing test | 93518190e2043642ece186776c72721034adedaa | <ide><path>src/View/Helper/FormHelper.php
<ide> protected function _initInputField($field, $options = []) {
<ide> }
<ide> if (!isset($options['val']) && isset($options['default'])) {
<ide> $options['val'] = $options['default'];
<del> unset($options['default']);
<ide> }
<add> unset($options['value'], $options['default']);
<ide>
<ide> if ($context->hasError($field)) {
<ide> $options = $this->addClass($options, $this->settings['errorClass']); | 1 |
Ruby | Ruby | favor composition over inheritence | 307e6b2b74ba3ae72602dc33e6d45cd3e46181c7 | <ide><path>activemodel/lib/active_model/errors.rb
<ide> module ActiveModel
<ide> # p.validate! # => ["can not be nil"]
<ide> # p.errors.full_messages # => ["name can not be nil"]
<ide> # # etc..
<del> class Errors < ActiveSupport::OrderedHash
<add> class Errors
<add> include Enumerable
<add>
<ide> CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank]
<ide>
<add> attr_reader :messages
<add>
<ide> # Pass in the instance of the object that is using the errors object.
<ide> #
<ide> # class Person
<ide> class Errors < ActiveSupport::OrderedHash
<ide> # end
<ide> # end
<ide> def initialize(base)
<del> @base = base
<del> super()
<add> @base = base
<add> @messages = ActiveSupport::OrderedHash.new
<add> end
<add>
<add> # Clear the messages
<add> def clear
<add> messages.clear
<ide> end
<ide>
<del> alias_method :get, :[]
<del> alias_method :set, :[]=
<add> # Get messages for +key+
<add> def get(key)
<add> messages[key]
<add> end
<add>
<add> # Set messages for +key+ to +value+
<add> def set(key, value)
<add> messages[key] = value
<add> end
<ide>
<ide> # When passed a symbol or a name of a method, returns an array of errors
<ide> # for the method.
<ide> def []=(attribute, error)
<ide> # # then yield :name and "must be specified"
<ide> # end
<ide> def each
<del> each_key do |attribute|
<add> messages.each_key do |attribute|
<ide> self[attribute].each { |error| yield attribute, error }
<ide> end
<ide> end
<ide> def size
<ide> values.flatten.size
<ide> end
<ide>
<add> # Returns all message values
<add> def values
<add> messages.values
<add> end
<add>
<add> # Returns all message keys
<add> def keys
<add> messages.keys
<add> end
<add>
<ide> # Returns an array of error messages, with the attribute name included
<ide> #
<ide> # p.errors.add(:name, "can't be blank")
<ide> def as_json(options=nil)
<ide> end
<ide>
<ide> def to_hash
<del> hash = ActiveSupport::OrderedHash.new
<del> each { |k, v| (hash[k] ||= []) << v }
<del> hash
<add> messages.dup
<ide> end
<ide>
<ide> # Adds +message+ to the error messages on +attribute+, which will be returned on a call to | 1 |
Python | Python | break long lines | 5bc6926d063866731cbe568366137f9e12182648 | <ide><path>numpy/lib/function_base.py
<ide> def unwrap(p, discont=None, axis=-1, *, period=2*pi):
<ide> difference from their predecessor of more than ``max(discont, period/2)``
<ide> to their `period`-complementary values.
<ide>
<del> For the default case where `period` is :math:`2\pi` and is `discont` is :math:`\pi`,
<del> this unwraps a radian phase `p` such that adjacent differences are never
<del> greater than :math:`\pi` by adding :math:`2k\pi` for some integer :math:`k`.
<add> For the default case where `period` is :math:`2\pi` and is `discont` is
<add> :math:`\pi`, this unwraps a radian phase `p` such that adjacent differences
<add> are never greater than :math:`\pi` by adding :math:`2k\pi` for some
<add> integer :math:`k`.
<ide>
<ide> Parameters
<ide> ----------
<ide> p : array_like
<ide> Input array.
<ide> discont : float, optional
<ide> Maximum discontinuity between values, default is ``period/2``.
<del> Values below ``period/2`` are treated as if they were ``period/2``. To have an effect
<del> different from the default, `discont` should be larger than ``period/2``.
<add> Values below ``period/2`` are treated as if they were ``period/2``.
<add> To have an effect different from the default, `discont` should be
<add> larger than ``period/2``.
<ide> axis : int, optional
<ide> Axis along which unwrap will operate, default is the last axis.
<ide> period: float, optional
<del> Size of the range over which the input wraps. By default, it is ``2 pi``.
<add> Size of the range over which the input wraps. By default, it is
<add> ``2 pi``.
<ide>
<ide> .. versionadded:: 1.21.0
<ide>
<ide> def unwrap(p, discont=None, axis=-1, *, period=2*pi):
<ide> interval_low = -interval_high
<ide> ddmod = mod(dd - interval_low, period) + interval_low
<ide> if boundary_ambiguous:
<del> # for `mask = (abs(dd) == period/2)`, the above line made `ddmod[mask] == -period/2`.
<del> # correct these such that `ddmod[mask] == sign(dd[mask])*period/2`.
<del> _nx.copyto(ddmod, interval_high, where=(ddmod == interval_low) & (dd > 0))
<add> # for `mask = (abs(dd) == period/2)`, the above line made
<add> # `ddmod[mask] == -period/2`. correct these such that
<add> # `ddmod[mask] == sign(dd[mask])*period/2`.
<add> _nx.copyto(ddmod, interval_high,
<add> where=(ddmod == interval_low) & (dd > 0))
<ide> ph_correct = ddmod - dd
<ide> _nx.copyto(ph_correct, 0, where=abs(dd) < discont)
<ide> up = array(p, copy=True, dtype=dtype) | 1 |
Go | Go | add minimum limit for memory reservation | 50a61810056a421fb94acf26277995f2c1f31ede | <ide><path>daemon/daemon_unix.go
<ide> func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysi
<ide> logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
<ide> resources.MemoryReservation = 0
<ide> }
<add> if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
<add> return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
<add> }
<ide> if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
<ide> return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage")
<ide> }
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
<ide> c.Assert(err, check.NotNil)
<ide> expected := "Minimum memory limit should be larger than memory reservation limit"
<ide> c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
<add>
<add> out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
<add> c.Assert(err, check.NotNil)
<add> expected = "Minimum memory reservation allowed is 4MB"
<add> c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestStopContainerSignal(c *check.C) { | 2 |
Python | Python | fix a bug for `callbackhandler.callback_list` | 7bff0af0a4b09b9bfc3ade2532c2a3acdff95eda | <ide><path>src/transformers/trainer_callback.py
<ide> def remove_callback(self, callback):
<ide>
<ide> @property
<ide> def callback_list(self):
<del> return "\n".join(self.callbacks)
<add> return "\n".join(cb.__class__.__name__ for cb in self.callbacks)
<ide>
<ide> def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl):
<ide> return self.call_event("on_init_end", args, state, control)
<ide><path>tests/test_trainer_callback.py
<ide> def test_event_flow(self):
<ide> trainer.train()
<ide> events = trainer.callback_handler.callbacks[-2].events
<ide> self.assertEqual(events, self.get_expected_events(trainer))
<add>
<add> # warning should be emitted for duplicated callbacks
<add> with unittest.mock.patch("transformers.trainer_callback.logger.warn") as warn_mock:
<add> trainer = self.get_trainer(
<add> callbacks=[MyTestTrainerCallback, MyTestTrainerCallback],
<add> )
<add> assert str(MyTestTrainerCallback) in warn_mock.call_args[0][0] | 2 |
Javascript | Javascript | add support for min & max on html 5 inputs | 8eb4e53a478c086d93d2414114e0bd8704237ecc | <ide><path>packages/ember-handlebars/lib/controls/text_field.js
<ide> Ember.TextField = Ember.Component.extend(Ember.TextSupport,
<ide>
<ide> classNames: ['ember-text-field'],
<ide> tagName: "input",
<del> attributeBindings: ['type', 'value', 'size', 'pattern', 'name'],
<add> attributeBindings: ['type', 'value', 'size', 'pattern', 'name', 'min', 'max'],
<ide>
<ide> /**
<ide> The `value` attribute of the input element. As the user inputs text, this
<ide> Ember.TextField = Ember.Component.extend(Ember.TextSupport,
<ide> size: null,
<ide>
<ide> /**
<del> The `pattern` the pattern attribute of input element.
<add> The `pattern` attribute of input element.
<ide>
<ide> @property pattern
<ide> @type String
<ide> @default null
<ide> */
<del> pattern: null
<add> pattern: null,
<add>
<add> /**
<add> The `min` attribute of input element used with `type="number"` or `type="range"`.
<add>
<add> @property min
<add> @type String
<add> @default null
<add> */
<add> min: null,
<add>
<add> /**
<add> The `max` attribute of input element used with `type="number"` or `type="range"`.
<add>
<add> @property max
<add> @type String
<add> @default null
<add> */
<add> max: null
<ide> }); | 1 |
PHP | PHP | remove incorrect phpdoc tags | 424f2eb1f292a64bd53dfc29e478dd995eebe38d | <ide><path>src/Cache/Cache.php
<ide> * See Cache engine documentation for expected configuration keys.
<ide> *
<ide> * @see config/app.php for configuration settings
<del> * @param string $name Name of the configuration
<del> * @param array $config Optional associative array of settings passed to the engine
<del> * @return array [engine, settings] on success, false on failure
<ide> */
<ide> class Cache
<ide> {
<ide><path>src/Datasource/ResultSetDecorator.php
<ide> /**
<ide> * Generic ResultSet decorator. This will make any traversable object appear to
<ide> * be a database result
<del> *
<del> * @return void
<ide> */
<ide> class ResultSetDecorator extends Collection implements ResultSetInterface
<ide> { | 2 |
PHP | PHP | fix deprecation comments | cc569504434599ad656ae81ca4fc745f4e7b6ab6 | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsTo.php
<ide> public function getRelationName()
<ide> * Get the name of the relationship.
<ide> *
<ide> * @return string
<del> * @deprecated The getRelationName() method should be used instead. Will be removed in Laravel 5.9.
<add> * @deprecated The getRelationName() method should be used instead. Will be removed in Laravel 6.0.
<ide> */
<ide> public function getRelation()
<ide> {
<ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> abstract class ServiceProvider
<ide> /**
<ide> * Indicates if loading of the provider is deferred.
<ide> *
<del> * @deprecated Implement the \Illuminate\Contracts\Support\DeferrableProvider interface instead. Will be removed in Laravel 5.9.
<add> * @deprecated Implement the \Illuminate\Contracts\Support\DeferrableProvider interface instead. Will be removed in Laravel 6.0.
<ide> *
<ide> * @var bool
<ide> */ | 2 |
PHP | PHP | stop email re-verification with same link | be70858192281f00006adc1a76c5e136476063f4 | <ide><path>src/Illuminate/Foundation/Auth/VerifiesEmails.php
<ide> public function verify(Request $request)
<ide> if ($request->route('id') != $request->user()->getKey()) {
<ide> throw new AuthorizationException;
<ide> }
<del>
<add>
<ide> if ($request->user()->hasVerifiedEmail()) {
<ide> return redirect($this->redirectPath());
<ide> } | 1 |
Javascript | Javascript | follow up to 15150 | daeda44d8f5abdb7354742bb69a967302d34d7f9 | <ide><path>packages/react-events/index.js
<ide>
<ide> 'use strict';
<ide>
<del>const ReactEvents = require('./src/ReactEvents');
<del>
<del>// TODO: decide on the top-level export form.
<del>// This is hacky but makes it work with both Rollup and Jest.
<del>module.exports = ReactEvents.default || ReactEvents;
<add>export * from './src/ReactEvents';
<ide><path>packages/react-events/src/ReactEvents.js
<ide> import {
<ide> } from 'shared/ReactSymbols';
<ide> import type {ReactEventTarget} from 'shared/ReactTypes';
<ide>
<del>const TouchHitTarget: ReactEventTarget = {
<add>export const TouchHitTarget: ReactEventTarget = {
<ide> $$typeof: REACT_EVENT_TARGET_TYPE,
<ide> type: REACT_EVENT_TARGET_TOUCH_HIT,
<ide> };
<del>
<del>const ReactEvents = {
<del> TouchHitTarget,
<del>};
<del>
<del>export default ReactEvents; | 2 |
Text | Text | fix broken link caused by case sensitivity | 9634cea47478507f915bcc0074f7a248df6fd027 | <ide><path>docs/api-guide/serializers.md
<ide> To serialize a queryset or list of objects instead of a single object instance,
<ide>
<ide> #### Deserializing multiple objects
<ide>
<del>The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#ListSerializer) documentation below.
<add>The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#listserializer) documentation below.
<ide>
<ide> ## Including extra context
<ide> | 1 |
PHP | PHP | apply fixes from styleci | c0ed2e420d1853e213c7b39729346a3c9c51a6e5 | <ide><path>src/Illuminate/Mail/MailManager.php
<ide> protected function createSendmailTransport(array $config)
<ide> protected function createSesTransport(array $config)
<ide> {
<ide> $config = array_merge(
<del> $this->app['config']->get('services.ses', []),
<del> ['version' => 'latest', 'service' => 'email'],
<add> $this->app['config']->get('services.ses', []),
<add> ['version' => 'latest', 'service' => 'email'],
<ide> $config
<ide> );
<ide> | 1 |
PHP | PHP | define contract for message bag | 672d6f8b8aec7f4231777667906c8405d8b25e83 | <ide><path>src/Illuminate/Contracts/Support/MessageBag.php
<add><?php namespace Illuminate\Contracts\Support;
<add>
<add>interface MessageBag {
<add>
<add> /**
<add> * Get the keys present in the message bag.
<add> *
<add> * @return array
<add> */
<add> public function keys();
<add>
<add> /**
<add> * Add a message to the bag.
<add> *
<add> * @param string $key
<add> * @param string $message
<add> * @return $this
<add> */
<add> public function add($key, $message);
<add>
<add> /**
<add> * Merge a new array of messages into the bag.
<add> *
<add> * @param \Illuminate\Contracts\Support\MessageProvider|array $messages
<add> * @return $this
<add> */
<add> public function merge($messages);
<add>
<add> /**
<add> * Determine if messages exist for a given key.
<add> *
<add> * @param string $key
<add> * @return bool
<add> */
<add> public function has($key = null);
<add>
<add> /**
<add> * Get the first message from the bag for a given key.
<add> *
<add> * @param string $key
<add> * @param string $format
<add> * @return string
<add> */
<add> public function first($key = null, $format = null);
<add>
<add> /**
<add> * Get all of the messages from the bag for a given key.
<add> *
<add> * @param string $key
<add> * @param string $format
<add> * @return array
<add> */
<add> public function get($key, $format = null);
<add>
<add> /**
<add> * Get all of the messages for every key in the bag.
<add> *
<add> * @param string $format
<add> * @return array
<add> */
<add> public function all($format = null);
<add>
<add> /**
<add> * Get the default message format.
<add> *
<add> * @return string
<add> */
<add> public function getFormat();
<add>
<add> /**
<add> * Set the default message format.
<add> *
<add> * @param string $format
<add> * @return $this
<add> */
<add> public function setFormat($format = ':message');
<add>
<add> /**
<add> * Determine if the message bag has any messages.
<add> *
<add> * @return bool
<add> */
<add> public function isEmpty();
<add>
<add> /**
<add> * Get the number of messages in the container.
<add> *
<add> * @return int
<add> */
<add> public function count();
<add>
<add> /**
<add> * Get the instance as an array.
<add> *
<add> * @return array
<add> */
<add> public function toArray();
<add>
<add>}
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Routing/Registrar.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/View/Factory.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/MessageProvider.php',
<add> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/Support/MessageBag.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Contracts/View/View.php',
<ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Container/Container.php',
<ide> $basePath.'/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernelInterface.php',
<ide><path>src/Illuminate/Support/MessageBag.php
<ide> use Illuminate\Contracts\Support\Jsonable;
<ide> use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Contracts\Support\MessageProvider;
<add>use Illuminate\Contracts\Support\MessageBag as MessageBagContract;
<ide>
<del>class MessageBag implements Arrayable, Countable, Jsonable, MessageProvider, JsonSerializable {
<add>class MessageBag implements Arrayable, Countable, Jsonable, JsonSerializable, MessageBagContract, MessageProvider {
<ide>
<ide> /**
<ide> * All of the registered messages. | 3 |
Javascript | Javascript | kill double `.normalize` | 305c488ad56bb21e49cbd0a8651f05b766979206 | <ide><path>src/extras/core/Curve.js
<ide> class Curve {
<ide> const u = i / segments;
<ide>
<ide> tangents[ i ] = this.getTangentAt( u, new Vector3() );
<del> tangents[ i ].normalize();
<ide>
<ide> }
<ide> | 1 |
Text | Text | fix typos in contributing guide [ci skip] | 60cb61dba69b131dcb468afae570da56f14276c9 | <ide><path>guides/source/contributing_to_ruby_on_rails.md
<ide> Having a way to reproduce your issue will be very helpful for others to help con
<ide> * Template for Action Pack (controllers, routing) issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
<ide> * Generic template for other issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_gem.rb)
<ide>
<del>These templates includes the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or Rails master (`*_master.rb`).
<add>These templates include the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or Rails master (`*_master.rb`).
<ide>
<del>Simply copy the content of the appropriate template into a `.rb` file on your computer and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
<add>Simply copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
<ide>
<ide> You can then share your executable test case as a [gist](https://gist.github.com), or simply paste the content into the issue description.
<ide> | 1 |
Java | Java | remove parameterized type from websockethandler | f347988428b50286ab9d5a7d19553917def76883 | <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/AbstractSockJsSession.java
<ide> public abstract class AbstractSockJsSession implements WebSocketSession {
<ide> * @param sessionId
<ide> * @param webSocketHandler the recipient of SockJS messages
<ide> */
<del> public AbstractSockJsSession(String sessionId, WebSocketHandler<?> webSocketHandler) {
<add> public AbstractSockJsSession(String sessionId, WebSocketHandler webSocketHandler) {
<ide> Assert.notNull(sessionId, "sessionId is required");
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> this.sessionId = sessionId;
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/SockJsSessionFactory.java
<ide> * @param webSocketHandler the underlying {@link WebSocketHandler}
<ide> * @return a new non-null session
<ide> */
<del> S createSession(String sessionId, WebSocketHandler<?> webSocketHandler);
<add> S createSession(String sessionId, WebSocketHandler webSocketHandler);
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java
<ide> public abstract class AbstractServerSockJsSession extends AbstractSockJsSession
<ide> private ScheduledFuture<?> heartbeatTask;
<ide>
<ide>
<del> public AbstractServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler<?> handler) {
<add> public AbstractServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler handler) {
<ide> super(sessionId, handler);
<ide> this.sockJsConfig = config;
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
<ide> public boolean isWebSocketEnabled() {
<ide> * @throws Exception
<ide> */
<ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> String sockJsPath, WebSocketHandler<?> webSocketHandler) throws IOException, TransportErrorException {
<add> String sockJsPath, WebSocketHandler webSocketHandler) throws IOException, TransportErrorException {
<ide>
<ide> logger.debug(request.getMethod() + " [" + sockJsPath + "]");
<ide>
<ide> else if (sockJsPath.equals("/websocket")) {
<ide> }
<ide>
<ide> protected abstract void handleRawWebSocketRequest(ServerHttpRequest request,
<del> ServerHttpResponse response, WebSocketHandler<?> webSocketHandler) throws IOException;
<add> ServerHttpResponse response, WebSocketHandler webSocketHandler) throws IOException;
<ide>
<ide> protected abstract void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> String sessionId, TransportType transportType, WebSocketHandler<?> webSocketHandler)
<add> String sessionId, TransportType transportType, WebSocketHandler webSocketHandler)
<ide> throws IOException, TransportErrorException;
<ide>
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsService.java
<ide> public interface SockJsService {
<ide>
<ide>
<ide> void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> String sockJsPath, WebSocketHandler<?> webSocketHandler) throws IOException, TransportErrorException;
<add> String sockJsPath, WebSocketHandler webSocketHandler) throws IOException, TransportErrorException;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/TransportHandler.java
<ide> public interface TransportHandler {
<ide> TransportType getTransportType();
<ide>
<ide> void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> handler, AbstractSockJsSession session) throws TransportErrorException;
<add> WebSocketHandler handler, AbstractSockJsSession session) throws TransportErrorException;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
<ide> public Map<TransportType, TransportHandler> getTransportHandlers() {
<ide>
<ide> @Override
<ide> protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler) throws IOException {
<add> WebSocketHandler webSocketHandler) throws IOException {
<ide>
<ide> if (isWebSocketEnabled()) {
<ide> TransportHandler transportHandler = this.transportHandlers.get(TransportType.WEBSOCKET);
<ide> protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpRe
<ide>
<ide> @Override
<ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> String sessionId, TransportType transportType, WebSocketHandler<?> webSocketHandler)
<add> String sessionId, TransportType transportType, WebSocketHandler webSocketHandler)
<ide> throws IOException, TransportErrorException {
<ide>
<ide> TransportHandler transportHandler = this.transportHandlers.get(transportType);
<ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo
<ide> }
<ide>
<ide> public AbstractSockJsSession getSockJsSession(String sessionId,
<del> WebSocketHandler<?> webSocketHandler, TransportHandler transportHandler) {
<add> WebSocketHandler webSocketHandler, TransportHandler transportHandler) {
<ide>
<ide> AbstractSockJsSession session = this.sessions.get(sessionId);
<ide> if (session != null) {
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/SockJsHttpRequestHandler.java
<ide> public class SockJsHttpRequestHandler implements HttpRequestHandler {
<ide>
<ide> private final SockJsService sockJsService;
<ide>
<del> private final WebSocketHandler<?> webSocketHandler;
<add> private final WebSocketHandler webSocketHandler;
<ide>
<ide> private final UrlPathHelper urlPathHelper = new UrlPathHelper();
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpReceivingTransportHandler.java
<ide> public ObjectMapper getObjectMapper() {
<ide>
<ide> @Override
<ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler, AbstractSockJsSession session)
<add> WebSocketHandler webSocketHandler, AbstractSockJsSession session)
<ide> throws TransportErrorException {
<ide>
<ide> if (session == null) {
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpSendingTransportHandler.java
<ide> public SockJsConfiguration getSockJsConfig() {
<ide>
<ide> @Override
<ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler, AbstractSockJsSession session)
<add> WebSocketHandler webSocketHandler, AbstractSockJsSession session)
<ide> throws TransportErrorException {
<ide>
<ide> // Set content type before writing
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/AbstractHttpServerSockJsSession.java
<ide> public abstract class AbstractHttpServerSockJsSession extends AbstractServerSock
<ide> private ServerHttpResponse response;
<ide>
<ide>
<del> public AbstractHttpServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler<?> handler) {
<add> public AbstractHttpServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler handler) {
<ide> super(sessionId, config, handler);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/EventSourceTransportHandler.java
<ide> protected MediaType getContentType() {
<ide> }
<ide>
<ide> @Override
<del> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler<?> handler) {
<add> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler handler) {
<ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration");
<ide> return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), handler) {
<ide> @Override
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/HtmlFileTransportHandler.java
<ide> protected MediaType getContentType() {
<ide> }
<ide>
<ide> @Override
<del> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler<?> handler) {
<add> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler handler) {
<ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration");
<ide>
<ide> return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), handler) {
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/JsonpPollingTransportHandler.java
<ide> protected MediaType getContentType() {
<ide> }
<ide>
<ide> @Override
<del> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler<?> handler) {
<add> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler handler) {
<ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration");
<ide> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/PollingServerSockJsSession.java
<ide>
<ide> public class PollingServerSockJsSession extends AbstractHttpServerSockJsSession {
<ide>
<del> public PollingServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler<?> handler) {
<add> public PollingServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler handler) {
<ide> super(sessionId, config, handler);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/SockJsWebSocketHandler.java
<ide> public class SockJsWebSocketHandler extends TextWebSocketHandlerAdapter {
<ide>
<ide> private final SockJsConfiguration sockJsConfig;
<ide>
<del> private final WebSocketHandler<?> webSocketHandler;
<add> private final WebSocketHandler webSocketHandler;
<ide>
<ide> private WebSocketServerSockJsSession sockJsSession;
<ide>
<ide> public class SockJsWebSocketHandler extends TextWebSocketHandlerAdapter {
<ide> private final ObjectMapper objectMapper = new ObjectMapper();
<ide>
<ide>
<del> public SockJsWebSocketHandler(SockJsConfiguration config, WebSocketHandler<?> webSocketHandler) {
<add> public SockJsWebSocketHandler(SockJsConfiguration config, WebSocketHandler webSocketHandler) {
<ide> Assert.notNull(config, "sockJsConfig is required");
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> this.sockJsConfig = config;
<ide> public void afterConnectionEstablished(WebSocketSession wsSession) {
<ide> }
<ide>
<ide> @Override
<del> public void handleMessage(WebSocketSession wsSession, TextMessage message) {
<add> public void handleTextMessage(WebSocketSession wsSession, TextMessage message) {
<ide> this.sockJsSession.handleMessage(message, wsSession);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/StreamingServerSockJsSession.java
<ide> public class StreamingServerSockJsSession extends AbstractHttpServerSockJsSessio
<ide> private int byteCount;
<ide>
<ide>
<del> public StreamingServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler<?> handler) {
<add> public StreamingServerSockJsSession(String sessionId, SockJsConfiguration config, WebSocketHandler handler) {
<ide> super(sessionId, config, handler);
<ide> }
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/WebSocketTransportHandler.java
<ide> public void setSockJsConfiguration(SockJsConfiguration sockJsConfig) {
<ide>
<ide> @Override
<ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler, AbstractSockJsSession session) throws TransportErrorException {
<add> WebSocketHandler webSocketHandler, AbstractSockJsSession session) throws TransportErrorException {
<ide>
<ide> try {
<del> WebSocketHandler<?> sockJsWrapper = new SockJsWebSocketHandler(this.sockJsConfig, webSocketHandler);
<add> WebSocketHandler sockJsWrapper = new SockJsWebSocketHandler(this.sockJsConfig, webSocketHandler);
<ide> this.handshakeHandler.doHandshake(request, response, sockJsWrapper);
<ide> }
<ide> catch (Throwable t) {
<ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response
<ide> // HandshakeHandler methods
<ide>
<ide> @Override
<del> public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler<?> handler)
<add> public boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler)
<ide> throws IOException {
<ide>
<ide> return this.handshakeHandler.doHandshake(request, response, handler);
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/XhrPollingTransportHandler.java
<ide> protected FrameFormat getFrameFormat(ServerHttpRequest request) {
<ide> return new DefaultFrameFormat("%s\n");
<ide> }
<ide>
<del> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler<?> handler) {
<add> public PollingServerSockJsSession createSession(String sessionId, WebSocketHandler handler) {
<ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration");
<ide> return new PollingServerSockJsSession(sessionId, getSockJsConfig(), handler);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/transport/XhrStreamingTransportHandler.java
<ide> protected MediaType getContentType() {
<ide> }
<ide>
<ide> @Override
<del> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler<?> handler) {
<add> public StreamingServerSockJsSession createSession(String sessionId, WebSocketHandler handler) {
<ide> Assert.notNull(getSockJsConfig(), "This transport requires SockJsConfiguration");
<ide>
<ide> return new StreamingServerSockJsSession(sessionId, getSockJsConfig(), handler) {
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/WebSocketHandler.java
<ide> * @author Phillip Webb
<ide> * @since 4.0
<ide> */
<del>public interface WebSocketHandler<T extends WebSocketMessage<?>> {
<add>public interface WebSocketHandler {
<ide>
<ide> /**
<ide> * A new WebSocket connection has been opened and is ready to be used.
<ide> /**
<ide> * Handle an incoming WebSocket message.
<ide> */
<del> void handleMessage(WebSocketSession session, T message);
<add> void handleMessage(WebSocketSession session, WebSocketMessage<?> message);
<ide>
<ide> /**
<ide> * Handle an error from the underlying WebSocket message transport.
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/BinaryWebSocketHandlerAdapter.java
<ide>
<ide> package org.springframework.websocket.adapter;
<ide>
<del>import org.springframework.websocket.BinaryMessage;
<add>import java.io.IOException;
<add>
<ide> import org.springframework.websocket.CloseStatus;
<add>import org.springframework.websocket.TextMessage;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> import org.springframework.websocket.WebSocketSession;
<ide>
<ide> * @author Phillip Webb
<ide> * @since 4.0
<ide> */
<del>public class BinaryWebSocketHandlerAdapter implements WebSocketHandler<BinaryMessage> {
<add>public class BinaryWebSocketHandlerAdapter extends WebSocketHandlerAdapter {
<ide>
<del> @Override
<del> public void afterConnectionEstablished(WebSocketSession session) {
<del> }
<del>
<del> @Override
<del> public void handleMessage(WebSocketSession session, BinaryMessage message) {
<del> }
<del>
<del> @Override
<del> public void handleTransportError(WebSocketSession session, Throwable exception) {
<del> }
<ide>
<ide> @Override
<del> public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
<add> protected void handleTextMessage(WebSocketSession session, TextMessage message) {
<add> try {
<add> session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Text messages not supported"));
<add> }
<add> catch (IOException e) {
<add> // ignore
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/JettyWebSocketListenerAdapter.java
<ide> import org.springframework.websocket.CloseStatus;
<ide> import org.springframework.websocket.TextMessage;
<ide> import org.springframework.websocket.WebSocketHandler;
<del>import org.springframework.websocket.WebSocketMessage;
<ide> import org.springframework.websocket.WebSocketSession;
<ide>
<ide> /**
<ide> public class JettyWebSocketListenerAdapter implements WebSocketListener {
<ide>
<ide> private static Log logger = LogFactory.getLog(JettyWebSocketListenerAdapter.class);
<ide>
<del> private final WebSocketHandler<WebSocketMessage<?>> webSocketHandler;
<add> private final WebSocketHandler webSocketHandler;
<ide>
<ide> private WebSocketSession wsSession;
<ide>
<ide>
<del> public JettyWebSocketListenerAdapter(WebSocketHandler<?> webSocketHandler) {
<add> public JettyWebSocketListenerAdapter(WebSocketHandler webSocketHandler) {
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> this.webSocketHandler = new WebSocketHandlerInvoker(webSocketHandler).setLogger(logger);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/StandardEndpointAdapter.java
<ide> public class StandardEndpointAdapter extends Endpoint {
<ide>
<ide>
<ide>
<del> public StandardEndpointAdapter(WebSocketHandler<?> webSocketHandler) {
<add> public StandardEndpointAdapter(WebSocketHandler webSocketHandler) {
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> this.handler = new WebSocketHandlerInvoker(webSocketHandler).setLogger(logger);
<ide> this.handlerClass= webSocketHandler.getClass();
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/TextWebSocketHandlerAdapter.java
<ide>
<ide> package org.springframework.websocket.adapter;
<ide>
<add>import java.io.IOException;
<add>
<add>import org.springframework.websocket.BinaryMessage;
<ide> import org.springframework.websocket.CloseStatus;
<del>import org.springframework.websocket.TextMessage;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> import org.springframework.websocket.WebSocketSession;
<ide>
<ide> * @author Phillip Webb
<ide> * @since 4.0
<ide> */
<del>public class TextWebSocketHandlerAdapter implements WebSocketHandler<TextMessage> {
<add>public class TextWebSocketHandlerAdapter extends WebSocketHandlerAdapter {
<ide>
<del> @Override
<del> public void afterConnectionEstablished(WebSocketSession session) {
<del> }
<del>
<del> @Override
<del> public void handleMessage(WebSocketSession session, TextMessage message) {
<del> }
<del>
<del> @Override
<del> public void handleTransportError(WebSocketSession session, Throwable exception) {
<del> }
<ide>
<ide> @Override
<del> public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
<add> protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) {
<add> try {
<add> session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Binary messages not supported"));
<add> }
<add> catch (IOException e) {
<add> // ignore
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/WebSocketHandlerAdapter.java
<ide> * @see TextWebSocketHandlerAdapter
<ide> * @see BinaryWebSocketHandlerAdapter
<ide> */
<del>public class WebSocketHandlerAdapter implements WebSocketHandler<WebSocketMessage<?>> {
<add>public class WebSocketHandlerAdapter implements WebSocketHandler {
<ide>
<ide> @Override
<ide> public void afterConnectionEstablished(WebSocketSession session) {
<ide> else if (message instanceof BinaryMessage) {
<ide> handleBinaryMessage(session, (BinaryMessage) message);
<ide> }
<ide> else {
<add> // should not happen
<ide> throw new IllegalStateException("Unexpected WebSocket message type: " + message);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/adapter/WebSocketHandlerInvoker.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.websocket.CloseStatus;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> * @author Phillip Webb
<ide> * @since 4.0
<ide> */
<del>public class WebSocketHandlerInvoker implements WebSocketHandler<WebSocketMessage<?>> {
<add>public class WebSocketHandlerInvoker implements WebSocketHandler {
<ide>
<ide> private Log logger = LogFactory.getLog(WebSocketHandlerInvoker.class);
<ide>
<del> private final WebSocketHandler<?> handler;
<del>
<del> private final Class<?> supportedMessageType;
<add> private final WebSocketHandler handler;
<ide>
<ide> private final AtomicInteger sessionCount = new AtomicInteger(0);
<ide>
<ide>
<del> public WebSocketHandlerInvoker(WebSocketHandler<?> webSocketHandler) {
<add> public WebSocketHandlerInvoker(WebSocketHandler webSocketHandler) {
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> this.handler = webSocketHandler;
<del> Class<?> handlerType = webSocketHandler.getClass();
<del> this.supportedMessageType = GenericTypeResolver.resolveTypeArgument(handlerType, WebSocketHandler.class);
<ide> }
<ide>
<ide> public WebSocketHandlerInvoker setLogger(Log logger) {
<ide> public void tryCloseWithError(WebSocketSession session, Throwable ex) {
<ide> }
<ide>
<ide> public void tryCloseWithError(WebSocketSession session, Throwable exeption, CloseStatus status) {
<del> if (exeption != null) {
<del> logger.error("Closing due to exception for " + session, exeption);
<del> }
<add> logger.error("Closing due to exception for " + session, exeption);
<ide> if (session.isOpen()) {
<ide> try {
<ide> session.close((status != null) ? status : CloseStatus.SERVER_ERROR);
<ide> public void tryCloseWithError(WebSocketSession session, Throwable exeption, Clos
<ide> }
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Received " + message + ", " + session);
<ide> }
<del> if (!this.supportedMessageType.isAssignableFrom(message.getClass())) {
<del> tryCloseWithError(session, null, CloseStatus.NOT_ACCEPTABLE.withReason("Message type not supported"));
<del> return;
<del> }
<ide> try {
<del> ((WebSocketHandler) this.handler).handleMessage(session, message);
<add> this.handler.handleMessage(session, message);
<ide> }
<ide> catch (Throwable ex) {
<ide> tryCloseWithError(session,ex);
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketClient.java
<ide> public interface WebSocketClient {
<ide> WebSocketSession doHandshake(WebSocketHandler webSocketHandler,
<ide> String uriTemplate, Object... uriVariables) throws WebSocketConnectFailureException;
<ide>
<del> WebSocketSession doHandshake(WebSocketHandler<?> webSocketHandler, HttpHeaders headers, URI uri)
<add> WebSocketSession doHandshake(WebSocketHandler webSocketHandler, HttpHeaders headers, URI uri)
<ide> throws WebSocketConnectFailureException;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java
<ide> public class WebSocketConnectionManager extends AbstractWebSocketConnectionManag
<ide>
<ide> private final WebSocketClient client;
<ide>
<del> private final WebSocketHandler<?> webSocketHandler;
<add> private final WebSocketHandler webSocketHandler;
<ide>
<ide> private WebSocketSession webSocketSession;
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/endpoint/StandardWebSocketClient.java
<ide> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler, String ur
<ide> }
<ide>
<ide> @Override
<del> public WebSocketSession doHandshake(WebSocketHandler<?> webSocketHandler,
<add> public WebSocketSession doHandshake(WebSocketHandler webSocketHandler,
<ide> final HttpHeaders httpHeaders, URI uri) throws WebSocketConnectFailureException {
<ide>
<ide> Endpoint endpoint = new StandardEndpointAdapter(webSocketHandler);
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/DefaultHandshakeHandler.java
<ide> public String[] getSupportedProtocols() {
<ide>
<ide> @Override
<ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler) throws IOException {
<add> WebSocketHandler webSocketHandler) throws IOException {
<ide>
<ide> logger.debug("Starting handshake for " + request.getURI());
<ide>
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/HandshakeHandler.java
<ide> public interface HandshakeHandler {
<ide>
<ide>
<del> boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response,
<del> WebSocketHandler<?> webSocketHandler) throws IOException;
<add> boolean doHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler)
<add> throws IOException;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/RequestUpgradeStrategy.java
<ide> public interface RequestUpgradeStrategy {
<ide> * Perform runtime specific steps to complete the upgrade.
<ide> * Invoked only if the handshake is successful.
<ide> *
<del> * @param handler the handler for WebSocket messages
<add> * @param webSocketHandler the handler for WebSocket messages
<ide> */
<ide> void upgrade(ServerHttpRequest request, ServerHttpResponse response, String selectedProtocol,
<del> WebSocketHandler<?> webSocketHandler) throws IOException;
<add> WebSocketHandler webSocketHandler) throws IOException;
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/AbstractEndpointUpgradeStrategy.java
<ide> public abstract class AbstractEndpointUpgradeStrategy implements RequestUpgradeS
<ide>
<ide> @Override
<ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
<del> String protocol, WebSocketHandler<?> webSocketHandler) throws IOException {
<add> String protocol, WebSocketHandler webSocketHandler) throws IOException {
<ide>
<ide> upgradeInternal(request, response, protocol, new StandardEndpointAdapter(webSocketHandler));
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/JettyRequestUpgradeStrategy.java
<ide> public JettyRequestUpgradeStrategy() {
<ide> public Object createWebSocket(UpgradeRequest request, UpgradeResponse response) {
<ide> Assert.isInstanceOf(ServletWebSocketRequest.class, request);
<ide> ServletWebSocketRequest servletRequest = (ServletWebSocketRequest) request;
<del> WebSocketHandler<?> webSocketHandler =
<del> (WebSocketHandler<?>) servletRequest.getServletAttributes().get(HANDLER_PROVIDER_ATTR_NAME);
<add> WebSocketHandler webSocketHandler =
<add> (WebSocketHandler) servletRequest.getServletAttributes().get(HANDLER_PROVIDER_ATTR_NAME);
<ide> return new JettyWebSocketListenerAdapter(webSocketHandler);
<ide> }
<ide> });
<ide> public String[] getSupportedVersions() {
<ide>
<ide> @Override
<ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
<del> String selectedProtocol, WebSocketHandler<?> webSocketHandler) throws IOException {
<add> String selectedProtocol, WebSocketHandler webSocketHandler) throws IOException {
<ide>
<ide> Assert.isInstanceOf(ServletServerHttpRequest.class, request);
<ide> HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
<ide> public void upgrade(ServerHttpRequest request, ServerHttpResponse response,
<ide> }
<ide>
<ide> private void upgrade(HttpServletRequest request, HttpServletResponse response,
<del> String selectedProtocol, final WebSocketHandler<?> webSocketHandler) throws IOException {
<add> String selectedProtocol, final WebSocketHandler webSocketHandler) throws IOException {
<ide>
<ide> Assert.state(this.factory.isUpgradeRequest(request, response), "Not a suitable WebSocket upgrade request");
<ide> Assert.state(this.factory.acceptWebSocket(request, response), "Unable to accept WebSocket");
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/support/WebSocketHttpRequestHandler.java
<ide> public class WebSocketHttpRequestHandler implements HttpRequestHandler {
<ide>
<ide> private final HandshakeHandler handshakeHandler;
<ide>
<del> private final WebSocketHandler<?> webSocketHandler;
<add> private final WebSocketHandler webSocketHandler;
<ide>
<ide>
<ide> public WebSocketHttpRequestHandler(WebSocketHandler webSocketHandler) {
<ide> this(webSocketHandler, new DefaultHandshakeHandler());
<ide> }
<ide>
<del> public WebSocketHttpRequestHandler( WebSocketHandler<?> webSocketHandler, HandshakeHandler handshakeHandler) {
<add> public WebSocketHttpRequestHandler( WebSocketHandler webSocketHandler, HandshakeHandler handshakeHandler) {
<ide> Assert.notNull(webSocketHandler, "webSocketHandler is required");
<ide> Assert.notNull(handshakeHandler, "handshakeHandler is required");
<ide> this.webSocketHandler = webSocketHandler;
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/support/PerConnectionWebSocketHandlerProxy.java
<ide>
<ide> package org.springframework.websocket.support;
<ide>
<del>import java.io.IOException;
<ide> import java.util.Map;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide>
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.beans.factory.BeanFactoryAware;
<del>import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.websocket.CloseStatus;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public class PerConnectionWebSocketHandlerProxy implements WebSocketHandler<WebSocketMessage<?>>, BeanFactoryAware {
<add>public class PerConnectionWebSocketHandlerProxy implements WebSocketHandler, BeanFactoryAware {
<ide>
<ide> private Log logger = LogFactory.getLog(PerConnectionWebSocketHandlerProxy.class);
<ide>
<del> private final BeanCreatingHandlerProvider<WebSocketHandler<?>> provider;
<add> private final BeanCreatingHandlerProvider<WebSocketHandler> provider;
<ide>
<del> private Map<WebSocketSession, WebSocketHandler<?>> handlers =
<del> new ConcurrentHashMap<WebSocketSession, WebSocketHandler<?>>();
<add> private Map<WebSocketSession, WebSocketHandler> handlers =
<add> new ConcurrentHashMap<WebSocketSession, WebSocketHandler>();
<ide>
<del> private final Class<?> supportedMessageType;
<ide>
<del>
<del> public PerConnectionWebSocketHandlerProxy(Class<? extends WebSocketHandler<?>> handlerType) {
<del> this.provider = new BeanCreatingHandlerProvider<WebSocketHandler<?>>(handlerType);
<del> this.supportedMessageType = GenericTypeResolver.resolveTypeArgument(handlerType, WebSocketHandler.class);
<add> public PerConnectionWebSocketHandlerProxy(Class<? extends WebSocketHandler> handlerType) {
<add> this.provider = new BeanCreatingHandlerProvider<WebSocketHandler>(handlerType);
<ide> }
<ide>
<ide>
<ide> public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
<ide>
<ide> @Override
<ide> public void afterConnectionEstablished(WebSocketSession session) {
<del> WebSocketHandler<?> handler = this.provider.getHandler();
<add> WebSocketHandler handler = this.provider.getHandler();
<ide> this.handlers.put(session, handler);
<ide> handler.afterConnectionEstablished(session);
<ide> }
<ide>
<del> @SuppressWarnings("unchecked")
<ide> @Override
<ide> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
<del> if (!this.supportedMessageType.isAssignableFrom(message.getClass())) {
<del> try {
<del> session.close(CloseStatus.NOT_ACCEPTABLE.withReason("Message type not supported"));
<del> }
<del> catch (IOException e) {
<del> destroy(session);
<del> }
<del> }
<del> else {
<del> ((WebSocketHandler) getHandler(session)).handleMessage(session, message);
<del> }
<add> getHandler(session).handleMessage(session, message);
<ide> }
<ide>
<del> private WebSocketHandler<?> getHandler(WebSocketSession session) {
<del> WebSocketHandler<?> handler = this.handlers.get(session);
<add> private WebSocketHandler getHandler(WebSocketSession session) {
<add> WebSocketHandler handler = this.handlers.get(session);
<ide> Assert.isTrue(handler != null, "WebSocketHandler not found for " + session);
<ide> return handler;
<ide> }
<ide> public void afterConnectionClosed(WebSocketSession session, CloseStatus closeSta
<ide> }
<ide>
<ide> private void destroy(WebSocketSession session) {
<del> WebSocketHandler<?> handler = this.handlers.remove(session);
<add> WebSocketHandler handler = this.handlers.remove(session);
<ide> try {
<ide> if (handler != null) {
<ide> this.provider.destroy(handler); | 37 |
Javascript | Javascript | assign bufferrow property to line number nodes | 5b073349938308a205b0e924e2dac725245f9a9a | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> await component.getNextUpdatePromise()
<ide> expect(element.classList.contains('has-selection')).toBe(false)
<ide> })
<add>
<add> it('assigns a buffer-row to each line number as a data field', async () => {
<add> const {editor, element, component} = buildComponent()
<add> editor.setSoftWrapped(true)
<add> await component.getNextUpdatePromise()
<add> await setEditorWidthInCharacters(component, 40)
<add>
<add> expect(
<add> Array.from(element.querySelectorAll('.line-number:not(.dummy)'))
<add> .map((element) => element.dataset.bufferRow)
<add> ).toEqual([
<add> '0', '1', '2', '3', '3', '4', '5', '6', '6', '6',
<add> '7', '8', '8', '8', '9', '10', '11', '11', '12'
<add> ])
<add> })
<ide> })
<ide>
<ide> describe('mini editors', () => {
<ide><path>src/text-editor-component.js
<ide> class TextEditorComponent {
<ide> this.guttersToRender = [this.props.model.getLineNumberGutter()]
<ide> this.lineNumbersToRender = {
<ide> maxDigits: 2,
<del> numbers: [],
<add> bufferRows: [],
<ide> keys: [],
<add> softWrappedFlags: [],
<ide> foldableFlags: []
<ide> }
<ide> this.decorationsToRender = {
<ide> class TextEditorComponent {
<ide> if (!this.props.model.isLineNumberGutterVisible()) return null
<ide>
<ide> if (this.measurements) {
<del> const {maxDigits, keys, numbers, foldableFlags} = this.lineNumbersToRender
<add> const {maxDigits, keys, bufferRows, softWrappedFlags, foldableFlags} = this.lineNumbersToRender
<ide> return $(LineNumberGutterComponent, {
<ide> ref: 'lineNumberGutter',
<ide> element: gutter.getElement(),
<ide> class TextEditorComponent {
<ide> rowsPerTile: this.getRowsPerTile(),
<ide> maxDigits: maxDigits,
<ide> keys: keys,
<del> numbers: numbers,
<add> bufferRows: bufferRows,
<add> softWrappedFlags: softWrappedFlags,
<ide> foldableFlags: foldableFlags,
<ide> decorations: this.decorationsToRender.lineNumbers,
<ide> blockDecorations: this.decorationsToRender.blocks,
<ide> class TextEditorComponent {
<ide> const endRow = this.getRenderedEndRow()
<ide> const renderedRowCount = this.getRenderedRowCount()
<ide>
<del> const {numbers, keys, foldableFlags} = this.lineNumbersToRender
<del> numbers.length = renderedRowCount
<add> const {bufferRows, keys, softWrappedFlags, foldableFlags} = this.lineNumbersToRender
<add> bufferRows.length = renderedRowCount
<ide> keys.length = renderedRowCount
<ide> foldableFlags.length = renderedRowCount
<ide>
<ide> class TextEditorComponent {
<ide> for (let row = startRow; row < endRow; row++) {
<ide> const i = row - startRow
<ide> const bufferRow = model.bufferRowForScreenRow(row)
<add> bufferRows[i] = bufferRow
<ide> if (bufferRow === previousBufferRow) {
<del> numbers[i] = -1
<del> keys[i] = bufferRow + 1 + '-' + softWrapCount++
<add> softWrapCount++
<add> softWrappedFlags[i] = true
<ide> foldableFlags[i] = false
<add> keys[i] = bufferRow + '-' + softWrapCount
<ide> } else {
<ide> softWrapCount = 0
<del> numbers[i] = bufferRow + 1
<del> keys[i] = bufferRow + 1
<add> softWrappedFlags[i] = false
<ide> foldableFlags[i] = model.isFoldableAtBufferRow(bufferRow)
<add> keys[i] = bufferRow
<ide> }
<ide> previousBufferRow = bufferRow
<ide> }
<ide> class LineNumberGutterComponent {
<ide> render () {
<ide> const {
<ide> parentComponent, height, width, lineHeight, startRow, endRow, rowsPerTile,
<del> maxDigits, keys, numbers, foldableFlags, decorations
<add> maxDigits, keys, bufferRows, softWrappedFlags, foldableFlags, decorations
<ide> } = this.props
<ide>
<ide> let children = null
<ide>
<del> if (numbers) {
<add> if (bufferRows) {
<ide> const renderedTileCount = parentComponent.getRenderedTileCount()
<ide> children = new Array(renderedTileCount)
<ide>
<ide> class LineNumberGutterComponent {
<ide> for (let row = tileStartRow; row < tileEndRow; row++) {
<ide> const i = row - startRow
<ide> const key = keys[i]
<add> const softWrapped = softWrappedFlags[i]
<ide> const foldable = foldableFlags[i]
<del> let number = numbers[i]
<add> const bufferRow = bufferRows[i]
<ide>
<ide> let className = 'line-number'
<ide> if (foldable) className = className + ' foldable'
<ide>
<ide> const decorationsForRow = decorations[row - startRow]
<ide> if (decorationsForRow) className = className + ' ' + decorationsForRow
<ide>
<del> if (number === -1) number = '•'
<add> let number = softWrapped ? '•' : bufferRow + 1
<ide> number = NBSP_CHARACTER.repeat(maxDigits - number.length) + number
<ide>
<del> let lineNumberProps = {key, className}
<add> let lineNumberProps = {key, className, dataset: {bufferRow}}
<ide>
<ide> if (row === 0 || i > 0) {
<ide> let currentRowTop = parentComponent.pixelPositionAfterBlocksForRow(row)
<ide> class LineNumberGutterComponent {
<ide>
<ide> return $.div(
<ide> {
<del> className: 'gutter line-numbers',
<add> className: 'gutter line-bufferRows',
<ide> attributes: {'gutter-name': 'line-number'},
<ide> style: {position: 'relative', height: height + 'px'},
<ide> on: {
<ide> class LineNumberGutterComponent {
<ide> if (oldProps.maxDigits !== newProps.maxDigits) return true
<ide> if (newProps.didMeasureVisibleBlockDecoration) return true
<ide> if (!arraysEqual(oldProps.keys, newProps.keys)) return true
<del> if (!arraysEqual(oldProps.numbers, newProps.numbers)) return true
<add> if (!arraysEqual(oldProps.bufferRows, newProps.bufferRows)) return true
<ide> if (!arraysEqual(oldProps.foldableFlags, newProps.foldableFlags)) return true
<ide> if (!arraysEqual(oldProps.decorations, newProps.decorations)) return true
<ide> | 2 |
Go | Go | ignore hns networks with type private | b91fd26bb57c94a7ea7f77e5e548233506b78d21 | <ide><path>daemon/daemon_windows.go
<ide> func (daemon *Daemon) initNetworkController(config *config.Config, activeSandbox
<ide> // discover and add HNS networks to windows
<ide> // network that exist are removed and added again
<ide> for _, v := range hnsresponse {
<add> if strings.ToLower(v.Type) == "private" {
<add> continue // workaround for HNS reporting unsupported networks
<add> }
<ide> var n libnetwork.Network
<ide> s := func(current libnetwork.Network) bool {
<ide> options := current.Info().DriverOptions() | 1 |
Javascript | Javascript | use s_client instead of curl | 4d5489667cb073ec9d82ef292ecd0749de494238 | <ide><path>test/simple/test-https-foafssl.js
<ide> var assert = require('assert');
<ide> var join = require('path').join;
<ide>
<ide> var fs = require('fs');
<del>var exec = require('child_process').exec;
<del>
<add>var spawn = require('child_process').spawn;
<ide> var https = require('https');
<ide>
<ide> var options = {
<ide> var options = {
<ide> };
<ide>
<ide> var reqCount = 0;
<add>var CRLF = '\r\n';
<ide> var body = 'hello world\n';
<ide> var cert;
<ide> var subjectaltname;
<ide> var server = https.createServer(options, function(req, res) {
<ide> res.end(body);
<ide> });
<ide>
<del>
<ide> server.listen(common.PORT, function() {
<del> var cmd = 'curl --insecure https://127.0.0.1:' + common.PORT + '/';
<del> cmd += ' --cert ' + join(common.fixturesDir, 'foafssl.crt');
<del> cmd += ' --key ' + join(common.fixturesDir, 'foafssl.key');
<del> console.error('executing %j', cmd);
<del> exec(cmd, function(err, stdout, stderr) {
<del> if (err) throw err;
<del> common.error(common.inspect(stdout));
<del> assert.equal(body, stdout);
<add> var args = ['s_client',
<add> '-quiet',
<add> '-connect', '127.0.0.1:' + common.PORT,
<add> '-cert', join(common.fixturesDir, 'foafssl.crt'),
<add> '-key', join(common.fixturesDir, 'foafssl.key')];
<add>
<add> var client = spawn(common.opensslCli, args);
<add>
<add> client.stdout.on('data', function(data) {
<add> var message = data.toString();
<add> var contents = message.split(CRLF + CRLF).pop();
<add> assert.equal(body, contents);
<ide> server.close();
<ide> });
<ide>
<add> client.stdin.write('GET /\n\n');
<add>
<add> client.on('error', function(error) {
<add> throw error;
<add> });
<ide> });
<ide>
<ide> process.on('exit', function() { | 1 |
Go | Go | lock container when set state to restarting | 155714c59650a7b9b8f890f4d20c83ea9b80206b | <ide><path>container/monitor.go
<ide> func (m *containerMonitor) start() error {
<ide> m.resetMonitor(err == nil && exitStatus.ExitCode == 0)
<ide>
<ide> if m.shouldRestart(exitStatus.ExitCode) {
<del> m.container.SetRestarting(&exitStatus)
<add> m.container.SetRestartingLocking(&exitStatus)
<ide> m.logEvent("die")
<ide> m.resetContainer(true)
<ide> | 1 |
Javascript | Javascript | add some better documentation to the async counter | 8a86259f6134d5c099093903da2c94adbe472141 | <ide><path>examples/universal/api/counter.js
<ide> function getRandomInt(min, max) {
<ide> }
<ide>
<ide> export function fetchCounter(callback) {
<add> // Rather than immediately returning, we delay our code with a timeout to simulate asynchronous behavior
<ide> setTimeout(() => {
<ide> callback(getRandomInt(1, 100));
<ide> }, 500);
<add>
<add> // In the case of a real world API call, you'll normally run into a Promise like this:
<add> // API.getUser().then(user => callback(user));
<ide> } | 1 |
Go | Go | fix validation of plugins without rootfs in config | 6c7cb520094866cacbecb96695aed2d67d8a64a0 | <ide><path>plugin/manager.go
<ide> func configToRootFS(c []byte) (*image.RootFS, error) {
<ide> if err := json.Unmarshal(c, &pluginConfig); err != nil {
<ide> return nil, err
<ide> }
<add> // validation for empty rootfs is in distribution code
<add> if pluginConfig.Rootfs == nil {
<add> return nil, nil
<add> }
<ide>
<ide> return rootFSFromPlugin(pluginConfig.Rootfs), nil
<ide> } | 1 |
PHP | PHP | remove useless foreach | 2c4c93175db79b37331b07e561d7e2232894b7f8 | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> protected function replaceRouteParameters($path, array &$parameters)
<ide> return $match[0];
<ide> }
<ide>
<del> foreach ($parameters as $key => $value) {
<del> return array_shift($parameters);
<del> }
<add> return array_shift($parameters);
<ide> }, $path);
<ide> }
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.