text:
# gatsby-source-drupal

Source plugin for pulling data (including images) into Gatsby from Drupal sites.

It pulls data from Drupal 8/9 sites with the
[Drupal JSONAPI module](https://www.drupal.org/project/jsonapi) installed.

An example site built with the headless Drupal distro
[ContentaCMS](https://twitter.com/contentacms) is at
https://using-drupal.gatsbyjs.org/

The `apiBase` option allows changing the API entry point depending on the version of
jsonapi used by your Drupal instance. The default value is `jsonapi`, which has
been used since jsonapi version `8.x-1.0-alpha4`.

## Install

`npm install gatsby-source-drupal`

## How to use

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
      },
    },
  ],
}
```

On the Drupal side, we highly recommend installing [JSON:API
Extras](https://www.drupal.org/project/jsonapi_extras) and enabling "Include
count in collection queries" `/admin/config/services/jsonapi/extras` as that
[speeds up fetching data from Drupal by around
4x](https://github.com/gatsbyjs/gatsby/pull/32883).

Previously Gatsby would fetch all image files during the Gatsby build process, transform them for frontend performance, and then serve them as static files on the frontend.
 The first front-end visitor of any image will transform that image and cache it for all other users. Image CDN works on all hosting platforms like Gatsby Cloud or Netlify.

- [Image CDN blog post](https://www.gatsbyjs.com/blog/image-cdn-lightning-fast-image-processing-for-gatsby-cloud/)
- [What is Image CDN?](https://support.gatsbyjs.com/hc/en-us/articles/4426379634835-What-is-Image-CDN-)
- [How to enable Image CDN on Gatsby Cloud](https://support.gatsbyjs.com/hc/en-us/articles/4426393233171-How-to-Enable-Image-CDN)

#### Querying for Gatsby Image CDN fields

Follow [this guide](https://support.gatsbyjs.com/hc/en-us/articles/4426393233171-How-to-Enable-Image-CDN) to understand how to use the new `gatsbyImage` GraphQL field.

#### Turning off file downloads

When you're using Gatsby Image CDN you no longer need Gatsby to fetch all of the files in your Drupal instance. Turn that off with the following plugin option. This is required for Image CDN to work.

```js
  {
    resolve: `gatsby-source-drupal`,
    options: {
      skipFileDownloads: true,
      // other plugin options go here
    },
  },
```

Note that this option will cause this plugin to fetch extra image metadata for Image CDN. If you need to use the `skipFileDownloads` option but don't want to use Image CDN and fetch extra metadata, you can disable it by explicitly turning Image CDN off:

```js
  {
    resolve: `gatsby-source-drupal`,
    options: {
      imageCDN: false,
      // other plugin options go here
    },
  },
```

#### Local dev improvements

Using Image CDN also speeds up your local development startup times when running `gatsby develop`. Instead of fetching all files locally, `gatsby develop` has a local Image CDN emulator.
This means Gatsby will only fetch and process the minimal amount of images required to render any page when you visit your Gatsby site at `http://localhost:8000`.

#### Configuring placeholders for Gatsby Images

By default full size images are fetched and scaled down to be used for low quality image placeholders (for lazy loading images on the frontend).
This can make your builds slower than necessary so follow these steps to configure a new smaller placeholder image size in Drupal. This will speed up your builds when using Gatsby Image CDN.

1. Install the [Consumer image styles module](https://www.drupal.org/project/consumer_image_styles)
2. Navigate to "Extend->Web Services" and turn on "Consumer Image Styles" by checking the box and hitting save.
3. Navigate to "Configuration->Image Styles". and add an image style called "Placeholder".
4. Create a new scale effect and set its width and height to 20.
5. If you already have a placeholder style you want to use, you can set the `gatsby-source-drupal` plugin option `placeholderStyleName` as the machine name of your style. \*\* See example option below
6. For each entity that has an image field, navigate into "Configuration->Web Services->JSON:API->JSON:API Resource Overrides->Entity Type->(overwrite/edit)".
7. Click on "advanced" for each image field you have, select "Image Styles (Image Field)" in the dropdown, then select the placeholder image style and save.
8. Go to "Configuration->Web Services->Consumers" and add a default consumer if it doesn't already exist.
9. Edit your default consumer and add the "Placeholder" image style by checking the box in the bottom section and saving.
10. You may need to clear Drupal's cache under "Config->development->clear all caches".

\*\* Example placeholder style plugin option

```js
{
  resolve: `gatsby-source-drupal`,
  options: {
    placeholderStyleName: `custom_placeholder` // default is `placeholder`
  }
}
```

### Filters

You can use the `filters` option to limit the data that is retrieved from Drupal. Filters are applied per JSON API collection. You can use any [valid JSON API filter query](https://www.drupal.org/docs/8/modules/jsonapi/filtering). For large data sets this can reduce the build time of your application by allowing Gatsby to skip content you'll never use.

As an example, if your JSON API endpoint (https://live-contentacms.pantheonsite.io/api) returns the following collections list, then `articles` and `recipes` are both collections that can have a filters applied:

```json
{
  ...
  links: {
    articles: "https://live-contentacms.pantheonsite.io/api/articles",
    recipes: "https://live-contentacms.pantheonsite.io/api/recipes",
    ...
  }
}
```

To retrieve only recipes with a specific tag you could do something like the following where the key (recipe) is the collection from above, and the value is the filter you want to apply.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`,
        filters: {
          // collection : filter
          recipe: "filter[tags.name][value]=British",
        },
      },
    },
  ],
}
```

Which would result in Gatsby using the filtered collection https://live-contentacms.pantheonsite.io/api/recipes?filter[tags.name][value]=British to retrieve data.

### Basic Auth

You can use `basicAuth` option if your site is protected by basicauth.
First, you need a way to pass environment variables to the build process, so secrets and other secured data aren't committed to source control. We recommend using [`dotenv`][dotenv] which will then expose environment variables. [Read more about dotenv and using environment variables here][envvars]. Then we can _use_ these environment variables and configure our plugin.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        basicAuth: {
          username: process.env.BASIC_AUTH_USERNAME,
          password: process.env.BASIC_AUTH_PASSWORD,
        },
      },
    },
  ],
}
```

### Fastbuilds

You can use the `fastBuilds` option to enable fastbuilds. This requires the
Gatsby Drupal module (called gatsby_fastbuilds) to be enabled. This will speed
up your development and build process by only downloading content that has
changed since you last ran `gatsby build` or `gatsby develop`.

This will require authentication to your Drupal site and a Drupal user with the
Drupal permission to `sync gatsby fastbuild log entities`.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        basicAuth: {
          username: process.env.BASIC_AUTH_USERNAME,
          password: process.env.BASIC_AUTH_PASSWORD,
        },
        fastBuilds: true,
      },
    },
  ],
}
```

## Request Headers

You can add optional request headers to the request using `headers` param.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        headers: {
          Host: "https://example.com", // any valid request header here
        },
      },
    },
  ],
}
```

One case where custom headers can be useful is if your webserver returns a `406 Not Acceptable` response.
This happens when it requires narrow conformance with the JSON:API MIME type (e.g. Apache2 with security
module enabled).

```javascript
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        // ...
        headers: {
          accept: "application/vnd.api+json",
        },
      },
    },
  ],
}
```

## CDN

You can add an optional CDN or API gateway URL `proxyUrl` param. The URL can be a simple proxy of the Drupal
`baseUrl`, or another URL (even containing a path) where the Drupal JSON API resources can be retrieved.

This option is required as Drupal doesn't know about the CDN so it returns URLs pointing to the `baseUrl`. With `proxyUrl` set, the plugin will rewrite URLs returned from Drupal to keep pointing at the `proxyUrl`

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        proxyUrl: `https://xyz.cloudfront.net/`, // optional, defaults to the value of baseUrl
        apiBase: `api`, // optional, defaults to `jsonapi`
      },
    },
  ],
}
```

## GET Search Params

You can append optional GET request params to the request url using `params` option.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        params: {
          "api-key": "your-api-key-header-here", // any valid key value pair here
        },
      },
    },
  ],
}
```

### File Downloads

You can use the `skipFileDownloads` option if you do not want Gatsby to download
files from your Drupal website. This is useful if you are using another option
for processing/serving images.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        skipFileDownloads: true,
      },
    },
  ],
}
```

You can also filter out temporary files. This will help to avoid Gatsby throwing an error when a 404 is returned from a file that does not exist:

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`,
        filters: {
          // collection : filter
          "file--file": "filter[status][value]=1",
        },
      },
    },
  ],
}
```

## Concurrent File Requests

You can use the `concurrentFileRequests` option to change how many simultaneous file requests are made to the server/service. This benefits build speed, however too many concurrent file request could cause memory exhaustion depending on the server's memory size so change with caution.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`, // optional, defaults to `jsonapi`
        concurrentFileRequests: 60, // optional, defaults to `20`
      },
    },
  ],
}
```

## Concurrent API Requests

You can use the `concurrentAPIRequests` option to change how many simultaneous API requests are made to the server/service. 20 is the default and seems to be the fastest for most sites.

## API Request Timeout

You can use the `requestTimeoutMS` option to set the request timeout for API requests. API requests sometimes stall and we want to retry these instead of endlessly waiting.

The default is 30000ms. Very large sites might need to increase this.

## Disallowed Link Types

You can use the `disallowedLinkTypes` option to skip link types found in JSON:API documents. By default it skips the `self`, `describedby`, `contact_message--feedback`, and `contact_message--pesonal` links, which do not provide data that can be sourced. You may override the setting to add additional link types to be skipped.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        // skip the action--action resource type.
        disallowedLinkTypes: [
          `self`,
          `describedby`,
          `contact_message--feedback`,
          `contact_message--personal`,
        ],
      },
    },
  ],
}
```

_NOTES_:

When using [includes](https://www.drupal.org/docs/8/modules/jsonapi/includes) in your JSON:API calls the included data will automatically become available to query, even if the link types are skipped using `disallowedLinkTypes`.

This enables you to fetch only the data you need at build time, instead of all data of a certain entity type or bundle.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        // Skip the node--page resource type and paragraph components.
        disallowedLinkTypes: [
          `self`,
          `describedby`,
          `node--page`,
          `paragraph--text`,
          `paragraph--image`,
        ],
        filters: {
          // Use includes so only the news content paragraph components are fetched.
          "node--news": "include=field_content",
        },
      },
    },
  ],
}
```

## Entity Reference revisions and relationships

By default `gatsby-source-drupal` resolves Entity Reference relationships using just ID. If you are
using the contrib module [Entity reference revisions](https://drupal.org/project/entity_reference_revisions) and [Paragraphs](https://drupal.org/project/paragraphs),
you may have advanced use-cases such as fetching drafts where you want to resolve these relationships using both ID and
revision ID. You can nominate entity-type IDs where you wish to resolve relationships using the revision ID by adding
them to the `entityReferenceRevisions` configuration option. Please note that `gatsby-source-drupal` only ever fetches
the default (published) revision, so this functionality is only needed in advanced cases where you have custom code
Drupal side that is applying additional logic.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        apiBase: `api`,
        entityReferenceRevisions: ["paragraph"], // optional, defaults to `[]`
      },
    },
  ],
}
```

