text:
# Wrench
Library for more easily using [BBolt](https://github.com/etcd-io/bbolt)
Based almost entirely on internal methods from my [BoltInspector](https://github.com/89yoyos/BoltInspector) tool

## About
Wrench is a tool I am working on to simplify implementing Bolt databases. The idea is to make reading the database as easy as simply using Insert and Delete commands (among others). Obviously, majorly simplifying the library also limits it in some ways, however I feel the tradeoffs are worthwhile for developers (like myself) who aren't stressing over perfect implementation and simply want a quick and easy way to store information.

## Usage
### Adding Wrench to Your Project

You can grab this library with Go Get
```
$ go get https://github.com/89yoyos/Wrench/...
```

Then import the library like any other
```go
import ("https://github.com/89yoyos/Wrench")
```

### Setup
To use Wrench, you need to declare a Wrench object.
```go
w := Wrench.Wrench{}
```
Next, just use your Wrench to open the Bolt database you want to use.
```go
err := w.OpenDB("File/Path.db")
```
The `OpenDB` command returns a normal Error object if it fails to open the file, so you can implement whatever error handling you're most comfortable with.

### Adding a Bucket
An empty Bolt database cannot hold key value pairs, they need to be inside of a bucket. To create a bucket with Wrench, use the `CreateBucket` command.
```go
w.CreateBucket("key")
```
If you've used Bolt before, you may have noticed that Wrench treats all keys as strings. This is intentional, though not in line with pure Bolt, which allows any array of bytes to be used as a key. I found this limitation immensely simplifies working with the database, though it may cause issues with databases with non-string keys.

### Navigating Your Database
In Bolt, accessing buckets could be tedious, and accessing sub-buckets would only make it worse. Wrench attempts to alleviate this by treating the database like a filesystem. Your Wrench object knows its current location within the database, and anything you do is relative to position. To see where your Wrench is currently positioned, you can use the `CurrentBucket` and `CurrentBucketString` functions.

`CurrentBucket` returns an array of strings, starting at the root of the directory and working through all the buckets and sub-buckets to get to your current position.

`CurrentBucketString` works in a similar way, however it returns a single string representing that path.

To change where your Wrench is positioned, you can use the `GoTo` function.
```go
w.GoTo(["~","Path","as","an","Array"])
```
Or, if you don't want to construct an array, you can use the built-in method to do that
```go
w.GoToString("~/Path/as/a/String")
```
This function uses the `StringToPath` function to construct an array of string, and passes that to the `GoTo` function. The benefit being that the `StringToPath` function does some nifty things, like allowing relative paths to be used.

Additionally, note the `~` in both examples. A `~` denotes the root of the database for absolute paths. If you use the `GoToString` method or the `StringToPath` method, it will create an array that includes the `~`, adding it to the path even if you forget to include it.

### Inserting Values
Bolt does not support inserting values into the root of the database. So to insert a value, you must first create a bucket, then navigate your wrench into that bucket. With Wrench, this is very simple to do.
```go
w := Wrench.Wrench{}
err := w.OpenDB("File/Path.db")
// Error Handling Here
w.CreateBucket("Example")
w.GoToString("~/Example")
```
In 4 lines of code, you created a Wrench, opened the database, created a bucket and are now ready to write to that bucket.

Inserting a value is just as easy.
```go
w.Insert("key",[value as bytes])
```
Like buckets, values' keys are limited to strings when using Wrench. Their values are arrays of bytes. To convert a value to bytes, Go has built in methods.
```go
w.Insert("key",[]byte("value"))
```
This method also works with non-string values.

### Reading Values
Because of how Bolt works, the default method to read values from a bucket is to get all of them at once and sort through them. This can be done with the `GetAll` function.
```go
w.GetAll()
```

This function, along with all others that read from the database, return a DBVal object. DBVals are just things in the database. They can be either Values or Buckets. They include the `path` to the value, the `key` for that value, and the `value` itself. If a DBVal represents a bucket in the database, the `value` will be `nil`.

DBVals can be used to manipulate entries in the database, however that functionality is still under development.

If you don't want all of the values, the `GetOne` function allows you to get just the one value you're looking for.
```go
w.Get("key")
```

There are also several other `Get` functions.
```go
w.GetValues() // Returns just the non-bucket values in the current bucket
w.GetBuckets() // Returns just the buckets in the current bucket
w.GetBoth() // Returns 2 arrays, one of values and one of buckets
```

There are also function to count the values in the current bucket.
```go
w.Count() // Counts everything in the bucket
w.CountValues() // Counts the non-bucket values
w.CountBuckets() // Counts the buckets
w.CountBoth() // Returns the counts of the buckets and of the non-buckets as separate numbers
```

### Deleting Values
There are 2 commands that can be used to delete database entries.
```go
w.Delete("key")
```
The `Delete` command can delete both values and buckets, and it works exactly how you would expect.

```go
w.Empty()
```
The `Empty` command is a bit less intuitive, however it can be very useful in some circumstances. This command deletes all values and buckets in the Wrench's current location. For example, let's say your database looks like this:
```
~ [Root]
- TestBucket
- - TestVal1
- - TestVal2
```
If you point your Wrench at `~/TestBucket` and run `w.Empty()`, it will delete `~/TestBucket/TestVal1` and `~/TestBucket/TestVal2`, but `~/TestBucket` will remain in place, now empty of any values.

## Conclusion
Those are the basics of using Wrench. It's simple, but powerful. Additional functionality will likely be added in the future as I use this library in my own projects.

Among planned updates is the expansion of the `DBVal` class. I'd like to make it a more useful tool for manipulating data rather than simply reading it. The `DBVal.AsWrench()` function is a working, but unsatisfying version of this for now, which returns a new Wrench object that can then be used to manipulate data. Future versions will likely add functions to `DBVal` to update and delete the referenced entries.

repository: doytsujin/Wrench

repo_name: doytsujin/Wrench


text:
# How to add a new team member?

In the root of the project run the following command:

```bash
hugo new team/<name-surname>.md
```

Replace `<name-surname>` with the name and surname of the team member you want to add. Favor lower case names.

This will generate a `<name-surname>.md` file in the `content/team` directory.
The content of the file will look like this:

```
---
name: Candide Smith
organization: IRISA
position: PhD student
category: member
social:
  website: http://candide.github.io
  twitter: candide-smith
  linkedin: candide-smith
  github: candidesmith
---
```

## Parameters

* `name`: (**Mandatory**) Name of the team member, as it should be displayed.
* `organization`: (**Mandatory**) Current organization to which this team member belongs, for example, Inria.
* `position`: (**Mandatory**) Position the team member holds in the previous organization.
* `category`: (**Optional**) Possible values are: `member`, `alumni`, `former`. Default value is `member`.
* `social`: Social profiles for the member. All are optional.

Team member may add a photo to the website. This photo should be placed in `static/images/team`. The filename should be the same as the Markdown file containing the information about the team member and must be a `PNG` or a `JPEG` image, for example:  `candice-smith.png`. The image may have any size, but favor square dimensions, otherwise the result is unexpected.

If the team member has a Github profile, the build process will fetch its avatar. A default image will be used if there is no Github profile.

license: MIT

branch_name: refs/heads/gh-pages-edit

extension: md

gha_language: SCSS

gha_license_id: MIT

license_type: permissive


text:
# iot-thing | ESP8266 - MQTT - NTP - OTA
A gentle introduction to the Internet of Things

## Overview
This is a software library to help you quickly build a microcontroller
project with internet connectivity for control and datalogging. The library has
been developed for use with the Arduino softwre using the WeMos D1 R2 ESP8266
microcontroller.

## Features
The library wraps up a few other libraries into one neat package, so you can
focus on building your application and not worry about munging strings and
checking the time (unless that's your thing). The library combines:
* WiFi connectivity
* Over the air (OTA) updates
* MQTT messaging - multiple subscriptions, each with their own callback
* Network Time Protocol (NTP) time sync - so you don't need an RTC
* TickerScheduler - to call a number of functions at regular intervals

## Dependencies
This library requies the aforementioned libraries.

repository: jkairys/iot-thing

branch_name: refs/heads/master

repo_name: jkairys/iot-thing


text:
# Snake Game
*Snake* is simple game for Corona SDK inspired by youtube video [The Snake Game](https://www.youtube.com/watch?v=AaGK-fj-BAM).

![Screenshot](https://i.imgur.com/CNLqZYb.gif)

### Run

To run game you need install [Corona SDK](https://portal.coronalabs.com)

Controls: Arrows keys.

### License

This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/ldurniat/Snake-Game/blob/master/LICENSE) file for details.

repository: ldurniat/Snake-Game

repo_name: ldurniat/Snake-Game


text:
# SSAS query proxy

Simple ASP.NET Web API application for full .NET Framework that runs as a **proxy between client** (something that needs data from SQL Server Analysis Services (SSAS) instance) **and the SSAS instance** (the server).
When the client and the server are in the same Active Directory domain, everything works just fine. But when this is not the case, problems start to appear.
There are also different ways of connecting to SSAS - direct connection (using Windows authentication) and HTTP(S) connection with MSMDPUMP ISAPI module (using Basic authentication, maybe Windows authentication is also possible).

The main motivation was a situation with Power BI Service (as of 2019-12). If you are using SSAS independent of your AD domain (ie. hosted in Azure VM for your customers, accessed mainly through HTTPS and MSMDPUMP) and you want to publish Power BI reports to Power BI Service with automated scheduled refresh of the report data, you are screwed. Every single way of connection fails (direct from Power BI Service or through the gateway, direct to SSAS or through MSMDPUMP, using this or that authentication, import mode or DirectQuery mode, using R Script as data source, using Python script as data source, simply everything you can think of).

**That's where SSASQueryProxy comes in.**

You simply deploy it somewhere (Azure Web App, ordinary server, doesn't matter), publish it to the internet via HTTPS and use it as "web content source" in your Power BI report. You set your target server, target SSAS database, username, password and MDX query by URL parameters and/or request body. SSASQueryProxy executes ordinary ADOMD.NET command with your MDX query and returns back results as JSON data.

## Deployment to Azure Web App

Don't forget this:

* you can use the lowest available App Service plan size (F1 - free tier)
  * even this free tier allows you to use HTTPS, but only with URL provided by Azure, not with your custom domain ... which is perfectly fine for the proxy
  * originally I thought that 64bit platform would be required (and that's not available in the free tier), but it looks like that the NuGet package with ADOMD.NET client only has "amd64" in its name, but in fact doesn't require 64bit platform ... proxy works even with 32bit platform
* add item to Configuration - Application Settings named "allowedSsasServers" containing semicolon delimited list of allowed SSAS servers (probably URLs to MSMDPUMP endpoints)
* add item to Configuration - Application Settings named "SCM\_DO\_BUILD\_DURING\_DEPLOYMENT" containing "true" if you plan to perform deployment by ZIP deploy

You can use Git for deployment or you can just ZIP the repository content and upload it to ZIP deploy page in Azure Web App KUDU console. It's probably the easiest way.

If you need to troubleshoot something, just enable App Service logs - Application Logging (filesystem) and set Level to Verbose. Then go to Log stream and watch your proxy work (or not).

## Usage

### URL, parameters, authentication, output

Proxy uses following URL (when deployed to Azure Web App): https://yourwebappname.azurewebsites.net/?server=YOURSERVER&db=YOURDB&localeIdentifier=1029&applicationName=MYAPP&timeout=900

Method: POST or GET (see below)

Parameters:

* server - server hostname (probably an URL to MSMDPUMP endpoint)
* db - SSAS database name
* localeIdentifier - (optional, default 1029, which is English) locale identifier
* applicationName - (optional, default SSASQueryProxy) application identifier to distinguish your application in SSAS traces
* timeout (optional, default 120 seconds) connect timeout and also command timeout in seconds

Credentials:

* pass them with Basic authentication
* or you can use a little trick - manually construct Authorization header with value "Basic XXX" where XXX is BASE64-encoded string "username:password"
* SSAS only allows specifying username and password in the connection string for MSMDPUMP-based access, therefore if you want to pass authentication this way, you have to specify the server as an URL to MSMDPUMP endpoint; for direct connection the user under which the proxy is running will be used instead

MDX query:

* send MDX query in the request body (in that case use POST method)
* or send MDX query in `query` parameter (in that case use GET method), of course you will be limited by maximum URL length in your client software or along the way to the proxy

Output:

* JSON structure with data returned by SSAS
* could be also XML, but you have to prepare your MDX query in a way that doesn't use XML-illegal characters in field names etc (and also specify Accept: application/xml request header)

### Usage in Power BI report / Power Query

Use Web.Contents M language function, see https://docs.microsoft.com/en-us/powerquery-m/web-contents. Unfortunately there is another problem with this function (they are really trying to make this as hard as possible!). You CANNOT use the Content option to specify request body and convert the request to use the POST method IF you are using authentication. What?? You heard it right ... That's why SSASQueryProxy supports 2 methods of passing the MDX query - in the request body and also in `query` URL parameter. And that's why I mention this little trick about Authorization header above ... because you can use it to trick Power BI into thinking that the request is not authenticated (and therefore use the Content option). Crazy right?

The little trick has one disadvantage - you cannot use ordinary Power BI support for credentials, you have to store them in Power Query parameters or somewhere else.

Both ways of usage allow configuring of scheduled refresh when uploaded to Power BI Service. You then specify the credentials or Power Query parameters in dataset settings in Power BI Service.

The M language code follows. First the one with the mentioned trick:

```
Table.FromRecords(Json.Document(Web.Contents(
  "https://yourwebappname.azurewebsites.net/",
  [
    Headers = [#"Authorization" = "Basic " & Binary.ToText(Text.ToBinary(
      ParameterUsername & ":" & ParameterPassword
    ), BinaryEncoding.Base64)],
    Query = [
      server = "YOURSERVERorMSMDPUMPURL",
      db = "YOURDB",
      applicationName = "SSASQueryProxyPBI",
      localeIdentifier = "1029",
      timeout = "900"
    ],
    Content = Text.ToBinary("MDXQUERY")
  ]
)))
```

And the other with ordinary Power BI Basic authentication working, but with limited maximum MDX query length:

```
Table.FromRecords(Json.Document(Web.Contents(
  "https://yourwebappname.azurewebsites.net/",
  [
    Query = [
      server = "YOURSERVERorMSMDPUMPURL",
      db = "YOURDB",
      applicationName = "SSASQueryProxyPBI",
      localeIdentifier = "1029",
      timeout = "900",
      query = "MDXQUERY"
    ]
  ]
)))
```

## Testing from command line

While developing the proxy, you can test it from the command line with `curl`:

```
curl.exe --insecure --user "USER:PASSWORD" --data-ascii "MDXQUERY" --verbose "https://localhost:44380/?server=SERVERorHTTPMSMDPUMPURL&db=DATABASE&localeIdentifier=1029&applicationName=SSASQueryProxyDEV&timeout=900"
```

## Troubleshooting

When deploying under IIS you can see the tracing logs after adding this to `web.config` under the
`configuration` element:

```
  <system.diagnostics>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <remove name="Default" />
        <add name="Default" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\inetpub\logs\SSASQueryProxy\SSASQueryProxy.log" />
      </listeners>
    </trace>
  </system.diagnostics>
```

Don't forget to add permissions for the application pool identity user for the target directory.

repository: jmarsik/SSASQueryProxy

gha_language: C#

repo_name: jmarsik/SSASQueryProxy


text:
---
title: influxd recovery user update
description: >
  The `influxd recovery user update` command lets you change your password if you forget your credentials.
menu:
  influxdb_2_4_ref:
    parent: influxd recovery user
weight: 401
---

Use `influxd recovery user update` to update a password. Useful when you forget your username and need to update your credentials. To retrieve all usernames in the system, use [`influxd recovery user list`](/influxdb/v2.4/reference/cli/influxd/recovery/user/list/) or use [`influxd recovery user create`](/influxdb/v2.4/reference/cli/influxd/recovery/user/create/) to create new user for recovery purposes.

{{% note %}}
This command can only be executed when the InfluxDB server (`influxd`) is not running.
{{% /note %}}

## Usage
```sh
influxd recovery user update [flags]
```

## Flags
| Flag |                      | Description                                                   | Input Type |
| :--- | :------------------- | :------------------------------------------------------------ | :--------: |
|      | `--bolt-path`        | Path to the BoltDB file (default `~.influxdbv2/influxd.bolt`) |   string   |
| `-h` | `--help`             | Help for `update`                                             |            |
|      | `--id` or `username` | Enter the ID or name for an existing user                     |   string   |
|      | `--password`         | New password for the specified user                           |   string   |

## Examples

##### Update a user password

```sh
influxd recovery user update \
  --username example-username \
  --password ExAmPL3-paS5W0rD
```


text:
# AKS Voting App - App Component (1.0)

## Overview

Provides the `app` component for the Azure Voting App. This is a web ui that allows users to vote for one of the two categories and observe the results.

## Dependencies

Version `1.x` of this component leverages a `Redis` backend for storage and version `1.x` of the `analytics` component to provide voting analytics.

## Configuration

The app component can be configured via the following environment variables:

|Environment Variable  |Default Value      |Description                                                                |
|----------------------|-------------------|---------------------------------------------------------------------------|
|PORT                  | 8080              | The port that the app component web ui is exposed on.                     |
|TITLE                 | AKS Voting App    | The title displayed by the web ui.                                        |
|VOTE1VALUE            | Cats              | The value of the 1st voting category.                                     |
|VOTE2VALUE            | Dogs              | The value of the 2nd voting category.                                     |
|SHOWDETAILS           | false             | A switch to display the container/pod name and the storage (Redis/MySQL). |
|FEATUREFLAG           | false             | A switch to enable feature flag capabilities.                             |
|REDIS_HOST            | voting-storage    | The host name of the Redis instance.                                      |
|REDIS_PORT            | 6379              | The port that the Redis instance is exposed on.                           |
|ANALYTICS_HOST        | voting-analytics  | The host name of the analytics component.                                 |
|ANALYTICS_PORT        | 8080              | The port that the analytics component is exposed on.                      |

## Docker image

This component is available as a Docker image via:

- mcr.microsoft.com/aks/samples/voting/app:1.0

## Build Dockerfile

Powershell

```powershell
PS> docker build --no-cache --build-arg IMAGE_VERSION="1.0" --build-arg IMAGE_CREATE_DATE="$(Get-Date((Get-Date).ToUniversalTime()) -UFormat '%Y-%m-%dT%H:%M:%SZ')" --build-arg IMAGE_SOURCE_REVISION="$(git rev-parse HEAD)" -f Dockerfile -t "mcr.microsoft.com/aks/samples/voting/app:1.0" .
```

Bash

```bash
$ docker build --no-cache --build-arg IMAGE_VERSION="1.0" --build-arg IMAGE_CREATE_DATE="`date -u +"%Y-%m-%dT%H:%M:%SZ"`" --build-arg IMAGE_SOURCE_REVISION="`git rev-parse HEAD`" -f Dockerfile -t "mcr.microsoft.com/aks/samples/voting/app:1.0" .
```

repository: afrozquadri/aks-voting-app

repo_name: afrozquadri/aks-voting-app


text:
# multi tenant configuration file

Orchard Core Framework (OCF) support multi-tenancy via url, either by host or prefix. This sample shows how OCF provides the infrastructure for each tenant to have its own configuration file.

The tenants are configured at `App_Data/tenants.json`. Additional tenant specific configuration information can be found at `App_Data/Sites/{TenantName}/appSettings.json`.

All these information is accessible via `OrchardCore.Environment.Shell.ShellSettings`.

repository: dodyg/practical-aspnetcore

repo_name: dodyg/practical-aspnetcore


text:
# Deep Video Deblurring for Hand-held Cameras
This is a third-party tensorflow implemention for [Deep Video Deblurring for Hand-held Cameras](https://github.com/shuochsu/DeepVideoDeblurring).

Since the code is not well implemented and the other files are lost, sorry that no further support will be provided.

### Citation
If you find this code useful for your research, please cite:
```
@inproceedings{su2017deep,
  title={Deep Video Deblurring for Hand-held Cameras},
  author={Su, Shuochen and Delbracio, Mauricio and Wang, Jue and Sapiro, Guillermo and Heidrich, Wolfgang and Wang, Oliver},
  booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition},
  pages={1279--1288},
  year={2017}
}
```

repository: chengzhag/DeepVideoDeblurring

repo_name: chengzhag/DeepVideoDeblurring


text:
# Snapshot Isolation
This implementation is used for analyzing base line of ERMIA(/SSN/latch-free SSN).

So some parts is like ERMIA in implementation, configuration, and design to analyze concurrency controls deeply.

## How to use
- Build masstree
```
$ cd ../
$ ./bootstrap.sh
```
This makes ../third_party/masstree/libkohler_masstree_json.a used by building si.
- Build mimalloc
```
$ cd ../
$ ./bootstrap_mimalloc.sh
```
This makes ../third_party/mimalloc/out/release/libmimalloc.a used by building si.
- Build
```
$ mkdir build
$ cd build
$ cmake -G Ninja -DCMAKE_BUILD_TYPE=Release ..
$ ninja
```
- Confirm usage
```
$ ./si.exe
```
- Execution example
```
$ numactl --interleave=all ./si.exe 1000 10 224 100 off 0 off 2100 10 100 0 3
```

## How to customize options in CMakeLists.txt
- `ADD_ANALYSIS` : If this is 1, it is deeper analysis than setting 0.

default : `0`
- `BACK_OFF` : If this is 1, it use Cicada's backoff.

default : `0`
- `KEY_SORT` : If this is 1, its transaction accesses records in ascending key order.

default : `0`
- `MASSTREE_USE` : If this is 1, it use masstree as data structure. If not, it use simple array αs data structure.
default : `1`
- `VAL_SIZE` : Value of key-value size. In other words, payload size.

default : `4`
- CFLAGS
 - Use either `-DCCTR_ON` or `-DCCTR_TW`. These meanings is described below in section **Details of Implementation**.

## Custom build examples
```
$ cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DKEY_SIZE=1000 -DVAL_SIZE=1000 ..
```
- Note: If you re-run cmake, don't forget to remove cmake cache.
```
$ rm CMakeCache.txt
```
The cmake cache definition data is used in preference to the command line definition data.

## Optimizations
- Rapid garbage collection from Cicada's paper.
- Cicada's backoff (easy to use from ccbench/include/backoff.hh by a few restriction)
- Mitigate contentions for centralized counter.

## Detail of Implementation
 This protocol follow two rules.
 1. Read operation reads the committed version which was latest at beginning of the transaction.
 2. First Updater (Committer) Wins Rule.

First Updater (Commiter) Wins Rule enforces that when two or more transactions execute a write operation on the same record, the lifetimes of those transactions do not overlap.

Normally this protocol gets a unique value from the shared counter at the start of the transaction and at the end of the transaction.
However, touching the shared counter twice in lifetime of transaction causes very high contention for the counter and degrading performance.

Author (tanabe) gives two selection which are able to be defined at Makefile.
 1. `-DCCTR_TW` means "Centralized counter is touched twice in the lifetime(begin/end) of transaction." It is normally technique.
 2. `-DCCTR_ON` means "Centralized counter is touched once in the lifetime of transaction." It is special technique. Counting up of shared counter only happen when a transaction commits. Instead of getting the count from the shared counter at the start of the transaction, get the latest commit timestamps of all the worker threads via the transaction mapping table. The element of the table may be refered by multiple concurrent worker thread. So getting and updating information are done by CAS. This technique reduces contentions for shared counter but increases overhead of memory management.

Author observed that author's technique `-DCCTR_ON` was better than `-DCCTR_TW` in some YCSB-A,C. Because the major bottleneck of performance generally is not memory management, but centralized counter. the author's technique is reducing cost about centralized counter and increasing memory management cost. Generally it contributes to improve performance. So normally it is better to set `-DCCTR_ON`.

gha_language: Shell


text:
# _Meal Tracker_

#### _Angular 2 app for tracking meals eaten_

#### By _**Lina Shadrach**_

## Description.
_This app allows the user to make a list of the meals that they have eaten throughout a day. For each meal, the user can specify what food groups it satisfied, the amount that was ingested of each food group, whether the meal was processed, and the time that the meal was eaten._

## Prerequisites

You will need the following things properly installed on your computer.

* [Git](https://git-scm.com/)
* [Node.js](https://nodejs.org/) (with NPM)
* [Bower](https://bower.io/)
* [Angular](https://angularjs.org/)

## Installation

* `git clone <https://github.com/LinaShadrach/meal-tracker-angular.git>`
* `cd meal-tracker-angular`
* `npm install`
* `bower install`

## Running / Development

* `gulp serve`
* Visit app at [http://localhost:3000](http://localhost:3000).

### Building

* `gulp build`

## Known Bugs

_None known._

## Support and contact details
_Please contact author through GitHub at username: LinaShadrach_

## Technologies and Resources used
_Angular 2, Bower, Bootstrap, CSS, GitHub, HTML, Javascript, Node.js, Typescript_

### License
_MIT_
  Copyright(c) 2016 ***Lina Shadrach***

repository: LinaShadrach/meal-tracker-angular

repo_name: LinaShadrach/meal-tracker-angular


text:
---
layout: page
title: Desert Gold Peach
---

This very vigorous and heavy-bearing tree offers fruit with exceptionally good flavor and sweetness for such an early variety. Its medium-sized semi-freestone fruit has firm yellow flesh and yellow skin with a red blush. Fragrant pink flowers adorn the green foliage on this self-fruiting tree. Tolerates heat and humidity. Requires 250 chill hours. Edible Fruit. Bird Friendly. Edible. Showy Fruit.

          Size

264.0" W X 264.0" H

          Type

Deciduous Tree

          Flower Color

Pink

          Foliage Color

Green

          Lighting

Full sun

    Discover More Plants Like This

repository: LastZactionHero/bloom-landing

repo_name: LastZactionHero/bloom-landing


text:
---
title: History
description: Contains history entry object description and API calls to interact with it.
---

# History

Contains history entry object description and API calls to interact with it.

## Tracker history entry

```json
{
    "id": 1,
    "type": "tracker",
    "is_read": false,
    "message": "Alarm",
    "time": "2020-01-01 00:00:00",
    "event": "offline",
    "tracker_id": 2,
    "rule_id": 3,
    "track_id": 4,
    "location":{
        "lat": 50.0,
        "lng": 60.0,
        "precision": 50
    },
    "address": "address",
    "extra": {
        "task_id": null ,
        "parent_task_id": null,
        "counter_id": null,
        "service_task_id": null,
        "checkin_id": null,
        "place_ids": null,
        "last_known_location": false,
        "tracker_label": "Tracker label",
        "emergency": false
    }
}
```

* `id` - int. An id of event.
* `type` - [enum](../../../getting-started.md#data-types). Type of device. Can be "socket", "tracker", or "camera".
* `is_read` - boolean. If `true` the notification seen by user and marked as read.
* `message` - string. Notification message.
* `time` - [date/time](../../../getting-started.md#data-types). When this notification received.
* `event` - [enum](../../../getting-started.md#data-types). Type of history event extension. Available event types can be obtained by [/history/type/list](./history_type.md#list) action.
* `tracker_id` - int. An id of the tracker (aka "object_id"). Tracker must belong to authorized user and not be blocked.
* `rule_id` - int. An id of assigned rule.
* `track_id` - int. An id of a track on which the event happened.
* `location` - location object. Location where the event happened.
* `address` - string. Address of location or `""` (empty string) if no address for location.
* `extra` - object. Extra fields for events. Like for what task or tracker the event was.
    * `task_id` - int. Related task identifier.
    * `parent_task_id` - int. Related parent task identifier (for task checkpoint related history entries).
    * `counter_id` - int. Related counter identifier.
    * `service_task_id` - int. Related service task id.
    * `checkin_id` - int. Related check-in marker.
    * `place_ids` - int. Related place identifiers.
    * `last_known_location` - boolean. `true` if location may be outdated.
    * `tracker_label` - string. Tracker label.
    * `emergency` - boolean. `true` for emergency events with the same flag in a rule.

Date/time type described in [data types description section](../../../getting-started.md#data-types).

## API actions

API path: `/history`.

### read

Returns history entry with the specified id.

#### parameters

| name | description | type |
| :--- | :--- | :--- |
| id | [History entry](#tracker-history-entry) ID. | int |
| add_tracker_label | Optional. If `true` tracker label will be added to message. | boolean |

#### examples

=== "cURL"

    ```shell
    curl -X POST '{{ extra.api_example_url }}/history/read' \
        -H 'Content-Type: application/json' \
        -d '{"hash": "22eac1c27af4be7b9d04da2ce1af111b", "id": 11231, "add_tracker_label": true}'
    ```

=== "HTTP GET"

    ```
    {{ extra.api_example_url }}/history/read?hash=a6aa75587e5c59c32d347da438505fc3&id=11231&add_tracker_label=true
    ```

#### response

```json
{
    "success": true,
    "value": {
         "id": 1,
         "type": "tracker",
         "is_read": false,
         "message": "Alarm",
         "time": "2020-01-01 00:00:00",
         "event": "offline",
         "tracker_id": 2,
         "rule_id": 3,
         "track_id": 4,
         "location":{
             "lat": 50.0,
             "lng": 60.0,
             "precision": 50
         },
         "address": "address",
         "extra": {
             "task_id": null ,
             "parent_task_id": null,
             "counter_id": null,
             "service_task_id": null,
             "checkin_id": null,
             "place_ids": null,
             "last_known_location": false,
             "tracker_label": "Tracker label",
             "emergency": false
         }
    }
}
```

#### errors

* 201 – Not found in the database - when there are no history entries with that id.

### mark_read

Marks history entry as read by `id` (see: [Tracker history entry](#tracker-history-entry)).

#### parameters

| name | description | type |
| :--- | :--- | :--- |
| id | [Tracker history entry](#tracker-history-entry) ID | int |

#### examples

=== "cURL"

    ```shell
    curl -X POST '{{ extra.api_example_url }}/history/mark_read' \
        -H 'Content-Type: application/json' \
        -d '{"hash": "22eac1c27af4be7b9d04da2ce1af111b", "id": 11231}'
    ```

=== "HTTP GET"

    ```
    {{ extra.api_example_url }}/history/mark_read?hash=a6aa75587e5c59c32d347da438505fc3&id=11231
    ```

#### response

```json
{ "success": true }
```

#### errors

* 201 – Not found in the database - when there are no history entries with that id.

### mark_read_all

Marks all the user's history entries read.

#### parameters

Only session `hash`.

#### examples

=== "cURL"

    ```shell
    curl -X POST '{{ extra.api_example_url }}/history/mark_read_all' \
        -H 'Content-Type: application/json' \
        -d '{"hash": "22eac1c27af4be7b9d04da2ce1af111b"}'
    ```

=== "HTTP GET"

    ```
    {{ extra.api_example_url }}/history/mark_read_all?hash=a6aa75587e5c59c32d347da438505fc3
    ```

#### response

```json
{ "success": true }
```

#### errors

* [General](../../../getting-started.md#error-codes) types only.


text:
---
title: Client-Based HAWQ Load Tools
---

HAWQ supports data loading from Red Hat Enterprise Linux 5, 6, and 7 and Windows XP client systems. HAWQ Load Tools include both a loader program and a parallel file distribution program.

This topic presents the instructions to install the HAWQ Load Tools on your client machine. It also includes the information necessary to configure HAWQ databases to accept remote client connections.

## RHEL Load Tools

The RHEL Load Tools are provided in a HAWQ distribution.

### Installing the RHEL Loader

1. Download a HAWQ installer package or build HAWQ from source.

2. Refer to the HAWQ command line install instructions to set up your package repositories and install the HAWQ binary.

3. Install the `libevent` and `libyaml` packages. These libraries are required by the HAWQ file server. You must have superuser privileges on the system.

    ``` shell
    $ sudo yum install -y libevent libyaml
    ```

### About the RHEL Loader Installation

The files/directories of interest in a HAWQ RHEL Load Tools installation include:

`bin/` — data loading command-line tools ([gpfdist](../../reference/cli/admin_utilities/gpfdist.html) and [hawq load](../../reference/cli/admin_utilities/hawqload/index.html))
`greenplum_path.sh` — environment set up file

### Configuring the RHEL Load Environment

A `greenplum_path.sh` file is located in the HAWQ base install directory following installation. Source `greenplum_path.sh` before running the HAWQ RHEL Load Tools to set up your HAWQ environment:

``` shell
$ . /usr/local/hawq/greenplum_path.sh
```

Continue to [Using the HAWQ File Server (gpfdist)](g-using-the-hawq-file-server--gpfdist-/index.html) for specific information about using the HAWQ load tools.

## Windows Load Tools

### Installing Python 2.5
The HAWQ Load Tools for Windows requires that the 32-bit version of Python 2.5 be installed on your system.

**Note**: The 64-bit version of Python is **not** compatible with the HAWQ Load Tools for Windows.

1. Download the [Python 2.5 installer for Windows](https://www.python.org/downloads/).  Make note of the directory to which it was downloaded.

2. Double-click on the `python Load Tools for Windows-2.5.x.msi` package to launch the installer.
3. Select **Install for all users** and click **Next**.
4. The default Python install location is `C:\Pythonxx`. Click **Up** or **New** to choose another location. Click **Next**.
5. Click **Next** to install the selected Python components.
6. Click **Finish** to complete the Python installation.

### Running the Windows Installer

1. Download the `greenplum-loaders-4.3.x.x-build-n-WinXP-x86_32.msi` installer package from [Pivotal Network](https://network.pivotal.io/products/pivotal-gpdb). Make note of the directory to which it was downloaded.

2. Double-click the `greenplum-loaders-4.3.x.x-build-n-WinXP-x86_32.msi` file to launch the installer.
3. Click **Next** on the **Welcome** screen.
4. Click **I Agree** on the **License Agreement** screen.
5. The default install location for HAWQ Loader Tools for Windows is `C:\"Program Files (x86)"\Greenplum\greenplum-loaders-<IP_ADDRESS>-build-1`. Click **Browse** to choose another location.
6. Click **Next**.
7. Click **Install** to begin the installation.
8. Click **Finish** to exit the installer.

### About the Windows Loader Installation
Your HAWQ Windows Load Tools installation includes the following files and directories:

`bin/` — data loading command-line tools ([gpfdist](http://gpdb.docs.pivotal.io/4380/client_tool_guides/load/unix/gpfdist.html) and [gpload](http://gpdb.docs.pivotal.io/4380/client_tool_guides/load/unix/gpload/index.html))
`lib/` — data loading library files
`greenplum_loaders_path.bat` — environment set up file

### Configuring the Windows Load Environment

A `greenplum_loaders_path.bat` file is provided in your load tools base install directory following installation. This file sets the following environment variables:

- `GPHOME_LOADERS` - base directory of loader installation
- `PATH` - adds the loader and component program directories
- `PYTHONPATH` - adds component library directories

Execute `greenplum_loaders_path.bat` to set up your HAWQ environment before running the HAWQ Windows Load Tools.

## Enabling Remote Client Connections
The HAWQ master database must be configured to accept remote client connections.  Specifically, you need to identify the client hosts and database users that will be connecting to the HAWQ database.

1. Ensure that the HAWQ database master `pg_hba.conf` file is correctly configured to allow connections from the desired users operating on the desired database from the desired hosts, using the authentication method you choose. For details, see [Configuring Client Access](../../clientaccess/client_auth.html#topic2).

    Make sure the authentication method you choose is supported by the client tool you are using.

2. If you edited the `pg_hba.conf` file, reload the server configuration. If you have any active database connections, you must include the `-M fast` option in the `hawq stop` command:

    ``` shell
    $ hawq stop cluster -u [-M fast]
    ```

3. Verify and/or configure the databases and roles you are using to connect, and that the roles have the correct privileges to the database objects.

repository: dyozie/mkdocs-book-hdb

repo_name: dyozie/mkdocs-book-hdb


text:
<!--title={Add Two Numbers: The Intuition}-->

The key to solving the problem is making sure to keep track of the carry using a variable and simulate digits-by-digits sum starting from the head of list, which contains the least-significant digit.

![](../images/ATN_2.svg)

In the above example, we visualize the addition of two numbers: 342 + 465 = 807. Each node contains a single digit and the digits are stored in reverse order.

repository: ShayanRiyaz/curriculum

repo_name: ShayanRiyaz/curriculum


text:
# Level 2 : Ducky
![level2_ducky](../images/level2_ducky.png)

## Description

Munchman Ducky is a SuperMicro (<$75) cluster fighter.  This cluster has two computing components a [Raspberry Pi
Zero W](https://www.raspberrypi.org/products/raspberry-pi-zero-w/) ($10) and a Lattice [iCE40-HX8K Breakout
Board](http://www.latticesemi.com/en/Products/DevelopmentBoardsAndKits/iCE40HX8KBreakoutBoard) ($49).  The
communication between the boards will use USB2.0.  I plan to use the Open Source
[Icestorm](http://www.clifford.at/icestorm/) tools for the iCE40 FPGA development.

## Development

Here is the outline of the development plan.

1.  **Loopback Test**:
- Instantiate a uart in Verilog and verify in simulation.  The uart I am using is from [fpga4fun.com](https://www.fpga4fun.com/SerialInterface4.html).
- Instantiate transmit and receive in the FPGA as a loopback test.
- Write code on the PC to send data over the USB to the FPGA.
- Verify can send and receive data.
- Figure out max datarate data can be sent and received.

2. **MD5 core**: Write or find a MD5Core and testbench...

3. Integration and app development.

## Simulation

Using [Icarus Verilog (a.k.a iverilog)](http://iverilog.icarus.com/) and
[GTKWave](http://gtkwave.sourceforge.net/) for simulation.
I used apt-get to install gtkwave.
I compiled iverilog from source using the [github repo](https://github.com/steveicarus/iverilog).
I compiled from source because the version in the Ubuntu 16.04 apt-get
did not compile the async.v source. It gave a message about unsupported "static functions".
The latest version in github does not have this problem.
The instruction for compiling iverilog is [here](http://iverilog.wikia.com/wiki/Installation_Guide).
Here is a summary of the commands I used to compile iverilog on Ubuntu 16.04.

```
$ sudo apt-get install gperf libreadline-dev valgrind
$ git clone git@github.com:steveicarus/iverilog.git
$ cd iverilog
$ sh autoconf.sh
$ ./configure --with-valgrind
$ make
$ sudo make install
```

There are other prerequisites packages you may need to install.  Check the github repo readme.  Also you
can uninstall if you are in the iverilog directory via

```
$ cd iverilog
$ sudo make uninstall
```

## FTDI library

I compiled [libftdi](https://www.intra2net.com/en/developer/libftdi/) from source. I got the source via

```
$ git clone git://developer.intra2net.com/libftdi
```

Build instructions in the README and README.build

repository: ClusterFights/MunchMan

repo_name: ClusterFights/MunchMan


text:
+++
title = "Working with Arrays"
weight = 2
+++

In order to work with arrays you need follow these steps.

 * Declare a variable to reference the array object.
 * Create a new array object.
 * Assign the reference of the array object to the array variable.
 * Store information in the newly created array.

## Declaring Array Variables

Before you start working with an array, you need to create a variable that
can store a reference to the array object.

Here is the general form of an array variable declaration statement.
```
type[] identifier;
```

Here, the `type` indicates the type of elements stored in the array. You can
name the variable with any valid identifier.

The square brackets serve two purpose.

 * They help you differentiate your array variable from regular variable declarations.

 * The square brackets actually indictae the dimension of the array. When you
   write a single pair it indicates one dimensional array. Similarly, when you
   write two pairs they indicate two dimensional array, and so on. You will learn
   about array dimensions later in this chapter.

Optionally, you can write the square brackets after the identifier. The position
of the brackets does not matter unless you declare multiple variables in the same
statement. If you place the brackets after the type and before any identifier,
the brackets apply to all the variables. Similarly, if you place the brackets
after an identifier, the brackets apply only to that variable.

We recommend you to stay away from declaring multiple variables in the same
statement. This makes your code less readable.

Here is an example of array variable declarations.
```
String[] names;
Object objects[];
int[] marks;
Student students[];
```

## Creating Array Objects

After you declare the array variable, you need to create an array object and
assign its reference to the variable. Unlike other objects, arrays can be created
in two different ways. The first technique is to use an array initializer and
the other is to use the new operator.

An array has a fixed length that is set when your create it. You cannot change
the length of an array after you create it. You can determine the length of an
array by using the length field of an array object.

### Using Array Initializer

An array initializer is a list of expressions, separated by commas. The list
of expressions is enclosed within braces. The commas separate the values of the
array elements. The array will be large enough to hold the number of elements you
specify in the array initializer.

With this technique, you don't have to use the new operator. However, you can
use this syntax only with the array variable declaration statement.

The general syntax of an array initializer is shown here.
```
type[] identifier = {
    expression1,
    expression2,
    ...,
    expressionN
};
```

The main advantage of this technique is, when you know the initial values
of your array you don't have to write multiple statements for allocating and
initializing your array.

For example, to store the days of the week you would create an array like this.
```
public class DaysOfWeek {

    public static void main(String ... arguments) {
        String[] daysOfWeek = {
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
        };
        System.out.println("The second day of the week is " + daysOfWeek[1]);
    }
}
```

In this example, you create an array of String. It consists of the days in a
week. A print statement prints the second day of the week. Notice that we used
`1` as the index to access "Monday". This is because array indexes start from
zero.

## Using the New Operator to Allocate Array Objects

Arrays are objects in Java. Therefore, you can use the new operator to create a
new instance of an array. However, the syntax of the new operator is bit different
when you allocate an array.

Here is the general syntax of the new operator when allocating an array.
```
new type[size]
```

Here, the type indicates the component type of the array.

The `size` indicates the capacity of the array, that is, the number of elements
it can store.

Here is an example of allocating an array capable of storing 7 object references.
```
Object[] objects = new Object[7];
```
In this example, the declaration and allocation is combined in the same statement.
It allocates an array with 7 slots, where you can store seven references.

When you create an array object using the new operator, you are basically
creating empty slots where you can store references to objects. You should
remember that allocating an array does not allocate objects in the slots. You
must manually allocate objects and store their references in the array later.

In fact, when you create an array with a reference component type, Java
automatically initializes the slots to null reference. The keyword null refers
to a null object and can be used stored in any reference variable. Unlike C and
C++, the null reference is not equivalent to 0 or the null character (`\0`).

Here is another example of allocating an array that can store integers.
```
int marks[] = new int[10];
```
When you create an array with a primitive component type, Java automatically
initializes the slots to `0` for numeric types, `\0` (null character) for
the character type, and `false` for the boolean type.

An array size can be zero or more. If you specify a negative size, Java throws
the `NegativeArraySizeException`.

Here is an example of allocating a negative sized array.
```
public class NegativeArraySizeDemo {

    public static void main(String ... arguments) {
        String[] daysOfWeek = new String[-1];
    }
}
```

When you run this example, Java throws an exception like this.
```
Exception in thread "main" java.lang.NegativeArraySizeException: -1
        at NegativeArraySizeDemo.main(NegativeArraySizeDemo.java:4)
```

## Initializing Array Objects

Because each slot in an array contains a default value when you create it, you
must assign a value to each slot before using it.

Once you have allocated an array, you can access a specific element in the array
using the index enclosed in square brackets, known as the subscript operator.
An index starts at zero and extend to `n - 1`, where `n` is the size of the array.

Here is the general form of accessing an element in an array using the subscript
operator.
```
identifier[index]
```

The identifier represents the name of the array variable. The index indicates
the element slot which you want to access.

Here is an example which creates an array of three integers and assigns their
respective slots.

```
int[] marks = new int[3];
marks[0] = 40;
marks[1] = 63;
marks[2] = 55;
```

Here is another version of the days of the week program we saw earlier.
```
public class DaysOfWeek {

    public static void main(String ... arguments) {
        String[] daysOfWeek = new String[7];
        daysOfWeek[0] = "Sunday";
        daysOfWeek[1] = "Monday";
        daysOfWeek[2] = "Tuesday";
        daysOfWeek[3] = "Wednesday";
        daysOfWeek[4] = "Thursday";
        daysOfWeek[5] = "Friday";
        daysOfWeek[6] = "Saturday";
        System.out.println("The fourth day of the week is " + daysOfWeek[3]);
    }
}
```

In this example, you create an array of String. It consists of the days in a
week. The array is manually initialized by assigning each slot. A print statement
prints the fourth day of the week. Notice that we used `3` as the index to access
"Wednesday". This is because array indexes start from zero.

## Accessing Array Elements

After you have an array with initial values, you can read, modify, and test the
values in each slot. The value in a slot is accessed using the subscript operator.
You can write expressions like this using the subscript operator.
```
array[index] = value;
```

Whenever you try to access an element with an index, Java makes sure that you
are specifying a valid index. The index should always be greater than or equal
to zero and lesser than the size of the array, known as the arrays boundaries.
Unlike C and C++, in Java you cannot access a slot outside the array's boundaries.
In case you try to access an element outside the arrays boundaries, Java
throws `ArrayIndexOutOfBoundsException`.

Here is an example which triggers an `ArrayIndexOutOfBoundsException`.
```
public class InvalidDayOfWeek {

    public static void main(String... arguments) {
        String[] daysOfWeek = new String[7];
        daysOfWeek[0] = "Sunday";
        daysOfWeek[1] = "Monday";
        daysOfWeek[2] = "Tuesday";
        daysOfWeek[3] = "Wednesday";
        daysOfWeek[4] = "Thursday";
        daysOfWeek[5] = "Friday";
        daysOfWeek[6] = "Saturday";
        System.out.println("The seventh day of the week is " + daysOfWeek[7]);
    }
}
```

This example produces the following output.

```
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7
        at InvalidDayOfWeek.main(InvalidDayOfWeek.java:12)
```

Since the size of the array is 7, the last valid index is 6. In this example,
the program tried to access the slot at index 7, which is invalid index.
This is why Java throws an `ArrayIndexOutOfBoundsException`.

Every array object exposes a field called `length`. You can use this to determine
the size of an array. Note that this field is immutable, which means you cannot
modify it without making your compiler grumpy.

## Combining Array Allocation and Initializer

You cannot directly use the array initializer in an expression outside a variable
declaration statement. However, you can combine array allocation and initializer
in any expression.

Here is the general syntax which allows you to combine array allocation and
array initializer.

```
new type[] {
    expression1,
    expression2,
    ...
    expressionN
}
```

Here, you do not have to specify the number of elements in your array. Therefore,
you can leave the square brackets empty. The list of expressions enclosed by
the braces consist of the values which are assigned to the slots. You must
separate each expression with a comma.

Here is an example of this technique.
```
new int[] { 10, 20, 30, 40, 50 }
```

repository: itssamuelrowe/binarystars

repo_name: itssamuelrowe/binarystars


text:
Calculates A1000 final classification based on A1000 classification and A1000 full reports.

## Script Data
---

| **Name** | **Description** |
| --- | --- |
| Script Type | python3 |
| Cortex XSOAR Version | 6.0.0 |

## Inputs
---

| **Argument Name** | **Description** |
| --- | --- |
| a1000_classification_report | A1000 classification report |
| a1000_full_report | A1000 full report |

## Outputs
---

| **Path** | **Description** | **Type** |
| --- | --- | --- |
| File.SHA256 | The SHA256 hash of the file. | String |
| File.SHA1 | The SHA1 hash of the file. | String |
| File.SHA512 | The SHA512 hash of the file. | String |
| File.Name | The name of the file. | String |
| File.EntryID | The Entry ID. | String |
| File.Info | Information about the file. | String |
| File.Type | The type of the file. | String |
| File.MD5 | MD5 hash of the file. | String |
| DBotScore.Score | The actual score. | Number |
| DBotScore.Type | The indicator type. | String |
| DBotScore.Indicator | The indicator that was tested. | String |
| DBotScore.Vendor | The vendor used to calculate the score. | String |

repository: demisto/content

gha_language: Python

repo_name: demisto/content


text:
---
title: intercept
---

Use `cy.intercept()` to manage the behavior of HTTP requests at the network layer.

With `cy.intercept()`, you can:

- stub or spy on any type of HTTP request.
  - If `cy.intercept()` provides a response object, or a fixture, or calls `req.reply()` then the request will NOT go to the server, and instead will be mocked from the test.
  - Otherwise the request will go out to the server, and the test spies on the network call. The spying intercept can even modify the real response from the server before it is returned to the web application under test.
- [modify an HTTP request's body, headers, and URL](#Intercepting-a-request) before it is sent to the destination server.
- stub the response to an HTTP request, either dynamically or statically.
- [modify real HTTP responses](#Intercepting-a-response), changing the body, headers, or HTTP status code before they are received by the browser.
- and much more - `cy.intercept()` gives full access to all HTTP requests at all stages.

## Comparison to `cy.route()`

Unlike [cy.route()](/api/commands/route), `cy.intercept()`:

- can intercept all types of network requests including Fetch API, page loads, XMLHttpRequests, resource loads, etc.
- does not require calling [cy.server()](/api/commands/server) before use - in fact, `cy.server()` does not influence `cy.intercept()` at all.
- does not have method set to `GET` by default, but intercepts `*` methods.

## Usage

```ts
cy.intercept(url, routeHandler?)
cy.intercept(method, url, routeHandler?)
cy.intercept(routeMatcher, routeHandler?)
cy.intercept(url, routeMatcher, routeHandler)
```

**Note:** all intercepts are automatically cleared before every test.

### Arguments

#### **<Icon name="angle-right"></Icon> url** **_(`string | RegExp`)_**

Specify the URL to match. See the examples for [Matching URL](#Matching-URL) to see how URLs are matched.

```ts
cy.intercept('http://example.com/widgets')
cy.intercept('http://example.com/widgets', { fixture: 'widgets.json' })
```

#### **<Icon name="angle-right"></Icon> method** **_(`string`)_**

Specify the HTTP method to match on.

```ts
cy.intercept('POST', 'http://example.com/widgets', {
  statusCode: 200,
  body: 'it worked!',
})
```

#### **<Icon name="angle-right"></Icon> routeMatcher** **_(`RouteMatcher`)_**

`routeMatcher` is an object used to match which incoming HTTP requests will be handled by this route.

All properties are optional. All properties that are set must match for the route to handle a request. If a `string` is passed to any property, it will be glob-matched against the request using [`minimatch`](https://github.com/isaacs/minimatch).The available `routeMatcher` properties are listed below:

```ts
{
  /**
   * Match against the username and password used in HTTP Basic authentication.
   */
  auth?: { username: string | RegExp, password: string | RegExp }
  /**
   * Match against HTTP headers on the request.
   */
  headers?: {
    [name: string]: string | RegExp
  }
  /**
   * Match against the requested HTTP hostname.
   */
  hostname?: string | RegExp
  /**
   * If 'true', only HTTPS requests will be matched.
   * If 'false', only HTTP requests will be matched.
   */
  https?: boolean
  /**
   * Match against the request's HTTP method.
   * @default '*'
   */
  method?: string | RegExp
  /**
   * If `true`, this will pass the request on to the next `RouteMatcher` after the request handler completes.
   * Can only be used with a dynamic request handler.
   * @default false
   */
  middleware?: boolean
  /**
   * Match on request path after the hostname, including query params.
   */
  path?: string | RegExp
  /**
   * Matches like 'path', but without query params.
   */
  pathname?: string | RegExp
  /**
   * Match based on requested port, or pass an array of ports
   * to match against any in that array.
   */
  port?: number | number[]
  /**
   * Match on parsed querystring parameters.
   */
  query?: {
    [key: string]: string | RegExp
  }
  /**
   * Match against the full request URL.
   */
  url?: string | RegExp
}
```

`routeMatcher` usage examples:

```ts
cy.intercept({
  pathname: '/search',
  query: {
    q: 'some terms',
  },
}).as('searchForTerms')
// this 'cy.wait' will only resolve once a request is made to '/search'
// with the query paramater 'q=some+terms'
cy.wait('@searchForTerms')

cy.intercept(
  {
    // this RegExp matches any URL beginning with 'http://api.example.com/widgets'
    url: /^http:\/\/api\.example\.com\/widgets/,
    headers: {
      'x-requested-with': 'exampleClient',
    },
  },
  (req) => {
    // only requests to URLs starting with 'http://api.example.com/widgets'
    // having the header 'x-requested-with: exampleClient' will be received
  }
})

// in this example, the supplied URL `/users` is merged with the RouteMatcher
// passed as the second argument
cy.intercept('/users', { middleware: true }, (req) => {
  req.headers['authorization'] = `Bearer ${bearerToken}`
})
```

#### <Icon name="angle-right"></Icon> routeHandler (string | object | Function | [StaticResponse][staticresponse])

The `routeHandler` defines what will happen with a request if the [routeMatcher](#routeMatcher-RouteMatcher) matches. It can be used to [statically define a response](#Stubbing-a-response) for matching requests, or a function can be passed to [dynamically intercept the outgoing request](#Intercepting-a-request).

- If a **string** is passed, requests to the route will be fulfilled with that string as the body. Passing `"foo"` is equivalent to using a [`StaticResponse`][staticresponse] object with `{ body: "foo" }`.
- If a **[`StaticResponse`][staticresponse] object** is passed, requests to the route will be fulfilled with a response using the values supplied in the `StaticResponse`. A `StaticResponse` can define the body of the response, as well as the headers, HTTP status code, and more. See [Stubbing a response with a `StaticResponse` object](#With-a-StaticResponse-object) for an example of how this is used.
- If an **object with no [`StaticResponse`][staticresponse] keys** is passed, it will be sent as a JSON response body. For example, passing `{ foo: 'bar' }` is equivalent to passing `{ body: { foo: 'bar' } }`.
- If a **callback** is passed, it will be called whenever a request matching this route is received, with the first parameter being the request object. From inside the callback, you can modify the outgoing request, send a response, access the real response, and much more. See ["Intercepted requests"][req] for more information.

### Yields [<Icon name="question-circle"/>](/guides/core-concepts/introduction-to-cypress#Subject-Management)

- `cy.intercept()` yields `null`.
- `cy.intercept()` can be aliased, but otherwise cannot be chained further.
- Waiting on an aliased `cy.intercept()` route using [cy.wait()](/api/commands/wait) will yield an object that contains information about the matching request/response cycle. See [Using the yielded object](#Using-the-yielded-object) for examples of how to use this object.

## Examples

### Matching URL

You can provide the entire URL to match

```js
// will match any request that exactly matches the URL
//   matches GET https://prod.cypress.io/users
//   won't match GET https://staging.cypress.io/users
cy.intercept('https://prod.cypress.io/users')
```

You can provide a [`minimatch`](/api/utilities/minimatch) pattern

```javascript
// will match any HTTP method to urls that end with 3 or 5
cy.intercept('**/users?_limit=+(3|5)')
```

**Tip:** you can evaluate your URL using DevTools console to see if the [`minimatch` pattern](https://www.npmjs.com/package/minimatch) is correct.

```javascript
// paste into the DevTools console while Cypress is running
Cypress.minimatch(
  'https://jsonplaceholder.cypress.io/users?_limit=3',
  '**/users?_limit=+(3|5)'
) // true

// print verbose debug information
Cypress.minimatch(
  'https://jsonplaceholder.cypress.io/users?_limit=3',
  '**/users?_limit=+(3|5)',
  { debug: true }
) // true + lots of debug messages
```

You can even add an assertion to the test itself to ensure the URL is matched

```javascript
// arguments are url and the pattern
expect(
  Cypress.minimatch(
    'https://jsonplaceholder.cypress.io/users?_limit=3',
    '**/users?_limit=+(3|5)'
  ),
  'Minimatch test'
).to.be.true
```

For the most powerful matching, provide a regular expression

```javascript
cy.intercept(/\/users\?_limit=(3|5)$/).as('users')
cy.get('#load-users').click()
cy.wait('@users').its('response.body').should('have.length', 3)

// intercepts _limit=5 requests
cy.get('#load-five-users').click()
cy.wait('@users').its('response.body').should('have.length', 5)
```

### Waiting on a request

Use [cy.wait()](/api/commands/wait) with `cy.intercept()` aliases to wait for the request/response cycle to complete.

#### With URL

```js
cy.intercept('http://example.com/settings').as('getSettings')
// once a request to http://example.com/settings responds, this 'cy.wait' will resolve
cy.wait('@getSettings')
```

#### With [RouteMatcher](#routeMatcher-RouteMatcher)

```js
cy.intercept({
  url: 'http://example.com/search*',
  query: { q: 'expected terms' },
}).as('search')

// once any type of request to http://example.com/search with a querystring containing
// 'q=expected+terms' responds, this 'cy.wait' will resolve
cy.wait('@search')
```

#### Using the yielded object

Using [cy.wait()](/api/commands/wait) on a `cy.intercept()` route alias yields an interception object which represents the request/response cycle:

```js
cy.wait('@someRoute').then((interception) => {
  // 'interception' is an object with properties 'id', 'request' and 'response'
})
```

You can chain [`.its()`](/api/commands/its) and [`.should()`](/api/commands/should) to assert against request/response cycles:

```js
// assert that a request to this route was made with a body that included 'user'
cy.wait('@someRoute').its('request.body').should('include', 'user')

// assert that a request to this route received a response with HTTP status 500
cy.wait('@someRoute').its('response.statusCode').should('eq', 500)

// assert that a request to this route received a response body that includes 'id'
cy.wait('@someRoute').its('response.body').should('include', 'id')
```

#### Aliasing individual requests

Aliases can be set on a per-request basis by setting the `alias` property of the intercepted request:

```js
cy.intercept('POST', '/graphql', (req) => {
  if (req.body.hasOwnProperty('query') && req.body.query.includes('mutation')) {
    req.alias = 'gqlMutation'
  }
})

// assert that a matching request has been made
cy.wait('@gqlMutation')
```

#### Aliasing individual GraphQL requests

Aliases can be set on a per-request basis by setting the `alias` property of the intercepted request.

This is useful against GraphQL endpoints to wait for specific Queries and Mutations.

Given that the `operationName` property is optional in GraphQL requests, we can `alias` with or without this property.

With `operationName` property:

```js
cy.intercept('POST', '/graphql', (req) => {
  if (req.body.operationName.includes('ListPosts')) {
    req.alias = 'gqlListPostsQuery'
  }
})

// assert that a matching request for the ListPosts Query has been made
cy.wait('@gqlListPostsQuery')
```

```js
cy.intercept('POST', '/graphql', (req) => {
  if (req.body.operationName.includes('CreatePost')) {
    req.alias = 'gqlCreatePostMutation'
  }
})

// assert that a matching request for the CreatePost Mutation has been made
cy.wait('@gqlCreatePostMutation')
```

Without `operationName` property:

```js
cy.intercept('POST', '/graphql', (req) => {
  const { body } = req

  if (body.hasOwnProperty('query') && body.query.includes('ListPosts')) {
    req.alias = 'gqlListPostsQuery'
  }
})

// assert that a matching request for the ListPosts Query has been made
cy.wait('@gqlListPostsQuery')
```

```js
cy.intercept('POST', '/graphql', (req) => {
  const { body } = req

  if (body.hasOwnProperty('query') && body.query.includes('CreatePost')) {
    req.alias = 'gqlCreatePostMutation'
  }
})

// assert that a matching request for the CreatePost Mutation has been made
cy.wait('@gqlCreatePostMutation')
```

#### Waiting on errors

You can use [cy.wait()](/api/commands/wait) to wait on requests that end with network errors:

```js
cy.intercept('GET', '/should-err', { forceNetworkError: true }).as('err')

// assert that this request happened, and that it ended in an error
cy.wait('@err').should('have.property', 'error')
```

### Stubbing a response

#### With a string

```js
// requests to '/update' will be fulfilled with a body of "success"
cy.intercept('/update', 'success')
```

#### With a fixture

```js
// requests to '/users.json' will be fulfilled
// with the contents of the "users.json" fixture
cy.intercept('/users.json', { fixture: 'users.json' })
```

#### With a `StaticResponse` object

A [`StaticResponse`][staticresponse] object represents a response to an HTTP request, and can be used to stub routes:

```js
const staticResponse = {
  /* some StaticResponse properties here... */
}

cy.intercept('/projects', staticResponse)
```

For example, to stub a response with a JSON body:

```js
cy.intercept('/projects', {
  body: [{ projectId: '1' }, { projectId: '2' }],
})
```

Or to stub headers, status code, and body all at once:

```js
cy.intercept('/not-found', {
  statusCode: 404,
  body: '404 Not Found!',
  headers: {
    'x-not-found': 'true',
  },
})
```

See ["`StaticResponse` objects"][staticresponse] for more information on `StaticResponse`s.

### Intercepting a request

#### Asserting on a request

```js
cy.intercept('POST', '/organization', (req) => {
  expect(req.body).to.include('Acme Company')
})
```

#### Modifying an outgoing request

You can use the request handler callback to modify the request before it is sent.

```js
cy.intercept('POST', '/login', (req) => {
  // set the request body to something different before it's sent to the destination
  req.body = 'username=janelane&password=secret123'
})
```

#### Adding a header to an outgoing request

You can add a header to an outgoing request, or modify an existing header

```js
cy.intercept('/req-headers', (req) => {
  req.headers['x-custom-headers'] = 'added by cy.intercept'
})
```

**Note:** the new header will NOT be shown in the browser's Network tab, as the request has already left the browser. You can still confirm the header was added by waiting on the intercept as shown below:

```js
cy.intercept('/req-headers', (req) => {
  req.headers['x-custom-headers'] = 'added by cy.intercept'
}).as('headers')

// the application makes the call ...
// confirm the custom header was added
cy.wait('@headers')
  .its('request.headers')
  .should('have.property', 'x-custom-headers', 'added by cy.intercept')
```

#### Add, modify or delete a header to all outgoing requests

You can add, modify or delete a header to all outgoing requests using a `beforeEach()` in the `cypress/support/index.js` file

```ts
// Code from Real World App (RWA)
// cypress/support/index.ts
import './commands'

beforeEach(() => {
  cy.intercept(
    { url: 'http://localhost:3001/**', middleware: true },
    // Delete 'if-none-match' header from all outgoing requests
    (req) => delete req.headers['if-none-match']
  )
})
```

<Alert type="info">

##### <Icon name="graduation-cap"></Icon> Real World Example

Clone the <Icon name="github"></Icon> [Real World App (RWA)](https://github.com/cypress-io/cypress-realworld-app) and refer to the [cypress/support/index.ts](https://github.com/cypress-io/cypress-realworld-app/blob/develop/cypress/support/index.ts) file for a working example.

</Alert>

#### Dynamically stubbing a response

You can use the [`req.reply()`][req-reply] function to dynamically control the response to a request.

```js
cy.intercept('/billing', (req) => {
  // functions on 'req' can be used to dynamically respond to a request here

  // send the request to the destination server
  req.reply()

  // respond to the request with a JSON object
  req.reply({ plan: 'starter' })

  // send the request to the destination server, and intercept the response
  req.continue((res) => {
    // 'res' represents the real destination's response
    // See "Intercepting a response" for more details and examples
  })
})
```

See ["Intercepted requests"][req] for more information on the `req` object and its properties and methods.

#### Returning a Promise

If a Promise is returned from the route callback, it will be awaited before continuing with the request.

```js
cy.intercept('POST', '/login', (req) => {
  // you could asynchronously fetch test data...
  return getLoginCredentials().then((credentials) => {
    // ...and then, use it to supplement the outgoing request
    req.headers['authorization'] = credentials
  })
})
```

#### Passing a request to the next request handler

If [`req.reply()`][req-reply] is not explicitly called inside of a request handler, requests will pass to the next request handler until none are left.

```js
// you could have a top-level middleware handler that sets an auth token on all requests
// setting `middleware: true` will cause this to always be called first
cy.intercept('http://api.company.com/', { middleware: true }, (req) => {
  req.headers['authorization'] = `token ${token}`
})

// and then have another handler that more narrowly asserts on certain requests
cy.intercept('POST', 'http://api.company.com/widgets', (req) => {
  expect(req.body).to.include('analytics')
})

// a POST request to http://api.company.com/widgets would hit both
// of those callbacks, middleware first, then the request would be sent out
// with the modified request headers to the real destination
```

### Intercepting a response

Inside of a callback passed to `req.continue()`, you can access the destination server's real response.

```js
cy.intercept('/integrations', (req) => {
  // req.continue() with a callback will send the request to the destination server
  req.continue((res) => {
    // 'res' represents the real destination response
    // you can manipulate 'res' before it's sent to the browser
  })
})
```

See ["Intercepted responses"][res] for more information on the `res` object. See ["Controlling the outbound request with `req.continue()`"][req-continue] for more information about `req.continue()`.

#### Asserting on a response

```js
cy.intercept('/projects/2', (req) => {
  req.continue((res) => {
    expect(res.body).to.include('My Project')
  })
})
```

#### Returning a Promise

If a Promise is returned from the route callback, it will be awaited before sending the response to the browser.

```js
cy.intercept('/users', (req) => {
  req.continue((res) => {
    // the response will not be sent to the browser until 'waitForSomething()' resolves
    return waitForSomething()
  })
})
```

#### Throttle or delay response all incoming responses

You can throttle or delay all incoming responses using a `beforeEach()` in the `cypress/support/index.js` file

```ts
// Code from Real World App (RWA)
// cypress/support/index.ts
import { isMobile } from './utils'
import './commands'
// Throttle API responses for mobile testing to simulate real world conditions
if (isMobile()) {
  cy.intercept({ url: 'http://localhost:3001/**', middleware: true }, (req) => {
    req.on('response', (res) => {
      // Throttle the response to 1 Mbps to simulate a mobile 3G connection
      res.setThrottle(1000)
    })
  })
}
```

<Alert type="info">

##### <Icon name="graduation-cap"></Icon> Real World Example

Clone the <Icon name="github"></Icon> [Real World App (RWA)](https://github.com/cypress-io/cypress-realworld-app) and refer to the [cypress/support/index.ts](https://github.com/cypress-io/cypress-realworld-app/blob/develop/cypress/support/index.ts) file for a working example.

</Alert>

## Intercepted requests

If a function is passed as the handler for a `cy.intercept()`, it will be called with the first argument being an object that represents the intercepted HTTP request:

```js
cy.intercept('/api', (req) => {
  // `req` represents the intercepted HTTP request
})
```

From here, you can do several things with the intercepted request:

- you can modify and assert on the request's properties (body, headers, URL, method...)
- the request can be sent to the real upstream server
  - optionally, you can intercept the response from this
- a response can be provided to stub out the request
- listeners can be attached to various events on the request

### Request object properties

The request object (`req`) has several properties from the HTTP request itself. All of the following properties on `req` can be modified except for `httpVersion`:

```ts
{
  /**
   * The body of the request.
   * If a JSON Content-Type was used and the body was valid JSON, this will be an object.
   * If the body was binary content, this will be a buffer.
   */
  body: string | object | any
  /**
   * The headers of the request.
   */
  headers: { [key: string]: string }
  /**
   * Request HTTP method (GET, POST, ...).
   */
  method: string
  /**
   * Request URL.
   */
  url: string
  /**
   * The HTTP version used in the request. Read only.
   */
  httpVersion: string
}
```

`req` also has some optional properties which can be set to control Cypress-specific behavior:

```ts
{
  /**
   * If provided, the number of milliseconds before an upstream response to this request
   * will time out and cause an error. By default, `responseTimeout` from config is used.
   */
  responseTimeout?: number
  /**
   * Set if redirects should be followed when this request is made. By default, requests will
   * not follow redirects before yielding the response (the 3xx redirect is yielded)
   */
  followRedirect?: boolean
  /**
   * If set, `cy.wait` can be used to await the request/response cycle to complete for this
   * request via `cy.wait('@alias')`.
   */
  alias?: string
}
```

Any modifications to the properties of `req` will be persisted to other request handlers, and finally merged into the actual outbound HTTP request.

### Controlling the outbound request with `req.continue()`

Calling `req.continue()` without any argument will cause the request to be sent outgoing, and the response will be returned to the browser after any other listeners have been called. For example, the following code modifies a `POST` request and then sends it to the upstream server:

```js
cy.intercept('POST', '/submitStory', (req) => {
  req.body.storyName = 'some name'
  // send the modified request and skip any other matching request handlers
  req.continue()
})
```

If a function is passed to `req.continue()`, the request will be sent to the real upstream server, and the callback will be called with the response once the response is fully received from the server. See ["Intercepted responses"][res]

Note: calling `req.continue()` will stop the request from propagating to the next matching request handler in line. See ["Interception lifecycle"][lifecycle] for more information.

### Providing a stub response with `req.reply()`

The `req.reply()` function can be used to send a stub response for an intercepted request. By passing a string, object, or [`StaticResponse`][staticresponse] to `req.reply()`, the request can be preventing from reaching the destination server.

For example, the following code stubs out a JSON response from a request interceptor:

```js
cy.intercept('/billing', (req) => {
  // dynamically get billing plan name at request-time
  const planName = getPlanName()
  // this object will automatically be JSON.stringified and sent as the response
  req.reply({ plan: planName })
})
```

Instead of passing a plain object or string to `req.reply()`, you can also pass a [`StaticResponse`][staticresponse] object. With a [`StaticResponse`][staticresponse], you can force a network error, delay/throttle the response, send a fixture, and more.

For example, the following code serves a dynamically chosen fixture with a delay of 500ms:

```js
cy.intercept('/api/users/*', async (req) => {
  // asynchronously retrieve fixture filename at request-time
  const fixtureFilename = await getFixtureFilenameForUrl(req.url)
  req.reply({
    fixture: fixtureFilename,
    delay: 500,
  })
})
```

See the [`StaticResponse` documentation][staticresponse] for more information on stubbing responses in this manner.

`req.reply()` also supports shorthand, similar to [`res.send()`][res-send], to avoid having to specify a `StaticResponse` object:

```js
req.reply(body) // equivalent to `req.reply({ body })`
req.reply(body, headers) // equivalent to `req.reply({ body, headers })`
req.reply(statusCode, body, headers) // equivalent to `req.reply({ statusCode, body, headers})`
```

There are also two convenience functions available on `req`:

```ts
{
  /**
   * Destroy the request and respond with a network error.
   */
  destroy(): void
  /**
   * Respond to this request with a redirect to a new 'location'.
   * @param statusCode HTTP status code to redirect with. Default: 302
   */
  redirect(location: string, statusCode?: number): void
}
```

Note: calling `req.reply()` will end the request phase and stop the request from propagating to the next matching request handler in line. See ["Interception lifecycle"][lifecycle] for more information.

### Request events

For advanced use, several events are available on `req`, that represent different stages of the [Interception lifecycle][lifecycle].

By calling `req.on`, you can subscribe to different events:

```js
cy.intercept('/shop', (req) => {
  req.on('before:response', (res) => {
    /**
     * Emitted before `response` and before any `req.continue` handlers.
     * Modifications to `res` will be applied to the incoming response.
     * If a promise is returned, it will be awaited before processing other event handlers.
     */
  })

  req.on('response', (res) => {
    /**
     * Emitted after `before:response` and after any `req.continue` handlers - before the response is sent to the browser.
     * Modifications to `res` will be applied to the incoming response.
     * If a promise is returned, it will be awaited before processing other event handlers.
     */
  })

  req.on('after:response', (res) => {
    /**
     * Emitted once the response to a request has finished sending to the browser.
     * Modifications to `res` have no impact.
     * If a promise is returned, it will be awaited before processing other event handlers.
     */
  })
})
```

See ["Intercepted responses"][res] for more details on the `res` object yielded by `before:response` and `response`. See ["Interception lifecycle"][lifecycle] for more details on request ordering.

## Intercepted responses

The response can be intercepted in two ways:

- by passing a callback to [`req.continue()`](req-continue) within a request handler
- by listening for the `before:response` or `response` request events (see ["Request events"](#Request-events))

The response object, `res`, will be passed as the first argument to the handler function:

```js
cy.intercept('/url', (req) => {
  res.on('before:response', (res) => {
    // this will be called before any `req.continue` or `response` handlers
  })

  req.continue((res) => {
    // this will be called after all `before:response` handlers and before any `response` handlers
    // by calling `req.continue`, we signal that this request handler will be the last one, and that
    // the request should be sent outgoing at this point. for that reason, there can only be one
    // `req.continue` handler per request.
  })

  res.on('response', (res) => {
    // this will be called after all `before:response` handlers and after the `req.continue` handler
    // but before the response is sent to the browser
  })
})
```

### Response object properties

The response object (`res`) yielded to response handlers has several properties from the HTTP response itself. All of the following properties on `res` can be modified:

```ts
{
  /**
   * The body of the response.
   * If a JSON Content-Type was used and the body was valid JSON, this will be an object.
   * If the body was binary content, this will be a buffer.
   */
  body: string | object | any
  /**
   * The headers of the response.
   */
  headers: { [key: string]: string }
  /**
   * The HTTP status code of the response.
   */
  statusCode: number
  /**
   * The HTTP status message.
   */
  statusMessage: string
}
```

`res` also has some optional properties which can be set to control Cypress-specific behavior:

```ts
{
  /**
   * Kilobits per second to send 'body'.
   */
  throttleKbps?: number
  /**
   * Milliseconds to delay before the response is sent.
   */
  delay?: number
}
```

Any modifications to the properties of `res` will be persisted to other response handlers, and finally merged into the actual incoming HTTP response.

### Ending the response with `res.send()`

To end the response phase of the request, call `res.send()`. Optionally, you can pass a [`StaticResponse`][staticresponse] to `res.send()`, to be merged with the actual response.

When `res.send()` is called, the response phase will end immediately and no other response handlers will be called for the current request. Here is an example of how `res.send()` could be used:

```js
cy.intercept('/notification', (req) => {
  req.continue((res) => {
    if (res.body.status === 'failed') {
      // sends a fixture body instead of the existing 'res.body'
      res.send({ fixture: 'success.json' })
    }
  })
})
```

See the [`StaticResponse` documentation][staticresponse] for more information on the format.

`res.send()` also supports shorthand, similar to [`req.reply()`][req-reply], to avoid having to specify a `StaticResponse` object:

```js
res.send(body) // equivalent to `res.send({ body })`
res.send(body, headers) // equivalent to `res.send({ body, headers })`
res.send(statusCode, body, headers) // equivalent to `res.send({ statusCode, body, headers})`
```

There are also two convenience functions available on `res`:

```ts
{
  /**
   * Wait for 'delay' milliseconds before sending the response to the client.
   */
  setDelay: (delay: number) => IncomingHttpResponse
  /**
   * Serve the response at 'throttleKbps' kilobytes per second.
   */
  setThrottle: (throttleKbps: number) => IncomingHttpResponse
}
```

Note: calling `res.send()` will end the response phase and stop the response from propagating to the next matching response handler in line. See ["Interception lifecycle"][lifecycle] for more information.

## `StaticResponse` objects

A `StaticResponse` represents a stubbed response to an HTTP request. You can supply a `StaticResponse` to Cypress in 3 ways:

- Directly to `cy.intercept()`, to stub a response to a route: `cy.intercept('/url', staticResponse)`
- To [`req.reply()`][req-reply], to stub a response from a request handler: `req.reply(staticResponse)`
- To [`res.send()`][res-send], to stub a response from a response handler: `res.send(staticResponse)`

The following properties are available on `StaticResponse`. All properties are optional:

```ts
{
  /**
   * Serve a fixture as the response body.
   */
  fixture?: string
  /**
   * Serve a static string/JSON object as the response body.
   */
  body?: string | object | object[]
  /**
   * HTTP headers to accompany the response.
   * @default {}
   */
  headers?: { [key: string]: string }
  /**
   * The HTTP status code to send.
   * @default 200
   */
  statusCode?: number
  /**
   * If 'forceNetworkError' is truthy, Cypress will destroy the browser connection
   * and send no response. Useful for simulating a server that is not reachable.
   * Must not be set in combination with other options.
   */
  forceNetworkError?: boolean
  /**
   * Milliseconds to delay before the response is sent.
   */
  delay?: number
  /**
   * Kilobits per second to send 'body'.
   */
  throttleKbps?: number
}
```

See ["Stubbing a response with a `StaticResponse` object"][#with-a-staticresponse-object] for examples of stubbing with `cy.intercept()`.

## Interception lifecycle

The lifecycle of a `cy.intercept()` interception begins when an HTTP request is sent from your app that matches one or more registered `cy.intercept()` routes. From there, each interception has two phases: request and response.

`cy.intercept()` routes are matched in reverse order of definition, except for routes which are defined with `{ middleware: true }`, which always run first. This allows you to override existing `cy.intercept()` declarations by defining an overlapping `cy.intercept()`.

### Request phase

The following steps are used to handle the request phase.

1. Start with the first matching route according to the above algorithm (middleware first, followed by handlers in reverse order).
2. Was a handler (body, [`StaticResponse`][staticresponse], or function) supplied to `cy.intercept()`? If not, continue to step 7.
3. If the handler was a body or [`StaticResponse`][staticresponse], immediately end the request with that response.
4. If the handler was a function, call the function with `req`, the incoming request, as the first argument. See ["Intercepted requests"][req] for more information on the `req` object.
   - If [`req.reply()`][req-reply] is called, immediately end the request phase with the provided response. See ["Providing a stub response with `req.reply()`"](#Providing-a-stub-response-with-req-reply).
   - If [`req.continue()`][req-continue] is called, immediately end the request phase, and send the request to the destination server. If a callback is provided to [`req.continue()`][req-continue], it will be called during the [response phase](#Response-phase)
5. If the handler returned a Promise, wait for the Promise to resolve.
6. Merge any modifications to the request object with the real request.
7. If there is another matching `cy.intercept()`, return to step 2 and continue following steps with that route.
8. Send the request outgoing to the destination server and end the request phase. The [response phase](#Response-phase) will begin once a response is received.

### Response phase

Once the HTTP response is received from the upstream server, the following steps are applied:

1. Get a list of registered `before:response` event listeners.
2. For each `before:response` listener (if any), call it with the [`res`][res] object.
   - If [`res.send()`][res-send] is called, end the response phase and merge any passed arguments with the response.
   - If a Promise is returned, await it. Merge any modified response properties with the real response.
3. If a `req.continue()` with callback is declared for this route, call the callback with the [`res`][res] object.
   - If [`res.send()`][res-send] is called, end the response phase and merge any passed arguments with the response.
   - If a Promise is returned, await it. Merge any modified response properties with the real response.
4. Get a list of registered `response` event listeners.
5. For each `response` listener (if any), call it with the [`res`][res] object.
   - If [`res.send()`][res-send] is called, end the response phase and merge any passed arguments with the response.
   - If a Promise is returned, await it. Merge any modified response properties with the real response.
6. Send the response to the browser.
7. Once the response is complete, get a list of registered `after:response` event listeners.
8. For each `after:response` listener (if any), call it with the [`res`][res] object (minus `res.send`)
   - If a Promise is returned, await it.
9. End the response phase.

## History

| Version                                     | Changes                                                                                |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [7.0.0](/guides/references/changelog#7-0-0) | Removed `matchUrlAgainstPath` option from `RouteMatcher`, reversed handler ordering, added request events, removed substring URL matching, removed `cy.route2` alias, added `middleware` RouteMatcher option, renamed `res.delay()` to `res.setDelay()` and `res.throttle()` to `res.setThrottle()`. |
| [6.4.0](/guides/references/changelog#6-4-0) | Renamed `delayMs` property to `delay` (backwards-compatible).                                                                                |
| [6.2.0](/guides/references/changelog#6-2-0) | Added `matchUrlAgainstPath` option to `RouteMatcher`.                                                                                |
| [6.0.0](/guides/references/changelog#6-0-0) | Renamed `cy.route2()` to `cy.intercept()`.                                                                                |
| [6.0.0](/guides/references/changelog#6-0-0) | Removed `experimentalNetworkStubbing` option and made it the default behavior.                                                                                |
| [5.1.0](/guides/references/changelog#5-1-0) | Added experimental `cy.route2()` command under `experimentalNetworkStubbing` option.                                                                                |

## Notes

### `cy.intercept()` cannot be debugged using [`cy.request()`](/api/commands/request)

#### `cy.request()` sends requests to actual endpoints, bypassing those defined using `cy.intercept()`

The intention of `cy.request()` is to be used for checking endpoints on an actual, running server without having to start the front end application.

## See also

- [`.as()`](/api/commands/as)
- [`cy.fixture()`](/api/commands/fixture)
- [`cy.wait()`](/api/commands/wait)
- [Migrating `cy.route()` to `cy.intercept()`](/guides/references/migration-guide#Migrating-cy-route-to-cy-intercept)
- [`cy.intercept()` example recipes with real-world examples](https://github.com/cypress-io/cypress-example-recipes#stubbing-and-spying)
  - spying on requests
  - stubbing any request
  - changing the response from the server
  - intercepting static resources like HTML and CSS
  - redirecting requests
  - replying with different responses
- [How cy.intercept works](https://slides.com/bahmutov/how-cy-intercept-works) presentation
- [Cypress cy.intercept Problems](https://glebbahmutov.com/blog/cypress-intercept-problems/) with advanced `cy.intercept` tips to solve the common problems:
  - The intercept was registered too late
  - `cy.wait` uses the intercept
  - The response was cached
  - The request matched multiple intercepts
  - How to overwrite interceptors
  - How to avoid using Cypress commands inside the interceptor
  - Sending different responses
- [`cy.route()` vs `cy.route2()`](https://glebbahmutov.com/blog/cy-route-vs-route2/) blog post
- [Smart GraphQL Stubbing in Cypress](https://glebbahmutov.com/blog/smart-graphql-stubbing/) blog post
- [Open issues for `net stubbing`](https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aopen+label%3Apkg%2Fnet-stubbing) and [closed issues for `net stubbing`](https://github.com/cypress-io/cypress/issues?q=is%3Aissue+is%3Aclosed+label%3Apkg%2Fnet-stubbing)

[staticresponse]: #StaticResponse-objects
[lifecycle]: #Interception-lifecycle
[req]: #Intercepted-requests
[req-continue]: #Controlling-the-outbound-request-with-req-continue
[req-reply]: #Providing-a-stub-response-with-req-reply
[res]: #Intercepted-responses
[res-send]: #Ending-the-response-with-res-send

repository: NoriSte/cypress-documentation

repo_name: NoriSte/cypress-documentation


text:
# Mutility
Mutility is for keeping track of record changes. When attempting to do data science on a database, it can be difficult and even impossible to retrieve historical data unless the database tracks data changes. Mutility intends to keep a database lossless of updates to data.

## Usage
Suppose you have a `Comment` model with `body` and `tag` columns of which you would like to track changes. You'll need to create a change model to track `Comment` changes.

```bash
$ rails generate model comment_change comment_id:integer body:text tag:string
$ rails db:migrate
```

You don't want a foreign key constraint in the `CommentChange` table such that you are still able to delete a `Comment` and retain its changes. Due to this, you'll have to manually assign the `Comment` association to your `CommentChange` model. Mutility uses this association to assign the foreign key.

##### app/models/comment_change.rb

```ruby
class CommentChange < ApplicationRecord
  belongs_to :comment
end

```

Now you can include Mutility in the `Comment` model to track changes to the `body` and `tag` columns.

##### app/models/comment.rb

```ruby
class Comment < ApplicationRecord
  include Mutility
  mutilize :body, :tag

  ...
end

```

Mutility will now track changes to the `Comment` model.

```bash
$ rails console
> comment = Comment.create body: 'some comment', tag: 'super cool'
> CommentChange.count
=> 0
> comment.update body: 'changed my mind'
> CommentChange.count
=> 1
> CommentChange.last
=> #<CommentChange id: 1, body: "some comment", tag: "super cool", created_at: "...", updated_at: "...">
> comment.update tag: 'not really that cool'
> CommentChange.count
=> 2
> CommentChange.last
=> #<CommentChange id: 2, body: "changed my mind", tag: "super cool", created_at: "...", updated_at: "...">
```

The change model can configured if you don't want the suffix `Change` for your models.

##### app/models/comment.rb

```ruby
class Comment < ApplicationRecord
  include Mutility
  mutilize :body, :tag, change_model: CommentDifference

  ...
end

```

The columns in your source model can be mapped to columns with different names in your change model.

##### app/models/comment.rb

```ruby
class Comment < ApplicationRecord
  include Mutility
  mutilize :body, :tag, map_columns: { body: :body_was }

  ...
end

```

## Installation
Add this line to your application's Gemfile:

```ruby
gem 'mutility'
```

And then execute:
```bash
$ bundle
```

Or install it yourself as:
```bash
$ gem install mutility
```

<!-- ## Contributing -->
<!-- Contribution directions go here. -->

## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).

repository: lucaswinningham/mutility

repo_name: lucaswinningham/mutility


text:
### Unreleased

### [1.2.0] - 2023-03-29

- maint: replace for..i iterator with for..of, add test
- feat: add redis enabled setting, #28

### [1.1.0] - 2022-11-22

- fix: use this.redis_ping during runtime, #26
- test: more async tests

### 1.0.4 - 2022-11-15

- fix: run redis_ping when registering, fixes #23
- ci: replace travis/appveyor with GHA
- dep(redis): 2 -> 4
- dep(pi-redis): * -> 2
- dep(eslint): 4 -> 8
- dep(url): drop npm url package, use builtin
- test: replace node_unit with mocha
- doc(README): update badge URLs

### 1.0.3 - 2019-04-11

- test fix for unitialized redis config block

### 1.0.2 - 2018-03-05

- for MX entries, previously only full email address matches in the file were parsed for LMTP/SMTP routes. Now all MX entries are parsed (email file, email domain, email redis, and domain redis) for URIs.
- use es6 arrow functions
- refactored the functions in rcpt() into separate functions (simplify, more testable)

### 1.0.1 - 2017-08-19

- enable Redis install on AppVeyor CI testing

### 1.0.0 - 2017-07-28

- imported from haraka/plugins/rcpt_to.routes

[1.0.4]: https://github.com/haraka/haraka-plugin-recipient-routes/releases/tag/1.0.4
[1.1.0]: https://github.com/haraka/haraka-plugin-recipient-routes/releases/tag/1.1.0
[1.2.0]: https://github.com/haraka/haraka-plugin-recipient-routes/releases/tag/1.2.0

repository: haraka/haraka-plugin-recipient-routes

gha_language: JavaScript

repo_name: haraka/haraka-plugin-recipient-routes


text:
# SellingPartnerApiForFinances.Promotion

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**promotionType** | **String** | The type of promotion. | [optional]
**promotionId** | **String** | The seller-specified identifier for the promotion. | [optional]
**promotionAmount** | [**Currency**](Currency.md) |  | [optional]

repository: clousale/amazon-sp-api-javascript

repo_name: clousale/amazon-sp-api-javascript