text:
---
title: 25 Years of Art, Activism and Family!
sidebar:
  heading: There are so many ways to participate!
  text: Your generous support is vital to our work. **[Make your gift
    today](https://goldenthread.secure.force.com/donate/?dfId=a0n3Z00000tn4RsQAI)**.

 Request a match through your employer’s matching gift program and
    double your gift!

 Designate us to receive 0.5% of your Amazon
    purchases when you shop through
    **[smile.amazon.com](http://smile.amazon.com)**.
---
[![Donate Button](/img/archive/2015/03/Donate-Button-400.jpg)](https://goldenthread.secure.force.com/donate/?dfId=a0n3Z00000tn4RsQAI)

![](/img/archive/2015/03/20thAnniversary-Line-1024x36.jpg)

# Another 25 years starts with your donation today!

As the world around us changes, Golden Thread’s commitment to bring you stories from and about the Middle East remains constant.

For 25 years we've been:

**Enriching the American Theatre**

In 25 years, we have premiered more than 120 plays, offering complex and layered representations of the Middle East and its people through new play commissions, ensemble devised work, and local and international collaborations. We have created opportunities for more than 1,000 artists, making deep investment in their work so they may tell their stories in their own words.

**Leading the Charge on Equity**

Building on years of advocating for artists of Middle Eastern heritage, we co-authored two seminal documents released in 2017. The Middle Eastern American Theatre Artists Bill of Rights and the Dear Producers letter were early examples of calls for more equitable practices in the American theater and have since served as models of change among theatre producers.

**Championing Community**

We are the first American theatre to focus on the Middle East, with a founder widely recognized as “the Mother of Middle Eastern American Theatre.” We are also a proud founding member of the newly launched Middle Eastern North African Theatre Makers Alliance, the first national organization advocating for our community.

**Diversity is Our Core**

Our audience is unlike any other. Over half of our audience self-identify as Middle Eastern, and there are 12 languages spoken amongst them. More than 70% of our artists are from BIPOC and immigrant communities, with many also identifying as mixed blood and/or LGBTQ. Golden Thread is that rare artistic home where everyone is encouraged to bring their full self and the many layers of their identity to the table.

**Innovation is Our Practice**

We continuously innovate and make space for artistic risk taking. Back in 2009 we staged The Review, written to be performed over Skype with one actor, director, and audience team in San Francisco, and one team in Cairo. In 2012, we launched Project Alo?, a video dialogue project produced on participants smart phones, that partnered Middle Eastern American artists with artists in the Middle East. And today, we are producing audio plays and connecting with our global audience through new digital content.

**Instilling Cultural Pride**

Our ground-breaking programs like Golden Thread Fairytale Players and Islam 101 bring timeless tales and historical figures to life with dazzling visuals, dance, and music, providing Middle Eastern youth and families the rare opportunity to celebrate their heritage across generations and communities.

Your support is essential as we adapt to the many challenges ahead. Make your contribution online today!

[![Donate Button](/img/archive/2015/03/Donate-Button-400.jpg)](https://goldenthread.secure.force.com/donate/?dfId=a0n3Z00000tn4RsQAI)


text:
# Setup tools and environment on windows 10

## resources:
- https://docs.microsoft.com/en-us/windows/wsl/install-win10
- https://linuxhint.com/install_aws_cli_ubuntu/
- https://kubernetes.io/docs/tasks/tools/install-kubectl/
- https://kubernetes.io/docs/setup/production-environment/tools/kops/
- https://helm.sh/docs/intro/install/

## Step 1: Gather all the tools you need:
- enable windows sub system linux - important
- ubuntu windows app - PowerShell is nice but this is so much better!
- awscli - needed to be able to access our AWS cloude
- kubectl - needed to deploy and update your kubernetes cluster
- kops - used to deploy configure and update your cluster
- helm - used to easily create and deploy services
- restart and verify installation

## Enable windows sub system linux
First run PowerShell as administrator ( right click run as administrator)
enter the following line. \
`Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux` \
click enter and restart ( *important!* )

## Ubuntu 18 windows app
Next we need to go to Microsoft Store ( start -> Microsoft Store ). We are looking for Ubuntu 18. Once you find it click install. \
Once installed it will prompt you to enter username and password
- NOTE: dont overdo it, use simple username and password you can easily write, you will be writing it a lot
- recommended - pin the terminal in start menu, makes life easier

Once install you will see Linux terminal with `your username@pc name:~$`.
- Disclaimer, this distribution does not support `snap`
- Pasting and copying is right click

## Install aws-cli
Open Linux Terminal and run these code snippets in order
- ``sudo apt-get update``
- ``sudo apt-get install awscli``
- ``aws --version`` - my version for this tutorial is `aws-cli/1.14.44`

## Install kubectl
Open Linux Terminal and run these code snippets in order
- ``cd ~``
- ``curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl``
- ``chmod +x ./kubectl``
- ``sudo mv ./kubectl /usr/local/bin/kubectl``
- ``kubectl version --client`` - my version for this tutorial is `v1.18.2`

## Install kops
Open Linux Terminal and run these code snippets in order
- ``cd ~``
- ``curl -LO https://github.com/kubernetes/kops/releases/download/$(curl -s https://api.github.com/repos/kubernetes/kops/releases/latest | grep tag_name | cut -d '"' -f 4)/kops-linux-amd64``
- ``chmod +x kops-linux-amd64``
- ``sudo mv kops-linux-amd64 /usr/local/bin/kops``
- ``kops version`` - my version for this tutorial is `1.16.1`

## Install heml
Open Linux Terminal and run these code snippets in order
- ``cd ~``
- ``curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3``
- ``chmod 700 get_helm.sh``
- ``./get_helm.sh``
- ``helm version`` - my version for this tutorial is `v3.2.0`

## Restart and verify
To make sure everything runs properly i highly recommend to restart your PC, enter Linux Terminal and run versions
- ``aws --version`` - my version for this tutorial is `aws-cli/1.14.44`
- ``kubectl version --client`` - my version for this tutorial is `v1.18.2`
- ``kops version`` - my version for this tutorial is `1.16.1`
- ``helm version`` - my version for this tutorial is `v3.2.0`

Congrats! Now you have linux running on your Windows machine and you can move to the next step!

license: MIT

repository: howtoclient/aws-kops-instalation

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: howtoclient/aws-kops-instalation


text:
React provides a way to take some actions on different lifecycle phases of the component. There are several benefits of  that. For example we may want to fetch some data when a component is rendered, or clean up some resources before the component is removed from the DOM. React calls these lifecycle methods (if we have defined them) during these lifecycle phases. You are not required to implement any of these lifecycle methods and implement only those that you need on your particular component.

```jsx
class ComponentWithLifecycle extends React.Component {
    constructor(props){
        super(props);
    }

    componentDidMount(){
        //This will be called after the component is mounted to the DOM
    }

    componentDidUpdate(prevProps, prevState){
        //This will be called after the component is updated
        //Remember component can only be updated when the state changes
        //or the props changes
    }

    componentWillUnmount(){
        //This will be called right before this component is unmounted from
        //the DOM
    }
}
```

Lets look at some common use cases of when these lifecycle methods comes in handy.

Let's consider the `CompanyProfile` example we looked at earlier where we were displaying the `ticker` and the `companyProfileInformation`. On the example the parent of the component passed both `ticker` and `companyProfileInformation` as `props`. But let's assume that parent only has the `ticker` information which it will pass as `props` but it doesn't have the profile information data. Assume there's an API that the `CompanyProfile` component can use to fetch the profile information data. This is very common use case. So how/when should the `CompanyProfile` component fetch the data. `componentDidMount` is the right lifecycle method to make the network call (fetch data using the API). This method is called only once when the component is mounted on the DOM. After the API returns the data we can set the data to the `state` and use `this.state.companyProfileInformation` instead of `this.props.companyProfileInformation` inside the `render` function.
Remember in this case the parent didn't pass the `companyProfileInformation` props but instead `CompanyProfile` fetched that data itself and stored in the `state`.

```jsx
import DataApi from '../api';

class CompanyProfile extends React.Component {
    componentDidMount() {
        DataApi.getCompanyProfile(this.props.ticker)
        .then(profile => {
            this.setState({
                companyProfileInformation: profile
            })
        })
    }
}
```

Let's do the same exercise. Please open the exercise file and make the change as instructed on the file.

<!--exercise-->

That works for the initial value of `ticker` passed by parent because `componentDidMount` is called only once but what happens when the `props` changes - meaning the parent component passes a new `ticker` value. How/When would `CompanyProfile` component know to fetch data again for the new `ticker`? In that case you can use `componentDidUpdate`. This lifecycle method is called every time component is updated. Remember component is updated every time the `props` or the `state` changes.

You're probably thinking - 'This doesn't sound good'. If you were to fetch the data inside `componentDidUpdate` (which would be called every time your component updates), your component will make a lot of repetitive network calls to get the profile information for same ticker because the component might have updated not just when `ticker` props changed but when any other `props` changed or some other `state` changed.
Well you're thinking correctly. That's the reason why you should **always** check if the `props` you are interested in changed (in this case `ticker` changed) before making the network request.

```jsx
import DataApi from '../api';

class CompanyProfile extends React.Component {
    //when react calls componentDidUpdate, it gives as argument the value of
    // props and state before the update happened so you can do the comparision
    componentDidUpdate(prevProps, prevState) {
        //always be defensive otherwise you will make a lot of
        //unnecessary network calls
        //in this case we only make the network call if the
        //ticker props before and after the component updated are not same
        if (prevProps.ticker !== this.props.ticker) {
            DataApi.getCompanyProfile(this.props.ticker)
            .then(profile => {
                this.setState({
                    companyProfileInformation: profile
                })
            })
        }
    }
}

```

These are just some common use cases when you want to use lifecycle methods provided by React. Please refer to the
[React documentations](https://reactjs.org/docs/react-component.html#the-component-lifecycle)
for extensive list of all the lifecycle methods available.

Also note that there are some lifecycle methods that were available as part of earlier version of React (16 and earlier) but they will be deprecated as part of version 17.0, so **DO NOT** use them.

- componentWillMount
- componentWillUpdate
- componentWillReceiveProps

Please refer to this [blog post](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html) to understand why these lifecycle methods are being deprecated and also more about some best practices regarding usage of lifecycle methods.

repository: jankohlbach/learn-react-app

gha_language: JavaScript

gha_license_id: MIT

repo_name: jankohlbach/learn-react-app


text:
---
layout: tutorial
title: Form validation
icon: exclamation-circle
overview: This tutorial covers patterns for form validation, building on both the form widget tutorial and the state management tutorial.
paginate: true
topic: forms
---

{% section 'first' %}

# Form validation

## Overview

This tutorial will cover how to handle basic form validation within the context of the demo app. Handling form data has already been covered in the tutorial on [injecting state](../1010_containers_and_injecting_state); here we will build on those concepts to add a validation state and errors to the existing form. Over the course of the tutorial we will build an example pattern for creating both dynamic client-side validation and mock server-side validation.

## Prerequisites
You can open the [tutorial on codesandbox.io](https://codesandbox.io/s/github/dojo/dojo.io/tree/master/site/source/tutorials/1015_form_validation/demo/initial/biz-e-corp) or [download](../assets/1015_form_validation-initial.zip) the demo project and run `npm install` to get started.

This tutorial assumes that you have gone through the [form widgets tutorial](../005_form_widgets) as well as the [state management tutorial](../1010_containers_and_injecting_state).

{% section %}

## Create a place to store form errors

{% task 'Add form errors to the application context.' %}

Right now the error object should mirror `WorkerFormData` in both `WorkerForm.ts` and `ApplicationContext.ts`. In the wild this error configuration could be handled in a number of ways; one might be to provide an option for multiple validation steps with individual error messages for a single input. Here we will go for the simplest solution with a boolean valid/invalid state for each input.

{% instruction 'Create an interface for `WorkerFormErrors` in `WorkerForm.ts`' %}

{% include_codefile 'demo/finished/biz-e-corp/src/widgets/WorkerForm.ts' lines:15-19 %}

Defining the properties in the `WorkerFormErrors` interface as optional allows us to effectively create three possible states for form fields: unvalidated, valid, and invalid.

{% instruction 'Next add a `formErrors` method to the `ApplicationContext` class' %}

As an exercise, complete the following three steps:

1. Create a private field for `_formErrors` in the ApplicationContext class
2. Define a public getter for the `_formErrors` field within the `ApplicationContext`
3. Update the `getProperties` function in the `WorkerFormContainer.ts` file to pass through the new error object

Hint: Follow the existing `_formData` private field in the `ApplicationContext` class to see how it's used. The `_formErrors` variable you need to add can follow the same flow.

Make sure the following lines are present somewhere in `ApplicationContext.ts`:
```typescript
// modify import to include WorkerFormErrors
import { WorkerFormData, WorkerFormErrors } from './widgets/WorkerForm';

// private field
private _formErrors: WorkerFormErrors = {};

// public getter
get formErrors(): WorkerFormErrors {
	return this._formErrors;
}
```

The modified `getProperties` function in `WorkerFormContainer.ts`:
```typescript
function getProperties(inject: ApplicationContext, properties: any) {
	const {
		formData,
		formErrors,
		formInput: onFormInput,
		submitForm: onFormSave
	} = inject;

	return {
		formData,
		formErrors,
		onFormInput: onFormInput.bind(inject),
		onFormSave: onFormSave.bind(inject)
	};
}
```

{% instruction 'Finally, modify `WorkerFormProperties` in `WorkerForm.ts` to accept the `formErrors` object passed in by the application context:' %}

```ts
export interface WorkerFormProperties {
	formData: WorkerFormData;
	formErrors: WorkerFormErrors;
	onFormInput: (data: Partial<WorkerFormData>) => void;
	onFormSave: () => void;
}
```

{% section %}

## Tie validation to form inputs

{% task 'Perform validation on `onInput`' %}

We now have a place to store form errors in the application state, and those errors are passed into the form widget. The form still lacks any actual validation of the user input; for that, we need to dust off our regular expressions and write a basic validation function.

{% instruction 'Create a private `_validateInput` method in `ApplicationContext.ts`' %}

Like the existing `formInput` function, `_validateInput` should take a partial `WorkerFormData` input object. The validation function should return a `WorkerFormErrors` object. The example app shows only the most basic validation checks -- the email regex pattern for example is concise but somewhat lax. You are free to substitute a more robust email test, or add other modifications like a minimum character count for the first and last names.

{% include_codefile 'demo/finished/biz-e-corp/src/ApplicationContext.ts' lines:32-50 %}

For now, we will test our validation by calling it directly in every `onInput` event. Add the following line to `formInput` in `ApplicationContext.ts`:

```ts
this._formErrors = deepAssign({}, this._formErrors, this._validateInput(input));
```

{% instruction 'Update the render method of the `WorkerForm` class to display validation state' %}

At this point in our progress, the `WorkerForm` widget holds the validation state of each form field in its `formErrors` property, updated every time an `onInput` handler is called. All that remains is to pass the valid/invalid property to the inputs themselves. Luckily the Dojo `TextInput` widget contains an `invalid` property that sets the `aria-invalid` attribute on a DOM node, and toggles classes used for visual styling.

The updated render function in `WorkerForm.ts` should set the `invalid` property on all form field widgets to reflect `formErrors`. We also add a `novalidate` attribute to the form element to prevent native browser validation.

```ts
protected render() {
	const {
		formData: { firstName, lastName, email },
		formErrors
	} = this.properties;

	return v('form', {
		classes: this.theme(css.workerForm),
		novalidate: 'true',
		onsubmit: this._onSubmit
	}, [
		v('fieldset', { classes: this.theme(css.nameField) }, [
			v('legend', { classes: this.theme(css.nameLabel) }, [ 'Name' ]),
			w(TextInput, {
				key: 'firstNameInput',
				label:'First Name',
				labelHidden: true,
				placeholder: 'Given name',
				value: firstName,
				required: true,
				invalid: this.properties.formErrors.firstName,
				onInput: this.onFirstNameInput
			}),
			w(TextInput, {
				key: 'lastNameInput',
				label: 'Last Name',
				labelHidden: true,
				placeholder: 'Surname name',
				value: lastName,
				required: true,
				invalid: this.properties.formErrors.lastName,
				onInput: this.onLastNameInput
			})
		]),
		w(TextInput, {
			label: 'Email address',
			type: 'email',
			value: email,
			required: true,
			invalid: this.properties.formErrors.email,
			onInput: this.onEmailInput
		}),
		w(Button, {}, [ 'Save' ])
	]);
}
```

Now when you view the app in the browser, the border color of each form field changes as you type. Next we'll add error messages and update `onInput` validation to only occur after the first blur event.

{% section %}

## Extending TextInput

{% task 'Create an error message' %}

Simply changing the border color of form fields to be red or green doesn't impart much information to the user -- we need to add some error message text along with invalid state. On a basic level, our error text must be associated with a form input, styleable, and accessible. A single form field with an error message might look something like this:

```ts
v('div', { classes: this.theme(css.inputWrapper) }, [
	w(TextInput, {
		...
		aria: {
			describedBy: this._errorId
		},
		onInput: this._onInput
	}),
	invalid === true ? v('span', {
		id: this._errorId,
		classes: this.theme(css.error),
		'aria-live': 'polite'
	}, [ 'Please enter valid text for this field' ]) : null
])
```

The error message is associated with the text input through `aria-describedby`, and the `aria-live` attribute ensures it will be read if it is added to the DOM or changed. Wrapping both the input and the error message in a containing `<div>` allows us to position the error message relative to the input if desired.

{% instruction 'Extend `TextInput` to create a `ValidatedTextInput` widget with an error message and `onValidate` method' %}

Re-creating the same error message boilerplate for multiple text inputs seems overly repetitive, so we're going to extend `TextInput` instead. This will also allow us to have better control over when validation occurs, e.g. by adding it to blur events as well. For now, just create a `ValidatedTextInput` widget that accepts the same properties interface as `TextInput` but with an `errorMessage` string and `onValidate` method. It should return the same node structure modeled above.

You will also need to create `validatedTextInput.m.css` with `error` and `inputWrapper` classes, although we will forgo adding specific styles in this tutorial:

```css
.inputWrapper {}

.error {}
```

```ts
import { WidgetBase } from '@dojo/framework/widget-core/WidgetBase';
import { TypedTargetEvent } from '@dojo/framework/widget-core/interfaces';
import { v, w } from '@dojo/framework/widget-core/d';
import uuid from '@dojo/framework/core/uuid';
import { ThemedMixin, theme } from '@dojo/framework/widget-core/mixins/Themed';
import TextInput, { TextInputProperties } from '@dojo/widgets/text-input';
import * as css from '../styles/validatedTextInput.m.css';

export interface ValidatedTextInputProperties extends TextInputProperties {
	errorMessage?: string;
	onValidate?: (value: string) => void;
}

export const ValidatedTextInputBase = ThemedMixin(WidgetBase);

@theme(css)
export default class ValidatedTextInput extends ValidatedTextInputBase<ValidatedTextInputProperties> {
	private _errorId = uuid();

	protected render() {
		const {
			disabled,
			label,
			maxLength,
			minLength,
			name,
			placeholder,
			readOnly,
			required,
			type = 'text',
			value,
			invalid,
			errorMessage,
			onBlur,
			onInput
		} = this.properties;

		return v('div', { classes: this.theme(css.inputWrapper) }, [
			w(TextInput, {
				aria: {
					describedBy: this._errorId
				},
				disabled,
				invalid,
				label,
				maxLength,
				minLength,
				name,
				placeholder,
				readOnly,
				required,
				type,
				value,
				onBlur,
				onInput
			}),
			invalid === true ? v('span', {
				id: this._errorId,
				classes: this.theme(css.error),
				'aria-live': 'polite'
			}, [ errorMessage ]) : null
		]);
	}
}
```

You may have noticed that we created `ValidatedTextInput` with an `onValidate` property, but we have yet to use it. This will become important in the next few steps by allowing us to have greater control over when validation occurs. For now, just treat it as a placeholder.

{% instruction 'Use `ValidatedTextInput` within `WorkerForm`' %}

Now that `ValidatedTextInput` exists, let's import it and swap it with `TextInput` in `WorkerForm`, and write some error message text while we're at it:

**Import block**
{% include_codefile 'demo/finished/biz-e-corp/src/widgets/WorkerForm.ts' lines:1-7 %}

**Inside render()**
{% include_codefile 'demo/finished/biz-e-corp/src/widgets/WorkerForm.ts' lines:72-108 %}

{% task 'Create `onFormValidate` method separate from `onFormInput`' %}

{% instruction 'Update the context to pass in an `onFormValidate` method' %}

Currently the validation logic is unceremoniously dumped in `formInput` within `ApplicationContext.ts`. Now let's break that out into its own `formValidate` function, and borrow the `onFormInput` pattern to pass `onFormValidate` to `WorkerForm`. There are three steps to this:

1. Add a `formValidate` method to `ApplicationContext.ts` and update `_formErrors` there instead of in `formInput`:
	{% include_codefile 'demo/finished/biz-e-corp/src/ApplicationContext.ts' lines:72-80 %}
2. Update `WorkerFormContainer` to pass `formValidate` as `onFormValidate`:
	{% include_codefile 'demo/finished/biz-e-corp/src/containers/WorkerFormContainer.ts' lines:6-22 %}
3. Within `WorkerForm` first add `onFormValidate` to the `WorkerFormProperties` interface:
	{% include_codefile 'demo/finished/biz-e-corp/src/widgets/WorkerForm.ts' lines:21-27 %}
	Then create internal methods for each form field's validation and pass those methods (e.g. `onFirstNameValidate`) to each `ValidatedTextInput` widget. This should follow the same pattern as `onFormInput` and `onFirstNameInput`, `onLastNameInput`, and `onEmailInput`:
	{% include_codefile 'demo/finished/biz-e-corp/src/widgets/WorkerForm.ts' lines:49-59 %}

{% instruction 'Handle calling `onValidate` within `ValidatedTextInput`' %}

You might have noticed that the form no longer validates on user input events. This is because we no longer handle validation within `formInput` in `ApplicationContext.ts`, but we also haven't added it anywhere else. To do that, add the following private method to `ValidatedTextInput`:

```ts
private _onInput(value: string) {
	const { onInput, onValidate } = this.properties;
	onInput && onInput(value);
	onValidate && onValidate(value);
}
```

Now pass it to `TextInput` in place of `this.properties.onInput`:
```ts
w(TextInput, {
	aria: {
		describedBy: this._errorId
	},
	disabled,
	invalid,
	label,
	maxLength,
	minLength,
	name,
	placeholder,
	readOnly,
	required,
	type,
	value,
	onBlur,
	onInput: this._onInput
})
```

Form errors should be back now, along with error messages for invalid fields.

{% section %}

## Making use of the blur event

{% task 'Only begin validation after the first blur event' %}

Right now the form displays validation as soon as the user begins typing in a field, which can be a poor user experience. Seeing "invalid email address" types of errors at the beginning of typing an email is both unnecessary and distracting. A better pattern would be to hold off on validation until the first blur event, and then begin updating the validation on input events.

{% aside 'Blur events' %}
The [blur](https://developer.mozilla.org/en-US/docs/Web/Events/blur) event fires when an element loses focus.
{% endaside %}

Now that calling `onValidate` is handled within the `ValidatedTextInput` widget, this is possible.

{% instruction 'Create a private `_onBlur` function that calls `onValidate`' %}

In `ValidatedTextInput.ts`:
```ts
private _onBlur(value: string) {
	const { onBlur, onValidate } = this.properties;
	onValidate && onValidate(value);
	onBlur && onBlur();
}
```

We only need to use this function on the first blur event, since subsequent validation can be handled by `onInput`. The following code will use either `this._onBlur` or `this.properties.onBlur` depending on whether the input has been previously validated:

{% include_codefile 'demo/finished/biz-e-corp/src/widgets/ValidatedTextInput.ts' lines:50-67 %}

Now all that remains is to modify `_onInput` to only call `onValidate` if the field already has a validation state:

{% include_codefile 'demo/finished/biz-e-corp/src/widgets/ValidatedTextInput.ts' lines:24-31 %}

Try inputting an email address with these changes; it should only show an error message (or green border) after leaving the form field, while subsequent edits immediately trigger changes in validation.

{% section %}

## Validating on submit

{% task 'Create mock server-side validation when the form is submitted' %}

Thus far our code provides nice hints to the user, but does nothing to prevent bad data being submitted to our worker array. We need to add two separate checks to the `submitForm` action:

1. Immediately fail to submit if the existing validation function catches any errors.
2. Perform some additional checks (in this case we'll look for email uniqueness). This is where we would insert server-side validation in a real app.

{% instruction 'Create a private `_validateOnSubmit` method in `ApplicationContext.ts`' %}

The new `_validateOnSubmit` should start by running the existing input validation against all `_formData`, and returning false if there are any errors:

```ts
private _validateOnSubmit(): boolean {
	const errors = this._validateInput(this._formData);
	this._formErrors = deepAssign({ firstName: true, lastName: true, email: true }, errors);

	if (this._formErrors.firstName || this._formErrors.lastName || this._formErrors.email) {
		console.error('Form contains errors');
		return false;
	}

	return true;
}
```

Next let's add an extra check: let's say each worker's email must be unique, so we'll test the input email value against the `_workerData` array. Realistically this check would be performed server-side for security:

{% include_codefile 'demo/finished/biz-e-corp/src/ApplicationContext.ts' lines:53-70 %}

After modifying the `submitForm` function in `ApplicationContext.ts`, only valid worker entries should successfully submit. We also need to clear `_formErrors` along with `_formData` on a successful submission:

{% include_codefile 'demo/finished/biz-e-corp/src/ApplicationContext.ts' lines:82-92 %}

{% section %}

## Summary

There is no way this tutorial could cover all possible use cases, but the basic patterns for storing, injecting, and displaying validation state provide a strong base for creating more complex form validation. Some possible next steps include:

- Configuring error messages in an object passed to `WorkerForm`
- Creating a toast to display submission-time errors
- Add multiple validation steps for a single form field

If you would like, you can open the completed demo application on [codesandbox.io](https://codesandbox.io/s/github/dojo/dojo.io/tree/master/site/source/tutorials/1015_form_validation/demo/finished/biz-e-corp) or alternatively [download](../assets/1015_form_validation-finished.zip) the project.

{% section 'last' %}

gha_language: TypeScript

gha_license_id: NOASSERTION


text:
# recAPI

Flask REST-API for storing, editing and searching recipes.

## Prerequisites

* A Unix-like environment (e.g. Linux, OS X)
* [Python 3.6](http://python.org/) or newer
* mariaDB

## Installation

* Install the requirements, e.g. with virtualenv:

  ```
  python3 -m venv venv
  source venv/bin/activate
  pip install -r requirements.txt
  ```

* Optional: create `config.py` inside the instance directory and adjust configuration.

## Running the backend

* Run in development mode (with `venv` activated):

  ```
  python run.py
  ```

# User CLI

Command line interface for administration of the user data base.

## Setup

Start serving the command-line API on a suitable port, e.g.:

```
  export FLASK_APP=recapi/user_cli.py FLASK_RUN_PORT=8083
```

## Command line options

Available commands:

* `flask add --user USER --display DISPLAY_NAME [--admin true|false]`: Creates a new user. Will prompt for password. Default value for admin is `false`

* `flask show --user USER`:  Displays user info.

* `flask showall`: Shows the entire user data base.

* `flask check --user USER`: Authenticates user `USER`. Will prompt for password.

* `flask deactivate --user USER`: Sets `USER`'s status to passive.

* `flask changepw --user USER`: Change password for `USER`.

gha_language: Python


text:
Weird Stories
=============

> A personal attempt to compiling a complete list of the stories part of the Cthulhu Mythos

I first started this list some years ago when I was editor at [Lovecraft Zero](https://web.archive.org/web/*/lovecraftzero.it). Back then, moved by curiosity and by the need of gatherer the tremendous literary opus produced by HPL, I began to spontaneously note down literary works referred to the Cthulhu Mythos or its elements.

### H.P. Lovecraft

* **Dagon** (1917)
* **Nyarlathotep** (1920)
* **The Nameless City** (1921)
* **The Outsider** (?)
* **The Festival** (1923)
* **The Call of Cthulhu** (1926)

### Clark Ashton Smith

* **The Uncharted Isle** (1930)
* **The Return of the Sorcerer** (1931)
* **The Nameless Offspring** (1932)
* **The Ghoul** (1934)
* **The Epiphany of Death** (1934)
* **The Chain of Aforgomon** (1935)
* **The Treader of the Dust** (1935)

### Robert E. Howard

* **The Lost Race** (1927)
* **The Black Stone** (1931)
* **The Thing on the Roof** (1932)
* **People of the Dark** (1932)
* **The Abbey** _with C. J. Henderson_ (1975)
* **The Fire of Asshurbanipal** (1936)
* **The Door the World** _with Joseph S. Pulver_ (1977)
* **The Hoofed Thing** (1970)
* **The House in the Oaks** _with August Derleth_ (1971)
* **The Black Bear Bites** (1974)
* **Skull-Face** (1929)
* **The House of Arabu** (1952)

## Credit

Maintained by [Alessio Schreiber](https://github.com/Aleschreiber)

## License

[![CC0](http://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg)](https://creativecommons.org/publicdomain/zero/1.0/)

repository: Aleschreiber/weird-stories

repo_name: Aleschreiber/weird-stories


text:
# Jax Loss
A jax library of common machine learning loss functions

## Installation

``pip install jax-loss``

## Loss Functions Included

- Binary Cross Entropy With Logits Loss

If you don't see the loss function you need, feel free to open an issue or open a PR!

## Loss Functions to be Implemented

- L1
- Mean Squared Error
- Cross Entropy
- Negative Log Liklihood
- KL Divergance
- Binary Cross Entropy
- Triplet Margin
- Cosine Embedding Loss
- Hinge

repository: ddehueck/jax-loss

repo_name: ddehueck/jax-loss


text:
# DSL Documentation Tool

Apipie-dsl is a DSL for documenting DSLs written in Ruby. Instead of traditional
use of `#comments`, ApipieDSL lets you describe the code, through the code.

## Getting started
#### Within Rails application
The easiest way to get ApipieDSL up and running with your app is:

```sh
  echo "gem 'apipie-dsl'" >> Gemfile
  bundle install
  rails g apipie:install
```

Now you can start documenting your DSLs (see
[DSL Reference](#DSL-Reference) for more info):

```ruby
  apipie :method, 'Method description' do
    required :string, String, 'Required string parameter'
  end
  def print(string)
   # ...
  end
```

#### Within plain Ruby application
```sh
  echo "gem 'apipie-dsl'" >> Gemfile
  # To be able to generate HTML documentation via rake command
  echo "gem 'rake'" >> Gemfile
  echo "gem 'actionview'" >> Gemfile
  bundle install
```
In case if you want to generate HTML documentation via rake command, I'd suggest
have the following in your `Rakefile`:
```ruby
require 'apipie-dsl'

# Configuration is required!
ApipieDSL.configure do |config|
  config.app_name = 'My DSL Docs'
  # Matchers are needed to load your code with documentation
  config.dsl_classes_matchers = [
    "#{File.dirname(__dir__)}/dsl_example/common_classes.rb",
    "#{File.dirname(__dir__)}/dsl_example/dsl.rb"
  ]
  # This is important for plain ruby application!
  config.rails = false
  # ... other configurations
end
spec = Gem::Specification.find_by_name('apipie-dsl')
rakefile = "#{spec.gem_dir}/lib/apipie_dsl/Rakefile"
load(rakefile)
```

# Documentation
## Contents
  - [__Configuration Reference__](#Configuration-Reference)
  - [__DSL Reference__](#DSL-Reference)

### Configuration Reference

Create a configuration file (e.g. `/config/initializers/apipie-dsl.rb` for
Rails). You can set the application name, footer text, DSL and documentation
base URL and turn off validations. You can also choose your favorite markup
language for full descriptions.

  - __app_name__ - Name of your application; used in breadcrumbs navigation.

  - __app_info__ - Application long description.

  - __copyright__ - Copyright information (shown in page footer).

  - __doc_base_url__ - Documentation frontend base url.

  - __default_version__ - Default DSL version to be used (1.0 by default).

  - __sections__ - What sections should the HTML documentation have
    ([:all] by default).

  - __validate__ - Parameters validation is turned off when set to false. When
    set to `:explicitly`, you must do the parameters validation yourself.
    When set to `:implicitly` (or just true), your classes' methods are wrapped
    with generated methods which already contain parameters validation
    (`:implicitly` by default).

  - __validate_value__ - Check the value of params against specified validators
    (true by default).

  - __dsl_classes_matchers__ - For reloading to work properly you need to
    specify where your DSL classes are. Can be an array if multiple paths are
    needed.

  - __markup__ - You can choose markup language for descriptions of your
    application, classes and methods. __RDoc__ is the default but you can
    choose from `ApipieDSL::Markup::Markdown.new` or
    `ApipieDSL::Markup::Textile.new`. In order to use Markdown you need
    `Maruku` gem and for Textile you need `RedCloth`. Add those to your
    `Gemfile` and run bundle if you want to use them. You can also add any
    other markup language processor.

  - __ignored__ - An array of class names (strings) (might include methods as
    well) to be ignored when generating the documentation (e.g.
    `%w[DSL::Output DSL::HTML#tag]`).

  - __class_full_names__ - Use class paths instead of class names as class id.
    This prevents same named classes overwriting each other (`true` by default).

  - __link_extension__ - The extension to use for DSL pages ('.html' by
    default). Link extensions in static DSL docs cannot be changed from '.html'.

  - __languages__ - List of languages the DSL documentation should be
    translated into. Empty by default.

  - __default_locale__ - Locale used for generating documentation when no
    specific locale is set. Set to 'en' by default.

  - __locale__ - Pass locale setter/getter.
  ```ruby
    config.locale = lambda { |loc| loc ? FastGettext.set_locale(loc) : FastGettext.locale }
  ```
  - __translate__ - Pass proc to translate strings using the localization
    library your project uses. For example see [Localization](#Localization).

  - __help_layout__ - Pass path to a html with custom help section if needed.

#### Example:
```ruby
ApipieDSL.configure do |config|
  config.app_name = "Test app"
  config.copyright = "© 2019 Oleh Fedorenko"
  config.doc_base_url = "/apipie-dsl"
  config.validate = false
  config.markup = ApipieDSL::Markup::Markdown.new
  config.dsl_controllers_matchers = [
    "#{File.dirname(__dir__)}/dsl_example/common.rb",
    "#{File.dirname(__dir__)}/dsl_example/dsl.rb"
  ]
  config.app_info["1.0"] = "
   This is where you can inform user about your application and DSL
   in general.
  "
  config.sections = %i[all additional]
end
```
### DSL Reference

#### Common Description

  - __short__ (also __short_description__) - Short description of the class
    (it's shown on both the list of classes, and class details).

  - __desc__ (also __description__ and __full_description__)
    Full description of the class (shown only in class details).

  - __dsl_versions__ (also __dsl_version__)
    What versions does the class define the methods (see
    [Versioning](#Versioning) for details).

  - __meta__ - Hash or array with custom metadata.

  - __deprecated__ - Boolean value indicating if the class is marked as
    deprecated (false by default).

  - __show__ - Class/method is hidden from documentation when set to false
    (true by default).

#### Class/Module Description

Describe your class via:
```ruby
  apipie :class do
    # ...
  end
```

Inheritance is supported, so you can specify common params for group of classes
in their parent class.

The following keywords are available (all are optional):
  - __name__ - Custom class name (in case if you want to explicitly save full
    class name e.g. ParentModule::Class)

  - __refs__/__referenced_on__ - Which references should the class understand
    to be linked in the documentation (e.g. if the class is mentioned as return
    value of a method, then the value will be linked with the class).

  - __sections__ - In which sections the class should be shown.

  - __property__ - Object's property (could be an `attr_reader` or public
    method with return value).

##### Example:
```ruby
  apipie :class, 'Base tag' do
    name 'Base::Tag'
    sections only: :additional
    refs 'BaseTag', 'Base::Tag', 'Tag'
    dsl_version 'development'
    meta :author => {:name => 'John', :surname => 'Doe'}
    deprecated false
    description <<-EOS
      == Long description
      Example class for dsl documentation
      ...
    EOS
  end
```

#### Method Description

Then describe methods available to your DSL:
```ruby
  apipie :method do
    # ...
  end
```
  - __param__ - Look at [Parameter description](#Parameter-description) section
    for details.

  - __returns__ - Look at [Response description](#Response-description) section
    for details.

  - __raises__ - Describe each possible error that can happen while calling this
    method.

  - __param_group__ - Extract parameters defined via `apipie :param_group do ...
    end`

  - __see__ - Provide reference to another method, this has to be a string with
    `class_name#method_name`.

##### Example:
```ruby
  apipie :method, 'Short description' do
    description 'Full method description'
    required :id, String, desc: 'ID for tag'
    optional :type, String, desc: 'Optional type', default: ''
    param :css_class, String, :desc => 'CSS class', type: :optional, default: ''
    keyword :content, Hash, :desc => 'Hash with content' do
      optional :text, String, 'Text string', default: 'Default text'
    end
    returns BaseTag
    raises ArgumentError, 'String is expected'
    raises ArgumentError, 'Hash is expected'
    meta :message => 'Some very important info'
    see 'html#tag', 'Link description'
    see :link => 'html#tags', :desc => 'Another link description'
    show false
  end
  def tag(id, type = '', css_class = '', content: { text: 'Default text' })
   #...
  end
```
#### Parameter Description

Use `param` to describe every possible parameter. You can use the Hash validator
in conjunction with a block given to the param method to describe nested
parameters.

  - __name__- The first argument is the parameter name as a symbol.

  - __validator__ - Second parameter is the parameter validator, choose one
    from section [Validators](#Validators).

  - __desc__ - Parameter description.

  - __required__ Set this true/false to make it required/optional. Default is
    true.

##### Example:
```ruby
  param :user, Hash, :desc => 'User info' do
    param :username, String, desc: 'Username for login', required: true
    param :password, String, desc: 'Password for login', required: true
    param :membership, ['standard','premium'], desc: 'User membership'
    param :admin_override, String, desc: 'Not shown in documentation', show: false
  end
  def create
    #...
  end
```
#### DRY with param_group

Often, params occur together in more methods. These params can be extracted
with `def_param_group` and `param_group` keywords.

The definition is looked up in the scope of the class. If the
group is defined in a different class, it might be referenced by
specifying the second argument.

##### Example:
```ruby
  # v1/users_class.rb
  def_param_group :address do
    param :street, String
    param :number, Integer
    param :zip, String
  end

  def_param_group :user do
    param :user, Hash do
      param :name, String, 'Name of the user'
      param_group :address
    end
  end

  apipie :method, 'Create an user' do
    param_group :user
  end
  def create(user)
    # ...
  end

  apipie :method, 'Update an user' do
    param_group :user
  end
  def update(user)
    # ...
  end

  # v2/users_class.rb
  apipie :method, 'Create an user' do
    param_group :user, V1::UsersClass
  end
  def create(user)
    # ...
  end
```
#### Return Description

TODO

##### Example:
```ruby
  # TODO
```

## Rails Integration

TODO

### Validators

TODO

### TypeValidator

Check the parameter type. Only String, Hash and Array are supported
for the sake of simplicity. Read more to find out how to add
your own validator.

```ruby
  # TODO
```

### RegexpValidator

Check parameter value against given regular expression.

```ruby
  param :regexp_param, /^[0-9]* years/, desc: 'regexp param'
```

### EnumValidator

Check if parameter value is included in the given array.

```ruby
  param :enum_param, [100, 'one', 'two', 1, 2], desc: 'enum validator'
```

### ProcValidator

If you need more complex validation and you know you won't reuse it, you
can use the Proc/lambda validator. Provide your own Proc, taking the value
of the parameter as the only argument. Return true if value passes validation
or return some text about what is wrong otherwise. Don't use the keyword *return*
if you provide an instance of Proc (with lambda it is ok), just use the last
statement return property of ruby.

```ruby
  param :proc_param, lambda { |val|
    val == 'param value' ? true : "The only good value is 'param value'."
  }, desc: 'proc validator'
```

### HashValidator

You can describe hash parameters in depth if you provide a block with a
description of nested values.

```ruby
   param :user, Hash, desc: 'User info' do
     required :username, String, desc: 'Username for login'
     required :password, String, desc: 'Password for login'
     param :membership, ['standard','premium'], desc: 'User membership'
   end
```

### NumberValidator

Check if the parameter is a positive integer number or zero.

```ruby
  required :product_id, :number, desc: 'Identifier of the product'
  required :quantity, :number, desc: 'Number of products to order'
```

### DecimalValidator

Check if the parameter is a decimal number.

```ruby
  required :latitude, :decimal, desc: 'Geographic latitude'
  required :longitude, :decimal, desc: 'Geographic longitude'
```

### ArrayValidator

Check if the parameter is an array.
```ruby
  required :array_param, Array, desc: 'array param'
```

##### Additional options

  - __of__ - Specify the type of items. If not given it accepts an array of any
    item type.

  - __in__ - Specify an array of valid item values.

##### Examples:

Assert `things` is an array of any items.

```ruby
  param :things, Array
```
Assert `hits` must be an array of integer values.

```ruby
  param :hits, Array, of: Integer
```

Assert `colors` must be an array of valid string values.

```ruby
  param :colors, Array, in: ['red', 'green', 'blue']
```

The retrieving of valid items can be deferred until needed using a lambda. It is evaluated only once
```ruby
  param :colors, Array, in: ->  { Colors.all.map(&:name) }
```

### NestedValidator

You can describe nested parameters in depth if you provide a block with a
description of nested values.

```ruby
  param :comments, Array, desc: 'User comments' do
    required :name, String, desc: 'Name of the comment'
    required :comment, String, desc: 'Full comment'
  end
```

### Adding custom validator

TODO

### Versioning

TODO

### Markup

The default markup language is
[RDoc](https://rdoc.github.io/rdoc/RDoc/Markup.html). It can be changed in
the config file (`config.markup=`) to one of these:

  - __Markdown__ - Use `Apipie::Markup::Markdown.new`. You need Maruku gem.

  - __Textile__ - Use `Apipie::Markup::Textile.new`. You need RedCloth gem.

Or provide you own object with a `to_html(text)` method. For inspiration, this
is how Textile markup usage is implemented:

```ruby
  class Textile
    def initialize
      require 'RedCloth'
    end

    def to_html(text)
      RedCloth.new(text).to_html
    end
  end
```

### Localization

TODO

### Static files

TODO

### Known issues
 - __Circular dependency detected while autoloading constant...__
   Can appear in Rails when using a non-standard class as a validator. Passing
   the validator as a string (e.g. MyClass -> 'MyClass') solves the issue.

repository: ofedoren/apipie-dsl

gha_language: Ruby

repo_name: ofedoren/apipie-dsl


text:
# NordicRF24 class reference

## Initialisation

### set_spi(IHardwareSPI *pSPI)
Takes a reference to an SPI hardware interface. SPI needs to be configured prior to setting.
Returns false if the SPI interface is invalid

### set_gpio(IHardwareGPIO *pGPIO, uint8_t ce, uint8_t irq)
Takes a reference to a GPIO hardware interface. The pin numbers for CE and IRQ also need to be specified in BCM format. This function configures the pins using the GPIO interface provided
Returns false if the GPIO interface is invalid

### reset_rf24()
Resets the RF24 hardware and resets all class attributes.
This will need to be called after providing SPI and GPIO interfaces.
Returns false if the reset failed

### auto_update(bool update)
If update is set to true then every read and write call to registers will be pulled/pushed over SPI.
If update is set to false then separate read_ and write_ calls will be needed to sync the changes to the hardware.

## Link layer functions

### write_packet(uint8_t *packet)
Writes a packet of data and pulses the CE to send the data.
This will only work if the RF24 is is transmit mode and powered up:
*power_up(true);*
*receiver(false) ;*
packet buffer must match required length of packet data as set by:
*set_transmit_width(uint8_t width);*

### get_rx_data_size(uint8_t pipe)
This is a helper function which reads the pipe data size or the dynamic data size depending on the RF24 settings.
Returns 0 if there's an error with SPI, GPIO or dynamic data size is corrupt.

### read_payload(uint8_t *buffer, uint8_t len)
Reads from the RX buffer. len and buffer must match the RX data size read using:
*get_rx_data_size(uint8_t pipe);*
Returns false if call fails

### write_payload(uint8_t *buffer, uint8_t len)
Writes a packet of data to the TX buffer. This call will not pulse CE to send data. len and buffer can be any length up to 32 bytes, but to keep things simple it's suggested that the length matches if fixed payload sizes are used:
*set_transmit_width(uint8_t width);*

## Hardware configuration functions

### Configuration register
#### read_config()
Reads the configuration settings from the RF24 hardware into the class. All values are cached in the class
Returns false if there's an error

#### write_config()
Writes all configuration settings to the RF24 hardware from the class cache.
Returns false if there's an error

#### use_interrupt_data_ready()
Returns true if the DR interrupt is in use

#### use_interrupt_data_sent()
Returns true if the DS interrupt is in use

#### use_interrupt_max_retry()
Returns true if the RT interrupt is in use

#### is_crc_enabled()
Returns true if CRC functionality is enabled

#### is_powered_up()
Returns true if the RF24 has been powered up.

#### is_receiver()
Returns true if the RF24 device is running as a receiver. Returns false if the device is a transmitter.

#### is_2_byte_crc()
Returns true if 16bit CRC is in use. Returns false if 8bit CRC is in use

#### set_use_interrupt_data_ready(bool set)
Specify if the interrupt should be set if data is ready.
Set to true to activate the interrupt, false to deactivate

#### set_use_interrupt_data_sent(bool set)
Specify if the interrupt should be set if data has been sent
Set to true to activate the interrupt, false to deactivate

#### set_use_interrupt_max_retry(bool set)
Specify if the interrupt should be set if the max retries has been exceeded
Set to true to activate the interrupt, false to deactivate

#### crc_enabled(bool set)
Enable or disable CRC

#### set_2_byte_crc(bool set)
Set CRC to 8 or 16 bit. If set is true then it will use 16 bit CRC

#### power_up(bool set)
If set is true then then it will be powered up. If false then the RF24 hardware will be set to powered down state

#### receiver(bool set)
Set to true to act as a receiver. Use false to act as a transmitter.

### Auto acknowledgement
#### read_enaa()
Pull settings from the RF24 hardware for the auto acknowledgement register. This reads the settings for all pipes. This is a required call if auto update is not enabled.
Returns false if the read fails.

#### write_enaa()
Write all pipe ack states to the RF24 hardware. This call is required if auto update is disabled.
Returns false if the write fails.

#### is_pipe_ack(uint8_t pipe)
Check if a *pipe* has auto acknowledgement enabled.
Returns true if set and false if disabled.

#### set_pipe_ack(uint8_t pipe, bool val)
Sets a pipe auto acknowledgement state.
*pipe* defines which to set and *val* specifies if auto acknowledgement is enabled.

### Enable pipes
Pipes 0 and 1 are enabled by default. To control which are enabled and disabled use these functions.
#### read_enrxaddr()
This is a manual read function to pull settings from the device.
If auto_update() is enabled then this will be called automatically.
Returns false if call fails with hardware.

#### write_enrxaddr()
This is a manual write function to push settings to the device.
If auto_update() is enabled then this will be called automatically.
Returns false if call fails with hardware.

#### is_pipe_enabled(uint8_t pipe)
*pipe* is a valid pipe number from 0 to 5.
Returns true if *pipe* is enabled, else returns false.
Invalid pipe numbers cause the function to return false.

#### enable_pipe(uint8_t pipe, bool enabled)
*pipe* is a valid pipe number from 0 to 5. Invalid pipe numbers will cause the function to do nothing.
*enabled* defines if the pipe is enabled - true or disabled - false.

### Address width management
Addresses can be 3-5 bytes long.

#### set_address_width(uint8_t width)
Define the address width to use. The affects all pipes and TX address settings
Returns false if an error occurred or the address width is invalid

#### get_address_width()
Returns the width used for the addresses. Can be 3, 4 or 5 bytes.
Returns 0 if an error has occurred.

### Retry settings
Sets delays from 250-4000 micro seconds and the number of retries attempted.

#### set_retry(uint8_t delay_multiplier, uint8_t retry_count)
Sets both parameters at once.
*delay_multiplier* sets the delay in multiples of 250, starting at 250.
*retry_count* sets the number of retries when an ack fails

#### get_retry_delay()
Returns the delay factor or -1 on error

#### get_retry_count()
Returns the retry count or -1 on error

### Channel settings
Channels are set from 2.4GHz to 2.525GHz in 1 MHz increments
Note that not all channels are allowed/valid in all countries.

#### set_channel(uint8_t channel)
Set a channel value from 0 to 124. Invalid channels will result in a failure and false returned.
If set then function returns true

#### get_channel()
Returns the channel set in the hardware. Returns 0x80 on error.

### Setup register
These set of functions update automatically if auto_update() is set to true.
They operate on the setup register held in the hardware.

#### read_setup()
This is a manual read function to pull settings from the device.
If auto_update() is enabled then this will be called automatically.
Returns false if call fails to call the hardware.

#### write_setup()
This is a manual write function to push settings to the device.
If auto_update() is enabled then this will be called automatically.
Returns false if call fails to call the hardware.

#### set_power_level(uint8_t level)
Power level can be one of 4 values:
- RF24_0DBM which is max power 0db
- RF24_NEG6DBM which is -6db power
- RF24_NEG12DBM which is -12db power
- RF24_NEG18DBM which is the lowest power at -18db

Invalid values are ignored

#### get_power_level()
Returns one of the following values
- RF24_0DBM
- RF24_NEG6DBM
- RF24_NEG12DBM
- RF24_NEG18DBM

If an error occurs then the value may be inaccurate

#### set_data_rate(uint8_t datarate)
*datarate* represents one of the following values
- RF24_250KBPS
- RF24_1MBPS
- RF24_2MBPS

Invalid values will default the rate to 1MB per sec

#### get_data_rate()
Returns the data rate set in the hardware
- RF24_250KBPS
- RF24_1MBPS
- RF24_2MBPS

If an error occurs then the value may be inaccurate

#### set_continuous_carrier_transmit(bool set)
Used for testing by setting a continuous carrier wave.
Set to true along with PLL lock enabled to test.
See Appendix C in the product specification.

#### is_continuous_carrier_transmit()
Returns true if continuous carrier wave is enabled. False if not set.


text:
---
layout: post
title: Showing Results Within Your Agency's Website
category: manual
tags: api activate-search
---

We offer an API that allows agencies to display results from our service on their website. Instead of searchers going to our hosted search results page, agencies can use the "Search Results API" to pull results from our service and display the results within their own pages. Agencies that want to maintain an exact match of their headers, footers, and other branding are encouraged to use this API.

The API exposes all relevant results “modules” in a single JSON call, including:

* Web results
* [Best Bets](/manual/best-bets.html)
* [Health topics](/manual/govbox-health.html)
* [Job openings](/manual/govbox-jobs.html)
* [Recent tweets](/manual/twitter.html)
* [Recent news](/manual/rss.html)
* [Recent videos](/manual/youtube.html)
* [Federal Register documents](/manual/govbox-federal-register.html)
* [Related searches](/manual/display-overview.html#modules)

***Note about Web Results:*** To retrieve web results through this API, you must either use our indexes (populated via the [i14y API](/developer/i14y.html) or via [RSS](/manual/rss.html)), or you must purchase an API key from Bing.

This API is available for use on official government websites only. You must be a Search.gov customer to access the instructions. [Sign in](https://search.usa.gov/sites) is required.

Instructions can be found under [Admin Center](https://search.usa.gov/sites) > YourSite > Activate Search > Search Results API Instructions. The Search Results API key can be found under [Admin Center](https://search.usa.gov/sites) > YourSite > Activate Search > API Access Key.


text:
K'Thar Techno-Magic
================

## A Minecraft mod of technological magic.

K'thar Magic was an ancient form of drawing upon the powers of the world. Casting of this magic was called shaping, and while most people were born with the seed within them, few were able to develop this into an ability they could control and use.

The magic power used to shape feats of magic is drawn from Wells of Essence. There are four wells: Mind, Celestials, World and End. Each of these have their core elements that are used while shaping.

* Well of the Mind:
  * Life <-> Death
  * Body <-> Soul
* Well of the Celestials
  * Light <-> Dark
  * Heat <-> Cold
* Well of the World
  * Water <-> Fire
  * Earth <-> Wind
* Well of the End
  * Stasis <-> Motion

Little remains of the old art, and now few are able to pull and shape essence without the aid of various objects as focus. Machine blueprints were created to ease the access to the four wells, and have become a requirement to be able to access the magic power.

## License

The MIT License (MIT)

Copyright (c) 2013 Henrik 'Tivec' Bergvin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

## Modpacks

Using this mod in a modpack is strictly forbidden without the authors permission. Seek me out on irc.esper.net, #notenoughmods or #tivec, and we can discuss permissions.

repository: techtronics/KtharTechnoMagic

repo_name: techtronics/KtharTechnoMagic


text:
Core Concepts of Spatial Information - Haskell
==============================================

Abstract: Specifications and implementation of the core concepts in Haskell.

See the [Readme](../README.md) in the parent directory for general information about the Core Concepts.

Currently, the implementation is in a proof of concept state and should not be considered stable for a production environment.

Contents
----------------------

- `Event.hs`: Specifications of events.
- `Field.hs`: Specifications of fields.
- `Location.hs`: Specifications of locations.
- `Makefile`: Common commands for unix platforms.
- `NetworkExamples.hs`: Examples for networks.
- `Network.hs`: Specifications of networks.
- `NetworkImpl.hs`: Implementations of networks.
- `Object.hs`: Specifications of objects.

How to test the code and run the examples
-----------------------------------------

### Unix/Linux platforms
To run the Unit Tests execute: `make test-all`

To run the examples execute: `make example-all`

Dependencies
----------------------
- [FGL](https://hackage.haskell.org/package/fgl) (Version: latest*)

\* Most recent stable release on package

### Unix/Linux platforms
To install the dependencies execute: `make install-dependencies`


text:
---
layout: post
title:  "An attempt to delete Facebook account"
date:   2018-04-12 00:00:00 +0530
categories: misc
comments: true
---
I have wanted to delete my facebook account for last 2-3 years. But I have been failing to do that (I will show reasons soon), and had decided to simply ignore facebook forever. I recently noticed that unless I remove my account, I will be subject to their new policies. I will _have_ to login to the account and take action on the policy updates.

The first step to delete the account is to go to https://www.facebook.com/help/delete_account

I get the following message on the page:

```
If you do not think you will use Facebook again and would like your account deleted, we can take care of this for you. Keep in mind that you will not be able to reactivate your account or retrieve any of the content or information you have added.
You're listed as the only developer for 1 Platform application. Permanently deleting your account will also delete these apps. If you don't want them to be deleted, transfer ownership of the apps before you delete your account.

If you would still like your account deleted, click "Delete My Account".
```
Notice `You're listed as the only developer for 1 Platform application`.

To confirm this application association, I checked my developer account. Here is the screenshot:

As you can see, there are _no apps shown_ at all.

When I click on "Delete My Account" on the account deletion page, I get the following error:

Since I have been getting this error for a _very_ long time, I contacted the people with whom I used to work during the time I made the app. I told them to make sure I am not associated with any of the app. They confirmed I am not a part of any app anymore. I also posted on facebook developer community a few times (2-3 times IIRC) with screenshots, but nobody replied.

I have also tried to delete the account from https://www.facebook.com/deactivate/ where I selected options like `Permanently delete all applications for which I'm the only developer`. The page shows app ID<PHONE_NUMBER>19067 as the app I'm associated with. But I get the same error upon clicking "Deactivate":

### EDIT
You might suggest I disable plugins, use Chrome etc. I have tried disabling all plugins in Firefox, tried doing it from Chrome with all plugins disabled. I believe this should not affect anything, but I still tried. To clarify again, I disabled _all_ plugins and tried to delete & deactivate the account with the same results.

Please note, that I will *ONLY* login to facebook from private mode.

There is a link to "edit" the app. The link is to https://developers.facebook.com/apps/704087509719067/ upon clicking, it redirects to https://developers.facebook.com/apps/ which again shows no apps (first screenshot's page).

Since the link redirects, there is added evidence that the app doesn't exist (or at least I do not have permission to it anymore).

And thus, this has become a frustrating thing.

If you know how to overcome this, or have advice on what should be done next, please let me know!

extension: markdown

gha_language: Mathematica


text:
---
date: "2009-12-26T01:00:00"
title: "Cutting Squares"
description: "Problem 270"
---

A square piece of paper with integer dimensions N×N is placed with a corner at the origin and two of its sides along the <var>x</var>- and <var>y</var>-axes. Then, we cut it up respecting the following rules:

We only make straight cuts between two points lying on different sides of the square, and having integer coordinates.

Two cuts cannot cross, but several cuts can meet at the same border point.

Proceed until no more legal cuts can be made.

Counting any reflections or rotations as distinct, we call C(N) the number of ways to cut an N×N square. For example, C(1) = 2 and C(2) = 30 (shown below).

What is C(30) mod 108 ?


text:
---
tile: Installing Calico in DC/OS
canonical_url: 'https://docs.projectcalico.org/v1.5/getting-started/mesos/installation/dc-os'
---

This guide provides instructions for installing Calico and its
prerequisites on a [Mesos DC/OS](https://dcos.io/) cluster.

## Prerequisites

### Mesos Master and Agents

You will need to be running a cluster with at least one Mesos master
and and at least one Mesos agent (though we recommend having two or
more agents).

You can set up a cluster fairly easily by following the [DC/OS Vagrant Install guide](https://github.com/dcos/dcos-vagrant). It is important to note that
if you install from this vagrant script, the Docker version on the machines
will be insufficient, so you will need to upgrade to Docker 1.9 or above ***before*** launching the Calico service.

We currently support DC/OS `1.7` (with Mesos `0.28.1`).
We support Centos7 and CoreOS as operating systems for use with
the Unified Containerizer and Docker Containerizer.

### Etcd
Calico requires an etcd datastore. A service discovery URL is required
to access the datastore, which can be configured in the Calico service's
Advanced Install options.

You can quickly spin up an etcd cluster using ths DCOS Universe
package as follows (Calico is configured to use the default service discovery URL in this install, so you won't need to edit this URL in the Calico config):

 - Go to the **Universe** tab in your DC/OS UI.
 - Find the **etcd** package
 - Click the **Install** button
 - (Optional) choose **Advanced Installation** from
the pop-up window.
	- In non-production environments used for testing, you might have
	  extremely limited resources available on each host (this is
      certainly the case for the DCOS vagrant install), so you may want to set all of
      the **mem** options to use 50MB or lower (this includes
      `mem` and `mem-limit`).
 - Choose **Review and Install**
 - Double-check configuration then click **Install**.

You can check the status of etcd by visiting the **Services**
tab. You can install Calico once etcd appears with a status
of **`Healthy`** (note that this could take a few minutes).

### Mesos-DNS

Calico is compatible with Mesos-DNS, but requires a minor configuration change to preferentially resolve to a container's IP address instead of resolving to its host's. Follow these steps on each master in your cluster to allow containers to be resolvable via their containerized IP:

1. Open `/opt/mesosphere/etc/mesos-dns.json` with any text editor.
2. Find the line that reads: `"IPSources": ["host", "netinfo"]`
3. Reverse the order of those two fields: `"IPSources": ["netinfo", "host"]`
4. Restart mesos-dns with: `sudo systemctl restart dcos-mesos-dns`

## Install Calico

You can easily install Calico from within the DCOS UI.

### Install Calico Package

You can now install the Calico package from the **Universe**
tab. To start the install:

 - Go to the **Universe** tab
 - Find the Calico package
 - Click the **Install** button then choose **Advanced
   Installation** in the pop-up window.

![alt tag]({{site.baseurl}}/images/mesos/dcos-calico-package-install.png)

##### At this point you have a few options:

In non-production environments used for testing, you might have
extremely limited resources available on each host (this is
certainly the case for the DCOS vagrant install), so you may want to set all of
the **mem** options to use 50MB or lower, as seen in the image below. This will
ensure that smaller tasks with low memory requirements
will be scheduled immediately. The changes include
modifying `mem-limit-framework`, `mem-limit-install`,
`mem-limit-etcd-proxy`, `mem-limit-node`, and
`mem-limit-libnetwork`.

![alt tag]({{site.baseurl}}/images/mesos/dcos-calico-config-changes.png)

You could also speed up the install by increasing
`max-concurrent-restarts`, allowing Calico to restart
the Mesos agent and Docker services on more than one
agent at a time. **NOTE: This is not generally recommended,
but it is fine if you're bringing up a new system.**

##### After configuring the options:

Click **Review and Install**, double-check your
configuration settings, then choose **Install**.

Calico will now begin installation on your cluster.

### Check Calico Status
It will take a few minutes for Calico to finish
installing on your cluster.

Calico runs the following tasks on each agent:
 - Configure an Etcd proxy
 - Install Docker multi-host networking
 - Install Mesos net-modules
 - Run the `calico-node` Docker image
 - Run the `calico-libnetwork` Docker image

You can check the status of each process on each agent
by visiting Calico's status web interface:

 - Go to the **Services** tab
 - Find Calico in the list of running services
   (note that it may take a few minutes for Calico
    to appear).
 - Once the Calico service is `Healthy`, click the
   square pop-out icon next to the service name to
   open the Calico status page in a new tab.

![alt tag]({{site.baseurl}}/images/mesos/dcos-calico-open-status.png)

You should see a page that looks like the following:

![alt tag]({{site.baseurl}}/images/mesos/dcos-calico-status.png)

The webpage may fail to load initially since the Calico
service restarts the Docker and Mesos agent services, which
will cause a restart of the Calico framework when it happens
on the same agent. This is expected and nothing to be
concerned about. Once the status page is running, you will see a
table where each row represents an agent, including statuses
for each of the Calico components installed.

## Next Steps
Once all of the Calico components are installed and
running, you can start launching tasks with your
Mesos cluster.

Get started by checking out our user guides for
the [Docker Containerizer]({{site.baseurl}}/{{page.version}}/getting-started/mesos/tutorials/docker)
or the [Unified Containerizer]({{site.baseurl}}/{{page.version}}/getting-started/mesos/tutorials/unified),
or to learn more about the differences between the
two containerizers, check out our [Mesos README]({{site.baseurl}}/{{page.version}}/getting-started/mesos/).

repository: daiyinliang/calico

repo_name: daiyinliang/calico


text:
---
home: true
heroImage: /favicon.png
heroText: Vue Accounts
tagline: Greatly simplifies building an accounts frontend with Vue
actionText: Get Started →
actionLink: /guide/
features:
- title: Incrementally adoptable
  details: Vue Accounts has a tiny, but pluggable core that you can extend to suit your systems needs.
- title: Use with any backend
  details: It takes just a few lines of code to connect to any backend like Apollo, A simple OAuth API, Meteor Accounts or a provider like Auth0.
- title: Custom onboarding
  details: All methods are available everywhere in your app. This makes it really easy to implement your own onboarding flow.
- title: Connect any state store
  details: Vue Accounts supports the most popular client stores like Vuex, Apollo Client and Redux, but its also very easy to add your own!
- title: Define Strategies
  details: Each strategy represents a set of global methods to handle authentication like login and registration. There are drop-ins available or you build your own.
- title: Drop-in Components
  details: A set of drop-in auth components is provided for some of the most popular libraries like Vuetify, Element, Buefy and Bootstrap Vue!
footer: MIT Licensed | Copyright © 2019-present Chris Visser - Cloudspider
---

repository: chris-visser/vue-accounts

repo_name: chris-visser/vue-accounts


text:
# Farm Clicker Tycoon

Manage your crop resources so you can feed your animals so you can produce products so you can make money so you can get rich all so you can have fun!

* [Play Live](https://farmclickertycoon.netlify.com/)

### Demo accounts:

__**username - password**__

farmDummy - password

farmSmartie - password

* [Server Repo](https://github.com/darrenrjones/farm-clicker-server)

## Contents

1. [Getting Started](#getting-started)
2. [Installing](#installing)
3. [Screenshots](#screenshots)
4. [Adding to the game](#adding-to-the-game)
5. [Built With](#built-with)
6. [License](#license)
7. [Acknowledgments](#acknowledgments)
8. [Author](#author)

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

## Installing

First get your server up and running by following "Installing" instructions at [Server](https://github.com/darrenrjones/farm-clicker-server)

after the server is up, and you run 'npm start' on the server side code, you should be able to log in with the default account after these client side installation instructions are followed:

clone this repo

```
git@github.com:darrenrjones/farm-clicker.git
```

```
cd farm-clicker
```

```
npm install
```

```
npm start
```

this should open default browser at localhost:3000

You can now log in or register to play.

## Screenshots

![landing playscreen](https://i.ibb.co/gmjZF4r/Landing-Fresh.png)

![playscreen crops](https://i.ibb.co/p4Py2xb/2048x1536.png)

![manager feed chain broken](https://i.ibb.co/H4wRvVj/1334x750.png)

![store fix feed](https://i.ibb.co/HHYHZhJ/fixFeed.png)

## Adding to the game

### Adding a CardContainer animal or crop

You can easily add more animals or crops if you want to swap stuff out to make this game your own.

To add a different animal or crop you can simply create a new <CardContainer /> component in one of the render files at

/src/components/playscreen

Add an animal in AnimalRender9.js or AnimalRender4.js

```
<CardContainer
  type='newAnimal'
  field='newAnimal1'
  screen='animals'
  feed='wheat corn'
  screenDisplay={props.screenDisplay}
  managerDisplay={props.managerDisplay}
/>
```

Add a crop in CropRender9.js or CropRender4.js or swap one out so you don't have to restyle the grid

```
<CardContainer
  type='newCrop'
  field='newCrop1'
  screen='crops'
  feed='null'
  screenDisplay={props.screenDisplay}
  managerDisplay={props.managerDisplay}
/>
```

Be sure to follow naming conventions as these values are used throughout the CardContainer logic and elsewhere. CardContainer.js will use the type name as the image source to generate the icons in game so find your image png file and put it in the respective images folder:

/src/images/animals

or

/src/images/crops

### Getting your new card to persist to the database

This is done in the [Server Side code](https://github.com/darrenrjones/farm-clicker-server) but I'll put the instructions here:

When a new user registers it uses the /seed/animals1.json and /seed/crops1.json files to create the crops and animals and tie them to the new user account so we need to add your new crop or animal item to the relative /seed/animals1.json or /seed/crops1.json file.

You can place your animal/crop in the json in the order you want just like you would place the CardContainer item from above in the AnimalRender9.js file in whatever order you want it to appear to the user. For this example we will add to the end of the list.

```
...
  {
    "type": "goat1",
    "count": 0,
    "price": 75,
    "feed": "wheat, corn, soy, clover",
    "user": "5b4d0890a6b4fb75280719a9",
    "manager": false
  },
  {
    "type": "fish1",
    "count": 0,
    "price": 100,
    "feed": "fishfood",
    "user": "5b4d0890a6b4fb75280719a9",
    "manager": false
  },
  //your new item below
  {
    "type": "newItem1",
    "count": 0,
    "price": 100,
    "feed": "wheat",
    "user": "5b4d0890a6b4fb75280719a9",
    "manager": false
  },
]
```

note: the "user" id is an example and is overwritten in the seed process so the "5b4d0890a6b4fb75280719a9" doesn't matter that it's fake.

A new crop does not need the feed property at all so an example of a new crop object would look like:

```
{
    "type": "newCrop1",
    "count": 0,
    "price": 15,
    "user" : "5b4d0890a6b4fb75280719a9",
    "manager": false
  },
```

note: remember to put a 1 at the end of the type as other logic in the code base counts on this naming convention as you could add a 'newCrop2' and 3 etc.

Now when a new user registers that crop/animal item will be put onto the crop/animal collection will be added to the databse referring to the userID that was just created.

note: the default accounts use these .json files for testing purposes so if you add a new crop/animal in the animals1 or crops1 file the user 'farmDummy' will be the only one to receive these items (and only after reseeding the database as described in the server readme) as the other defualt accounts use the number 2 and 3 (ex. seed/animals2.json and seed/crops2.json files). To add your new item to all default account you would also add your new item object to the animals2.json, crops2.json, animals3.json, crops3.json files respecitvely, and then reseed to reset the database.

## Built With

- [React](https://reactjs.org/)
- [Redux](https://redux.js.org/)
- [Redux Thunk](https://www.npmjs.com/package/redux-thunk)
- [React Router](https://www.npmjs.com/package/react-router)
- [Redux Form](https://www.npmjs.com/package/redux-form)
- [Jest](https://facebook.github.io/jest/)
- [Enzyme](http://airbnb.io/enzyme/)
- [jwt-decode](https://www.npmjs.com/package/jwt-decode)

## License

This project is licensed under the MIT License

## Acknowledgments

* Header logo made at : [Logomakr](https://logomakr.com/)
* All crop, animal and product icons found at: [iconarchive](http://www.iconarchive.com/)
* Card background : [pngtree](https://pngtree.com/free-grass-png?)

## Author:

* **Darren Jones**(https://github.com/darrenrjones) - [Portfolio](https://DarrenRaymondJones.com)

repository: darrenrjones/farm-clicker

repo_name: darrenrjones/farm-clicker


text:
# Games Engines 2 Lab Test 2018

## Instructions
This is a video of what your project should look like at the end of today's lab test:

[![YouTube](http://img.youtube.com/vi/bydalDzhCBY/0.jpg)](https://www.youtube.com/watch?v=bydalDzhCBY)

You will have to make a prefab for the Eagle ship and make a spawner component that instiantiates formations of Eagles

- Download [this starter Unity project](https://github.com/skooter500/GE2-Labtest1-2018/blob/master/Space1999.zip?raw=true) that has a skybox asset and a model of the Eagle transporter ship.
- Create a new, Unity project on github. Name it Space1999 and push your project to it. You can use whatever git client you are familiar with, but if you are not sure how to do this, cd to the folder you unzipped the project to and type:

    ```bash
    git init
    git remote add origin PASTE_THE_REPO_URL_FROM_YOUR_BROWSER_HERE
    git pull origin master
    git add .
    git commit -m "Initial version"
    git push --set-upstream origin master
    ```
- Create a new empty scene in your Unity project
- Set up the skybox and position the camera at (42, 8, -45), with a rotation of 83o around the Y axis. (To set the skybox, set the skybox material from Window | Lighting)
- Drag the Eagle model into the scene. Delete the camera gameObject from the model. It's called Cinema_4D_Editor in the hierarchy. Rotate it so that it points down the Z azis and parent it to an empty gameobject called eaglePrefab.
- Add a new component called Boid to the eaglePrefab. Give the Boid public fields for mass and maximumSpeed. Give these the values of 1 and 10. Later you will write behaviours and an integration method.
- Make a prefab out of the Eagle ship and remove it from the scene.
- Make an empty GameObject called eagleSpawner and give it a position of (93, 3, -5) and a Y rotation of -116o
- Add a new EagleSpawner component to the eagleSpawner gameObject. Give it the following fields:

    ```C#
    public float gap = 20;
    public float followers = 2;
    public GameObject prefab;
    ```
- Write code in the Awake method of the EagleSpawner to spawn a fleet of Eagles in a "V pattern" around the position of the eagleSpawner game object. The variable ```gap``` is used to set the gap between each of the Eagles on the X and Z axis. ```followers``` is used to set the number of eagles to spawn each side of the leader. For example a value of 2 means 2 followers each side of the leader, meaning 5 Eagles in total. Drag the Eagle prefab you made earlier to the prefab gameObject. The diagram below shows how the eagles should be spawned. This script needs to work correctly even if the eagleSpawner is rotated, which it is.

![Eagles](images/eagles.jpg)

- Dynamically assign a Seek behaviour to the leader of the fleet so that it seeks a target 1000 units in front of itself.
- Dynamically assign an Offset Pursue behaviour to the followers of the leader so that they try and stay in formation with the leader.
- You will have to code these behaviours and write an integration function for the Boid class you made earlier. You can use a rigidBody for the integration if you can get it working or use any of the other techniques you learned on the course to implement these behaviours.
- Make the camera look at the leader of the formation.

To get full marks you should use game components and draw useful gizmos

[Submit your repo link here](https://docs.google.com/forms/d/e/1FAIpQLScYLzCt6HRRMQnAAAm2On9IiWaIrWxM6bvjCbNDbbRf_GNLIQ/viewform).

## Marking scheme

| Feature | Marks |
|---------|-------|
| Setting up the scene with the skybox, camera, prefab & spawner | 10 marks |
| Writing the EagleSpawner behaviour | 30 marks |
| Implement the Leader behaviour | 20 marks |
| Implement the Follower behaviour | 30 marks |
| Camera following | 10 marks |


text:
[@bigcommerce/checkout-sdk](../README.md) › [OptionsResponse](optionsresponse.md)

# Interface: OptionsResponse

When creating your Drop-in instance, you can specify options to trigger different features or functionality.
https://docs.digitalriver.com/digital-river-api/payment-integrations-1/drop-in/drop-in-integration-guide#drop-in-options

## Hierarchy

* **OptionsResponse**

## Index

### Properties

* [button](optionsresponse.md#optional-button)
* [flow](optionsresponse.md#optional-flow)
* [paymentMethodConfiguration](optionsresponse.md#optional-paymentmethodconfiguration)
* [showComplianceSection](optionsresponse.md#optional-showcompliancesection)
* [showSavePaymentAgreement](optionsresponse.md#optional-showsavepaymentagreement)
* [showTermsOfSaleDisclosure](optionsresponse.md#optional-showtermsofsaledisclosure)
* [usage](optionsresponse.md#optional-usage)

## Properties

### `Optional` button

• **button**? : *[ButtonResponse](buttonresponse.md)*

Use this option to customize the text of the Drop-in button.

___

### `Optional` flow

• **flow**? : *undefined | string*

Use this option if you are using Drop-in within a standard checkout flow. Example Value: "checkout"

___

### `Optional` paymentMethodConfiguration

• **paymentMethodConfiguration**? : *[BaseElementOptions](baseelementoptions.md)*

Additional configuration details for drop-in.

___

### `Optional` showComplianceSection

• **showComplianceSection**? : *undefined | false | true*

Will show a localized compliance link section as part of Drop-in. This is an important piece for accessing the Digital River business model.

___

### `Optional` showSavePaymentAgreement

• **showSavePaymentAgreement**? : *undefined | false | true*

When enabled, presents the customer with an option to save their payment details for future use within Drop-in.
Enabling this feature will show the appropriate check boxes and localized disclosure statements and facilitate
any necessary Strong Customer Authentication.
If disabled, Drop-in will not present the customer with an option to save their payment details.

___

### `Optional` showTermsOfSaleDisclosure

• **showTermsOfSaleDisclosure**? : *undefined | false | true*

Use this option to show the required terms of sale disclosure. These localized terms automatically update if recurring products are purchased.

___

### `Optional` usage

• **usage**? : *undefined | string*

Use this option to specify the future use of a source.

repository: rlopz/checkout-sdk-js

repo_name: rlopz/checkout-sdk-js


text:
---
id: aws-go-s3-folder
title: Aws Go S3 Folder
desc: ''
updated:<PHONE_NUMBER>268
created:<PHONE_NUMBER>268
isDir: false
gitNotePath: '{{ noteHiearchy }}/README.md'
sources:
  - name: pulumi examples
    url: 'https://github.com/pulumi/examples'
    license: Apache License 2.0
---
[![Deploy](https://get.pulumi.com/new/button.svg)](https://app.pulumi.com/new)

# Host a Static Website on Amazon S3

A static website that uses [S3's website support](https://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html).
For a detailed walkthrough of this example, see the tutorial [Static Website on AWS S3](https://www.pulumi.com/docs/tutorials/aws/s3-website/).

## Deploying and running the program

1. Create a new stack:

   ```bash
   $ pulumi stack init website-testing
   ```

2. Set the AWS region:

   ```
   $ pulumi config set aws:region us-west-2
   ```

3. Run `pulumi up` to preview and deploy changes.

   ```bash
   $ pulumi up
   Previewing stack 'website-testing'
   Previewing changes:
   ...

   Performing changes:

   #: Resource Type        Name                              Status     Extra Inf
   1: pulumi:pulumi:Stack  website-testing  + created
   2: aws:s3:Bucket        s3-website-bucket                 + created
   3: aws:s3:BucketPolicy  bucketPolicy                      + created
   4: aws:s3:BucketObject  favicon.png                       + created
   5: aws:s3:BucketObject  index.html                        + created

   info: 5 changes performed:
       + 5 resources created
   Update duration: 8.827698762s
   ```

4.  To clean up resources, run `pulumi destroy` and answer the confirmation question at the prompt.

* * *

## Imported Assets

- [Pulumi.yaml](/assets/pulumi.yaml)
- [go.mod](/assets/go.mod)
- [go.sum](/assets/go.sum)
- [main.go](/assets/main.go)

repository: stjordanis/seeds-pulumi-examples

branch_name: refs/heads/main

repo_name: stjordanis/seeds-pulumi-examples


text:
# job_launcher

Job Launcher is a python3 script that launchs two types of threads :
The first scan a directory with filename like job:[0-9]\*:process, extract the number in the filename,ass it in a queue and delete the file.
The second retrieve a number from the previous queue, execute a batch script with the number as argument.
If the script does not return 0, it try 3 times.
## Installation

On Debian Buster :

```bash
apt install python3 python3-pip
pip3 install -r ./requirements
```

## Usage

```bash
export JOB_LAUNCHER_DIRECTORY=./tmp
chmod +x ./entrypoint
./entrypoint
```

JOB_LAUNCHER_DIRECTORY is the directory where the script looks for files.

# Tests

```bash
export JOB_LAUNCHER_DIRECTORY=./tmp
export JOB_LAUNCHER_NUMBER=10
chmod +x ./tests/create_files.sh
./tests/create_files.sh
chmod +x ./entrypoint
./entrypoint
```
JOB_LAUNCHER_NUMBER is the number of files to create.

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

## License
[MIT](https://choosealicense.com/licenses/mit/)


text:
Title: Wirefly Hive Problem
Date: 2023-02-06
Tags: puzzles

{% import 'macros.html' as macros %}

This puzzle comes from a video about Magic the Gathering that my brother sent me, which you can watch [here](https://www.youtube.com/watch?v=mKZ-ibOkRzs).

The video is more about the specific rules of Magic, but this isn't a Magic blog, so let's get to the math as soon as possible.

I'll try to summarize what's going on here, but I don't actually play Magic, so please forgive the inevitable inaccuracy here.

It's your turn, and on your side of the board, you have some infinite source of mana, a **Wirefly Hive**, and **Filigree Sages**. Meanwhile, your opponent has a **Leonin Elder**.

![Wirefly Hive](/images/wirefly/wirefly-hive.jpg){:height="350px"}

![Filigree Sages](/images/wirefly/filigree-sages.jpg){:height="350px"}

![Leonin Elder](/images/wirefly/leonin-elder.jpg){:height="350px"}

Basically, what this means is that, due to the effect of **Filigree Sages**, you can activate **Wirefly Hive** as many times as you want this turn. Each time you do so, you flip a coin.

- If it comes up heads, you get a **Wirefly** with 2 power (i.e attack strength), and your opponent gains 1 life from the effect of **Leonin Elder**.
- However, if it's tails, all your Wireflies are destroyed. Plus, your opponent keeps their increased life!

 However, the more you flip tails, the harder your task becomes, as your opponent's life steadily climbs higher.

The question is: if your opponent starts with $L$ life, what is the probability that you eventually amass enough Wireflies to win?

# Small $L$

Obviously if $L = 0$ you have already won, so let's look at $L = 1$.

 Because our Wirefly has attack 2, that's enough for us to win.

But what if we flip tails?

All zero of our Wireflies get destroyed, and our opponent remains at 1 life, so this is actually a no-op. Nothing has happened, and we are free to keep flipping until we get a heads.

In other words, the probability of winning with $L = 1$ is 100%!

How about $L = 2$?

# Recurrence Relation

Just like before, we can keep flipping tails at the start, and nothing will happen.  But now it gets harder.

- If we get another heads, we get a second Wirefly, and our opponent heals to 4 life. We can now attack with our two Wireflies for 4 damage and win.
- If we get tails, we lose our Wirefly, and have to start all over, but our opponent starts with 3 life this time.

If we let $p(L)$ be the probability of winning, when our opponent starts with $L$ life, then we have
$$p(2) = \frac{1}{2} + \frac{1}{2} p(3)$$

We can do something similar for higher $L$.  After that, if we get a streak of $L$ heads, our opponent will have $2L$ life, but we will have $L$ Wireflies total, and that is just enough to win. However, if our streak only lasts $k < L$ heads, we have to start over, with our opponent at $L+k$ life.

The probability of getting a streak of $L$ heads (remember, the first is "free"), is $1/2^{L-1}$. The probability of getting $k$ heads followed by a tail is $1/2^{k-1+1}$. Putting it all together, we get:

$$ p(L) = \frac{1}{2^L} + \sum_{k = 1}^{L} \frac{1}{2^k} p(L+k) $$

Unlike normal recurrence relations, this grows towards higher values of $L$, and we have no base case to start with (try expanding this formula for $L=1$!).

Additionally, this relation is under-determined. For example, it is satisfied by $p(L) = 1$ always, which could be the answer, but as we discover below, it is not. So we've lost some information somewhere, but I don't know what it is.

I was not able to get anywhere with this, but maybe there's some fancy generating function tricks one can do.

# Random Walk

To make some progress, let's transform the problem a bit.

If instead, we weaken our Wireflies to have only 1 attack, and change the effect on **Leonin Elder** to be "Whenever an artifact is destroyed, gain 1 life", then we get the same puzzle, but it's easier to reason about geometrically!

(If our opponent has $L$ life, we still have to flip $L$ heads in a row to get lethal damage. And when we break a streak of $k$ heads, we still have to start over with our opponent at $L+k$ life.)

Let's draw a grid, where the x-axis is "opponent's life", and the y-axis is "number of Wireflies". Each time we flip heads, we move up one step, and when we flip tails, we slide diagonally down to the x-axis. Our goal is to touch the diagonal $x=y$, at which point we have lethal damage.

  ![Grid showing the directions of the random walk](/images/wirefly/grid.svg){height="300px"}

Now our problem takes the form of a random walk!

In order to figure out the probability of touching the diagonal, let's figure out the probability of touching it at each point.

If our opponent starts with $L$ life, and we touch the diagonal at $(N, N)$, then we must have:

- Traversed some path from $(L, 0)$ to $(N, 0)$, without touching the diagonal.
- Then we flipped $N$ consecutive heads.

The probability of the latter is easy to compute; we've done it several times already: $1/2^{N-1}$. The former is trickier.

Any particular path from $(L, 0)$ to $(N, 0)$ comes from a specific sequence of heads streaks, punctuated by arbitrary runs of tails. For example, the sequence shown in the diagram above has streaks of $(1, 2, 1)$, and could have been produced by:

- **H**T**HH**T**H**T
- **H**TTTT**HH**TTTTT**H**TTTTTT
- TTTTT**H**T**HH**TT**H**T
- and so on

What's the probability of getting this particular sequence?

- We have to get a streak of one head: $1/2$
- Then a streak of two heads: $1/4$
- And lastly, a streak of one head again: $1/2$

In total, that's $1/16$.

In general, the probability of getting a streak pattern of $(k_1, k_2, \ldots, k_i)$ is $1/2^{k_1} \cdot 1/2^{k_2} \cdots 1/2^{k_i}$, or in other words, $1/2^{k_1 + k_2 + \cdots + k_i}$. And since we know we need $N - L$ heads to get from $(L, 0)$ to $(N, 0)$, that means each path has the **exact same probability**: $1/2^{N - L}$.

The only thing we're missing is the number of paths from $(L, 0)$ to $(N, 0)$. If we call that quantity $a_{L, N}$, then the probability that we win is:

$$ p(L) = \sum_{N = L}^\infty p(\textrm{walked to $(N, 0)$}) \cdot \frac{1}{2^{N-1}} = \sum_{N = L}^\infty \frac{a_{L, N}}{2^{N - L}} \cdot \frac{1}{2^{N-1}} $$

The only thing left to do is find the values of $a_{L, N}$.

# Counting Paths

Counting these paths turns out to be quite an ordeal, and I never ended up finding a closed form for them. Still though, there's a clean recurrence relation that one can use to compute these things, so let's dive in.

If we're looking for a path from $(L, 0)$ to $(N, 0)$, our last step has to be a diagonal. There's only a few possible places we can slide down the diagonal and hit $(N, 0)$.

![Diagonal arrow down to (6, 0)](/images/wirefly/diagonal-slide.svg){height="300px"}

Specifically, we can be on any point $(N - i, N + i)$, as long as $N - i < N + i$, otherwise we'd be on (or past) the diagonal, and this would not be a valid path.

The only way to get from $(L, 0)$ to $(N - i, N + i)$ is to make it to $(N - i, 0)$, and then go straight up. So each path to $(N - i, 0)$ gives us exactly one path to $(N, 0)$, meaning the number of paths is just:

$$ a_{L, N} = \sum_{i} a_{L, N - i} $$

where the sum is taken over all $i$ such that $N - i < N + i$. Also, we can skip all $i$ such that $N - i < L$, because there are no paths going backwards.

For a specific example, consider $a_{2, 6}$.

We can slide down to $(6, 0)$ from $(5, 1)$ or $(4, 2)$, but not $(3, 3)$. So we have that $a_{2, 6} = a_{2, 5} + a_{2, 4}$. The possible paths are shown below, albeit, kind of cluttered:

![All paths from (2, 0) to (6, 0)](/images/wirefly/paths-for-six.svg){height="300px"}

We see that there are 3 possible paths, two of which come from $a_{2, 5}$ (blue and purple), and one of which comes from $a_{2, 4}$ (cyan).

# Simpler Recurrence

This is a pretty simple recurrence relation, but we can actually do better!

Consider $a_{2, 7}$. From our existing knowledge, we have that $a_{2, 7} = a_{2, 6} + a_{2, 5} + a_{2, 4}$. But if we replace $a_{2, 5} + a_{2, 4}$, then we get that $a_{2, 7} = 2 a_{2, 6}$!

Similarly, $a_{2, 8} = a_{2, 7} + a_{2, 6} + a_{2, 5}$, but here we are not quite so lucky -- we do not have all the terms we need. The best we can do is $a_{2, 8} = 2 a_{2, 7} - a_{2, 4}$.

And in general, for all $n$ and $k > n$, we have:

$$ a_{n, 2k+1} = 2 a_{n, 2k} $$
$$ a_{n, 2k} = 2 a_{n, 2k-1} - a_{n, k} $$

# Conclusion?

Unfortunately, I was not able to find any closed-form solution here.

I threw the recurrence relation into Python, and got the following results:

| $L$ | $p(L)$    |
|-----|-----------|
| 0   | N/A       |
| 1   | 1         |
| 2   | 0.68332   |
| 3   | 0.36663   |
| 4   | 0.18645   |
| 5   | 0.093619  |
| 6   | 0.046859  |
| 7   | 0.023435  |
| 8   | 0.011718  |
| 9   | 0.0058593 |
| 10  | 0.0029297 |

Additionally, I found an [OEIS sequence](https://oeis.org/A002083) that counts $a_{2, n}$, and I was able to find other references to this sequence, but not the specific sum we're looking for. Wolfram Alpha doesn't produce any reasonable guesses for a closed form either. Can't win them all, I guess.


text:
# YAML Includes

Adds support for the YAML include directive as defined by the [RAML spec].

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'yaml-includes'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install yaml-includes

## Usage

Once required, simply use the YAML.load_file as normal.
Only load_file is supported because include paths may be relative, therefore we
need a file path as a starting point.

## YAML include directive

Take the external YAML file:

``` yaml
#properties.yaml

propertyA: valueA
propertyB: valueB
```

It can be included using the `!include` directive:

``` yaml
#main.yaml

name: example
properties: !include properties.yaml
```

Resulting in the structure

``` yaml
name: example
properties:
  propertyA: valueA
  propertyB: valueB
```

## How does it work?
It works by overloading the parse method to check the file for include
directives, loading any include files as strings and replacing the directive
with the included content.

## Contributing

1. [Fork it]!
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Run test with `$ rspec` or run `$ guard` for automatic testing.
4.  Push to the branch (`git push origin my-new-feature`)
6. Create a new Pull Request

[RAML Spec]:http://raml.org/spec.html
[Fork it]:https://github.com/codeindulgence/yaml-includes/fork

repository: codeindulgence/yaml-includes

repo_name: codeindulgence/yaml-includes