## Translations

If you have translations or multilingual enabled on your Drupal site, you can opt-in to sourcing translations of entities. To do this, enable in your plugin's configuration the languages and entity types you'd like to source. E.g.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        languageConfig: {
          defaultLanguage: `en`,
          enabledLanguages: [
            `en`,
            `fil`,
            // add an object here if you've renamed a langcode in Drupal
            {
              langCode: `en-gb`,
              as: `uk`,
            },
          ],
          filterByLanguages: false
          // add a boolean `true` here if you'd like to filter the Drupal API response by the current language
          translatableEntities: [`node--article`],
          nonTranslatableEntities: [`file--file`],
        },
      },
    },
  ],
}
```

Some entities are not translatable like Drupal files and will return null result when language code from parent entity doesn't match up. These items can be specified as nonTranslatableEntities and receive the defaultLanguage as fallback.

## Type prefix

By default, types are created with names that match the types in Drupal. However you can use the `typePrefix` option to add a prefix to all types. This is useful if you have multiple Drupal sources and want to differentiate between them, or if you have Drupal types that conflict with other types in your site.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        typePrefix: `Drupal`,
      },
    },
  ],
}
```

You would then query for `allDrupalArticle` instead of `allArticle`.

```graphql
{
  allDrupalArticle {
    nodes {
      title
    }
  }
}
```

## Gatsby Preview (experimental)

You will need to have the Drupal module installed, more information on that here: https://www.drupal.org/project/gatsby

In your Drupal module configuration, set the update URL to your Gatsby Preview instance URL.

_NOTES_:

- This is experimental feature in active development. APIs used for this feature are not yet stable - it can break while we iterate on API design (particularly when versions of `gatsby-source-drupal` and `Gatsby Live Preview` Drupal module are incompatible).

### Preview Secret

While you don't need to pass any additional options for preview to work, you can pass a `secret` for added security between your Drupal instance and Gatsby preview. Ensure this secret matches the one set in your Drupal Gatsby Preview settings.

```javascript
// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-drupal`,
      options: {
        baseUrl: `https://live-contentacms.pantheonsite.io/`,
        secret: process.env.PREVIEW_SECRET, // optional, must match Drupal instance preview secret
      },
    },
  ],
}
```

## How to query

You can query nodes created from Drupal like the following:

```graphql
{
  allArticle {
    edges {
      node {
        title
        internalId
        created(formatString: "DD-MMM-YYYY")
      }
    }
  }
}
```

[dotenv]: https://github.com/motdotla/dotenv
[envvars]: https://www.gatsbyjs.com/docs/environment-variables

repository: gatsbyjs/gatsby

repo_name: gatsbyjs/gatsby


text:
---
heading: Egnyte
seo: API Provider Setup | API provider setup | Egnyte | Cloud Elements API Docs
title: API Provider Setup
description: Setup tasks required to authenticate an element instance
layout: sidebarelementdoc
breadcrumbs: /docs/elements.html
elementId: 4016
elementKey: key
parent: Back to Element Guides
order: 5
---

# API Provider Setup

To authenticate a {{page.heading}} element instance you must register an app with {{page.heading}} and know the **Key**, **Shared Secret**, and **Registered OAuth Redirect URI** of the app. You use these when you authenticate an element instance as the API Key, API Secret, and OAuth Callback URL.

To set up the API provider:

1. Log in to your developer account at [Egnyte](https://developers.egnyte.com).
3. Click **Create New Application**.
4. Complete the required information.
5. In **Egnyte domain you will use for testing** enter the domain that you have access to for testing. When you authenticate an element instance, you also provide an Egnyte domain. When testing, these values should match.
5. In **Registered OAuth Redirect URI** enter the URL that you will use as the OAuth Callback URL when you authenticate an element instance.
![Egnyte Setup 1](img/egnyte-domain-callback.png)
3. Record your **Registered OAuth Redirect URI** as the OAuth Callback URL.
2. In the SELECT WHICH WEB APIS THIS APPLICATION WILL USE section, note the rate limits.
![Rate Limits](img/rate-limits.png)
2. Click **Register Application**.
3. Record the **Key** and **Shared Secret** as your API Key and API Secret.

Next [authenticate an element instance with {{page.heading}}](authenticate.html).

license: MIT

repository: cloud-elements/devportal

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

license_type: permissive

repo_name: cloud-elements/devportal


text:
---
layout: post
title: "Drive 28BYJ-48 Stepper Motor with ULN2003 driver and the BeagleBone Black"
author: wilmer
categories: [BeagleBone]
tags: [StepperMotors]
image: assets/images/Post54/CoverPost.png
description: "Drive 28BYJ-48 Stepper Motor 1/4-turn in both directions in full step mode with 1 coil at the same time with the BeagleBone Black"
featured: false
hidden: false
rating: 4.5
date:   2022-11-02 08:00:00 -0500
---

In this post, I show how to drive the stepper motor 28BYJ-48 with the driver ULN2003 which can drive a wide range of loads including solenoids, relay DC motors, LED display filament lamps and thermal printheads. In practice, this driver can be found in a popular green-coloured board that has been designed to make it easy to play and interact with the 28BYJ-48 as this and this another tutorial show.

The 28BYJ-48 is a stepper motor that moves in steps or "degree intervals". It has an internal gear set that let it turn 2048 steps in each revolution in a mode that is called Full Step or 4096 steps in each revolution in a mode called Half Step.

These are theoretical values and depend on the gearbox used by the 28BYJ-48`s manufacturer. Sometimes, instead of 2048 steps, the real value is 2037 steps per revolution.

It is important to remember that the logic voltage for the BeagleBone is 3.3V. If the user provides a greater voltage, the BeagleBone could be damaged.

## Circuit and components

The circuit can be seen in Figure 1. It consists of a UNL2003 driver module, 28BYJ48 stepper motor, and the BeagleBone.

    Figure 1: Circuit to drive a 28BYJ48 stepper motor with the ULN2003 driver.

The components are:
- 1 28BYJ-48 stepper motor 5V
- 1 ULN2003 module driver
- 1 Protoboard mini
- Jumpers male-male to make the connections

The pins used to control the stepper motor are:
- GPIO **P8_12**, **P8_14**, **P8_16** and **P8_18** to control the motor rotation speed and direction

## Coding

First, four `GPIO` objects are declared and named `IN1, IN2, IN3 and IN4`.
```cpp
// Declaring the pins for motor
GPIO IN1 (P8_12);
GPIO IN2 (P8_14);
GPIO IN3 (P8_16);
GPIO IN4 (P8_18);
```

These pins will be used to declare and initialize a `StepperMotor` object with the name of `myStepper` in this manner:
```cpp
StepperMotor myStepper (IN1, IN2, IN3, IN4);
```

The `StepperMotor` object constructor **definition** is in a class named `STEPPERMOTOR` who is part of the whole library to use and program the BeagleBone Black with C++. The source files can be found here.

The `StepperMotor` object constructor is shown in the next listing:
```cpp
// Overload constructor
StepperMotor(
              GPIO, GPIO, GPIO, GPIO,
              STEPPER_MODE controlMode = fullStep1Coil,
              unsigned int stepsPerRevolution = 2048,
              unsigned int maxSpeed = 500
            );
```

It requires seven input parameters, from which, the last three have **default values** avoiding the user to specify these if it does not want to.
- The first four parameters are the `GPIO` pins to control the stepper motors.
- The last three define the control mode and other movement parameters for the stepper motor:
  - The `controlMode` parameter defines the stepper motor's control mode to one of the next modes:
    - `fullStep1Coil`: Full step with one coil activation. It is the default value
    - `fullStep2Coils`: Full step with two coil activation.
    - `halfStep`: Half step with two coil activation by nature.
    - `driver`:  Another way, by example, using another custom driver.
  - The `stepsPerRevolution` defines the number of steps per revolution of the motor. It takes `2048` steps as the default value.
  - The `maxSpeed` defines the maximum rotation speed of the motor in steps/second. It takes `500` as the default value.

The `StepperMotor` object constructor **declaration** is shown in the next listing. It requires at least, four `GPIO` pins to control the stepper motor and initialize them as `OUTPUT` pins with the private method `InitMotorPins()`. Then, the correct number for the activation sequence steps is set up in the variable `stepsPerMode` according to the control mode that the user wants:
  - 4 steps for **Full Step** mode with 1 or 2 coil activation.
  - 8 steps for **Half Step** mode.

```cpp
// Overload Constructor
StepperMotor::StepperMotor (GPIO newMotorPin1,
                            GPIO newMotorPin2,
                            GPIO newMotorPin3,
                            GPIO newMotorPin4,
                            STEPPER_MODE newControlMode,
                            unsigned int newStepsPerRevolution,
                            unsigned int newMaxSpeed) :
                            motorPin1 (newMotorPin1),
                            motorPin2 (newMotorPin2),
                            motorPin3 (newMotorPin3),
                            motorPin4 (newMotorPin4),
                            controlMode (newControlMode),
                            stepsPerRevolution (newStepsPerRevolution),
                            maxSpeed (newMaxSpeed)
{
  InitMotorPins();
  stepsCounter = 0;
  currentStep = 0;

  std::string modeString;
  switch (controlMode)
  {
    case fullStep1Coil:
      modeString = "Full step with 1 Coil";
      stepsPerMode = fullStep1CoilVector.size();
      break;
    case halfStep:
      modeString = "Half step";
      stepsPerMode = halfStepVector.size();
      break;
    case fullStep2Coils:
      modeString = "Full step with 2 coils";
      stepsPerMode = fullStep2CoilsVector.size();
      break;
    case driver:
      modeString = "Driver mode was chosen";
      break;
  }

  std::string message;
  message = "\nStepperMotor object with the next parameters / pins was created:\n" +
            std::string("\tMotorPin1: ") + this->motorPin1.GetPinHeaderId() +
            "\n" +
            std::string("\tMotorPin2: ") + this->motorPin2.GetPinHeaderId() +
            "\n" +
            std::string("\tMotorPin3: ") + this->motorPin3.GetPinHeaderId() +
            "\n" +
            std::string("\tMotorPin4: ") + this->motorPin4.GetPinHeaderId() +
            "\n" +
            std::string("\tControl Mode: ") + modeString + "\n" +
            std::string("\tMax speed: ") + std::to_string(maxSpeed) + "\n\n";
  std::cout << RainbowText(message, "Light Gray");
}

/*
  Private method to initialize the Pins
*/
void StepperMotor::InitMotorPins()
{
  // Set the right modes for the pins
  motorPin1.SetMode(OUTPUT);
  motorPin2.SetMode(OUTPUT);
  motorPin3.SetMode(OUTPUT);
  motorPin4.SetMode(OUTPUT);
}
```
To turn the stepper motor declared as a `StepperMotor` object with the name of `myStepper` in this program, the method `TurnBySteps(CW, 512)` can be used, which specifies the rotation direction, CW in this case, and the number of steps to rotate the stepper motor, 512 in this case, which corresponds to 1/4-turn due that the 28BYJ-48 has 2048 steps per revolution.
```cpp
myStepper.TurnBySteps(CW, 512);
```

