text:
# mlab-tools

3D animation tools for [mlab](http://docs.enthought.com/mayavi/mayavi/mlab.html).

## Overview

This project aims at simplifying the production of geometric animations through [mlab](http://docs.enthought.com/mayavi/mayavi/mlab.html), a Python API for 3D plotting. It defines a collection of classes that wrap and extend `mlab` and [tvtk](http://docs.enthought.com/mayavi/tvtk/README.html) (traited VTK).

### Features

 * Automatic recording of AVI videos.
 * Definition of arbitrary polyhedrons through a (basic) support of [OFF (Object File Format)](https://en.wikipedia.org/wiki/OFF_(file_format)).
 * Animated polylines (i.e., continuous lines made up of linear segments) that can mimic 3D trajectories.
 * Clean interface to manipulate the animation scene in order to dynamically add or remove objects, handle the camera, etc.

## Getting started

### Prerequisites

* [Python 2.7](https://www.python.org/download/releases/2.7/)
* [Mayavi2](http://code.enthought.com/projects/mayavi/) and its `mlab` API
* Python bindings for [OpenCV 2.4](http://opencv.org/) (only for video recording)

### Installation

You can simply clone this repository and use it locally right away.

### Examples

In the [examples](examples) folder you can find the following demos:

 * [Shrinking polyhedron](examples/shrinking_polyhedron.py), a basic animation that shrinks an OFF-based polyhedron by 20% on each frame.
 * [Animated polyhedrons](examples/animated_polyhedrons.py), another basic animation that transforms two OFF-based polyhedrons and dynamically updates some of their properties (such as their color).
 * [Polyhedron and lines](examples/polyhedron_and_random_lines.py), an animation that shows an OFF-based polyhedron rotating and randomly changing colors along with some random polylines appearing and disappearing:
 ![alt text](https://user-images.githubusercontent.com/5144049/28150482-3c382c12-676b-11e7-80d2-8c8e2e90541e.gif "Polyhedron and lines")
 * [Primitives and points](examples/primitives_and_points.py), where some primitive shapes (namely, sphere, cube, cone and cylinder) are displayed and an animated polyline progressively joins a random set of points.
 * [Rotating cubes](examples/rotating_cubes.py), an animation where cubes of random sizes and colors are generated on each frame and keep rotating:
 ![alt text](https://user-images.githubusercontent.com/5144049/28150484-3c38eb66-676b-11e7-8cd1-04ef8ea70f54.gif "Rotating cubes")
 * [Helix in detector](examples/detector_helix.py), a more complex animation that shows a small fragment of a particle detector, zooming into it to reveal a particle describing a helicoidal trajectory inside:
 ![alt text](https://user-images.githubusercontent.com/5144049/28150481-3c380a3e-676b-11e7-81f8-eee51ae450b8.gif "Helix in detector")

## License

This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for further details.

repository: lukius/mlab-tools

repo_name: lukius/mlab-tools


text:
### Version 0.0.2
2014-9-19

* Use coverage analysis to choose which specs to rerun
* Don't block key commands while waiting for RSpec results
* Bugfixes

### Version 0.0.1
2014-8-12

* Watch for file changes and rerun all specs
* Concise backtraces with configurable verbosity level
* Rotate list of failures to show different specs at the top
* Fullscreen Curses output with color and resizing detection

license: MIT

repository: brianauton/rspec-live

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: brianauton/rspec-live


text:
---
layout: kanji
v4: 1634
v6: 1762
kanji: 排
keyword: repudiate
elements: repudiate, finger, fingers, un-, jail cell, prison bars
strokes: 11
image: E68E92
on-yomi: ハイ
permalink: /rtk/排/
prev: 俳
next: 悲
---

1) [rgravina] 21-8-2006(251): When ordered to go to the jail cell, the defendant gave the judge the finger and said he repudiated all that the legal system stood for if they were going to send an innocent man like him to jail.

2) [jameserb] 13-7-2008(56): He reached his fingers through the bars of his jail cell, trying to touch his beloved. But she repudiated him and left.

3) [FutureBlues] 1-9-2008(31): Once he had his fingers around the jail cell bars he repudiated all ties with his former gang!

4) [romanrozhok] 16-2-2008(17): 排他 【はいた】 (n) exclusion; (P) 排日 【はいにち】 (n) anti-Japanese; (P) 排出 【はいしゅつ】 (n,vs) evacuation; emission (e.g. of CO2, etc.); ejection; (P) 排除 【はいじょ】 (n,vs) exclusion; removal; rejection; (P) STORY: Giving everyone the FINGER in a JAIL CELL is a good way to be EXCLUDED by everyone from the next prison break.

 Indignant, she points a FINGER at the guards, screaming, "I refutiate this! I refudiate it!" Picture the guards and the other prisoners replying, "Don't you mean, REPUDIATE?".


text:
---
layout: post
title: "Home School: MS Webcam League"
cover: /assets/images/2021-08-20/home_school.jpg
---

![]({{site.cdn_url}}/assets/images/2021-08-20/home_school.jpg)

*	**Format:** Middle School, using Eternal Central's deck construction and play rules (i.e. mana burn, damage on the stack, etc)
*	**Location:** Play will take place over webcam, and event coordinating over the Romancing The Stones Discord
*	**Entry:** RSVP to<EMAIL_ADDRESS>with an optional $5 donation to the Central Texas Food Bank
  trophy card, and a spot at the 2020/2021 Invitational.
*	**Proxy Limit:** 100% proxy. Please make your proxies clear so opponents can easily identify them.
* **Decklists:** Send a decklist to<EMAIL_ADDRESS>prior to your first match. At the end of the league, we'll ask for crispy deck photos to share on our site.
* **Structure:** Swiss rounds with a cut to Top 8. Each round, players will have 1 week to coordinate and play their match
* **Date & Time:** Signups open Wednesday, August 11th and close on Friday, August 20th. Round 1 will begin on Monday, August 23rd.

branch_name: refs/heads/main

gha_language: SCSS

gha_license_id: NOASSERTION


text:
:warning: This project is archived and the repository is no longer maintained.

# Accessible Tabs Widget
## _from the Book:_ [Designing with Progressive Enhancement](http://filamentgroup.com/dwpe)

This repository includes open-sourced code developed and maintained by [Filament Group, Inc.](http://filamentgroup.com/) as part of the book "Designing With Progressive Enhancement" (Peachpit).

Those who purchase the book can access to all of the examples from the book at the following URL: (http://filamentgroup.com/dwpe#codeexamples)[http://filamentgroup.com/dwpe#codeexamples]

All examples use the jQuery JavaScript library

Demos:

- [Demo](http://filamentgroup.github.com/Accessible-jQuery-Tabs/demo-default.html)
- [Demo with auto-rotation](http://filamentgroup.github.com/Accessible-jQuery-Tabs/demo-rotate.html)
- [Demo with hash updating](http://filamentgroup.github.com/Accessible-jQuery-Tabs/demo-updateHash.html)

repository: filamentgroup/Accessible-jQuery-Tabs

gha_language: JavaScript

repo_name: filamentgroup/Accessible-jQuery-Tabs


text:
[![Netlify Status](https://api.netlify.com/api/v1/badges/1a9f592f-9787-4a25-a24b-dc01f58a0565/deploy-status)](https://app.netlify.com/sites/clever-bohr-d6b52c/deploys)

# [stuartmyers.com](https://stuartmyers.com/)

## Portfolio website for Stuart Myers

This is the source code for my portfolio website.

Using Gatsby as the site doesn't require server-side rendering, so a static site generator saves on hosting costs.

Also migrated away from using Wordpress.com as the back-end CMS as it's expensive (using just markdown is free) and I can keep the content and the layout together in one place.

Having my website content as markdown also means if I migrate elsewhere it is easy to export/import anywhere else.

repository: LaustinSpayce/stuartmyers-portfolio

gha_license_id: MIT

repo_name: LaustinSpayce/stuartmyers-portfolio


text:
---
layout:     survey
title:      "A quick GDPR evaluation for SMBs"
subtitle:   "Unsure whether GDPR affects you?"
description: "This free, short questionnaire will help you understand if you need to take action regarding GDPR. Take two minutes to see where you fall and get important information on how to take the next steps."
date:       2018-04-21 12:02:00
permalink:  /gdpr-survey-q2
author:     dario.pw Staff
header-img: "img/GDPR-privacy-protection.jpg"
image: "img/GDPR-privacy-protection.jpg"
header-title:
header-author:
header-credit-link:
header-license:
question: true
answer-yes: /gdpr-survey-a2
answer-no: /gdpr-survey-q3
---

**Question 2 of 10**

Does your organization employ anyone, even an outside contractor, resident in an EU country, or do business with an EU-based company?


text:
---
Order: 30
xref: cpmr0030
Title: CPMR0030 - Description Contains Invalid Markdown Heading (nuspec)
Description: Information on how to remediate the Chocolatey Package Moderation Rule 0030
RuleType: Requirement
---

<?! Include "../../../../../shared/package-validator-rule-requirement.txt" /?>

## Issue

The Description element of the package nuspec file contains invalid Markdown headings.  For example, you may have this:

```
###This is my heading
```
instead of:

```
### This is my heading
```

## Recommended Solution

Please update the description element of the nuspec file to contain valid Markdown Headings.  More information can be found [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#headers).

## Reasoning

The Chocolatey Community Repository uses the Markdig Library for parsing/rendering Markdown content.  When invalid headings are used, the result looks like the following:

![Example of invalid markdown from nuspec description rendering on the website](/assets/images/moderation/invalid-markdown-rendering.png)

A prior version of the Chocolatey Community Repository did support this way for writing headings, but it is not part of the official Markdown specification, and as such, we don't want any further invalid headings making their way into the repository.

repository: StefanoFrazzetto/docs

repo_name: StefanoFrazzetto/docs


text:
# 13.3 Exercises

1. It would violate other properties, the resolution to which is less procedurally obvious.

2. elide

3. elide

4. Can't because no uncle; case 1 doesn't apply. Also, z.p would be black because root, so would terminate first.

5. Always leaves at least 1 red node (other than root) since default is red and only re-colors ancestors of latest inserted node when not the root or moves it up the chain and leaves others.

6. Keep track of ancestors on an auxiliary structure (say, a stack) during insertion; use as necessary for `.p` and `.p.p`.

repository: TheYargonaut/algorithms-text-answers

repo_name: TheYargonaut/algorithms-text-answers


text:
# Automated Machine Learning

Automated machine learning (automated ML) builds high quality machine learning models for you by automating model and hyperparameter selection. Bring a labelled dataset that you want to build a model for, automated ML will give you a high quality machine learning model that you can use for predictions.

If you are new to Data Science, automated ML will help you get jumpstarted by simplifying machine learning model building. It abstracts you from needing to perform model selection, hyperparameter selection and in one step creates a high quality trained model for you to use.

If you are an experienced data scientist, automated ML will help increase your productivity by intelligently performing the model and hyperparameter selection for your training and generates high quality models much quicker than manually specifying several combinations of the parameters and running training jobs. Automated ML provides visibility and access to all the training jobs and the performance characteristics of the models to help you further tune the pipeline if you desire.

## Using Automated Machine Learning

Follow the instructions in the [documentation](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-create-portal-experiments) for a full overview of the user interface.

1. Navigate to the left pane of your workspace. Select Automated Machine Learning under the Authoring (Preview) section.
![Automated ML tab](https://docs.microsoft.com/en-us/azure/machine-learning/service/media/how-to-create-portal-experiments/nav-pane.png).

1. Enter your experiment name, then select a compute from the list of your existing computes or [create a new compute](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-create-portal-experiments#create-an-experiment).

1. Select the telcochurn dataset that you had created above.

1. Preview data and keep all columns selected for training.

1. Select the training job type: **Classification**
1. Select target column: **Churn**

1. Open “**Advanced settings**”, set the 'Primary metric' to 'AUC_weighted' and training job time to 15 minutes (for the workshop).

1. Hit "**Start**" and wait for the training job to start. You’ll be able to see the models which are created during the run, click on any of the models to open the detailed view of that model, where you can analyze the [graphs and metrics](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-understand-automated-ml).

1. Once the run is completed, click **deploy the best model** to create a deployed endpoint from the model.

To learn more about automated ML, see documentation [here](https://docs.microsoft.com/en-us/azure/machine-learning/service/concept-automated-ml).

Optional Tasks:
- Once your model has been deployed, follow these [instructions](https://docs.microsoft.com/en-us/power-bi/service-machine-learning-integration) to consume the model from Power BI.

- Try the sample notebooks [here](https://github.com/Azure/MachineLearningNotebooks/tree/master/how-to-use-azureml/automated-machine-learning).


text:
## Scikit-learn Python Tutorials

This section contains tutorials with Scikit-learn in Python. We are going to provide examples for different tasks and use cases.

**Currently, this repository is under development and we will add more and more tutorials in the future.**

### Overview

* [Classification](classification.ipynb)

repository: exasol/data-science-examples

gha_language: Jupyter Notebook

repo_name: exasol/data-science-examples


text:
# khalyomede/monad

Maybe, Option and Result monads for PHP.

## Summary

- [About](#about)
- [Features](#features)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Examples](#examples)
- [API](#api)

## About

I published on [reddit](https://www.reddit.com/r/PHP/comments/oxcmw9/rfc_proposal_enums_constructor/) an RFC proposal for what I called "enums constructor" (which happened to be an existing concept called "tagged unions"). Out of [one comment](https://www.reddit.com/r/PHP/comments/oxcmw9/rfc_proposal_enums_constructor/h7qgo1n?utm_source=share&utm_medium=web2x&context=3), I shown how to chain calls to various ADT outcomes, in order to reduces pyramidal matches.

This got me into wanting to use more monads right now on my next projects. After searching on packagist.org, I did not found something that fits what I expected, so I decided to make my own version of how I think monads should look like in PHP.

## Features

- Supports theses monads:
  - Option
  - Maybe
  - Result
- PHPStan and static analyzers friendly

## Prerequisites

- PHP 8+ installed

## Installation

```bash
composer require khalyomede/monad
```

## Examples

- [1. Getting a file content](#1-getting-a-file-content)
- [2. Get users from an SQL table](#2-get-users-from-an-sql-table)
- [3. Chain multiple outcomes](#3-chain-multiple-outcomes)

### 1. Getting a file content

In this example, we will use the Maybe monad as result, and use it in our main code.

```php
use Khalyomede\Monad\Maybe;

function getFileContent(string $filePath): Maybe
{
  $content = file_get_contents($filePath);

  return $content === false ? Maybe::nothing() : Maybe::just($content);
}

// main
$content = getFileContent("data.txt")
  ->then(fn (string $data): string => $data)
  ->catch(fn (): string => "N/A");

echo $content;
```

### 2. Get users from an SQL table

In this example, we will use the Result monad to return the list of users or an error from PDO.

```php
use Khalyomede\Monad\Result;

function getUsers(): Result
{
  $pdo = new PDO("sqlite::memory:");

  $statement = $pdo->prepare("SELECT * FROM users");

  if ($statement === false) {
    $message = $pdo->errorInfo()[2];

    return Result::error($message);
  }

  $result = $statement->execute();

  if ($result === false) {
    $message = $statement->errorInfo()[2];

    return Result::error($message);
  }

  return Result::ok($statement->fetchAll());
}

// main
$users = getUsers()
  ->then(fn (array $records): array => $records)
  ->catch(function (string $error): array {
    error_log($error);

    return [];
  });
```

### 3. Chain multiple outcomes

In this example, we will chain multiple times "then", similar to what is possible in other languages through "map".

```php
use Khalyomede\Monad\Result;

function getFileContent(string $path): Result
{
  $content = file_get_contents($path);

  return $content === false ?
    Result::error(new Exception("Cannot get content of file $path.")) :
    Result::ok($content);
}

function saveFileContent(string $path, string $content): Result
{
  $result = file_put_contents($path, $content);

  return $result === false ?
    Result::error(new Exception("Cannot write file content of file $path.")) :
    Result::ok(true);
}

// main
$result = fileGetContent("composer.json")
  ->then(fn (string $content): Result => saveFileContent("composer.json.save", $content))
  ->then(fn (): string => "composer.json backup finished.")
  ->catch(fn (Exception $exception): string => $exception->getMessage());

echo $result . PHP_EOL;
```

```bash
khalyomede@pc > php index.php
composer.json backup finished.
```

If you remove the file, the result becomes

```bash
khalyomede@pc > php index.php
Cannot get content of file composer.json.
```

If you remove the write permission on this file, the result becomes

```bash
khalyomede@pc > php index.php
Cannot write file content of file composer.json.save.
```

## API

For a list of all possible functions, see the _tests\unit_ folder.

## Tests

```bash
composer run install-security-checker
composer run test
composer run mutate
composer run analyse
composer run check
composer outdated --direct
```

repository: khalyomede/monad

gha_language: PHP

repo_name: khalyomede/monad


text:
# SafetyCulture Python SDK and iAuditor Tools

# DEPRECATED

The SafetyCultue Python SDK is no longer supported, it's recommend you connect to our APIs directly. You can find examples of doing this in our [developer documentation](https://developer.safetyculture.com/).

## There is a newer version of the Exporter tool that forms part of this SDK. If you're looking to export data out of iAuditor, please check out the [iAuditor Exporter](https://github.com/SafetyCulture/iauditor-exporter) rather than following the instuctions below.

Contains:

* The SafetyCulture Python SDK: core functions to interact with the iAuditor API

* The iAuditor Export Tool for exporting audit data to your computer

* The Import Global Response Set (GRS) Tool for importing and updating response sets from a spreadsheet

* The Export Users Tool to export a list of all users and their groups from iAuditor into a spreadsheet

* The Sync Users Tool allows you to use a spreadsheet to keep your users and their group associations up to date and automatically reflect that in iAuditor.

* Examples of how to import individual modules of the SDK into your own scripts.

## iAuditor Export Tool

### First Time Install and Run

You will need to have [Python 2.7 or higher](https://www.python.org/downloads/) and [Pip](https://pip.pypa.io/en/stable/installing/) installed on your computer. If you are using Windows, make sure to select the option to "Add Python to PATH" during the installation process. Also, Windows users may need to prepend the following commands with
```
python -m
```
i.e.
```
python -m pip install safetyculture-sdk-python
```

To install the Python SDK, run the following commands from your terminal:

1. Install the SDK and tools
```
pip install safetyculture-sdk-python
```

2. Setup (creates `config.yaml` file in new folder `iauditor_exports_folder`)
```
iauditor_exporter --setup
```

3. Navigate into to the newly created folder
```
cd iauditor_exports_folder
```

4. Run the tool to export PDF reports of all your audits (for other formats see later sections in this tutorial)
```
iauditor_exporter
```

### Upgrading from an Older Version of the Exporter Tool

**Option 1 (re-use existing exports folder)**

Install the latest version of the SDK and Export Tool (you may need to substitute pip with pip3 depending on your configuration):
```
pip install safetyculture-sdk-python
```

If the above command reports that everything is already up to date, run with the force command:
```
pip install safetyculture-sdk-python --force
```

Then navigate into your existing exporter folder. This is located within the cloned repository at `safetyculture-sdk-python/tools/exporter`
and run `iauditor_exporter` from there. Export data will be saved in the existing `exports` folder, and the existing `last_successful.txt` file will
be used to pick up where the last export left off.

**Option 2 (re-use existing exports folder)**

Get the latest version of the code by navigating into `safetyculture-sdk-python` and running
```
git pull
```
Navigate into `safetyculture-sdk-python/tools/exporter`
Run the iAuditor export tool directly:
```
python exporter.py
```

**Option 3 (export audits in new folder)**

Follow the instructions above to start exporting data to the new folder named `iauditor_exports_folder`. The setup script will give you the option to start your exports from the
current date and time, so that you do not have to re-export older audits.

### How to use the iAuditor Export Tool

The API token saved in `config.yaml` provides access to data associated with a single account. Namely, the account used to generate the API token.
Only audits that are accessible to the single iAuditor account associated with the iAuditor API token used are available for exporting.

All exported data is saved in a folder called `exports`. The folder will be created in the current working directory if it does not already exist.

To export all completed audits in PDF format, run
```
iauditor_exporter
```

To enable the exporter to run continuously until interrupted, use the loop command line argument

```
iauditor_exporter --loop
```

To specify the export format explicitly run

```
iauditor_exporter --format pdf
```

More than one supported formats can be exported at once e.g.

```
iauditor_exporter --format  pdf  docx  json  csv  media  web-report-link  actions
```

Note:
* Unless you start the tool with the --loop argument, it will sync documents once and terminate
* Only completed audits will be exported
* Only audits that are owned by or shared with the iAuditor user account that generated the API token will be exported
* Up to 1000 audits will be exported each sync cycle. If more than 1000 audits exist they will be retrieved automatically in subsequent sync cycles

### CSV Export

#### Bulk CSV Export

For an overview of the CSV format used, see [here](https://support.safetyculture.com/integrations/safetyculture-csv-exporter-tool/#format)

Audits built from the same template will be saved in the same CSV file which is named after the template's unique ID number.
i.e. `TEMPLATE_ID.csv`

To export multiple audits in bulk to a CSV file, run the `iauditor_exporter` with the format option set to CSV:
```
iauditor_exporter --format csv
```
#### The format of the following CSV values do not match the format used by the SafetyCulture API Audit JSON

##### Date/Time field
* JSON: `2017-03-03T03:45:58.090Z`
* CSV:  `03 March 2017 03:45 AM`

##### Checkbox field
* JSON: `1` or `0`
* CSV:  `True` or `False`

##### Media List, Multiple Choice Responses
* JSON: List Object
* CSV:  Newline separated values in single cell

#### Bulk CSV Export Gotchas
* If you update an Audit that has already been exported, it may be appended to the CSV file a second time.
* If you update a template, Audits with the new format will be appended to the same CSV file.

### Media Export
* Running
```
iauditor_exporter --format media
```
will export all audit media files for each audit (images, attachments, signature, and drawings) to a folder named after the audit ID.

### Web Report Link Export
* Running
```
iauditor_exporter --format web-report-link
```
will export your Web Report Links to a CSV file named `web-report-links.csv`.

The CSV file includes five columns: Template ID, Template Name, Audit ID, Audit Name, and Web Report Link.

### Actions Export
Running
```
iauditor_exporter --format actions
```
will export all actions to a file named `iauditor_actions.csv`

The actions export tool reads and writes to a file named `last_successful_actions_export.txt` to keep track of what actions have already been exported.
If it does not already exist, `last_successful_actions_export.txt` is created.

Each time actions are exported, newly created actions are appended to `iauditor_actions.csv`. Additionally, any existing actions that have been modified since the last
time actions were exported will be re-appended to the CSV file.

`iauditor_actions.csv` consists of the following columns
- actionId
- description
- assignee
- priority
- priorityCode
- status
- statusCode
- due_datetime
- audit
- auditId
- linkedToItem
- linkedToItemId
- creatorName
- creatorId
- createdDatetime
- modifiedDatetime
- completedDatetime
- site
- title

The fields `priorityCode` and `statusCode` are number values. All other fields are string values.
See [here](https://developer.safetyculture.io/#search-actions) for more information about the status codes and priority codes.

## Export settings

To override default export settings edit config.yaml in this directory.

Things you can configure:

|  Setting | Description  |
|---|---|
| export_path  | absolute or relative path to the directory where to save exported data to  |
| filename  |  an audit item ID whose response is going to be used to name the files of exported audit reports. Can only be an item with a response type of `text` from the header section of the audit such as Audit Title, Document No., Client / Site, Prepared By, Personnel, or any custom header item which has a 'text' type response (doesn't apply when exporting as CSV) |
| preferences  | to apply a preference transformation to particular templates, give here a list of preference ids
| sync_delay_in_seconds | time in seconds to wait after completing one export run, before running again
| export_inactive_items | This setting only applies when exporting to CSV. Valid values are true (export all items) or false (do not export inactive items). Items that are nested under [Smart Field](https://support.safetyculture.com/templates/smart-fields/) will be 'inactive' if the smart field condition is not satisfied for these items.
| media_sync_offset_in_seconds | time in seconds since an audit has been modified before it will by synced

Here is an example customised config.yaml:

```
API:
    token: YOUR_IAUDITOR_API_TOKEN
export_options:
    export_path: /Users/Monty/Dropbox
    filename: f3245d40-ea77-11e1-aff1-0800200c9a66
    csv:
        export_inactive_items: false
preferences:
    template_3E631E46F466411B9C09AD804886A8B4:E15A6525-EFA5-4835-92F0-D11CA9F364F3
    template_3E631E46F466411B9C09AD804886A8B4:E50645A1-2851-4E92-B4EA-60C5CE7981BE
    ...
    ...
sync_delay_in_seconds: 36000
media_sync_offset_in_seconds: 600
```

Note: Templates for which there is no preference id listed in the config file will be exported without a preference applied

### Naming the exported files

(Doesn't apply when exporting as CSV - names are always the template ID.)

Note that when automatic Audit Title rules are set on the template, the Audit will not contain an Audit Title field by default. Regardless, the export filename setting will still work as expected using the automatically generated Audit name.

When configuring a custom filename convention in export settings (in `config.yaml`) you can provide an audit item ID from the ones below to cause all exported audit reports be named after the response of that particular item in the audit.

Here are some standard item IDs

| Item Name| Item ID|
|---|---|
|Audit Title |f3245d40-ea77-11e1-aff1-0800200c9a66|
|Conducted By |f3245d43-ea77-11e1-aff1-0800200c9a66|
|Document No |f3245d46-ea77-11e1-aff1-0800200c9a66|
|Client Site |f3245d41-ea77-11e1-aff1-0800200c9a66|
|Conducted On (Date) |f3245d42-ea77-11e1-aff1-0800200c9a66|
|Conducted At (Location) |f3245d44-ea77-11e1-aff1-0800200c9a66|
|Personnel |f3245d45-ea77-11e1-aff1-0800200c9a66|

or from any other header item of the audit created by the user (a custom header item). Tip: To find the item ID of such custom header items export one audit from the template of interest in JSON format and inspect the contents to identify the item ID of interest in the `header_items` section.

E.g. the following `config.yaml`

```
export_options:
    filename: f3245d40-ea77-11e1-aff1-0800200c9a66
```

will result in all exported files named after the `Audit Title` field.

### How to list available preference IDs
To list all available global preference IDs and their associated templates:

```
iauditor_exporter --list_preferences
```
To list global and template specific preference IDs associated with specific templates:
```
iauditor_exporter --list_preferences template_3E631E46F466411B9C09AD804886A8B4
```

Multiple template IDs can be passed, separated by a space

### How to maintain multiple configurations

You may want to maintain multiple export configurations in different YAML configuration files. To use a specific configuration file (other than config.yaml) do

```
iauditor_exporter --config=/path/to/alternate_config.yaml
```
Note that you can supply a relative or absolute path to an alternate_config.yaml if it is in another directory

Arguments can be combined e.g. -
```
iauditor_exporter --config=alternate_config.yaml --format pdf json
```

### Troubleshooting

#### Nothing gets exported

Your API key may be missing or has expired. Generate a new API token from the iAuditor web application or using the iAuditor API and replace it in the config.yaml file of the top-level directory of this repository. Ensure your API key corresponds to a SafetyCulture account that contains the audits you want to export.

#### Some audits failed to transfer

If an audit failed to transfer the export process will not stop, it will simply record the failure in the log file and continue. You can find the log files under the log/ directory. To retry a failed audit export you can reset the export start date as shown in "Setting the export start date" below.

#### pdf documents have placeholder images, or docx documents won't open

Sometimes media on an audit can take longer to sync than the rest of the data.  Increasing the value of the media_sync_offset_in_seconds config setting can improve this.

#### Re-setting the export start date

Once you have successfully used this tool to extract audit reports, the next time you run it it will only export reports modified or completed since the last time it ran. To reset the export start date edit or delete the file last_successful.txt generated by the exporter tool in this directory. The time is UTC in ISO 8061 format (example: 2016-10-20T05:19:18.352Z).

IMPORTANT: Exporting large numbers of audits in bulk over and over again may result in your account being throttled or your API token revoked.

### The Import Global Response Sets (GRS) tool

This tool helps maintain Global Response Sets up to date by importing them automatically from a Microsoft Excel spreadsheet (xls or xlsx, version 2 or higher).

To import response sets from a spreadsheet file:
```
import_grs --token <YOUR_IAUDITOR_API_TOKEN> --file <FULL_PATH_TO_SPREADSHEET_FILE>
```
Each sheet in the Excel file will correspond to one Global Response Set. Any Global Response Set that exists in your account which has a name that does not match a sheet in the Excel file will not be affected. The name of the sheet will correspond to the name of the Global Response Set.  Please note that if you name a sheet exactly the same as a currently existing Global Response Set, that Global Response Set will be modified - including deletion of any responses that don't exist in the Excel file.

The tool is case-sensitive - if you have 'city names' and 'City Names' as separate sheet names, a new Global Response Set will be created for each. Similarly, if you want to manage an existing Global Response Set, ensure you name the sheet exactly as it appears in the response set, including capitalization.
A single column per sheet is required, each cell in that column will correspond to the label of a response.

To update your Global Response Set, add one or more rows to the spreadsheet. To delete from your Global Response Set, just delete the relevant rows from the spreadsheet.

Caveat: deleting a response, and then re-adding the same response later will result in iAuditor Analytics dashboard treating these as different responses. This is because the new response will have a different internal identifier than the deleted response had. To update a response while keeping the same internal identifier you will need to use the response set API directly, instead of this tool. See the iAuditor developer portal for more details.

### The Export Users tool

This tool exports a list of users and their groups from iAuditor into a CSV file named `iauditor_users.csv`. To use this tool you need to have Admin permissions in the organisation.

To run it:
Open a command-line terminal and navigate to the directory called `safetyculture-sdk-python/tools/export_users`.
Run the following command:
```
python export_users.py --token <YOUR_IAUDITOR_API_TOKEN>
```
The exported CSV file will be saved in the current working directory. If the file already exists, it is overwritten.

The exported CSV file columns contain the following user information and structure:
- email
- lastname
- firstname
- groups

| email| lastname| firstname| groups|
|---|---|---|---|
<EMAIL_ADDRESS>|Smith|John|Group 1, Group 2|
<EMAIL_ADDRESS>3|
<EMAIL_ADDRESS>|

The field `groups` contains a comma-separated list of all iAuditor groups the user is a member of. All fields are string values.
Note: Group names that contain commas are not supported. If a group name contains a comma, no user will be assigned to it and you may see errors in the logs.

### The Sync Users tool

This tool updates the organisation users in iAuditor from a CSV file. After running this tool, users in iAuditor and their corresponding groups will match the contents of the CSV file. The groups specified in the CSV file must have been created in iAuditor before running the tool. If a group doesn't exist, the user will not be added to that group. To use this tool you need to have Admin permissions in the organisation.

Caveat: Any users added in iAuditor without using this tool which are not listed in the CSV file, will be removed from iAuditor after running this tool. If you want to keep all users, run the Export Users tool and modify the file that is generated to reflect the desired user state.

The input file specified in the command line arguments has the following structure:

| email| lastname| firstname| groups|
|---|---|---|---|
<EMAIL_ADDRESS>|Smith|John|Group 1, Group 2|
<EMAIL_ADDRESS>3|
<EMAIL_ADDRESS>|

The first row must contain the column headings and will be ignored by the tool. See `example_user_listing.csv` in `safetyculture-sdk-python/tools/sync_users` for an example.

Any row that contains more than one groups, must surround the list of groups with double quotes.

To run the tool:
Open a command-line terminal and navigate to the directory called `safetyculture-sdk-python/tools/sync_users`
Run the following command:
```
python sync_users.py --token <YOUR_IAUDITOR_API_TOKEN> --file <FULL_PATH_TO_CSV_FILE>
```
If the user already exists in the organisation in iAuditor, then the user will be added to all the groups in the `groups` field. If the user is not in iAuditor, the user will be added to iAuditor first and then added to the groups listed in the `groups` field. If no groups are specified, the user is only added to the organisation. If the user is not in the CSV file but is present in iAuditor, the user will be deactivated in iAuditor. If a user already belongs to a group, when that group is removed from the list of groups in the relevant CSV field, the user is removed from that group in iAuditor after running the tool.

### Importing SafetyCulture Python SDK Modules into your own scripts

See example scripts in `./examples/`

### Known Limitations:
1. If two or more groups have the same name, the user will be added to only one of those groups.
2. Adding a user in the CSV when that user exists on the server but is deactivated then the user will not be activated.
3. Adding an already invited user will log an error and have no effect.

## SafetyCulture Python SDK
1. Import `safetypy` into a Python module or Python interpreter:
```
import safetypy
```
2. Create an instance of the SafetyCulture class:
```
sc = safetypy.SafetyCulture(YOUR_IAUDITOR_API_TOKEN)
```
### For more information regarding the Python SDK functionality
1. To open the Python interpreter, run
```
python
```
2. From the Python interpreter, import the Python SDK by running
```
import safetypy
```
3. For an overview of available functionality, run
```
help(safetypy.SafetyCulture)
```

## License

Copyright 2017 SafetyCulture Pty Ltd

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

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

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

repository: SafetyCulture/safetyculture-sdk-python

gha_language: Python

repo_name: SafetyCulture/safetyculture-sdk-python


text:
## SuperFly:  Separating class heirarchy from class definition.
Originally published: 2009-02-15 20:43:57
Last updated: 2009-02-15 20:47:51
Author: Ted Skolnick

This is a recipe for defining class hierarchies outside of class definitions.  This way you could at, runtime, decide what class should act as the parent of a given class.   A class could sometimes have one parent, sometimes another.


text:
# Realistic Rendering Techniques on Parametric Surfaces

The project uses jQuery for UI interactions.

To run the project put the files into a http host. If you run the index.html directly, the browser may give the following exception:
"from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https."

This happens because I followed ES6 rules for javascript. The project designed as modular.

If you run the project with Chrome browser, you can bypass CORS policy by using the following argument:
"--allow-file-access-from-files"


text:
# New ReadMe
https://github.com/Gshell/New ReadMe
# Description
ReadMe Creator
# Table of Contents
* [Installation](#install)
* [Usage](#usage)
* [Contribution](#contribution)
* [Tests](#testing)
# Installation
The following necessary dependencies must be installed to run the application: npm
* [License](#license)
# Usage
In order to use this app,
# License
This project is licensed under the MIT license.
![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)
# Contributing
Contributors: please reach out to me on github or email
# Tests
The following is needed to run the test:
# Questions
If you have any questions about the repo, open an issue or contact Gshell directly at<EMAIL_ADDRESS>

repository: GrantShell/ReadMeGenerator

repo_name: GrantShell/ReadMeGenerator


text:
# Create New Chain

The first chain of the entire system was created by the development team, and the creation process is the same as other blockchain systems.
All other chains are created through "Creating Chain Transaction".
Each chain allows the creation of 2 child chains, as long as the conditions are met, anyone can create them.
There are no restrictions on the creation of the second and third chains, and anyone can create them at any time.
The creation of subsequent chains needs to meet the following conditions:

1. The average block size of the chain is greater than 300K (recent average), avoiding unlimited creation.
2. Tokens need to be spent. The maximum amount of tokens is 10,000 times the block reward. The larger the average block size, the lower the cost.
3. A child chain does not exist when it is created.
4. Create the left child chain first, then the right child chain.

repository: govm-net/docs

repo_name: govm-net/docs


text:
# ResponsiveImageBundle

[![Build Status](https://travis-ci.org/irishdan/ResponsiveImageBundle.svg?branch=master)](https://travis-ci.org/irishdan/ResponsiveImageBundle)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/irishdan/ResponsiveImageBundle/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/irishdan/ResponsiveImageBundle/?branch=master)

## Overview:

The ResponsiveImageBundle adds the ability to easily create styled and responsive images (scaled, cropped, greyscale) in Symfony3.
Responsive images are generated as <picture> tags or as <mg> tags with sizes and scrset attributes.

A crop and focus area widget is also provided to ensure that cropped images always include the most important part of the image.

The bundle uses [FlySystem](http://flysystem.thephpleague.com/) filesystem abstraction layer giving you control over where images are stored.
Events are used to drive the system, giving more flexibiltiy and the ability to implement queuing of intensive image processing.

## Features

- Image objects are stored via Doctrine ORM
- Handles uploading images to a "[FlySystem](http://flysystem.thephpleague.com/)" filesystem
- Images styles are defined in configuration.
- Breakpoints and pictures sets are defined in configuration
- Handles creation of styled images on the fly (as they are viewed) if using a local filesystem
- Includes a widget to define an image's crop and focus areas giving art direction to styled images

## Quick and basic setup

Out of the box, ResponsiveImage bundle should work with minimal configuration.

### Step 1: Download, enable the bundle and import its services and configuration

Download with composer
```
composer require irishdan/responsive-image-bundle
```
Enable the bundle and OneupFlysystem in the kernel
```php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new IrishDan\ResponsiveImageBundle\ResponsiveImageBundle(),
        new Oneup\FlysystemBundle\OneupFlysystemBundle(),
    );
}
```

### Step 2: Import its services, default configuration and the local image routing

Import responsive image services, default and filesystem configuration.
```
imports:
    - { resource<EMAIL_ADDRESS>}
    - { resource<EMAIL_ADDRESS>}
    - { resource<EMAIL_ADDRESS>}
```

Import the routing for local on the fly image generation.

```yml
responsive_image:
    resource<EMAIL_ADDRESS>    prefix:   /
```

### Step 3: [Install](Resources/doc/installation.md) the bundle and [generate](Resources/doc/commands.md) a [ResponsiveImage entity](Resources/doc/entities.md) and it's CRUD.

```php
php bin/console responsive_image:generate:entity
php bin/console responsive_image:generate:crud
```
With the generated image [entity](Resources/doc/entities.md) and CRUD you can now, create and [upload](Resources/doc/uploading.md) images, apply '[art direction](Resources/doc/art-direction.md)' to images.

### Step 4: Define some image styles in your [configuration](Resources/doc/configuration.md) file. (Usually config.yml)

```yml
responsive_image:
    image_styles:
        groovy_thumbnail_style:
            effect: crop
            width: 180
            height: 180
        groovy_thumbnail_style_base:
            effect: scale
            width: 240
        groovy_thumbnail_style_mobile:
            effect: scale
            height:480
        groovy_thumbnail_style_mobile:
            effect: crop
            width: 200
            height: 300
            greyscale: true

```
You can now [render](Resources/doc/rendering.md) a styled in your twig template like so:
 ```
    {{ styled_image(image, 'groovy_thumbnail_style') }}

 ```
### Step 5: Define some breakpoints and "picture sets"

```yml
breakpoints:
    base:
        media_query: 'min-width: 0px'
    mobile:
        media_query: 'min-width: 300px'
    desktop:
        media_query: 'min-width: 1100px'
    groovey_picture_set:
        fallback: 'groovy_thumbnail_style'
        sources:
            base: groovy_thumbnail_style_base
            mobile: groovy_thumbnail_style_mobile
            desktop: groovy_thumbnail_style_desktop

```
You can now render <picture> [responsive images](Resources/doc/rendering.md) or render [responsive background image css](Resources/doc/rendering.md) in twig templates

```
<head>
    {{ background_responsive_image(image, 'picture_set_name', '#header') }}
</head>
<body>
    {{ picture_image(image, 'groovey_picture_set') }}
</body>
```

### Step 6: Define some size sets

```yml
responsive_image:
    size_sets:
        blog_sizes:
            fallback: 'groovy_thumbnail_style_base'
            sizes:
                10vw:
                    breakpoint: 'mobile'
            srcsets: [ 'groovy_thumbnail_style_mobile', 'groovy_thumbnail_style_desktop' ]

```
You can now render <img> [responsive images](Resources/doc/rendering.md) width srcset and sizes attributes in twig templates.

```
    {{ sizes_image(image, 'blog_sizes') }}
```

## Documentation

- [Installation and Setup](Resources/doc/installation.md)
- [Filesystems](Resources/doc/filesystem.md)
- [Image entities](Resources/doc/entities.md)
- [Uploading](Resources/doc/uploading.md)
- [Styled image generation](Resources/doc/styled-image-generation.md)
- [Image rendering](Resources/doc/rendering.md)
- [Art Direction](Resources/doc/art-direction.md)
- [Commands](Resources/doc/commands.md)
- [Configuration](Resources/doc/configuration.md)
- [Urls](Resources/doc/urls.md)
- [Events](Resources/doc/events.md)
- [Tests](Resources/doc/test.md)

## Attribution

- [Intervention](http://image.intervention.io/) is the standalone PHP Imagine Library is used by this bundle for image transformations
- [OneupFlysystemBundle](https://github.com/1up-lab/OneupFlysystemBundle) which used [Flysystem](https://flysystem.thephpleague.com/) filesystem astraction library, is required by this bundle
- The CropFocus art direction widget javascript was created by following this [TutsPlus tutorial](http://code.tutsplus.com/tutorials/how-to-create-a-jquery-image-cropping-plugin-from-scratch-part-i--net-20994)

repository: irishdan/ResponsiveImageBundle

repo_name: irishdan/ResponsiveImageBundle


text:
---
title: How to generate a random string with given length in JavaScript
tags:
    - JavaScript
    - ES6
    - one-line
    - js
    - Random
layout: note
---

In this Article we will go through how to generate a random string with given length only using single line of code in JavaScript.
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => `Arrow Function`.

Let's define this short function:

```js {.wrap}
const generateString = length => Array(length).fill('').map((v) => Math.random().toString(36).charAt(2)).join('');
```


text:
# Starlight VM internals

## Memory management

Starlight uses tracing GC for memory management and implements Mark&Sweep algorithm. Read more in [gc/gc.md](gc/gc.md)

## Execution pipeline

Starlight has a multi-tiered execution pipeline. First function code is interpreted in our interpreter called `photon` for fast startup and after a few hunderds loop iteration or function calls it will be JITed to native code for high throughput.


text:
## Valueset Creation
This little python program takes in a csv of codes and code titles and outputs a json file with the codes in the valueset format.

#### Example Input (csv format)
```
Code,Code Title
237620003,Abnormal metabolic state due to diabetes mellitus (disorder)
735200002,Absence of lower limb due to diabetes mellitus (disorder)
...
```

#### Example Output (json)
```
[
    {
        "system": "http://snomed.info/sct",
        "code": "237620003", "display":
        "Abnormal metabolic state due to diabetes mellitus (disorder)"
    },
    {
        "system": "http://snomed.info/sct",
        "code": "735200002",
        "display": "Absence of lower limb due to diabetes mellitus (disorder)"
    }
    ...
]
```

### Developer Setup
#### Set up with `virtualenv`
1. Install Python 3.8 on your machine
2. Create a virtualenv for your installation
```shell script
cd valueset-creation
virtualenv --python=python3 .venv
source .venv/bin/activate
```
3. Install Requirements
```shell script
pip3 install -r requirements.txt
```

#### Set up with `pyenv`
1. `pyenv install 3.8.0`
2. `pyenv virtualenv 3.8.0 <name_of_environment>`
3. `source ~/.pyenv/versions/<name_of_environment>/bin/activate`
4. `pip3 install -r requirements.txt`

### Steps to generate valueset output
1. Create a csv of Codes & Code Titles and put it in the `valueset-creation/input` folder.
2. Update the filename on line 25 of `program.py` to the name of the csv you just created.
3. Run `python3 program.py` from the `valueset-creation` directory.
4. Output will appear here: `valueset-creation/output/data.json`.
5. You can then use the output when creating a valueset in the `input/vocabulary/ValueSet` directory by copying and pasting it into the `"contains"` array of the valueset.
```
{
...
    "contains": [
            {
                "system": "http://snomed.info/sct",
                "code": "237620003", "display":
                "Abnormal metabolic state due to diabetes mellitus (disorder)"
            },
            {
                "system": "http://snomed.info/sct",
                "code": "735200002",
                "display": "Absence of lower limb due to diabetes mellitus (disorder)"
            }
            ...
        ]
}
```
*See other valuesets to reference how they are structured and where to copy/paste the output, i.e.: `input/vocabulary/ValueSet/valueset-covid-19-condition-risk-obstructive-sleep-apnea-icd10.json`

##### Note:
This program hard-codes the `"system"` value in the output to `"http://snomed.info/sct"` but it can be updated on line 13 of `program.py`

repository: Bondzio/covid-ed-ig

repo_name: Bondzio/covid-ed-ig


text:
# Twee 4.0

**Twee** is the advanced WordPress starter theme focused on simplifying the theme development and support

## Features

* Asset management library allowing to manage scripts, stylesheets, and localization strings
* Resize and cache thumbnails with or without registering a new image size
* Base widget class with custom settings
* Taxonomy and terms processing libraries
* Breadcrumbs with built-in JSON-LD and microdata support
* Pagination with custom query support
* Modules to load more posts and process the contact form with attachments
* One file configuration. It allows you to specify all your image sizes, assets, menu locations, sidebars, custom post types, taxonomies, and other things in
  one place

## About

Author: Andrii Toniievych

Contact: [toniyevych<EMAIL_ADDRESS>
Feel free to contact me if you have any questions.

## Contribution

* Fork this repository
* Commit your changes
* Push it to the branch
* Create the new pull request

## License

**Twee** is released under the MIT Public License.

Note: The "About" section in `README.md` and the author (`@author`) notice in the file-headers shall not be edited or deleted without permission. Thank you!

repository: TwistedAndy/wp-theme

repo_name: TwistedAndy/wp-theme


text:
# Log Services

## Concepts

### ILogService
`ILogService` is the main touch-point for the projects. It provides several methods to log such as: `Info`,`Warn`,`Error`,`Exception`.

### ILogHandler
By itself `ILogService` doesn't do anything. You must add `ILogHandler`s as necessary. This allows each project to specify how and when, exactly logs are produced. For example, you may want to write Info and Warnings to the log, but send any Exceptions to a web-service for collection.

``` csharp
public class OnlyExceptionsLogHandler : ILogHandler
{
    public void Exception(Exception exception)
    {
        UnityEngine.Debug.LogException(exception);
    }

    public void Error(string message) {}
    public void Info(string message) {}
    public void Warn(string message) {}
}

// Add to service...
_logService.AddHandler(new OnlyExceptionsLogHandler());
```

repository: Antihero-Studios/log-services

repo_name: Antihero-Studios/log-services


text:
# pipeline-application

## Usage

Changes pushed to any branch except master should trigger the following actions:

  - build a container image tagged with the build ID suitable for deploying to a staging cluster
  - clone the [pipeline-application-infra-staging](https://github.com/dellintosh/pipeline-application-infra-staging) repo
  - patch the pipeline deployment configuration file with the staging container image and commit the changes to the `pipeline-application-infra-staging` repo

> The `pipeline-application-infra-staging` repo will deploy any updates committed to the master branch.

Tagging this repo should trigger the following actions:

  - build a container image tagged with the tag name suitable for deploying to a qa cluster
  - clone the [pipeline-application-infra-qa](https://github.com/dellintosh/pipeline-application-infra-qa) repo
  - patch the pipeline deployment configuration file with the qa container image and commit the changes to the `pipeline-application-infra-qa` repo

> The `pipeline-application-infra-qa` repo will deploy any updates committed to the master branch and issue a pull request to the `pipeline-application-infra-production` repo

See the [.drone.yml](.drone.yml) file for more details.

repository: dellintosh/pipeline-application

repo_name: dellintosh/pipeline-application


text:
# Krabby Pizza
#### An online pizza store that allows you to design and order pizzas, 17/04/2020
#### By **Collin Owino**
## Description
Krabby Pizza is an online store that allows you to order custom pizzas. It has a menu of crusts and toppings with prices for different pizza sizes you may want. Through the app you can design as many pizzas as you want, place an order, see your order summary and cost, choose whether to have it delivered, and see the grand total charge for your orders.
## Use/Run Requirements
* Visit Krabby Pizza at https://collin9726.github.io/krabbyPizza/ .
* Name your Pizza, choose one size and one crust for each pizza and add at least one topping.
* Add as many pizzas as you want then check out.
* Choose whether to have your orders delivered.

## Known Bugs
No bugs noted as yet.
## Technologies Used
Krabby Pizza has been built with HTML5, CSS, JavaScript, jQuery and Bootstrap. JavaScript and jQuery make the app interactive. Bootstrap makes it responsive, HTML structures the website and CSS gives it the final aesthetics. Standard syntax and indentation has been used all through in accordance with coding best practices. Version control has been made thus far through Git. The box model has largely been applied using divs to structure and style the website.
## Support and contact details
Feel free to send us a message through the email<EMAIL_ADDRESS>whenever you have any inquiries, notice any bugs or have a feedback to give. We at Krabby Pizza appreciate your feedback and will get back to you soonest possible. Looking forward to your reviews.
### [License](LICENSE.md)
MIT
Copyright (c) 2020 **Collin Owino**


text:
# Todo

These are the steps defined to reach 1.0. Assistance is very welcome.

- [x] Handle mutually exclusive fields
- [ ] Refactor the various NodeFactory modules to be a less confusing
      hierachical structure. Consider having factories subclass instead of use
      mixin
- [x] Decouple Document class for the source file. Consider a source file class
      instead
- [x] Validate that a reference creates the type of node that is expected in
      a context
- [x] Allow opening of references from additional files
- [x] Allow opening of openapi documents by URL
- [x] Support references by URL
- [ ] Consider option to limit open by URL/path behaviour
- [x] Support converting CommonMark to HTML
- [ ] Reach parity with OpenAPI specification for validation
- [ ] Consider a lenient mode for a document to only have to comply with type
      based validation
- [ ] Improve test coverage
- [ ] Publish documentation of the interface through the structure
- [x] Consider a resolved context class for representing context with a node
      that can handle scenarios where a node is represented by both a reference
      and resolved context
- [ ] Create error classes for various scenarios
- [ ] Associate/resolve operation id / operation references
- [ ] Do something to model expressions
- [x] Improve the modelling of namespace
- [ ] Set up nicer string representations of key classes to help them be
      debugged
- [x] Ensure Array and Map nodes return empty ones by default rather than nil
- [ ] Make JSON pointer public access to be consistent accepting string, array
      or (potentially) a pointer class
- [ ] Support creating a default Server object on servers property of OpenAPI
      Node
- [ ] Support relative URLs being able to be relative the first server object
      see: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#relative-references-in-urls
- [ ] Support validating a Server URL based on default values
- [ ] Validate paths to check path parameters within them appear in paths
      see: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#fixed-fields-10


text:
# DolphinScheduler E2E Automation Test

## I. Preparatory knowledge

### 1. The difference between E2E Test and Unit Test

E2E, which stands for "End to End", can be translated as "end-to-end" testing. It imitates the user, starting from a certain entry point and progressively performing actions until a certain job is completed. And unit tests are different, the latter usually requires testing parameters, types and parameter values, the number of arguments, the return value, throw an error, and so on, the purpose is to ensure that a specific function to finishing the work is stable and reliable in all cases. Unit testing assumes that if all functions work correctly, then the whole product will work.

In contrast, E2E test does not emphasize so much the need to cover all usage scenarios, it focuses on whether a complete chain of operations can be completed. For the web front-end, it is also concerned with the layout of the interface and whether the content information meets expectations.

For example, E2E test of the login page is concerned with whether the user is able to enter and log in normally, and whether the error message is correctly displayed if the login fails. It is not a major concern whether input that is not legal is processed.

### 2. Selenium test framework

[Selenium](https://www.selenium.dev) is an open source testing tool for executing automated tests on a web browser. The framework uses WebDriver to transform Web Service commands into browser native calls through the browser's native components to complete operations. In simple words, it simulates the browser and makes selection operations on the elements of the page.

A WebDriver is an API and protocol which defines a language-neutral interface for controlling the behavior of a web browser.  Every browser has a specific WebDriver implementation, called a driver. The driver is the component responsible for delegating to the browser and handling the communication with Selenium and the browser.

The Selenium framework links all these components together through a user-facing interface that allows transparent work with different browser backends, enabling cross-browser and cross-platform automation.

## II. E2E Test

### 1. E2E-Pages

DolphinScheduler's E2E tests are deployed using docker-compose. The current tests are in standalone mode and are mainly used to check some basic functions such as "add, delete, change and check". For further cluster validation, such as collaboration between services or communication mechanisms between services, refer to `deploy/docker/docker-compose.yml` for configuration.

For E2E test (the front-end part),  the [page model](https://www.selenium.dev/documentation/guidelines/page_object_models/) form is used, mainly to create a corresponding model for each page. The following is an example of a login page.

```java
package org.apache.dolphinscheduler.e2e.pages;

import org.apache.dolphinscheduler.e2e.pages.common.NavBarPage;
import org.apache.dolphinscheduler.e2e.pages.security.TenantPage;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import lombok.Getter;
import lombok.SneakyThrows;

@Getter
public final class LoginPage extends NavBarPage {
    @FindBy(id = "inputUsername")
    private WebElement inputUsername;

    @FindBy(id = "inputPassword")
    private WebElement inputPassword;

    @FindBy(id = "btnLogin")
    private WebElement buttonLogin;

    public LoginPage(RemoteWebDriver driver) {
        super(driver);
    }

    @SneakyThrows
    public TenantPage login(String username, String password) {
        inputUsername().sendKeys(username);
        inputPassword().sendKeys(password);
        buttonLogin().click();

        new WebDriverWait(driver, 10)
            .until(ExpectedConditions.urlContains("/#/security"));

        return new TenantPage(driver);
    }
}
```

During the test process, we only test the elements we need to focus on, not all elements of the page. So on the login page only the username, password and login button elements are declared. The FindBy interface is provided by the Selenium test framework to find the corresponding id or class in a Vue file.

In addition, during the testing process, the elements are not manipulated directly. The general choice is to package the corresponding methods to achieve the effect of reuse. For example, if you want to log in, you input your username and password through the `public TenantPage login()` method to manipulate the elements you pass in to achieve the effect of logging in. That is, when the user finishes logging in, he or she jumps to the Security Centre (which goes to the Tenant Management page by default).

The SecurityPage provides goToTab methods to test the corresponding sidebar jumps, mainly including TenantPage, UserPage, WorkerGroupPage and QueuePage. These pages are implemented in the same way, mainly to test whether the input, add and delete buttons of the form can return to the corresponding page.

```java
public <T extends SecurityPage.Tab> T goToTab(Class<T> tab) {
       if (tab == TenantPage.class) {
           WebElement menuTenantManageElement = new WebDriverWait(driver, 60)
                   .until(ExpectedConditions.elementToBeClickable(menuTenantManage));
           ((JavascriptExecutor)driver).executeScript("arguments[0].click();", menuTenantManageElement);
           return tab.cast(new TenantPage(driver));
       }
       if (tab == UserPage.class) {
           WebElement menUserManageElement = new WebDriverWait(driver, 60)
                   .until(ExpectedConditions.elementToBeClickable(menUserManage));
           ((JavascriptExecutor)driver).executeScript("arguments[0].click();", menUserManageElement);
           return tab.cast(new UserPage(driver));
       }
       if (tab == WorkerGroupPage.class) {
           WebElement menWorkerGroupManageElement = new WebDriverWait(driver, 60)
                   .until(ExpectedConditions.elementToBeClickable(menWorkerGroupManage));
           ((JavascriptExecutor)driver).executeScript("arguments[0].click();", menWorkerGroupManageElement);
           return tab.cast(new WorkerGroupPage(driver));
       }
       if (tab == QueuePage.class) {
           menuQueueManage().click();
           return tab.cast(new QueuePage(driver));
       }
       throw new UnsupportedOperationException("Unknown tab: " + tab.getName());
   }
```

![SecurityPage](../../../img/e2e-test/SecurityPage.png)

For navigation bar options jumping, the goToNav method is provided in `org/apache/dolphinscheduler/e2e/pages/common/NavBarPage.java`. The currently supported pages are: ProjectPage, SecurityPage and ResourcePage.

```java
    public <T extends NavBarItem> T goToNav(Class<T> nav) {
        if (nav == ProjectPage.class) {
            WebElement projectTabElement = new WebDriverWait(driver, 60)
                .until(ExpectedConditions.elementToBeClickable(projectTab));
            ((JavascriptExecutor)driver).executeScript("arguments[0].click();", projectTabElement);
            return nav.cast(new ProjectPage(driver));
        }

        if (nav == SecurityPage.class) {
            WebElement securityTabElement = new WebDriverWait(driver, 60)
                .until(ExpectedConditions.elementToBeClickable(securityTab));
            ((JavascriptExecutor)driver).executeScript("arguments[0].click();", securityTabElement);
            return nav.cast(new SecurityPage(driver));
        }

        if (nav == ResourcePage.class) {
            WebElement resourceTabElement = new WebDriverWait(driver, 60)
                .until(ExpectedConditions.elementToBeClickable(resourceTab));
            ((JavascriptExecutor)driver).executeScript("arguments[0].click();", resourceTabElement);
            return nav.cast(new ResourcePage(driver));
        }

        throw new UnsupportedOperationException("Unknown nav bar");
    }
```

### E2E-Cases

Current E2E test cases supported include: File Management, Project Management, Queue Management, Tenant Management, User Management, Worker Group Management and Workflow Test.

![E2E_Cases](../../../img/e2e-test/E2E_Cases.png)

The following is an example of a tenant management test. As explained earlier, we use docker-compose for deployment, so for each test case, we need to import the corresponding file in the form of an annotation.

The browser is loaded using the RemoteWebDriver provided with Selenium. Before each test case is started there is some preparation work that needs to be done. For example: logging in the user, jumping to the corresponding page (depending on the specific test case).

```java
@BeforeAll
public static void setup() {
    new LoginPage(browser)
            .login("admin", "dolphinscheduler123")
            .goToNav(SecurityPage.class)
            .goToTab(TenantPage.class)
    ;
}
```

When the preparation is complete, it is time for the formal test case writing. We use a form of @Order() annotation for modularity, to confirm the order of the tests. After the tests have been run, assertions are used to determine if the tests were successful, and if the assertion returns true, the tenant creation was successful. The following code can be used as a reference:

```java
    @Test
    @Order(10)
    void testCreateTenant() {
        final TenantPage page = new TenantPage(browser);
        page.create(tenant);

        await().untilAsserted(() -> assertThat(page.tenantList())
                .as("Tenant list should contain newly-created tenant")
                .extracting(WebElement::getText)
                .anyMatch(it -> it.contains(tenant)));
    }
```

The rest are similar cases and can be understood by referring to the specific source code.

https://github.com/apache/dolphinscheduler/tree/dev/dolphinscheduler-e2e/dolphinscheduler-e2e-case/src/test/java/org/apache/dolphinscheduler/e2e/cases

## III. Supplements

When running E2E tests locally, First, you need to start the local service, you can refer to this page:
[development-environment-setup](./development-environment-setup.md)

When running E2E tests locally, the `-Dlocal=true` parameter can be configured to connect locally and facilitate changes to the UI.

When running E2E tests with `M1` chip, you can use `-Dm1_chip=true` parameter to configure containers supported by
`ARM64`.

![Dlocal](../../../img/e2e-test/Dlocal.png)

If a connection timeout occurs during a local run, increase the load time to a recommended 30 and above.

![timeout](../../../img/e2e-test/timeout.png)

The test run will be available as an MP4 file.

![MP4](../../../img/e2e-test/MP4.png)

repository: parampavar/incubator-dolphinscheduler

branch_name: refs/heads/dev

gha_language: Java

repo_name: parampavar/incubator-dolphinscheduler


text:
The bigcloud framework consists of two spaces

1. Backend Space
2. Clientend Space
3.  There are also mongoDB,couchDB
backend for  aggregating the analytics and user activity logs from Hadoop based middleware. This
middleware uses machine learning tools (mahout, jubatus). The Backend web app is modulerized so
that its easier to integrate the facebook graph, gcm console, kakao people, nhn sdk, gree sdk, dena sdk apis.

Clientend consists of Android, Blackberry, iOS, Bada client, Web integration SDKs.

MIT License

repository: claymodel/bigcloud

repo_name: claymodel/bigcloud


text:
#Analysis Directions:
##Software Dependencies:
* **[EnergyPlus 8.1](http://apps1.eere.energy.gov/buildings/energyplus/energyplus_about.cfm)**
* **OpenStudio 1.5.1, 1.5.2, or 1.5.3**
	* [Download OpenStudio 1.5.1 here](http://developer.nrel.gov/downloads/buildings/openstudio/builds/)
    * Make sure that you select the Windows version not the 64bit version (For example, for the 1.5.1, the donwloaded file has `OpenStudio-<IP_ADDRESS>c740efe7c-Windows.exe` name)
* **Ruby 2.0.0**
    * [Download Ruby 2.0.0 here](https://www.ruby-lang.org/en/documentation/installation/)
    * Make sure that you select the regular version of the ruby 2.0.0-p598 version not the 64bit version (The donwloaded file has this name: `rubyinstaller-2.0.0-p598`)
    * During the installation make sure thay you check the 2nd and 3rd boxes to add ruby to the environmental paths and assocaited files.
    * If you select the 64bit versions for the OpenStudio and ruby, OpenStudio will show a Win32 error message.
    * add *Ruby200\bin* to the [path Environmental Variable](http://en.wikipedia.org/wiki/Environment_variable)
* **OpenStudio gem**
    * add a file **openstudio.rb** to *Ruby\lib\ruby\site_ruby* with this in it (Windows machine):
```ruby
require 'C:\Program Files (x86)\OpenStudio 1.5.1\Ruby\openstudio.rb'
```
* **minitest 5.4.2 gem or greater**
    * [Download minitest 5.4.2](https://rubygems.org/gems/minitest/versions/5.4.2)
    * Put the file in the `C:\Ruby200\lib\ruby\gems\2.0.0\gems`
    * Go to the command line and navigate to the folder
    * Type `gem install minitest-5.4.2.gem`
    * You should see a new folder *minitest-5.4.2*

* **R, recommend RStudio 0.98.1083 or greater**
	* [Download RStudio](http://www.rstudio.com/products/RStudio/)
	* Install packages DBI, grid, gridExtra, gsubfn, ggplot2, proto, reshape2, RSQLite, scales, sqldf, tcltk, zoo

##Folders:
* **autosize_measure**
 contains the autosizing measure to hard size HVAC equipment to values from a prior simulation run.

* **base_scripts**
 contains the base scripts for building a ruby run manager call.

* **energyplus_additions**
 contains .idf file output requests for environmental impact, utility rates, and load component summaries.

* **lib**
 contains R functions for recursion, permutation, net present value, etc.

* **measures**
 contains the ruby script implementation for each R measure.

* **model**
 contains the base openstudio model

* **run_scripts**
 contains the run scripts for each unique simulation.

* **weather**
 contains the weather file

##Run these files in order:
1.  **RetrofitPermute.R**
 Reads in measure names and generates all possible permutations.
 A copy of the list replaces permutations with combinations with identical simulation results.  E.g., if to measures are independent, then ab = ba, whereas for a third, independent measure c, ac <> ca.  This copy is a "map" to back to the original permutation.  Finally, only unique simulations in the map are identified for simulation.  Saves permutation list, map, simulations required, and cost array to an .RData file.

2.  **run_generation.rb**
 Takes in a text file of a measure table, with a corresponding letter lookup, and a text file of the unique simulations needed.  It writes a run manager ruby script for each unique simulation. If a measure is dependent on preceding simulations, it will hardsize the equipment based on the .eio file of the prior simulation.

3.  **run_master.rb**
 Runs all the ruby scripts for each unique simulation, and deletes extraneous files after each simulation.

4.  **ResultsReader.R**
 Reads in the simulation results and saves them to an .RData file.

5.  **ResultsConstruction.R**
 Takes in the simulation results and duplicate simulation mapping file.
 Creates cash flows for each permutation, based on a capital constraint.
 Saves these in data frames to the results folder under run_scripts

6.  **RetrofitCharts.R**
 Takes in the data frames from ResultsConstruction and uses them to produce graphics

7.  **ResultsReaderSingleSimulation.R**
 Reads in the simulation results for a single simulation generates load component information and energy use breakdown.

repository: CITY-at-UMD/retrofitLCC

repo_name: CITY-at-UMD/retrofitLCC


text:
About this site
==============================================

The primary focus of this site is:

<img class="lizard" src="http://www.student.bth.se/~pica16/dbwebb-kurser/htmlphp/me/kmom06/me6/img/the-noble-lizard-300px.png" width="240px" style="float: right">

* To be help me learn web design in the [dbwebb course design](http://dbwebb.se/design).

The original source for this site is available on GitHub in [canax/anax-flat](git@github.com:canax/anax-flat.git).

The specific source for my site can be found on
[GitHub](https://github.com/dog8001/anax-flat)

The specific source for my theme can be found on
[GitHub](https://github.com/dog8001/anax-flat-theme)

This site is produced by [Pierre Carlsson](http://www.student.bth.se/~pica16/dbwebb-kurser/htmlphp/me/kmom06/me6/me.php) (carlsson.pierre@gmail.com).


text:
# Documents for C++ base library CO

Translated by [daidai21](https://github.com/daidai21).

## 15. Coroutine library(co)

include: [base/co.h](https://github.com/idealvin/co/blob/master/base/co.h).

### 15.1 Basic Concepts

- Coroutines are lightweight scheduling units that run in threads.
- The thread coroutine runs in is called a scheduling thread.
- There can be multiple coroutine scheduling threads in a process, and different scheduling threads are independent of each other.
- There can be multiple coroutines in a scheduling thread, but at most one coroutine runs at the same time.
- When a coroutine suspends, the scheduling thread automatically switches to another coroutine in that thread.
- Coroutine switching is performed in user mode, which is faster than switching between threads.

Coroutines are very suitable for writing network programs. It's one of the best way for network programming. It writes code in a synchronous manner without nested asynchronous callbacks, which greatly reduces the programmer's thinking burden.

The `co` coroutine library implements a [golang](https://github.com/golang/go/) style coroutine with the following features:

- Built-in multiple coroutine scheduling threads, default is the number of system CPU cores.
- Coroutines in the same thread share a stack. When a coroutine is suspended, the data on the stack will be saved to the coroutine, and the data will be restored to the stack when it is switched back. This method greatly reduces the memory footprint and millions of coroutines can be easily created on a single machine.
- Coroutine can be created anywhere (including in another coroutine).

The co coroutine library is based on [epoll](http://man7.org/linux/man-pages/man7/epoll.7.html), [kqueue](https://man.openbsd.org/kqueue.2), [iocp](https://docs.microsoft.com/en-us/windows/win32/fileio/io-completion-ports) implementation.

The relevant code for context switching in the co coroutine library is taken from [tbox](https://github.com/tboox/tbox/), while tbox refers to [boost context](https://www.boost.org/doc/libs/1_70_0/libs/context/doc/html/index.html), thanks!

### 15.2 Create coroutines (go)

`Golang` uses the keyword `go` to create coroutines. Similarly, the co library provides the `go()` method to create coroutines.

Creating a coroutine is similar to creating a thread. You need to specify a coroutine function. The first parameter of the `go()` method is the coroutine function:

```cpp
void go(void (*f)());
void go(void (*f)(void*), void* p);  // p specifies function parameters

template<typename T>
void go(void (T::*f)(), T* p);       // p binds a class T object

void go(const std::function<void()>& f);
```

Actual tests found that creating objects of type `std::function` is expensive, so go() is especially optimized for function types `void f()`,` void f(void *)`, `void T::f() `. In practical applications, these three types of functions should be used preferentially.

Strictly speaking, the go() method just allocates a `callback` to a scheduling thread. The actual creation of the coroutine is done by the scheduling thread. However, from the user's point of view, it can be logically considered that go() creates a coroutine and assigns it to a designated scheduling thread, waiting to be executed.

- Code example

```cpp
go(f);                       // void f();
go(f, p);                    // void f(void*);   void* p;
go(&T::f, p);                // void T::f();     T* p;
go(std::bind(f, 7));         // void f(int);
go(std::bind(&T::f, p, 7));  // void T::f(int);  T* p;
```

### 15.3 Coroutine scheduling control

The scheduling of coroutines is done automatically by the scheduling thread, so users do not need to care. Specifically, the scheduling thread does the following:

- Create and launch coroutines.
- Suspend coroutines when blocking.
- Timely wake up coroutines.
- When the coroutine function ends, recycle the coroutine resources.

The user cannot directly control the coroutine, but can control when the coroutine function ends execution. The co library only provides users with two coroutine APIs:

```cpp
void sleep(unsigned int ms); // millisecond
void stop();
```

- When `sleep` is called in a coroutine, the scheduling thread will suspend the current coroutine and switch to other coroutine.
- `stop` does not stop the coroutine, but stops all scheduling threads. Server programs are generally not terminal, and this method is rarely used.

- Code example

```cpp
// print one line "hello world" per second
void f() {
    while (true) {
        co::sleep(1000);
        cout << "hello world" << endl;
    }
}

int main(int argc, char** argv) {
    go(f);          // Start coroutine
    sleep::sec(8);  // Prevent the main thread from exiting immediately
    co::stop();     // Exit all scheduled threads
    return 0;
}
```

### 15.4 socket APIs

CO wraps commonly used socket APIs to support general network programming. All these APIs are in the `namespace co`, which must generally be called in a coroutine. Most of the APIs are basically the same as the native socket APIs, and their usage is almost the same as the native APIs.

When IO is blocked for these APIs, the scheduling thread will automatically suspend the current coroutine and switch to other coroutine execution.

#### 15.4.1 Commonly used socket APIs

CO provides several commonly used socket APIs:

```cpp
sock_t tcp_socket(int v=4); // 4 for ipv4, 6 for ipv6
sock_t udp_socket(int v=4); // 4 for ipv4, 6 for ipv6

close  shutdown   bind   listen   accept   getsockopt
recv   recvfrom   send   sendto   connect  setsockopt

int recvn(sock_t fd, void* buf, int n, int ms=-1);
```

The above APIs are slightly different from the native APIs, as follows:

- The `struct sockaddr*` in the native api parameter was replaced by `void*`, eliminating the need for manual conversion.

- `tcp_socket`, `udp_socket` are used to create sockets. The created sockets are non-blocking on Linux/Mac, and [overlapped](https://support.microsoft.com/en-us/help/181611/socket-overlapped-io-versus-blocking-nonblocking-mode) on Windows.

- `close` can take one more parameter `@ms`(default is 0), suspend the current coroutine for several milliseconds, and then close the socket. This delayed shutdown operation can alleviate continuous illegal attacks to a certain extent.

- `shutdown` specifies the closing direction with a single character `@c`, `'r'` turns off reading,`'w'` turns off writing, both reading and writing are turned off by default.

```cpp
int shutdown(sock_t fd, char c='b');
```

- The socket returned by `accept` is non-blocking or overlapped, and does not need to be set by the user.

- `connect, recv, recvn, recvfrom, send, sendto` can take one more parameter specifying the timeout time `@ms`(default is -1). When a timeout occurs, these APIs return -1 and set errno to `ETIMEDOUT`.

- `recvn` receives `@n` bytes of tcp data, returns n after receiving all, returns 0 when the connection is disconnected, and returns -1 for other errors.

- The above api returns -1 when an error occurs. You can use `co::error()` to get the error code, and `co::strerror()` to see the error description.

#### 15.4.2 Common socket option settings

```cpp
void set_reuseaddr(sock_t fd);                // Setting SO_REUSEADDR
void set_tcp_nodelay(sock_t fd);              // Setting TCP_NODELAY
void set_tcp_keepalive(sock_t fd);            // Setting SO_KEEPALIVE
void set_send_buffer_size(sock_t fd, int n);  // Set send buffer size
void set_recv_buffer_size(sock_t fd, int n);  // Set the receive buffer size
```

#### 15.4.3 Other APIs

```cpp
// Fill ip address
bool init_ip_addr(struct sockaddr_in* addr, const char* ip, int port);
bool init_ip_addr(struct sockaddr_in6* addr, const char* ip, int port);

// ip address to string
fastring ip_str(struct sockaddr_in* addr);
fastring ip_str(struct sockaddr_in6* addr);

// Send a RST to close the TCP connection abnormally to avoid entering the timedwait state. It is mostly used by the server.
// @ms: default is 0, suspend the current coroutine for several milliseconds before resetting the socket
void reset_tcp_socket(sock_t fd, int ms=0);

int error();                    // Returns the current error code
const char* strerror();         // Returns the string corresponding to the current error code
const char* strerror(int err);  // Returns the string corresponding to @err
```

#### 15.4.4 System api hook

Calling the socket API of the co library in coroutines will not block, but the native socket API called in some third-party libraries may still block. In order to solve this problem, it's necessary to hook related APIs.

The co library currently supports hooks for linux/mac platforms. The following is a list of hook functions:

```cpp
sleep   usleep   nanosleep

accept  accept4  connect   close  shutdown
read    readv    recv   recvfrom   recvmsg
write   writev   send   sendto     sendmsg
select  poll  gethostbyaddr  gethostbyname

gethostbyaddr_r  gethostbyname2   // linux
gethostbyname_r  gethostbyname2_r // linux

epoll_wait  // linux
kevent      // mac
```

Users generally don't need to care about api hooks. If you are interested, you can read the source code implementation of [hook](https://github.com/idealvin/co/tree/master/base/co/impl/).

#### 15.4.5 tcp server/client example

- server code example

```cpp
struct Connection {
    sock_t fd;   // conn fd
    fastring ip; // peer ip
    int port;    // peer port
};

void on_new_connection(void* p) {
    std::unique_ptr<Connection> conn((Connection*)p);
    sock_t fd = conn->fd;
    co::set_tcp_keepalive(fd);
    co::set_tcp_nodelay(fd);

    fastream fs(1024);

    while (true) {
        int r = co::recv(fd, (void*)fs.data(), fs.capacity());
        if (r == 0) {          // The client closed the connection
            co::close(fd);     // Call close to close the connection normally
            break;
        } else if (r == -1) {  // Abnormal error, reset connection directly
            co::reset_tcp_socket(fd, 3000);
            break;
        } else {
            fs.resize(r);
            cout << fs.c_str() << endl;
            co::send(fd, fs.data(), r);
        }
    }
}

void server_fun() {
    sock_t fd = co::tcp_socket();
    co::set_reuseaddr(fd);

    sock_t connfd;
    int addrlen = sizeof(sockaddr_in);
    struct sockaddr_in addr;
    co::init_ip_addr(&addr, "<IP_ADDRESS>", 7788);

    co::bind(fd, &addr, sizeof(addr));
    co::listen(fd, 1024);

    while (true) {
        connfd = co::accept(fd, &addr, &addrlen);
        if (connfd == -1) continue;

        Connection* conn = new Connection;
        conn->fd = connfd;
        conn->ip = co::ip_str(&addr);
        conn->port = addr.sin_port;

        // Create a new coroutine for each client connection and process the data on the connection in the coroutine
        co::go(on_new_connection, conn);
    }
}

go(server_fun);  // Start server coroutine
```

- client code example

```cpp
void client_fun() {
    sock_t fd = co::tcp_socket();

    struct sockaddr_in addr;
    co::init_ip_addr(&addr, "<IP_ADDRESS>", 7788);

    co::connect(fd, &addr, sizeof(addr), 3000);
    co::set_tcp_nodelay(fd);

    char buf[12] = { 0 };

    for (int i = 0; i < 7; ++i) {
        co::sleep(1000);
        co::send(fd, "hello world", 11);
        co::recv(fd, buf, 12);
        cout << buf << endl;
    }

    co::close(fd);
}

go(client_fun);  // Start client coroutine
```

### 15.5 Coroutine synchronization mechanism

The co library implements a synchronization mechanism similar to threads. Developers who are familiar with multithreaded programming can easily switch from threads to coroutine programming.

#### 15.5.1 Coroutine Locks (co::Mutex)

The co library implements the coroutine lock `co::Mutex`, which is used exactly the same as `Mutex` in the thread library, except that it needs to be used in the coroutine environment. When the coroutine lock acquisition fails, the scheduling thread will suspend the current coroutine and switch to other coroutines, and the scheduling thread itself will not block.

Similar to the thread library, the co library also provides a `co::MutexGuard` class, which is used in exactly the same way as `MutexGuard` in the thread library.

- Code example

```cpp
co::Mutex mtx;
int v = 0;

void f1() {
    co::MutexGuard g(mtx);
    ++v;
}

void f2() {
    co::MutexGuard g(mtx);
    --v;
}

go(f1);
go(f2);
```

#### 15.5.2 Coroutine synchronization event (co::Event)

The co library implements the synchronous event class `co::Event`, which is similar to `SyncEvent` in the thread library, but needs to be used in the coroutine environment. When the `wait()` method is called to wait for a synchronization event, the scheduling thread automatically suspends the current coroutine and switches to other coroutine execution.

- Code example

```cpp
co::Event ev;
int v = 0;

void f1() {
    ev.wait();
    if (v == 2) v = 1;
}

void f2() {
    v = 2;
    ev.signal();
}

go(f1);
go(f2);
```

### 15.6 Pool

#### 15.6.1 The Pool class and its usage

Threads support the `TLS` mechanism, and coroutines can also support similar `CLS` mechanisms, but considering that millions of coroutines may be created in the system, CLS does not seem to be very efficient. The co library eventually abandoned CLS and implemented the `co::Pool` instead:

```cpp
class Pool {
  public:
    Pool();
    ~Pool();

    void* pop();
    void push(void* p);
    void clear(const std::function<void(void*)>& cb=0);

  private:
    void* _p;
};
```

Pool mainly provides two methods: `pop` and `push`. The former pulls an element from the Pool and the latter pushs back the element to the Pool.

The Pool class is coroutine-safe. Methods in Pool do not require locks, but must be used in coroutines. There are multiple pools in the internal implementation, and each coroutine scheduling thread owns one.

- Code example

```cpp
co::Pool p;

Redis* rds = (Redis*) p.pop();     // Pull a redis connection from the pool
if (rds == NULL) rds = new Redis;  // Create a new redis connection when the pool is empty

rds->get("xx");                    // Call redis get method
p.push(rds);                       // push back to the pool

// Clear the current thread's pool
p.clear(
    [](void* p) { delete (Redis*) p; }
);
```

#### 15.6.2 Simplifying Pool Operations with Kakalot

Manually pushing elements back to Pool may be not so convenient. To this end, the co library provides the `Kakalot` class (Kakalot), which pulls an element from the Pool when constructing, and puts it back when destructing, and it also comes with pointer properties, you can use Kakalot the way similar to `std::unique_ptr'.

- Code example

```cpp
co::Pool p;

void f() {
    co::Kakalot<Redis> rds(p);         // Kakalot is now a Redis* pointer
    if (rds == NULL) rds = new Redis;  // Reassign Kakalot
    rds->get("xx");                    // Kakalot is really strong
}

go(f);
```

With CLS mechanism, 100k coroutines needs to establish 100k connections. But using Pool, 100k coroutines may only need to share a small number of connections. Pool seems to be more efficient and reasonable than CLS, which is why this library does not support CLS.

### 15.7 Configuration items

The configuration items supported by the co library are as follows:

- co_sched_num

  Number of scheduling threads. The default is the number of system CPU cores. In the current implementation, this value must be <= the number of CPU cores.

- co_stack_size

  Coroutine stack size, default is 1MB. Each scheduling thread allocates a stack, and coroutines within the scheduling thread share this stack.

- co_max_recv_size

  The maximum data length that can be received at a time. The default is 1M. If it exceeds this size, data will be received in multiple calls of `co::recv`.

- co_max_send_size

  The maximum data length that can be sent at a time. The default is 1M. If it exceeds this size, data will be sent in multiple calls of `co::send`.

repository: yiippee/co

repo_name: yiippee/co