text:
# node-pre-gyp

#### node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries

[![NPM](https://nodei.co/npm/node-pre-gyp.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-pre-gyp/)

[![Build Status](https://api.travis-ci.org/mapbox/node-pre-gyp.svg)](https://travis-ci.org/mapbox/node-pre-gyp)
[![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp)
[![Dependencies](https://david-dm.org/mapbox/node-pre-gyp.svg)](https://david-dm.org/mapbox/node-pre-gyp)

`node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment.

### Features

 - A command line tool called `node-pre-gyp` that can install your package's C++ module from a binary.
 - A variety of developer targeted commands for packaging, testing, and publishing binaries.
 - A JavaScript module that can dynamically require your installed binary: `require('node-pre-gyp').find`

For a hello world example of a module packaged with `node-pre-gyp` see <https://github.com/springmeyer/node-addon-example> and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples.

## Credits

 - The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate)
 - Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost).
 - Development is sponsored by [Mapbox](https://www.mapbox.com/)

## FAQ

See the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ).

## Depends

 - Node.js >= node v6.x

## Install

`node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like:

    ./node_modules/.bin/node-pre-gyp --help

But you can also install it globally:

    npm install node-pre-gyp -g

## Usage

### Commands

View all possible commands:

    node-pre-gyp --help

- clean - Remove the entire folder containing the compiled .node module
- install - Install pre-built binary for module
- reinstall - Run "clean" and "install" at once
- build - Compile the module by dispatching to node-gyp or nw-gyp
- rebuild - Run "clean" and "build" at once
- package - Pack binary into tarball
- testpackage - Test that the staged package is valid
- publish - Publish pre-built binary
- unpublish - Unpublish pre-built binary
- info - Fetch info on published binaries

You can also chain commands:

    node-pre-gyp clean build unpublish publish info

### Options

Options include:

 - `-C/--directory`: run the command in this directory
 - `--build-from-source`: build from source instead of using pre-built binary
 - `--update-binary`: reinstall by replacing previously installed local binary with remote binary
 - `--runtime=node-webkit`: customize the runtime: `node`, `electron` and `node-webkit` are the valid options
 - `--fallback-to-build`: fallback to building from source if pre-built binary is not available
 - `--target=0.4.0`: Pass the target node or node-webkit version to compile against
 - `--target_arch=ia32`: Pass the target arch and override the host `arch`. Valid values are 'ia32','x64', or `arm`.
 - `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`.

Both `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module.

For example: `npm install --build-from-source=myapp`. This is useful if:

 - `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependency with `npm install`.
 - The larger app also depends on other modules installed with `node-pre-gyp`
 - You only want to trigger a source compile for `myapp` and the other modules.

### Configuring

This is a guide to configuring your module to use node-pre-gyp.

#### 1) Add new entries to your `package.json`

 - Add `node-pre-gyp` to `dependencies`
 - Add `aws-sdk` as a `devDependency`
 - Add a custom `install` script
 - Declare a `binary` object

This looks like:

```js
    "dependencies"  : {
      "node-pre-gyp": "0.6.x"
    },
    "devDependencies": {
      "aws-sdk": "2.x"
    }
    "scripts": {
        "install": "node-pre-gyp install --fallback-to-build"
    },
    "binary": {
        "module_name": "your_module",
        "module_path": "./lib/binding/",
        "host": "https://your_module.s3-us-west-1.amazonaws.com"
    }
```

For a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/master/package.json).

Let's break this down:

 - Dependencies need to list `node-pre-gyp`
 - Your devDependencies should list `aws-sdk` so that you can run `node-pre-gyp publish` locally or a CI system. We recommend using `devDependencies` only since `aws-sdk` is large and not needed for `node-pre-gyp install` since it only uses http to fetch binaries
 - Your `scripts` section should override the `install` target with `"install": "node-pre-gyp install --fallback-to-build"`. This allows node-pre-gyp to be used instead of the default npm behavior of always source compiling with `node-gyp` directly.
 - Your package.json should contain a `binary` section describing key properties you provide to allow node-pre-gyp to package optimally. They are detailed below.

Note: in the past we recommended putting `node-pre-gyp` in the `bundledDependencies`, but we no longer recommend this. In the past there were npm bugs (with node versions 0.10.x) that could lead to node-pre-gyp not being available at the right time during install (unless we bundled). This should no longer be the case. Also, for a time we recommended using `"preinstall": "npm install node-pre-gyp"` as an alternative method to avoid needing to bundle. But this did not behave predictably across all npm versions - see https://github.com/mapbox/node-pre-gyp/issues/260 for the details. So we do not recommend using `preinstall` to install `node-pre-gyp`. More history on this at https://github.com/strongloop/fsevents/issues/157#issuecomment-265545908.

##### The `binary` object has three required properties

###### module_name

The name of your native node module. This value must:

 - Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world)
 - Must be a valid C variable name (e.g. it cannot contain `-`)
 - Should not include the `.node` extension.

###### module_path

The location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball.

Note: This property supports variables based on [Versioning](#versioning).

###### host

A url to the remote location where you've published tarball binaries (must be `https` not `http`).

It is highly recommended that you use Amazon S3. The reasons are:

  - Various node-pre-gyp commands like `publish` and `info` only work with an S3 host.
  - S3 is a very solid hosting platform for distributing large files.
  - We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp.

Why then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a GitHub repo. This is not recommended, but if an author really wants to host in a non-S3 location then it should be possible.

It should also be mentioned that there is an optional and entirely separate npm module called [node-pre-gyp-github](https://github.com/bchr02/node-pre-gyp-github) which is intended to complement node-pre-gyp and be installed along with it. It provides the ability to store and publish your binaries within your repositories GitHub Releases if you would rather not use S3 directly. Installation and usage instructions can be found [here](https://github.com/bchr02/node-pre-gyp-github), but the basic premise is that instead of using the ```node-pre-gyp publish``` command you would use ```node-pre-gyp-github publish```.

##### The `binary` object has two optional properties

###### remote_path

It **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `""` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`.

Note: This property supports variables based on [Versioning](#versioning).

###### package_name

It is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`.

Avoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like:

```sh
aws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/
```

Note: This property supports variables based on [Versioning](#versioning).

#### 2) Add a new target to binding.gyp

`node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path).

A new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`.

Add a target like this at the end of your `targets` list:

```js
    {
      "target_name": "action_after_build",
      "type": "none",
      "dependencies": [ "<(module_name)" ],
      "copies": [
        {
          "files": [ "<(PRODUCT_DIR)/<(module_name).node" ],
          "destination": "<(module_path)"
        }
      ]
    }
```

For a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp).

#### 3) Dynamically require your `.node`

Inside the main js file that requires your addon module you are likely currently doing:

```js
var binding = require('../build/Release/binding.node');
```

or:

```js
var bindings = require('./bindings')
```

Change those lines to:

```js
var binary = require('node-pre-gyp');
var path = require('path');
var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json')));
var binding = require(binding_path);
```

For a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4)

#### 4) Build and package your app

Now build your module from source:

    npm install --build-from-source

The `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build.

Now `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`.

#### 5) Test

Now `npm test` should work just as it did before.

#### 6) Publish the tarball

Then package your app:

    ./node_modules/.bin/node-pre-gyp package

Once packaged, now you can publish:

    ./node_modules/.bin/node-pre-gyp publish

Currently the `publish` command pushes your binary to S3. This requires:

 - You have installed `aws-sdk` with `npm install aws-sdk`
 - You have created a bucket already.
 - The `host` points to an S3 http or https endpoint.
 - You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details).

You can also host your binaries elsewhere. To do this requires:

 - You manually publish the binary created by the `package` command to an `https` endpoint
 - Ensure that the `host` value points to your custom `https` endpoint.

#### 7) Automate builds

Now you need to publish builds for all the platforms and node versions you wish to support. This is best automated.

 - See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows.
 - See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux.

#### 8) You're done!

Now publish your module to the npm registry. Users will now be able to install your module from a binary.

What will happen is this:

1. `npm install <your package>` will pull from the npm registry
2. npm will run the `install` script which will call out to `node-pre-gyp`
3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place
4. Assuming that all worked, you are done

If a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module.

## N-API Considerations

[N-API](https://nodejs.org/api/n-api.html#n_api_n_api) is an ABI-stable alternative to previous technologies such as [nan](https://github.com/nodejs/nan) which are tied to a specific Node runtime engine. N-API is Node runtime engine agnostic and guarantees modules created today will continue to run, without changes, into the future.

Using `node-pre-gyp` with N-API projects requires a handful of additional configuration values and imposes some additional requirements.

The most significant difference is that an N-API module can be coded to target multiple  N-API versions. Therefore, an N-API module must declare in its `package.json` file which N-API versions the module is designed to run against. In addition, since multiple builds may be required for a single module, path and file names must be specified in way that avoids naming conflicts.

### The `napi_versions` array property

An N-API modules must declare in its `package.json` file, the N-API versions the module is intended to support. This is accomplished by including an `napi-versions` array property in the `binary` object. For example:

```js
"binary": {
    "module_name": "your_module",
    "module_path": "your_module_path",
    "host": "https://your_bucket.s3-us-west-1.amazonaws.com",
    "napi_versions": [1,3]
  }
```

If the `napi_versions` array property is *not* present, `node-pre-gyp` operates as it always has. Including the `napi_versions` array property instructs `node-pre-gyp` that this is a N-API module build.

When the `napi_versions` array property is present, `node-pre-gyp` fires off multiple operations, one for each of the N-API versions in the array. In the example above, two operations are initiated, one for N-API version 1 and second for N-API version 3. How this version number is communicated is described next.

### The `napi_build_version` value

For each of the N-API module operations `node-pre-gyp` initiates, it ensures that the `napi_build_version` is set appropriately.

This value is of importance in two areas:

1. The C/C++ code which needs to know against which N-API version it should compile.
2. `node-pre-gyp` itself which must assign appropriate path and file names to avoid collisions.

### Defining `NAPI_VERSION` for the C/C++ code

The `napi_build_version` value is communicated to the C/C++ code by adding this code to the `binding.gyp` file:

```
"defines": [
    "NAPI_VERSION=<(napi_build_version)",
]
```

This ensures that `NAPI_VERSION`, an integer value, is declared appropriately to the C/C++ code for each build.

> Note that earlier versions of this document recommended defining the symbol `NAPI_BUILD_VERSION`. `NAPI_VERSION` is prefered because it used by the N-API C/C++ headers to configure the specific N-API veriosn being requested.

### Path and file naming requirements in `package.json`

Since `node-pre-gyp` fires off multiple operations for each request, it is essential that path and file names be created in such a way as to avoid collisions. This is accomplished by imposing additional path and file naming requirements.

Specifically, when performing N-API builds, the `{napi_build_version}` text configuration value  *must* be present in the `module_path` property. In addition, the `{napi_build_version}` text configuration value  *must* be present in either the `remote_path` or `package_name` property. (No problem if it's in both.)

Here's an example:

```js
"binary": {
    "module_name": "your_module",
    "module_path": "./lib/binding/napi-v{napi_build_version}",
    "remote_path": "./{module_name}/v{version}/{configuration}/",
    "package_name": "{platform}-{arch}-napi-v{napi_build_version}.tar.gz",
    "host": "https://your_bucket.s3-us-west-1.amazonaws.com",
    "napi_versions": [1,3]
  }
```

## Supporting both N-API and NAN builds

You may have a legacy native add-on that you wish to continue supporting for those versions of Node that do not support N-API, as you add N-API support for later Node versions. This can be accomplished by specifying the `node_napi_label` configuration value in the package.json `binary.package_name` property.

Placing the configuration value `node_napi_label` in the package.json `binary.package_name` property instructs `node-pre-gyp` to build all viable N-API binaries supported by the current Node instance. If the current Node instance does not support N-API, `node-pre-gyp` will request a traditional, non-N-API build.

The configuration value `node_napi_label` is set by `node-pre-gyp` to the type of build created, `napi` or `node`, and the version number. For N-API builds, the string contains the N-API version nad has values like `napi-v3`. For traditional, non-N-API builds, the string contains the ABI version with values like `node-v46`.

Here's how the `binary` configuration above might be changed to support both N-API and NAN builds:

```js
"binary": {
    "module_name": "your_module",
    "module_path": "./lib/binding/{node_napi_label}",
    "remote_path": "./{module_name}/v{version}/{configuration}/",
    "package_name": "{platform}-{arch}-{node_napi_label}.tar.gz",
    "host": "https://your_bucket.s3-us-west-1.amazonaws.com",
    "napi_versions": [1,3]
  }
```

The C/C++ symbol `NAPI_VERSION` can be used to distinguish N-API and non-N-API builds. The value of `NAPI_VERSION` is set to the integer N-API version for N-API builds and is set to `0` for non-N-API builds.

For example:

```C
#if NAPI_VERSION
// N-API code goes here
#else
// NAN code goes here
#endif
```

### Two additional configuration values

The following two configuration values, which were implemented in previous versions of `node-pre-gyp`, continue to exist, but have been replaced by the `node_napi_label` configuration value described above.

1. `napi_version` If N-API is supported by the currently executing Node instance, this value is the N-API version number supported by Node. If N-API is not supported, this value is an empty string.

2. `node_abi_napi` If the value returned for `napi_version` is non empty, this value is `'napi'`. If the value returned for `napi_version` is empty, this value is the value returned for `node_abi`.

These values are present for use in the `binding.gyp` file and may be used as `{napi_version}` and `{node_abi_napi}` for text substituion in the `binary` properties of the `package.json` file.

## S3 Hosting

You can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [Travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu, and with [Appveyor](http://appveyor.com) to automate builds for Windows. Here is an approach to do this:

First, get setup locally and test the workflow:

#### 1) Create an S3 bucket

And have your **key** and **secret key** ready for writing to the bucket.

It is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like:

```js
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1394587197000",
      "Effect": "Allow",
      "Action": [
        "s3:DeleteObject",
        "s3:GetObject",
        "s3:GetObjectAcl",
        "s3:ListBucket",
        "s3:PutObject",
        "s3:PutObjectAcl"
      ],
      "Resource": [
        "arn:aws:s3:::node-pre-gyp-tests/*"
      ]
    }
  ]
}
```

#### 2) Install node-pre-gyp

Either install it globally:

    npm install node-pre-gyp -g

Or put the local version on your PATH

    export PATH=`pwd`/node_modules/.bin/:$PATH

#### 3) Configure AWS credentials

There are several ways to do this.

You can use any of the methods described at http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html.

Or you can create a `~/.node_pre_gyprc`

Or pass options in any way supported by [RC](https://github.com/dominictarr/rc#standards)

A `~/.node_pre_gyprc` looks like:

```js
{
    "accessKeyId": "xxx",
    "secretAccessKey": "xxx"
}
```

Another way is to use your environment:

    export node_pre_gyp_accessKeyId=xxx
    export node_pre_gyp_secretAccessKey=xxx

You may also need to specify the `region` if it is not explicit in the `host` value you use. The `bucket` can also be specified but it is optional because `node-pre-gyp` will detect it from the `host` value.

#### 4) Package and publish your build

Install the `aws-sdk`:

    npm install aws-sdk

Then publish:

    node-pre-gyp package publish

Note: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config.

## Appveyor Automation

[Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports:

 - Windows Visual Studio 2013 and related compilers
 - Both 64 bit (x64) and 32 bit (x86) build configurations
 - Multiple Node.js versions

For an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml).

Below is a guide to getting set up:

#### 1) Create a free Appveyor account

Go to https://ci.appveyor.com/signup/free and sign in with your GitHub account.

#### 2) Create a new project

Go to https://ci.appveyor.com/projects/new and select the GitHub repo for your module

#### 3) Add appveyor.yml and push it

Once you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your GitHub repo and pushed it AppVeyor should automatically start building your project.

#### 4) Create secure variables

Encrypt your S3 AWS keys by going to <https://ci.appveyor.com/tools/encrypt> and hitting the `encrypt` button.

Then paste the result into your `appveyor.yml`

```yml
environment:
  node_pre_gyp_accessKeyId:
    secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA=
  node_pre_gyp_secretAccessKey:
    secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL
```

NOTE: keys are per account but not per repo (this is difference than Travis where keys are per repo but not related to the account used to encrypt them).

#### 5) Hook up publishing

Just put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`.

#### 6) Publish when you want

You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:

    SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE%
    if not "%CM%" == "%CM:[publish binary]=%" node-pre-gyp --msvs_version=2013 publish

If your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`:

    ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish }

Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package.

## Travis Automation

[Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both:

 - Ubuntu Precise and OS X (64 bit)
 - Multiple Node.js versions

For an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml).

Note: if you need 32 bit binaries, this can be done from a 64 bit Travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74).

Below is a guide to getting set up:

#### 1) Install the Travis gem

    gem install travis

#### 2) Create secure variables

Make sure you run this command from within the directory of your module.

Use `travis-encrypt` like:

    travis encrypt node_pre_gyp_accessKeyId=${node_pre_gyp_accessKeyId}
    travis encrypt node_pre_gyp_secretAccessKey=${node_pre_gyp_secretAccessKey}

Then put those values in your `.travis.yml` like:

```yaml
env:
  global:
    - secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M=
    - secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI=
```

More details on Travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/.

#### 3) Hook up publishing

Just put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`.

##### OS X publishing

If you want binaries for OS X in addition to linux you can enable [multi-os for Travis](http://docs.travis-ci.com/user/multi-os/#Setting-.travis.yml)

Use a configuration like:

```yml

language: cpp

os:
- linux
- osx

env:
  matrix:
    - NODE_VERSION="4"
    - NODE_VERSION="6"

before_install:
- rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm
- source ~/.nvm/nvm.sh
- nvm install $NODE_VERSION
- nvm use $NODE_VERSION
```

See [Travis OS X Gotchas](#travis-os-x-gotchas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix.

Also create platform specific sections for any deps that need install. For example if you need libpng:

```yml
- if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi;
- if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi;
```

For detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml).

##### Travis OS X Gotchas

First, unlike the Travis Linux machines, the OS X machines do not put `node-pre-gyp` on PATH by default. To do so you will need to:

```sh
export PATH=$(pwd)/node_modules/.bin:${PATH}
```

Second, the OS X machines do not support using a matrix for installing different Node.js versions. So you need to bootstrap the installation of Node.js in a cross platform way.

By doing:

```yml
env:
  matrix:
    - NODE_VERSION="4"
    - NODE_VERSION="6"

before_install:
 - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm
 - source ~/.nvm/nvm.sh
 - nvm install $NODE_VERSION
 - nvm use $NODE_VERSION
```

You can easily recreate the previous behavior of this matrix:

```yml
node_js:
  - "4"
  - "6"
```

#### 4) Publish when you want

You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`:

    COMMIT_MESSAGE=$(git log --format=%B --no-merges -n 1 | tr -d '\n')
    if [[ ${COMMIT_MESSAGE} =~ "[publish binary]" ]]; then node-pre-gyp publish; fi;

Then you can trigger new binaries to be built like:

    git commit -a -m "[publish binary]"

Or, if you don't have any changes to make simply run:

    git commit --allow-empty -m "[publish binary]"

WARNING: if you are working in a pull request and publishing binaries from there then you will want to avoid double publishing when Travis CI builds both the `push` and `pr`. You only want to run the publish on the `push` commit. See https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/is_pr_merge.sh which is called from https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/publish.sh for an example of how to do this.

Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on Travis see http://about.travis-ci.org/docs/user/deployment/npm/

# Versioning

The `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed.

 - `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version.
 - `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override.
 - `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override.
 - `libc` matches `require('detect-libc').family` like `glibc` or `musl` unless the user passes the `--target_libc` option to override.
 - `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build.
 - `module_name` - the `binary.module_name` attribute from `package.json`.
 - `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property).
 - `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version`
 - `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that`
 - `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta`

The options are visible in the code at <https://github.com/mapbox/node-pre-gyp/blob/612b7bca2604508d881e1187614870ba19a7f0c5/lib/util/versioning.js#L114-L127>

# Download binary files from a mirror

S3 is broken in China for the well known reason.

Using the `npm` config argument: `--{module_name}_binary_host_mirror` can download binary files through a mirror.

e.g.: Install [v8-profiler](https://www.npmjs.com/package/v8-profiler) from `npm`.

```bash
$ npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/
```

repository: holzschu/a-shell

gha_language: C

repo_name: holzschu/a-shell


text:
---
layout: archive
title: "Projects"
permalink: /projects/
author_profile: true
---

Here are a few of my projects I have work on over the years. These projects are from work, classes, or personal hobby projects.

## HEBI Robotics - Application Designer - Agile Inspection Robots - 2023

* Helped onboard customers with our inspection robots.
* Designed custom robotics solutions in Python & Matlab to support customers needs
* Maintain documentation and manuals for robotics solutions
* Led robotics demos for conferences (i.e. ICRA & ROS) and webinars
* Created YouTube video course tutorials and examples for actuator controls and robot kinematics
* Wrote and pitch, and led government contracts for the Air Force

## Python/Computer Vision - Robot Aimbot - 2022

For a personal project of mine, I made a physical robot that moved a mouse around to shoot targets on the screen. The robot moved using knowledge of where the targets were on the screen and then doing PID control to send a velocity command to the motors.

Software Tools

* Computer Vision - (OpenCV)
* Object Detection (PyTorch - Yolov)
* Controls - PID
* Odometry - Model Omnidirectional Robot

## ROS/GAZEBO - Passive Walking Simulation - 2019

For my graduate research study I deployed a working simulation of a simple passive dynamic walking. Modeling rigid bodies and real world friction parameters.

## Ballbot - Balancing Robot - 2019

Spring  2019 capstone project for 16-264 Humanoids Class at Carnegie Mellon University.

The projects was greatly inspired by [Ballbot](https://www.youtube.com/watch?v=8BtDuzu2WeI) a humanoid size robot made in CMU's Microdynamic Systems Laboratory. Instead of balancing on a ball with a 200mm (7.87 inches) diameter we built our robot to balance on a smaller ball with a 95mm (3.75 inches) diameter.

Robot Control

* Modeled as two decoupled planar systems
* PID (innerloop for ball velocity)
* LQR (outerloop)
* Full State Feedback Control (outer loop)

**Balancing**

Mechanical Design

* Primarily Assembled with Laser Cutting & 3D Printing
* 4 Brushed DC Motors with Encoders
* 3.75 inch dimater ball

**Assembly**

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
path: "/2007/01/30/2007130posting-what-you-can-do-and-what-will-kill-you-html/"
date: "2007-01-30T11:11:00+00:00"
title: Posting what you can do and what will kill you
tags:
  - australia

---
Kathy Sierra has a recent post about how nice it is to see a sign that tells you to do what most signs tell you not to do. There is a sign at the entrance to the Royal Botanic Gardens in Sydney that asks you to please DO walk on the grass. Thats a great sign. But in that same city I saw two signs that were very different on my last trip there. Both had a common theme: don’t do something, but if you do, you’re dead, but if you survive you will wish you were dead.

The first was at the Sydney Aquarium. The hotel I stay at in Sydney is the Sheraton Four Points Darling Harbor. Its a crappy hotel, but it lets me add a bunch of nights to my Starwood Platinum membership and its far cheaper than the 450 or so Australian dollar per night Westin up the street. The aquarium is almost next door and is a very nice facility; combined with the wildlife center next door, it makes for a great way to spend the afternoon. Anyway, above the crocodile enclosure was this sign:

    DO NOT ENTER

    If the fall does not kill you

    the crocodile will

below that was a nice visual of a croc chomping on a falling human. Nice!!!

The other sign I saw was across the harbor towards the ocean. There  was a great sign that warned me that I would probably die from the fall. If on the off chance I actually survived, then I would have to pay someone to get me out.


text:
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [0.3.5] - 2020-05-18

### Changed

- Dependency updates

## [0.3.4] - 2020-03-16

### Changed

- Dependency updates

## [0.3.3] - 2020-01-26

### Changed

- Moved from `yarn` to `npm`.

## [0.3.2] - 2020-01-20

### Changed

- Dependency upgrades

## [0.3.1] - 2020-01-09

### Changed

- Moved chat layouts to be side-by-side with the game and lobby.

## [0.3.0] - 2019-11-22

### Added

- Bots learned how to bid by looking at their hands.
- Bots learned how to pick cards with some logic instead of randomly. They
  don't play perfectly, but they play "good enough" and are aware of nils.
  Note that they don't try to avoid bags.

## [0.2.1] - 2019-11-19

### Added

- Chat windows in the lobby and game rooms. Overall page layout needs to be
  improved, though.

## [0.2.0] - 2019-11-18

### Added

- Dumb bots to play against. They will always bid 3 and play random cards.

## [0.1.1] - 2019-11-17

### Fixed

- Fixed idle rooms not automatically deleting.

## [0.1.0] - 2019-11-16

Initial release. Rough, but playable with 4 people.

[unreleased]: https://github.com/mreishus/spades/compare/v0.3.5...HEAD
[0.3.5]: https://github.com/mreishus/spades/compare/v0.3.4...v0.3.5
[0.3.4]: https://github.com/mreishus/spades/compare/v0.3.3...v0.3.4
[0.3.3]: https://github.com/mreishus/spades/compare/v0.3.2...v0.3.3
[0.3.2]: https://github.com/mreishus/spades/compare/v0.3.1...v0.3.2
[0.3.1]: https://github.com/mreishus/spades/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/mreishus/spades/compare/v0.2.1...v0.3.0
[0.2.1]: https://github.com/mreishus/spades/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/mreishus/spades/compare/v0.1.1...v0.2.0
[0.1.1]: https://github.com/mreishus/spades/compare/v0.1.0...v0.1.1
[0.1.0]: https://github.com/mreishus/spades/releases/tag/v0.1.0

repository: mreishus/spades

gha_language: Elixir

gha_license_id: MIT

repo_name: mreishus/spades


text:
---
date: 2019-06-06
tags: documentation
---

# Precis Setup

## Requirements

Precis has no dependencies other than *git* and these basic *nix commands:

- awk
- cat
- cut
- echo
- grep
- sed
- sh
- sort
- tr
- xargs

Most of these commands are installed by default. Otherwise, please install them using your operating system's package manager.

## Installation

- Fork or clone [this repo](https://github.com/abhin4v/precis) from Github.
- Delete all the markdown files:

```shell
$ rm *.md *.markdown tags/*.md
```

- Push to your own repo on Github.
- Enable Github pages for your repo in the repo settings with _master branch_ as the source.

## Usage

- Add a git pre commit hook with the following command:

```shell
bin/mk-site
```

- Modify `_config.yml` file with correct values as per your setup:

```yaml
# the name for your notes website
name: Precis

# the description of the notes website
description: Precis is a minimal note taking web-app built over Github Pages.
```

- Write notes in Markdown in the root directory of your repo. Upon committing the files in git, home page and tag pages will be auto-generated.
- Push to Github and wait for few minutes for the notes to be published.

## Notes Format

You can use [Github flavoured Markdown] to write your notes. You can add date and tags to the notes using the Markdown front-matter format.

A sample note:

```markdown
---
date: 2019-06-06
tags: meeting office
---

# Meetings Notes

- need to do things
- need to do more things
```

See [this demo note](./demo-note) to get a look and feel.

[Github flavoured Markdown]: https://guides.github.com/features/mastering-markdown/

extension: markdown

gha_language: SCSS


text:
# “Couldn't match expected type with actual type” error when using Codec.BMP

## Question

I have a very little experience in Haskell and I want to write a simple ray tracer for practice. Because I didn't want to use GUI tools like wxHaskell (I think it'll take a lot of time to learn how to use them), I decided to simply save the output image to BMP file. But I have a problem here:

    module Main where

    import Codec.BMP
    import qualified Data.ByteString as BS

    main = do
      Right bmp <- readBMP "grass.bmp"
      BS.putStrLn $ BS.take 4 $ unpackBMPToRGBA32 bmp

Here I just want to take first pixel of the image and print its RGBA values. But I get an error saying

    Couldn't match expected type `BS.ByteString'
                with actual type `bytestring-<IP_ADDRESS>:Data.ByteString.Internal.ByteString'
    In the return type of a call of `unpackBMPToRGBA32'
    In the second argument of `($)', namely `unpackBMPToRGBA32 bmp'
    In the second argument of `($)', namely
      `BS.take 4 $ unpackBMPToRGBA32 bmp'

What am I doing wrong? How can I take the pixels of the image and print their values?

## Answer

You have two `bytestring` packages installed, so `unpackBMPToRGBA32` return `ByteString` from `bytestring-<IP_ADDRESS>`, and `BS.putStrLn` expects `ByteString` from other version.

Try `ghc-pkg list bytestring` to list all `bytestring` versions installed.

And the solution could be

*   unregister one of them with `ghc-pkg unregister bytestring-<version>`
*   hide one of them when building: `ghc --make -hide-package bytestring-<version>`

repository: stackflow-io/stackflow

repo_name: stackflow-io/stackflow


text:
Distributed-Compressor-Decompressor---DCD--
===========================================

Distributed Compressor / Decompress-or [DCD] will perform file compression / decompression in distributed fashion.

The file compression / decompression will be accomplished by ZLIB library.
Interesting fact about this tool is that, it manages to accomplish the task
under distributed fashion, thereby taking more load in parallel.

Typical applications would be using this tool to quickly compress the files, before uploading to storage servers etc.

Following binaried planned for this project.

1) Client tool ---> Which takes the file name as input and trigger the task to server.
2) Server tool ---> Which runs in multithreaded mode to parallely compress files in distributed fashion.
3) Server peers tool --> Which runs in sync with other server peers [either in same machine / different machines], communicates via IPC / RPC / Sockets to share the load.
4) Monitoring tool / webpage to present the status of the server peers.


text:
# Eloquent Filter [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Eloquent%20Filter%20adds%20custom%20filters%20to%20your%20Eloquent%20Models%20in%20Laravel%26url%3Dhttps%3A%2F%2Fgithub.com%2Fmehdi-fathi%2Feloquent-filter%26via%3Dmehdi-fathi%26hashtags%3Dlaravel%2Celoquent%2Cphp%2Cmysql%2Cdatabase%2Celoquentfilter)

![alt text](./eloquent-filter.jpg "eloquent-filter")

[![Latest Stable Version](https://img.shields.io/packagist/v/mehdi-fathi/eloquent-filter)](https://packagist.org/packages/mehdi-fathi/eloquent-filter)
![Run tests](https://github.com/mehdi-fathi/eloquent-filter/workflows/Run%20tests/badge.svg?branch=master)
[![License](https://poser.pugx.org/mehdi-fathi/eloquent-filter/license)](https://packagist.org/packages/mehdi-fathi/eloquent-filter)
[![GitHub stars](https://img.shields.io/github/stars/mehdi-fathi/eloquent-filter)](https://github.com/mehdi-fathi/eloquent-filter/stargazers)
[![Monthly Downloads](https://img.shields.io/packagist/dm/mehdi-fathi/eloquent-filter?color=blue)](https://packagist.org/packages/mehdi-fathi/eloquent-filter)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/mehdi-fathi/eloquent-filter/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/mehdi-fathi/eloquent-filter/?branch=master)
[![codecov](https://codecov.io/gh/mehdi-fathi/eloquent-filter/branch/develop/graph/badge.svg?token=QY9HA6NXFH)](https://codecov.io/gh/mehdi-fathi/eloquent-filter)

We are excited to introduce Eloquent Filter, a power-full composer package for filtering data of models by inputs like query strings in Laravel.
It's easy to use and fully dynamic.

- Support complex queries
- Straightforward ways to override conditions based on your desire
- Having awesome harmonic with Laravel, Eloquent even with query builder as a new feature
- Take control of every step of running

**Note** We considered what predictable features you wanted to implement no matter simple or complex, although we have a lot of features to make able you to implement your specific something's else.

## Table of Content

- [Introduction](#microphone-introduction)
- [Installation](#electric_plug-installation)
- [Basic Usage](#book-basic-usage)
    - [Config Model](#config-model-and-set-whitelist)
    - [Use in Controller](#use-in-controller)
    - [Simple Examples](#simple-examples)
    - [Custom Query Filter](#custom-query-filter)
    - [Custom Detection Condition](#custom-detection-condition)
- [Configuring](#configuring)
    - [Publish Config](#publish-config)
    - [Config](#config)
    - [Alias](#alias)
- [Query Builder](#query-builder)
  - [Introduction](#db-introduction)
- [Magic Methods](#magic-methods)
    - [Request Filter](#request-filter)
    - [Response Filter](#response-filter)
    - [Macro Methods](#macro-Methods)
    - [Black List Detections](#black-list-detections)

## Requirements
- PHP 8.0,8.1,8.2
- Laravel 8.x,9.x,10.x(New)

### Version information

The Eloquent Filter has reached more than 100,000 installations recently, so I made a decision to release version 4.0 with 2 new features.

The current version supports:

- Support query builder along with eloquent
- Set a specific name fo custom methods

| Version | Illuminate    | Status         | PHP Version |
|---------|---------------|----------------|-------------|
| ^4.0    | 4.x.x - 4.x.x | Active support | >= 8.0      |
| ^3.0    | 3.2.x - 3.4.x | End of life    | >= 8.0      |
| ^3.0    | 3.0.0 - 3.0.5 | End of life    | >= 7.4.0    |
| ^2.0    | 2.0.0 - 2.6.7 | End of life    | <= 7.4.0    |

## :microphone: Introduction

Conceivably, you would face challenges if you've done a task as an end-point in which there are some queries with many advanced options.

Let's say we want to make an advanced search page with multiple filter options.

![alt text](https://raw.githubusercontent.com/mehdi-fathi/mehdi-fathi.github.io/master/eloquent-filter/assets/img/Esfand-05-1399%2022-23-21.gif "sample 1 eloquent-filter")

### A simple implementation without Eloquent Filter
The Resource URI would be look like:

    /users/index?age_more_than=25&gender=male&created_at=25-09-2019

And a simple implementation in the Controller would look like :

```php
<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::where('is_active', true);

        if ($request->has('age_more_than')) {
            $users->where('age', '>', $request->age_more_than);
        }

        if ($request->has('gender')) {
            $users->where('gender', $request->gender);
        }

        if ($request->has('created_at')) {
            $users->where('created_at','>=', $request->created_at);
        }

        return json_encode($users->get());
    }
}
```
This solution is simple and that works well but not for an enterprise project.
But you'd have to add a condition for each filter you need.
Especially if you would make more complex filtering, your code can become a monster quickly! :boom:

Hence, Eloquent Filter is ready for to you get rid of complexity in addition to saving time.

### A simple implementation with Eloquent Filter

Eloquent Filter can help you to fix that ``problem. Just you will set query string to work with that.
It would make your own query automatically and systematically while you can control them.

Right After installing Eloquent Filter, the request URI would be like this:

    /users/list?age_more_than[operator]=>&age[value]=35&gender=male&created_at[operator]==>&created_at[value]=25-09-2019

And in the Controller, You just need that one line:
```php
/**
 * Class UsersController.
 */

namespace App\Http\Controllers;

use App\User;

class UsersController
{
    public function list()
    {
        return User::filter()->get();
    }
}
```
By Eloquent filter implementation, you can use all the documented filters!

## :electric_plug: Installation

1- Run this Composer command to install the latest version

        $ composer require mehdi-fathi/eloquent-filter

- **Note**  for Laravel versions older than 5.8 you should install version 2.2.5

        $ composer require mehdi-fathi/eloquent-filter:2.2.5

- **Note** We support auto-discovery but you can check them.

2- Add `eloquentFilter\ServiceProvider::class` to provider app.php

   ```php
   'providers' => [
     /*
      * Package Service Providers...
      */
       eloquentFilter\ServiceProvider::class
   ]
   ```
3- Add Facade `'EloquentFilter' => eloquentFilter\Facade\EloquentFilter::class` to aliases app.php

```php
'alias' => [
  /*
   * Facade alias...
   */
    'EloquentFilter' => eloquentFilter\Facade\EloquentFilter::class,
],
```
That's it enjoy! :boom:
## :book: Basic Usage

### Config Model and set whitelist

Add the `Filterable` trait to yourself models and set fields in the whitelist array in which you will want to use of filter .
You can override this method in your models as well.

```php
use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;

    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];
}
```
- You can set `*` char for that filter in all fields aslike below example:

```php
private static $whiteListFilter = ['*'];
```
You able add or set `$whiteListFilter` on the fly in your method. For example:

***Set array to WhiteListFilter***

- **Note** This method override `$whiteListFilter` array
```php
User::setWhiteListFilter(['name']);
```
***Add new field to WhiteListFilter***
```php
User::addWhiteListFilter('name');
```

### Use in Controller

Change your code the controller of the laravel project as like below example:

```php

namespace App\Http\Controllers;

/**
 * Class UsersController.
 */
class UsersController
{

    public function list()
    {
          if (!empty(request()->get('username'))) {

              $users = User::ignoreRequest('perpage')
                        ->filter()
                        ->with('posts')
                        ->orderByDesc('id')
                        ->paginate(request()->get('perpage'),['*'],'page');

          } else {
              $users = User::filter(
                ['username' => ['mehdi','ali']]
                )->with('posts')
                ->orderByDesc('id')
                ->paginate(10,['*'],'page');
          }
    }
}
```
-**Note** The Eloquent Filter config by default uses the query string to make queries in Laravel.
 Although, you can set the collection data in the `filter` method Model for making your own custom condition without query string.

-**Note**  Therefore you must unset yourself param as perpage. Just you can set page param for paginate this param ignore from the filter.

- You can ignore some request params via use of the bellow code.

```php

User::ignoreRequest(['perpage'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');
```

Call `ignoreRequest` that will ignore some requests that you don't want to use in conditions of eloquent filter.
e.g: the perpage param will never be in the conditions eloquent filter.
it's related to the paginate method. `page` param ignore by default in Eloquent Filter of Laravel.

- You can filter some request params as acceptable filter.

```php

User::AcceptRequest(['username','id'])
            ->filter()
            ->paginate(request()->get('perpage'), ['*'], 'page');
```

Call `AcceptRequest` will accept requests in which you want to use in conditions Eloquent Filter.
e.g: `username` and `id` key will be in the conditions eloquent filter.

-**Note** Just in case, you must set `$whiteListFilter` in Models. Aim of the method avert to manipulation query string by a bad user.

### Simple Examples

You just pass data form as query string. For example:

**Simple Where**
```
<EMAIL_ADDRESS>
SELECT ... WHERE ... email =<EMAIL_ADDRESS>```

```
/users/list?first_name=mehdi&last_name=fathi

SELECT ... WHERE ... first_name = 'mehdi' AND last_name = 'fathi'
```

- If you send date format `Y-m-d` we will work like `WhereDate()` method Laravel.

***Where In***

This example make method `whereIn`.

```
/users/list?username[]=ali&username[]=ali22&family=ahmadi

SELECT ... WHERE ... username in ('ali','ali22') AND family = 'ahmadi'
```

***OrWhere***

This example make method `orWhere()`.

```
/users/list?name=mehdi&username=fathi&or[username]=ali

SELECT ... WHERE ... name = 'mehdi' AND username = 'fathi' or username = 'ali'
```

***Where like***

If you are going to make a query by like conditions. You can do that by this example.

```
/users/list?first_name[like]=%John%

SELECT ... WHERE ... first_name LIKE '%John%'

```

***Where by operator***

You can set any operator mysql in the queries string.

```
/users/list?count_posts[operator]=>&count_posts[value]=35

SELECT ... WHERE ... count_posts > 35
```
```
/users/list?username[operator]=!=&username[value]=ali

SELECT ... WHERE ... username != 'ali'
```
```
/users/list?count_posts[operator]=<&count_posts[value]=25

SELECT ... WHERE ... count_posts < 25
```

**Where the nested relations Model**

You can set all nested relations in the query string just via the array of query string. imagine, the user model has a relation with posts.
And posts table has a relation with orders table.

You can make query conditions by set `posts[count_post]` and `posts[orders][name]` in the query string.

- Just be careful you must set `posts.count_post` and `posts.orders.name` in the User model.

```php
use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;

    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

}
```

```
/users/list?posts[count_post]=876&username=mehdi

select * from "users" where exists
         (select * from "posts" where "posts"."user_id" = "users"."id"
         and "posts"."count_post" = 876)
         and "username" = "mehdi"
```
- The above example is the same code that you used without the eloquent filter. Check it under code. It's not amazing?

```php
$builder = (new User())->with('posts');
        $builder->whereHas('posts', function ($q) {
            $q->where('count_post', 876);
        })->where('username','mehdi');

```

***Where array the nested relation Model***

You can pass array to make whereIn condition.

```
/users/list?posts[category][]=php&posts[category][]=laravel&posts[category][]=jquery&username=mehdi

select * from "users" where exists
         (select * from "posts" where
         "posts"."category" in ('php','laravel','jquery') )
         and "username" = "mehdi"
```

****Special Params****

You can set special params `limit` and `orderBy` in the query string to make a query by that.
```
/users/list?f_params[limit]=1

SELECT ... WHERE ... order by `id` desc limit 1 offset 0
```
```
/users/list?f_params[orderBy][field]=id&f_params[orderBy][type]=ASC

SELECT ... WHERE ... order by `id` asc
```
```
/users/list?f_params[orderBy][field]=id,count_posts&f_params[orderBy][type]=ASC

SELECT ... WHERE ...  order by `id` asc, `count_posts` asc
```
***Where between***

If you are going to make a query based on date, You must fill keys, `start`, and `end` in the query string.
Hence You can set it as a query string. These params are used for the filter by date.

```
/users/list?created_at[start]=2016/05/01&created_at[end]=2017/10/01

SELECT ... WHERE ... created_at BETWEEN '2016/05/01' AND '2017/10/01'
```

****Advanced Where****
```
/users/list?count_posts[operator]=>&count_posts[value]=10&username[]=ali&username[]=mehdi&family=ahmadi&created_at[start]=2016/05/01&created_at[end]=2020/10/01
&f_params[orderBy][field]=id&f_params[orderBy][type]=ASC

select * from `users` where `count_posts` > 10 and `username` in ('ali', 'mehdi') and
`family` = ahmadi and `created_at` between '2016/05/01' and '2020/10/01' order by 'id' asc limit 10 offset 0
```

Therefore, fields of query string are same rows table database in `$whiteListFilter` in your model or declare the method in your model as override method.
The overridden method can be considered a custom query filter.

### Custom Query Filter

Eloquent Filter doesn't support all the conditions by default. For this situation, you can make an overridden method.
If you are going to make yourself a query filter, you can do it easily.
You should take care of using `filterCustom` before method name in new version.

You should run the command to make a trait and use it on the model:

    php artisan eloquentFilter:filter users

```php
namespace App\ModelFilters;

use Illuminate\Database\Eloquent\Builder;

/**
 * Trait UsersFilter.
 */
trait UsersFilter
{
    /**
     * This is a sample custom query
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param                                       $value
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function filterCustomSample_like(Builder $builder, $value)
    {
        return $builder->where('username', 'like', '%'.$value.'%');
    }
}
```

-**Note** These fields of query string are the same methods of the trait. Use trait in your model:

```
/users/list?sample_like=a

select * from `users` where `username` like %a% order by `id` desc limit 10 offset 0
```

```php

use App\ModelFilters\UsersFilter;

class User extends Model
{
    use UsersFilter,Filterable;

    protected $table = 'users';
    protected $guarded = [];
    private static $whiteListFilter =[
        'id',
        'username',
        'email',
        'created_at',
        'updated_at',
    ];

}
```

### Some Filter methods
```php
User::filter()->paginate();
```
- `EloquentFilter::filterRequests()` : get all params that used by the Eloquent Filter.
  You can set key to get specific index.
  For example `EloquentFilter::filterRequests('username')` it's getting username index.

- `EloquentFilter::getAcceptedRequest()` : get all params that set by the AcceptRequest method.

- `EloquentFilter::getIgnoredRequest()` : get all ignored params that set by the getIgnoreRequest method.

### Custom Detection Conditions

Sometimes you want to make your custom condition to make a new query that Eloquent Filter doesn't support by default.
The good news is you would make a custom condition in the eloquent filter from now on.

You can make conditions to generate a new query after checking by that. For example:

We must have two classes. The First detects conditions second class generates the query.

- Step 1: Create a class to detect some conditions

```php

use eloquentFilter\QueryFilter\Detection\Contract\DetectorConditionsContract;

/**
 * Class WhereRelationLikeCondition.
 */
class WhereRelationLikeCondition implements DetectorConditionsContract
{
    /**
     * @param $field
     * @param $params
     * @param $is_override_method
     *
     * @return string|null
     */
    public static function detect($field, $params, $is_override_method = false): ?string
    {
        if (!empty($params['value']) && !empty($params['limit']) && !empty($params['email'])) {
            $method = WhereRelationLikeConditionQuery::class;
        }

        return $method ?? null;
    }
}
```

- Step 2:Right after, create a class to generate a query. In this example we make `WhereRelationLikeConditionQuery` class:

```php
use eloquentFilter\QueryFilter\Queries\BaseClause;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class WhereRelationLikeConditionQuery.
 */
class WhereRelationLikeConditionQuery extends BaseClause
{
    /**
     * @param $query
     *
     * @return Builder
     */
    public function apply($query): Builder
    {
        return $query
            ->whereHas('posts', function ($q) {
                $q->where('comment', 'like', "%" . $this->values['like_relation_value'] . "%");
            })
            ->where("$this->filter", '<>', $this->values['value'])
            ->where('email', 'like', "%" . $this->values['email'] . "%")
            ->limit($this->values['limit']);
    }
}
```
- Step 3: You make the method `EloquentFilterCustomDetection` for return array detections of the condition in the model.

```php
use eloquentFilter\QueryFilter\ModelFilters\Filterable;

class User extends Model
{
    use Filterable;

    private static $whiteListFilter =[
        'username',
        'posts.count_post',
        'posts.category',
        'posts.orders.name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function posts()
    {
        return $this->belongsTo('Models\Post');
    }

    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class
        ];
    }

}
```

- Each of the query params is used to detect in `WhereRelationLikeCondition` for the first time after that check by default detection eloquent filter.

Make method `EloquentFilterCustomDetection` in the above example and return array conditions class.

```
/users/list?username[value]=mehdi&username[limit]=10&username[email]=mehdifathi&username[like_relation_value]=mehdi&count_posts=10

select * from "users"
 where exists (select * from "posts" where
"users"."post_id" = "posts"."id"
and "comment" like ?) and "username" <> ? and "email" like ? and "count_posts" = ? limit 10
```
You just run code ` User::filter();` for see result.

- `Model::setLoadInjectedDetection(false)` : You can deactivate custom detection conditions on the fly.

-**Note** as well, you can set custom detection on the fly by use of the method `SetCustomDetection`. For example :

```php
$users = User::SetCustomDetection([WhereRelationLikeCondition::class])->filter();
```

-**Note** You can disable `EloquentFilterCustomDetection` on the fly by this code :

```php
 User::SetLoadDefaultDetection(false)->filter();
```

-**Note** You can set many detection conditions. e.g:

```php

class User extends Model
{
    use Filterable;
    public function EloquentFilterCustomDetection(): array
    {
        return [
            WhereRelationLikeCondition::class,
            WhereRelationLikeVersion2Condition::class,
            WhereRelationLikeVersion3Condition::class,
        ];
    }
}
```

- `EloquentFilter::getInjectedDetections()` gets all of your customs injected detection.

-**Note** Every custom detection will run before any detections by default eloquent filter.

## Configuring

You can generate a config file to configure Eloquent Filter.

### Publish Config

    php artisan vendor:publish --provider="eloquentFilter\ServiceProvider"

### Config

- You can disable/enable Eloquent Filter in the config file (eloquentFilter.php).

        'enabled' => env('EloquentFilter_ENABLED', true),

- Eloquent Filter recognizes every param of the queries string.
  Maybe you have a query string that you don't want to recognize by Eloquent Filter. You can use `ignoreRequest` for his purpose.
  But we have a clean solution to this problem. You can set param `request_filter_key` in the config file.
  Therefore, every query string will recognize by the `request_filter_key` param.

        'request_filter_key' => '', // filter

For example, if you set `'request_filter_key' => 'filter',` that Eloquent Filter recognizes `filter` query string.

`
<EMAIL_ADDRESS>

- You can disable/enable all the custom detection of Eloquent Filter in the config file (eloquentFilter.php).

        'enabled_custom_detection' => env('EloquentFilter_Custom_Detection_ENABLED', true),

- You should set an index array `ignore_request` to ignore all filters.

        'ignore_request' => [] //[ 'show_query','new_trend' ],

- You had better keep `max_limit`. It's a limitation for preventing making awful queries mistakenly by the developer or intentionally by a villain user.

        'max_limit' => 20

### Alias

Sometimes you may want to change some parameters in the URL while those mention a field of the model.
e.g. name of the input form is not similar to the model ,or you want to change them for other reasons so the alias as a new feature can be useful.

```php

    class Stat extends Model
    {
        use Filterable;
        /**
         * @var array
         */
        private static $whiteListFilter = [
            'type',
            'national_code',
        ];

        /**
         * @var array
         */
        private $aliasListFilter = [
            'national_code' => 'code',
        ];
    }

```

Then you should send the `code` param in the URL for making a query with the national code field of the model readily.

# Query Builder Introduction

Great news!

Some people asked me a lot to add new feature to support Laravel query builder.
It needed a lot of energy and devoting time , so I decided to implement it.
It's quite tough however finally it's almost done now.

We are supporting query builder along with eloquent from now on. Not only you would use query builder ,but also you can use eloquent at the same time.

It's a new feature ,and I'm snowed under the code to fix issues. Anyway this feature is up right now with just some limitation.
We don't support `WhereCustomCondition` and `WhereHas` for query builder at the moment but other conditions were ready to use.
in addition, we don't have any kind of `whitelist` , `blacklist` , `custom detectioon` or `alias`.
currently , It's just a simple feature.

- Below is an order checking conditions list if you use name of them for set a black list.

| Name                  | Method eloquent | Example                                  |
|-----------------------|-----------------|------------------------------------------|
| SpecialCondition      |                 | support f_params, e.g: limit and order   |
| WhereBetweenCondition | whereBetween    |                                          |
| WhereByOptCondition   | where           | where('column', ">", $value)             |
| WhereLikeCondition    | where           | where('column', 'like', $value)          |
| WhereInCondition      | whereIn         | whereIn('column', $value)                |
| WhereOrCondition      | orWhere         | orWhere('column', $value)                |
| WhereDateCondition    | whereDate       | whereDate('column', $value)              |
| where                 | where           | where('column', $value)                  |

- Usage of them is just extremely like model just you need use filter as a method. Obviously, there's no need any change like use trait or etc.

```php
 DB::table('users')->filter();
```

## Magic Methods

Magic methods are a collection of methods that you can use as a wrapper in the Eloquent Filter.
For example, serialize data before filtering or changing data in response and others.
Now Eloquent Filter have `serializeRequestFilter`,`ResponseFilter`.

### Request Filter

Eloquent Filter has a magic method for just change requests injected before handling by eloquent filter. This method is
SerializeRequestFilter. You just implement `SerializeRequestFilter` method in your Model. For example

```php

class User extends Model
{
    use Filterable;
    public function serializeRequestFilter($request)
    {
       $request['username'] = trim($request['username']);
       return $request;
    }
}
```

As above code, you can modify every query params of the Model in the method `serializeRequestFilter` before running by Eloquent Filter.
That is a practical method when you want to set user_id or convert date or remove space and others.

### Response Filter

Response Filter is an overriding method for changing response right after handle by Eloquent Filter. The method called
`getResponseFilter` and You could implement the method `getResponseFilter` in your Model. e.g:

```php

class User extends Model
{
    use Filterable;
    public function getResponseFilter($response)
    {
        $data['data'] = $response;
        return $data;
    }
}
```

### Black List Detections

Obviously, you never want all users who are able to get data by manipulating requests. As a result, we'd better have
an eloquent control feature.
Although we have this ability on request side, we need this feature on Eloquent side as well.

We would set a blacklist detection to prevent making conditions by using it. Therefore, that list has been disabled in making conditions. for example:

```php

namespace App\Http\Controllers;

/**
 * Class UsersController.
 */
class UsersController
{

    public function list()
    {
              $users = User::setBlackListDetection(
                  [
                      'WhereCondition',
                  ]
                )->filter()
                ->orderByDesc('id')
                ->paginate();
    }
}
```

- Below is an order checking conditions list if you use name of them for set a black list.

| Name                  | Method eloquent | Example                                  |
|-----------------------|-----------------|------------------------------------------|
| WhereCustomCondition  |                 | Your declared custom method of Model     |
| SpecialCondition      |                 | support f_params, e.g: limit and order   |
| WhereBetweenCondition | whereBetween    |                                          |
| WhereByOptCondition   | where           | where('column', ">", $value)             |
| WhereLikeCondition    | where           | where('column', 'like', $value)          |
| WhereInCondition      | whereIn         | whereIn('column', $value)                |
| WhereOrCondition      | orWhere         | orWhere('column', $value)                |
| WhereHas              | WhereHas        |                                          |
| WhereDateCondition    | whereDate       | whereDate('column', $value)              |
| where                 | where           | where('column', $value)                  |

- You are able to set on Model layer as well. `black_list_detections` array is used for this purpose.

```php
<?php

namespace Tests\Models;

use eloquentFilter\QueryFilter\ModelFilters\Filterable;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    use Filterable;

    private static $whiteListFilter = '*';

    protected $black_list_detections = [
        'WhereCondition',
    ];
}
```

### Macro Methods

-`isUsedEloquentFilter` is a macro method for builder to check either query used eloquent-filter.

-`getDetectionsInjected` is a macro method to get list array of injected objects.

e.g:

```php
        $users = User::SetCustomDetection([WhereRelationLikeCondition::class])->filter();
        echo $users->isUsedEloquentFilter(); // will true
        echo $users->getDetectionsInjected(); // will showing a list array of injected objects
```

## Contributing

If you'd like to contribute to Eloquent Filter, please fork the repository and create a pull request. We welcome contributions of all kinds, including bug fixes, new features, and documentation improvements.

## License

Eloquent Filter is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT).

## Contact

If you have any questions or feedback about Eloquent Filter, please feel free to contact us at<EMAIL_ADDRESS>We'd love to hear from you!

## Acknowledgements

We'd like to thank the Laravel community for their support and contributions to this project.

repository: mehdi-fathi/eloquent-filter

gha_language: PHP

repo_name: mehdi-fathi/eloquent-filter


text:
---
layout: post
title:  "Arrays and Hashes"
date:   2015-9-06 10:54:34
categories: technical
---

#Overview#

According to Chapter 9 in "The Well-Grounded Rubyist" by David A. Black, arrays and hashes are collection and container objects and what he means by this is that both hold stuff! Both hold many different values that can can be selected easily in one singular place.

#Arrays#

Arrays are a list of items that are ordered. This doesn't mean that Ruby sorts them but rather Ruby knows where each value is. This means that if you have an array of grocery items:

{% highlight ruby %}
grocery = ['apples', 'bread', 'milk']
{% endhighlight %}

you can select each one of these items individually. For Example,

{% highlight ruby %}
grocery[0]
{% endhighlight %}

is going to give you apples back as a value. This is really convinient because you can always use every part of your list in a very logical way.  Hashes are a list of what Ruby calles "value" and "key" pairs. Every key has a value that you can retrieve with it. This is helpful when you have a long value and you want to expedite your coding or format key inputs to values for people. First is a bit of hash syntax:

{% highlight ruby %}
state_hash = {"California" => "CA", "Maryland" => "MD"}
{% endhighlight %}

gha_language: HTML


text:
# Thumbnail Auto Crop

The IMDB ([OMDB](https://www.omdbapi.com/)) API provides a thumbnail image when querying
something like a TV show episode. Most times the image is not in a 16:9 aspect ratio
though, and manually cropping thumbnails for several seasons of a TV show is tedious.
This program automates the cropping of the thumbnails by detecting faces in the images
and cropping them in frame.

## Example
### Input
![](https://i.imgur.com/Dxk43NU.png)

### Cropped output image (with debug info)
![](https://i.imgur.com/24kI5yj.png)

repository: jayden-chan/thumbnail-auto-crop

repo_name: jayden-chan/thumbnail-auto-crop


text:
---
layout: default
---

# 1994-03-17 - Re: (fwd) Re: What's so bad about a Surveillance State?

## Header Data

From<EMAIL_ADDRESS>(Timothy C. May)

To<EMAIL_ADDRESS>Message Hash: 9c928f57b57b74f4aa9ef15156f388b1e8be3f0d1133710e9e3b89229b626480

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1994-03-17 18:03:00 UTC

Raw Date: Thu, 17 Mar 94 10:03:00 PST

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(Timothy C. May)
Date: Thu, 17 Mar 94 10:03:00 PST
To<EMAIL_ADDRESS>Subject: Re: (fwd) Re: What's so bad about a Surveillance State?
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

Citizen-Unit Miller wastes more of the social body's time by writing:

> > Citizen-Unit Miller is to be commended for his
> > recognition that the common good is served when the state
> > fulfills its surveillance obligations.
>

> > [more funny stuff deleted]
>
> I enjoyed Tim May's post.  I'm hoping you all realize my post was
> simply an electronic stick jabbed into the hornet's nest.

Thanks, Unit Jim! This citizen-unit did indeed realize your
motivations, especially as you went on to explain them (in the section
I carefully elided!).

"What's wrong with a surveillance state?" is so easily answered with
satire, with an "if this goes on" analysis, that I couldn't resist.
All of the arguments are well-know to cypherpunks, of course, but Jim
posted his call for comments to various newsgroups, where the
arguments are either not as well known or are confused by comments
from didactic shills like David Sternlight and Steve Pope.

> I do *not* think a surveillance state is a good thing.  I
> deliberately constructed my post to get people's attention.  I want
> people (other than just Cypherpunks) to think about life in a
> surveillance state.
>

Good luck to Jim, I suppose. Me, I've been so opposed to the Big
Brother state since 1966 (when I first read "1984"), that I can't
conceive of sitting down to make arguments about the "benefits" of
such a surveillance state.

I'll stick to humor of color.

--Tim May

--
..........................................................................
Timothy C. May         | Crypto Anarchy: encryption, digital money,
<EMAIL_ADDRESS>     | anonymous networks, digital pseudonyms, zero
408-688-5409           | knowledge, reputations, information markets,
W.A.S.T.E.: Aptos, CA  | black markets, collapse of governments.
Higher Power: 2^859433 | Public Key: PGP and MailSafe available.
"National borders are just speed bumps on the information superhighway."

{% endraw %}
```

## Thread

+ Return to [March 1994](/archive/1994/03)

+ Return to<EMAIL_ADDRESS>(Jim Miller)](/authors/jim_at_bilbo_suite_com_jim_miller_)"
+ Return to<EMAIL_ADDRESS>(Timothy C. May)](/authors/tcmay_at_netcom_com_timothy_c_may_)"

+ 1994-03-16 (Wed, 16 Mar 94 09:22:32 PST) - [Re: (fwd) Re: What's so bad about a Surveillance State?](/archive/1994/03/dd71bd783965d199af6f301fd4354ce85dffea62d6101f3646be1134be2b97f7) -<EMAIL_ADDRESS>(Jim Miller)_
  + 1994-03-17 (Thu, 17 Mar 94 10:03:00 PST) - Re: (fwd) Re: What's so bad about a Surveillance State? -<EMAIL_ADDRESS>(Timothy C. May)_


text:
# Tic-tac-toe written in Prolog

This program is the first larger dialogical logic program I've written.
It's describing a perfect play of tic-tac-toe.

Dialogical logic programming treats proof-search as a game-tree-search.
This can be used to write programs that refuse to interact
if it cannot be proven that there would be a desirable outcome.

The program is configured to do a perfect play, eg. Either a win or tie.
If you adjust the option of tie away, it refuses to play.
You may also loosen the constraints and you may make it to
prevent itself from winning or disregard the outcome.

I believe that the approach of building this kind of a program
can be generalised to arbitrary programs.

This program has been tested in SWI-Prolog.

## How to play

    ?- consult('tictactoe.pro').
    ?- play.

## Example gameplay

    ?- play.
    ...
    x..
    ...
    Available moves:[move(o,2,2),move(o,2,1),move(o,2,0),move(o,1,2),move(o,1,1),move(o,1,0),move(o,0,2),move(o,0,0)]
    Give your move:
    |: move(o, 1,1).
    ...
    xo.
    x..
    Available moves:[move(o,2,2),move(o,2,1),move(o,2,0),move(o,1,2),move(o,1,0),move(o,0,0)]
    Give your move:
    |: move(o, 0, 0).
    o..
    xo.
    x.x
    Available moves:[move(o,2,1),move(o,2,0),move(o,1,2),move(o,1,0)]
    Give your move:
    |: move(o, 2, 0).
    o.o
    xo.
    xxx
    I won.


text:
# BeerGear

[![GitHub license](https://img.shields.io/crates/l/rustc-serialize.svg)](https://github.com/prshntpnwr/BeerGear/blob/master/LICENSE.txt)

BeerGear is simple shopping cart based Android Application.

## Used Libraries:
- Kotlin as main development language
- MVVM as architecture component
- Room for data persistence
- Retrofit for making Network calls
- Jetpack Navigation for fragment transactions
- Paging Library from loading data gradually
- Glide for image caching and loading
- AndroidX components
- Lottie Animations
- Updated Material design guidlines. Used collapsing Toolbar, Carview and Recyclerview etc.

## License

Copyright 2020 Prashant Panwar

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

repository: prshntpnwr/BeerGear

repo_name: prshntpnwr/BeerGear


text:
# Headings

Markdown offers two styles of headings: Setext and atx.

- Setext-style headings for `h1` and `h2` are created by “underlining” with equal signs `=` and hyphens `-`, respectively.
- To create an atx-style heading, you put 1-6 hash marks `#` at the beginning of the line — the number of hashes equals the resulting HTML heading level.

branch_name: refs/heads/gh-pages

gha_language: JavaScript


text:
---
layout: post
title: "C++ String"
description: ""
category: C++
tags: []
---
{% include JB/setup %}

整理自：_Thinking in C++, Volume 2_

-----

## 1. Creating strings

To use strings you include the C++ header file `<string>`. The `string` class is also in the namespace `std`.

```cpp
string imBlank;
string heyMom("Where are my socks?");
string standardReply = "Beamed into deep "
	"space on wide angle dispersion?";	// concat string literals
string useThisOneAgain(standardReply);

// Copy the first 8 chars:
string s4(s1, 0, 8);

// concat
string quoteMe = s4 + "that";

string source("xxx");
string s(source.begin(), source.end()); // string iterator
assert(s == source);

string okay(5, 'a'); // initialize a string with a number of copies of a single character
assert(okay == string("aaaaa"));
```

## 2. Operating on strings

### 2.1 Appending, inserting, and concatenating strings

```cpp
#include <string>
#include <iostream>
using namespace std;

int main() {
    string bigNews("I saw Elvis in a UFO. ");
    cout << bigNews << endl;

	// How much data have we actually got?
    cout << "Size = " << bigNews.size() << endl;
    cout << "Length = " << bigNews.length() << endl; // .length() and .size() are identical
	// How much can we store without reallocating?
    cout << "Capacity = " << bigNews.capacity() << endl;

	// Insert this string in bigNews immediately
	// before bigNews[1]:
    bigNews.insert(1, " thought I");
    cout << bigNews << endl;
    cout << "Size = " << bigNews.size() << endl;
    cout << "Capacity = " << bigNews.capacity() << endl;

	// Make sure that there will be this much space
    bigNews.reserve(500); // 注意是 reserve 不是 reverse

	// Add this to the end of the string:
    bigNews.append("I've been working too hard.");
    cout << bigNews << endl;
    cout << "Size = " << bigNews.size() << endl;
    cout << "Capacity = " << bigNews.capacity() << endl;

    // appends spaces if the new size is greater than the current string size or truncates the string otherwise
    bigNews.resize(10);
    cout << bigNews << endl;
    cout << "Size = " << bigNews.size() << endl;
    cout << "Capacity = " << bigNews.capacity() << endl;
}

// output:
/*
	I saw Elvis in a UFO.
	Size = 22
	Length = 22
	Capacity = 22
	I thought I saw Elvis in a UFO.
	Size = 32
	Capacity = 44
	I thought I saw Elvis in a UFO. I've been working too hard.
	Size = 59
	Capacity = 500
	I thought
	Size = 10
	Capacity = 500
*/
```

### 2.2 Replacing string characters

There are a number of overloaded versions of `string::replace()`, but the simplest one takes three arguments:

- an integer indicating where to start in the string,
- an integer indicating how many characters to eliminate from the original string,
- and the replacement string.

```cpp
#include <cassert>
#include <cstddef> // For size_t
#include <string>
using namespace std;

int main() {
    string bigNews = "I thought I saw Elvis in a UFO. "
		"I have been working too hard.";
    string replacement("wig");
    string findMe("UFO");

	// Look in bigNews for the "UFO"
	// starting at position 0:
    size_t i = bigNews.find(findMe, 0);

	// Did we find the "UFO"?
    if(i != string::npos) {
    	// Replace the "UFO" with "wig":
        bigNews.replace(i, findMe.size(), replacement);
	}

	assert(bigNews == "I thought I saw Elvis in a wig. "
		"I have been working too hard.");
}
```

另外还有一个 generic algorithm `replace()`:

```cpp
#include <algorithm>
#include <cassert>
#include <string>
using namespace std;

int main() {
	string s("aaaXaaaXXaaXXXaXXXXaaa");
	replace(s.begin(), s.end(), 'X', 'Y');
	assert(s == "aaaYaaaYYaaYYYaYYYYaaa");
}
```

The `replace()` algorithm only works with single objects (in this case, `char` objects) and will not replace quoted char arrays or string objects.

### 2.3 Removing characters from strings

`string::erase()` takes two arguments:

- where to start removing characters (which defaults to 0),
- and how many to remove (which defaults to `string::npos`).

因为 `string::npos` 其实是个极大的整数，而 If you specify more characters than remain in the string, the remaining characters are all erased anyway. So calling `string::npos` without any arguments removes all characters in it.

## 3. Searching in strings

`string::find()` family，用法大体相同：找到了就返回 starting position of the first match，没找到就返回 `string:npos`。family 有：

- find()
- find_first_of()
- find_last_of()
- find_first_not_of()
- find_last_not_of()
- rfind() 				// find reversely

见名知意。

## 4. Comparing strings

C++ 的字符串是可以用 >、<、>=、<=、!=、== 来比较大小的，遵循的是字母序，比如 "a" < "b"，"aa" < "ab" 这样。

另外也可以用 `string::compare()`，与 java 的用法一致。

## 5. Strings and character traits

Observe how `string` is declared in the Standard C++ header file:

```cpp
typedef basic_string<char> string;

template <class CharType, class Traits = char_traits<CharType>, class Allocator = allocator<CharType>>
class basic_string;
```

根据 [MSDN: basic_string Class](https://msdn.microsoft.com/en-us/library/syxtdd4f.aspx) 的说法：

- CharType for `string` is `char`
- CharType for `wstring` is `wchar_t`
- CharType for `u16string` is `char16_t`
- CharType for `u32string` is `char32_t`

To change the way the string class treats character comparison (e.g. take uppercase and lowercase into accounts), you must supply a different `char_traits<>` template because that defines the behavior of the individual character comparison member functions.

书上 P111 给了一个例子。


text:
**NOTE:  This Package Will Be Abandoned**
Due to several factors, including the fact that I no longer use ES,
I will be ceasing development on this package.  Bug fixes with PRs will
eventually be looked at, but requests for new features or general support
questions may go unanswered.

If you are interested in taking over this project, please reach out to
me here on Github, or on Twitter: @cviebrock

---

Please be sure you include all the relevant information in your issue so we can help you:

- [ ] What steps where taken to reproduce your issue?
- [ ] What are your configuration file(s), where relevant?
- [ ] If it's a problematic ES query, then have you tested it directly
      with the [official PHP client](https://github.com/elastic/elasticsearch-php)?
      Remember, this package is basically just a configuration helper that wraps the
      official client.  If it doesn't work there, then the issue isn't with my package.
- [ ] Is there any other code we might need to see in order to help?

Please use a descriptive title for your issue.  "Why doesn't this work?" doesn't provide
other users much information if they are scanning the list of issues.

Also, *please* use [fenced code blocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/)
when pasting more than one line of code.  It makes it so much more readable for everyone!

**Thank you!**

repository: cviebrock/laravel-elasticsearch

branch_name: refs/heads/main

repo_name: cviebrock/laravel-elasticsearch