The code of this method is shown here to illustrate how the movement of each step is done. The logic behind this is to activate each coil in the right order and sequence. The order determines if the stepper motor will rotate in the CCW direction starting the activation of the first terminal of the first coil or, in the other case, it will rotate in the CW direction if the activation starts in the second terminal of the second coil. The right sequence has to ensure that both terminals of both coils are activated sequentially to let the motor rotate.

```cpp
/*
  Public method to turn the motor by steps
  @param DIRECTION: The desired direction for the motor rotation
  @param unsigned int: The steps required
  @param unsigned int: The rotation's speed in steps / sec (0,maxSpeed]
  @param bool: Flag to print / no print the messages on the console. Default value: <false>
*/
void StepperMotor::TurnBySteps(
                                DIRECTION direction,
                                unsigned int stepsRequired,
                                unsigned int speed,
                                bool printMessages
                              )
{
  // Check the speed limit value
  if (speed > maxSpeed)
    speed = maxSpeed;

  int coilStep {0};

  if (printMessages == true)
  {
    std::string message;
    if (direction == CW)
      message = "Turning stepper motor CW ";
    else
      message = "Turning stepper motor CCW ";

    message +=
    std::to_string(stepsRequired) + " steps at " +
    std::to_string(speed) + " steps/second\n";

    std::cout << RainbowText(message, "Light Gray");
  }

  // Turn 1 step in CW direction
  if (direction == CW)
  {
    for (int i = 0; i < stepsRequired; i++)
    {
      coilStep = stepsPerMode - 1 - (i % stepsPerMode);
      this->Turn1Step(coilStep, speed);

      // Update counters
      stepsCounter++;
      currentStep++;
    }
  }
  // Turn 1 step in CCW direction
  else if (direction == CCW)
  {
    for (int i = 0; i < stepsRequired; i++)
    {
      coilStep = i % stepsPerMode;
      this->Turn1Step(coilStep, speed);

      // Update counters
      stepsCounter++;
      currentStep--;
    }
  }
}
```

To know how many steps the stepper motor has executed, the next method can be used:
```cpp
myStepper.GetStepsCounter();
```

In the same way, to know the actual position of the stepper motor axis in terms of number of steps, the next method can be used:
```cpp
myStepper.GetCurrentStep()();
```

The complete code for this application is shown in the next listing together with its corresponding execution output.

### 28BYJ-48-ULN2003_1.1.cpp
```cpp
/******************************************************************************
28BYJ48-ULN2003_1.1.cpp
@wgaonar
03/04/2022
https://github.com/wgaonar/BeagleCPP

- Move the stepperMotor by steps in fullStep with 1 Coil mode

Class: STEPPERMOTOR
******************************************************************************/

#include <iostream>
#include "../../../Sources/STEPPERMOTOR.h"

using namespace std;

// Declaring the pins for motor
GPIO IN1 (P8_12);
GPIO IN2 (P8_14);
GPIO IN3 (P8_16);
GPIO IN4 (P8_18);

/*
  Declare the 28BYJ-48 stepper motor object with default parameters:
  full step with the activation of 1 coil,
  default 2048 steps per revolution
  and a default maximum speed of 500 steps/second
*/
StepperMotor myStepper (IN1, IN2, IN3, IN4);

int main()
{
  string message = "Main program starting here...";
  cout << RainbowText(message,"Blue", "White", "Bold") << endl;

  /*
    Turn the stepper motor 1/4-turn in CW direction at 500 steps/second
  */
  myStepper.TurnBySteps(CW, 512);
  cout << "Steps executed by the motor: " << myStepper.GetStepsCounter() << endl;
  cout << "Actual position of the motor axis: " << myStepper.GetCurrentStep() << endl;

  /*
    Turn the stepper motor 1/4-turn in CCW direction at 500 steps/second
  */
  myStepper.TurnBySteps(CCW, 512);
  cout << "Steps executed by the motor: " << myStepper.GetStepsCounter() << endl;
  cout << "Actual position of the motor axis: " << myStepper.GetCurrentStep() << endl;

  message = "Main program finishes here...";
  cout << RainbowText(message,"Blue", "White","Bold") << endl;

  return 0;
}
```

Se you in the next post.

branch_name: refs/heads/main


text:
# Personal Portfolio

Welcome to my personal portfolio source code!

If you're looking for my actual portfolio just go here -> https://danielwalker.dev

![Project Screenshot](/src/images/portfolio.gif)

This project was created with:
* React

This project is hosted:
* Frontend - Netlify
* Backend - Heroku


text:
HungryUp.desktop-ie
=========

Use wine to setup many versions of Internet Explorer on mac

Requirements
------------

Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.

Example Playbook
----------------

    - hosts: localhost
      roles:
         - { role: HungryUp.desktop-ie, x: 42 }

License
-------

BSD

repository: HungryUp/ansible-role-desktop-ie

repo_name: HungryUp/ansible-role-desktop-ie


text:
# API Working Group

## Date 4/27/20

### Attendees
- @nornagon
- @jkleinsc
- @codebytere
- @MarshallOfSound
- @itsananderson

### Visitors
- @deepak1556

