text:
## Example using Ory Cloud with Ory Keto self-hosted

This example shows a basic configuration of `cookie_session` authenticator for
Ory Oathkeeper and `remote_json` for authorization.

## Develop

Ory Oathkeeper Access Rules: [`access-rules.yml`](./oathkeeper/access-rules.yml)
Ory Oathkeeper Configuration: [`oathkeeper.yml`](./oathkeeper/oathkeeper.yml)

For more information, please refer to
[the Ory Oathkeeper documentation](https://www.ory.sh/docs/oathkeeper)

### Prerequisites

1. [Docker](https://docs.docker.com/get-docker/)
1. [Ory Oathkeeper](https://www.ory.sh/docs/oathkeeper/install)
1. [Ory Keto](https://www.ory.sh/docs/keto/install)

### Run locally

```bash
   git clone git@github.com:ory/examples
   cd examples/oathkeeper/11_kratos_keto
   docker-compose up --build
```

Wait for a couple of seconds and open
[http://<IP_ADDRESS>:8080/hello](http://<IP_ADDRESS>:8080/hello). You will be
redirected to the login page. After logging in, you still cannot access
[/hello](http://<IP_ADDRESS>:8080/hello). To get the required access, visit
[http://<IP_ADDRESS>:8080/grant-access](http://<IP_ADDRESS>:8080/grant-access).

## Contribute

Feel free to
[open a discussion](https://github.com/ory/examples/discussions/new) to provide
feedback or talk about ideas, or
[open an issue](https://github.com/ory/examples/issues/new) if you want to add
your example to the repository or encounter a bug. You can contribute to Ory in
many ways, see the
[Ory Contributing Guidelines](https://www.ory.sh/docs/ecosystem/contributing)
for more information.

repository: ory/examples

gha_language: Shell

repo_name: ory/examples


text:
# Pigeon
Pigeon brings your records to redcap. Pigeon will print its log to stdout by default and any errors it comes across to stderr.
It is able to take both json and csv flat records and upload them to redcap.

```
  _____ _____ _____ ______ ____  _   _
 |  __ \_   _/ ____|  ____/ __ \| \ | |
 | |__) || || |  __| |__ | |  | |  \| |
 |  ___/ | || | |_ |  __|| |  | | . ` |
 | |    _| || |__| | |___| |__| | |\  |
 |_|   |_____\_____|______\____/|_| \_|

```

# Installation and first use
Pigeon is a python3 application so make sure that you are utilizing the correct
python and pip.

Note that you need a redcap project with an API token and data to import into.

Finally you

1. `$ git clone https://github.com/ctsit/cappy.git`
2. `$ pip install ./cappy`
3. `$ git clone pigeon`
4. `$ pip install ./pigeon`
5. `$ cp pigeon/pigeon/pigeon.example.conf.yaml my_redcap_pigeon_conf.yaml`
6. `$ pigeon my_redcap_data.json my_redcap_pigeon_conf.yaml -o pigeon_output.json`

Alternatively 6 can be replaced with
`$ pigeon my_redcap_data.json REDCAPTOKEN REDCAPURL -o pigeon_output.json`

# Usage Examples
    Pigeon is used to load data into redcap. It is able to use various formats of data and
    various upload strategies, batches of varying size, and also pigeon will always upload everything it can.
    Running pigeon after installation gives help text on how to use it.

    `$ pigeon my_redcap_data.json my_redcap_pigeon_conf.yaml -o pigeon_output.json`
    `$ pigeon my_redcap_data.json REDCAPTOKEN REDCAPURL -o pigeon_output.json`

# Development setup
    ## TODO: Write Here

# Release History
    ## TODO: Write Here

# License
    ## TODO: Write Here

# Author(s)
    ## TODO: Write Here

# Issues
    ## TODO: Write Here

# Wiki
    ## TODO: Write Here

repository: PFWhite/pigeon

branch_name: refs/heads/master

extension: md

gha_language: Python

license_type: permissive

repo_name: PFWhite/pigeon


text:
  SplitterBills

**🍷 An Elixir application that provides an balanced bills splitting to avoid losing friends/relationships.**

## Features
- Command line interface (CLI)
- Generate random list of N items and M e-mails from code
- Generate random list of N items and M e-mails from files

## Requirements
- [Elixir](https://elixir-lang.org/install.html)
- [Git](https://git-scm.com)

## Installation
In the guide below I am ilustrating the step-by-step to installation the SplitterBills (_I am using Windows 10 and that's the reason I needed to call escript.exe to run the executable.This took me a long time and headache to figure out_ 🤯).
```powershell
# Clone this repository
$ git clone https://github.com/AkioCode/SplitterBills.git

# Navigate to the program's directory
$ cd path\to\SplitterBills\

# Build the app
$ mix deps

# Build the executable
$ mix escript.build

# Run the app
$ path/to/escript.exe .\commandline
        "--mode, -m (l - Load file | r - Random)",
        "--emailsFile, -e_f path/to/emailsFile",
        "--itemsFile, -i_f path/to/itemsFile",
        "--emails, -e",
        "--items, -i"
```

## How to use
```powershell
# Load random data from files, 4 e-mails and 10 items
$ path/to/escript.exe .\commandline --mode l --emailsFile data/emails.csv --itemsFile data/items.csv --emails 4 --items 10

# Load random data from code, 4 e-mails and 10 items
$ path/to/escript.exe .\commandline --mode r --emails 4 --items 10

# You can also use it with iex:
$ iex.bat -S mix
iex(1)> emailList = ["clumsy-penguin@mail.com","grumpy-seagull<EMAIL_ADDRESS>["clumsy-penguin@mail.com","grumpy-seagull<EMAIL_ADDRESS>
iex(2)> itemList = [%{features: %{price: 200, quantity: 2}, name: "rice"},%{features: %{price: 100, quantity: 2}, name: "bread"},%{features: %{price: 400, quantity: 2}, name: "cheese"},%{features: %{price: 300, quantity: 2}, name: "ram"}]
[
  %{features: %{price: 200, quantity: 2}, name: "rice"},
  %{features: %{price: 100, quantity: 2}, name: "bread"},
  %{features: %{price: 400, quantity: 2}, name: "cheese"},
  %{features: %{price: 300, quantity: 2}, name: "ram"}
]

iex(3)> Splitbills.splitBills(itemList, emailList)
Total: 2000
Remainder: 2
Split bill: 666
Result: [%{bill: "$6,66", email<EMAIL_ADDRESS>%{bill: "$6,67", email<EMAIL_ADDRESS>%{bill: "$6,67", email<EMAIL_ADDRESS>[
  %{bill: "$6,66", email<EMAIL_ADDRESS>  %{bill: "$6,67", email<EMAIL_ADDRESS>  %{bill: "$6,67", email<EMAIL_ADDRESS>]
```
## Data files format
The data files format are .csv, delimited by commas, with header, located at .\data\ directory. You need to remove the commas if the name contains it (Need to fix this 😶).
```csv
name,price,quantity
Food Colouring - Orange,310,5
Cheese - Woolwich Goat,265,6
```
## Testing
You may want to run some tests, so here we go:
```powershell
# At the .\SplitterBills\ directory, run:
$ mix test
```

## License

🏛 MIT

---

license: MIT

repository: AkioCode/SplitterBills

repo_name: AkioCode/SplitterBills


text:
---
title: Graphic (X) utilities
date: 20180108
tags: X,graphic,utilities,programs,software
---

# Graphic (X) utilities

## Image viewers

* mirage: very complete.
* feh: simple.
* pinta: it's also an editor.

[ubuntuforums](https://ubuntuforums.org/showthread.php?t=1951155)


text:
# Contributions

## Non-Government
Contributions to the baseline project from outside the US Federal Government
should be submitted as a pull request to the [upstream
project](https://github.com/simp) on GitHub.

By submitting a [Pull Request](https://help.github.com/articles/using-pull-requests/)
to this repository, you agree that you:

1. Own the contribution that you are providing or have obtained permission from
   the contribution owner

1. Allow your contribution to be licensed under the license of the target
   project

1. Allow your contribution to be freely distributed to the public

1. Allow the US Government [Unlimited Rights](#Unlimited-Rights) to your contribution

If you or your company wish your copyright in your contribution to be annotated
in the project documentation (such as this README), then your pull request
should include that annotation.

## Government
Contributions from Government agencies require verification that the government
has unlimited rights to the contribution.  An email to **TBD** is sufficient,
stating that the contribution was developed by an employee of the United States
Government in the course of his or her duties. Alternatively, if the
contribution was developed by a contractor, the email should provide the name
of the Contractor, Contract number, and an assertion that the contract included
the standard "Unlimited Rights" clause specified by [DFARS<PHONE_NUMBER>](http://www.acq.osd.mil/dpap/dars/dfars/html/current/252227.htm#252.227-7014)
"Rights in noncommercial computer software and noncommercial computer software
documentation".

Government agencies are encouraged to submit contributions as pull requests on
GitHub.  If your agency cannot use GitHub, contributions can be emailed as
patches to **TBD**.

## Unlimited Rights

As specified in [DFARS<PHONE_NUMBER>](http://www.acq.osd.mil/dpap/dars/dfars/html/current/252227.htm#252.227-7014):

> “Unlimited Rights” means rights to use, modify, reproduce, release, perform,
> display, or disclose computer software or computer software documentation in
> whole or in part, in any manner and for any purpose whatsoever, and to have
> or authorize others to do so.

repository: mcanthony/SIMP

repo_name: mcanthony/SIMP


text:
gclone
====
English [简体中文](https://github.com/tomyummmm/gclone/blob/master/README_zh.md)

A modified version of the [rclone](//github.com/rclone/rclone)
Provide dynamic replacement SA file support for google drive operation.
All other functions are the same as rclone.

This version includes PR#38 in original gclone [filepath end with slash /](https://github.com/donwa/gclone/pull/38)

```
// View version information
gclone version
```

## Instructions
### 1. service_account_file_path Configuration
Add `service_account_file_path` Configuration. For dynamic replacement service_account_file(SA file). Replaces SA file when `rateLimitExceeded` error occurs to bypass 750GB limit.

`rclone.conf` example:
```
[gc]
type = drive
scope = drive
service_account_file = /root/accounts/1.json
service_account_file_path = /root/accounts/  <------- (Important) Add this in configuration
root_folder_id = root
```
`/root/accounts/` Folder contains multiple access and edit permissions ***service account file (x.json)***.
Once set up, when `gclone` sees `rateLimitExceeded` error, it will automatically change SA file, seamlessly bypassing the limit in real-time.

### 2. Use gc-local.bat provided for ease of use and operation of gclone. (Windows only)
Read the instructions [here](https://telegra.ph/How-to-use-GC-Remote-and-Localbat-08-21) written by me.
You can find the original [repository](https://github.com/tomyummmm/gclone-batch-file) written by me.

## Features
### 1. Supports Folder ID
If the original rclone is across team disks or shared folders, multiple configuration drive letters are required for operation.

gclone supports Folder ID operations
```
gclone copy gc:{folder_id1} gc:{folder_id2}  --drive-server-side-across-configs
```
folder_id1 can be: common directory, shared directory, team drive.

```
gclone copy gc:{folder_id1} gc:{folder_id2}/media/  --drive-server-side-across-configs
```

```
gclone copy gc:{shared_folder_id} gc:{folder_id2}  --drive-server-side-across-configs
```

### 2. Direct Copy with file ID
`id` operations: common directory, shared directory, team drive.
```
gclone copy gc:{shared_file_id} gc:{folder_id2}  --drive-server-side-across-configs
```

Supports {Folder ID} proceeding filepaths
```
gclone copy gc:{shared_file_id} gc:{Team Drive ID}/media/  --drive-server-side-across-configs
```

## Code edited
### All additional code that makes gclone run is encased. Most of the code edited is in drive.go inside \backend\drive
```
//------------------------------------------------------------
// 如果存在 ServiceAccountFilePath,调用 changeSvc, 重试
// If ServiceAccountFilePath exists, call changeSvc and try again
if(f.opt.ServiceAccountFilePath != ""){
	f.waitChangeSvc.Lock()
	f.changeSvc()
	f.waitChangeSvc.Unlock()
	return true, err
}
//------------------------------------------------------------
```

repository: kokoamartin/gclone

repo_name: kokoamartin/gclone


text:
---
layout: post
title: 'Using definitions internal to json schema and external to json schema (version – draft -04)'
categories: [Programming]
tags:  [Json Schema, JSON]
comments: true
---

There could be times when you end with a generously large schema with lots of redundant properties due to certain business requirements.

Json schema comes with a good feature named as definitions. It is used to contain repeating properties in one place and then referencing these using $ref and also overriding some property if needed.

Let’s take a look at schema below:

	{
     "title": "Contact Details",
      "readOnly": false,
      "$schema": "http://json-schema.org/draft-04/hyper-schema",
      "description": "Contact Details",
        "properties":{
        "contactDetails": {
              "title": "Contact Details",
              "properties": {
                "primaryAddress": {
                  "title": "Primary Address",
                  "readOnly": false,
                  "strictProperties": true,
                  "description": "",
                  "propertyOrder": 1,
                  "type": "string",
                  "options": {
                    "hidden": false
                  }
                },
                "secondryAddress": {
                  "title": "Secondry Address",
                  "readOnly": false,
                  "strictProperties": true,
                  "description": "",
                  "propertyOrder": 2,
                  "type": "string",
                  "options": {
                    "hidden": false
                  }
                }
              },
              "type": "object"
            }
        },
        "type":"object"
    }

Primary Address and Secondy address are two simple schema properties for now but these could be big object properties which may contain phone number,email address etc details as well. For easy understading let’s go with simple schema above. One thing to notice is that both primaryAddress and secondryAddress are similar except their title and being two separate objects.
This could be reduced to below using $ref combined with definitions:

	{
     "title": "Contact Details",
      "readOnly": false,
      "$schema": "http://json-schema.org/draft-04/hyper-schema",
      "description": "Contact Details",
      "definitions":{
          "address": {
                  "title": "Address",
                  "readOnly": false,
                  "strictProperties": true,
                  "description": "",
                  "type": "string",
                  "options": {
                    "hidden": false
                  }
                }
      },
        "properties":{
        "contactDetails": {
              "title": "Contact Details",
              "properties": {
                "primaryAddress": {
                  "title": "Primary Address",
                  "$ref":"#/definitions/address",
                  "propertyOrder":1
                },
                "secondryAddress": {
                  "title": "Secondry Address",
                  "$ref":"#/definitions/address",
                  "propertyOrder":2
                }
              },
              "type": "object"
            }
        },
        "type":"object"
    }

If you notice, schema size has been reduced and this could be significantly reduce, prove very helpful and make schema highly maintainable in case where reusable properties are bigger objects containing nested group of other objects.
To put more light on what happened, let go through the schema with definitions and $ref usage:
1. Definitions refer to shared properties which could be reused throughout schema or by some external schema.
2. $ref says either reference external schema or schema itself. Hence, it acts as JSON pointer.
3. Now in $ref ‘s value # refers to current document and could be prepended with relative url or some external url to specify external json as current refernce. # alone means current document #/definitions means definitions in current document. And hence #/definitions/address means address property/object contained within definitions in current document.
For external json schema let’s use http://myjson.com and see an example below:
Here we could add our sample extenal json file which contains our reusable definitions and get the url like in image below.

![_config.yml]({{ site.baseurl }}/images/posts/sampleOfUsingExternalJsonFile.png)

You could try it right now.
I have added below schema to the server:

	{
	  "$schema": "http://json-schema.org/draft-04/schema#",
	  "type": "object",
	  "definitions": {
		  "address":{
			  "title":"Address",
			  "properties":{
				  "street_address":{
					  "type":"string"
				  },
				  "city":{
					  "type":"string"
				  },
				  "state":{
					  "type":"string"
				  }
			  },
			  "type":"object"
		  }
	  }
	}

and got https://api.myjson.com/bins/3bkzl url. Keep in mind myjson.com could at some point may not work. Hence, we could also create our own local file server for same.

In our another json schema which want to re-use extenal schema could do it like below:

	{
	  "$schema": "http://json-schema.org/draft-04/schema#",
	  "type": "object",
	  "properties": {
		"residential_address": { "$ref": "https://api.myjson.com/bins/3bkzl.json#/definitions/address" },
		"office_address": { "$ref": "https://api.myjson.com/bins/3bkzl.json#/definitions/address" }

	  },
	  "additionalProperties": false
	}

Last but not least, let’s understand the pattern which is:

>[url]#/definitions/[property]

 + url – url of external json schema
 + *#* `–` pound stands for current document which is the one if specified by url else current document in which we are writing it.
 + property – is the property from definitions in schema specified. It could be / seperated nested value e.g. in our case “https://api.myjson.com/bins/3bkzl.json#/definitions/address/city”


text:
# Acknowledgement of Receipt of Employee Handbook

I acknowledge I have received a copy of the Comake Employee Handbook, have read it, and understand its provisions.  I further understand that if I have a question, I am obligated to ask one of the founders for clarification of any provisions in the Employee Handbook.

I further understand that the statements contained in the handbook do not create any contractual or other legal obligations of employment.  I also understand that Comake may at any time modify, rescind, or revise any policy, benefit, or practice described in the handbook, except for its policy of at-will employment.

I understand and agree that my employment with Comake is at-will and can be terminated by either me or the company without cause or notice and that nothing in the handbook should be interpreted to the contrary.  This is the entire agreement between me and Comake on this subject; it supersedes any prior inconsistent representations or agreements and may only be modified in a writing signed by me and the CEO.

I acknowledge that it is my responsibility to read and become familiar with the contents of the handbook.

```

Date: ________________________

Print Name: ________________________

Signature: ________________________

```

***

## Contents of the Comake Employee Handbook
This handbook is hosted online at [github.com/comake/handbook](https://github.com/handbook), along with several other policies. The *Comake Employee Handbook* consists of only the policies listed below.

### Introduction
* [Handbook Introduction](https://github.com/comake/handbook/blob/master/Hiring%20Documents/Handbook%20Introduction.md)
* [Mission Statement](https://github.com/comake/handbook/blob/master/Mission%20Statement.md)
* [Comake Values](https://github.com/comake/handbook/blob/master/Comake%20Values.md)

### Employment Policies
* [Equal Opportunity Employment](https://github.com/comake/handbook/blob/master/Employment%20Policies/Equal%20Opportunity%20Employment.md)
* [At-Will Employment](https://github.com/comake/handbook/blob/master/Employment%20Policies/At-Will%20Employment.md)
* [Salary and Equity Compensation](https://github.com/comake/handbook/blob/master/Employment%20Policies/Salary%20and%20Equity%20Compensation.md)
* [Code of Conduct in the Community](https://github.com/comake/handbook/blob/master/Employment%20Policies/Code%20of%20Conduct%20in%20the%20Community.md)
* [Complaint Policy](https://github.com/comake/handbook/blob/master/Employment%20Policies/Complaint%20Policy.md)
* [Drug and Alcohol Policy](https://github.com/comake/handbook/blob/master/Employment%20Policies/Drug%20and%20Alcohol%20Policy.md)
* [Employee Privacy](https://github.com/comake/handbook/blob/master/Employment%20Policies/Employee%20Privacy.md)
* [Working Remotely](https://github.com/comake/handbook/blob/master/Employment%20Policies/Working%20Remotely.md)

### Benefits and Perks
* [Health Care and Disability Insurance](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Healthcare%20and%20Disability%20Insurance.md)
* [Vacation and Sick Leave](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Vacation%20and%20Sick%20Leave.md)
* [Holiday List](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Holiday%20List.md)
* [Referral Bonuses](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Referral%20Bonuses.md)
* [Continuing Education](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Continuing%20Education.md)
* [Sabbatical](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Sabbatical.md)
* [New Parent Leave](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/New%20Parent%20Leave.md)
* [Other Protected Absences](https://github.com/comake/handbook/blob/master/Benefits%20and%20Perks/Other%20Protected%20Absences.md)

repository: comake/handbook

path: /Hiring Documents/Acknowledgment of Receipt.md

filename: Acknowledgment of Receipt.md

repo_name: comake/handbook


text:
![License](https://img.shields.io/badge/license-MIT-blue)
# Note-Taker

## Description

This application helps you to keep your notes organized in one place.

## Table of Contents

* [Usage](#usage)

* [Link](#link)

* [Demo](#Demo)

* [License](#license)

* [Contributing](#contributing)

* [Questions](#questions)

## Usage

To start to organize your notes, click on the provided link to open this application. It will bring you to the homepage, where you can click on the `Get Start` button. It will bring you to your `Notes`, where you can write new notes, save them, see previous saved notes, and delete the ones that are not relevant anymore.

## Link
[Note Taker](https://organize-notes.herokuapp.com)

## Demo
![Note Taker Demo](https://github.com/Mimila-85/Note-Taker/blob/master/develop/public/assets/image/noteTaker.gif)

## License

This project is licensed under the terms of the MIT license.

## Contributing

If you would like to participate on this project please submit any bugs or feature requests to the contact listed on the `questions` section of this README.

## Questions

If you have any questions about the repo, open an issue or contact me directly at<EMAIL_ADDRESS>You can find more of my work at [Mimila-85](https://github.com/Mimila-85).


text:
## Prepare for the workshop

The following commands should run without errors:

* `git clone https://github.com/jacksingleton/injection-workshop.git`
* `cd injection-workshop`
* `mvn -DskipTests clean package`
* `java -jar target/injection-1.0-SNAPSHOT-jar-with-dependencies.jar`

## Exploit the Application

Find a way to login as the administrator named “admin” without using their password.

Hint: It will be helpful to [download](https://db.apache.org/derby/derby_downloads.html) Derby and use
the ij tool to try different sql commands against a live database.

Bonus:
Enumerate all the user passwords in the database.

## Generate IDEA Project
* ```mvn idea:idea```

## Run tests
* ```mvn test```

## Fix the failing test
* The test fails for the simplest case of sql injection
* A passing test does not imply correctness!

## Package & Test Manually
* ```mvn clean package```
* ```java -jar target/injection-1.0-SNAPSHOT-jar-with-dependencies.jar```

## Review slides (or become a facilitator!)
* The slides are html/js
* Open presentation/index.html in a web browser

## Learn more

- sql injection prevention cheat sheet:
  *https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet*
- owasp page: *https://www.owasp.org/index.php/Top_10_2013-A1-Injection*
- sqlmap: *http://sqlmap.org/*

repository: jeetsang/injection-workshop

repo_name: jeetsang/injection-workshop


text:
# Making a Tilegram

A “tilegram” is a map made of tiles
where regions are sized proportionally to a dataset.
The name is short for a tiled
[cartogram](https://en.wikipedia.org/wiki/Cartogram).
Tilegrams can represent demographic data more truthfully than conventional,
geographic maps, while still retaining a familiar appearance.

This free, open-source tool enables news designers and developers
to browse existing tilegrams or make their own for use in interactive
and print publications.

Even with computer automation, tilegrams can be time-consuming to produce,
because, to be effective, they require a human eye to verify that geographic
contours will be recognizable and meaningful to a general readership. For this
reason, you're encouraged to begin with existing tilegrams before authoring
your own.

You can read more about the project in our announcement
[blog post](http://pitchinteractive.com/latest/tilegrams-more-human-maps/).

This manual proceeds from the most basic to the most advanced usage case.

## Exporting existing tilegrams

On load, you will see a ready-made tilegram, as selected in the
**Load existing** menu. Try selecting other options to browse around.

If you are satisfied with the tilegram as it appears, go right ahead and
**Export**—as **TopoJSON** or **SVG**—using the buttons at the lower left.

Designers will be able to import the SVG into their software of choice
(e.g. Illustrator) and developers will be able to pull the TopoJSON into
web applications. In both cases, the data is identified with the US
[FIPS](https://en.wikipedia.org/wiki/Federal_Information_Processing_Standards)
code.

## Editing tilegrams

Suppose you've loaded a tilegram, but want to reshape a region. Maybe Florida
looks too heavy, or Missouri is streched too thin.

Click step **2**: **Refine your tilegram**.

### Moving tiles around

Click and drag any tile to move it around.

To move many tiles around, click and drag a
rectangular marquee around them, and then drag them around.

To move just a specific region around, double-click
any tile in it to select them all—then drag them around.

You can also hover over a region in the **State Tiles**
sidebar area to see that region's tiles highlighted on the map.

### Ensuring statistical accuracy

Under **State Tiles**, you'll see a list of each state with a number and a
hexagon.

The number indicates the _delta inaccuracy_ between the number of tiles that
region _currently_ has on the map and how many it _should_ have, based on the
dataset. If the delta is positive, that region has too many tiles on the map.
If the delta is negative, it doesn't have enough tiles on the map. If there
If there is a warning sign, then that region doesn't have enough data for even a
single tile on the map at the chosen resolution.

(_Why does this happen?_ It is computationally very difficult to produce
tilegrams which are accurate _and_ recognizable. As you begin to make
cartograms, you'll appreciate the difficult trade-offs you must make between
preserving the approximate shapes of regions and their adjacency to other
regions.)

To remove a tile from the map, click it, and hit 'Delete' on your keyboard.

To add a tile to the map, click the hexagon from the left sidebar and drag it
onto the map.

## Generating new tilegrams

If you've made it this far, you are ready to produce your own tilegram.

Select **Generate from data**. You will see the tilegram generated before your
eyes, by beginning with a conventional geographic map and then progressively
resizing its regions to conform to the selected dataset.

Under **Dataset**, you may select one of a few prepared datasets, or input
your own **Custom CSV**, by pasting in a dataset in the format specified,
using US FIPS codes.

Then you may alter the resolution in two ways. The most visually gratifying is
to click and grab the **Resolution** slider and watch as the tiles are
re-computed in realtime. The other, more statistically accurate way is to click
into the **Per tile** field and entire your desired value per tile.

For example, if you are using population to scale the regions of your tilegram,
you might enter '500,000' so that each tile corresponds to (approximately) five
hundred thousand people. Then, each region's number of tiles is rounded to the
nearest multiple of that number. So, in this same example, if you have a region
with 700,000 people, the metrics would show that you need one tile and if you
have a region with 800,000 people it would round up to two tiles.

As you adjust the **Dataset** and **Resolution**/**Per tile**, you'll notice
that the _deltas_ under **State Tiles** update dynamically. Please remember
to take note of them and ensure that they all read `0` to make responsible
tilegrams.

## Using exported tilegrams

### In D3

You can export either SVG or TopoJSON for use in [D3](https://d3js.org/).

The following examples use D3 v4 and were tested against this hosted version:

```html
<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
```

#### Rendering tilegram SVG in D3

The simplest D3 integration may just be to write the SVG to the DOM and then
add handlers for interactivity:

```javascript
var WIDTH = 800

d3.text('tiles.svg', (e, data) => {
  var div = d3.select(document.body).append('div').html(data)
  var svg = div.select('svg')
  var groups = svg.selectAll('g')

  // Scale SVG
  var importedWidth = parseInt(svg.attr('width'))
  var importedHeight = parseInt(svg.attr('height'))
  var scale = WIDTH / importedWidth
  svg
    .attr('width', importedWidth * scale)
    .attr('height', importedHeight * scale)
  groups.attr('transform', 'scale(' + scale + ')')

  // Apply handlers
  groups.on('click', (e) => {
    console.log('Clicked', d3.event.target.parentNode.id)
  })
})
```

#### Rendering tilegram TopoJSON in D3

When displaying tilegrams TopoJSON in D3, it's important not to use a geographic
projection, as the TopoJSON coordinates do not refer to latitude/longitude,
but to dimensionless Euclidean space.

It is currently also necessary to flip the map vertically. (This is
because the exported tilegram coordinates assume that the origin (`0, 0`) is in
the lower-left corner, whereas projection-less rendering will assume that it's
in the upper-left.) Note the `transform` below.

First, be sure to import `topojson` as well:

```html
<script type="text/javascript" src="http://d3js.org/topojson.v1.min.js"></script>
```

Then:

```javascript
var WIDTH = 1400
var HEIGHT = 1000

var svg = d3.select('body').append('svg')
    .attr('width', WIDTH)
    .attr('height', HEIGHT)

d3.json('tiles.topo.json', function showData(error, tilegram) {
  var tiles = topojson.feature(tilegram, tilegram.objects.tiles)

  var transform = d3.geoTransform({
    point: function(x, y) {
      this.stream.point(x, -y)
    }
  })

  var path = d3.geoPath().projection(transform)

  var g = svg.append('g')
    .attr('transform', 'translate(0,' + HEIGHT + ')')

  g.selectAll('.tiles')
    .data(tiles.features)
    .enter().append('path')
    .attr('d', path)
})
```

To draw a border around each state:

```javascript
// Build list of state codes
var stateCodes = []
tilegram.objects.tiles.geometries.forEach(function(geometry) {
  if (stateCodes.indexOf(geometry.properties.state) === -1) {
    stateCodes.push(geometry.properties.state)
  }
})

// Build merged geometry for each state
var stateBorders = stateCodes.map(function(code) {
  return topojson.merge(
    tilegram,
    tilegram.objects.tiles.geometries.filter(function(geometry) {
      return geometry.properties.state === code
    })
  )
})

// Draw path
g.selectAll('path.border')
  .data(stateBorders)
  .enter().append('path')
  .attr('d', path)
  .attr('class', 'border')
  .attr('fill', 'none')
  .attr('stroke', 'black')
  .attr('stroke-width', 4)
```

## Sharing tilegrams

If you use, enjoy, or can't stand this tool, we'd love to hear from you at
[@pitchinc](http://twitter.com/pitchinc) or
[info@pitchinteractive.com](mailto:info@pitchinteractive.com).
We hope to include more example tilegrams in the application.

Happy tilegramming!

license: ISC

repository: haroine/tilegrams

repo_name: haroine/tilegrams


text:
---
#date: "2019-02-25T00:00:00Z"
external_link: ""
image:
  caption:
  focal_point: Smart
#links:
# - icon: graduation-cap
# - url: https://www.some.ox.ac.uk/
slides:
summary:
tags:
- Public Engagement
title: Oxford Brain Bank Open Days - Student Demonstrations
url_code: ""
url_pdf: ""
url_slides: ""
url_video: ""
---
London International Youth Science Forum

The London International Youth Science Forum (LIYSF) is a two week residential student event held at Imperial College London & The Royal Geographical Society, with lecture demonstrations from leading scientists, visits to world class laboratories and universities combined with cultural interaction, with 500 students aged 16-21 years old from 70 countries.

Groups of 23 of these students (pictured) visit our Department. The latest group came from 14 countries including UAE, Australia China, India, Israel, Sweden, Taiwan and New Zealand. Our Breathe Oxford lab got them involved in some interactive activities related to their research into the brain and breathing. The students also had the chance to visit our neuropathology lab, and learned about reaction times and Parkinson’s from our NeuroMetrology Group.

repository: ConnorScott-Ox/Professional-Profile

repo_name: ConnorScott-Ox/Professional-Profile


text:
---
title: How to get the Lync client to redownload the address book
permalink: /win/lync-address-book/
categories:
  - Windows
---
**Lync 2010**

Log off of the Lync client and delete the profile from:

**%userprofile%/AppData/Local/Microsoft/Communicator**

Then run the following command into an elevated command prompt to add the registry that forces the Lync client to immediately download the address book:

**reg add HKLM/Software/Policies/MicrosoftCommunicator /v GalDownloadInitialDelay /t REG_DWORD /d 0 /f**

**Lync 2013**

Log off of the Lync client and delete the profile from:

**%userprofile%/appdata/Local/Microsoft/Office/15.0/Lync**

Then run the following command into an elevated command prompt to add the registry that forces the Lync client to immediately download the address book:

**reg add HKLMSoftwarePoliciesMicrosoftOffice15.0Lync /v GalDownloadInitialDelay /t REG_DWORD /d 0 /f**

Note: The Lync address book is saved in the following files on the local workstations:  GalContacts.db & GalContacts.db.idx.

gha_language: SCSS

gha_license_id: MIT


text:
# React Native Boilerplate

> Clean and minimalist React Native template for a quick start with TypeScript.
Forked from: https://github.com/react-native-community/react-native-template-typescript

```sh
npx react-native init MyApp --template https://github.com/codeserk/react-native-boilerplate
```

repository: codeserk/react-native-boilerplate

repo_name: codeserk/react-native-boilerplate


text:
---
layout: session
title: "A new map renderer for OSM? Rasters, vectors, language and internationalization"
code: "JGF9WA"
speaker_names_with_affiliations: ['Brandon Liu']
room: "Track 1 - Talks"
length: "20"
time: "Sunday, 16:30"
time_iso: "2021-07-11T16:30:00Z"
resources: []
recording: True
---
OSM's mission is to create a free, global dataset of geodata for diverse applications. A mainstream OSM use case is **web cartography**: the graphical display of geographic features on the standardized browser platform. Cartographers want to make beautiful, labeled, multi-resolution maps; maps need to be loaded progressively for a smooth user experience.

The web map status quo centers around two distinct approaches. One approach, used by the OSM Carto project, is server-rendered raster map tiles displayed as images in the browser. Another approach is to use a WebGL framework that consumes tiles of vector features. In the first part of this talk, I will investigate the tradeoffs inherent in these approaches with regards to **multilingual text and internationalization**, as these pose limitations for localizing OSM applications to different languages and cultures.

The second part of this talk will introduce new techniques and libraries for rendering OSM data that are a compromise between the raster and vector map ecosystems. I'll demonstrate some of these ideas in protomaps.js, a new Canvas2D and Leaflet-based open source map rendering library.

branch_name: refs/heads/main


text:
This directory contains the inputs and outputs of PLINK check-sex analysis.

#### Inputs:
  * [chrX-all-samples-merged.bim](chrX-all-samples-merged.bim) and [chrX-all-samples-merged.bed](chrX-all-samples-merged.bed):
    * These files were transformed from a VCF file that was created using
      the query included below. The primary reason for using a customized input
      file was to ensure PLINK used the same input as BigQuery. For instance,
      the multi-sample variants table used in the query only contains
      reference-matches for SNPs (i.e. indels matching the reference are not
      included). Thus, indels needed to be excluded from the provided inputs
      as well.
      Also, to obtain accurate results in PLINK, the input files must
      contain merged info about all samples for each SNP. Thus, using
      separate VCF files (each containing info for a specific individual)
      was not feasible.

  * [chrX-all-samples-merged.fam](chrX-all-samples-merged.fam):
    * This file contains pedigree information for all 17 individuals.

#### Outputs:
  * [sex-check-with-fam](sex-check-with-fam.sexcheck):
    * PLINK output when using actual pedigree info.

  * [sex-check-no-fam](sex-check-no-fam.sexcheck):
    * PLINK output when using a dummy .fam file where all individuals have
      unknown parents. This was used to obtain comparable results to
      BiqQuery since it also ignores pedigree info.

#### Query used to generate the input VCF file:
    SELECT reference_name, start, reference_bases, alternate_bases,
    GROUP_CONCAT(calls, ',') AS all_calls
    FROM (
    SELECT
      reference_name,
      start,
      reference_bases,
      alternate_bases,
      call.call_set_name + ':' + string(IFNULL(first_allele, -1)) + '/' + string(IFNULL(second_allele, -1)) as calls
    FROM (
        SELECT
          reference_name,
          start,
          reference_bases,
          GROUP_CONCAT(alternate_bases) WITHIN RECORD AS alternate_bases,
          call.call_set_name,
          NTH(1, call.genotype) WITHIN call AS first_allele,
          NTH(2, call.genotype) WITHIN call AS second_allele,
        FROM
          [google.com:biggene:platinum_genomes.expanded_variants]
        WHERE
          reference_name = 'chrX' AND
          (start NOT BETWEEN 59999 AND 2699519) AND
          (start NOT BETWEEN 154931042 AND 155260559)
          AND reference_bases IN ('A', 'C', 'T', 'G')
        HAVING
           alternate_bases IN ('A', 'C', 'T', 'G')
    ))
    GROUP BY reference_name, start, reference_bases, alternate_bases

repository: wiesnervos/codelabs

repo_name: wiesnervos/codelabs


text:
# Web Scrapping HUB

|Language|Framework|Library|
|:-:|:-:|:-:|
|![](https://i.imgur.com/QRuBmpk.png)|![](https://i.imgur.com/5rP4JC9.png)|![](https://www.crummy.com/software/BeautifulSoup/bs4/doc/_images/6.1.jpg)|
|||

Web Scrapping interface developed in Python using PyQt5 as Framework.

## ***Main Window***

![](https://i.imgur.com/jRtokkp.png)

## ***BBC News website***
![](https://i.imgur.com/0sw2S57.png)

## ***Extracting TAG and CLASS***
![](https://i.imgur.com/LWvW2oq.png)
![](https://i.imgur.com/Xm8jq2x.png)

## ***Result***
![](https://i.imgur.com/J6bv4cC.png)

---

Web Design icon icon by Icons8


text:
# PowerMeta
PowerMeta searches for publicly available files hosted on various websites for a particular domain by using specially crafted Google, and Bing searches. It then allows for the download of those files from the target domain. After retrieving the files, the metadata associated with them can be analyzed by PowerMeta. Some interesting things commonly found in metadata are usernames, domains, software titles, and computer names.

## Public File Discovery
For many organizations it's common to find publicly available files posted on their external websites. Many times these files contain sensitive information that might be of benefit to an attacker like usernames, domains, software titles or computer names. PowerMeta searches both Bing and Google for files on a particular domain using search strings like "site:targetdomain.com filetype:pdf". By default it searches for "pdf, docx, xlsx, doc, xls, pptx, and ppt".

## Metadata Extraction
PowerMeta uses Exiftool by Phil Harvey to extract metadata information from files. If you would prefer to download the binary from his site directly instead of using the one in this repo it can be found here: http://www.sno.phy.queensu.ca/~phil/exiftool/. Just make sure the exiftool executable is in the same directory as PowerMeta.ps1 when it is run. By default it just extracts the 'Author' and 'Creator' fields as these commonly have usernames saved. However all metadata for files can be extracted by passing PowerMeta the -ExtractAllToCsv flag.

## Requirements
PowerShell version 3.0 or later

## Usage
### Import the Module
```
C:\> powershell.exe -exec bypass
PS C:\> Import-Module PowerMeta.ps1
```
### Basic Search
This command will initiate Google and Bing searches for files on the 'targetdomain.com' domain ending with a file extension of pdf, docx, xlsx, doc, xls, pptx, or pptx. Once it has finished crafting this list it will prompt the user asking if they wish to download the files from the target domain. After downloading files it will prompt again for extraction of metadata from those files.
``` PowerShell
PS C:\> Invoke-PowerMeta -TargetDomain targetdomain.com
```
### Changing FileTypes and Automatic Download and Extract
This command will initiate Google and Bing searches for files on the 'targetdomain.com' domain ending with a file extension of pdf, or xml. It will then automatically download them from the target domain and extract metadata.
``` PowerShell
PS C:\> Invoke-PowerMeta -TargetDomain targetdomain.com -FileTypes "pdf, xml" -Download -Extract
```
### Downloading Files From A List
This command will initiate Google and Bing searches for files on the 'targetdomain.com' domain ending with a file extension of pdf, docx, xlsx, doc, xls, pptx, or pptx and write the links of files found to disk in a file called "target-domain-links.txt".
``` PowerShell
PS C:\> Invoke-PowerMeta -TargetDomain targetdomain.com -TargetFileList target-domain-links.txt
```
### Extract All Metadata and Limit Page Search
This command will initiate Google and Bing searches for files on the 'targetdomain.com' domain ending with a file extension of pdf, docx, xlsx, doc, xls, pptx, or pptx but only search the first two pages. All metadata (not just the default fields) will be saved in a CSV called all-target-metadata.csv.
``` PowerShell
PS C:\> Invoke-PowerMeta -TargetDomain targetdomain.com -MaxSearchPages 2 -ExtractAllToCsv all-target-metadata.csv
```
### Extract Metadata From Files In A Directory
This command will simply extract all the metadata from all the files in the folder "\2017-03-031-144953\" and save it in a CSV called all-target-metadata.csv
``` PowerShell
PS C:\> ExtractMetadata -OutputDir .\2017-03-031-144953\ -ExtractAllToCsv all-target-metadata.csv
```
## PowerMeta Options
```
TargetDomain        - The target domain to search for files.
FileTypes           - A comma seperated list of file extensions to search for. By default PowerMeta searches for "pdf, docx, xlsx, doc, xls, pptx, ppt".
OutputList          - A file to output the list of links discovered through web searching to.
OutputDir           - A directory to store all downloaded files in.
TargetFileList      - List of file links to download.
Download            - Instead of being prompted interactively pass this flag to auto-download files found.
Extract             - Instead of being prompted interactively pass this flag to extract metadata from found files pass this flag to auto-extract any metadata.
ExtractAllToCsv     - All metadata (not just the default fields) will be extracted from files to a CSV specified with this flag.
UserAgent           - Change the default User Agent used by PowerMeta.
MaxSearchPages      - The maximum number of pages to search on each search engine.
```

repository: psychsecurity/PowerMeta

repo_name: psychsecurity/PowerMeta


text:
# `dd` documentation

# Table of Contents

- [Design principles](#design-principles)
- [Create and plot a binary decision diagram](#create-and-plot-a-binary-decision-diagram)
    - [Using a `BDD` manager](#using-a-bdd-manager)
    - [Plotting](#plotting)
    - [Alternatives](#alternatives)
    - [Reminders about the implementation beneath](#reminders-about-the-implementation-beneath)
    - [Pickle](#pickle)
    - [Nodes as `Function` objects](#nodes-as-function-objects)
        - [BDD equality](#bdd-equality)
        - [Other methods](#other-methods)
- [CUDD interface: `dd.cudd`](#cudd-interface-ddcudd)
    - [Functions](#functions)
- [Lower level: `dd.bdd`](#lower-level-ddbdd)
    - [Reference counting](#reference-counting)
    - [Reordering](#reordering)
    - [Other methods](#other-methods)
- [Example: Reachability analysis](#example-reachability-analysis)
- [Syntax for quantified Boolean formulas](#syntax-for-quantified-boolean-formulas)
- [Multi-valued decision diagrams (MDD)](#multi-valued-decision-diagrams-mdd)
- [Footnotes](#footnotes)
- [Copying](#copying)

## Design principles

The interface is in Python. The representation depends on what you want and
have installed. For solving small to medium size problems, say for teaching,
or prototyping new algorithms, pure Python can be more convenient.
To work with larger problems, it works better if you install the C library
[CUDD](https://web.archive.org/web/http://vlsi.colorado.edu/~fabio/CUDD/html/index.html).
Let's call these “backends”.

The same user code can run with both the Python and C backends.
You only need to modify an `import dd.autoref as _bdd` to
`import dd.cudd as _bdd`, or import the best available interface:

```python
try:
    import dd.cudd as _bdd
except ImportError:
    import dd.autoref as _bdd
```

The following sections describe how to use the high level interface
(almost identical in `autoref` and `cudd`). The lower level interface to
the pure-Python implementation in `dd.bdd` is also described,
for those interested in more details.

## Create and plot a binary decision diagram

The starting point for using a BDD library is a *shared* reduced ordered
binary decision diagram. Implementations call this *manager*.
The adjectives mean:

- binary: each node represents a propositional formula
- ordered: variables have a fixed order that changes in a controlled way
- reduced: given variable order, equivalent propositional formulas are
  represented by a unique diagram
- shared: common subformulas are represented using common elements in memory.

The manager is a directed graph, with each node representing a formula.
Each formula can be understood as a collection of assignments to variables.
As mentioned above, the variables are ordered.
The *level* of a variable is its index in this order, starting from 0.
The *terminal* nodes correspond to `TRUE` and `FALSE`, with maximal index.

Each manager is a `BDD` class, residing in a different module:

- `dd.autoref.BDD`: high-level interface to pure Python implementation
- `dd.cudd.BDD`: same high-level interface to a C implementation
- `dd.sylvan.BDD`: interface to another C implementation (multi-core)
- `dd.bdd.BDD`: low-level interface to pure Python implementation
  (wrapped by `dd.autoref.BDD`).

The main difference between these modules is how a BDD node is represented:

- `autoref`: `autoref.Function`
- `cudd`: `cudd.Function`
- `sylvan`: `sylvan.Function`
- `bdd`: `int`

In `autoref` and `cudd`, a `Function` class represents a node.
In `bdd`, a signed integer represents a node.

All implementations use negated edges,
so logical negation takes *constant* time.

### Using a `BDD` manager

Roughly four kinds of operations suffice to perform most tasks:

- creating BDDs from formulas
- quantification (`forall`, `exist`)
- substitution (`let`)
- enumerating models that satisfy a BDD

First, instantiate a manager and declare variables

```python
from dd import autoref as _bdd

bdd = _bdd.BDD()
bdd.declare('x', 'y', 'z')
```

To create a BDD node for a propositional formula, call the parser

```python
u = bdd.add_expr('x /\ y')  # conjunction
v = bdd.add_expr('z \/ ~ y')  # disjunction and negation
w = u & ~ v
```

The formulas above are in [TLA+](https://en.wikipedia.org/wiki/TLA%2B) syntax.
If you prefer the syntax `&, |, !`, the parser recognizes those operators too.
The inverse of `BDD.add_expr` is `BDD.to_expr`:

```python
s = bdd.to_expr(u)
>>> s
'ite(x, y, False)'
```

Lets create the BDD of a more colorful Boolean formula

```python
s = '(x /\ y) <=> (~ z \/ ~ (y <=> x))'
v = bdd.add_expr(s)
```

In natural language, the expression `s` reads:
“(x and y) if and only if ( (not z) or (y xor x) )”.
The Boolean constants are `bdd.false` and `bdd.true`, and in syntax
`FALSE` and `TRUE`.

Variables can be quantified by calling the methods `exist` and `forall`

```python
u = bdd.add_expr('x /\ y')
v = bdd.exist(['x'], u)
```

or by writing quantified formulas

```python
# there exists a value of x, such that (x and y)
u = bdd.add_expr('\E x:  x /\ y')
y = bdd.add_expr('y')
assert u == y, (u, y)

# forall x, there exists y, such that (y or x)
u = bdd.add_expr('\A x:  \E y:  y \/ z')
assert u == bdd.true, u
```

`dd` supports "inline BDD references" via the `@` operator. Each BDD node `u`
has an integer representation `int(u)` and a string representation `str(u)`.
For example, if the integer representation is `5`, then the string
representation is `@5`. These enable you to mention existing BDD nodes
in formulas, without the need to expand them as formulas. For example:

```python
u = bdd.add_expr('y \/ z')
s = 'x /\ {r}'.format(u=u)
v = bdd.add_expr(s)
v_ = bdd.add_expr('x /\ (y \/ z)')
assert v == v_
```

Substitution comes in several forms:

- replace some variable names by other variable names
- replace some variable names by Boolean constants
- replace some variable names by BDD nodes, so by arbitrary formulas

All these kinds of substitution are performed via the method `let`,
which takes a `dict` that maps the variable names to replacements.
To substitute some variables for some other variables

```python
bdd.declare('x', 'p', 'y', 'q', 'z')
u = bdd.add_expr('x  \/  (y /\ z)')
# substitute variables for variables (rename)
d = dict(x='p', y='q')
v = bdd.let(d, u)
>>> v.support
{'p', 'q', 'z'}
```

The other forms are similar

```python
# substitute constants for variables (cofactor)
values = dict(x=True, y=False)
v = bdd.let(values, u)
# substitute BDDs for variables (compose)
d = dict(x=bdd.add_expr('z \/ w'))
v = bdd.let(d, u)
```

A BDD represents a formula, a syntactic object. Semantics is about how
syntax is used to describe the world. We could interpret the same formula
using different semantics and reach different conclusions.

A formula is usually understood as describing some assignments of values to
variables. Such an assignment is also called a *model*.
A model is represented as a `dict` that maps variable names to values.

```python
u = bdd.add_expr('x \/ y')
>>> bdd.pick(u)  # choose an assignment, `u.pick()` works too
{'x': False, 'y': True}
```

When working with BDDs, two issues arise:

- which variable names are present in an assignment?
- what values do the variables take?

The values are Boolean, because BDD machinery is designed to reason for
that case only, so `1 /\ 5` is a formula outside the realm of BDD reasoning.
The choice of variable names is a matter we discuss below.

Consider the example

```python
bdd.declare('x', 'y', 'z')
u = bdd.add_expr('x \/ y')
>>> u.support
{'x', 'y'}
```

This tells us that the variables `x` and `y` occur in the formula that the
BDD node `u` represents. Knowing what (Boolean) values a model assigns to
the variables `x` and `y` suffices to decide whether the model satisfies `u`.
In other words, the values of other variables, like `z`, are irrelevant to
evaluating the expression `x \/ y`.

The choice of semantics is yours. Which variables you want an assignment to
mention depends on what you are doing with the assignment in your algorithm.

```python
u = bdd.add_expr('x')
# default: variables in support(u)
models = list(bdd.pick_iter(u))
>>> models
[{'x': True}]
# variables in `care_vars`
models = list(bdd.pick_iter(u, care_vars=['x', 'y']))
>>> models
[{'x': True, 'y': False}, {'x': True, 'y': True}]
```

By default, `pick_iter` returns assignments to all variables in the support
of the BDD node `u` given as input.
In this example, the support of `u` contains one variable: `x`
(because the value of the expression `'x'` is independent of variable `y`).

We can use the argument `care_vars` to specify the variables that we want
the assignment to include. The assignments returned will include all variables
in `care_vars`, plus the variables that appear along each path traversed in
the BDD. Variables in `care_vars` that are unassigned along each path will
be exhaustively enumerated (i.e., all combinations of `True` and `False`).

For example, if `care_vars == []`, then the assignments will contain only
those variables that appear along the recursive traversal of the BDD.
If `care_vars == support(u)`, then the result equals the default result.
For `care_vars > support(u)` we will see more variables in each assignment
than the variables in the support.

We can also count how many assignments satisfy a BDD. The number depends on
how many variables occur in an assignment. The default number is as many
variables are contained in the support of that node. You can pass a larger
number

```python
bdd.declare('x', 'y')
u = bdd.add_expr('x')
>>> u.count()
1
models = list(bdd.pick_iter(u))
>>> models
[{'x': True}]
# pass a larger number of variables
>>> u.count(nvars=3)
4
models = list(bdd.pick_iter(u, ['x', 'y', 'z']))
>>> models
[{'x': True, 'y': False, 'z': False},
 {'x': True, 'y': True, 'z': False},
 {'x': True, 'y': False, 'z': True},
 {'x': True, 'y': True, 'z': True}]
```

A convenience method for creating a BDD from an assignment `dict` is

```python
d = dict(x=True, y=False, z=True)
u = bdd.cube(d)
v = bdd.add_expr('x /\ ~ y /\ z')
assert u == v, (u, v)
```

The interface is specified in the module `dd._abc`. Although internal,
you may want to take a look at the `_abc` module.

Above we discussed semantics from a [proof-theoretic viewpoint](
    https://en.wikipedia.org/wiki/Metamathematics).
The same discussion can be rephrased in terms of function domains containing
assignments to variables, so a [model-theoretic viewpoint](
    https://en.wikipedia.org/wiki/Model_theory).

### Plotting

You can dump a PDF of all nodes in the manager as follows

```python
from dd import autoref as _bdd

bdd = _bdd.BDD()
bdd.declare('x', 'y', 'z')
u = bdd.add_expr('(x /\ y) \/ ~ z')
bdd.collect_garbage()  # optional
bdd.dump('awesome.pdf')
```

The result is shown below, with the meaning:

- integers on the left signify levels (thus variables)
- each node is annotated with a variable name (like `x`) dash the
  node index in `dd.bdd.BDD._succ` (mainly for debugging purposes)
- solid arcs represent the “if” branches
- dashed arcs the “else” branches
- only an “else” branch can be negated, signified by a `-1` annotation

Negated edges mean that logical negation, i.e., `~`, is applied to the node
that is pointed to.
Negated edges and BDD theory won't be discussed here, please refer to
a reference from those listed in the docstring of the module `dd.bdd`.
For example, [this document](
    http://www.ecs.umass.edu/ece/labs/vlsicad/ece667/reading/somenzi99bdd.pdf)
by Fabio Somenzi (CUDD's author).

In the following diagram, the BDD rooted at node `x-7` represents the
Boolean function `(x /\ y) \/ ~ z`. For example, for the assignment
`dict(x=False)`, the dashed arc from node `x-7` leads to the negation
(due to the negated edge, signified by a `-1`) of the node `z-5`.
The BDD rooted at `z-5` represents the Boolean function `z`,
so its negation is `~ z`.

The nodes `x-2`, `x-4`, `y-3` are intermediate results that result while
constructing the BDD for the Boolean function `(x /\ y) \/ ~ z`.
The BDD rooted at node `x-2` represents the Boolean function `x`, and the
BDD rooted at node `x-4` represents the Boolean function `x /\ y`.

![example_bdd](https://rawgithub.com/johnyf/binaries/master/dd/awesome.png)

An external reference to a BDD is an arc that points to a node.
For example, `u` above is an external reference. An external reference can be
a complemented arc. External references can be included in a BDD diagram by
using the argument `roots` of the method `BDD.dump`. For example

```python
from dd import autoref as _bdd

bdd = _bdd.BDD()
bdd.declare('x', 'y', 'z')
u = bdd.add_expr('(x /\ y) \/ ~ z')
print(u.negated)
v = ~ u
print(v.negated)
bdd.collect_garbage()
bdd.dump('rooted.pdf', roots=[v])
```

The result is the following diagram, where the node `@-7` is the external
reference `v`, which is a complemented arc.

![example_bdd](https://rawgithub.com/johnyf/binaries/master/dd/rooted.png)

It is instructive to dump the `bdd` with and without collecting garbage.

### Alternatives

As mentioned above, there are various ways to apply propositional operators

```python
x = bdd.var('x')
y = bdd.var('y')
u = x & y
u = bdd.apply('and', x, y)
u = bdd.apply('/\\', x, y)  # TLA+ syntax
u = bdd.apply('&', x, y)  # Promela syntax
```

Infix Python operators work for BDD nodes in `dd.autoref` and `dd.cudd`,
not in `dd.bdd`, because nodes there are plain integers (`int`).
Besides the method `apply`, there is also the ternary conditional method `ite`,
but that is more commonly used internally.

For single variables, the following are equivalent

```python
u = bdd.add_expr('x')
u = bdd.var('x')  # faster
```

In `autoref`, a few functions (not methods) are available for efficient
operations that arise naturally in fixpoint algorithms when transition
relations are involved:

- `image`, `preimage`: rename some variables, conjoin, existentially quantify,
  and rename some variables, all at once
- `copy_vars`: copy the variables of one BDD manager to another manager

### Reminders about the implementation beneath

The Python syntax for Boolean operations (`u & v`) and the method `apply`
are faster than the method `add_expr`, because the latter invokes the
parser (generated using [`ply.yacc`](https://github.com/dabeaz/ply)).
Using `add_expr` is generally quicker and more readable.
In practice, prototype new algorithms using `add_expr`,
then profile, and if it matters convert the code to use `~`, `&`, `|`,
and to call directly `apply`, `exist`, `let`, and other methods.

In the future, a compiler may be added, to compile expressions into
functions that can be called multiple times, without invoking again the parser.

The number of nodes in the manager `bdd` is `len(bdd)`.
As noted earlier, each variable corresponds to a level, which is an index in
the variable order. This mapping can be obtained with

```python
level = bdd.level_of_var('x')
var = bdd.var_at_level(level)
assert var == 'x', var
```

In `autoref.BDD`, the `dict` that maps each defined variable to its
corresponding level can be obtained also from the attribute `BDD.vars`

```python
>>> bdd.vars
{'x': 0, 'y': 1, 'z': 2}
```

To copy a node from one BDD manager to another manager

```python
a = _bdd.BDD()
a.declare('x', 'y', 'z')
u = a.add_expr('(x /\ y) \/ z')
# copy to another BDD manager
b = _bdd.BDD()
b.declare(*a.vars)
v = a.copy(u, b)
```

### Pickle

The `dd.autoref` and `dd.bdd` modules can dump the manager to a
[pickle file](https://en.wikipedia.org/wiki/Pickle_%28Python%29) and
load it back

```python
bdd.dump('manager.p')
```

and later, or in another run:

```python
bdd = BDD.load('manager.p')
```

### Nodes as `Function` objects

As mentioned earlier, the main difference between the main `dd` modules is
what type of object the user sees as a “node”:

- `dd.bdd` gives to the user signed integers as nodes
- `dd.autoref` and `dd.cudd` give her `Function` objects as nodes.

Seldom should this make a difference to the user.
However, for integers, the meaning of the Python operators `~`, `&`, `|`, `^`
is *unrelated* to the BDD manager.
So, if `u = -3` and `v = 25` are nodes in the `dd.bdd.BDD` manager `bdd`,
you cannot write `w = u & v` to get the correct result.
You have to use either:

- `BDD.apply('and', u, v)` or
- `BDD.add_expr('{u} /\ {v}'.format(u=u, v=v))`.

Unlike `dd.bdd`, the nodes in `autoref` and `cudd` are of class `Function`.
This abstracts away the underlying node representation, so that you can run
the same code in both pure Python (with `dd.bdd.BDD` underneath as manager),
as well as C (with the `struct` named [`DdManager`](
    https://github.com/johnyf/cudd/blob/80c9396b7efcb24c33868aeffb89a557af0dc356/cudd/cudd/cudd.h#L281)
in `cudd.h` underneath as manager).

The [magic methods](https://github.com/RafeKettler/magicmethods) for
`~`, `&`, `|`, `^` implemented by `Function` are its most frequently used aspect.
Two methods called `implies` and `equiv` are available.
But it is more readable to use `bdd.apply` or `bdd.add_expr`,
or just `v | ~ u` for `u.implies(v)` and `~ (u ^ v)` for `u.equiv(v)`.

#### BDD equality

If `u` and `v` are instances of `Function`, and `u == v`, then `u` represents
the same BDD as `v`.

This is **NOT** true for nodes in `dd.bdd`, because `u` and `v` may be nodes
from *different* manager instances.
So, that `u == -3 == v` does not suffice to deduce that `u` and `v`
represent the same BDD. In this case, we have to ensure that `u` and `v`
originate from the same manager. Thus, using `dd.bdd` offers less protection
against subtle errors that will go undetected.

#### Other methods

Information about a node `u` can be read with a few attributes and magic:

- `len(u)` is the number of nodes in the graph that represents `u` in memory
- `u.var` is the name (`str`) of the variable in `BDD.support(u)` with
  minimal level (recall that variables are ordered)
- `u.level` is the level of `u.var`
- `u.ref` is the reference count of `u`, meaning the number of other nodes
  `v` with an edge `(v, u)`, plus external references to `u` by the user.

We say that the node `u` is “labeled” with variable `u.var`.
At this point, recall that these diagrams track *decisions*.
At each node, we decide where to go next, depending on the value of `u.var`.
If `u.var` is true, then we go to node `u.high`, else to node `u.low`.
For this reason, `u.high` is also called the “then” child of `u`,
and `u.low` the “else” child.

This object-oriented appearance is only an external interface for the user's
convenience. Typically, the bulk of the nodes aren't referenced externally.
Internally, the nodes are managed efficiently en masse, no `Function`s there.
A `Function.to_expr` method is present, but using `BDD.to_expr` looks tidier.

## CUDD interface: `dd.cudd`

We said earlier that you can develop with `autoref`, deferring usage of
`CUDD` for when really needed. This raises two questions:

1. Why not use `cudd` from the start ?
2. When should you switch from `autoref` to `cudd` ?

The answer to the second question is simple: when your problem takes more
time and memory than available.
For light to moderate use, `cudd` probably won't be needed.

Regarding the first question, `dd.cudd` requires to:

- *compile* CUDD, and
- *cythonize, compile, and link* `dd/cudd.pyx`.

The `setup.py` of `dd` can do these for you, as described in the file
[`README.md`](
    https://github.com/tulip-control/dd/blob/master/README.md#cython-bindings).
However, this may require more attention than appropriate for the occassion.
An example is teaching BDDs in a class on data structures, with the objective
for students to play with BDDs, not with [`gcc`](
    https://en.wikipedia.org/wiki/GNU_Compiler_Collection)
and [linking](
    https://en.wikipedia.org/wiki/Linker_%28computing%29)
errors (that's enlightening too, but in the realm of a slightly different class).

If you are interested in tuning CUDD to get most out of it (or because some
problem demands it due to its size), then use:

- `BDD.statistics` to obtain the information described in
  [CUDD Programmer's manual / Gathering and interpreting statistics](
      http://www.cs.rice.edu/~lm30/RSynth/CUDD/cudd/doc/node4.html#SECTION00048000000000000000).
- `BDD.configure` to read and set the parameters “max memory”, “loose up to”,
  “max cache hard”, “min hit”, and “max growth”.

Due to how CUDD manages variables, the method `add_var` takes as keyword
argument the variable index, *not* the level (which `autoref` does).
The level can still be set with the method `insert_var`.

The methods `dump` and `load` store the BDD of a selected node in a DDDMP file.
Pickling and PDF plotting are not available yet in `dd.cudd`.

An interface to the BuDDy C libary also exists, as `dd.buddy`.
However, experimentation suggests that BuDDy does not contain as successful
heuristics for deciding *when* to invoke reordering.

CUDD is initialized with a `memory_estimate` of 1 GB. If the machine has les
RAM, then `cudd.BDD` will raise an error. In this case, pass a smaller initial
memory estimate, for example `cudd.BDD(memory_estimate=0.5 * 2**30)`.

### Functions

The functions `and_exists`, `or_forall` in `dd.cudd` offer the functionality of
relational products (meaning neighboring variable substitution, conjunction,
and quantification, all at one pass over BDDs).
This functionality is implemented with `image`, `preimage` in `dd.autoref`.
Note that (pre)image contains substitution, unlike `and_exists`.

The function `cudd.reorder` is similar to `autoref.reorder`,
but does not default to invoking automated reordering.
Typical use of CUDD enables dynamic reordering.

## Lower level: `dd.bdd`

We discuss now some more details about the pure Python implementation
in `dd.bdd`. Two interfaces are available:

- convenience: the module
  [`dd.autoref`](https://github.com/tulip-control/dd/blob/master/dd/autoref.py) wraps
  `dd.bdd` and takes care of reference counting
  using [`__del__`](https://docs.python.org/3/reference/datamodel.html#object.__del__).

- "low level": the module
  [`dd.bdd`](https://github.com/tulip-control/dd/blob/master/dd/bdd.py) requires that
  the user in/decrement the reference counters associated with nodes that
  are used outside of a `BDD`.

The pure-Python module `dd.bdd` can be used directly,
which allows access more extensive than `dd.autoref`.
The `n` variables in a `dd.bdd.BDD` are ordered
from `0` (top level) to `n - 1` (bottom level).
The terminal node `1` is at level `n`.
The constant `TRUE` is represented by `+1`, and `FALSE` by `-1`.

To avoid running out of memory, a BDD manager deletes nodes when they are not
used anymore. This is called [garbage collection](
    https://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29).
So, two things need to happen:

1. keep track of node “usage”
2. invoke garbage collection

Garbage collection is triggered either explicitly by the user, or
when invoking the reordering algorithm.
To prevent nodes from being garbage collected, their reference counts should
be incremented, which is discussed in the next section.

Node usage is tracked with reference counting, for each node.
In `autoref`, the reference counts are maintained by the constructor and
destructor methods of `Function` (hence the “auto”).
These methods are invoked when the `Function` object is not referenced any
more by variables, so [Python decides](
    https://docs.python.org/3/glossary.html#term-garbage-collection)
to delete it.

In `dd.bdd`, you have to perform the reference counting by suitably adding to
and subtracting from the counter associated to the node you reference.
Also, garbage collection is invoked either explicitly or by reordering
(explicit or dynamic). So if you don't need to collect garbage, then you
can skip the reference counting (not recommended).

### Reference counting

The reference counters live inside [`dd.bdd.BDD._ref`](
    https://github.com/tulip-control/dd/blob/cbbc96f93da68d3d10f161ef27ccc5e3756c5ae2/dd/bdd.py#L81).
To guard against corner cases, like attempting to decrement a zero counter, use

- [`BDD.incref(u)`](
    https://github.com/tulip-control/dd/blob/cbbc96f93da68d3d10f161ef27ccc5e3756c5ae2/dd/bdd.py#L126):
  +1 to the counter of node `u`
- [`BDD.decref(u)`](
    https://github.com/tulip-control/dd/blob/cbbc96f93da68d3d10f161ef27ccc5e3756c5ae2/dd/bdd.py#L130):
  -1 to the same counter.

The method names `incref` and `decref` originate from the
[Python reference counting](https://docs.python.org/3/c-api/refcounting.html)
implementation. If we want node `u` to persist after garbage collection,
then it needs to be actively referenced at least once

```python
u = bdd.add_expr(s)
bdd.incref(u)
```

Revisiting an earlier example, manual reference counting looks like:

```python
from dd import bdd as _bdd

bdd = _bdd.BDD()
bdd.declare('x', 'y', 'z')
s = '(x /\ y) \/ ~ z'  # TLA+ syntax
s = '(x & y) | ! z'  # Promela syntax
u = bdd.add_expr(s)
bdd.incref(u)
bdd.dump('before_collections.pdf')
bdd.collect_garbage()
bdd.dump('middle.pdf')
bdd.decref(u)
bdd.collect_garbage()
bdd.dump('after_collections.pdf')
```

A formula may depend on a variable, or not.
There are two ways to find out

```python
u = bdd.add_expr('x /\ y')  # TLA+ syntax
u = bdd.add_expr('x & y')  # Promela syntax

c = 'x' in bdd.support(u)  # more readable
c_ = bdd.is_essential(u, 'x')  # slightly more efficient
assert c == True, c
assert c == c_, (c, c_)

c = 'z' in bdd.support(u)
assert c == False, c
```

### Reordering

Given a BDD, the size of its graph representation depends on the variable order.
Reordering changes the variable order. Reordering *optimization* searches for
a variable order better than the current one.
*Dynamic* reordering is the automated invocation of reordering optimization.
BDD managers use heuristics to decide when to invoke reordering,
because it is [NP-hard](https://en.wikipedia.org/wiki/NP-hardness) to
find a variable order that minimizes a given BDD.

The function `dd.bdd.reorder` implements [Rudell's sifting algorithm](
    http://www.eecg.toronto.edu/~ece1767/project/rud.pdf).
This reordering heuristic is the most commonly used, also in CUDD.
Dynamic variable reordering can be enabled by calling:

```python
from dd import bdd as _bdd

bdd = _bdd.BDD()
bdd.configure(reordering=True)
```

By default, dynamic reordering in `dd.bdd.BDD` is disabled.
This default is unlike `dd.cudd` and will change in the future to enabled.

You can also invoke reordering explicitly when desired, besides dynamic
invocation. For example:

```python
from dd import bdd as _bdd

bdd = _bdd.BDD()
vrs = ['x{i}'.format(i=i) for i in range(3)]
vrs.extend('y{i}'.format(i=i) for i in range(3))
bdd.declare(*vrs)
>>> bdd.vars
{'x0': 0, 'x1': 1, 'x2': 2, 'y0': 3, 'y1': 4, 'y2': 5}

s = '(x0 /\ y0) \/ (x1 /\ y1) \/ (x2 /\ y2)'  # TLA+ syntax
s = '(x0 & y0) | (x1 & y1) | (x2 & y2)'  # Promela syntax
u = bdd.add_expr(s)
bdd.incref(u)
>>> len(bdd)
22

# collect intermediate results produced while making u
bdd.collect_garbage()
>>> len(bdd)
15
bdd.dump('before_reordering.pdf')

# invoke variable order optimization by sifting
_bdd.reorder(bdd)
>>> len(bdd)
7
>>> bdd.vars
{'x0': 0, 'x1': 3, 'x2': 5, 'y0': 1, 'y1': 2, 'y2': 4}
bdd.dump('after_reordering.pdf')
```

If you want to obtain a particular variable order, then give the
desired variable order as a `dict` to the function `reorder`.

```python
my_favorite_order = dict(
    x0=0, x1=1, x2=2,
    y0=3, y1=4, y2=5)
>>> len(bdd)
7
_bdd.reorder(bdd, my_favorite_order)
>>> len(bdd)
15
```

(Request such inefficient reordering only if you have some special purpose.)
You can turn [`logging`](https://docs.python.org/3/library/logging.html) to
`DEBUG`, if you want to watch reordering in action.

In some cases you might want to make some pairs of variables adjacent to
each other, but don't care about the location of each pair in the
variable order (e.g., this enables efficient variable renaming).
Use `reorder_to_pairs`.

All reordering algorithms rely on the elementary operation of swapping two
adjacent levels in the manager. You can do this by calling `BDD.swap`,
so you can implement some reordering optimization algorithm different
than Rudell's.
The difficult part to implement is `swap`, not the optimization heuristic.

The garbage collector in
[`dd.bdd.BDD.collect_garbage`](
    https://github.com/tulip-control/dd/blob/cbbc96f93da68d3d10f161ef27ccc5e3756c5ae2/dd/bdd.py#L614)
works by scanning all nodes, marking the unreferenced ones,
then collecting those (mark-and-sweep).

The function `dd.bdd.to_nx(bdd, roots)` converts the subgraph of `bdd` rooted
at `roots` to a [`networkx.MultiDiGraph`](
    http://networkx.readthedocs.io/en/stable/tutorial/tutorial.html#multigraphs).

The function `to_pydot(bdd)` converts the manager `bdd` to a [`pydot`](
    https://github.com/erocarrera/pydot) graph.

### Other methods

The remaining methods of `dd.bdd.BDD` will be of interest more to developers
of algorithms that manipulate or read the graph of BDD nodes itself.
For example, say you wanted to write a little function that explores the
BDD graph rooted at node `u`.

```python
def print_descendants_forgetful(bdd, u):
    i, v, w = bdd._succ[abs(u)]
    print(u)
    # u is terminal ?
    if v is None:
        return
    print_descendants_forgetful(bdd, v)
    print_descendants_forgetful(bdd, w)
```

In the worst case, this can take time exponential in the nodes of `bdd`.
To make sure that it takes linear time, we have to remember visited nodes

```python
def print_descendants(bdd, u, visited):
    p = abs(u)
    i, v, w = bdd._succ[p]
    # visited ?
    if p in visited:
        return
    # remember
    visited.add(p)
    print(u)
    # u is terminal ?
    if v is None:
        return
    print_descendants(bdd, v, visited)
    print_descendants(bdd, w, visited)
```

Run it with `visited = set()`.

New nodes are created with `BDD.find_or_add(level, low, high)`.
Always use this method to make a new node, because it first checks in
the *unique table* `BDD._pred` whether the node at `level` with successors
`(low, high)` already exists. This uniqueness is at the heart of reduced
ordered BDDs, the reason of their efficiency.

Throughout `dd.bdd`, nodes are frequently referred to as *edges*.
The reason is that all nodes stored are positive integers.
Negative integers signify negation, and appear only as either edges to
successors (negated edges), or references given to the user (because
a negation is popped to above the root node, for reasons of
[representation uniqueness](https://dx.doi.org/10.1145/123186.123222)).

The method `BDD.levels` returns a generator of tuples `(u, i, v, w)`,
over all nodes `u` in `BDD._succ`, where:

- `u` is a node in the iteration
- `i` is the level that `u` lives at
- `v` is the low (“else”) successor
- `w` is the high (“then”) successor

The iteration starts from the bottom (largest level), just above the terminal
node for “true” and “false” (which is `-1` in `dd.bdd`).
It scans each level, moving upwards, until it reaches the top level
(indexed with 0).

The nodes contained in the graph rooted at node `u` are `bdd.descendants([u])`.
An efficient implementation of `let` that works only for variables with
level <= the level of any variable in the support of node `u` is
`_top_cofactor(u, level)`.

Finally, `BDD.reduction` is of only academic interest.
It takes a binary decision diagram that contains redundancy in its graph
representation, and *reduces* it to the non-redundant, canonical form that
corresponds to the chosen variable order.
This is the function described originally [by Bryant](https://dx.doi.org/10.1109/TC.1986.1676819).

It is never used, because all BDD graphs are *constructed* bottom-up
to be reduced. To observe `reduction` in action, you have to manually
create a BDD graph that is not reduced.

## Example: Reachability analysis

We have been talking about BDDs, but you're probably here because you
want to *use* them. A common application is manipulation of Boolean functions
in the context of relations that represent dynamics, sometimes called
transition relations.

Suppose that we have an elevator that moves between three floors.
We are interested in the elevator's location, which can be at one of
the three floors. So, we can pretend that 0, 1, 2 are the three floors.

Using bits, we need at least two bits to represent the triple `{0, 1, 2}`.
Two bits can take a few too many values, so we should tell the computer that
3 is not possible in our model of the three floors.

Suppose that now the elevator is at floor `x0`, `x1`, and next at floor
`x0'`, `x1'` (read “x prime”).
The identifiers `["x0", "x1", "x0'", "x1'"]` are just four bits.
The elevator can move as follows

```python
from dd import autoref as _bdd

bdd = _bdd.BDD()
bdd.declare("x0", "x0'", "x1", "x1'")
# TLA+ syntax
s = (
    "((~ x0 /\ ~ x1) => ( (~ x0' /\ ~ x1') \/ (x0' /\ ~ x1') )) /\ "
    "((x0 /\ ~ x1) => ~ (x0' /\ x1')) /\ "
    "((~ x0 /\ x1) => ( (~ x0' /\ ~ x1') \/ (x0' /\ x1') )) /\ "
    " ~ (x0 /\ x1)")
transitions = bdd.add_expr(s)
```

We can now find from which floors the elevator can reach floor 2.
To compute this, we find the floors that either:

- are already inside the set `{2}`, or
- can reach `q` after one transition.

This looks for existence of floors, hence the existential quantification.
We enlarge `q` by the floors we found, and repeat.
We continue this backward iteration, until reaching a [least fixpoint](
    https://en.wikipedia.org/wiki/Knaster%E2%80%93Tarski_theorem)
(meaning that two successive iterates are equal).

```python
# target is the set {2}
target = bdd.add_expr('~ x0 /\ x1')
# start from empty set
q = bdd.false
qold = None
prime = {"x0": "x0'", "x1": "x1'"}
qvars = {"x0'", "x1'"}
# fixpoint reached ?
while q != qold:
    qold = q
    next_q = bdd.let(prime, q)
    u = transitions & next_q
    # existential quantification over x0', x1'
    pred = bdd.quantify(u, qvars, forall=False)
    q = q | pred | target
```

At the end, we obtain

```python
>>> q.to_expr()
'(! ite(x0, x1, False))'
```

which is the set `{0, 1, 2}` (it does not contain 3, because that would
evaluate to `! ite(True, True, False)` which equals `! True`, so `False`).

More about building symbolic algorithms, together with infrastructure for
arithmetic and automata, and examples, can be found in the package [`omega`](
    https://github.com/tulip-control/omega/blob/master/doc/doc.md).

## Syntax for quantified Boolean formulas

The method `BDD.add_expr` parses the following grammar.

```
       # predicate logic
expr ::= '\A' names ':' expr  # universal quantification (forall)
         '\E' names ':' expr  # existential quantification (exists)
         '\S' pairs ':' expr  # renaming of variables (substitution)

       # propositional

       # TLA+ syntax
       | '~' expr         # negation (not)
       | expr '/\' expr   # conjunction (and)
       | expr '\/' expr   # disjunction (or)
       | expr '=>' expr   # implication (implies)
       | expr '<=>' expr  # equivalence (if and only if)

       # Promela syntax
       | '!' expr         # negation
       | expr '&' expr    # conjunction
       | expr '|' expr    # disjunction
       | expr '->' expr   # implication
       | expr '<->' expr  # equivalence

       # other
       | expr '^' expr    # xor (exclusive disjunction)
       | 'ite' '(' expr ',' expr ',' expr ')'
                          # ternary conditional (if-then-else)
       | expr '=' expr    #
       | '(' expr ')'     # parentheses
       | NAME             # identifier (bit variable)
       | '@' INTEGER      # BDD node reference
       | 'False'          # Boolean constant
       | 'True'           # Boolean constant

pairs ::= [pairs] ',' pair
pair ::= NAME '/' NAME

names ::= [names] ',' name
name ::= NAME

NAME ::= [A-Za-z_][A-za-z0-9_.']*
INTEGER ::= [-][0-9]*
```

Trailing comments can be added using a hashmark,
for example `# this is comment`.

The token precedence (lowest to highest) and associativity
(r = right, l = left, n = none) is:

- `:` (l)
- `<=>, <->` (l)
- `=>, ->` (l)
- `-` (l)
- `^` (l)
- `\/, |` (l)
- `/\, &` (l)
- `=`, `!=` (l)
- `~, !` (r)
- `-` (r) unary minus, as in `-5`

Both and `setup.py`, and a developer may want to force a rebuild of the
parser table. For this purpose, each module that contains a parser,
also has a function `_rewrite_tables` that deletes and rewrites the tables.
If the module is run as a script, then the `__main__` stanza calls this
function to delete and the write the parser tables to the current directory.
The parsers use [`astutils`](https://pypi.python.org/pypi/astutils).

## Multi-valued decision diagrams (MDD)

A representation for functions from integer variables to Boolean values.
The primary motivation for implementing MDDs was to produce more readable
string and graphical representations of BDDs.
MDDs are implemented in pure Python.
The interface is “low”, similar to `dd.bdd`, with reference counting
managed by the user.
A core of necessary methods have been implemented, named as the `BDD` methods
with the same functionality in other `dd` modules.
Complemented edges are used here too.

BDDs are predicates over binary variables (two-valued).
MDDs are predicates over integer variables (multi-valued).
As expected, the data structure and algorithms for representing an MDD are
a slight generalization of those for BDDs.
For example, compare the body of `dd.mdd.MDD.find_or_add` with
`dd.bdd.BDD.find_or_add`.

The variables are defined by a `dict` argument to the constructor
(in the future, dynamic variable addition may be implemented,
by adding a method `MDD.add_var`)

```python
from dd import mdd as _mdd

dvars = dict(
    x=dict(level=0, len=4),
    y=dict(level=1, len=2))
mdd = _mdd.MDD(dvars)
```

So, variable `x` is an integer that can take values in `range(4)`.

Currently, the main use of an MDD is for more comprehensive representation of
a predicate stored in a BDD. This is achieved with the function
`dd.mdd.bdd_to_mdd` that takes a `dd.bdd.BDD` and a mapping from
MDD integers to BDD bits. Referencing of BDD nodes is necessary,
because `bdd_to_mdd` invokes garbage collection on the BDD.

```python
from dd.bdd import BDD
from dd import mdd as _mdd

bits = dict(x=0, y0=1, y1=2)
bdd = BDD(bits)
u = bdd.add_expr('x \/ (~ y0 /\ y1)')
bdd.incref(u)

# convert BDD to MDD
ints = dict(
    x=dict(level=1, len=2, bitnames=['x']),
    y=dict(level=0, len=4, bitnames=['y0', 'y1']))
mdd, umap = _mdd.bdd_to_mdd(bdd, ints)

# map node `u` from BDD to MDD
v = umap[abs(u)]
# complemented ?
if u < 0:
    v = - v
>>> v
    -3
s = mdd.to_expr(v)
>>> print(s)
    (! if (y in set([0, 1, 3])): (if (x = 0): 1,
    elif (x = 1): 0),
    elif (y = 2): 0)

# plot MDD with graphviz
pd = _mdd.to_pydot(mdd)
pd.write_pdf('mdd.pdf')
```

Note that the `MDD` node `v` is complemented (-3 < 0), so the predicate
in the negated value computed for node `y-3` in the next image.

![example_bdd](https://rawgithub.com/johnyf/binaries/master/dd/mdd.png)

## Footnotes

- The `Makefile` contains the rules `sdist` and `wheel` that
  create distributions for uploading to PyPI with `twine`.

- Press `Ctrl + \` on Linux and Darwin to quit the Python process when
  CUDD computations take a long time. See `stty -a` for your settings.

- To use `Ctrl + C` (`KeyboardInterrupt`) to interrupt CUDD computations
  that take a long time, install `cysignals`, then build `dd.cudd`.

- If you are interested in exploring other decision diagram packages,
  you can find [a list at `github.com/johnyf/tool_lists/`](
    https://github.com/johnyf/tool_lists/blob/master/bdd.md).

## Copying

This document is copyright 2015-2020 by California Institute of Technology.
All rights reserved. Licensed under 3-clause BSD.

repository: keepingbetter/dd

repo_name: keepingbetter/dd


text:
## 1452. People Whose List of Favorite Companies Is Not a Subset of Another List

Given the array ```favoriteCompanies``` where ```favoriteCompanies[i]``` is the list of favorites companies for the ```i```-th person (**indexed from 0**).

*Return the indices of people whose list of favorite companies is not a **subset** of any other list of favorites companies*. You must return the indices in increasing order.

### Example 1:
```
Input: favoriteCompanies = [["leetcode","google","facebook"],["google","microsoft"],["google","facebook"],["google"],["amazon"]]
Output: [0,1,4]
Explanation:
Person with index=2 has favoriteCompanies[2]=["google","facebook"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] corresponding to the person with index 0.
Person with index=3 has favoriteCompanies[3]=["google"] which is a subset of favoriteCompanies[0]=["leetcode","google","facebook"] and favoriteCompanies[1]=["google","microsoft"].
Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].
```
### Example 2:
```
Input: favoriteCompanies = [["leetcode","google","facebook"],["leetcode","amazon"],["facebook","google"]]
Output: [0,1]
Explanation: In this case favoriteCompanies[2]=["facebook","google"] is a subset of favoriteCompanies[0]=["leetcode","google","facebook"], therefore, the answer is [0,1].
```
### Example 3:
```
Input: favoriteCompanies = [["leetcode"],["google"],["facebook"],["amazon"]]
Output: [0,1,2,3]
```

### Constraints:

* ```1 <= favoriteCompanies.length <= 100```
* ```1 <= favoriteCompanies[i].length <= 500```
* ```1 <= favoriteCompanies[i][j].length <= 20```
* All strings in ```favoriteCompanies[i]``` are **distinct**.
* All lists of favorite companies are **distinct**, that is, If we sort alphabetically each list then ```favoriteCompanies[i] != favoriteCompanies[j]```.
* All strings consist of lowercase English letters only.

repository: stdstring/leetcode

repo_name: stdstring/leetcode


text:
---
author: kubu4
comments: true
date: 2009-06-09 04:44:10+00:00
layout: post
slug: pcr-c-pugetti-gdna-from-20090513-20090526
title: PCR - C.pugetti gDNA from 20090513 & 20090526
wordpress_id: 1037
author:
  - kubu4
categories:
  - Miscellaneous
tags:
  - 1492R
  - 16s
  - 27F
  - Cycloclasticus pugetii
  - gDNA
  - gel
  - PCR
---

Previous PCRs from [20090601](/Sam%27s+Working+Notebook+Jun-Aug+2009#sjw20090601) & [20090602](/Sam%27s+Working+Notebook+Jun-Aug+2009#sjw20090602) both showed contamination in the negative control. Suspect that the primer stocks were contaminated due to the usage of older, non-sterile TE for reconstitution. New stocks were received and reconstituted with filter-sterilized TE. Working stocks were made with filter-sterilized Nanopure H2O. All pipettes, tips, tubes, racks were UV-sterilized in the biological hood. The PCR reaction was set up in the biological hood. [PCR set up is here](https://eagle.fish.washington.edu/Arabidopsis/Notebook%20Workup%20Files/20090608-02.jpg). Used universal 16s bacteria primers (27F, 1492R). Sequences from Sara Kelly. Anneal 60C.

![](https://eagle.fish.washington.edu/Arabidopsis/20090609.JPG)

Lane 1 - 100bp ladder

Lane 2 - gDNA (5/13/2009)

Lane 3 - gDNA (5/26/2009)

Lane 4 - H2O

Lane 5 - H2O

Lane 6 - H2O

Lane 7 - H2O

Results: Still contamination in the water-only samples!!!

repository: RobertsLab/sams-notebook

extension: markdown

repo_name: RobertsLab/sams-notebook