text:
[![](resources/readme/introduction.png)](#readme)

# JFrog Extension for VS Code & Eclipse Theia

![JFrog Extension Marketplace Installs](https://img.shields.io/visual-studio-marketplace/i/JFrog.jfrog-vscode-extension?label=VS%20Code%20installs&color=blue&style=for-the-badge)

 [![Visual Studio Code Version](https://img.shields.io/visual-studio-marketplace/v/JFrog.jfrog-vscode-extension?style=for-the-badge)](https://marketplace.visualstudio.com/items?itemName=JFrog.jfrog-vscode-extension)

[![Visual Studio Marketplace](https://img.shields.io/badge/Visual%20Studio%20Code-Marketplace-blue.png)](https://marketplace.visualstudio.com/items?itemName=JFrog.jfrog-vscode-extension)  [![Open VSX Registry](https://img.shields.io/badge/Open%20VSX%20Registry-Marketplace-blue.png)](https://open-vsx.org/extension/JFrog/jfrog-vscode-extension)
[![Scanned by Frogbot](https://raw.github.com/jfrog/frogbot/master/images/frogbot-badge.png)](https://github.com/jfrog/frogbot#readme) [![Test](https://github.com/jfrog/jfrog-vscode-extension/actions/workflows/test.yml/badge.svg)](https://github.com/jfrog/jfrog-vscode-extension/actions/workflows/test.yml?branch=master)

# Table of Contents
- [About this Extension](#about-this-extension)
- [Getting Started](#getting-started)
    - [Install the **JFrog** extension in VS Code](#install-the-jfrog-extension-in-vs-code)
    - [Connecting VS Code to Your JFrog Platform](#connecting-vs-code-to-your-jfrog-platform)
    - [Using the extension](#using-the-extension)
        - [Severity Icons](#severity-icons)
- [The Local View](#the-local-view)
    - [General](#general)
    - [Software Composition Analysis (SCA)](#software-composition-analysis)
    - [CVE Research and Enrichment](#cve-research-and-enrichment)
    - [Vulnerability Contextual Analysis](#vulnerability-contextual-analysis)
    - [Secrets Detection](#secrets-detection)
- [The CI View](#the-ci-view)
    - [How Does It Work?](#how-does-it-work)
    - [Setting Up Your CI Pipeline](#setting-up-your-ci-pipeline)
    - [Setting Up the CI View](#setting-up-the-ci-view)
- [Extension Settings](#extension-settings)
    - [Apply Xray Policies to your Projects](#apply-xray-policies-to-your-projects)
    - [Exclude Paths from Scan](#exclude-paths-from-scan)
    - [Proxy Configuration](#proxy-configuration)
    - [Proxy Authorization](#proxy-authorization)
        - [Basic authorization](#basic-authorization)
        - [Access token authorization](#access-token-authorization)
        - [Example](#example)
- [Behind the Scenes - Software Composition Analysis (SCA)](#behind-the-scenes)
- [Troubleshooting](#troubleshooting)
- [License](#license)
- [Building and Testing the Sources](#building-and-testing-the-sources)
    - [Preconditions](#preconditions)
- [Code Contributions](#code-contributions)
    - [Guidelines](#guidelines)

## About this Extension
The cost of remediating a vulnerability is akin to the cost of fixing a bug.
The earlier you remediate a vulnerability in the release cycle, the lower the cost.
The extension allows developers to find and fix security vulnerabilities in their projects and to see valuable information
about the status of their code by continuously scanning it locally with the [JFrog Platform](https://jfrog.com/xray/).

### What security capabilities do we provide?
#### 🌟 Basic

  Software Composition Analysis (SCA)
Scans your project dependencies for security issues and shows you which dependencies are vulnerable. If the vulnerabilities have a fix, you can upgrade to the version with the fix in a click of a button.

  CVE Research and Enrichment
For selected security issues, get leverage-enhanced CVE data that is provided by our JFrog Security Research team.
Prioritize the CVEs based on:

- **JFrog Severity**: The severity given by the JFrog Security Research team after the manual analysis of the CVE by the team.
CVEs with the highest JFrog security severity are the most likely to be used by real-world attackers.
This means that you should put effort into fixing them as soon as possible.
- **Research Summary**: The summary that is based on JFrog's security analysis of the security issue provides detailed technical information on the specific conditions for the CVE to be applicable.
- **Remediation**: Detailed fix and mitigation options for the CVEs

You can learn more about enriched CVEs [here](https://jfrog.com/help/r/jfrog-security-documentation/jfrog-security-cve-research-and-enrichment).

Check out what our research team is up to and stay updated on newly discovered issues by clicking on this link: <https://research.jfrog.com>

#### 🌟 Advanced
*Requires Xray version 3.66.5 or above and Enterprise X / Enterprise+ subscription with [Advanced DevSecOps](https://jfrog.com/xray/#xray-advanced).*

  Vulnerability Contextual Analysis
Uses the code context to eliminate false positive reports on vulnerable dependencies that are not applicable to the code.
Vulnerability Contextual Analysis is currently supported for Python, Java and JavaScript code.

  Secrets Detection
Prevents the exposure of keys or credentials that are stored in your source code.

  Infrastructure as Code (IaC) Scan
Secures your IaC files. Critical to keeping your cloud deployment safe and secure.

#### 🌟 Additional Perks

- Security issues are easily visible inline.
- The results show issues with context, impact, and remediation.
- View all security issues in one place, in the JFrog tab.
- For Security issues with an available fixed version, you can upgrade to the fixed version within the plugin.
- Track the status of the code while it is being built, tested, and scanned on the CI server.

The extension also applies [JFrog File Spec JSON schema](https://raw.githubusercontent.com/jfrog/jfrog-cli/master/schema/filespec-schema.json) on the following file patterns: `**/filespecs/*.json`, `*filespec*.json` and `*.filespec`. Read more about JFrog File specs [here](https://www.jfrog.com/confluence/display/JFROG/FileSpec).

#### 🛡 Supported Packages
| Features                                             | [Go](#go-projects) | [Maven](#maven-projects) | [npm](#npm-projects) | [Yarn v1](#yarn-v1-projects) | [Pypi](#pypi-projects) | [.NET](#net-projects) | [Terraform](#-infrastructure-as-code-(iac)-Scan) |
|---------------------------------------------------|:----:|:------:|:-------:|:----:|:--------:|:-------:|:-------:|
| [SCA](#-software-composition-analysis-sca)                                               |  ✅  |   ✅   |   ✅    |  ✅  |    ✅    |   ✅    |   ❌    |
| [Upgrade vulnerable dependencies to fixed versions](#updating-dependencies) |  ✅  |   ✅   |   ✅    |  ✅  |    ✅    |   ✅    |   ❌    |
| [Vulnerability Contextual Analysis](#-vulnerability-contextual-analysis)                               |  ❌  |    ✅   |   ✅    |  ✅  |    ✅    |   ❌    |   ❌    |
| [Secrets Detection](#-secrets-detection)                          |  ✅  |   ✅   |   ✅    |  ✅  |    ✅    |   ✅    |✅    |
| [Exclude dev dependencies](#exclude-development-dependencies-during-scan)                          |  ❌  |   ❌   |   ✅    |  ❌  |    ❌    |   ❌    |   ❌    |
| [Infrastructure as Code (IaC) Scan](#-infrastructure-as-code-(iac)-Scan)                          |  ❌  |   ❌   |   ❌    |  ❌  |    ❌    |   ❌    |   ✅     |

## Getting Started

1. [Install the **JFrog** extension in VS Code](#install-the-jfrog-extension-in-vs-code)
2. [Connect VS Code to Your JFrog Environment](#connecting-vs-code-to-your-jfrog-environment)
3. [Start using the extension](#using-the-extension)

## Install the **JFrog** extension in VS Code

The extension is available to install from the VS Code extensions marketplace. after installing the JFrog extension tab  will appear in the activity bar
![Install](resources/readme/preview/install.png)

## Connecting VS Code to Your JFrog Platform

If you don't have a JFrog Platform instance, create a free instance in the cloud by running one of the following commands in your terminal.

**MacOS and Linux using cUrl**

```
curl -fL "https://getcli.jfrog.io?setup" | sh
```

**Windows using PowerShell**

```
powershell "Start-Process -Wait -Verb RunAs powershell '-NoProfile iwr https://releases.jfrog.io/artifactory/jfrog-cli/v2-jf/[RELEASE]/jfrog-cli-windows-amd64/jf.exe -OutFile $env:SYSTEMROOT\system32\jf.exe'" ; jf setup
```
The commands will do the following:

1. Install JFrog CLI on your machine.
2. Create a FREE JFrog environment in the cloud for you.
3. Configure VS Code to connect to your new environment.

Once the JFrog Extension is installed in VS Code, click on the JFrog tab:

![jfrogTab](resources/readme/preview/jfrogTab.png)

This will open the Sign in page:

![SighInPage](resources/readme/preview/sighInPage.png)

Fill in your connection details and click on the `Sign In` button to start using the extension

**Note**: If you would like to use custom URLs for Artifactory or Xray, click on 'Advanced'.

You can also choose other option to authenticate with your JFrog Platform instance:
1. [SSO](#connect-using-sso)
2. [JFrog CLI's Connection Details](#connect-using-jfrog-cli-connection-details)
3. [Using Environment Variables](#connect-using-environment-variables).

### Connect Using SSO

To sign in using SSO, follow these steps:

1. On the sign-in page, click the `Continue with SSO` button:

![SighInSsoButton](resources/readme/preview/ssoButton.png)

2. After entering your JFrog platform URL, click on `Sign in With SSO`.

3. It will take a few seconds for the browser to redirect you to the SSO sign in page.

4. You should now be signed in in at vscode.

### Connect Using JFrog CLI Connection Details

If JFrog CLI is installed on your machine and is configured with your JFrog Platform connection details, then you should see the message popup in the Sigh in page:

![LoginPageJfrogCli](resources/readme/preview/sighInPageJFrogCli.png)

### Connect Using Environment Variables

You may set the connection details using the following environment variables. VS Code will read them after it is launched.

-   `JFROG_IDE_URL` - JFrog URL
-   `JFROG_IDE_USERNAME` - JFrog username
-   `JFROG_IDE_PASSWORD` - JFrog password
-   `JFROG_IDE_ACCESS_TOKEN` - JFrog access token
-   `JFROG_IDE_STORE_CONNECTION` - Set the value of this environment variable to **true**, if you'd like VS Code to store the connection details after reading them from the environment variables.

Once the above environment variables are configured, you can expect to see a message popup in the Sigh in page:

![LoginPageEnvVar](resources/readme/preview/sighInPageEnvVar.png)

**Note**: For security reasons, it is recommended to unset the environment variables after launching VS Code.

## Using the Extension

The extension offers two modes, **Local** and **CI**.
The two modes can be toggled by pressing on their respective buttons that will appear next to the components tree.

-   The **Local** view displays information about the local code as it is being developed in VS Code. The developer can scan their local workspace continuously. The information is displayed in the **Local** view.
-   The **CI** view allows the tracking of the code as it is built, tested and scanned by the CI server. It displays information about the status of the build and includes a link to the build log on the CI server.

### Severity Icons
The icon demonstrates the top severity issue of a selected component and its transitive dependencies. The following table describes the severities from highest to lowest:

| Icon                                                          | Severity  | Description                      |
|:---------------------------------------------------------------:|:---------:|:--------------------------------:|
|   |  Critical |   Issue with critical severity   |
|   |  High  |   Issue with high severity   |
|   |  Medium  |   Issue with medium severity   |
|   |  Low  |   Issue with low severity   |
|   |  Unknown  |   Issue with unknown severity   |
|  |  Not Applicable  |   CVE issue that is not applicable to your source code   |
|   |  Normal  |   No issues (Used only in CI view)   |

## The Local View
### General
The JFrog VS Code Extension enables continuous scans of your project with the JFrog Platform. The security related information will be displayed under the Local view.
It allows developers to view vulnerability information about their dependencies and source code in their IDE.
With this information, you can make an informed decision on whether to use a component or not before it gets entrenched into the organization’s product.

scan your workspace by clicking the Scan/Rescan button, the  icon at the extension tab or click on Start Xray Scan from within the editor. The scan will create a list of files with vulnerabilities in the workspace.
![Refresh](resources/readme/preview/refresh.png)

### Software Composition Analysis (SCA)
Each descriptor file (like pom.xml in Maven, go.mod in Go, etc.) displayed in the JFrog Panel contains vulnerable dependencies, and each dependency contains the vulnerabilities themselves.

Each file node in the tree is interactive. Click and expand it to view its children noded and navigate to the corresponding file in the IDE editor for better visibility. Upon navigating to a file, the extension will highlight the vulnerable line, making it easier to locate the specific issue

In addition the locations with vulnerabilities will be marked in the editor. By clicking on the light bulb icon next to a vulnerable location in the editor, you can instantly jump to the corresponding entry in the tree view.

![Tree view](resources/readme/preview/treeView.png)

Clicking on a CVE in the list will open the location with the issue in the editor and a vulnerability details view. This view contains information about the vulnerability, the vulnerable component, fixed versions, impact paths and much more.

![Impact_Graph](resources/readme/preview/impactGraph.png)
![Public_Resources](resources/readme/preview/publicDetails.png)

Update a vulnerable direct dependency to a fixed version directly from the vulnerable location at the editor using quick fix
![Set_Fixed_Version](resources/readme/preview/updateQuickFix.png)

When Xray watches are enabled and a vulnerability is detected, a closed eye icon will appear next to the vulnerability line in the JFrog extension. By clicking on this icon, you can initiate the process of creating an [Ignore Rule](https://www.jfrog.com/confluence/display/JFROG/Ignore+Rules) in Xray.
![Ignore_Rule](resources/readme/preview/ignoreRule.png)

### CVE Research and Enrichment
For selected security issues, get leverage-enhanced CVE data that is provided by our JFrog Security Research team. Prioritize the CVEs based on:

* JFrog Severity: The severity given by the JFrog Security Research team after the manual analysis of the CVE by the team. CVEs with the highest JFrog security severity are the most likely to be used by real-world attackers. This means that you should put effort into fixing them as soon as possible.
* Research Summary: The summary that is based on JFrog's security analysis of the security issue provides detailed technical information on the specific conditions for the CVE to be applicable.
Remediation: Detailed fix and mitigation options for the CVEs

Check out what our research team is up to and stay updated on newly discovered issues by clicking on this [link](https://research.jfrog.com).

![JFrog_Research](resources/readme/preview/research.png)

### Vulnerability Contextual Analysis
> **_NOTE:_**  Vulnerability Contextual Analysis requires Xray version 3.66.5 or above and Enterprise X / Enterprise+ subscription with Advanced DevSecOps.

Xray automatically validates some high and very high impact vulnerabilities, such as vulnerabilities that have prerequisites for exploitations, and provides contextual analysis information for these vulnerabilities, to assist you in figuring out which vulnerabilities need to be fixed. Vulnerability Contextual Analysis data includes:

* Vulnerability Contextual Analysis status: Vulnerability Contextual Analysis results indicating if a CVE was found applicable in your application or not applicable.
* Vulnerability Contextual Analysis breakdown: An explanation provided by our research team as to why the CVE was found applicable or not applicable.
* Remediation: Contextual mitigation steps and options provided by our research team that assist you with remediating the issues.

![Contextual_Analysis](resources/readme/preview/contextualDetails.png)

### Secrets Detection
> **_NOTE:_**  Secrets Detection requires Xray version 3.66.5 or above and Enterprise X / Enterprise+ subscription with Advanced DevSecOps.

Detect any secrets left exposed inside the code. to prevent any accidental leak of internal tokens or credentials. To ignore detected secrets, you can add a comment which includes the phrase *jfrog-ignore* above the line with the secret.

![Secrets_Detection](resources/readme/preview/secrets.png)

### Infrastructure as Code (IaC) Scan
> **_NOTE:_**  Infrastructure as Code (IaC) requires Xray version 3.66.5 or above and Enterprise X / Enterprise+ subscription with Advanced DevSecOps.

Scan Infrastructure as Code (Terraform) files for early detection of cloud and infrastructure misconfigurations.

![iac_scan](resources/readme/preview/iac.png)

## The CI View
The CI view of the extension allows you to view information about your builds directly from your CI system. This allows developers to keep track of the status of their code, while it is being built, tested and scanned as part of the CI pipeline, regardless of the CI provider used.

This information can be viewed inside JFrog VS Code Extension, from the JFrog Panel, after switching to CI mode.

The following details can be made available in the CI view.

-   Status of the build run (passed or failed)
-   Build run start time
-   Git branch and latest commit message
-   Link to the CI run log
-   Security information about the build artifacts and dependencies

### How Does It Work?

The CI information displayed in VS Code is pulled by the JFrog Extension directly from JFrog Artifactory. This information is stored in Artifactory as part of the build-info, which is published to Artifactory by the CI server.

Read more about build-info in the [Build Integration](https://www.jfrog.com/confluence/display/JFROG/Build+Integration) documentation page. If the CI pipeline is also configured to scan the build-info by JFrog Xray, the JFrog VS Code Extension will pull the results of the scan from JFrog Xray and display them in the CI view as well.

### Setting Up Your CI Pipeline

Before VS Code can display information from your CI in the CI View, your CI pipeline needs to be configured to expose this data.
Read [this guide](https://www.jfrog.com/confluence/display/JFROG/Setting+Up+CI+Integration) which describes how to configure your CI pipeline.

### Setting Up the CI View

Set your CI build name in the Build name pattern field at the [Extension Settings](#extension-settings). This is the name of the build published to Artifactory by your CI pipeline. You have the option of setting \* to view all the builds published to Artifactory.

After your builds were fetched from Artifactory, press on the Builds ![Builds](resources/light/build.png) button to choose what build to display.

![CI](resources/readme/gifs/ci.gif)

## Extension Settings

To open the extension settings, use the extension settings icon:
![Open_Settings](resources/readme/preview/openSettings.png)
Or use the following VS Code menu command:

-   On Windows/Linux - File > Preferences > Settings > Extensions > JFrog
-   On macOS - Code > Preferences > Settings > Extensions > JFrog

### Apply Xray Policies to your Projects

You can configure the JFrog VS-Code extension  to use the security policies you create in Xray. Policies enable you to create a set of rules, in which each rule defines security criteria, with a corresponding set of automatic actions according to your needs. Policies are enforced when applying them to Watches.

If you'd like to use a JFrog Project that is associated with the policy, follow these steps:

1. Create a [JFrog Project](https://www.jfrog.com/confluence/display/JFROG/Projects), or obtain the relevant JFrog Project key.
1. Create a [Policy](https://www.jfrog.com/confluence/display/JFROG/Creating+Xray+Policies+and+Rules) on JFrog Xray.
1. Create a [Watch](https://www.jfrog.com/confluence/display/JFROG/Configuring+Xray+Watches) on JFrog Xray and assign your Policy and Project as resources to it.
1. Configure your Project key in the [Extension Settings](#extension-settings).

If however your policies are referenced through an Xray Watch or Watches, follow these steps instead:

1. Create one or more [Watches](https://www.jfrog.com/confluence/display/JFROG/Configuring+Xray+Watches) on JFrog Xray.
1. Configure your Watches in the [Extension Settings](#extension-settings).

### Exclude Paths from Scan

By default, paths containing the words `test`, `venv` and `node_modules` are excluded from Xray scan.
The exclude pattern can be configured in the [Extension Settings](#extension-settings).

### Proxy Configuration

If your JFrog environment is behind an HTTP/S proxy, follow these steps to configure the proxy server:

1. Go to Preferences --> Settings --> Application --> Proxy
1. Set the proxy URL under 'Proxy'.
1. Make sure 'Proxy Support' is 'override' or 'on'.

-   Alternatively, you can use the HTTP_PROXY and HTTPS_PROXY environment variables.

### Proxy Authorization

If your proxy server requires credentials, follow these steps:

1. Follow 1-3 steps under [Proxy configuration](#proxy-configuration).

#### Basic authorization

1. Encode with base64: `[Username]:[Password]`.
1. Under 'Proxy Authorization' click on 'Edit in settings.json'.
1. Add to settings.json:

-   `"http.proxyAuthorization": "Basic [Encoded credentials]"`.

#### Access token authorization

1. Under 'Proxy Authorization' click on 'Edit in settings.json'.
1. Add to settings.json:

-   `"http.proxyAuthorization": "Bearer [Access token]"`.

#### Example

-   `Username: foo`
-   `Password: bar`

settings.json:

```json
{
    "http.proxyAuthorization": "Basic Zm9vOmJhcg=="
}
```

## Behind the Scenes - Software Composition Analysis (SCA)
### Go Projects
Behind the scenes, the JFrog VS Code Extension scans all the project dependencies, both direct and indirect (transitive), even if they are not declared in the project's go.mod. It builds the Go dependencies tree by running `go mod graph` and intersecting the results with `go list -f '{{with .Module}}{{.Path}} {{.Version}}{{end}}' all` command. Therefore, please make sure to have Go CLI in your system PATH.

### Maven Projects
The JFrog VS Code Extension builds the Maven dependencies tree by running `mvn dependency:tree`. View licenses and top issue severities directly from the pom.xml.

Important notes:

1. To have your project dependencies scanned by JFrog Xray, make sure Maven is installed, and that the mvn command is in your system PATH.
2. For projects which include the [Maven Dependency Plugin](https://maven.apache.org/plugins/maven-dependency-plugin/examples/resolving-conflicts-using-the-dependency-tree.html) as a build plugin, with include or exclude configurations, the scanning functionality is disabled. For example:

```xml
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-dependency-plugin</artifactId>
          <configuration>
            <includes>org.apache.*</includes>
          </configuration>
        </plugin>
      </plugins>
```

### Npm Projects

Behind the scenes, the extension builds the npm dependencies tree by running `npm list`. View licenses and top issue severities directly from the package.json.

Important:
To have your project dependencies scanned by JFrog Xray, make sure the npm CLI is installed on your local machine and that it is in your system PATH.
In addition, the project dependencies must be installed using `npm install`.

### Exclude Development Dependencies During Scan

Development dependencies are scanned by default. You can exclude them by choosing `Exclude Dev Dependencies` in the [Extension Settings](#extension-settings). Currently, only npm is supported.

### Yarn v1 Projects

Behind the scenes, the extension builds the Yarn dependencies tree by running `yarn list`. View licenses and top issue severities directly from the yarn.lock.

Important:

-   To have your project dependencies scanned by JFrog Xray, make sure the Yarn CLI is installed on your local machine and that it is in your system PATH.
-   Yarn v2 is not yet supported.

### Pypi Projects

Behind the scenes, the extension builds the Pypi dependencies tree by running `pipdeptree` on your Python virtual environment. It also uses the Python interpreter path configured by the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python). View licenses and top issue severities directly from your requirements.txt files. The scan your Pypi dependencies, make sure the following requirements are met:

1. The [Python extension for VS Code](https://code.visualstudio.com/docs/python/python-tutorial#_install-visual-studio-code-and-the-python-extension) is installed.
2. Depending on your project, Please make sure Python 2 or 3 are included in your system PATH.
3. Create and activate a virtual env as instructed in [VS-Code documentation](https://code.visualstudio.com/docs/python/environments#_global-virtual-and-conda-environments). Make sure that Virtualenv Python interpreter is selected as instructed [here](https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment).
4. Open a new terminal and activate your Virtualenv:

    - On macOS and Linux:

        ```sh
        source <venv-dir>/bin/activate

        # For example:
        source .env/bin/activate
        ```

    - On Windows:

        ```powershell
        .\<venv-dir>\Scripts\activate

        # For example:
        .\env\Scripts\activate
        ```

5. In the same terminal, install your python project and dependencies according to your project specifications.

### .NET Projects

For .NET projects which use NuGet packages as dependencies, the extension displays the NuGet dependencies tree, together with the information for each dependency.
Behind the scenes, the extension builds the NuGet dependencies tree using the [NuGet deps tree](https://github.com/jfrog/nuget-deps-tree) npm package.

Important:

-   Does your project define its NuGet dependencies using a _packages.config_ file? If so, then please make sure the `nuget` CLI is installed on your local machine and that it is in your system PATH. The extension uses the `nuget` CLI to find the location of the NuGet packages on the local file-system.
-   The project must be restored using `nuget restore` or `dotnet restore` prior to scanning. After this action, you should click on the Refresh ![Refresh](resources/readme/refresh.png) button, for the tree view to be refreshed and updated.

## Troubleshooting

Change the log level to 'debug', 'info', 'warn', or 'err' in the [Extension Settings](#extension-settings).

View the extension log:
![Logs](resources/readme/gifs/logs.gif)

## License

The extension is licensed under [Apache License 2.0](LICENSE).

## Building and Testing the Sources

### Preconditions

-   npm 7 and above
-   JFrog CLI's `jf` executable - required for tests

To build the extension from sources, please follow these steps:

1. Clone the code from Github.
2. Update submodules:

```bash
git submodule init
git submodule update
```

3. Build and create the VS-Code extension vsix file by running the following npm command:

```bash
npm i
npm run package
```

After the build finishes, you'll find the vsix file in the _jfrog-vscode-extension_ directory.
The vsix file can be loaded into VS-Code

To run the tests:

```bash
npm t
```

## Code Contributions

We welcome community contribution through pull requests.

### Guidelines

-   Before creating your first pull request, please join our contributors community by signing [JFrog's CLA](https://secure.echosign.com/public/hostedForm?formid=5IYKLZ2RXB543N).
-   If the existing tests do not already cover your changes, please add tests.
-   Pull requests should be created on the _dev_ branch.
-   Please run `npm run format` for formatting the code before submitting the pull request.

repository: jfrog/jfrog-vscode-extension

repo_name: jfrog/jfrog-vscode-extension


text:
# Salus: Fine-Grained GPU Sharing Primitives for Deep Learning Applications.

[![pipeline status]][gitlabci]

Implementation of Salus ([arXiv paper][arXiv]).

Must be used with a customized tensorflow at [SymbioticLab/tensorflow-salus][tf-salus].
Note that these two projects are tightly coupled together. Make sure to use latest commit from both projects.

## Try it out

Using docker. You will need the [nvidia-docker] extension.

```bash
docker run --rm -it registry.gitlab.com/salus/salus
```

This will start a salus server listen at port 5501.

Then when creating tensorflow session, use `zrpc://tcp://localhost:5501` as the session target.

## Compile yourself

Requires `CMake 3.10` and modern compiler with c++14 support, e.g. `GCC 5.4` is minimum.

### Dependencies

- ZeroMQ with C++ binding
- Boost 1.66
- protobuf 3.4.1
- gperftools 2.7 (if build with TCMalloc)
- [nlohmann-json]
- [concurrentqueue]
- [docopt.cpp]
- [easyloggingpp]

See [toplevel CMakeLists.txt](CMakeLists.txt) for details.

[arXiv]: https://arxiv.org/abs/1902.04610
[tf-salus]: https://github.com/SymbioticLab/tensorflow-salus
[gitlabci]: https://gitlab.com/Salus/Salus/pipelines
[pipeline status]: https://gitlab.com/Salus/Salus/badges/master/pipeline.svg
[nvidia-docker]: https://github.com/NVIDIA/nvidia-docker
[nlohmann-json]: https://github.com/nlohmann/json
[concurrentqueue]: https://github.com/cameron314/concurrentqueue
[docopt.cpp]: https://github.com/docopt/docopt.cpp
[easyloggingpp]: https://github.com/muflihun/easyloggingpp

repository: lisongju/Salus

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: lisongju/Salus


text:
![Cache](https://github.com/hyperoslo/Cache/blob/master/Resources/CachePresentation.png)

[![CI Status](https://circleci.com/gh/hyperoslo/Cache.png)](https://circleci.com/gh/hyperoslo/Cache)
[![Version](https://img.shields.io/cocoapods/v/Cache.svg?style=flat)](http://cocoadocs.org/docsets/Cache)
[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)
[![License](https://img.shields.io/cocoapods/l/Cache.svg?style=flat)](http://cocoadocs.org/docsets/Cache)
[![Platform](https://img.shields.io/cocoapods/p/Cache.svg?style=flat)](http://cocoadocs.org/docsets/Cache)
[![Documentation](https://img.shields.io/cocoapods/metrics/doc-percent/Cache.svg?style=flat)](http://cocoadocs.org/docsets/Cache)
![Swift](https://img.shields.io/badge/%20in-swift%205-orange.svg)

## Table of Contents

* [Description](#description)
* [Key features](#key-features)
* [Usage](#usage)
  * [Storage](#storage)
  * [Configuration](#configuration)
  * [Sync APIs](#sync-apis)
  * [Async APIs](#async-apis)
  * [Expiry date](#expiry-date)
* [Observations](#observations)
  * [Storage observations](#storage-observations)
  * [Key observations](#key-observations)
* [Handling JSON response](#handling-json-response)
* [What about images?](#what-about-images)
* [Installation](#installation)
* [Author](#author)
* [Contributing](#contributing)
* [License](#license)

## Description

<img src="https://github.com/hyperoslo/Cache/blob/master/Resources/CacheIcon.png" alt="Cache Icon" align="right" />

**Cache** doesn't claim to be unique in this area, but it's not another monster
library that gives you a god's power. It does nothing but caching, but it does it well. It offers a good public API
with out-of-box implementations and great customization possibilities. `Cache` utilizes `Codable` in Swift 4 to perform serialization.

Read the story here [Open Source Stories: From Cachable to Generic Storage in Cache](https://medium.com/hyperoslo/open-source-stories-from-cachable-to-generic-storage-in-cache-418d9a230d51)

## Key features

- [x] Work with Swift 4 `Codable`. Anything conforming to `Codable` will be saved and loaded easily by `Storage`.
- [x] Hybrid with memory and disk storage.
- [X] Many options via `DiskConfig` and `MemoryConfig`.
- [x] Support `expiry` and clean up of expired objects.
- [x] Thread safe. Operations can be accessed from any queue.
- [x] Sync by default. Also support Async APIs.
- [x] Extensive unit test coverage and great documentation.
- [x] iOS, tvOS and macOS support.

## Usage

### Storage

`Cache` is built based on [Chain-of-responsibility pattern](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern), in which there are many processing objects, each knows how to do 1 task and delegates to the next one, so can you compose Storages the way you like.

For now the following Storage are supported

- `MemoryStorage`: save object to memory.
- `DiskStorage`: save object to disk.
- `HybridStorage`: save object to memory and disk, so you get persistented object on disk, while fast access with in memory objects.
- `SyncStorage`: blocking APIs, all read and write operations are scheduled in a serial queue, all sync manner.
- `AsyncStorage`: non-blocking APIs, operations are scheduled in an internal queue for serial processing. No read and write should happen at the same time.

Although you can use those Storage at your discretion, you don't have to. Because we also provide a convenient `Storage` which uses `HybridStorage` under the hood, while exposes sync and async APIs through `SyncStorage` and `AsyncStorage`.

All you need to do is to specify the configuration you want with `DiskConfig` and `MemoryConfig`. The default configurations are good to go, but you can customise a lot.

```swift
let diskConfig = DiskConfig(name: "Floppy")
let memoryConfig = MemoryConfig(expiry: .never, countLimit: 10, totalCostLimit: 10)

let storage = try? Storage(
  diskConfig: diskConfig,
  memoryConfig: memoryConfig,
  transformer: TransformerFactory.forCodable(ofType: User.self) // Storage<String, User>
)
```

### Generic, Type safety and Transformer

All `Storage` now are generic by default, so you can get a type safety experience. Once you create a Storage, it has a type constraint that you don't need to specify type for each operation afterwards.

If you want to change the type, `Cache` offers `transform` functions, look for `Transformer` and `TransformerFactory` for built-in transformers.

```swift
let storage: Storage<String, User> = ...
storage.setObject(superman, forKey: "user")

let imageStorage = storage.transformImage() // Storage<String, UIImage>
imageStorage.setObject(image, forKey: "image")

let stringStorage = storage.transformCodable(ofType: String.self) // Storage<String, String>
stringStorage.setObject("hello world", forKey: "string")
```

Each transformation allows you to work with a specific type, however the underlying caching mechanism remains the same, you're working with the same `Storage`, just with different type annotation. You can also create different `Storage` for each type if you want.

`Transformer` is necessary because the need of serialising and deserialising objects to and from `Data` for disk persistency. `Cache` provides default `Transformer ` for `Data`, `Codable` and `UIImage/NSImage`

#### Codable types

`Storage` supports any objects that conform to [Codable](https://developer.apple.com/documentation/swift/codable) protocol. You can [make your own things conform to Codable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) so that can be saved and loaded from `Storage`.

The supported types are

- Primitives like `Int`, `Float`, `String`, `Bool`, ...
- Array of primitives like `[Int]`, `[Float]`, `[Double]`, ...
- Set of primitives like `Set<String>`, `Set<Int>`, ...
- Simply dictionary like `[String: Int]`, `[String: String]`, ...
- `Date`
- `URL`
- `Data`

#### Error handling

Error handling is done via `try catch`. `Storage` throws errors in terms of `StorageError`.

```swift
public enum StorageError: Error {
  /// Object can not be found
  case notFound
  /// Object is found, but casting to requested type failed
  case typeNotMatch
  /// The file attributes are malformed
  case malformedFileAttributes
  /// Can't perform Decode
  case decodingFailed
  /// Can't perform Encode
  case encodingFailed
  /// The storage has been deallocated
  case deallocated
  /// Fail to perform transformation to or from Data
  case transformerFail
}
```

There can be errors because of disk problem or type mismatch when loading from storage, so if want to handle errors, you need to do `try catch`

```swift
do {
  let storage = try Storage(diskConfig: diskConfig, memoryConfig: memoryConfig)
} catch {
  print(error)
}
```

### Configuration

Here is how you can play with many configuration options

```swift
let diskConfig = DiskConfig(
  // The name of disk storage, this will be used as folder name within directory
  name: "Floppy",
  // Expiry date that will be applied by default for every added object
  // if it's not overridden in the `setObject(forKey:expiry:)` method
  expiry: .date(Date().addingTimeInterval(2*3600)),
  // Maximum size of the disk cache storage (in bytes)
  maxSize: 10000,
  // Where to store the disk cache. If nil, it is placed in `cachesDirectory` directory.
  directory: try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
    appropriateFor: nil, create: true).appendingPathComponent("MyPreferences"),
  // Data protection is used to store files in an encrypted format on disk and to decrypt them on demand
  protectionType: .complete
)
```

```swift
let memoryConfig = MemoryConfig(
  // Expiry date that will be applied by default for every added object
  // if it's not overridden in the `setObject(forKey:expiry:)` method
  expiry: .date(Date().addingTimeInterval(2*60)),
  /// The maximum number of objects in memory the cache should hold
  countLimit: 50,
  /// The maximum total cost that the cache can hold before it starts evicting objects
  totalCostLimit: 0
)
```

On iOS, tvOS we can also specify `protectionType` on `DiskConfig` to add a level of security to files stored on disk by your app in the app’s container. For more information, see [FileProtectionType](https://developer.apple.com/documentation/foundation/fileprotectiontype)

### Sync APIs

`Storage` is sync by default and is `thread safe`, you can access it from any queues. All Sync functions are constrained by `StorageAware` protocol.

```swift
// Save to storage
try? storage.setObject(10, forKey: "score")
try? storage.setObject("Oslo", forKey: "my favorite city", expiry: .never)
try? storage.setObject(["alert", "sounds", "badge"], forKey: "notifications")
try? storage.setObject(data, forKey: "a bunch of bytes")
try? storage.setObject(authorizeURL, forKey: "authorization URL")

// Load from storage
let score = try? storage.object(forKey: "score")
let favoriteCharacter = try? storage.object(forKey: "my favorite city")

// Check if an object exists
let hasFavoriteCharacter = try? storage.existsObject(forKey: "my favorite city")

// Remove an object in storage
try? storage.removeObject(forKey: "my favorite city")

// Remove all objects
try? storage.removeAll()

// Remove expired objects
try? storage.removeExpiredObjects()
```

#### Entry

There is time you want to get object together with its expiry information and meta data. You can use `Entry`

```swift
let entry = try? storage.entry(forKey: "my favorite city")
print(entry?.object)
print(entry?.expiry)
print(entry?.meta)
```

`meta` may contain file information if the object was fetched from disk storage.

#### Custom Codable

`Codable` works for simple dictionary like `[String: Int]`, `[String: String]`, ... It does not work for `[String: Any]` as `Any` is not `Codable` conformance, it will raise `fatal error` at runtime. So when you get json from backend responses, you need to convert that to your custom `Codable` objects and save to `Storage` instead.

```swift
struct User: Codable {
  let firstName: String
  let lastName: String
}

let user = User(fistName: "John", lastName: "Snow")
try? storage.setObject(user, forKey: "character")
```

### Async APIs

In `async` fashion, you deal with `Result` instead of `try catch` because the result is delivered at a later time, in order to not block the current calling queue. In the completion block, you either have `value` or `error`.

You access Async APIs via `storage.async`, it is also thread safe, and you can use Sync and Async APIs in any order you want. All Async functions are constrained by `AsyncStorageAware` protocol.

```swift
storage.async.setObject("Oslo", forKey: "my favorite city") { result in
  switch result {
    case .success:
      print("saved successfully")
    case .failure(let error):
      print(error)
  }
}

storage.async.object(forKey: "my favorite city") { result in
  switch result {
    case .success(let city):
      print("my favorite city is \(city)")
    case .failure(let error):
      print(error)
  }
}

storage.async.existsObject(forKey: "my favorite city") { result in
  if case .success(let exists) = result, exists {
    print("I have a favorite city")
  }
}

storage.async.removeAll() { result in
  switch result {
    case .success:
      print("removal completes")
    case .failure(let error):
      print(error)
  }
}

storage.async.removeExpiredObjects() { result in
  switch result {
    case .success:
      print("removal completes")
    case .failure(let error):
      print(error)
  }
}
```

### Expiry date

By default, all saved objects have the same expiry as the expiry you specify in `DiskConfig` or `MemoryConfig`. You can overwrite this for a specific object by specifying `expiry` for `setObject`

```swift
// Default expiry date from configuration will be applied to the item
try? storage.setObject("This is a string", forKey: "string")

// A given expiry date will be applied to the item
try? storage.setObject(
  "This is a string",
  forKey: "string"
  expiry: .date(Date().addingTimeInterval(2 * 3600))
)

// Clear expired objects
storage.removeExpiredObjects()
```

## Observations

[Storage](#storage) allows you to observe changes in the cache layer, both on
a store and a key levels. The API lets you pass any object as an observer,
while also passing an observation closure. The observation closure will be
removed automatically when the weakly captured observer has been deallocated.

## Storage observations

```swift
// Add observer
let token = storage.addStorageObserver(self) { observer, storage, change in
  switch change {
  case .add(let key):
    print("Added \(key)")
  case .remove(let key):
    print("Removed \(key)")
  case .removeAll:
    print("Removed all")
  case .removeExpired:
    print("Removed expired")
  }
}

// Remove observer
token.cancel()

// Remove all observers
storage.removeAllStorageObservers()
```

## Key observations

```swift
let key = "user1"

let token = storage.addObserver(self, forKey: key) { observer, storage, change in
  switch change {
  case .edit(let before, let after):
    print("Changed object for \(key) from \(String(describing: before)) to \(after)")
  case .remove:
    print("Removed \(key)")
  }
}

// Remove observer by token
token.cancel()

// Remove observer for key
storage.removeObserver(forKey: key)

// Remove all observers
storage.removeAllKeyObservers()
```

## Handling JSON response

Most of the time, our use case is to fetch some json from backend, display it while saving the json to storage for future uses. If you're using libraries like [Alamofire](https://github.com/Alamofire/Alamofire) or [Malibu](https://github.com/hyperoslo/Malibu), you mostly get json in the form of dictionary, string, or data.

`Storage` can persist `String` or `Data`. You can even save json to `Storage` using `JSONArrayWrapper` and `JSONDictionaryWrapper`, but we prefer persisting the strong typed objects, since those are the objects that you will use to display in UI. Furthermore, if the json data can't be converted to strongly typed objects, what's the point of saving it ? 😉

You can use these extensions on `JSONDecoder` to decode json dictionary, string or data to objects.

```swift
let user = JSONDecoder.decode(jsonString, to: User.self)
let cities = JSONDecoder.decode(jsonDictionary, to: [City].self)
let dragons = JSONDecoder.decode(jsonData, to: [Dragon].self)
```

This is how you perform object converting and saving with `Alamofire`

```swift
Alamofire.request("https://gameofthrones.org/mostFavoriteCharacter").responseString { response in
  do {
    let user = try JSONDecoder.decode(response.result.success, to: User.self)
    try storage.setObject(user, forKey: "most favorite character")
  } catch {
    print(error)
  }
}
```

## What about images

If you want to load image into `UIImageView` or `NSImageView`, then we also have a nice gift for you. It's called [Imaginary](https://github.com/hyperoslo/Imaginary) and uses `Cache` under the hood to make your life easier when it comes to working with remote images.

## Installation

### Cocoapods

**Cache** is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod 'Cache'
```

### Carthage

**Cache** is also available through [Carthage](https://github.com/Carthage/Carthage).
To install just write into your Cartfile:

```ruby
github "hyperoslo/Cache"
```

You also need to add `SwiftHash.framework` in your [copy-frameworks](https://github.com/Carthage/Carthage#if-youre-building-for-ios-tvos-or-watchos) script.

## Author

- [Hyper](http://hyper.no) made this with ❤
- Inline MD5 implementation from [SwiftHash](https://github.com/onmyway133/SwiftHash)

## Contributing

We would love you to contribute to **Cache**, check the [CONTRIBUTING](https://github.com/hyperoslo/Cache/blob/master/CONTRIBUTING.md) file for more info.

## License

**Cache** is available under the MIT license. See the [LICENSE](https://github.com/hyperoslo/Cache/blob/master/LICENSE.md) file for more info.

license: MIT

repository: hyperoslo/Cache

gha_language: Swift

gha_license_id: NOASSERTION

repo_name: hyperoslo/Cache


text:
# INSTALL Notes for Yara

1. Install yara on each node

    apt-get install yara

 OR

    wget https://code.google.com/p/yara-project/downloads/detail?name=yara-1.7.tar.gz
    wget https://yara-project.googlecode.com/files/yara-1.7.tar.gz
    tar zxvf yara-1.7.tar.gz
    cd yara-1.7
    ./configure && make && sudo make intall

2. install yara python on each node

    pip install yara

 OR

    wget https://yara-project.googlecode.com/files/yara-python-1.7.tar.gz
    tar zxvf yara-python-1.7.tar.gz
    cd yara-python-1.7
    python setup.py build
    sudo python setup.py install

3. run ```hadoop fs -put scripts yara_rules /tmp/```

** May want to install re2 and install both yara and yara-python with re2 support built in


text:
---
# Display name
title: H. Tony Chen

# Is this the primary user of the site?
superuser: true

# Role/position/tagline
role: PhD Student

# Organizations/Affiliations to show in About widget
organizations:
- name: Dartmouth College
  url: https://geiselmed.dartmouth.edu/

# Short bio (displayed in user profile at end of posts)
bio: I do research in biostatistics and epidemiological methods.

# Interests to show in About widget
interests:
- Causal Inference & Mediation
- Missing & Mismeasured Data
- Regularized Regression
- Tree-based Methods
- Cancer Clinical Epidemiology

# Education to show in About widget
education:
  courses:
  - course: Ph.D. in Quantitative Biomedical Sciences
    institution: Dartmouth College, Hanover, NH
    year: 2026 (expected)
  - course: B.S. (summa cum laude) in Biology | Applied Mathematics & Statistics
    institution: Emory University, Atlanta, GA
    year: 2021

# Social/Academic Networking
# For available icons, see: https://sourcethemes.com/academic/docs/page-builder/#icons
#   For an email link, use "fas" icon pack, "envelope" icon, and a link in the
#   form<EMAIL_ADDRESS>or "/#contact" for contact widget.
social:
- icon: envelope
  icon_pack: fas
  link<EMAIL_ADDRESS>- icon: twitter
  icon_pack: fab
  link: https://twitter.com/
- icon: graduation-cap  # Alternatively, use `google-scholar` icon from `ai` icon pack
  icon_pack: fas
  link: https://scholar.google.com/
- icon: github
  icon_pack: fab
  link: https://github.com/
- icon: linkedin
  icon_pack: fab
  link: https://www.linkedin.com/in/tony-c-424362133/

# Link to a PDF of your resume/CV.
# To use: copy your resume to `static/media/resume.pdf`, enable `ai` icons in `params.toml`,
# and uncomment the lines below.
# - icon: cv
#   icon_pack: ai
#   link: media/resume.pdf

# Enter email to display Gravatar (if Gravatar enabled in Config)
email: ""

# Highlight the author in author lists? (true/false)
highlight_name: true
---

I am a first-year PhD student at the [**Quantitative Biomedical Sciences**](https://geiselmed.dartmouth.edu/qbs/) (QBS) Program of Geisel School of Medicine at Dartmouth College. I am a biomedical data scientist and applied biostatistician with multidisplinary trainings in `statistical theory`, `epidemiology`, and `bioinformatics`. My research interests broadly lay on biostatistical methods motivated by analysis of observational studies (_causal inference, missing data, measurement error_) and dealing with high-dimensional variable selection (_regularized regression, random forest_).

I received my undergraduate trainings from Emory University in Biology and Applied Mathematics & Statistics, where I was a [**Quantitative Theory & Methods Research Fellow**](http://quantitative.emory.edu/people/undergraduate-fellows.html) and [**Emory Undergraduate Summer Research Fellow**](http://college.emory.edu/undergraduate-research/summer/index.html).

{{< icon name="download" pack="fas" >}} Download my {{< staticref "media/demo_resume.pdf" "newtab" >}}CV{{< /staticref >}}.


text:
# LaunchDarkly SDK for Java - DynamoDB integration

[![Circle CI](https://circleci.com/gh/launchdarkly/java-server-sdk-dynamodb.svg?style=shield)](https://circleci.com/gh/launchdarkly/java-server-sdk-dynamodb)
[![Javadocs](http://javadoc.io/badge/com.launchdarkly/launchdarkly-java-server-sdk-dynamodb-store.svg)](http://javadoc.io/doc/com.launchdarkly/launchdarkly-java-server-sdk-dynamodb-store)

This library provides a DynamoDB-backed persistence mechanism (data store) for the [LaunchDarkly Java SDK](https://github.com/launchdarkly/java-server-sdk), replacing the default in-memory data store.

This version of the library requires at least version 6.0.0 of the LaunchDarkly Java SDK, and at least version 2.1 of the AWS SDK for Java. For versions of the library to use with earlier SDK versions, see the changelog. The minimum Java version is 8.

See the [API documentation](https://launchdarkly.github.io/java-server-sdk-dynamodb) for details on classes and methods.

For more information, see also: [Using DynamoDB as a persistent feature store](https://docs.launchdarkly.com/sdk/features/storing-data/dynamodb#java).

## Quick setup

This assumes that you have already installed the LaunchDarkly Java SDK.

1. In DynamoDB, create a table which has the following schema: a partition key called "namespace" and a sort key called "key", both with a string type. The LaunchDarkly library does not create the table automatically, because it has no way of knowing what additional properties (such as permissions and throughput) you would want it to have.

2. Add this library to your project (updating the version number to use the [latest release](https://github.com/launchdarkly/java-server-sdk-dynamodb/releases)):

        <dependency>
          <groupId>com.launchdarkly</groupId>
          <artifactId>launchdarkly-java-server-sdk-dynamodb-store</artifactId>
          <version>5.0.0</version>
        </dependency>

3. If you do not already have the AWS SDK in your project, add the DynamoDB part of it. (This needs to be added separately, rather than being included in the LaunchDarkly jar, because AWS classes are exposed in the public interface.)

        <dependency>
          <groupId>software.amazon.awssdk</groupId>
          <artifactId>dynamodb</artifactId>
          <version>2.1.4</version>
        </dependency>

4. Import the LaunchDarkly package and the package for this library:

        import com.launchdarkly.sdk.server.*;
        import com.launchdarkly.sdk.server.integrations.*;

5. When configuring your SDK client, add the DynamoDB feature store:

        LDConfig config = new LDConfig.Builder()
            .dataStore(
                Components.persistentDataStore(
                    DynamoDb.dataStore("my-table-name")
                )
            )
            .build();

By default, the DynamoDB client will try to get your AWS credentials and region name from environment variables and/or local configuration files, as described in the AWS SDK documentation. There are methods in `DynamoDbDataStoreBuilder` for changing the configuration options. Alternatively, if you already have a fully configured DynamoDB client object, you can tell LaunchDarkly to use that:

                Components.persistentDataStore(
                    DynamoDb.dataStore("my-table-name").existingClient(myDynamoDbClientInstance)
                )

## Caching behavior

The LaunchDarkly SDK has a standard caching mechanism for any persistent data store, to reduce database traffic. This is configured through the SDK's `PersistentDataStoreBuilder` class as described the SDK documentation. For instance, to specify a cache TTL of 5 minutes:

        LDConfig config = new LDConfig.Builder()
            .dataStore(
                Components.persistentDataStore(
                    DynamoDb.dataStore("my-table-name")
                ).cacheTime(Duration.ofMinutes(5))
            )
            .build();

## Data size limitation

DynamoDB has [a 400KB limit](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ServiceQuotas.html#limits-items) on the size of any data item. For the LaunchDarkly SDK, a data item consists of the JSON representation of an individual feature flag or segment configuration, plus a few smaller attributes. You can see the format and size of these representations by querying `https://sdk.launchdarkly.com/flags/latest-all` and setting the `Authorization` header to your SDK key.

Most flags and segments won't be nearly as big as 400KB, but they could be if for instance you have a long list of user keys for individual user targeting. If the flag or segment representation is too large, it cannot be stored in DynamoDB. To avoid disrupting storage and evaluation of other unrelated feature flags, the SDK will simply skip storing that individual flag or segment, and will log a message (at ERROR level) describing the problem. For example:

```
    The item "my-flag-key" in "features" was too large to store in DynamoDB and was dropped
```

If caching is enabled in your configuration, the flag or segment may still be available in the SDK from the in-memory cache, but do not rely on this. If you see this message, consider redesigning your flag/segment configurations, or else do not use DynamoDB for the environment that contains this data item.

This limitation does not apply to target lists in [Big Segments](https://docs.launchdarkly.com/home/users/big-segments/).

A future version of the LaunchDarkly DynamoDB integration may use different strategies to work around this limitation, such as compressing the data or dividing it into multiple items. However, this integration is required to be interoperable with the DynamoDB integrations used by all the other LaunchDarkly SDKs and by the Relay Proxy, so any such change will only be made as part of a larger cross-platform release.

## About LaunchDarkly

* LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard.  With LaunchDarkly, you can:
    * Roll out a new feature to a subset of your users (like a group of users who opt-in to a beta tester group), gathering feedback and bug reports from real-world use cases.
    * Gradually roll out a feature to an increasing percentage of users, and track the effect that the feature has on key metrics (for instance, how likely is a user to complete a purchase if they have feature A versus feature B?).
    * Turn off a feature that you realize is causing performance problems in production, without needing to re-deploy, or even restart the application with a changed configuration file.
    * Grant access to certain features based on user attributes, like payment plan (eg: users on the ‘gold’ plan get access to more features than users in the ‘silver’ plan). Disable parts of your application to facilitate maintenance, without taking everything offline.
* LaunchDarkly provides feature flag SDKs for a wide variety of languages and technologies. Read [our documentation](https://docs.launchdarkly.com/sdk) for a complete list.
* Explore LaunchDarkly
    * [launchdarkly.com](https://www.launchdarkly.com/ "LaunchDarkly Main Website") for more information
    * [docs.launchdarkly.com](https://docs.launchdarkly.com/  "LaunchDarkly Documentation") for our documentation and SDK reference guides
    * [apidocs.launchdarkly.com](https://apidocs.launchdarkly.com/  "LaunchDarkly API Documentation") for our API documentation
    * [blog.launchdarkly.com](https://blog.launchdarkly.com/  "LaunchDarkly Blog Documentation") for the latest product updates

repository: launchdarkly/java-server-sdk-dynamodb

branch_name: refs/heads/main

gha_language: Java

repo_name: launchdarkly/java-server-sdk-dynamodb


text:
Grove - High Temperature Sensor  [![Build Status](https://travis-ci.com/Seeed-Studio/Grove_HighTemp_Sensor.svg?branch=master)](https://travis-ci.com/Seeed-Studio/Grove_HighTemp_Sensor)
-------------------------------------------------------------

[Grove - High Temperature Sensor](https://www.seeedstudio.com/Grove-High-Temperature-Sensor-p-1810.html)

Thermocouples are very sensitive, requiring a good amplifier with a cold - compensation reference. The Grove - Temperature Sensor USES a K type thermocouple Temperature detection, with a Thermistor to detect The ambient Temperature as Temperature compensation. The detectable range of this Sensor is -50-600℃ , and The accuracy is ±(2.0% + 2℃)

For more information please visit [wiki page](http://wiki.seeedstudio.com/Grove-High_Temperature_Sensor/).

----
This software is written by Loovee for seeed studio

and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt for more information.

Contributing to this software is warmly welcomed. You can do this basically by

[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above

for operating guide). Adding change log and your contact into file header is encouraged.

Thanks for your contribution.

Seeed Studio is an open hardware facilitation company based in Shenzhen, China.

Benefiting from local manufacture power and convenient global logistic system,

we integrate resources to serve new era of innovation. Seeed also works with

global distributors and partners to push open hardware movement.

[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Grove_HighTemp_Sensor)](https://github.com/igrigorik/ga-beacon)


text:
This exercise will ensure your system is ready for some serious coding at TWG.
If you're already setup, verify with

    twg-onboarding verify

## Install homebrew

    ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

## Install rbenv

    brew install rbenv

## Install node

    brew install node

## Install postgres

    brew install postgres

## Install POW

    curl get.pow.cx | sh

## Install ALL THE OTHER THINGS!

    brew install ALL_THE_OTHER_THINGS!

repository: jacobmoe/twg-onboarding

repo_name: jacobmoe/twg-onboarding


text:
---
layout: page
title: Using AI and real-time data to power an early warning system for public safety and the recognition of emotions
parent: Platforms/Infrastructure
grand_parent: Projects
nav_order: 17
---

# Using AI and real-time data to power an early warning system for public safety and the recognition of emotions
*Partner: Dacher	Keltner, UC Berkeley, Academic*

## Overview
### Project Description
We will build an AI system to detect negative emotion from vocalizations recorded by body cameras warn by police (building upon several published papers in my lab) and develop a warning system for police officers, that informs them of when their emotions are escalating to risky or aggressive behavior.
### Expected Deliverable
A Machine Learning algorithm for detecting emotion in the voice from police body cameras.  The beginning frame for developing an app that provides emotion specific feedback.
### What would a successful semester look like to you?
Build data base, train Machine Learning on that data base for successful classification.

## Data

## Models

## Conclusion

```python

```

path: /Projects/Platforms_Infrastructure/Using AI and real-time data.md

filename: Using AI and real-time data.md


text:
---
title: Lecture
custom_edit_url: https://github.com/cryptoeconomics-study/lectures//blob/master/ch1/1.2/lecture.md
hide_title: false
---

# Payment Processor Implementation
- Implementing a payment processor using the account model. Learn about state, state transitions, and replay protection.

# Slides

[Gooogle Sheets Link](https://docs.google.com/presentation/d/11HU5a3gVsU3N68Jfc6JMY_gH4MDTdKNlm0j0vqZETQU/edit#slide=id.g3b69596d2b_0_0)

# Ch1.2 Overview

## State

What is a state?
- A state is a particular configuration of data.

Examples of state:
- the physical world at any point in time
- a blockchain at a particular block
- a chess board after a player makes a move

## State Transition Function

What is a state transition function?
- a set of rules that determines how to transition the state from one configuration to another

Examples of state transition functions:
- the laws of physics
- the rules of a blockchain protocol
- the rules of chess

## Overview of PayPal structure

The state object which is a mapping of address->balance

There are two types of state mutations (each with their own logic)
1) `mint`
2) `send`

We start with an initial state (ie `genesis block`). We then receive transactions, and based on our state transition function reject invalid transactions and process valid transactions (ie create `blocks`). We then store the history of all transactions in a big ledger (ie a `blockchain`). Everyone's current accounts and balances is the current state (ie the latest `block`).
- The list of transactions (`blocks`) is called the “history”
- The result of computing all the transactions in the history leads to the current “state”
- In Ethereum the full history is approx 250 GB, while the state is approx 3 GB.

> Fun aside: Rent proposals say that people should pay rent on the state storage which they take up. There is no direct incentive to store the history, and so nodes today often do prune or delete historical data. If this happens too much there is a risk that we can’t recreate the chain anymore!

## Recommended Resources

[But how does a blockchain work?](https://www.youtube.com/watch?v=bBC-nXj3Ng4&feature=youtu.be) - Awesome video by 3Blue1Brown explaining how blockchains work.

[Anders Brownworth's blockchain demo](https://anders.com/blockchain/blockchain.html) - Put data in a block, "mine" (hash) it, then add data to the next block, "mine" (hash) it, etc... The "mine" button perfoms the state transition function and you can see the history (blockchain) being created right in front of you.

[Ethviewer](http://www.ethviewer.live/) - Live Ethereum blockchain visualization.

[Blockscout Ethereum block explorer](https://blockscout.com/eth/mainnet/) - You can see the current state of the Ethereum blockchain by clicking on the latest block. You can also explore the history by clicking on past blocks and seeing the transactions that were processed in that state transition function. You can also search for the current state of any account or contract.

Conways's Game Of Life
- [Wikipedia](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) - Explains the rules of the game (state transition function) and shows some fun demos.
- [Peter Daily's React implimentation of the Game of Life](https://thepeted.github.io/game-of-life-redux/) - Let's you play the game (really start it and watch it unfold).
- [Code for the above demo](https://github.com/thepeted/game-of-life-redux)

repository: EnochMbaebie/website

repo_name: EnochMbaebie/website


text:
# Coherence

## [Ontology](./ontology.md)

A set of one to many [Entities](./entity.md) acting in unison & [agreement](./agreement.md) with themselves & each other.

## [Axiology](./axiology.md)

Coherence increases the [Intelligence](./intelligence.md), efficiency, & capabilities of all of the Entities.

## [Epistemology](./epistemology.md)

### [Cultural](./culture.md) Definition

coherence (wiktionary)

> ### Noun

> Quality of cohering; of being coherent; internal consistency.

> a logical arrangement of parts "His arguments lacked coherence."

> (physics, of waves) the property of having the same wavelength and phase.

> (linguistics) Semantic relationship between different parts of the same text.

Coherence (Physics) (Wikipedia)

> Spatial coherence describes the correlation between waves at different points in space. Temporal coherence describes the correlation or predictable relationship between waves observed at different moments in time.

Coherence (Wikipedia)

Effects of Meditation on Brain Coherence and Intelligence (meditationplex.com)

### [Pattern](./pattern.md) Expression

Coherence is a pattern that is applicable anywhere in [Existence](./existence.md).

repository: btakita/philosophy

repo_name: btakita/philosophy


text:
---
layout: default
title: Graph View
parent: Visualisation
grand_parent: User guide
nav_order: 2
---

# Graph View

This section covers all of the rules which can be applied to a graph view. As mentioned in previous section a graph view can be defined as shown below:

```js
view = View.graph()
```

1) Width

Allows you to set the width of graph component. The argument value is considered as pixels.

```js
view.graph().width(100)
```

2) Height

Allows you to set the height of graph component. The argument value is considered as pixels.

```js
view.graph().width(100).height(50)
```

3) show_force

Provides a Gravitational view over the graph component. If set to false the graoh would simply appear rather than the floating effect.

```js
view.graph().width(100).show_force(true)
```
4) source

Alters the graph's view by treating the element mentioned in argument as the graph's source

```js
view.graph().source("v:A")
```

5) color

You can set color for graph's nodes in rgb format.

```js
view.graph().node("v:A").color([233, 54, 65])
```

5) fontfamily

Helps you to load icon families. By default Font Awesome is used here.

```js
view.graph().fontfamily('font')
```

6) edges

Alters the direction of edges pointing, based on values provided as arguments

```js
view.graph().edges(["v:B","v:A"])
```

repository: AndrewO/terminusdb-doc

gha_license_id: MIT

repo_name: AndrewO/terminusdb-doc


text:
---
title: v1.0.2 Release
date: 2020-12-02
tags: ['release', 'jbrowse 2']
---

This release addresses two main issues:

- A bug introduced in v1.0.1 where the CLI command `jbrowse create` would not
  download the latest version of JBrowse Web.
- A fix for a problem that prevented `@jbrowse/react-linear-genome-view` (first
  released in v1.0.1) from working properly.

Several other bug fixes and improvements are also included. See details below.

## Downloads

- [v1.0.2](https://github.com/GMOD/jbrowse-components/releases/tag/v1.0.2)

To install JBrowse 2 for the web, you can download the link above, or you can
use the JBrowse CLI to automatically download the latest version. See the
[JBrowse web quick start](https://jbrowse.org/jb2/docs/quickstart_web) for more
details.

## v1.0.2 (2020-12-02)

#### :rocket: Enhancement

- `core`
  - [#1513](https://github.com/GMOD/jbrowse-components/pull/1513) Add a custom
    scrollbar that overrides the auto-hiding behavior of scrollbars on OSX
    ([@elliothershberg](https://github.com/elliothershberg))

#### :bug: Bug Fix

- Other
  - [#1514](https://github.com/GMOD/jbrowse-components/pull/1514)
    react-linear-genome-view bug fixes
    ([@garrettjstevens](https://github.com/garrettjstevens))
  - [#1517](https://github.com/GMOD/jbrowse-components/pull/1517) Fix the use of
    filtering display on desktop ([@cmdcolin](https://github.com/cmdcolin))
  - [#1512](https://github.com/GMOD/jbrowse-components/pull/1512) Fix setting
    maxDisplayedBpPerPx for pileup display, helps prevent too large an area from
    being rendered ([@cmdcolin](https://github.com/cmdcolin))
  - [#1442](https://github.com/GMOD/jbrowse-components/pull/1442) Change track
    selector togglebutton to normal button
    ([@cmdcolin](https://github.com/cmdcolin))
  - [#1506](https://github.com/GMOD/jbrowse-components/pull/1506) Fix
    horizontally flipped translation frames position
    ([@cmdcolin](https://github.com/cmdcolin))
  - [#1501](https://github.com/GMOD/jbrowse-components/pull/1501) Fix CLI to
    allow jbrowse create to download newer monorepo tag format
    ([@cmdcolin](https://github.com/cmdcolin))
- `core`
  - [#1505](https://github.com/GMOD/jbrowse-components/pull/1505) Fix loading of
    local files in jbrowse-desktop ([@cmdcolin](https://github.com/cmdcolin))

#### Committers: 3

- Colin Diesh ([@cmdcolin](https://github.com/cmdcolin))
- Elliot Hershberg ([@elliothershberg](https://github.com/elliothershberg))
- Garrett Stevens ([@garrettjstevens](https://github.com/garrettjstevens))

repository: GMOD/jbrowse-components

gha_language: TypeScript

repo_name: GMOD/jbrowse-components


text:
---
title: quser.exe | Query User Utility
excerpt: What is quser.exe?
---

# quser.exe

* File Path: `C:\Windows\SysWOW64\quser.exe`
* Description: Query User Utility

## Hashes

Type | Hash
-- | --
MD5 | `C56FB0AA843D2D58F3166F6708B4613F`
SHA1 | `8DB5D2B2109CA42AD231553EADF0D6B01F2A1545`
SHA256 | `8A56B2B043ED340FFEEC3845498005EBF972AF3B937340F0FBA064EA014AB1BB`
SHA384 | `294DE575B62F43C68F615CD7775D445CD45820321B4F0DE8B64CF75181EC708D4F56A244A0E9A4AA33ED8B6A27962BE6`
SHA512 | `7DF28E5D792F52270E51FF355EF3F067C84AAD90425F6287E4D7C9038F9D2B1195A416B742C3D190321641215158FE7244BF9664E401DA8E670AF5C943700485`
SSDEEP | `384:2DFv6/9BVUogQjfR+/kyF7rASHJwnhHVJPwWU273XWSjFWu5:2DBgBKoFQ/MHK2TXp5`
IMP | `E9E1589ED6F2469789346FC3BDABFCE5`
PESHA1 | `E80BF2159DB6CC9D10B87FC1A8ED263444B9020E`
PE256 | `9F21FA1546849608346AA60553292B7E253698FF22B624D7327A2F2BC258FCD3`

## Runtime Data

### Usage (stdout):
```cmhg
Display information about users logged on to the system.

QUERY USER [username | sessionname | sessionid] [/SERVER:servername]

  username            Identifies the username.
  sessionname         Identifies the session named sessionname.
  sessionid           Identifies the session with ID sessionid.
  /SERVER:servername  The server to be queried (default is current).

```

### Usage (stderr):
```cmhg
Invalid parameter(s)
Display information about users logged on to the system.

QUERY USER [username | sessionname | sessionid] [/SERVER:servername]

  username            Identifies the username.
  sessionname         Identifies the session named sessionname.
  sessionid           Identifies the session with ID sessionid.
  /SERVER:servername  The server to be queried (default is current).

```

### Child Processes:
powershell.exe

### Loaded Modules:

Path |
-- |
C:\Windows\SYSTEM32\ntdll.dll |
C:\Windows\System32\wow64.dll |
C:\Windows\System32\wow64cpu.dll |
C:\Windows\System32\wow64win.dll |
C:\Windows\SysWOW64\quser.exe |

## Signature

* Status: Signature verified.
* Serial: `33000001C422B2F79B793DACB20000000001C4`
* Thumbprint: `AE9C1AE54763822EEC42474983D8B635116C8452`
* Issuer: CN=Microsoft Windows Production PCA 2011, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
* Subject: CN=Microsoft Windows, O=Microsoft Corporation, L=Redmond, S=Washington, C=US

## File Metadata

* Original Filename: quser.exe.mui
* Product Name: Microsoft Windows Operating System
* Company Name: Microsoft Corporation
* File Version: 10.0.17763.1 (WinBuild.160101.0800)
* Product Version: 10.0.17763.1
* Language: English (United States)
* Legal Copyright:  Microsoft Corporation. All rights reserved.
* Machine Type: 32-bit

## File Scan

* VirusTotal Detections: 0/67
* VirusTotal Link: https://www.virustotal.com/gui/file/8a56b2b043ed340ffeec3845498005ebf972af3b937340f0fba064ea014ab1bb/detection/

## Possible Misuse

*The following table contains possible examples of `quser.exe` being misused. While `quser.exe` is **not** inherently malicious, its legitimate functionality can be abused for malicious purposes.*

Source | Source File | Example | License
-- | -- | -- | --
[sigma](https://github.com/Neo23x0/sigma) | [win_local_system_owner_account_discovery.yml](https://github.com/Neo23x0/sigma/blob/master/rules/windows/process_creation/win_local_system_owner_account_discovery.yml) | `- '\quser.exe'`{:.highlight .language-yaml} | [DRL 1.0](https://github.com/Neo23x0/sigma/blob/master/LICENSE.Detection.Rules.md)
[sigma](https://github.com/Neo23x0/sigma) | [win_multiple_suspicious_cli.yml](https://github.com/Neo23x0/sigma/blob/master/rules/windows/process_creation/win_multiple_suspicious_cli.yml) | `- quser.exe`{:.highlight .language-yaml} | [DRL 1.0](https://github.com/Neo23x0/sigma/blob/master/LICENSE.Detection.Rules.md)
[sigma](https://github.com/Neo23x0/sigma) | [win_webshell_detection.yml](https://github.com/Neo23x0/sigma/blob/master/rules/windows/process_creation/win_webshell_detection.yml) | `- '\quser.exe'`{:.highlight .language-yaml} | [DRL 1.0](https://github.com/Neo23x0/sigma/blob/master/LICENSE.Detection.Rules.md)
[atomic-red-team](https://github.com/redcanaryco/atomic-red-team) | [T1033.md](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1033/T1033.md) | quser /SERVER:"#{computer_name}" | [MIT License. © 2018 Red Canary](https://github.com/redcanaryco/atomic-red-team/blob/master/LICENSE.txt)
[atomic-red-team](https://github.com/redcanaryco/atomic-red-team) | [T1033.md](https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1033/T1033.md) | quser | [MIT License. © 2018 Red Canary](https://github.com/redcanaryco/atomic-red-team/blob/master/LICENSE.txt)

## Additional Info*

**The information below is copied from [MicrosoftDocs](https://github.com/MicrosoftDocs/windowsserverdocs), which is maintained by [Microsoft](https://opensource.microsoft.com/codeofconduct/). Available under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) license.*

---

## quser

>Applies to: Windows Server 2022, Windows Server 2019, Windows Server 2016, Windows Server 2012 R2, Windows Server 2012

Displays information about user sessions on a Remote Desktop Session Host server. You can use this command to find out if a specific user is logged on to a specific Remote Desktop Session Host server. This command returns the following information:

- Name of the user

- Name of the session on the Remote Desktop Session Host server

- Session ID

- State of the session (active or disconnected)

- Idle time (the number of minutes since the last keystroke or mouse movement at the session)

- Date and time the user logged on

> [!NOTE]
> This command is the same as the [query user command](https://github.com/MicrosoftDocs/windowsserverdocs/tree/master/WindowsServerDocs/administration/windows-commands/query-user.md). To find out what's new in the latest version, see [What's New in Remote Desktop Services in Windows Server](/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn283323(v=ws.11)).

### Syntax

```
quser [<username> | <sessionname> | <sessionID>] [/server:<servername>]
```

#### Parameters

| Parameter | Description |
|--|--|
| `<username>` | Specifies the logon name of the user that you want to query. |
| `<sessionname>` | Specifies the name of the session that you want to query. |
| `<sessionID>` | Specifies the ID of the session that you want to query. |
| /server:`<servername>` | Specifies the Remote Desktop Session Host server that you want to query. Otherwise, the current Remote Desktop Session Host server is used. This parameter is only required if you're using this command from a remote server. |
| /? | Displays help at the command prompt. |

##### Remarks

- To use this command, you must have Full Control permission or special access permission.

- If you don't specify a user using the <*username*>, <*sessionname*>, or *sessionID* parameters, a list of all users who are logged on to the server is returned. Alternatively, you can also use the **query session** command to display a list of all sessions on a server.

- When **quser** returns information, a greater than `(>)` symbol is displayed before the current session.

#### Examples

To display information about all users logged on the system, type:

```
quser
```

To display information about the user *USER1* on server *Server1*, type:

```
quser USER1 /server:Server1
```

### Additional References

- [Command-Line Syntax Key](https://github.com/MicrosoftDocs/windowsserverdocs/tree/master/WindowsServerDocs/administration/windows-commands/command-line-syntax-key.md)

- [query user command](https://github.com/MicrosoftDocs/windowsserverdocs/tree/master/WindowsServerDocs/administration/windows-commands/query-user.md)

- [Remote Desktop Services (Terminal Services) Command Reference](https://github.com/MicrosoftDocs/windowsserverdocs/tree/master/WindowsServerDocs/administration/windows-commands/remote-desktop-services-terminal-services-command-reference.md)

---

MIT License. Copyright (c) 2020-2021 Strontic.


text:
# rayskeleton

A simple to use and build skeleton project for raylib. Uses CMake.

# Building and running in 6 easy steps

The commands here will bootstrap your rayskeleton project with it's own raylib
instance (and all of its dependencies). Raylib is automatically downloaded and
built by the bootstrap script.

    $ git clone git@github.com:oswjk/rayskeleton.git
    $ cd rayskeleton
    $ ./bootstrap.sh
    $ cd build
    $ make
    $ ./src/rayskeleton

# Building and running with a prebuilt/installed raylib

If you have built raylib yourself and want to use the same local raylib
installation for multiple projects, you can easily do that by setting the
LOCAL_RAYLIB CMake variable. The variable must point to a directory where you
have installed raylib (i.e., it contains bin, lib, include, etc.)

In this example I have built raylib in a directory at the same level as
rayskeleton, using a build directory named `build` and installed raylib under
the build directory in a directory named `stage`.

    $ git clone git@github.com:oswjk/rayskeleton.git
    $ cd rayskeleton
    $ mkdir build
    $ cd build
    $ cmake -DCMAKE_INSTALL_PREFIX=stage -DLOCAL_RAYLIB=../raylib/build/stage ..
    $ make
    $ ./src/rayskeleton

license: Zlib

repository: MSylvia/rayskeleton

repo_name: MSylvia/rayskeleton


text:
[Source](http://dotnetcodr.com/2013/03/04/claims-based-authentication-in-mvc4-with-net4-5-c-part-3-claims-based-authorisation/ "Permalink to Claims-based authentication in MVC4 with .NET4.5 C# part 3: claims based authorisation")

# Claims-based authentication in MVC4 with .NET4.5 C# part 3: claims based authorisation

In the [previous post][1] we discussed how to the save the authentication session so that we didn't need to perform the same auth logic on every page request. In this post we will look at how authorisation can be performed using claims in an MVC project.

**Introduction**

There are two main approaches to authorisation in an ASP.NET web application: pipeline authorisation and Intra-app authorisation.

**Pipeline auth** means performing coarse grained, URL-based authorisation. You may require the presence of a valid auth header in every request that comes to your server. Or the authenticated user must be in a certain Role in order to reach a certain protected URL. The advantage with this approach is that authorisation happens very early in the application lifecycle so you can reject a request very early on. In this scenario you will typically have little info about the user and what resource they are trying to access but these can be enough to reject a large number of users.

An example of pipeline auth in our simple MVC4 web we've been working on this series can be found in CustomClaimsTransformer.Authenticate. This is the stage where you can check the presence of a certain claim that your auth logic absolutely must have in order to make an early decision. If it's missing, then you may not care about what the user is trying to do, the request will be rejected.

Another example of pipeline auth comes from the good old 'location' elements in an ASP.NET web forms config where you could specify URL-based auth:

    <location path="customers">
        <system.web>
          <authorization>
            <allow roles="IT"/>
            <deny users="*"/>
          </authorization>
        </system.web>
      </location>

This is an acceptable approach in web-forms projects where the URL has a close affinity to the project file system, i.e. the value of the 'path' attribute represents an .aspx file. In MVC /Customers will of course not lead to an aspx page called Customers. In MVC urls and resources are unlikely to have a one-to-one match. You don't call physical files the same way as in a web-forms app. If the routing mechanism is changed then the path attribute will be meaningless. So all of a sudden people will have access to previously protected parts of your web app. Generally try to avoid this approach in an MVC application as it creates a tight coupling between the routing table and the project file structure.

Yet another example of pipeline auth is the ClaimsAuthorisationManager which can be registered in the web.config. This will sound familiar to you if you looked at the [post][2] on the very basics of claims. This is also a URL based approach, but it's based on Claims and not Roles.

**Intra-app auth** on the other hand means fine-grained checks within your code logic. The benefit is that you have the chance to collect as much information as possible about the user and the resources they are trying to use. Then you can tweak your authorisation logic on a wider information basis. In this scenario you will have more info on the user and make your reject/accept decision later in the app lifecycle than in the Pipeline auth scenario.

A definite advantage of this approach is that it is not URL based any more so it is independent of the routing tables. You will have more knowledge about the authorisation domain because you'll typically know exactly what claims the user holds and what they are trying to achieve on your site.

**PrincipalPermission and ClaimsPrincipalPermission**

You can follow a declarative approach using the ClaimsPrincipalPermission attribute or an imperative one within the method body. Either way you'll work with Claims and not Roles as in the 'old' days with the well-known 'Role="IT"' and .IsInRole("Admin") type of checks:

    [PrincipalPermission(SecurityAction.Demand, Role="IT")]

The old way of performing authorisation is not recommended now that we have access to claims in .NET4.5. Roles encouraged you to mix authorisation and business logic and they were limited to, well, Roles as the way of controlling access. However, you might have required more fine-grained control over your decision making. Then you ended up with specialised roles, like Admin, SuperAdmin, SuperSuperAdmin, MarketingOnThirdFloor etc. Decorating your methods with the PrincipalPermission attribute also disrupts unit testing as even the unit testing thread must have a User in the Role specified in the attribute. Also, if the current principal is not in the required group then an ugly security exception is thrown which you have to deal with somehow.

In [this][2] post we saw a detailed discussion on the ClaimsPrincipalPermission which replaces the PrincipalPermission. Here comes an example to refresh your memory:

    [ClaimsPrincipalPermission(SecurityAction.Demand, Operation="Show", Resource="Code")]

In short: we don't care which group or role the user is in any longer. This attribute describes the method it decorates. It involves a 'Show' operation on the 'Code' resource. If the current user wants to run this method then they better make sure that they have these claims. It will be the ClaimsAuthorizationManager that decides if the current principal is allowed to call the action 'Show' on the resource 'Code'. The principal still must have certain claims, just like they had to be in a certain Role before. However, the authorisation logic is now separated out to a different part of the application. You can even have that logic in a web service on a different machine so that the auth logic can be handled entirely separately from your application.

Another benefit is the following: what constitutes a certain Role can change over time. What is 'IT'? Who belongs to that group? So later on you may have to come back to every method with the attribute 'Role="IT"' and change it to e.g. "Geeks" because 'IT' has changed its definition at your company. On the other hand a method that has the function to 'Show' a resource called 'Code' will probably have that function over a long time, possible over the entire life time of the finalised production version of the application.

So, this attribute solves some of the problems with the PrincipalPermission. However, it does not solve all of them. It still gets in the way of unit testing and it still throws a SecurityException.

**The Authorize attribute**

The MVC 'equivalent' of the ClaimsPrincipal attribute is the Authorize attribute. It is still limited to roles:

    [Authorize]
    public ActionResult ShowMeTheCode()

    [Authorize(Roles="IT")]
    public ActionResult ShowMeTheCode()

It does not use the action/resource properties of the method and you still mix your auth logic with the 'real' application code leading to the same Separation of Concerns problem we mentioned above. However, this attribute is not invoked during unit testing and it does not throw Exceptions either. Instead, it returns a 404 which is a lot nicer way of dealing with unauthorised access.

We are only one step from the MVC4 claims-based authorisation nirvana. It would be great to have an Authorize attribute where you can specify the Resource and the Action just like in the case of ClaimsPrincipalPermission. You could derive from the existing Authorize attribute and implement this kind of logic there. The good news is that this has been done for you and it can be downloaded from NuGet. The NuGet package includes the imperative equivalent of the declarative attribute as well. So if you need to check if the user has access rights within a certain method, then there's a claims-enabled solution in MVC4. We'll use this attribute in the demo.

**Demo**

The initial steps of building the authorisation module have been outlined in [this][2] blog post. I will not repeat all of the details here again.

Open up the project where we left off in the previous blog post. If you remember then we included a CustomClaimsTransformer class to implement our own claims transformation logic. This is our claims based authentication module. We would like to extend the project to include authorisation as well.

First add a new class to the web project called CustomAuthorisationManager. It will need to derive from ClaimsAuthorizationManager in the System.Security.Claims namespace:

    public class CustomAuthorisationManager : ClaimsAuthorizationManager
        {
            public override bool CheckAccess(AuthorizationContext context)
            {
                return base.CheckAccess(context);
            }
        }

Recall that you can extract the Resource, the Action and the Principal from the AuthorizationContext object parameter.

Now let's say we want to make sure that only those with the name Andras who live in Sweden are allowed to view the code. I would do it as follows:

    public override bool CheckAccess(AuthorizationContext context)
            {
                string resource = context.Resource.First().Value;
                string action = context.Action.First().Value;

                if (action == "Show" && resource == "Code")
                {
                    bool livesInSweden = context.Principal.HasClaim(ClaimTypes.Country, "Sweden");
                    bool isAndras = context.Principal.HasClaim(ClaimTypes.GivenName, "Andras");
                    return isAndras && livesInSweden;
                }

                return false;
            }

Set a breakpoint at the first row of the method body, we'll need it later.

This should be straightforward: we extract the Action and the Resource – note that there can be multiple values, hence the 'First()' – and then check where the user lives and what their given name is. If those claims are missing or are not set to the required values then we return false.

Next we have to register this class in the web.config under the claimsAuthenticationManager we registered in the previous part:

    <system.identityModel>
        <identityConfiguration>
          <claimsAuthenticationManager type="ClaimsInMvc4.CustomClaimsTransformer,ClaimsInMvc4" />
          <claimsAuthorizationManager type="ClaimsInMvc4.CustomAuthorisationManager,ClaimsInMvc4"/>
        </identityConfiguration>
      </system.identityModel>

The type attribute is formatted as follows: [namespace.classname],[assembly].

Next we want to make sure that this logic is called when a protected action is called. We will try the claims-enabled version of the MVC4 Authorize attribute. Right-click 'References' and select 'Manage NuGet Packages…'. Search for 'Thinktecture' and install the below package:

![Thinktecture auth package NuGet][3]

This package will give you access to a new attribute called ClaimsAuthorize where you can pass in the Action and Resource parameters.

Imagine that our About page includes some highly sensitive data that can only be viewed by the ones specified in CustomAuthorisationManager.CheckAccess. So let's decorate the About action of the Home controller. Note that the attribute comes in two versions: one for MVC4 and one for WebAPI. If you haven't heard of Web API, then it is a technology to build RESTful web services whose structure is very much based on MVC. You can read more about it [here][4].

Reference the version for Mvc:

![Two versions of claims authorize][5]

…and decorate the About action as follows:

    [ClaimsAuthorize("Show", "Code")]
            public ActionResult About()
            {
                ViewBag.Message = "Your app description page.";

                return View();
            }

This is telling us that the About action will perform a 'Show' action on the resource called 'Code'.

Run the application now. Click on the 'About' link without logging in first. You should be redirected to the Log-in page. Enter the username and password and press the 'Log in' button. If everything went well then code execution should stop at our breakpoint within CustomAuthorisationManager.CheckAccess. Step through the method using F11 to see what happens. You can even inspect the AuthorizationContext object in the Locals window to see what it contains:

![AuthorizationContext object][6]

If the logged on user has the correct claims then you should be redirected to the About page. I will here again stress the point of getting away from the traditional Roles based authorisation of ASP.NET. We are not dealing with Roles any longer. We do not care who is in which group. Instead we describe using the Action and Resource parameters of the ClaimsAuthorize attribute what the logged on user is trying to achieve on our website. Based on that information we can make a better decision using the claims of the user whether to allow or deny access. The auth logic is separated away from the 'real' application in a class on its own which is called automatically if it is registered in web.config. The auth logic can even be 'outsourced' to a web service which can even be the basis of a separate user management application.

You can specify multiple Resource values in the attribute as follows:

    [ClaimsAuthorize("Show", "Code", "TvProgram", "Fireworks")]
            public ActionResult About()
            {
                ViewBag.Message = "Your app description page.";

                return View();
            }

…i.e. you just pass in the names of the Resources after the Action.

You can achieve the same imperatively within the method body as follows:

    public ActionResult About()
            {
                if (ClaimsAuthorization.CheckAccess("Show", "Code"))
                {
                    ViewBag.Message = "This is the secret code.";
                }
                else
                {
                    ViewBag.Message = "Too bad.";
                }

                return View();
            }

The CheckAccess method has an overloaded version which accepts an AuthorizationContext object, which gives the highest degree of freedom to specify all the resources and actions that are needed by the auth logic.

In case you wish to protect the entire controller, then it's possible as well:

    [ClaimsAuthorize("Show", "Everything")]
        public class HomeController : Controller

If you want to apply the attribute to the entire application you can do it by adding the attribute to the global filters in App_Data/FilterConfig as follows:

    public class FilterConfig
        {
            public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            {
                filters.Add(new HandleErrorAttribute());
                filters.Add(new ClaimsAuthorizeAttribute());
            }
        }

This discussion should be enough for you to get started with Claims-based authentication and authorisation in an MVC4 internet application. In the next post we'll start looking at separating out the login mechanism entirely: Single SignOn and Single SignOut.

You can view the list of posts on Security and Cryptography [here][7].

### Like this:

Like Loading...

### _Related_

[1]: http://dotnetcodr.com/2013/02/28/claims-based-authentication-in-mvc4-with-net4-5-c-part-2-storing-authentication-data-in-an-authentication-session/ "Claims-based authentication in MVC4 with .NET4.5 C# part 2: storing authentication data in an authentication session"
[2]: http://dotnetcodr.com/2013/02/21/introduction-to-claims-based-security-in-net4-5-with-c-part-4-authorisation-with-claims/ "Introduction to Claims based security in .NET4.5 with C# Part 4: authorisation with claims"
[3]: http://dotnetcodr.files.wordpress.com/2013/02/thinktectureidentitymodelnuget.png?w=300&h=46
[4]: http://www.asp.net/web-api "Web API"
[5]: http://dotnetcodr.files.wordpress.com/2013/02/twoversionsofclaimsauthorize.png?w=300&h=67
[6]: http://dotnetcodr.files.wordpress.com/2013/02/authorizationcontextobject.png?w=300&h=87
[7]: http://dotnetcodr.com/security-and-cryptography/ "Security and cryptography"

repository: forcewake/articles-for-translation

repo_name: forcewake/articles-for-translation