### Followup
* @zcbenz to [docs: views API: child views and layout engine] (https://github.com/electron/governance/pull/271) with "plan B"
    * not updated yet; followup again next meeting

### Agenda

1. [docs: add print API consistency proposal](https://github.com/electron/governance/pull/232)
    * **Verdict:** Approved
    * It's been approved, promisification backwards compat will be removed in v12
2. [docs: clipboard.getNativeFormat() and clipboard.writeBuffers()](https://github.com/electron/governance/pull/229)
    * Related - Raw Clipboard Access API (Fugu)
        * [Issue 897289: Raw Clipboard Access API](https://bugs.chromium.org/p/chromium/issues/detail?id=897289)
        * [Design Doc: Raw Clipboard Access](https://docs.google.com/document/d/1XDOtTv8DtwTi4GaszwRFIJCOuzAEA4g9Tk0HrasQAdE/edit)
    * if we rely on the fugu api, we'd be restricted to fugu's restrictions (e.g. only accessible in renderer process, only while view is active)
    * native node module is an option, but chromium already has high quality apis for this
    * if/when we do our own clipboard apis, we should aim to match fugu apis as close as possible
    * is there urgency on this? the current spec is close to landable, should we land it without the fugu changes and treat that as a separate thing?
        * No, not urgent, it's ok to refactor.
    * [ACTION] @jkleinsc to play with the fugu api and report back

3. [API review requested PRs](https://github.com/electron/electron/pulls?q=is%3Aopen+is%3Apr+label%3Aapi-review-requested)
    * [ [WIP] feat: route frame based permission checks through our permission check handler](https://github.com/electron/electron/pull/19903)
        * **Verdict:** No objections, let's go ahead.
        * Kind of a bugfix
    * [feat: add APIs for accessing NSUserDefaults in the given domain](https://github.com/electron/electron/pull/22193)
        * inactive
    * [feat: add desktopCapturer.getWebContentsStream() to get media stream id from web contents](https://github.com/electron/electron/pull/22701)
        * discussion ongoing
    * [feat: add support for optimizing simple objects and functions over the context bridge](https://github.com/electron/electron/pull/22774)
        * pending perf tests
    * [feat: add new render-process-gone event](https://github.com/electron/electron/pull/23096)
        * Should update doc to reflect it could be thrown from multiple WebContents
        * can we get the process id of the crashed process to detect dupes? => chromium doesn't give us that info, though maybe we could collect it somehow? for future work.
        * **Verdict:** Go ahead.

4. `crashReporter` API changes: [#23265](https://github.com/electron/electron/pull/23265)
    * some docs-parser issues
    * **Verdict:** Go ahead.

repository: electron/governance

gha_language: Shell

repo_name: electron/governance


text:
# Using Sharrow

This page will walk through an exercise of running a model with `sharrow`.

## How it Works

Sharrow accelerates ActivitySim in part by using numba to create optimized and
pre-compiled versions of utility specification files, and caching those bits
of code to disk.

```{important}
Running the compiler needs to be done in single-process mode, otherwise the
various process all do the compiling and compete to write to the same cache
location on disk, which is likely to fail.  You can safely run in
multiprocessing mode after all the compilation for all model components is
complete.
```

## Model Design Requirements

Activating the `sharrow` optimizations also requires using the new
[`SkimDataset`](skim-datasets) interface for skims instead of the legacy
[`SkimDict`](activitysim.core.skim_dictionary.SkimDict), and internally
recoding zones into a zero-based contiguous indexing scheme.

### Zero-based Recoding of Zones

Using sharrow requires recoding zone id's to be zero-based contiguous index
values, at least for internal usage.  This recoding needs to be written into
the input table list explicitly.  For example, the following snippet of a
`settings.yaml` settings file shows the process of recoding zone ids in
the input files.

```yaml
input_table_list:
  - tablename: land_use
    filename: land_use.csv
    index_col: zone_id
    recode_columns:
      zone_id: zero-based
  - tablename: households
    filename: households.csv
    index_col: household_id
    recode_columns:
      home_zone_id: land_use.zone_id
```

For the `land_use` table, the `zone_id` field is marked for recoding explicitly
as `zero-based`, which will turn whatever nominal id's appear in that column into
zero-based index values, as well as store a mapping of the original values that
is used to recode and decode zone id's when used elsewhere.

The first "elsewhere" recoding is in the households input table, where we will
map the `home_zone_id` to the new zone id's by pointing the recoding instruction
at the `land_use.zone_id` field.  If zone id's appear in other input files, they
need to be recoded in those fields as well, using the same process.

The other places where we need to handle zone id's is in output files.  The
following snippet of a `settings.yaml` settings file shows how those id's are
decoded in various output files.  Generally, for columns that are fully populated
with zone id's (e.g. tour and trip ends) we can apply the `decode_columns` settings
to reverse the mapping and restore the nominal zone id's globally for the entire
column of data.  For columns where there is some missing data flagged by negative
values, the "nonnegative" filter is prepended to the instruction.

```yaml
output_tables:
  action: include
  tables:
    - tablename: land_use
      decode_columns:
        zone_id: land_use.zone_id
    - tablename: households
      decode_columns:
        home_zone_id: land_use.zone_id
    - tablename: persons
      decode_columns:
        home_zone_id: land_use.zone_id
        school_zone_id: nonnegative | land_use.zone_id
        workplace_zone_id: nonnegative | land_use.zone_id
    - tablename: tours
      decode_columns:
        origin: land_use.zone_id
        destination: land_use.zone_id
    - tablename: trips
      decode_columns:
        origin: land_use.zone_id
        destination: land_use.zone_id
```

## Measuring Performance

Testing with sharrow requires two steps: test mode and production mode.

In test mode, the code is run to compile all the spec files and
ascertain whether the functions are working correctly.  Test mode is expected
to be slow, potentially much slower than older versions of ActivitySim,
especially for models with small populations and zone systems, as the compile
time is a function of the complexity of the utility functions and *not* a
function of the number of households or zones. Once the compile and test is
complete, production mode can then just run the pre-compiled functions with
sharrow, which is much faster.

It is possible to run test mode and production mode independently using the
existing `activitysim run` command line tool, pointing that tool to the test
and production configurations directories as appropriate.

To generate a meaningful measure of performance enhancement, it is necessary
to compare the runtimes in production mode against equivalent runtimes with
sharrow disabled.  This is facilitated by the `activitysim workflow` command
line tool, which permits the use of pre-made batches of activitysim runs, as
well as automatic report generation from the results.  For more details on the
use of this tool, see [workflows](workflows).

## Sharrow Compatability and Limitations

In general, utility specification files contain a sequence of :ref:`expressions` that
are evaluated for each row in a main DataFrame.  In legacy ActivitySim,
there are two fundamental evaluation modes:

- `pandas.DataFrame.eval`, which is the default, and
- plain Python `eval`, which is used when the expression is prefixed with an `@` symbol.

Under the `pandas.DataFrame.eval` mode, expressions are evaluated within the context
of the current main dataframe only. References can be made to other columns
in that dataframe directly, i.e. if the dataframe contains a column named "income",
the expression can reference that value as "income".  However, the expression can
*only* reference other values that are stored in the current row of the dataframe.
The available syntax for these expressions is a subset of regular python, see the
[supported syntax](https://pandas.pydata.org/docs/user_guide/enhancingperf.html#supported-syntax)
section of the pandas documentation for details.

Under the plain `eval` mode, expressions are evaluated within a broader context
that potentially includes other variables (which other variables is component
dependent) and constants defined in the model settings file.  References to
columns in the main dataframe must be made indirectly via attribution, i.e. if
the dataframe contains a column named "income", the expression needs to reference
that value as "df.income".  Typically, references to skims, time tables, and anything
else that isn't the simple original dataframe use this mode.  While it is sometimes
not as fast as `pandas.DataFrame.eval`, this mode is far more flexible, as you
can write basically any valid Python expression, including calling other functions,
accessing or manipulating table metadata, indexes, or adjacent rows, etc.

Within sharrow, the distinction between these two modes is ignored, as sharrow
uses a completely different evaluation system routed through numba. The `@` prefix
does not need to be stripped or added anywhere, it is simply ignored. The expression
can reference other columns of the main dataframe directly or indirectly, so that
either "income" or "df.income" is a valid reference to that column in the main
dataframe.  You can also reference other variables, including skims as usual for each component
and constants defined in in the model settings file.  Within scheduling models,
references can also be made to the timetable as "tt", accessing that interfaces
methods to compute presence and length of adjacent and available time windows.
However, you *cannot* write arbitrary Python code.  External functions are not allowed unless they have
already been compiled with numba's `njit` wrapper.  Typically, unless specifically
constructed to be allowed for a model component, cross-referencing, merging or
reindexing against tables other than the main dataframe is not allowed. Such
customizations will generally require a custom extension.

Sharrow only runs for utility specification files.  ActivitySim also features the
ability to apply pre-processors and post-processors to annotate tables, which use
specification files that look very similar to utility specifications.  These
functions do *not* run through sharrow, and are a great place to relocate expressions
that need to run arbitrary code or join data from other tables.

### Temporary Variables

Temporary variables can be created from `@` mode expressions by adding a variable
name beginning with an underscore before the `@`, e.g<EMAIL_ADDRESS>
In legacy mode, temporary variables are useful but they can consume substantial
memory, as the variable is computed and stored for every row in the entire dataframe
before it can be used in other expressions.  In sharrow, temporary variables are
allocated, used, and freed for each row separately, so no extra memory is required.

### Switchable Expressions

As a general rule, it is best to write each utility expression in a manner that
is cross-compatible between sharrow and legacy evaluation modes, even if that
means transitioning a few expressions or parts of expressions into preprocessors.

However, sometimes this is not possible or makes writing the expressions excessively
complex.  In this case, it is possible to write a toggling expression, where the
individual expression evaluated is different for sharrow and legacy modes.  The
special comment string `# sharrow:` splits the expression, with everything before this
comment evaluated under the legacy process, and everything after evaluated only
when sharrow is enabled.

An example of a switching expression is found in the trip destination utilities found
in several examples:

    `@np.log1p(size_terms.get(df.alt_dest, df.purpose)) # sharrow: np.log1p(size_terms['sizearray'])`

Here, `size_terms` is a DataFrameMatrix class instance, a special class written into
ActivitySim to facilitate reading from a DataFrame as it it were a 2-d array.  As it
is a special purpose class written in Python, the numba compiler cannot handle it directly.
Fortunately, sharrow provides an alternative: passing the size terms as a xarray `DataArray`.
This has a slightly different interface, so the sharrow and legacy evaluation modes require
different expressions. The switching expression is used to handle the DataFrameMatrix
on the left (before "# sharrow:") and the DataArray on the right.

### Performance Considerations

Sharrow is usually expected to bring significant performance gains to ActivitySim.
However, the numba engine beneath sharrow has a few known performance limitations,
most notably when using [strings](https://numba.readthedocs.io/en/stable/reference/pysupported.html#str).
To enhance performance, it is best to limit the number of string operations,
including simple equality checks (e.g. `df.tour_purpose == 'work'`).  Ideally,
such string operations won't appear in utility specifications at all, or if they
do appear, they are executed only once and stored in a temporary value for re-use
as needed.

For models with utility expressions that include a lot of string comparisons,
(e.g. because they are built for the legacy `pandas.eval` interpreter and have not
been updated) sharrow can be disabled by setting `sharrow_skip: true` in the
component's configuration yaml file.

### Limited Tracing and Estimation Mode Capabilities

When running sharrow-optimized code, large parts of certain calculations are routed
through numba to enhance speed and reduce memory footprint.  Many intermediate arrays
are not created, or are allocated and released by numba in a manner not visible to the
general Python interpreter.  As a result, in many places the "trace" capabilities of
ActivitySim are limited.  These capabilities output intermediate calculations in
extreme detail and are typically only used in debugging and model development, not
in production model runs that need to be optimized for speed.  Tracing features can
be re-enabled by switching sharrow off or by using "test" mode, which runs both sharrow
and legacy evaluations together to confirm they are substantially identical.  In this
fashion, detailed tracing (albeit slow) remains available for users on all models when
needed.

Similar constraints apply to estimation mode, as complete estimation mode output
capabilities are not yet integrated with the sharrow engine.  Estimation mode remains
fully available when running with sharrow disabled.

(digital-encoding)=
## Digital Encoding

Sharrow is compatible with and able to efficiently use
[digital encoding](https://activitysim.github.io/sharrow/walkthrough/encoding.html).
These encodings are applied to data either prospectively (i.e. before ActivitySim
ever sees the skim data), or dynamically within a run using the
`taz_skims.digital-encoding` or `taz_skims.zarr-digital-encoding` settings in
the `network_los.yaml` settings file.  The only difference between these two
settings is that the former applies this digital encoding internally every
time you run the model, while the latter applies it prior to caching encoded
skims to disk in Zarr format (and then reuses those values without re-encoding
on subsequent runs with the same data).  Dictionary encoding (especially joint
dictionary encodings) can take a long time to prepare, so caching the values can
be useful. As read/write speeds for zarr files are fast, you usually won't
notice a meaningful performance degradation when caching, so the default is
generally to use `zarr-digital-encoding`.

Very often, data can be expressed adequately with far less memory than is
needed to store a standard 32-bit floating point representation.  There are
two simple ways to reduce the memory footprint for data: fixed point
encoding, or dictionary encoding.

### Fixed Point Encoding

In fixed point encoding, which is also sometimes called scaled integers,
data is multiplied by some factor, then rounded to the nearest integer.
The integer is stored in memory instead of a floating point value, but the
original value can be (approximately) restored by reversing the process.
An offset factor can also be applied, so that the domain of values does not
need to start at zero.

For example, instead of storing matrix table values as 32-bit floating point values,
they could be multiplied by a scale factor (e.g., 100)
and then converted to 16-bit integers. This uses half the
RAM and can still express any value (to two decimal point
precision) up to positive or negative 327.68.  If the lowest
values in that range are never needed, it can also be shifted,
moving both the bottom and top limits by a fixed amount. Then,
for a particular scale $\mu$ and shift $\xi$ (stored in metadata),
from any array element $i$ the implied (original) value $x$
can quickly be recovered by evaluating $(i / \mu) - \xi$.

Fixed point digital encoding can be applied to matrix tables in the skims
using options in the `network_los.yaml` settings file.  Making transformations
currently also requires shifting the data from OMX to ZARR file formats;
future versions of ActivitySim may accept digitally encoded data directly
from external sources.

To apply the default 16-bit encoding to individual named skim variables in the
TAZ skims, just give their names under the `zarr-digital-encoding` setting
like this:

```yaml
taz_skims:
    omx: skims.omx
    zarr: skims.zarr
    zarr-digital-encoding:
        - name: SOV_TIME
        - name: HOV2_TIME
```

If some variables can use less RAM and still be represented adequately with only
8-bit integers, you can specify the bitwidth as well:

```yaml
taz_skims:
    omx: skims.omx
    zarr: skims.zarr
    zarr-digital-encoding:
        - name: SOV_TIME
        - name: HOV2_TIME
        - name: SOV_TOLL
          bitwidth: 8
        - name: HOV2_TOLL
          bitwidth: 8
```

If groups of similarly named variables should have the same encoding applied,
they can be identifed by regular expressions ("regex") instead of explicitly
giving each name.  For example:

```yaml
taz_skims:
    omx: skims.omx
    zarr: skims.zarr
    zarr-digital-encoding:
        - regex: .*_TIME
        - regex: .*_TOLL
          bitwidth: 8
```

### Dictionary Encoding

For dictionary encoding, a limited number of unique values are stored in a
lookup array, and then each encoded value is stored as the position of the
value (or its closest approximation) in the lookup array.  If there are fewer
than 256 unique values, this can allow the storage of those values to any level
of precision (even float64 if needed) while using only a single byte per array
element, plus a small fixed amount of overhead for the dictionary itself.  The
overhead memory doesn't scale with the dimensions of the array, so this works
particularly well for models with thousands of zones.

Dictionary encoding can be applied to a single variable in a similar fashion as
fixed point encoding, giving the dictionary bit width in the `by_dict` setting,
or as an additional setting value.

```yaml
taz_skims:
    omx: skims.omx
    zarr: skims.zarr
    zarr-digital-encoding:
        - name: TRANSIT_FARE
          by_dict: 8
        - name: TRANSIT_XFERS
          by_dict: true
          bitwidth: 8
```

The most dramatic memory savings can be found when the categorical correlation
(also known as [Cramér's V](https://en.wikipedia.org/wiki/Cram%C3%A9r%27s_V))
between multiple variables is high.  In this case, we can encode more than one
matrix table using the same dictionary lookup indexes.  There may be some
duplication in the lookup table, (e.g. if FARE and XFER are joint encoded,
and if a FARE of 2.25 can be matched with either 0 or 1 XFER, the 2.25 would
appear twice in the lookup array for FARE, once for each value of XFER.)

Since it is the lookup *indexes* that scale with the number of zones and consume most
of the memory for large zone systems, putting multiple variables together into one
set of indexes can save a ton of memory, so long as the overhead of the lookup array
does not combinatorially explode (hence the need for categorical correlation).

Practical testing for large zone systems suggest this method of encoding can
reduce the footprint of some low variance data tables (especially transit data)
by 95% or more.

Applying joint dictionary encoding requires more than one variable name, so only
the `regex` form works here. Use wildcards to match on name patterns, or select a
few specific names by joining them with the pipe operator (|).

```yaml
taz_skims:
    omx: skims.omx
    zarr: skims.zarr
    zarr-digital-encoding:
        - regex: .*_FARE|.*_WAIT|.*_XFERS
          joint_dict: true
        - regex: FERRYTIME|FERRYFARE|FERRYWAIT
          joint_dict: true
```

For more details on all the settings available for digital encoding, see
[DigitalEncoding](activitysim.core.configuration.network.DigitalEncoding).

repository: ActivitySim/activitysim

gha_language: Jupyter Notebook

repo_name: ActivitySim/activitysim


text:
# Events Tasks Solutions

For solving the tasks use kibana and zipkin.

1. Query: Find an event of the service imageflip (together)
   * in the kibana UI
   * navigate to the "Discover" menu
   * select the `events-*` index pattern
   * add a filter on the field `service.keyword`
   * use the operator `is`
   * select/type the value imageflip

2. Query: Find all imageflip transactions that have a duration higher than 1000ms (last 10h). Which one took the longest?
   * keep the filter from before
   * lookup a document and search for the field representing duration: `event.duration_ms`
      * it should be `number` typed, can be recognized by the `#` in front of it
      * **Caution: if the field is not available of text typed, this task is not doable**
   * add a filter for that field
      * operator: `is between`
      * values: `1000` and a very large number like `1000000`

3. Visualize: percentiles of durations of imagegrayscale events.
   * navigate to the "Visualize" menu
   * create new visualization
   * select line chart on the event-* index pattern
   * under Data > Metrics > Y-Axis select `percentiles` aggregation
      * as field set `event.duration_ms`
      * pick useful percentiles buckets, eg: 50, 75, 95, 99
   * under Data > Buckets add X-Axis
      * as aggregation select `Date Histogram`
      * as field select `@timestamp`
   * click `Update` to apply
   * select a reasonable timespan to look at (top right)
   * Example:
![image](imagegrayscale_duration_percentiles.png)

repository: feature-creeps/observability-workshop

gha_language: Java

repo_name: feature-creeps/observability-workshop


text:
# Description

Use the `create_file` script to create a new code file using one of the
templates provided in the `templates` folder.

The template to use will be automatically derived from the extension of the
file you are trying to create.

# Synopsis

```bash
./create_file script.pl # creates a new Perl script file using templates/pl.tpl

```

# License

This software is licensed under the MIT License

repository: pifanatic/file-templates

repo_name: pifanatic/file-templates


text:
# What is rz bot
RZ bot or with original name thats unwrittable in repo name "Ż bot", is a bot for managing osu servers on gulag. Right now there's not too much in the code because im rewriting it for 727th time. I want it to be usable on every osu server made on gulag.

You can see our trello board here: https://trello.com/b/sZORcdeI/rz-bot
Our discord, if you need help: https://discord.gg/56d8zy8fFp
# Requirements
Bot has been tested on both windows and Ubuntu 18.04.
So here are things that you need:

- Ubuntu 18.04/20.04 or Windows 7+
- SSL Cert installed on web, api and avatar domains
- tzdata python package (If running on windows)
- sendgrid (If you're going to use this module, you'll also need sendgrid api key, you can get it [here](https://sendgrid.com). If you dont plan using our mailing module, disable it in config.
- Also make sure that your terminal supports colors or it will look extremelly bad. Example that supports it: Windows Terminal from Microsoft Store

# Working with code
I strongly recommend using BeterComments extension for VS Code, idk if it exists for other editors too.
Also as MIT license says, you can resell it, edit it anything you want. Just leave information that we created it, or at least the base. Be a nice person. Thanks :)

# Installation
I'm too lazy to write down every command here so just in short
```
Clone repo
download python3.9
execute python3.9 -m pip install -r ext/requirements.txt
import table in ext/discord.sql to your gulag db
implement patch located at ext/verificationpatch.md, how to do it? It's explained in that file.
copy ext/config.sample.py to base folder and rename it to config.py
run bot with python3.9 main.py
```

### Discord part
```
You need to create new server, name it whatever you want.
Invite bot to it *CONFIGURE IT BEFORE* and add emojis located in images/emojis folder
Now the saddedst part, you need to manually copy id of every emoji and paste it into const/emojis.py file on correct places. (emoji names)
```

# My code
Yes, I do know that my code is shit and spaghetti, but don't worry! Every day I work on improving and this will be improved pretty quick, if you want to make something better feel free to open pr. :D

repository: zbancho-ml/rz-bot

repo_name: zbancho-ml/rz-bot


text:
# "How to Apply" Wizards Product Outline

## Overview
Help Veterans and others find the right online experience to apply for benefits by making it easier to complete "How to Apply" wizards.

We'll make this happen by iterating content pages to quickly navigate users to tools pages where wizards will help determine the right online application for a Veteran's situation.

## Problem Statement
> From [Wizards: "How to Apply" and "Can I file a claim online?" - Discovery Readout](https://github.com/department-of-veterans-affairs/va.gov-team/blob/master/products/public-websites/how-to-apply-wizards/discovery/wizards-discovery-readout.pdf)

Veterans learn about benefits and eligibility requirements from detailed content pages.
These pages may include prerequesite questions potential applicants *could* answer before intiating the "actual" application process.
Answers to these questions help determine where applicants are taken in order to apply i.e. which form or online tool is most appropriate.

A helpful example [is available here](https://www.va.gov/education/how-to-apply/). Applicants navigate to the wizard and complete a series of questions to determine which education application is most appropriate for their needs.

- They are currently four (4) urls where in-content "How to Apply" wizards exist:
  - https://www.va.gov/education/eligibility
  - https://www.va.gov/education/how-to-apply
  - https://www.va.gov/disability/eligibility
  - https://www.va.gov/disability/how-to-file-claim

Veterans typically land on these content pages while researching benefits.
However, these pages may not always make it easy for Veterans to find these helpful in-content wizards (and subsequently the right online application). *data point --> % of views on https://www.va.gov/education/how-to-apply/ that result in outbound navigation to application*

How might we make the Veteran experience of starting online applications more seamless?

<!--*In a couple of sentences, describe the Who, What, Why, and Where of the challenge / pain point you seek to address. [Here's a sample problem statement definition activity you can try on your team to help generate this](https://www.atlassian.com/team-playbook/plays/problem-framing)*-->

<!--*Follow your problem description up with a "How might we... _______" statement re-framing that challenge as an opportunity. Don't hint too much at what the solution might be, you should have enough of a focal point here to guide your ideas, but plenty of freedom to think laterally and innovatively as you experiment and prototype later.* -->

## Assumptions
- Veterans fill out applications that don't apply to their situations (riskiest)
  - Source: Contact Center, respective product teams e.g. Disability, Education
- It's difficult to find "How to Apply" wizards
  - Source: Google Analytics (bounce, etc.)
- Benefit content pages are unnecessarily detailed
  - Source: research studies, Google Analytics (scroll depth, etc.)

<!-- *Include indication of which assumption you think is most risky. Your Solution Approach (next section) should describe how you'll validate that assumtion w/your initial set of functionality* -->

---

## Desired User / Business Outcomes

**Why would a user want to use this?**
**With this problem solved, what should users be able to do/achieve that they couldn't before?**
**Why would your business want this to exist?**
**With this problem solved, what should your business be able to do/achieve that they couldn't before?**

- It's easier for Veterans to find the right online experience to apply for the benefits they're looking for
- Veterans aren't spending time filling out the wrong online application

## Undesired User / Business Outcomes

- It's harder for Veterans and others to find/start applications for benefits they seek

## KPIs
- *What data (qual or quant) will you look at to understand if your initial set of functionality is meeting your desired user and business outcomes, and not bringing about the undesired outcomes?*
  - Ratio of appropriate/inappropriate disability benefit applications started/completed
  - Ratio of appropriate/inappropriate education benefit applications started/completed
  - % of "How to Apply" wizard content pages resulting in applications started

---

## Solution Approach

- *What are you going to build now, and why have you decided to start there?*
- *Why this solution / approach over other solutions / approaches?*
- *What have you explicitly decided to not include in this initial set of functionality, and why?*
- *How will the solution / approach evolve after this initial build (knowing that this will likely change as you learn from users along the way)?*

---

## Go-to-market Strategy
- *How are Veterans and others using this product going to know it exists?*
  - Proposed hypotheses make it easier for Veterans to apply for benefits/submit a claim from content pages where they're most likely to end up in their research.
- *What marketing, outreach, or communications are necessary for this product to be successful?*

## Target Launch Date
- *What is your target launch date of your MVP/iteration?*
  - to be determined

- *What is your date for when you'll evaluate impact after launch?*
  - to be determined

---

## Solution Narrative

### Current Status

### Key Decisions

---

## Screenshots

### Before

### After

---
#### Communications
- Team Name: Public Websites
- GitHub Label: vsa-public-websites
- Slack channel: #vsa-public-websites, #va-how-to-apply-wizards
- POCs: Jennifer Lee, Liz Lantz, Selina Cooper, Mikki Northius

---


text:
# Project 1 - Flickster

Flickster shows the latest movies currently playing in theaters. The app utilizes the Movie Database API to display images and basic information about these movies to the user.

Time spent: 4 hours spent for base requirement

## User Stories

The following **required** functionality is completed:

* [X] User can **scroll through current movies** from the Movie Database API
* [X] Layout is optimized with the [ViewHolder](http://guides.codepath.com/android/Using-an-ArrayAdapter-with-ListView#improving-performance-with-the-viewholder-pattern) pattern.
* [X] For each movie displayed, user can see the following details:
  * [X] Title, Poster Image, Overview (Portrait mode)
  * [X] Title, Backdrop Image, Overview (Landscape mode)

The following **optional** features are implemented:

* [X] Display a nice default [placeholder graphic](http://guides.codepath.com/android/Displaying-Images-with-the-Picasso-Library#configuring-picasso) for each image during loading.
       As the screen is scrolled up, the "image" space is first filled with a blue on white "flowery" image for a brief period.
* [X] Improved the user interface through styling and coloring.
        The more popular movies have a red background with green/yellow and white texts.

The following **bonus** features are implemented:

* [X] Allow user to view details of the movie including ratings and popularity within a separate activity or dialog fragment.
        A new activity is spawned to show these features. The rating is mapped from 1 to 10 to 5 stars.
        The background color is grey.
* [X] When viewing a popular movie (i.e. a movie voted for more than 5 stars) the video should show the full backdrop image as the layout.  Uses [Heterogenous ListViews](http://guides.codepath.com/android/Implementing-a-Heterogenous-ListView) or [Heterogenous RecyclerView](http://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView) to show different layouts.
        Heterogenous view holders have been implemented.
* [X] Allow video trailers to be played in full-screen using the YouTubePlayerView.
        Included youTube player has a purple border.
    * [X] Overlay a play icon for videos that can be played.
        Included play icon.
    * [X] More popular movies should start a separate activity that plays the video immediately.
        A separate activity kicks off the video play -- issue with youtube key fetch due to ASYNC OkHTTP access
    * [X] Less popular videos rely on the detail page should show ratings and a YouTube preview.
        A different activity is first called to show the ratings and backdrop image, (no play icon) which is clickable
        to take the viewer to Youtube preview in yet another activity & screen
* [ ] Apply the popular [Butterknife annotation library](http://guides.codepath.com/android/Reducing-View-Boilerplate-with-Butterknife) to reduce boilerplate code.
        Did not want to do this a gradle update seemed to break my setup.
* [X] Apply rounded corners for the poster or background images using [Picasso transformations](https://guides.codepath.com/android/Displaying-Images-with-the-Picasso-Library#other-transformations)
        All posters and background images, as well as borders on "Title buttons" are rounded corners
* [X] Replaced android-async-http network client with the popular [OkHttp](http://guides.codepath.com/android/Using-OkHttp) networking libraries.
        Have used OkHttp everywhere ( with an if -- boolean-- for switch (set to OkHttp) to Async if needed)

The following **additional** features are implemented:

* [X] List anything else that you can get done to improve the app functionality!

Improve one issue with in thread (ASYNC) executions for youtube key fetch.
(Unable to implement the client request execut function with youtube key access in spite
of researching with code path documentation and other similar documents on line. )

Add Butterknife annotation, much earlier in the project so that the gradle environment
does not need to update at the 11 th hour.

Genymotion keeps crashing frequently. I used my phone for a lot of debugging and it went a bit faster.

## Video Walkthrough

Here's a walkthrough of implemented user stories:

.
http://i.imgur.com/pfL5Frw.gif

<iframe class="imgur-embed" width="100%" height="654" frameborder="0" src="http://i.imgur.com/pfL5Frw.gifv#embed"></iframe>

GIF created with [LiceCap](http://www.cockos.com/licecap/).

## Notes

Video guide provided by codepath is very useful.
Did not have any problems implementing base requirements plus a couple of optionals.

## Open-source libraries used

- [Android Async HTTP](https://github.com/loopj/android-async-http) - Simple asynchronous HTTP requests with JSON parsing
- [Picasso](http://square.github.io/picasso/) - Image loading and caching library for Android

## License

    Copyright [2017] [HK]

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

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

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

repository: Ameritronik/Flickster

repo_name: Ameritronik/Flickster


text:
# mkinnear2018

[![CI Status](https://img.shields.io/travis/mkinnear/mkinnear2018.svg?style=flat)](https://travis-ci.org/mkinnear/mkinnear2018)
[![Version](https://img.shields.io/cocoapods/v/mkinnear2018.svg?style=flat)](https://cocoapods.org/pods/mkinnear2018)
[![License](https://img.shields.io/cocoapods/l/mkinnear2018.svg?style=flat)](https://cocoapods.org/pods/mkinnear2018)
[![Platform](https://img.shields.io/cocoapods/p/mkinnear2018.svg?style=flat)](https://cocoapods.org/pods/mkinnear2018)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

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

```ruby
pod 'mkinnear2018'
```

## Author

mkinnear<EMAIL_ADDRESS>
## License

mkinnear2018 is available under the MIT license. See the LICENSE file for more info.


text:
# tf-aws-eks
This Terraform template deploy an high availability Amazon Web Services EKS cluster

# Configure AWS environment
```bash
export AWS_ACCESS_KEY_ID="anaccesskey"

export AWS_SECRET_ACCESS_KEY="asecretkey"

export AWS_DEFAULT_REGION="<us-west-2 | us-east-1 | eu-west-1>"
```

# Initialize Terraform
```bash
terraform init
```
Then onfigure Terraform's variables

# Run Terraform
```bash
terraform plan -var-file=eks.tfvars -out=out.tfplan

terraform apply out.tfplan
```

# Connect to EKS
Install Kubernetes CLI: kubectl and aws-iam-authenticator for Amazon EKS:
https://docs.aws.amazon.com/eks/latest/userguide/configure-kubectl.html

Create a file named "config" on your home directory and copy the content of Terraform output variable "kubeconfig".
Then:
```bash
export KUBECONFIG=$HOME/config
kubectl get svc
```

# Add node
Ass documented at this time, 2018-09-11, the EKS service does not provide a cluster-level API parameter or resource to automatically configure the underlying Kubernetes cluster to allow worker nodes to join the cluster via AWS IAM role authentication.
You have to manually enable worker nodes to join your cluster through Kuberneter config maps:
https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html

Note that output variable config-map-aws-auth, in node.tf, generate the config map.

repository: mondora/tf-aws-eks

repo_name: mondora/tf-aws-eks


text:
# Welcome to the VLOG Dataset!

This repository contains useful tools for working with the VLOG dataset. We may update
this with additional tools as time goes on. For the dataset itself, please see [here](http://people.eecs.berkeley.edu/~dfouhey/2017/VLOG/)
or if you are lazy, the data file is [here](http://people.eecs.berkeley.edu/~dfouhey/2017/VLOG/data/data_v1.1.tgz). You may
be able to download our cached copies if you meet certain conditions. Please see the website for details.

Dependencies:

* numpy
* scipy
* sklearn

You have to specify paths to files in the following files (although all the scripts will prompt you for paths):

* `DATA_ROOT` should contain the path of the labels directory
* `CLIP_ROOT` should contain the path of the clips, dumped in the /X/Y/Z/v_TUVWXYZ/001/clip.mp4 format described in the data folder
* `FRAME_ROOT` should contain the path of the frames, dumped in the /X/Y/Z/v_TUVWXZ/001/frame000001.jpg format described in the data folder

## Evaluation

`eval.py` contains evaluation scripts that will let you reproduce the numbers reported in the paper given
the precomputed predictions provided with the dataset.

You always have to specify:
* `--benchmark` (`hand_object`, `hand_state`, `scene_proxemic`, `scene_category`)
* `--predictions` a file specifying the predictions, either a .txt or .npy file

The following options always apply:
* `--dobci` This compute 95% bootstrapped confidence intervals using the bias correction method, boostrapping the uploader (i.e., not
 treating the videos as independently). They seem pretty tight and not worth worrying too much about.
* `--dobreakdown` (`scene_proxemic`, `scene_category`) This runs the evaluation for each of the proxemic/semantic categories for scenes.

## Demo Reading Code

`demo.py` contains demo code that loads and displays the data. This will open a series of windows using `eog` and `cvlc`, so it may
or may not work depending on your computer. It also displays hand bounding boxes by using opencv.

repository: dfouhey/VLOGToolkit

repo_name: dfouhey/VLOGToolkit


text:
---
title: "The Straits Times: Create shopping experiences that stands out to draw
  customers back"
permalink: /success-and-articles/articles/st-shopping-experiences/
description: ""
third_nav_title: Articles
---
Date:   14-04-2022

Forum: Create shopping experiences that stands out to draw customers back

*Click [here](https://www.straitstimes.com/opinion/forum/forum-create-shopping-experiences-that-stand-out-to-draw-customers-back) to read the full story from The Straits Times*

![Create shopping experiences that stands out to draw customers back to retail malls](/images/blog/20220414_mall.jpg)

As Singapore eases its COVID-19 measures and travel regulations, what should retailers with a physical presence do to attract customers back to their stores?

It is imperative for retailers to ensure that service excellence tops their corporate agenda, to create VIP experiences to attract footfall, engage with shoppers, and retain loyal customers.

Need help curating an unforgettable customer experience? Check out these courses conducted by SIRS:

* [Creating an Unforgettable Customer Experience ](https://www.sirs.edu.sg/wsq-programmes/wsq-modular-programmes/creating-an-unforgettable-customer-experience)
* [The Art and Science of Visual Merchandising](https://www.sirs.edu.sg/wsq-programmes/wsq-modular-programmes/the-art-and-science-of-visual-merchandising)
* [Digital Commerce Visual](https://www.sirs.edu.sg/digital-programmes/masterclasses-and-workshops/digital-commerce-visual)

url: https://raw.githubusercontent.com/isomerpages/nyp-sirs/1816e778ecc7b321d210ff3deb0bba37c6d9844b/_success-and-articles/Articles/The Straits Times: Create shopping experiences that stands out to draw customers back.md

repository: isomerpages/nyp-sirs

branch_name: refs/heads/staging

gha_language: SCSS

gha_license_id: NOASSERTION

repo_name: isomerpages/nyp-sirs


text:
# StarMadeJoinStats
StarMadeJoinStats is a small project to provide a few simple web graphs on player join statistics for the game StarMade

## About ##

StarMadeJoinStats is a small project utilising MySQL, PHP and javascript to provide a few simple graphs on player join statistics for the game StarMade.

It works by parsing the game log files on a scheduled basis (crontabs), and inserting into a MySQL table unique appearances of a player per day. Armed with that raw data, some simple analysis can be done to produce useful information such as new vs returning players per day and per month.

Live example: https://www.sheen.id.au/starmadejoinstats/

Example image: ![alt tag](https://raw.github.com/mikesheen/starmadejoinstats/master/sampleimage.png)

## Prerequisites ##

MySQL is required - in debian this is simple to install:
apt-get install mysql-server

## Installation ##
Create the MySQL database and user, and set permissions

```
mysql -u root -p
mysql> create user 'starmade'@'localhost' identified by 'thisismymysqlpassword';
mysql> create database starmadedb;
mysql> grant usage on *.* to starmade@localhost identified by 'thisismymysqlpassword';
mysql> grant all privileges on starmadedb.* to starmade@localhost;
```

Now create the table

```
CREATE TABLE IF NOT EXISTS `connectionlog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `playername` varchar(50) NOT NULL,
  `date` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `playername_date` (`playername`,`date`),
  KEY `playername` (`playername`,`date`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
```

## Configuration ##
### starmadeconnectionlog.php ###
This PHP script parses ALL the log files in your server log folder and puts the entries into the MySQL table.
place this file in your starmade server folder (the same folder as the game)
Edit the starmadeconnectionlog.php and set the variables at the top to be the appropriate values
### starmadeupdatedailyplayercount.sh ###
This shell script runs queries against the MySQL table to produce the text files (CSV) the web page needs for the graphs. I opted to generate the CSV's once an hour because I didn't want the web clients causing database hits - so this is a poor mans caching strategy.
place this file in your starmade server folder (the same folder as the game)
Edit the starmadeupdatedailyplayercount.sh and set the variables at the top to be the appropriate values
Set the permission for this file to allow execute:

```
chmod +x starmadeupdatedailyplayercount.sh
```
### www files ###
place these in a folder under your www root - be sure to include the js folder.
You will probably need to give permissions to the webserver on the js files

```
chgrp -R www-data js/*.*
```
### crontabs ###
You need to add some crontabs to regularly parse the logs and generate the files the graphs report on. I opted for once an hour. The unique index on the table means you can parse the same log file without risk of duplicates - this was the only reliable way I found of updating the logs with the retention policy which StarMade has for log files. You don't want the crontab to be more than a day, and and it only takes a fraction of a second to run - one hour has worked fine in my production server for over a year, with no impact on server peformance.
Edit the crontab with:

```
crontab -e
```
Then add the crontab entries:

```
# m h  dom mon dow   command
#crontab one minute past every hour to create log entries in the mysql connectionlog table
1 * * * * /usr/bin/php -f /home/starmade/StarMade/starmadeconnectionlog.php
#crontab on the second minute of every hour to generate the text files we graph on
2 * * * * /home/starmade/StarMade/starmadeupdatedailyplayercount.sh
```

It will be some time (days) before you start to get a useful amount of data. If you have older log files, you can feed that into the MySQL table by copying the starmadeconnectionlog.php, and editing the log file source in that, then running it for a one-off import of older logs.

eg: copy starmadeconnectionlog.php to legacyimport.php
Then edit legacyimport.php to point to your older log files
Now run the php manually:

```
/usr/bin/php -f /home/starmade/StarMade/legacyimport.php
```

repository: mikesheen/StarMadeJoinStats

repo_name: mikesheen/StarMadeJoinStats


text:
---
title: "Tip of the Week #181: Accessing the value of a StatusOr<T>"
layout: tips
sidenav: side-nav-tips.html
published: true
permalink: tips/181
type: markdown
order: "181"
---

Originally posted as TotW #181 on July 9, 2020

*By [Michael Sheely](mailto:msheely@google.com)*

Updated 2020-09-02

Quicklink: [abseil.io/tips/181](https://abseil.io/tips/181)

> `StatusOr<Readability>`: you don't have to choose!

When the time comes to access the value inside an `absl::StatusOr<T>` object, we
should strive to make that access *safe*, *clear*, and *efficient*.

Note: This tip attempts to highlight
[well lit paths](https://moma.corp.google.com/glossary/term/11ngkm2f_v)
providing guidance for typical use-cases. It is not intended to be exhaustive.
If you encounter edge cases, consider the recommendations and reasoning here and
exercise judgement.

## Recommendation

Accessing the value held by a `StatusOr` should be performed via `operator*` or
`operator->`, after a call to `ok()` has verified that the value is present.

// The same pattern used when handling a unique_ptr...
std::unique_ptr<Foo> foo = TryAllocateFoo();
if (foo != nullptr) {
  foo->DoBar();  // use the value object
}

// ...or an optional value...
std::optional<Foo> foo = MaybeFindFoo();
if (foo.has_value()) {
  foo->DoBar();
}

// ...is also ideal for handling a StatusOr.
absl::StatusOr<Foo> foo = TryCreateFoo();
if (foo.ok()) {
  foo->DoBar();
}

You can limit the scope of a `StatusOr` by declaring it in the initializer of
the `if` statement and checking `ok()` in the condition. If using a `StatusOr`
immediately, you generally *should* limit scope in this way (see
[Tip #165](/tips/165)):

if (absl::StatusOr<Foo> foo = TryCreateFoo(); foo.ok()) {
  foo->DoBar();
}

## Background on StatusOr

The `absl::StatusOr<T>` class is a
[tagged union](https://en.wikipedia.org/wiki/Tagged_union) with
[value semantics](https://isocpp.org/wiki/faq/value-vs-ref-semantics) indicating
exactly one of the following situations:

*   an object of type `T` is available,
*   an `absl::Status` error (`!ok()`) indicating why the value is not present.

You can read more about `absl::Status` and `absl::StatusOr` in
[Tip #76](/tips/76).

## Safety, Clarity, and Efficiency

Treating the `StatusOr` object as one would treat a smart pointer helps code
achieve clarity while remaining safe and efficient. Below, we will consider some
of the other ways you might have seen a `StatusOr` accessed, and why we prefer
the approach using the indirection operators.

### Alternative Value Accessor Safety Issues

What about `absl::StatusOr<T>::value()`?

absl::StatusOr<Foo> foo = TryCreateFoo();
foo.value().DoBar();  // Behavior depends on the build mode.

Here, the behavior depends on the build mode -- in particular, whether the code
was compiled with exceptions enabled.[^1] As such, it is not clear to readers if
an error status will terminate the program.

The `value()` method combines two actions: a test for validity followed by an
access of the value. It should therefore be used *only if* both actions are
intended (and even then, think twice and consider that its behavior depends on
the build mode). If the status is already known to be `OK`, then your ideal
accessor has semantics of simply accessing the value, which is exactly what
`operator*` and `operator->` provide. In addition to making the code more
precisely indicate your intent, the access will be at least as efficient as
`value()`'s contract to test for validity and then access the value.

### Avoiding Multiple Names for the Same Object

Treating `absl::StatusOr` objects as we would a smart pointer or `optional`
value also allows us to avoid the conceptually awkward situation of having two
variables referring to the same value. It also avoids the naming dilemmas and
`auto` overuse which come with this territory.

// Without digging up the declaration of TryCreateFoo(), a reader will not
// immediately understand the types here (optional? pointer? StatusOr?).
auto maybe_foo = TryCreateFoo();
// ...compounded by the use of implicit bool rather than `.ok()`.
if (!maybe_foo) { /* handle foo not present */ }
// Now two variables (maybe_foo, foo) represent the same value.
Foo& foo = maybe_foo.value();

### Avoiding the _or Suffix

Another benefit of using a `StatusOr` variable's intrinsic value type after
checking for validity (rather than creating multiple variables for the same
value) is that we can use the best name for the `StatusOr` without the need (or
temptation!) to add a prefix or suffix.

There is an analogy here to the
[avoidance of the "`_ptr`"](https://google.github.io/styleguide/cppguide.html#Windows_Code)
suffix when naming pointer variables.

// The type already describes that this is a unique_ptr; `foo` would be fine.
std::unique_ptr<Foo> foo_ptr;

absl::StatusOr<Foo> foo_or = MaybeFoo();
if (foo_or.ok()) {
  const Foo& foo = foo_or.value();
  foo.DoBar();
}

If there is only one variable (the `StatusOr`, avoiding a second named variable
for the unwrapped value), we can drop the suffix, simply naming the variable
after its underlying value (just as we do with pointers).

const absl::StatusOr<Foo> foo = MaybeFoo();
if (foo.ok()) {
  MakeUseOf(*foo);
  foo->DoBar();
}

### Moving from the Value of an absl::StatusOr

We might write code to move from the `T` of an `absl::StatusOr<T>`:

absl::StatusOr<Foo> foo = MaybeFoo();
if (foo.ok()) {
  ConsumeFoo(std::move(*foo));
}

It's a little better, though, to move from the `StatusOr` itself, indicating to
readers (both humans and machines) that the entire `StatusOr` object should not
be used after its value has been moved from:

absl::StatusOr<Foo> foo = MaybeFoo();
if (foo.ok()) {
  ConsumeFoo(*std::move(foo));
}

## Solution

Testing the `absl::StatusOr` object for validity (as you would a smart pointer
or `optional`) and accessing it using `operator*` or `operator->` is readable,
efficient, and safe.

It helps you avoid the potential pitfalls of naming ambiguity mentioned above,
and does it all without the use of any macros.

Code that accesses values via `operator*` or `operator->` (whether using a
pointer, a `StatusOr`, an `optional`, or otherwise) must first verify that the
value is present. This validation should be close to where the value is accessed
so that readers can easily verify that it is present and correct.

[^1]: Per the
    [documentation](https://github.com/abseil/abseil-cpp/blob/master/absl/status/statusor.h)
    of the `value()` function, if exceptions are enabled, this will throw
    `absl::BadStatusOrAccess` (which may be caught, meaning the program may
    not terminate). If compiled without exceptions, code will crash with
    `LOG(FATAL)`.

gha_language: HTML


text:
# js-plugin-starter
Simple JS plugin starter repository

With all necessary configuration to bootstrap your ideas and get rid of setting everything all over again.

## Instruction

1. Clone Repository

    ```bash
    git clone git@github.com:michalsnik/js-plugin-starter.git your-plugin-name
    ```

2. Go to your-plugin name folder and install npm packages

    ```bash
    cd your-plugin-name && npm install
    ```

3. If you change ```plugin.js``` or ```plugin.scss``` name remember to change it inside ```plugin.json``` file as well.
    Gulp tasks relies on those names in order to do its job correctly.

4. Run gulp

    ```bash
    gulp
    ```

5. Go to ```http://localhost:3000/demo/``` and now you're ready to roll

### Additional info

Starter uses browserify for bundling JS, so don't hesitate to require node modules and partition your code to make it more pleasant to work with.

repository: michalsnik/js-plugin-starter

repo_name: michalsnik/js-plugin-starter


text:
# OPENQASM 2.0 Grammar

> This is the grammar for OPENQASM 2.0, written for Antlr4.
> NOTE: This grammar doesn't have 'include' statements, as that should be done in preprocessing

## Usage

You should have antlr4 installed: [here](http://www.antlr.org/download.html).

You can test the parser and see an AST like so:

```
$ antlr4 ./QASM.g4
$ javac QASM*.java
```

```
$ grun QASM mainprog -gui
```

## Examples

The following parse tree is from the QASM code below:

![Parse Tree](https://raw.github.com/qcgpu/QASM-Grammar/master/examples/antlr4_parse_tree.svg?sanitize=true)

```AS
// Repetition code syndrome measurement
OPENQASM 2.0;
qreg q[3];
qreg a[2];
creg c[3];
creg syn[2];
gate syndrome d1,d2,d3,a1,a2
{
  cx d1,a1; cx d2,a1;
  cx d2,a2; cx d3,a2;
}
x q[0]; // error
barrier q;
syndrome q[0],q[1],q[2],a[0],a[1];
measure a -> syn;
if(syn==1) x q[0];
if(syn==2) x q[2];
if(syn==3) x q[1];
measure q -> c;
```

## BNF Grammar

This grammar is based off the BNF grammar, detailed in [this paper](https://arxiv.org/pdf/1707.03429.pdf):

```bnf
mainprogram: "OPENQASM" real ";" program

program: statement | program statement

statement: decl
  :| gatedecl goplist }
  :| gatedecl }
  :| "opaque" id idlist ";"
  :| "opaque" id "( )" idlist ";"
  :| "opaque" id "(" idlist ")" idlist ";"
  :| qop
  :| "if (" id "==" nninteger ")" qop
  :| "barrier" anylist ";"

decl: "qreg" id [ nninteger ] ";" | "creg" id [ nninteger ] ";"

gatedecl: "gate" id idlist {
  :| "gate" id "( )" idlist {
  :| "gate" id "(" idlist ")" idlist {

goplist: uop
  :| "barrier" idlist ";"
  :| goplist uop
  :| goplist "barrier" idlist ";"

qop: uop
  :| "measure" argument "->" argument ";"
  :| "reset" argument ";"

uop: "U (" explist ")" argument ";"
  :| "CX" argument "," argument ";"
  :| id anylist ";" | id "( )" anylist ";"
  :| id "(" explist ")" anylist ";"

anylist: idlist | mixedlist

idlist: id | idlist "," id

mixedlist: id [ nninteger ] | miedlist "," id
  :| mixedlist "," id [ nninteger ]
  :| idlist "," id [ nninteger ]

argument: id | id [ nninteger ]

explist: exp | explist "," exp

exp: real | nninteger | "pi" | id
  :| exp + exp | exp - exp | exp * exp
  :| exp / exp | -exp | exp ^ exp
  :| "(" exp ")" | unaryop "(" exp ")"

unaryop: "sin" | "cos" | "tan" | "exp" | "ln" | "sqrt"

id        := [a-z][A-Za-z0-9_]*
real      := ([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?
nninteger := [1-9]+[0-9]*|0
```

## Licence

Copyright Adam Kelly, MIT License

repository: libtangle/QASM-Grammar

repo_name: libtangle/QASM-Grammar


text:
---
page_title: "morpheus_active_directory_identity_source Resource - terraform-provider-morpheus"
subcategory: ""
description: |-
  Provides an active directory identity source resource
---

# morpheus_active_directory_identity_source

Provides an active directory identity source resource

## Example Usage

```terraform
resource "morpheus_active_directory_identity_source" "addemo" {
  tenant_id               = 1
  name                    = "addemo"
  description             = "TF example AD identity source"
  ad_server               = "dc01.contoso.com"
  domain                  = "contoso.com"
  use_ssl                 = false
  binding_username        = "administrator"
  binding_password        = "Password123"
  required_group          = "administrators"
  search_member_groups    = true
  default_account_role_id = 7

  role_mapping {
    role_id                     = 2
    role_name                   = "developers"
    active_directory_group_name = "developers"
    active_directory_group_fqn  = "CN=developers,CN=Users,DC=contoso,DC=com"
  }
}
```

## Schema

### Required

- `ad_server` (String) The IP address or hostname of the active directory domain controller
- `binding_password` (String, Sensitive) The password of the account used to authenticate to the domain
- `binding_username` (String) The username of the account used to authenticate to the domain
- `default_account_role_id` (Number) The id of the default role a user is assigned when they are in the required group or if no specific group mapping applies to the user
- `domain` (String) The name of the active directory domain
- `name` (String) The name of the active directory identity source
- `tenant_id` (Number) The ID of the Morpheus tenant to associate the identity source with

### Optional

- `description` (String) The description of the active directory identity source
- `enable_role_mapping_permission` (Boolean) When enabled, Tenant users with appropriate rights to view and edit Roles will have the ability to set role mapping for the Identity Source integration
- `required_group` (String) The active directory group users must be in to access Morpheus
- `role_mapping` (Block Set) The Active Directory to Morpheus Role mapping (see [below for nested schema](#nestedblock--role_mapping))
- `search_member_groups` (Boolean) Whether groups nested inside the required group will also be included
- `use_ssl` (Boolean) Whether to use SSL when connecting to the domain controller

### Read-Only

- `id` (String) The ID of the active directory identity source

### Nested Schema for `role_mapping`

Optional:

- `active_directory_group_fqn` (String) The fully qualified name of the active directory role to map to (i.e. - CN=Administrators,CN=Builtin,DC=contoso,DC=com)
- `active_directory_group_name` (String) The name of the active directory role to map to
- `role_id` (Number) The id of the Morpheus role to map to
- `role_name` (String) The name or authority of the Morpheus role to map to

## Import

Import is supported using the following syntax:

```shell
terraform import morpheus_active_directory_identity_source.tf_example_active_directory_identity_source 1
```

repository: gomorpheus/terraform-provider-morpheus

gha_language: Go

gha_license_id: MIT

repo_name: gomorpheus/terraform-provider-morpheus


text:
# EMATS: Event Management and Attendance Tracking System using QR Codes

An intuitive and user-friendly tool for event management and attendance tracking. The system relies on Google Forms and ZXing QR Code Scanner for scanning QR codes. When the participants register for an event using the Google forms, the Google app script associated with the forms, sends out a QR code to the registered email address. The participant then presents this QR code at the event venue to gain entry (upon validation of the code). Additionally, the mobile app also shows pie charts with participant demographics, food requirements etc.

# Pre- Requisites and Dependencies
The following software tools are required to execute the EMATS:
- Android smartphone with [ZXing QR Code Scanner](https://play.google.com/store/apps/details?id=com.google.zxing.client.android&hl=en) for reading the QR codes
- [MIT App Inventor 2](http://ai2.appinventor.mit.edu/)
- Google Drive account to setup GForms and a linked spreadsheet to log the responses
- A stable internet connection as the data will be validated using the spreadsheet which is also updated iteratively

# Setting up for the 1st time
After making sure the prerequisites in the previous section are met, please follow the steps in [this video.](https://youtu.be/9VEm5XgfFrk)

# Scan Results

As seen below, the application will indicate whether the QR Code is authentic or not.

![Alt Text](https://media.giphy.com/media/TifymW8ZCUUT7o8opq/giphy.gif)

# Pie Chart

When deployed as a webservice, the link will lead to a pie chart that illustrates the attendance turnout. It can be accessed from any device with an internet connection, so it enables easy tracking of the turnout.

![piechart](https://gitlab.com/ktiwari9/event-management-system/uploads/39fd6e13d949b0ab794e93327de17f2c/piechart.PNG)

# Contributing

As this is an open-sourced project, we encourage users to contribute to further enhance the functionalities and features provided. In order to do so, please read the [contribution guidelines](https://gitlab.com/ktiwari9/event-management-system/blob/master/CONTRIBUTING.md).

# Developers
 - [Kshitij Tiwari](https://sites.google.com/view/kshitijtiwari/)
 - [Onur Sari](https://www.linkedin.com/in/onursari92/)

 # License and Rights for Reuse
 This project is licensed under the MIT License - see the [LICENSE.md](https://gitlab.com/ktiwari9/event-management-system/blob/master/LICENSE) file for details.

 # Feedback
 We would appreciate if you could leave us a feedback about your experience if you have used EMATS. Please use [this](https://docs.google.com/forms/d/e/1FAIpQLSdXwozGdVolg0sqWU2jXpGPJh0_A-vSuBDzdrt-fSwt9oVznA/viewform?usp=pp_url&entry.260474072=5&entry.879531967=Yes) form to let us know your opinion and you can use the same form to let us know if you wish to contribute to this project.